emviz 0.3.2 → 0.5.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
@@ -105,7 +105,7 @@ var require_path = __commonJS({
105
105
  Object.defineProperty(exports, "__esModule", { value: true });
106
106
  exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0;
107
107
  var os2 = __require("os");
108
- var path6 = __require("path");
108
+ var path8 = __require("path");
109
109
  var IS_WINDOWS_PLATFORM = os2.platform() === "win32";
110
110
  var LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2;
111
111
  var POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
@@ -117,7 +117,7 @@ var require_path = __commonJS({
117
117
  }
118
118
  exports.unixify = unixify;
119
119
  function makeAbsolute(cwd, filepath) {
120
- return path6.resolve(cwd, filepath);
120
+ return path8.resolve(cwd, filepath);
121
121
  }
122
122
  exports.makeAbsolute = makeAbsolute;
123
123
  function removeLeadingDotSegment(entry) {
@@ -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
  }
@@ -1414,7 +1414,7 @@ var require_braces = __commonJS({
1414
1414
  var require_constants2 = __commonJS({
1415
1415
  "../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/constants.js"(exports, module) {
1416
1416
  "use strict";
1417
- var path6 = __require("path");
1417
+ var path8 = __require("path");
1418
1418
  var WIN_SLASH = "\\\\/";
1419
1419
  var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
1420
1420
  var DEFAULT_MAX_EXTGLOB_RECURSION = 0;
@@ -1588,7 +1588,7 @@ var require_constants2 = __commonJS({
1588
1588
  /* | */
1589
1589
  CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
1590
1590
  /* \uFEFF */
1591
- SEP: path6.sep,
1591
+ SEP: path8.sep,
1592
1592
  /**
1593
1593
  * Create EXTGLOB_CHARS
1594
1594
  */
@@ -1615,7 +1615,7 @@ var require_constants2 = __commonJS({
1615
1615
  var require_utils2 = __commonJS({
1616
1616
  "../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/utils.js"(exports) {
1617
1617
  "use strict";
1618
- var path6 = __require("path");
1618
+ var path8 = __require("path");
1619
1619
  var win32 = process.platform === "win32";
1620
1620
  var {
1621
1621
  REGEX_BACKSLASH,
@@ -1644,7 +1644,7 @@ var require_utils2 = __commonJS({
1644
1644
  if (options && typeof options.windows === "boolean") {
1645
1645
  return options.windows;
1646
1646
  }
1647
- return win32 === true || path6.sep === "\\";
1647
+ return win32 === true || path8.sep === "\\";
1648
1648
  };
1649
1649
  exports.escapeLast = (input, char, lastIdx) => {
1650
1650
  const idx = input.lastIndexOf(char, lastIdx);
@@ -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
  };
@@ -3008,7 +3008,7 @@ var require_parse2 = __commonJS({
3008
3008
  var require_picomatch = __commonJS({
3009
3009
  "../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/picomatch.js"(exports, module) {
3010
3010
  "use strict";
3011
- var path6 = __require("path");
3011
+ var path8 = __require("path");
3012
3012
  var scan = require_scan();
3013
3013
  var parse = require_parse2();
3014
3014
  var utils = require_utils2();
@@ -3093,7 +3093,7 @@ var require_picomatch = __commonJS({
3093
3093
  };
3094
3094
  picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
3095
3095
  const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
3096
- return regex.test(path6.basename(input));
3096
+ return regex.test(path8.basename(input));
3097
3097
  };
3098
3098
  picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
3099
3099
  picomatch.parse = (pattern, options) => {
@@ -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 || [])) {
@@ -3320,7 +3320,7 @@ var require_pattern = __commonJS({
3320
3320
  "use strict";
3321
3321
  Object.defineProperty(exports, "__esModule", { value: true });
3322
3322
  exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
3323
- var path6 = __require("path");
3323
+ var path8 = __require("path");
3324
3324
  var globParent = require_glob_parent();
3325
3325
  var micromatch = require_micromatch();
3326
3326
  var GLOBSTAR = "**";
@@ -3415,8 +3415,8 @@ var require_pattern = __commonJS({
3415
3415
  }
3416
3416
  exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
3417
3417
  function isAffectDepthOfReadingPattern(pattern) {
3418
- const basename = path6.basename(pattern);
3419
- return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
3418
+ const basename2 = path8.basename(pattern);
3419
+ return endsWithSlashGlobStar(pattern) || isStaticPattern(basename2);
3420
3420
  }
3421
3421
  exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
3422
3422
  function expandPatternsWithBraceExpansion(patterns) {
@@ -3473,7 +3473,7 @@ var require_pattern = __commonJS({
3473
3473
  }
3474
3474
  exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative;
3475
3475
  function isAbsolute(pattern) {
3476
- return path6.isAbsolute(pattern);
3476
+ return path8.isAbsolute(pattern);
3477
3477
  }
3478
3478
  exports.isAbsolute = isAbsolute;
3479
3479
  }
@@ -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
  }
@@ -3648,10 +3648,10 @@ var require_utils3 = __commonJS({
3648
3648
  exports.array = array;
3649
3649
  var errno = require_errno();
3650
3650
  exports.errno = errno;
3651
- var fs6 = require_fs();
3652
- exports.fs = fs6;
3653
- var path6 = require_path();
3654
- exports.path = path6;
3651
+ var fs8 = require_fs();
3652
+ exports.fs = fs8;
3653
+ var path8 = require_path();
3654
+ exports.path = path8;
3655
3655
  var pattern = require_pattern();
3656
3656
  exports.pattern = pattern;
3657
3657
  var stream = require_stream();
@@ -3763,8 +3763,8 @@ var require_async = __commonJS({
3763
3763
  "use strict";
3764
3764
  Object.defineProperty(exports, "__esModule", { value: true });
3765
3765
  exports.read = void 0;
3766
- function read(path6, settings, callback) {
3767
- settings.fs.lstat(path6, (lstatError, lstat) => {
3766
+ function read(path8, settings, callback) {
3767
+ settings.fs.lstat(path8, (lstatError, lstat) => {
3768
3768
  if (lstatError !== null) {
3769
3769
  callFailureCallback(callback, lstatError);
3770
3770
  return;
@@ -3773,7 +3773,7 @@ var require_async = __commonJS({
3773
3773
  callSuccessCallback(callback, lstat);
3774
3774
  return;
3775
3775
  }
3776
- settings.fs.stat(path6, (statError, stat) => {
3776
+ settings.fs.stat(path8, (statError, stat) => {
3777
3777
  if (statError !== null) {
3778
3778
  if (settings.throwErrorOnBrokenSymbolicLink) {
3779
3779
  callFailureCallback(callback, statError);
@@ -3805,13 +3805,13 @@ var require_sync = __commonJS({
3805
3805
  "use strict";
3806
3806
  Object.defineProperty(exports, "__esModule", { value: true });
3807
3807
  exports.read = void 0;
3808
- function read(path6, settings) {
3809
- const lstat = settings.fs.lstatSync(path6);
3808
+ function read(path8, settings) {
3809
+ const lstat = settings.fs.lstatSync(path8);
3810
3810
  if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
3811
3811
  return lstat;
3812
3812
  }
3813
3813
  try {
3814
- const stat = settings.fs.statSync(path6);
3814
+ const stat = settings.fs.statSync(path8);
3815
3815
  if (settings.markSymbolicLink) {
3816
3816
  stat.isSymbolicLink = () => true;
3817
3817
  }
@@ -3833,12 +3833,12 @@ var require_fs2 = __commonJS({
3833
3833
  "use strict";
3834
3834
  Object.defineProperty(exports, "__esModule", { value: true });
3835
3835
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
3836
- var fs6 = __require("fs");
3836
+ var fs8 = __require("fs");
3837
3837
  exports.FILE_SYSTEM_ADAPTER = {
3838
- lstat: fs6.lstat,
3839
- stat: fs6.stat,
3840
- lstatSync: fs6.lstatSync,
3841
- statSync: fs6.statSync
3838
+ lstat: fs8.lstat,
3839
+ stat: fs8.stat,
3840
+ lstatSync: fs8.lstatSync,
3841
+ statSync: fs8.statSync
3842
3842
  };
3843
3843
  function createFileSystemAdapter(fsMethods) {
3844
3844
  if (fsMethods === void 0) {
@@ -3855,12 +3855,12 @@ var require_settings = __commonJS({
3855
3855
  "../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/settings.js"(exports) {
3856
3856
  "use strict";
3857
3857
  Object.defineProperty(exports, "__esModule", { value: true });
3858
- var fs6 = require_fs2();
3858
+ var fs8 = require_fs2();
3859
3859
  var Settings = class {
3860
3860
  constructor(_options = {}) {
3861
3861
  this._options = _options;
3862
3862
  this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
3863
- this.fs = fs6.createFileSystemAdapter(this._options.fs);
3863
+ this.fs = fs8.createFileSystemAdapter(this._options.fs);
3864
3864
  this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
3865
3865
  this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
3866
3866
  }
@@ -3882,17 +3882,17 @@ var require_out = __commonJS({
3882
3882
  var sync = require_sync();
3883
3883
  var settings_1 = require_settings();
3884
3884
  exports.Settings = settings_1.default;
3885
- function stat(path6, optionsOrSettingsOrCallback, callback) {
3885
+ function stat(path8, optionsOrSettingsOrCallback, callback) {
3886
3886
  if (typeof optionsOrSettingsOrCallback === "function") {
3887
- async.read(path6, getSettings(), optionsOrSettingsOrCallback);
3887
+ async.read(path8, getSettings(), optionsOrSettingsOrCallback);
3888
3888
  return;
3889
3889
  }
3890
- async.read(path6, getSettings(optionsOrSettingsOrCallback), callback);
3890
+ async.read(path8, getSettings(optionsOrSettingsOrCallback), callback);
3891
3891
  }
3892
3892
  exports.stat = stat;
3893
- function statSync(path6, optionsOrSettings) {
3893
+ function statSync(path8, optionsOrSettings) {
3894
3894
  const settings = getSettings(optionsOrSettings);
3895
- return sync.read(path6, settings);
3895
+ return sync.read(path8, settings);
3896
3896
  }
3897
3897
  exports.statSync = statSync;
3898
3898
  function getSettings(settingsOrOptions = {}) {
@@ -4015,8 +4015,8 @@ var require_utils4 = __commonJS({
4015
4015
  "use strict";
4016
4016
  Object.defineProperty(exports, "__esModule", { value: true });
4017
4017
  exports.fs = void 0;
4018
- var fs6 = require_fs3();
4019
- exports.fs = fs6;
4018
+ var fs8 = require_fs3();
4019
+ exports.fs = fs8;
4020
4020
  }
4021
4021
  });
4022
4022
 
@@ -4108,16 +4108,16 @@ var require_async2 = __commonJS({
4108
4108
  return;
4109
4109
  }
4110
4110
  const tasks = names.map((name) => {
4111
- const path6 = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
4111
+ const path8 = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
4112
4112
  return (done) => {
4113
- fsStat.stat(path6, settings.fsStatSettings, (error, stats) => {
4113
+ fsStat.stat(path8, settings.fsStatSettings, (error, stats) => {
4114
4114
  if (error !== null) {
4115
4115
  done(error);
4116
4116
  return;
4117
4117
  }
4118
4118
  const entry = {
4119
4119
  name,
4120
- path: path6,
4120
+ path: path8,
4121
4121
  dirent: utils.fs.createDirentFromStats(name, stats)
4122
4122
  };
4123
4123
  if (settings.stats) {
@@ -4211,14 +4211,14 @@ var require_fs4 = __commonJS({
4211
4211
  "use strict";
4212
4212
  Object.defineProperty(exports, "__esModule", { value: true });
4213
4213
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
4214
- var fs6 = __require("fs");
4214
+ var fs8 = __require("fs");
4215
4215
  exports.FILE_SYSTEM_ADAPTER = {
4216
- lstat: fs6.lstat,
4217
- stat: fs6.stat,
4218
- lstatSync: fs6.lstatSync,
4219
- statSync: fs6.statSync,
4220
- readdir: fs6.readdir,
4221
- readdirSync: fs6.readdirSync
4216
+ lstat: fs8.lstat,
4217
+ stat: fs8.stat,
4218
+ lstatSync: fs8.lstatSync,
4219
+ statSync: fs8.statSync,
4220
+ readdir: fs8.readdir,
4221
+ readdirSync: fs8.readdirSync
4222
4222
  };
4223
4223
  function createFileSystemAdapter(fsMethods) {
4224
4224
  if (fsMethods === void 0) {
@@ -4235,15 +4235,15 @@ var require_settings2 = __commonJS({
4235
4235
  "../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/settings.js"(exports) {
4236
4236
  "use strict";
4237
4237
  Object.defineProperty(exports, "__esModule", { value: true });
4238
- var path6 = __require("path");
4238
+ var path8 = __require("path");
4239
4239
  var fsStat = require_out();
4240
- var fs6 = require_fs4();
4240
+ var fs8 = require_fs4();
4241
4241
  var Settings = class {
4242
4242
  constructor(_options = {}) {
4243
4243
  this._options = _options;
4244
4244
  this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
4245
- this.fs = fs6.createFileSystemAdapter(this._options.fs);
4246
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path6.sep);
4245
+ this.fs = fs8.createFileSystemAdapter(this._options.fs);
4246
+ this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path8.sep);
4247
4247
  this.stats = this._getValue(this._options.stats, false);
4248
4248
  this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
4249
4249
  this.fsStatSettings = new fsStat.Settings({
@@ -4270,17 +4270,17 @@ var require_out2 = __commonJS({
4270
4270
  var sync = require_sync2();
4271
4271
  var settings_1 = require_settings2();
4272
4272
  exports.Settings = settings_1.default;
4273
- function scandir(path6, optionsOrSettingsOrCallback, callback) {
4273
+ function scandir(path8, optionsOrSettingsOrCallback, callback) {
4274
4274
  if (typeof optionsOrSettingsOrCallback === "function") {
4275
- async.read(path6, getSettings(), optionsOrSettingsOrCallback);
4275
+ async.read(path8, getSettings(), optionsOrSettingsOrCallback);
4276
4276
  return;
4277
4277
  }
4278
- async.read(path6, getSettings(optionsOrSettingsOrCallback), callback);
4278
+ async.read(path8, getSettings(optionsOrSettingsOrCallback), callback);
4279
4279
  }
4280
4280
  exports.scandir = scandir;
4281
- function scandirSync(path6, optionsOrSettings) {
4281
+ function scandirSync(path8, optionsOrSettings) {
4282
4282
  const settings = getSettings(optionsOrSettings);
4283
- return sync.read(path6, settings);
4283
+ return sync.read(path8, settings);
4284
4284
  }
4285
4285
  exports.scandirSync = scandirSync;
4286
4286
  function getSettings(settingsOrOptions = {}) {
@@ -4927,7 +4927,7 @@ var require_settings3 = __commonJS({
4927
4927
  "../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/settings.js"(exports) {
4928
4928
  "use strict";
4929
4929
  Object.defineProperty(exports, "__esModule", { value: true });
4930
- var path6 = __require("path");
4930
+ var path8 = __require("path");
4931
4931
  var fsScandir = require_out2();
4932
4932
  var Settings = class {
4933
4933
  constructor(_options = {}) {
@@ -4937,7 +4937,7 @@ var require_settings3 = __commonJS({
4937
4937
  this.deepFilter = this._getValue(this._options.deepFilter, null);
4938
4938
  this.entryFilter = this._getValue(this._options.entryFilter, null);
4939
4939
  this.errorFilter = this._getValue(this._options.errorFilter, null);
4940
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path6.sep);
4940
+ this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path8.sep);
4941
4941
  this.fsScandirSettings = new fsScandir.Settings({
4942
4942
  followSymbolicLinks: this._options.followSymbolicLinks,
4943
4943
  fs: this._options.fs,
@@ -4999,7 +4999,7 @@ var require_reader2 = __commonJS({
4999
4999
  "../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/reader.js"(exports) {
5000
5000
  "use strict";
5001
5001
  Object.defineProperty(exports, "__esModule", { value: true });
5002
- var path6 = __require("path");
5002
+ var path8 = __require("path");
5003
5003
  var fsStat = require_out();
5004
5004
  var utils = require_utils3();
5005
5005
  var Reader = class {
@@ -5012,7 +5012,7 @@ var require_reader2 = __commonJS({
5012
5012
  });
5013
5013
  }
5014
5014
  _getFullEntryPath(filepath) {
5015
- return path6.resolve(this._settings.cwd, filepath);
5015
+ return path8.resolve(this._settings.cwd, filepath);
5016
5016
  }
5017
5017
  _makeEntry(stats, pattern) {
5018
5018
  const entry = {
@@ -5428,7 +5428,7 @@ var require_provider = __commonJS({
5428
5428
  "../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/provider.js"(exports) {
5429
5429
  "use strict";
5430
5430
  Object.defineProperty(exports, "__esModule", { value: true });
5431
- var path6 = __require("path");
5431
+ var path8 = __require("path");
5432
5432
  var deep_1 = require_deep();
5433
5433
  var entry_1 = require_entry();
5434
5434
  var error_1 = require_error();
@@ -5442,7 +5442,7 @@ var require_provider = __commonJS({
5442
5442
  this.entryTransformer = new entry_2.default(this._settings);
5443
5443
  }
5444
5444
  _getRootDirectory(task) {
5445
- return path6.resolve(this._settings.cwd, task.base);
5445
+ return path8.resolve(this._settings.cwd, task.base);
5446
5446
  }
5447
5447
  _getReaderOptions(task) {
5448
5448
  const basePath = task.base === "." ? "" : task.base;
@@ -5623,16 +5623,16 @@ var require_settings4 = __commonJS({
5623
5623
  "use strict";
5624
5624
  Object.defineProperty(exports, "__esModule", { value: true });
5625
5625
  exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
5626
- var fs6 = __require("fs");
5626
+ var fs8 = __require("fs");
5627
5627
  var os2 = __require("os");
5628
5628
  var CPU_COUNT = Math.max(os2.cpus().length, 1);
5629
5629
  exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
5630
- lstat: fs6.lstat,
5631
- lstatSync: fs6.lstatSync,
5632
- stat: fs6.stat,
5633
- statSync: fs6.statSync,
5634
- readdir: fs6.readdir,
5635
- readdirSync: fs6.readdirSync
5630
+ lstat: fs8.lstat,
5631
+ lstatSync: fs8.lstatSync,
5632
+ stat: fs8.stat,
5633
+ statSync: fs8.statSync,
5634
+ readdir: fs8.readdir,
5635
+ readdirSync: fs8.readdirSync
5636
5636
  };
5637
5637
  var Settings = class {
5638
5638
  constructor(_options = {}) {
@@ -5855,17 +5855,17 @@ var require_visit = __commonJS({
5855
5855
  visit.BREAK = BREAK;
5856
5856
  visit.SKIP = SKIP;
5857
5857
  visit.REMOVE = REMOVE;
5858
- function visit_(key, node, visitor, path6) {
5859
- const ctrl = callVisitor(key, node, visitor, path6);
5858
+ function visit_(key, node, visitor, path8) {
5859
+ const ctrl = callVisitor(key, node, visitor, path8);
5860
5860
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
5861
- replaceNode(key, path6, ctrl);
5862
- return visit_(key, ctrl, visitor, path6);
5861
+ replaceNode(key, path8, ctrl);
5862
+ return visit_(key, ctrl, visitor, path8);
5863
5863
  }
5864
5864
  if (typeof ctrl !== "symbol") {
5865
5865
  if (identity.isCollection(node)) {
5866
- path6 = Object.freeze(path6.concat(node));
5866
+ path8 = Object.freeze(path8.concat(node));
5867
5867
  for (let i = 0; i < node.items.length; ++i) {
5868
- const ci = visit_(i, node.items[i], visitor, path6);
5868
+ const ci = visit_(i, node.items[i], visitor, path8);
5869
5869
  if (typeof ci === "number")
5870
5870
  i = ci - 1;
5871
5871
  else if (ci === BREAK)
@@ -5876,13 +5876,13 @@ var require_visit = __commonJS({
5876
5876
  }
5877
5877
  }
5878
5878
  } else if (identity.isPair(node)) {
5879
- path6 = Object.freeze(path6.concat(node));
5880
- const ck = visit_("key", node.key, visitor, path6);
5879
+ path8 = Object.freeze(path8.concat(node));
5880
+ const ck = visit_("key", node.key, visitor, path8);
5881
5881
  if (ck === BREAK)
5882
5882
  return BREAK;
5883
5883
  else if (ck === REMOVE)
5884
5884
  node.key = null;
5885
- const cv = visit_("value", node.value, visitor, path6);
5885
+ const cv = visit_("value", node.value, visitor, path8);
5886
5886
  if (cv === BREAK)
5887
5887
  return BREAK;
5888
5888
  else if (cv === REMOVE)
@@ -5903,17 +5903,17 @@ var require_visit = __commonJS({
5903
5903
  visitAsync.BREAK = BREAK;
5904
5904
  visitAsync.SKIP = SKIP;
5905
5905
  visitAsync.REMOVE = REMOVE;
5906
- async function visitAsync_(key, node, visitor, path6) {
5907
- const ctrl = await callVisitor(key, node, visitor, path6);
5906
+ async function visitAsync_(key, node, visitor, path8) {
5907
+ const ctrl = await callVisitor(key, node, visitor, path8);
5908
5908
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
5909
- replaceNode(key, path6, ctrl);
5910
- return visitAsync_(key, ctrl, visitor, path6);
5909
+ replaceNode(key, path8, ctrl);
5910
+ return visitAsync_(key, ctrl, visitor, path8);
5911
5911
  }
5912
5912
  if (typeof ctrl !== "symbol") {
5913
5913
  if (identity.isCollection(node)) {
5914
- path6 = Object.freeze(path6.concat(node));
5914
+ path8 = Object.freeze(path8.concat(node));
5915
5915
  for (let i = 0; i < node.items.length; ++i) {
5916
- const ci = await visitAsync_(i, node.items[i], visitor, path6);
5916
+ const ci = await visitAsync_(i, node.items[i], visitor, path8);
5917
5917
  if (typeof ci === "number")
5918
5918
  i = ci - 1;
5919
5919
  else if (ci === BREAK)
@@ -5924,13 +5924,13 @@ var require_visit = __commonJS({
5924
5924
  }
5925
5925
  }
5926
5926
  } else if (identity.isPair(node)) {
5927
- path6 = Object.freeze(path6.concat(node));
5928
- const ck = await visitAsync_("key", node.key, visitor, path6);
5927
+ path8 = Object.freeze(path8.concat(node));
5928
+ const ck = await visitAsync_("key", node.key, visitor, path8);
5929
5929
  if (ck === BREAK)
5930
5930
  return BREAK;
5931
5931
  else if (ck === REMOVE)
5932
5932
  node.key = null;
5933
- const cv = await visitAsync_("value", node.value, visitor, path6);
5933
+ const cv = await visitAsync_("value", node.value, visitor, path8);
5934
5934
  if (cv === BREAK)
5935
5935
  return BREAK;
5936
5936
  else if (cv === REMOVE)
@@ -5957,23 +5957,23 @@ var require_visit = __commonJS({
5957
5957
  }
5958
5958
  return visitor;
5959
5959
  }
5960
- function callVisitor(key, node, visitor, path6) {
5960
+ function callVisitor(key, node, visitor, path8) {
5961
5961
  if (typeof visitor === "function")
5962
- return visitor(key, node, path6);
5962
+ return visitor(key, node, path8);
5963
5963
  if (identity.isMap(node))
5964
- return visitor.Map?.(key, node, path6);
5964
+ return visitor.Map?.(key, node, path8);
5965
5965
  if (identity.isSeq(node))
5966
- return visitor.Seq?.(key, node, path6);
5966
+ return visitor.Seq?.(key, node, path8);
5967
5967
  if (identity.isPair(node))
5968
- return visitor.Pair?.(key, node, path6);
5968
+ return visitor.Pair?.(key, node, path8);
5969
5969
  if (identity.isScalar(node))
5970
- return visitor.Scalar?.(key, node, path6);
5970
+ return visitor.Scalar?.(key, node, path8);
5971
5971
  if (identity.isAlias(node))
5972
- return visitor.Alias?.(key, node, path6);
5972
+ return visitor.Alias?.(key, node, path8);
5973
5973
  return void 0;
5974
5974
  }
5975
- function replaceNode(key, path6, node) {
5976
- const parent = path6[path6.length - 1];
5975
+ function replaceNode(key, path8, node) {
5976
+ const parent = path8[path8.length - 1];
5977
5977
  if (identity.isCollection(parent)) {
5978
5978
  parent.items[key] = node;
5979
5979
  } else if (identity.isPair(parent)) {
@@ -6583,10 +6583,10 @@ var require_Collection = __commonJS({
6583
6583
  var createNode = require_createNode();
6584
6584
  var identity = require_identity();
6585
6585
  var Node = require_Node();
6586
- function collectionFromPath(schema, path6, value) {
6586
+ function collectionFromPath(schema, path8, value) {
6587
6587
  let v = value;
6588
- for (let i = path6.length - 1; i >= 0; --i) {
6589
- const k = path6[i];
6588
+ for (let i = path8.length - 1; i >= 0; --i) {
6589
+ const k = path8[i];
6590
6590
  if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
6591
6591
  const a = [];
6592
6592
  a[k] = v;
@@ -6605,7 +6605,7 @@ var require_Collection = __commonJS({
6605
6605
  sourceObjects: /* @__PURE__ */ new Map()
6606
6606
  });
6607
6607
  }
6608
- var isEmptyPath = (path6) => path6 == null || typeof path6 === "object" && !!path6[Symbol.iterator]().next().done;
6608
+ var isEmptyPath = (path8) => path8 == null || typeof path8 === "object" && !!path8[Symbol.iterator]().next().done;
6609
6609
  var Collection = class extends Node.NodeBase {
6610
6610
  constructor(type, schema) {
6611
6611
  super(type);
@@ -6635,11 +6635,11 @@ var require_Collection = __commonJS({
6635
6635
  * be a Pair instance or a `{ key, value }` object, which may not have a key
6636
6636
  * that already exists in the map.
6637
6637
  */
6638
- addIn(path6, value) {
6639
- if (isEmptyPath(path6))
6638
+ addIn(path8, value) {
6639
+ if (isEmptyPath(path8))
6640
6640
  this.add(value);
6641
6641
  else {
6642
- const [key, ...rest] = path6;
6642
+ const [key, ...rest] = path8;
6643
6643
  const node = this.get(key, true);
6644
6644
  if (identity.isCollection(node))
6645
6645
  node.addIn(rest, value);
@@ -6653,8 +6653,8 @@ var require_Collection = __commonJS({
6653
6653
  * Removes a value from the collection.
6654
6654
  * @returns `true` if the item was found and removed.
6655
6655
  */
6656
- deleteIn(path6) {
6657
- const [key, ...rest] = path6;
6656
+ deleteIn(path8) {
6657
+ const [key, ...rest] = path8;
6658
6658
  if (rest.length === 0)
6659
6659
  return this.delete(key);
6660
6660
  const node = this.get(key, true);
@@ -6668,8 +6668,8 @@ var require_Collection = __commonJS({
6668
6668
  * scalar values from their surrounding node; to disable set `keepScalar` to
6669
6669
  * `true` (collections are always returned intact).
6670
6670
  */
6671
- getIn(path6, keepScalar) {
6672
- const [key, ...rest] = path6;
6671
+ getIn(path8, keepScalar) {
6672
+ const [key, ...rest] = path8;
6673
6673
  const node = this.get(key, true);
6674
6674
  if (rest.length === 0)
6675
6675
  return !keepScalar && identity.isScalar(node) ? node.value : node;
@@ -6687,8 +6687,8 @@ var require_Collection = __commonJS({
6687
6687
  /**
6688
6688
  * Checks if the collection includes a value with the key `key`.
6689
6689
  */
6690
- hasIn(path6) {
6691
- const [key, ...rest] = path6;
6690
+ hasIn(path8) {
6691
+ const [key, ...rest] = path8;
6692
6692
  if (rest.length === 0)
6693
6693
  return this.has(key);
6694
6694
  const node = this.get(key, true);
@@ -6698,8 +6698,8 @@ var require_Collection = __commonJS({
6698
6698
  * Sets a value in this collection. For `!!set`, `value` needs to be a
6699
6699
  * boolean to add/remove the item from the set.
6700
6700
  */
6701
- setIn(path6, value) {
6702
- const [key, ...rest] = path6;
6701
+ setIn(path8, value) {
6702
+ const [key, ...rest] = path8;
6703
6703
  if (rest.length === 0) {
6704
6704
  this.set(key, value);
6705
6705
  } else {
@@ -9214,9 +9214,9 @@ var require_Document = __commonJS({
9214
9214
  this.contents.add(value);
9215
9215
  }
9216
9216
  /** Adds a value to the document. */
9217
- addIn(path6, value) {
9217
+ addIn(path8, value) {
9218
9218
  if (assertCollection(this.contents))
9219
- this.contents.addIn(path6, value);
9219
+ this.contents.addIn(path8, value);
9220
9220
  }
9221
9221
  /**
9222
9222
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -9291,14 +9291,14 @@ var require_Document = __commonJS({
9291
9291
  * Removes a value from the document.
9292
9292
  * @returns `true` if the item was found and removed.
9293
9293
  */
9294
- deleteIn(path6) {
9295
- if (Collection.isEmptyPath(path6)) {
9294
+ deleteIn(path8) {
9295
+ if (Collection.isEmptyPath(path8)) {
9296
9296
  if (this.contents == null)
9297
9297
  return false;
9298
9298
  this.contents = null;
9299
9299
  return true;
9300
9300
  }
9301
- return assertCollection(this.contents) ? this.contents.deleteIn(path6) : false;
9301
+ return assertCollection(this.contents) ? this.contents.deleteIn(path8) : false;
9302
9302
  }
9303
9303
  /**
9304
9304
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -9313,10 +9313,10 @@ var require_Document = __commonJS({
9313
9313
  * scalar values from their surrounding node; to disable set `keepScalar` to
9314
9314
  * `true` (collections are always returned intact).
9315
9315
  */
9316
- getIn(path6, keepScalar) {
9317
- if (Collection.isEmptyPath(path6))
9316
+ getIn(path8, keepScalar) {
9317
+ if (Collection.isEmptyPath(path8))
9318
9318
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
9319
- return identity.isCollection(this.contents) ? this.contents.getIn(path6, keepScalar) : void 0;
9319
+ return identity.isCollection(this.contents) ? this.contents.getIn(path8, keepScalar) : void 0;
9320
9320
  }
9321
9321
  /**
9322
9322
  * Checks if the document includes a value with the key `key`.
@@ -9327,10 +9327,10 @@ var require_Document = __commonJS({
9327
9327
  /**
9328
9328
  * Checks if the document includes a value at `path`.
9329
9329
  */
9330
- hasIn(path6) {
9331
- if (Collection.isEmptyPath(path6))
9330
+ hasIn(path8) {
9331
+ if (Collection.isEmptyPath(path8))
9332
9332
  return this.contents !== void 0;
9333
- return identity.isCollection(this.contents) ? this.contents.hasIn(path6) : false;
9333
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path8) : false;
9334
9334
  }
9335
9335
  /**
9336
9336
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -9347,13 +9347,13 @@ var require_Document = __commonJS({
9347
9347
  * Sets a value in this document. For `!!set`, `value` needs to be a
9348
9348
  * boolean to add/remove the item from the set.
9349
9349
  */
9350
- setIn(path6, value) {
9351
- if (Collection.isEmptyPath(path6)) {
9350
+ setIn(path8, value) {
9351
+ if (Collection.isEmptyPath(path8)) {
9352
9352
  this.contents = value;
9353
9353
  } else if (this.contents == null) {
9354
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path6), value);
9354
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path8), value);
9355
9355
  } else if (assertCollection(this.contents)) {
9356
- this.contents.setIn(path6, value);
9356
+ this.contents.setIn(path8, value);
9357
9357
  }
9358
9358
  }
9359
9359
  /**
@@ -11313,9 +11313,9 @@ var require_cst_visit = __commonJS({
11313
11313
  visit.BREAK = BREAK;
11314
11314
  visit.SKIP = SKIP;
11315
11315
  visit.REMOVE = REMOVE;
11316
- visit.itemAtPath = (cst, path6) => {
11316
+ visit.itemAtPath = (cst, path8) => {
11317
11317
  let item = cst;
11318
- for (const [field, index] of path6) {
11318
+ for (const [field, index] of path8) {
11319
11319
  const tok = item?.[field];
11320
11320
  if (tok && "items" in tok) {
11321
11321
  item = tok.items[index];
@@ -11324,23 +11324,23 @@ var require_cst_visit = __commonJS({
11324
11324
  }
11325
11325
  return item;
11326
11326
  };
11327
- visit.parentCollection = (cst, path6) => {
11328
- const parent = visit.itemAtPath(cst, path6.slice(0, -1));
11329
- const field = path6[path6.length - 1][0];
11327
+ visit.parentCollection = (cst, path8) => {
11328
+ const parent = visit.itemAtPath(cst, path8.slice(0, -1));
11329
+ const field = path8[path8.length - 1][0];
11330
11330
  const coll = parent?.[field];
11331
11331
  if (coll && "items" in coll)
11332
11332
  return coll;
11333
11333
  throw new Error("Parent collection not found");
11334
11334
  };
11335
- function _visit(path6, item, visitor) {
11336
- let ctrl = visitor(item, path6);
11335
+ function _visit(path8, item, visitor) {
11336
+ let ctrl = visitor(item, path8);
11337
11337
  if (typeof ctrl === "symbol")
11338
11338
  return ctrl;
11339
11339
  for (const field of ["key", "value"]) {
11340
11340
  const token = item[field];
11341
11341
  if (token && "items" in token) {
11342
11342
  for (let i = 0; i < token.items.length; ++i) {
11343
- const ci = _visit(Object.freeze(path6.concat([[field, i]])), token.items[i], visitor);
11343
+ const ci = _visit(Object.freeze(path8.concat([[field, i]])), token.items[i], visitor);
11344
11344
  if (typeof ci === "number")
11345
11345
  i = ci - 1;
11346
11346
  else if (ci === BREAK)
@@ -11351,10 +11351,10 @@ var require_cst_visit = __commonJS({
11351
11351
  }
11352
11352
  }
11353
11353
  if (typeof ctrl === "function" && field === "key")
11354
- ctrl = ctrl(item, path6);
11354
+ ctrl = ctrl(item, path8);
11355
11355
  }
11356
11356
  }
11357
- return typeof ctrl === "function" ? ctrl(item, path6) : ctrl;
11357
+ return typeof ctrl === "function" ? ctrl(item, path8) : ctrl;
11358
11358
  }
11359
11359
  exports.visit = visit;
11360
11360
  }
@@ -12656,14 +12656,14 @@ var require_parser = __commonJS({
12656
12656
  case "scalar":
12657
12657
  case "single-quoted-scalar":
12658
12658
  case "double-quoted-scalar": {
12659
- const fs6 = this.flowScalar(this.type);
12659
+ const fs8 = this.flowScalar(this.type);
12660
12660
  if (atNextItem || it.value) {
12661
- map.items.push({ start, key: fs6, sep: [] });
12661
+ map.items.push({ start, key: fs8, sep: [] });
12662
12662
  this.onKeyLine = true;
12663
12663
  } else if (it.sep) {
12664
- this.stack.push(fs6);
12664
+ this.stack.push(fs8);
12665
12665
  } else {
12666
- Object.assign(it, { key: fs6, sep: [] });
12666
+ Object.assign(it, { key: fs8, sep: [] });
12667
12667
  this.onKeyLine = true;
12668
12668
  }
12669
12669
  return;
@@ -12791,13 +12791,13 @@ var require_parser = __commonJS({
12791
12791
  case "scalar":
12792
12792
  case "single-quoted-scalar":
12793
12793
  case "double-quoted-scalar": {
12794
- const fs6 = this.flowScalar(this.type);
12794
+ const fs8 = this.flowScalar(this.type);
12795
12795
  if (!it || it.value)
12796
- fc.items.push({ start: [], key: fs6, sep: [] });
12796
+ fc.items.push({ start: [], key: fs8, sep: [] });
12797
12797
  else if (it.sep)
12798
- this.stack.push(fs6);
12798
+ this.stack.push(fs8);
12799
12799
  else
12800
- Object.assign(it, { key: fs6, sep: [] });
12800
+ Object.assign(it, { key: fs8, sep: [] });
12801
12801
  return;
12802
12802
  }
12803
12803
  case "flow-map-end":
@@ -13106,19 +13106,104 @@ var require_dist = __commonJS({
13106
13106
  });
13107
13107
 
13108
13108
  // src/index.ts
13109
- import fs5 from "node:fs";
13109
+ import fs7 from "node:fs";
13110
13110
  import http from "node:http";
13111
- import os from "node:os";
13112
- import path5 from "node:path";
13113
- import { execFileSync } from "node:child_process";
13111
+ import { randomUUID as randomUUID2 } from "node:crypto";
13112
+ import path7 from "node:path";
13113
+ import { execFileSync as execFileSync3 } from "node:child_process";
13114
13114
  import { fileURLToPath } from "node:url";
13115
13115
 
13116
13116
  // ../parser/dist/index.js
13117
13117
  var import_fast_glob = __toESM(require_out4(), 1);
13118
- var import_yaml3 = __toESM(require_dist(), 1);
13118
+ var import_yaml4 = __toESM(require_dist(), 1);
13119
13119
  import fs2 from "node:fs";
13120
13120
  import path2 from "node:path";
13121
13121
 
13122
+ // ../parser/dist/actors.js
13123
+ var import_yaml = __toESM(require_dist(), 1);
13124
+ var palette = ["#2563EB", "#7C3AED", "#0F766E", "#B45309", "#BE185D", "#4338CA", "#047857", "#9F1239"];
13125
+ function actorColor(id) {
13126
+ let hash = 0;
13127
+ for (const character of id)
13128
+ hash = Math.imul(hash, 31) + character.codePointAt(0) >>> 0;
13129
+ return palette[hash % palette.length];
13130
+ }
13131
+ function parseActorReferences(value) {
13132
+ if (value === void 0)
13133
+ return { actors: [] };
13134
+ if (!Array.isArray(value))
13135
+ return { actors: [], actorIssues: ["screen.actors must be an array of actor IDs."] };
13136
+ const actors = [];
13137
+ const actorIssues = [];
13138
+ for (const id of value) {
13139
+ if (typeof id !== "string" || !id.trim() || id !== id.trim()) {
13140
+ actorIssues.push("screen.actors IDs must be nonempty strings without surrounding whitespace.");
13141
+ } else if (actors.includes(id)) {
13142
+ actorIssues.push(`screen.actors lists "${id}" more than once.`);
13143
+ } else {
13144
+ actors.push(id);
13145
+ }
13146
+ }
13147
+ return { actors, ...actorIssues.length ? { actorIssues } : {} };
13148
+ }
13149
+ function loadActors(content, sourcePath, slices) {
13150
+ const definitions = /* @__PURE__ */ new Map();
13151
+ const actorIssues = [];
13152
+ const issue = (message, path8 = sourcePath) => actorIssues.push({ message, path: path8 });
13153
+ if (content !== void 0) {
13154
+ let raw;
13155
+ try {
13156
+ raw = import_yaml.default.parse(content);
13157
+ } catch (error) {
13158
+ issue(`Invalid actor registry: ${error instanceof Error ? error.message : String(error)}`);
13159
+ }
13160
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || !("actors" in raw) || !raw.actors || typeof raw.actors !== "object" || Array.isArray(raw.actors)) {
13161
+ issue("Actor registry must contain an actors mapping.");
13162
+ } else {
13163
+ for (const [id, value] of Object.entries(raw.actors)) {
13164
+ if (!id.trim() || id !== id.trim()) {
13165
+ issue("Actor IDs must be nonempty strings without surrounding whitespace.");
13166
+ continue;
13167
+ }
13168
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
13169
+ issue(`Actor "${id}" must be a mapping with optional name and color.`);
13170
+ continue;
13171
+ }
13172
+ const entry = value;
13173
+ let name = id;
13174
+ let color = actorColor(id);
13175
+ if (entry.name !== void 0) {
13176
+ if (typeof entry.name !== "string" || !entry.name.trim())
13177
+ issue(`Actor "${id}" name must be a nonempty string.`);
13178
+ else
13179
+ name = entry.name.trim();
13180
+ }
13181
+ if (entry.color !== void 0) {
13182
+ if (typeof entry.color !== "string" || !/^#[0-9a-f]{6}$/i.test(entry.color))
13183
+ issue(`Actor "${id}" color must be a quoted #RRGGBB value.`);
13184
+ else
13185
+ color = entry.color.toUpperCase();
13186
+ }
13187
+ definitions.set(id, { id, name, color });
13188
+ }
13189
+ }
13190
+ }
13191
+ const registered = new Set(definitions.keys());
13192
+ for (const slice of slices) {
13193
+ for (const message of slice.screen.actorIssues ?? [])
13194
+ issue(message, slice.path);
13195
+ if (slice.screen.type !== "user")
13196
+ continue;
13197
+ for (const id of slice.screen.actors) {
13198
+ if (content !== void 0 && !registered.has(id))
13199
+ issue(`screen.actors references undefined actor "${id}".`, slice.path);
13200
+ if (!definitions.has(id))
13201
+ definitions.set(id, { id, name: id, color: actorColor(id) });
13202
+ }
13203
+ }
13204
+ return { actors: [...definitions.values()], actorIssues };
13205
+ }
13206
+
13122
13207
  // ../parser/dist/id.js
13123
13208
  function slugify(value) {
13124
13209
  const normalized = value.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").toLowerCase();
@@ -13165,9 +13250,9 @@ function graphIds(project) {
13165
13250
  for (const slice of project.slices) {
13166
13251
  register(sliceId(slice.path), [slice.path]);
13167
13252
  register(screenId(slice.path), [slice.path]);
13168
- slice.commands.forEach((command2, index) => {
13169
- register(commandId(command2.name), localIdentity(slice.path, slice.commands, index));
13170
- for (const name of command2.produces)
13253
+ slice.commands.forEach((command, index) => {
13254
+ register(commandId(command.name), localIdentity(slice.path, slice.commands, index));
13255
+ for (const name of command.produces)
13171
13256
  register(eventId(name), [name]);
13172
13257
  });
13173
13258
  slice.queries.forEach((query, index) => {
@@ -13220,6 +13305,9 @@ function buildGraph(project) {
13220
13305
  type: slice.screen.type === "system" ? "processor" : "screen",
13221
13306
  label: slice.screen.name ?? (slice.screen.type === "system" ? "Processor" : "Screen"),
13222
13307
  actors: slice.screen.actors,
13308
+ ...slice.screen.type === "user" ? {
13309
+ actorDefinitions: slice.screen.actors.map((id2) => project.actors?.find((actor) => actor.id === id2)).filter((actor) => Boolean(actor))
13310
+ } : {},
13223
13311
  screenType: slice.screen.type
13224
13312
  });
13225
13313
  connect("slice-screen", currentSliceId, currentScreenId);
@@ -13231,12 +13319,12 @@ function buildGraph(project) {
13231
13319
  for (const name of query.fromEvents)
13232
13320
  connect("event-query", eventNodeId(name), currentId, name);
13233
13321
  });
13234
- slice.commands.forEach((command2, index) => {
13235
- const currentId = id(commandId(command2.name), localIdentity(slice.path, slice.commands, index));
13236
- nodes.push({ ...shared, id: currentId, type: "command", label: command2.name, sourceName: command2.name, fields: command2.fields });
13237
- if (slice.screen.executes.includes(command2.name))
13322
+ slice.commands.forEach((command, index) => {
13323
+ const currentId = id(commandId(command.name), localIdentity(slice.path, slice.commands, index));
13324
+ nodes.push({ ...shared, id: currentId, type: "command", label: command.name, sourceName: command.name, fields: command.fields });
13325
+ if (slice.screen.executes.includes(command.name))
13238
13326
  connect("screen-command", currentScreenId, currentId);
13239
- for (const name of command2.produces)
13327
+ for (const name of command.produces)
13240
13328
  connect("command-event", currentId, eventNodeId(name), name);
13241
13329
  });
13242
13330
  slice.gwt.forEach((scenario, index) => {
@@ -13257,7 +13345,7 @@ function buildGraph(project) {
13257
13345
  }
13258
13346
 
13259
13347
  // ../parser/dist/config.js
13260
- var import_yaml = __toESM(require_dist(), 1);
13348
+ var import_yaml2 = __toESM(require_dist(), 1);
13261
13349
  import fs from "node:fs";
13262
13350
  import path from "node:path";
13263
13351
  function findProjectRoot(startDir) {
@@ -13278,7 +13366,10 @@ function readConfig(projectRoot) {
13278
13366
  if (!fs.existsSync(configPath)) {
13279
13367
  throw new Error(`Missing .event-modeling/config.yaml at ${projectRoot}`);
13280
13368
  }
13281
- const raw = import_yaml.default.parse(fs.readFileSync(configPath, "utf8"));
13369
+ return parseConfig(fs.readFileSync(configPath, "utf8"));
13370
+ }
13371
+ function parseConfig(content) {
13372
+ const raw = import_yaml2.default.parse(content);
13282
13373
  const eventModelDir = raw?.paths?.event_model_dir ?? "event-model";
13283
13374
  const featuresDir = raw?.paths?.features_dir ?? "src/features";
13284
13375
  const sliceExtension = raw?.paths?.slice_extension ?? ".slice.yaml";
@@ -13289,26 +13380,32 @@ function readConfig(projectRoot) {
13289
13380
  featuresDir,
13290
13381
  sliceExtension,
13291
13382
  eventsFile: raw?.paths?.events_file ?? path.posix.join(eventModelDir, "events.yaml"),
13383
+ actorsFile: path.posix.normalize(raw?.paths?.actors_file ?? path.posix.join(eventModelDir, "actors.yaml")),
13292
13384
  storiesDir: raw?.paths?.stories_dir ?? path.posix.join(eventModelDir, "stories")
13293
13385
  }
13294
13386
  };
13295
13387
  }
13296
13388
 
13297
13389
  // ../parser/dist/browser.js
13298
- var import_yaml2 = __toESM(require_dist(), 1);
13299
-
13300
- // ../parser/dist/index.js
13301
- function asStringArray(value) {
13302
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
13303
- }
13390
+ var import_yaml3 = __toESM(require_dist(), 1);
13304
13391
  function normalizeRelativePath(filePath) {
13305
- return filePath.replaceAll("\\", "/").replace(/^\/+/, "");
13392
+ const parts = [];
13393
+ for (const part of filePath.replaceAll("\\", "/").split("/")) {
13394
+ if (!part || part === ".")
13395
+ continue;
13396
+ if (part === ".." && parts.length > 0 && parts.at(-1) !== "..")
13397
+ parts.pop();
13398
+ else
13399
+ parts.push(part);
13400
+ }
13401
+ return parts.join("/");
13306
13402
  }
13307
- function rel(projectRoot, filePath) {
13308
- return path2.relative(projectRoot, filePath).split(path2.sep).join(path2.posix.sep);
13403
+ function basename(filePath, extension = "") {
13404
+ const name = normalizeRelativePath(filePath).split("/").at(-1) ?? filePath;
13405
+ return extension && name.endsWith(extension) ? name.slice(0, -extension.length) : name;
13309
13406
  }
13310
- function resolveProjectPath(projectRoot, relativePath) {
13311
- return path2.resolve(projectRoot, relativePath);
13407
+ function asStringArray(value) {
13408
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
13312
13409
  }
13313
13410
  function parseEventsText(sourcePath, content) {
13314
13411
  const raw = import_yaml3.default.parse(content);
@@ -13320,23 +13417,15 @@ function parseEventsText(sourcePath, content) {
13320
13417
  sourcePath
13321
13418
  }));
13322
13419
  }
13323
- function parseEvents(projectRoot, eventsPath) {
13324
- const absolutePath = resolveProjectPath(projectRoot, eventsPath);
13325
- return parseEventsText(rel(projectRoot, absolutePath), fs2.readFileSync(absolutePath, "utf8"));
13326
- }
13327
13420
  function parseStoryText(storyPath, content) {
13328
13421
  const raw = import_yaml3.default.parse(content);
13329
13422
  return {
13330
- name: typeof raw?.name === "string" ? raw.name : path2.basename(storyPath, ".yaml"),
13423
+ name: typeof raw?.name === "string" ? raw.name : basename(storyPath, ".yaml"),
13331
13424
  description: typeof raw?.description === "string" ? raw.description : "",
13332
13425
  path: storyPath,
13333
13426
  slices: asStringArray(raw?.slices).map(normalizeRelativePath)
13334
13427
  };
13335
13428
  }
13336
- function parseStories(projectRoot, storiesDir) {
13337
- const pattern = path2.posix.join(storiesDir, "*.yaml");
13338
- return import_fast_glob.default.sync(pattern, { cwd: projectRoot, onlyFiles: true, ignore: ["node_modules/**", ".git/**", "dist/**"] }).sort().map((storyPath) => parseStoryText(storyPath, fs2.readFileSync(resolveProjectPath(projectRoot, storyPath), "utf8")));
13339
- }
13340
13429
  function parseCommands(value) {
13341
13430
  if (!Array.isArray(value))
13342
13431
  return [];
@@ -13372,7 +13461,7 @@ function parseScreen(raw) {
13372
13461
  return {
13373
13462
  type: raw?.type === "system" ? "system" : "user",
13374
13463
  name: typeof raw?.name === "string" ? raw.name : void 0,
13375
- actors: asStringArray(raw?.actors),
13464
+ ...parseActorReferences(raw?.actors),
13376
13465
  reads: asStringArray(raw?.reads),
13377
13466
  executes: asStringArray(raw?.executes)
13378
13467
  };
@@ -13380,7 +13469,7 @@ function parseScreen(raw) {
13380
13469
  function parseSliceText(slicePath, content, storyBySlice) {
13381
13470
  const raw = import_yaml3.default.parse(content);
13382
13471
  return {
13383
- title: typeof raw?.slice === "string" ? raw.slice : path2.basename(slicePath),
13472
+ title: typeof raw?.slice === "string" ? raw.slice : basename(slicePath),
13384
13473
  path: slicePath,
13385
13474
  storyName: storyBySlice.get(slicePath),
13386
13475
  screen: parseScreen(raw?.screen),
@@ -13390,6 +13479,147 @@ function parseSliceText(slicePath, content, storyBySlice) {
13390
13479
  raw: content
13391
13480
  };
13392
13481
  }
13482
+ function loadEventModelProjectFromFiles(files, options = {}) {
13483
+ const normalizedFiles = new Map(files.map((file) => [normalizeRelativePath(file.path), file.content]));
13484
+ const configContent = normalizedFiles.get(".event-modeling/config.yaml");
13485
+ const configRaw = configContent ? import_yaml3.default.parse(configContent) : null;
13486
+ const eventModelDir = configRaw?.paths?.event_model_dir ?? "event-model";
13487
+ const featuresDir = configRaw?.paths?.features_dir ?? "event-model/features";
13488
+ const sliceExtension = configRaw?.paths?.slice_extension ?? ".slice.yaml";
13489
+ const eventsFile = configRaw?.paths?.events_file ?? `${eventModelDir}/events.yaml`;
13490
+ const actorsFile = normalizeRelativePath(configRaw?.paths?.actors_file ?? `${eventModelDir}/actors.yaml`);
13491
+ const storiesDir = configRaw?.paths?.stories_dir ?? `${eventModelDir}/stories`;
13492
+ const eventsContent = normalizedFiles.get(eventsFile);
13493
+ if (eventsContent === void 0)
13494
+ throw new Error(`Missing events file: ${eventsFile}`);
13495
+ const events = parseEventsText(eventsFile, eventsContent);
13496
+ 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));
13497
+ const storyBySlice = /* @__PURE__ */ new Map();
13498
+ for (const story of stories)
13499
+ for (const slicePath of story.slices)
13500
+ storyBySlice.set(normalizeRelativePath(slicePath), story.name);
13501
+ const storySlicePaths = stories.flatMap((story) => story.slices.map(normalizeRelativePath));
13502
+ const discoveredSlicePaths = [...normalizedFiles.keys()].filter((filePath) => (featuresDir === "" || filePath.startsWith(`${featuresDir}/`)) && filePath.endsWith(sliceExtension));
13503
+ const slicePaths = [.../* @__PURE__ */ new Set([...storySlicePaths, ...discoveredSlicePaths])].sort();
13504
+ const slices = slicePaths.filter((filePath) => normalizedFiles.has(filePath)).map((filePath) => parseSliceText(filePath, normalizedFiles.get(filePath) ?? "", storyBySlice));
13505
+ const actorData = loadActors(normalizedFiles.get(actorsFile), actorsFile, slices);
13506
+ const projectWithoutGraph = {
13507
+ root: options.root ?? "browser-import",
13508
+ config: {
13509
+ language: configRaw?.language,
13510
+ paths: { eventModelDir, featuresDir, sliceExtension, eventsFile, actorsFile, storiesDir }
13511
+ },
13512
+ events,
13513
+ stories,
13514
+ slices,
13515
+ ...actorData
13516
+ };
13517
+ const graph = buildGraph(projectWithoutGraph);
13518
+ return { ...projectWithoutGraph, ...graph };
13519
+ }
13520
+
13521
+ // ../parser/dist/index.js
13522
+ function asStringArray2(value) {
13523
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
13524
+ }
13525
+ function normalizeRelativePath2(filePath) {
13526
+ const parts = [];
13527
+ for (const part of filePath.replaceAll("\\", "/").split("/")) {
13528
+ if (!part || part === ".")
13529
+ continue;
13530
+ if (part === ".." && parts.length > 0 && parts.at(-1) !== "..")
13531
+ parts.pop();
13532
+ else
13533
+ parts.push(part);
13534
+ }
13535
+ return parts.join("/");
13536
+ }
13537
+ function rel(projectRoot, filePath) {
13538
+ return path2.relative(projectRoot, filePath).split(path2.sep).join(path2.posix.sep);
13539
+ }
13540
+ function resolveProjectPath(projectRoot, relativePath) {
13541
+ return path2.resolve(projectRoot, relativePath);
13542
+ }
13543
+ function parseEventsText2(sourcePath, content) {
13544
+ const raw = import_yaml4.default.parse(content);
13545
+ const eventMap = raw?.events && typeof raw.events === "object" ? raw.events : raw ?? {};
13546
+ return Object.entries(eventMap).map(([name, entry]) => ({
13547
+ name,
13548
+ fields: typeof entry?.fields === "string" ? entry.fields : void 0,
13549
+ description: typeof entry?.description === "string" ? entry.description : void 0,
13550
+ sourcePath
13551
+ }));
13552
+ }
13553
+ function parseEvents(projectRoot, eventsPath) {
13554
+ const absolutePath = resolveProjectPath(projectRoot, eventsPath);
13555
+ return parseEventsText2(rel(projectRoot, absolutePath), fs2.readFileSync(absolutePath, "utf8"));
13556
+ }
13557
+ function parseStoryText2(storyPath, content) {
13558
+ const raw = import_yaml4.default.parse(content);
13559
+ return {
13560
+ name: typeof raw?.name === "string" ? raw.name : path2.basename(storyPath, ".yaml"),
13561
+ description: typeof raw?.description === "string" ? raw.description : "",
13562
+ path: storyPath,
13563
+ slices: asStringArray2(raw?.slices).map(normalizeRelativePath2)
13564
+ };
13565
+ }
13566
+ function parseStories(projectRoot, storiesDir) {
13567
+ const pattern = path2.posix.join(storiesDir, "*.yaml");
13568
+ return import_fast_glob.default.sync(pattern, { cwd: projectRoot, onlyFiles: true, ignore: ["node_modules/**", ".git/**", "dist/**"] }).sort().map((storyPath) => parseStoryText2(storyPath, fs2.readFileSync(resolveProjectPath(projectRoot, storyPath), "utf8")));
13569
+ }
13570
+ function parseCommands2(value) {
13571
+ if (!Array.isArray(value))
13572
+ return [];
13573
+ return value.filter((item) => Boolean(item) && typeof item === "object").map((item) => ({
13574
+ name: typeof item.name === "string" ? item.name : "",
13575
+ fields: typeof item.fields === "string" ? item.fields : void 0,
13576
+ notes: typeof item.notes === "string" ? item.notes : void 0,
13577
+ produces: asStringArray2(item.produces)
13578
+ }));
13579
+ }
13580
+ function parseQueries2(value) {
13581
+ if (!Array.isArray(value))
13582
+ return [];
13583
+ return value.filter((item) => Boolean(item) && typeof item === "object").map((item) => ({
13584
+ name: typeof item.name === "string" ? item.name : "",
13585
+ fields: typeof item.fields === "string" ? item.fields : void 0,
13586
+ notes: typeof item.notes === "string" ? item.notes : void 0,
13587
+ fromEvents: asStringArray2(item.from_events)
13588
+ }));
13589
+ }
13590
+ function parseGwt2(value) {
13591
+ if (!Array.isArray(value))
13592
+ return [];
13593
+ return value.filter((item) => Boolean(item) && typeof item === "object").map((item) => ({
13594
+ name: typeof item.name === "string" ? item.name : void 0,
13595
+ description: typeof item.description === "string" ? item.description : void 0,
13596
+ given: Array.isArray(item.given) ? item.given : [],
13597
+ when: Array.isArray(item.when) ? item.when : [],
13598
+ then: Array.isArray(item.then) ? item.then : []
13599
+ }));
13600
+ }
13601
+ function parseScreen2(raw) {
13602
+ return {
13603
+ type: raw?.type === "system" ? "system" : "user",
13604
+ name: typeof raw?.name === "string" ? raw.name : void 0,
13605
+ ...parseActorReferences(raw?.actors),
13606
+ reads: asStringArray2(raw?.reads),
13607
+ executes: asStringArray2(raw?.executes)
13608
+ };
13609
+ }
13610
+ function parseSliceText2(slicePath, content, storyBySlice) {
13611
+ const raw = import_yaml4.default.parse(content);
13612
+ return {
13613
+ title: typeof raw?.slice === "string" ? raw.slice : path2.basename(slicePath),
13614
+ path: slicePath,
13615
+ storyName: storyBySlice.get(slicePath),
13616
+ screen: parseScreen2(raw?.screen),
13617
+ commands: parseCommands2(raw?.commands),
13618
+ queries: parseQueries2(raw?.queries),
13619
+ gwt: parseGwt2(raw?.gwt),
13620
+ raw: content
13621
+ };
13622
+ }
13393
13623
  function parseSlices(projectRoot, stories, sliceGlob) {
13394
13624
  const storyBySlice = /* @__PURE__ */ new Map();
13395
13625
  for (const story of stories) {
@@ -13404,7 +13634,7 @@ function parseSlices(projectRoot, stories, sliceGlob) {
13404
13634
  ignore: ["node_modules/**", ".git/**", "dist/**", "build/**"]
13405
13635
  });
13406
13636
  const paths = [.../* @__PURE__ */ new Set([...storySlices, ...discoveredSlices])].sort();
13407
- return paths.filter((slicePath) => fs2.existsSync(resolveProjectPath(projectRoot, slicePath))).map((slicePath) => parseSliceText(slicePath, fs2.readFileSync(resolveProjectPath(projectRoot, slicePath), "utf8"), storyBySlice));
13637
+ return paths.filter((slicePath) => fs2.existsSync(resolveProjectPath(projectRoot, slicePath))).map((slicePath) => parseSliceText2(slicePath, fs2.readFileSync(resolveProjectPath(projectRoot, slicePath), "utf8"), storyBySlice));
13408
13638
  }
13409
13639
  function loadEventModelProject(startDir) {
13410
13640
  const root = findProjectRoot(startDir);
@@ -13412,7 +13642,11 @@ function loadEventModelProject(startDir) {
13412
13642
  const events = parseEvents(root, config.paths.eventsFile);
13413
13643
  const stories = parseStories(root, config.paths.storiesDir);
13414
13644
  const slices = parseSlices(root, stories, path2.posix.join(config.paths.featuresDir, `**/*${config.paths.sliceExtension}`));
13415
- const projectWithoutGraph = { root, config, events, stories, slices };
13645
+ const actorsPath = config.paths.actorsFile ?? path2.posix.join(config.paths.eventModelDir, "actors.yaml");
13646
+ const absoluteActorsPath = resolveProjectPath(root, actorsPath);
13647
+ const actorsContent = fs2.existsSync(absoluteActorsPath) ? fs2.readFileSync(absoluteActorsPath, "utf8") : void 0;
13648
+ const actorData = loadActors(actorsContent, actorsPath, slices);
13649
+ const projectWithoutGraph = { root, config, events, stories, slices, ...actorData };
13416
13650
  const graph = buildGraph(projectWithoutGraph);
13417
13651
  return {
13418
13652
  ...projectWithoutGraph,
@@ -13420,9 +13654,53 @@ function loadEventModelProject(startDir) {
13420
13654
  };
13421
13655
  }
13422
13656
 
13423
- // ../graph/dist/index.js
13657
+ // src/gitSources.ts
13424
13658
  import fs3 from "node:fs";
13659
+ import os from "node:os";
13425
13660
  import path3 from "node:path";
13661
+ import { execFileSync } from "node:child_process";
13662
+ function materializeGitRef(ref, cwd = process.cwd()) {
13663
+ const tempRoot = fs3.mkdtempSync(path3.join(os.tmpdir(), "emviz-diff-"));
13664
+ const files = execFileSync("git", ["ls-tree", "-r", "-z", "--name-only", ref, "--", ".event-modeling", "event-model"], {
13665
+ cwd,
13666
+ encoding: "utf8"
13667
+ }).split("\0").filter(Boolean);
13668
+ if (files.includes(".event-modeling/config.yaml")) {
13669
+ const configText = execFileSync("git", ["show", `${ref}:.event-modeling/config.yaml`], {
13670
+ cwd,
13671
+ encoding: "utf8",
13672
+ maxBuffer: 20 * 1024 * 1024
13673
+ });
13674
+ const config = parseConfig(configText);
13675
+ const actorsFile = path3.posix.normalize(config.paths.actorsFile ?? path3.posix.join(config.paths.eventModelDir, "actors.yaml"));
13676
+ if (path3.isAbsolute(actorsFile) || actorsFile === ".." || actorsFile.startsWith("../")) {
13677
+ throw new Error("Actor registry must stay inside the project directory.");
13678
+ }
13679
+ if (!files.includes(actorsFile)) {
13680
+ const tracked = execFileSync("git", ["ls-tree", "-r", "-z", "--name-only", ref, "--", actorsFile], {
13681
+ cwd,
13682
+ encoding: "utf8"
13683
+ }).split("\0");
13684
+ if (tracked.includes(actorsFile)) files.push(actorsFile);
13685
+ }
13686
+ }
13687
+ if (files.length === 0) throw new Error(`Git ref "${ref}" does not contain .event-modeling or event-model files.`);
13688
+ for (const file of files) {
13689
+ const content = execFileSync("git", ["show", `${ref}:${file}`], {
13690
+ cwd,
13691
+ encoding: "utf8",
13692
+ maxBuffer: 20 * 1024 * 1024
13693
+ });
13694
+ const outputPath = path3.join(tempRoot, file);
13695
+ fs3.mkdirSync(path3.dirname(outputPath), { recursive: true });
13696
+ fs3.writeFileSync(outputPath, content);
13697
+ }
13698
+ return tempRoot;
13699
+ }
13700
+
13701
+ // ../graph/dist/index.js
13702
+ import fs4 from "node:fs";
13703
+ import path4 from "node:path";
13426
13704
  function selectorForNode(node) {
13427
13705
  switch (node.type) {
13428
13706
  case "story":
@@ -13446,7 +13724,7 @@ function sourceTypeForNode(node) {
13446
13724
  return node.type === "processor" ? "screen" : node.type;
13447
13725
  }
13448
13726
  function defaultModelId(projectRoot) {
13449
- return path3.basename(projectRoot).replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase() || "event_model";
13727
+ return path4.basename(projectRoot).replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase() || "event_model";
13450
13728
  }
13451
13729
  function nodeSelectorKey(node) {
13452
13730
  return JSON.stringify({ type: node.type, selector: node.selector });
@@ -13485,6 +13763,7 @@ function comparableNode(node) {
13485
13763
  sliceTitle: node.sliceTitle,
13486
13764
  sourceName: node.sourceName,
13487
13765
  actors: node.actors,
13766
+ actorDefinitions: node.actorDefinitions,
13488
13767
  screenType: node.screenType,
13489
13768
  fields: node.fields,
13490
13769
  description: node.description,
@@ -13497,8 +13776,7 @@ function edgeKey(edge, nodeKeys) {
13497
13776
  return stableJson({
13498
13777
  kind: edge.kind,
13499
13778
  source: nodeKeys.get(edge.source) ?? edge.source,
13500
- target: nodeKeys.get(edge.target) ?? edge.target,
13501
- label: edge.label
13779
+ target: nodeKeys.get(edge.target) ?? edge.target
13502
13780
  });
13503
13781
  }
13504
13782
  function comparableEdge(edge, nodeKeys) {
@@ -13519,11 +13797,13 @@ function cloneProject(project) {
13519
13797
  return {
13520
13798
  ...project,
13521
13799
  events: project.events.map((event) => ({ ...event })),
13800
+ actors: project.actors?.map((actor) => ({ ...actor })),
13801
+ actorIssues: project.actorIssues?.map((issue) => ({ ...issue })),
13522
13802
  stories: project.stories.map((story) => ({ ...story, slices: [...story.slices] })),
13523
13803
  slices: project.slices.map((slice) => ({
13524
13804
  ...slice,
13525
13805
  screen: { ...slice.screen, actors: [...slice.screen.actors], reads: [...slice.screen.reads], executes: [...slice.screen.executes] },
13526
- commands: slice.commands.map((command2) => ({ ...command2, produces: [...command2.produces] })),
13806
+ commands: slice.commands.map((command) => ({ ...command, produces: [...command.produces] })),
13527
13807
  queries: slice.queries.map((query) => ({ ...query, fromEvents: [...query.fromEvents] })),
13528
13808
  gwt: slice.gwt.map((scenario) => ({
13529
13809
  ...scenario,
@@ -13532,7 +13812,7 @@ function cloneProject(project) {
13532
13812
  then: [...scenario.then]
13533
13813
  }))
13534
13814
  })),
13535
- nodes: project.nodes.map((node) => ({ ...node })),
13815
+ nodes: project.nodes.map((node) => structuredClone(node)),
13536
13816
  edges: project.edges.map((edge) => ({ ...edge }))
13537
13817
  };
13538
13818
  }
@@ -13580,7 +13860,7 @@ function mergeRemovedModelContainers(merged, base) {
13580
13860
  merged.slices.push({
13581
13861
  ...slice,
13582
13862
  screen: { ...slice.screen, actors: [...slice.screen.actors], reads: [...slice.screen.reads], executes: [...slice.screen.executes] },
13583
- commands: slice.commands.map((command2) => ({ ...command2, produces: [...command2.produces] })),
13863
+ commands: slice.commands.map((command) => ({ ...command, produces: [...command.produces] })),
13584
13864
  queries: slice.queries.map((query) => ({ ...query, fromEvents: [...query.fromEvents] })),
13585
13865
  gwt: slice.gwt.map((scenario) => ({
13586
13866
  ...scenario,
@@ -13621,6 +13901,7 @@ function buildGraphSidecar(project, existing) {
13621
13901
  },
13622
13902
  sources: {
13623
13903
  events: project.config.paths.eventsFile,
13904
+ actors: project.config.paths.actorsFile,
13624
13905
  stories: [`${project.config.paths.storiesDir}/**/*.yaml`],
13625
13906
  slices: [`${project.config.paths.featuresDir}/**/*${project.config.paths.sliceExtension}`]
13626
13907
  },
@@ -13654,6 +13935,8 @@ function diffEventModelProjects(base, target, labels = {}) {
13654
13935
  const targetNodesByKey = new Map(target.nodes.map((node) => [targetNodeKeysById.get(node.id), node]));
13655
13936
  const nodeStatus = {};
13656
13937
  const previousGwtNodes = {};
13938
+ const previousNodes = {};
13939
+ const previousEdges = {};
13657
13940
  const mergedNodeIdByBaseId = /* @__PURE__ */ new Map();
13658
13941
  mergeRemovedModelContainers(merged, base);
13659
13942
  for (const targetNode of target.nodes) {
@@ -13664,8 +13947,11 @@ function diffEventModelProjects(base, target, labels = {}) {
13664
13947
  continue;
13665
13948
  }
13666
13949
  nodeStatus[targetNode.id] = stableJson(comparableNode(baseNode)) === stableJson(comparableNode(targetNode)) ? "unchanged" : "changed";
13667
- if (targetNode.type === "gwt" && nodeStatus[targetNode.id] === "changed")
13668
- previousGwtNodes[targetNode.id] = structuredClone(baseNode);
13950
+ if (nodeStatus[targetNode.id] === "changed") {
13951
+ previousNodes[targetNode.id] = structuredClone(baseNode);
13952
+ if (targetNode.type === "gwt")
13953
+ previousGwtNodes[targetNode.id] = structuredClone(baseNode);
13954
+ }
13669
13955
  }
13670
13956
  for (const baseNode of base.nodes) {
13671
13957
  const key = baseNodeKeysById.get(baseNode.id);
@@ -13673,8 +13959,9 @@ function diffEventModelProjects(base, target, labels = {}) {
13673
13959
  continue;
13674
13960
  const id = uniqueNodeId(existingNodeIds, baseNode.id);
13675
13961
  mergedNodeIdByBaseId.set(baseNode.id, id);
13676
- merged.nodes.push({ ...baseNode, id });
13962
+ merged.nodes.push({ ...structuredClone(baseNode), id });
13677
13963
  nodeStatus[id] = "removed";
13964
+ previousNodes[id] = structuredClone(baseNode);
13678
13965
  }
13679
13966
  const baseEdgesByKey = new Map(base.edges.map((edge) => [edgeKey(edge, baseNodeKeysById), edge]));
13680
13967
  const targetEdgesByKey = new Map(target.edges.map((edge) => [edgeKey(edge, targetNodeKeysById), edge]));
@@ -13687,6 +13974,8 @@ function diffEventModelProjects(base, target, labels = {}) {
13687
13974
  continue;
13688
13975
  }
13689
13976
  edgeStatus[targetEdge.id] = stableJson(comparableEdge(baseEdge, baseNodeKeysById)) === stableJson(comparableEdge(targetEdge, targetNodeKeysById)) ? "unchanged" : "changed";
13977
+ if (edgeStatus[targetEdge.id] === "changed")
13978
+ previousEdges[targetEdge.id] = structuredClone(baseEdge);
13690
13979
  }
13691
13980
  for (const baseEdge of base.edges) {
13692
13981
  const key = edgeKey(baseEdge, baseNodeKeysById);
@@ -13697,6 +13986,7 @@ function diffEventModelProjects(base, target, labels = {}) {
13697
13986
  const id = uniqueEdgeId(existingEdgeIds, baseEdge.id);
13698
13987
  merged.edges.push({ ...baseEdge, id, source, target: targetId });
13699
13988
  edgeStatus[id] = "removed";
13989
+ previousEdges[id] = structuredClone(baseEdge);
13700
13990
  }
13701
13991
  return {
13702
13992
  project: merged,
@@ -13704,6 +13994,8 @@ function diffEventModelProjects(base, target, labels = {}) {
13704
13994
  base: { label: labels.base ?? "base" },
13705
13995
  target: { label: labels.target ?? "target" },
13706
13996
  previousGwtNodes,
13997
+ previousNodes,
13998
+ previousEdges,
13707
13999
  nodeStatus,
13708
14000
  edgeStatus,
13709
14001
  summary: {
@@ -13714,13 +14006,13 @@ function diffEventModelProjects(base, target, labels = {}) {
13714
14006
  };
13715
14007
  }
13716
14008
  function readGraphSidecar(projectRoot) {
13717
- const sidecarPath = path3.join(projectRoot, ".event-modeling", "graph.json");
13718
- if (!fs3.existsSync(sidecarPath))
14009
+ const sidecarPath = path4.join(projectRoot, ".event-modeling", "graph.json");
14010
+ if (!fs4.existsSync(sidecarPath))
13719
14011
  return void 0;
13720
- return JSON.parse(fs3.readFileSync(sidecarPath, "utf8"));
14012
+ return JSON.parse(fs4.readFileSync(sidecarPath, "utf8"));
13721
14013
  }
13722
14014
  function writeGraphSidecar(project) {
13723
- const sidecarPath = path3.join(project.root, ".event-modeling", "graph.json");
14015
+ const sidecarPath = path4.join(project.root, ".event-modeling", "graph.json");
13724
14016
  const existing = readGraphSidecar(project.root);
13725
14017
  const next = buildGraphSidecar(project, existing);
13726
14018
  const generated = generatedNodes(project);
@@ -13729,8 +14021,8 @@ function writeGraphSidecar(project) {
13729
14021
  const added = Object.entries(generated).filter(([, node]) => !existingSelectorKeys.has(nodeSelectorKey(node))).map(([id]) => id);
13730
14022
  const preserved = Object.entries(existing?.nodes ?? {}).filter(([, node]) => generatedSelectorKeys.has(nodeSelectorKey(node))).map(([id]) => id);
13731
14023
  const stale = Object.entries(existing?.nodes ?? {}).filter(([, node]) => !generatedSelectorKeys.has(nodeSelectorKey(node))).map(([id]) => id);
13732
- fs3.mkdirSync(path3.dirname(sidecarPath), { recursive: true });
13733
- fs3.writeFileSync(sidecarPath, `${JSON.stringify(next, null, 2)}
14024
+ fs4.mkdirSync(path4.dirname(sidecarPath), { recursive: true });
14025
+ fs4.writeFileSync(sidecarPath, `${JSON.stringify(next, null, 2)}
13734
14026
  `);
13735
14027
  return {
13736
14028
  path: sidecarPath,
@@ -13751,8 +14043,8 @@ function resolveSidecarNode(project, node) {
13751
14043
  }
13752
14044
 
13753
14045
  // ../validator/dist/index.js
13754
- import fs4 from "node:fs";
13755
- import path4 from "node:path";
14046
+ import fs5 from "node:fs";
14047
+ import path5 from "node:path";
13756
14048
  function finding(severity, check, message, pathValue, nodeId) {
13757
14049
  return {
13758
14050
  id: `${check}:${pathValue ?? "project"}:${message}`,
@@ -13853,8 +14145,8 @@ function connectedComponentCount(project) {
13853
14145
  }
13854
14146
  return components;
13855
14147
  }
13856
- function validateEventModelProject(project) {
13857
- const findings = [];
14148
+ function validateEventModelProject(project, snapshot) {
14149
+ const findings = (project.actorIssues ?? []).map((issue) => finding("error", "A1", issue.message, issue.path));
13858
14150
  const eventNames = new Set(project.events.map((event) => event.name));
13859
14151
  const produced = /* @__PURE__ */ new Map();
13860
14152
  const consumed = /* @__PURE__ */ new Map();
@@ -13863,7 +14155,7 @@ function validateEventModelProject(project) {
13863
14155
  findings.push(finding("warning", "S4", `Story "${story.name}" has ${story.slices.length} slices; consider splitting it.`, story.path));
13864
14156
  }
13865
14157
  for (const slicePath of story.slices) {
13866
- if (!fs4.existsSync(path4.join(project.root, slicePath))) {
14158
+ if (snapshot ? !snapshot.sourcePaths.has(slicePath) : !fs5.existsSync(path5.join(project.root, slicePath))) {
13867
14159
  findings.push(finding("error", "S2", `Story "${story.name}" lists missing slice "${slicePath}".`, story.path));
13868
14160
  }
13869
14161
  }
@@ -13881,7 +14173,7 @@ function validateEventModelProject(project) {
13881
14173
  }
13882
14174
  }
13883
14175
  for (const slice of project.slices) {
13884
- const commandNames = slice.commands.map((command2) => command2.name);
14176
+ const commandNames = slice.commands.map((command) => command.name);
13885
14177
  const queryNames = slice.queries.map((query) => query.name);
13886
14178
  for (const name of duplicates(commandNames)) {
13887
14179
  findings.push(finding("error", "L9", `Command "${name}" is duplicated within slice "${slice.title}".`, slice.path));
@@ -13914,15 +14206,15 @@ function validateEventModelProject(project) {
13914
14206
  if (slice.commands.length > 0 && slice.gwt.length === 0) {
13915
14207
  findings.push(finding("warning", "M1", `Command slice "${slice.title}" has no GWT scenarios.`, slice.path));
13916
14208
  }
13917
- for (const command2 of slice.commands) {
13918
- if (!command2.fields?.trim()) {
13919
- findings.push(finding("warning", "L6", `Command "${command2.name}" has no fields block.`, slice.path));
14209
+ for (const command of slice.commands) {
14210
+ if (!command.fields?.trim()) {
14211
+ findings.push(finding("warning", "L6", `Command "${command.name}" has no fields block.`, slice.path));
13920
14212
  }
13921
- for (const eventName of command2.produces) {
14213
+ for (const eventName of command.produces) {
13922
14214
  if (!eventNames.has(eventName)) {
13923
- findings.push(finding("error", "G1", `Command "${command2.name}" produces unregistered event "${eventName}".`, slice.path));
14215
+ findings.push(finding("error", "G1", `Command "${command.name}" produces unregistered event "${eventName}".`, slice.path));
13924
14216
  }
13925
- produced.set(eventName, [...produced.get(eventName) ?? [], `${slice.title}.${command2.name}`]);
14217
+ produced.set(eventName, [...produced.get(eventName) ?? [], `${slice.title}.${command.name}`]);
13926
14218
  }
13927
14219
  }
13928
14220
  for (const query of slice.queries) {
@@ -13968,7 +14260,7 @@ function validateEventModelProject(project) {
13968
14260
  findings.push(finding("error", "G3", `Event "${eventName}" is read by ${consumers.join(", ")} but no command produces it.`));
13969
14261
  }
13970
14262
  }
13971
- for (const name of duplicates(project.slices.flatMap((slice) => slice.commands.map((command2) => command2.name)))) {
14263
+ for (const name of duplicates(project.slices.flatMap((slice) => slice.commands.map((command) => command.name)))) {
13972
14264
  findings.push(finding("warning", "M5", `Command name "${name}" is used in multiple slices; command names should be globally unique.`));
13973
14265
  }
13974
14266
  for (const name of duplicates(project.slices.flatMap((slice) => slice.queries.map((query) => query.name)))) {
@@ -13978,7 +14270,7 @@ function validateEventModelProject(project) {
13978
14270
  if (commandSliceCount > 0 && project.events.length / commandSliceCount > 2) {
13979
14271
  findings.push(finding("warning", "M4", `The model has ${(project.events.length / commandSliceCount).toFixed(1)} events per command slice; check for UI/runtime events leaking into the model.`));
13980
14272
  }
13981
- const sidecar = readGraphSidecar(project.root);
14273
+ const sidecar = snapshot ? snapshot.sidecar : readGraphSidecar(project.root);
13982
14274
  if (sidecar) {
13983
14275
  for (const [nodeId, sidecarNode] of Object.entries(sidecar.nodes)) {
13984
14276
  const matches = resolveSidecarNode(project, sidecarNode);
@@ -14001,11 +14293,652 @@ function validateEventModelProject(project) {
14001
14293
  };
14002
14294
  }
14003
14295
 
14296
+ // src/feedback.ts
14297
+ import fs6 from "node:fs";
14298
+ import path6 from "node:path";
14299
+ import { randomUUID, createHash } from "node:crypto";
14300
+ import { execFileSync as execFileSync2 } from "node:child_process";
14301
+
14302
+ // src/network.ts
14303
+ import { isIP } from "node:net";
14304
+ import { timingSafeEqual } from "node:crypto";
14305
+ function parseHost(value = "127.0.0.1") {
14306
+ const host = value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
14307
+ const family = isIP(host);
14308
+ 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.");
14309
+ const normalized = family === 6 ? new URL("http://[" + host + "]/").hostname.slice(1, -1) : host;
14310
+ if (normalized === "0.0.0.0" || normalized === "::" || normalized === "::ffff:0:0") {
14311
+ throw new Error("--host must select one interface address. Wildcard addresses are not supported.");
14312
+ }
14313
+ return normalized;
14314
+ }
14315
+ function parseHostArgs(values) {
14316
+ let host = "127.0.0.1";
14317
+ let provided = false;
14318
+ const args = [];
14319
+ for (let index = 0; index < values.length; index++) {
14320
+ const value = values[index];
14321
+ if (value !== "--host" && !value.startsWith("--host=")) {
14322
+ args.push(value);
14323
+ continue;
14324
+ }
14325
+ if (provided) throw new Error("--host may be specified only once.");
14326
+ const address = value === "--host" ? values[++index] : value.slice("--host=".length);
14327
+ if (!address || address.startsWith("--")) throw new Error("--host requires an IPv4 or IPv6 address.");
14328
+ host = parseHost(address);
14329
+ provided = true;
14330
+ }
14331
+ return { host, args, provided };
14332
+ }
14333
+ function isLoopbackHost(host) {
14334
+ return host === "::1" || host.startsWith("127.");
14335
+ }
14336
+ function serverOrigin(host, port) {
14337
+ return "http://" + (host.includes(":") ? "[" + host + "]" : host) + ":" + port;
14338
+ }
14339
+ function trustedRequest(req, port, host = "127.0.0.1") {
14340
+ const authority = new URL(serverOrigin(host, port)).host;
14341
+ const allowed = host === "127.0.0.1" ? [authority, "localhost:" + port] : [authority];
14342
+ const requestHost = req.headers.host;
14343
+ if (!requestHost || !allowed.includes(requestHost)) return false;
14344
+ const origin = req.headers.origin;
14345
+ return origin === void 0 || origin === "http://" + requestHost;
14346
+ }
14347
+ function validToken(req, expected) {
14348
+ const token = req.headers["x-emviz-token"];
14349
+ if (typeof token !== "string") return false;
14350
+ const actual = Buffer.from(token);
14351
+ const wanted = Buffer.from(expected);
14352
+ return actual.length === wanted.length && timingSafeEqual(actual, wanted);
14353
+ }
14354
+ function apiRequestAuthorized(req, pathname, host, token) {
14355
+ return isLoopbackHost(host) || pathname !== "/api" && !pathname.startsWith("/api/") || validToken(req, token);
14356
+ }
14357
+
14358
+ // src/feedback.ts
14359
+ var FeedbackError = class extends Error {
14360
+ constructor(status, message) {
14361
+ super(message);
14362
+ this.status = status;
14363
+ }
14364
+ status;
14365
+ };
14366
+ function sourceKey(root, source) {
14367
+ const relative = path6.relative(root, path6.resolve(root, source));
14368
+ if (path6.isAbsolute(source) || relative.startsWith("..") || path6.isAbsolute(relative)) throw new FeedbackError(400, "Model sources must stay inside the project directory.");
14369
+ return relative.split(path6.sep).join("/");
14370
+ }
14371
+ function withinRoot(root, source) {
14372
+ const key = sourceKey(root, source);
14373
+ const resolved = fs6.realpathSync(path6.resolve(root, key));
14374
+ const relative = path6.relative(fs6.realpathSync(root), resolved);
14375
+ if (relative.startsWith("..") || path6.isAbsolute(relative)) throw new FeedbackError(400, "Model sources must stay inside the project directory.");
14376
+ return resolved;
14377
+ }
14378
+ function sourceExists(root, source) {
14379
+ try {
14380
+ fs6.lstatSync(path6.resolve(root, sourceKey(root, source)));
14381
+ return true;
14382
+ } catch (error) {
14383
+ if (error.code === "ENOENT") return false;
14384
+ throw error;
14385
+ }
14386
+ }
14387
+ function normalizedConfig(root, text) {
14388
+ const config = parseConfig(text);
14389
+ return { ...config, paths: {
14390
+ ...config.paths,
14391
+ eventModelDir: sourceKey(root, config.paths.eventModelDir),
14392
+ featuresDir: sourceKey(root, config.paths.featuresDir),
14393
+ eventsFile: sourceKey(root, config.paths.eventsFile),
14394
+ actorsFile: sourceKey(root, config.paths.actorsFile ?? path6.posix.join(config.paths.eventModelDir, "actors.yaml")),
14395
+ storiesDir: sourceKey(root, config.paths.storiesDir)
14396
+ } };
14397
+ }
14398
+ function parseFiles(root, files, config) {
14399
+ const paths = config.paths;
14400
+ const normalized = JSON.stringify({ language: config.language, paths: {
14401
+ event_model_dir: paths.eventModelDir,
14402
+ features_dir: paths.featuresDir,
14403
+ events_file: paths.eventsFile,
14404
+ actors_file: paths.actorsFile,
14405
+ stories_dir: paths.storiesDir,
14406
+ slice_extension: paths.sliceExtension
14407
+ } });
14408
+ return loadEventModelProjectFromFiles([...files].map(([name, content]) => ({
14409
+ path: name,
14410
+ content: name === ".event-modeling/config.yaml" ? normalized : content
14411
+ })), { root });
14412
+ }
14413
+ function readSnapshot(target) {
14414
+ const root = findProjectRoot(target);
14415
+ const files = /* @__PURE__ */ new Map();
14416
+ let bytes = 0;
14417
+ const read = (source) => {
14418
+ const key = sourceKey(root, source);
14419
+ if (files.has(key)) return;
14420
+ const file = withinRoot(root, key);
14421
+ if (files.size >= 512 || fs6.statSync(file).size + bytes > 8 * 1024 * 1024) throw new FeedbackError(413, "Feedback supports at most 512 files and 8 MiB.");
14422
+ const content = fs6.readFileSync(file, "utf8");
14423
+ bytes += Buffer.byteLength(content);
14424
+ if (bytes > 8 * 1024 * 1024) throw new FeedbackError(413, "Model grew beyond 8 MiB while reading.");
14425
+ files.set(key, content);
14426
+ };
14427
+ read(".event-modeling/config.yaml");
14428
+ const config = normalizedConfig(root, files.get(".event-modeling/config.yaml"));
14429
+ read(config.paths.eventsFile);
14430
+ if (config.paths.actorsFile && sourceExists(root, config.paths.actorsFile)) read(config.paths.actorsFile);
14431
+ let visitedEntries = 0;
14432
+ const walk = (directory, recursive, extension, visited = /* @__PURE__ */ new Set()) => {
14433
+ const key = sourceKey(root, directory);
14434
+ if (!sourceExists(root, key)) return;
14435
+ const resolved = withinRoot(root, key);
14436
+ if (visited.has(resolved)) return;
14437
+ visited.add(resolved);
14438
+ for (const entry of fs6.readdirSync(resolved, { withFileTypes: true })) {
14439
+ if (++visitedEntries > 1e4) throw new FeedbackError(413, "Model discovery exceeds 10000 directory entries.");
14440
+ if (entry.name.startsWith(".") || key === "" && ["node_modules", "dist", "build"].includes(entry.name)) continue;
14441
+ const relative = path6.posix.join(key, entry.name);
14442
+ const actual = withinRoot(root, relative);
14443
+ const stat = fs6.statSync(actual);
14444
+ if (stat.isDirectory() && recursive) walk(relative, true, extension, visited);
14445
+ else if (stat.isFile() && entry.name.endsWith(extension)) read(relative);
14446
+ }
14447
+ };
14448
+ walk(config.paths.storiesDir, false, ".yaml");
14449
+ walk(config.paths.featuresDir, true, config.paths.sliceExtension);
14450
+ const preliminary = parseFiles(root, files, config);
14451
+ for (const source of preliminary.stories.flatMap((story) => story.slices)) {
14452
+ const key = sourceKey(root, source);
14453
+ if (sourceExists(root, key)) read(key);
14454
+ }
14455
+ if (sourceExists(root, ".event-modeling/graph.json")) read(".event-modeling/graph.json");
14456
+ const project = parseFiles(root, files, config);
14457
+ const sidecarText = files.get(".event-modeling/graph.json");
14458
+ const graphSidecar = sidecarText === void 0 ? void 0 : JSON.parse(sidecarText);
14459
+ if (graphSidecar !== void 0 && (!graphSidecar || typeof graphSidecar !== "object" || typeof graphSidecar.model?.id !== "string" || !graphSidecar.nodes || typeof graphSidecar.nodes !== "object" || Array.isArray(graphSidecar.nodes) || Object.values(graphSidecar.nodes).some((node) => !node || typeof node.type !== "string" || !node.selector || typeof node.selector !== "object" || Object.values(node.selector).some((value) => typeof value !== "string")))) throw new FeedbackError(422, "Invalid .event-modeling/graph.json.");
14460
+ const validation = validateEventModelProject(project, { sourcePaths: new Set(files.keys()), sidecar: graphSidecar });
14461
+ const hash = createHash("sha256");
14462
+ for (const [source, content] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
14463
+ const actual = withinRoot(root, source);
14464
+ if (fs6.statSync(actual).size > 8 * 1024 * 1024 || fs6.readFileSync(actual, "utf8") !== content) throw new FeedbackError(409, "Model changed while reading. Try again.");
14465
+ hash.update(JSON.stringify([source, content]));
14466
+ }
14467
+ return { project, revision: hash.digest("hex"), files, graphSidecar, validation };
14468
+ }
14469
+ function gitBaseline(snapshot) {
14470
+ const root = snapshot.project.root;
14471
+ try {
14472
+ const git = (args) => execFileSync2("git", ["-C", root, ...args], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
14473
+ const commit = git(["rev-parse", "--verify", "HEAD^{commit}"]).trim();
14474
+ const repoRoot = git(["rev-parse", "--show-toplevel"]).trim();
14475
+ const prefix = path6.relative(fs6.realpathSync(repoRoot), fs6.realpathSync(root)).split(path6.sep).join("/");
14476
+ const names = git(["-C", repoRoot, "ls-tree", "--full-tree", "-r", "-z", "--name-only", commit, "--", prefix || "."]).split("\0").filter(Boolean);
14477
+ const tracked = new Set(names.map((name) => prefix ? name.slice(prefix.length + 1) : name));
14478
+ const files = /* @__PURE__ */ new Map();
14479
+ let bytes = 0;
14480
+ const read = (source) => {
14481
+ const key = sourceKey(root, source);
14482
+ if (files.has(key) || !tracked.has(key)) return;
14483
+ if (files.size >= 512) throw new Error("Git baseline exceeds 512 files.");
14484
+ const content = git(["show", commit + ":" + (prefix ? prefix + "/" : "") + key]);
14485
+ bytes += Buffer.byteLength(content);
14486
+ if (bytes > 8 * 1024 * 1024) throw new Error("Git baseline exceeds 8 MiB.");
14487
+ files.set(key, content);
14488
+ };
14489
+ read(".event-modeling/config.yaml");
14490
+ const rawConfig = files.get(".event-modeling/config.yaml");
14491
+ if (rawConfig === void 0) throw new Error("No model configuration at the baseline commit.");
14492
+ const config = normalizedConfig(root, rawConfig);
14493
+ read(config.paths.eventsFile);
14494
+ if (config.paths.actorsFile) read(config.paths.actorsFile);
14495
+ for (const key of tracked) {
14496
+ const isStory = (path6.posix.dirname(key) === "." ? "" : path6.posix.dirname(key)) === config.paths.storiesDir && !path6.posix.basename(key).startsWith(".") && key.endsWith(".yaml");
14497
+ const relative = config.paths.featuresDir ? key.slice(config.paths.featuresDir.length + 1) : key;
14498
+ const ignored = relative.split("/").some((part) => part.startsWith(".")) || ["node_modules/", "dist/", "build/"].some((directory) => key.startsWith(directory));
14499
+ const isSlice = !ignored && (config.paths.featuresDir === "" || key.startsWith(config.paths.featuresDir + "/")) && key.endsWith(config.paths.sliceExtension);
14500
+ if (isStory || isSlice) read(key);
14501
+ }
14502
+ const preliminary = parseFiles(root, files, config);
14503
+ for (const source of preliminary.stories.flatMap((story) => story.slices)) read(source);
14504
+ return { project: parseFiles(root, files, config), label: commit, kind: "git" };
14505
+ } catch (error) {
14506
+ return { project: structuredClone(snapshot.project), label: "Startup snapshot (Git baseline unavailable: " + (error instanceof Error ? error.message.split("\n")[0] : "unknown error") + ")", kind: "startup" };
14507
+ }
14508
+ }
14509
+ function textField(value, name, max) {
14510
+ if (typeof value !== "string" || !value.trim() || value.length > max) throw new FeedbackError(400, name + " must contain 1 to " + max + " characters.");
14511
+ return value;
14512
+ }
14513
+ function parseBatch(body) {
14514
+ const clientBatchId = textField(body.clientBatchId, "clientBatchId", 100);
14515
+ if (!Array.isArray(body.items) || body.items.length < 1 || body.items.length > 20) {
14516
+ throw new FeedbackError(400, "A batch must contain 1 to 20 items.");
14517
+ }
14518
+ const ids = /* @__PURE__ */ new Set();
14519
+ let messageLength = 0;
14520
+ const items = body.items.map((value) => {
14521
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new FeedbackError(400, "Expected a feedback item.");
14522
+ const item = value;
14523
+ const parsed = {
14524
+ id: textField(item.id, "item id", 100),
14525
+ nodeId: textField(item.nodeId, "nodeId", 500),
14526
+ reference: textField(item.reference, "reference", 1e3),
14527
+ revision: textField(item.revision, "revision", 100),
14528
+ message: textField(item.message, "message", 4e3)
14529
+ };
14530
+ if (ids.has(parsed.id)) throw new FeedbackError(400, "Batch item IDs must be unique.");
14531
+ ids.add(parsed.id);
14532
+ messageLength += parsed.message.length;
14533
+ return parsed;
14534
+ });
14535
+ if (messageLength > 16e3) throw new FeedbackError(413, "Batch messages exceed 16000 characters.");
14536
+ return { clientBatchId, items };
14537
+ }
14538
+ function nodeIdentity(node) {
14539
+ return JSON.stringify([node.type, node.sourcePath, node.sourceName, node.label, node.sliceTitle]);
14540
+ }
14541
+ function uniqueNodeIds(project) {
14542
+ const ids = /* @__PURE__ */ new Map();
14543
+ for (const node of project.nodes) {
14544
+ const key = nodeIdentity(node);
14545
+ ids.set(key, ids.has(key) ? void 0 : node.id);
14546
+ }
14547
+ return ids;
14548
+ }
14549
+ function captureNode(snapshot, nodeId) {
14550
+ const node = snapshot.project.nodes.find((item) => item.id === nodeId);
14551
+ if (!node) throw new FeedbackError(409, "This element is no longer in the current model.");
14552
+ const reference = "em://" + (snapshot.graphSidecar?.model.id ?? "event_model") + "/" + nodeId;
14553
+ const yaml = node.sourcePath && snapshot.files.get(node.sourcePath) || node.raw || node.fields || node.description || node.label;
14554
+ if (yaml.length > 64e3) throw new FeedbackError(413, "Selected source exceeds 64000 characters.");
14555
+ const related = snapshot.project.edges.filter((edge) => edge.source === nodeId || edge.target === nodeId);
14556
+ 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) })) });
14557
+ if (context.length > 128e3) throw new FeedbackError(413, "Connected context exceeds 128000 characters.");
14558
+ return { reference, sourcePath: node.sourcePath, yaml, context };
14559
+ }
14560
+ function batchRequest(input, receipt) {
14561
+ const first = input.items[0];
14562
+ 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");
14563
+ return {
14564
+ id: receipt.id,
14565
+ clientRequestId: input.clientBatchId,
14566
+ clientBatchId: input.clientBatchId,
14567
+ items: input.items,
14568
+ message,
14569
+ nodeId: first.nodeId,
14570
+ reference: first.reference,
14571
+ createdAt: receipt.createdAt
14572
+ };
14573
+ }
14574
+ var FeedbackSession = class {
14575
+ constructor(target) {
14576
+ this.target = target;
14577
+ this.current = readSnapshot(target);
14578
+ this.baseline = gitBaseline(this.current);
14579
+ }
14580
+ target;
14581
+ id = randomUUID();
14582
+ token = randomUUID();
14583
+ current;
14584
+ baseline;
14585
+ state = { status: "idle" };
14586
+ history = [];
14587
+ batchReceipts = /* @__PURE__ */ new Map();
14588
+ lastSeen;
14589
+ error;
14590
+ waiter;
14591
+ polling = false;
14592
+ generation = 0;
14593
+ refresh() {
14594
+ try {
14595
+ this.current = readSnapshot(this.target);
14596
+ this.error = void 0;
14597
+ return this.current;
14598
+ } catch (error) {
14599
+ this.error = error instanceof Error ? error.message : String(error);
14600
+ throw new FeedbackError(422, this.error);
14601
+ }
14602
+ }
14603
+ archive(request) {
14604
+ this.history = [...this.history.filter((entry) => entry.id !== request.id), { ...request }].slice(-20);
14605
+ }
14606
+ snapshot(view) {
14607
+ try {
14608
+ this.refresh();
14609
+ } catch {
14610
+ }
14611
+ let displayed = this.current;
14612
+ let project = displayed.project;
14613
+ let diff;
14614
+ if (view === "session") {
14615
+ const result = diffEventModelProjects(this.baseline.project, project, { base: this.baseline.label, target: "Working tree (all edits)" });
14616
+ project = result.project;
14617
+ diff = result.diff;
14618
+ } else if (view === "turn" && (this.state.status === "working" || this.state.status === "completed")) {
14619
+ const after = this.state.status === "completed" ? this.state.after : this.current;
14620
+ displayed = after;
14621
+ const result = diffEventModelProjects(this.state.before.project, after.project, { base: "Request " + this.state.context.request.id + " start", target: this.state.status === "completed" ? "Request reply (all edits)" : "Working tree (all edits)" });
14622
+ project = result.project;
14623
+ diff = result.diff;
14624
+ }
14625
+ const currentIds = uniqueNodeIds(this.current.project);
14626
+ const currentNodeIds = Object.fromEntries(project.nodes.flatMap((node) => {
14627
+ const id = currentIds.get(nodeIdentity(node));
14628
+ return id === void 0 || diff?.nodeStatus[node.id] === "removed" ? [] : [[node.id, id]];
14629
+ }));
14630
+ return {
14631
+ sessionId: this.id,
14632
+ token: this.token,
14633
+ revision: this.current.revision,
14634
+ currentNodeIds,
14635
+ project: { ...project, graphSidecar: displayed.graphSidecar },
14636
+ validation: displayed.validation,
14637
+ diff,
14638
+ baseline: { kind: this.baseline.kind, label: this.baseline.label },
14639
+ error: this.error,
14640
+ stale: Boolean(this.error),
14641
+ feedback: {
14642
+ status: this.state.status,
14643
+ request: "context" in this.state ? this.state.context?.request : void 0,
14644
+ history: this.history,
14645
+ agent: { connected: this.lastSeen !== void 0 && Date.now() - this.lastSeen < 6e4, lastSeen: this.lastSeen }
14646
+ }
14647
+ };
14648
+ }
14649
+ submit(body) {
14650
+ const clientRequestId = textField(body.clientRequestId, "clientRequestId", 100);
14651
+ const message = textField(body.message, "message", 4e3);
14652
+ const nodeId = textField(body.nodeId, "nodeId", 500);
14653
+ const revision = textField(body.revision, "revision", 100);
14654
+ if (this.batchReceipts.has(clientRequestId)) throw new FeedbackError(409, "Request ID already belongs to a batch.");
14655
+ const active = "context" in this.state ? this.state.context?.request : void 0;
14656
+ const known = active?.clientRequestId === clientRequestId ? active : this.history.find((item) => item.clientRequestId === clientRequestId);
14657
+ if (known?.clientRequestId === clientRequestId) {
14658
+ if (known.message !== message || known.nodeId !== nodeId) throw new FeedbackError(409, "Request ID already used with different content.");
14659
+ return known;
14660
+ }
14661
+ if (this.state.status === "stopped") throw new FeedbackError(409, "Feedback is stopped.");
14662
+ if (this.state.status === "working" || this.state.status === "queued") throw new FeedbackError(409, "Finish or stop the active request first.");
14663
+ const snapshot = this.refresh();
14664
+ if (revision !== snapshot.revision) throw new FeedbackError(409, "Model changed. Refresh and select the element again.");
14665
+ const captured = captureNode(snapshot, nodeId);
14666
+ const request = {
14667
+ id: randomUUID(),
14668
+ clientRequestId,
14669
+ message,
14670
+ nodeId,
14671
+ createdAt: Date.now(),
14672
+ reference: captured.reference
14673
+ };
14674
+ this.state = { status: "queued", context: { request, revision, ...captured } };
14675
+ this.waiter?.();
14676
+ return request;
14677
+ }
14678
+ submitBatch(body) {
14679
+ const input = parseBatch(body);
14680
+ const fingerprint = createHash("sha256").update(JSON.stringify(input)).digest("hex");
14681
+ const active = "context" in this.state ? this.state.context?.request : void 0;
14682
+ const receipt = this.batchReceipts.get(input.clientBatchId);
14683
+ if (receipt) {
14684
+ if (receipt.fingerprint !== fingerprint) throw new FeedbackError(409, "Batch ID already used with different content.");
14685
+ return active?.id === receipt.id ? active : this.history.find((item) => item.id === receipt.id) ?? batchRequest(input, receipt);
14686
+ }
14687
+ if (active?.clientRequestId === input.clientBatchId || this.history.some((item) => item.clientRequestId === input.clientBatchId)) {
14688
+ throw new FeedbackError(409, "Batch ID already belongs to a request.");
14689
+ }
14690
+ if (this.state.status === "stopped") throw new FeedbackError(409, "Feedback is stopped.");
14691
+ if (this.state.status === "working" || this.state.status === "queued") throw new FeedbackError(409, "Finish or stop the active request first.");
14692
+ if (this.batchReceipts.size >= 1e3) throw new FeedbackError(429, "This session has accepted 1000 batches. Restart the project server before sending another batch.");
14693
+ const snapshot = this.refresh();
14694
+ const currentIds = uniqueNodeIds(snapshot.project);
14695
+ const items = input.items.map((item) => {
14696
+ if (item.revision !== snapshot.revision) throw new FeedbackError(409, "Model changed. Review and queue each element again.");
14697
+ const captured = captureNode(snapshot, item.nodeId);
14698
+ if (item.reference !== captured.reference) throw new FeedbackError(409, "An item reference does not match its current node.");
14699
+ const node = snapshot.project.nodes.find((candidate) => candidate.id === item.nodeId);
14700
+ if (currentIds.get(nodeIdentity(node)) !== node.id) throw new FeedbackError(409, "An item is ambiguous. Select a uniquely named current node.");
14701
+ return { ...item, ...captured };
14702
+ });
14703
+ const context = JSON.stringify({ kind: "batch", revision: snapshot.revision, items });
14704
+ if (Buffer.byteLength(context) > 1024 * 1024) throw new FeedbackError(413, "Batch captured context exceeds 1 MiB.");
14705
+ const accepted = { fingerprint, id: randomUUID(), createdAt: Date.now() };
14706
+ const request = batchRequest(input, accepted);
14707
+ const yaml = items.map((item, index) => "# Item " + (index + 1) + " " + item.reference + "\n" + item.yaml).join("\n\n");
14708
+ this.batchReceipts.set(input.clientBatchId, accepted);
14709
+ this.state = { status: "queued", context: { request, items, revision: snapshot.revision, yaml, context } };
14710
+ this.waiter?.();
14711
+ return request;
14712
+ }
14713
+ async poll(agent, signal, waitMs = 25e3) {
14714
+ const agentId = textField(agent, "agent", 100);
14715
+ if (this.polling) throw new FeedbackError(409, "Only one poll may wait at a time.");
14716
+ if (this.state.status === "working" && this.state.agentId !== agentId) throw new FeedbackError(409, "Another agent owns the active request.");
14717
+ this.polling = true;
14718
+ const generation = this.generation;
14719
+ this.lastSeen = Date.now();
14720
+ try {
14721
+ if (this.state.status !== "queued" && this.state.status !== "working" && this.state.status !== "stopped") {
14722
+ await new Promise((resolve) => {
14723
+ const finish = () => {
14724
+ clearTimeout(timer);
14725
+ signal?.removeEventListener("abort", finish);
14726
+ this.waiter = void 0;
14727
+ resolve();
14728
+ };
14729
+ const timer = setTimeout(finish, Math.min(25e3, Math.max(0, waitMs)));
14730
+ this.waiter = finish;
14731
+ signal?.addEventListener("abort", finish, { once: true });
14732
+ if (signal?.aborted) finish();
14733
+ });
14734
+ }
14735
+ if (signal?.aborted) return { status: "disconnected", next_step: "Reconnect only if this session is still wanted." };
14736
+ this.lastSeen = Date.now();
14737
+ if (generation !== this.generation || this.state.status === "stopped") return { status: "stopped", next_step: "Stop polling and stop editing. The server cannot stop your process." };
14738
+ if (this.state.status === "queued") {
14739
+ const before = this.refresh();
14740
+ if (before.revision !== this.state.context.revision) {
14741
+ 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." });
14742
+ this.state = { status: "idle" };
14743
+ throw new FeedbackError(409, "Model changed before claim. Request cancelled.");
14744
+ }
14745
+ this.state.context.request.agentId = agentId;
14746
+ this.state = { status: "working", context: this.state.context, agentId, before };
14747
+ }
14748
+ if (this.state.status === "working") {
14749
+ 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." };
14750
+ }
14751
+ return { status: "timeout", next_step: "Run emviz poll again with the same --url, --token, and --agent. Wait in the foreground." };
14752
+ } finally {
14753
+ this.polling = false;
14754
+ }
14755
+ }
14756
+ reply(body) {
14757
+ const id = textField(body.id, "id", 100);
14758
+ const agentId = textField(body.agent, "agent", 100);
14759
+ const reply = textField(body.reply, "reply", 8e3);
14760
+ const recorded = this.history.find((entry) => entry.id === id && entry.agentId === agentId && entry.reply !== void 0);
14761
+ if (recorded) {
14762
+ if (recorded.reply !== reply) throw new FeedbackError(409, "Reply already recorded with different content.");
14763
+ return recorded;
14764
+ }
14765
+ if (this.state.status !== "working" || this.state.context.request.id !== id || this.state.agentId !== agentId) throw new FeedbackError(409, "No matching request owned by this agent.");
14766
+ const after = this.refresh();
14767
+ const request = { ...this.state.context.request, reply };
14768
+ this.state = { ...this.state, status: "completed", context: { ...this.state.context, request }, after };
14769
+ this.lastSeen = Date.now();
14770
+ this.archive(request);
14771
+ return request;
14772
+ }
14773
+ stop() {
14774
+ this.generation += 1;
14775
+ const context = "context" in this.state ? this.state.context : void 0;
14776
+ if (context) this.archive(context.request);
14777
+ this.state = { status: "stopped", context };
14778
+ this.lastSeen = void 0;
14779
+ this.waiter?.();
14780
+ }
14781
+ start() {
14782
+ if (this.state.status !== "stopped") throw new FeedbackError(409, "Session is already running.");
14783
+ this.state = { status: "idle" };
14784
+ }
14785
+ };
14786
+ async function readJson(req, maxBytes = 32768) {
14787
+ if (req.headers["content-type"]?.split(";")[0] !== "application/json") throw new FeedbackError(415, "Use application/json.");
14788
+ const content = await new Promise((resolve, reject) => {
14789
+ let size = 0;
14790
+ let failed = false;
14791
+ const parts = [];
14792
+ req.on("data", (chunk) => {
14793
+ if (failed) return;
14794
+ size += chunk.length;
14795
+ if (size > maxBytes) {
14796
+ failed = true;
14797
+ parts.length = 0;
14798
+ reject(new FeedbackError(413, "Request exceeds " + maxBytes / 1024 + " KiB."));
14799
+ } else parts.push(chunk);
14800
+ });
14801
+ req.once("end", () => {
14802
+ if (!failed) resolve(Buffer.concat(parts));
14803
+ });
14804
+ req.once("error", reject);
14805
+ req.once("aborted", () => reject(new FeedbackError(400, "Request disconnected.")));
14806
+ });
14807
+ try {
14808
+ const value = JSON.parse(content.toString("utf8"));
14809
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error();
14810
+ return value;
14811
+ } catch {
14812
+ throw new FeedbackError(400, "Expected a JSON object.");
14813
+ }
14814
+ }
14815
+ async function handleFeedback(req, res, session, close) {
14816
+ const url = new URL(req.url ?? "/", "http://localhost");
14817
+ if (url.pathname !== "/api/session" && !url.pathname.startsWith("/api/feedback/")) return false;
14818
+ const send = (value) => {
14819
+ res.setHeader("content-type", "application/json; charset=utf-8");
14820
+ res.setHeader("cache-control", "no-store");
14821
+ res.end(JSON.stringify(value));
14822
+ };
14823
+ try {
14824
+ if (url.pathname === "/api/session" && req.method === "GET") {
14825
+ const view = url.searchParams.get("view") ?? "current";
14826
+ if (!["current", "session", "turn"].includes(view)) throw new FeedbackError(400, "Unknown view.");
14827
+ send(session.snapshot(view));
14828
+ return true;
14829
+ }
14830
+ if (!validToken(req, session.token)) throw new FeedbackError(403, "Invalid session token.");
14831
+ if (url.pathname === "/api/feedback/poll" && req.method === "GET") {
14832
+ const controller = new AbortController();
14833
+ res.on("close", () => controller.abort());
14834
+ const result = await session.poll(url.searchParams.get("agent"), controller.signal);
14835
+ if (!res.destroyed) send(result);
14836
+ return true;
14837
+ }
14838
+ if (req.method !== "POST") throw new FeedbackError(405, "Method not allowed.");
14839
+ const body = await readJson(req, url.pathname === "/api/feedback/batch" ? 128 * 1024 : 32768);
14840
+ switch (url.pathname) {
14841
+ case "/api/feedback/request":
14842
+ send(session.submit(body));
14843
+ break;
14844
+ case "/api/feedback/batch":
14845
+ send(session.submitBatch(body));
14846
+ break;
14847
+ case "/api/feedback/reply":
14848
+ send({ request: session.reply(body), next_step: "Run emviz poll with the same connection options." });
14849
+ break;
14850
+ case "/api/feedback/stop":
14851
+ session.stop();
14852
+ send({ status: "stopped" });
14853
+ break;
14854
+ case "/api/feedback/start":
14855
+ session.start();
14856
+ send({ status: "idle" });
14857
+ break;
14858
+ case "/api/feedback/close":
14859
+ session.stop();
14860
+ send({ status: "closed" });
14861
+ close();
14862
+ break;
14863
+ default:
14864
+ throw new FeedbackError(404, "Unknown feedback endpoint.");
14865
+ }
14866
+ } catch (error) {
14867
+ if (!res.destroyed) {
14868
+ res.statusCode = error instanceof FeedbackError ? error.status : 500;
14869
+ send({ error: error instanceof Error ? error.message : String(error) });
14870
+ }
14871
+ }
14872
+ return true;
14873
+ }
14874
+
14875
+ // src/agent-cli.ts
14876
+ import { spawn } from "node:child_process";
14877
+ function parseConnection(values) {
14878
+ const options = /* @__PURE__ */ new Map();
14879
+ const positional = [];
14880
+ for (let index = 0; index < values.length; index++) {
14881
+ const value = values[index];
14882
+ if (value.startsWith("--")) {
14883
+ if (!["--url", "--token", "--agent"].includes(value) || !values[index + 1]) throw new Error("Unknown or incomplete option: " + value);
14884
+ options.set(value, values[++index]);
14885
+ } else positional.push(value);
14886
+ }
14887
+ const url = new URL(options.get("--url") ?? "");
14888
+ 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.");
14889
+ if (url.hostname !== "localhost") parseHost(url.hostname);
14890
+ const token = options.get("--token");
14891
+ if (!token) throw new Error("--token is required. Use the token printed by emviz open.");
14892
+ return { url, token, agent: options.get("--agent"), positional };
14893
+ }
14894
+ async function runAgentCommand(command, values) {
14895
+ const connection = parseConnection(values);
14896
+ if ((command === "poll" || command === "reply") && !connection.agent) throw new Error("--agent is required. Reuse one unique ID throughout the session.");
14897
+ const route = command === "poll" ? "/api/feedback/poll?agent=" + encodeURIComponent(connection.agent) : "/api/feedback/" + command;
14898
+ const body = command === "reply" ? { id: connection.positional[0], reply: connection.positional[1], agent: connection.agent } : {};
14899
+ if (command === "reply" && connection.positional.length !== 2) throw new Error("Usage: emviz reply <request-id> <text> --url <url> --token <token> --agent <id>");
14900
+ if (command !== "reply" && connection.positional.length) throw new Error("Unexpected positional argument.");
14901
+ const response = await fetch(new URL(route, connection.url), {
14902
+ method: command === "poll" ? "GET" : "POST",
14903
+ headers: { "X-Emviz-Token": connection.token, "Content-Type": "application/json" },
14904
+ body: command === "poll" ? void 0 : JSON.stringify(body),
14905
+ signal: AbortSignal.timeout(3e4),
14906
+ redirect: "error"
14907
+ });
14908
+ const result = await response.json();
14909
+ console.log(JSON.stringify(result));
14910
+ if (!response.ok) process.exitCode = 1;
14911
+ }
14912
+ async function openProject(entry, target, host = "127.0.0.1") {
14913
+ const address = parseHost(host);
14914
+ const child = spawn(process.execPath, [entry, "serve", target, "--host", address], { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
14915
+ await new Promise((resolve, reject) => {
14916
+ const timer = setTimeout(() => {
14917
+ child.kill();
14918
+ reject(new Error("Project server did not become ready within 15 seconds."));
14919
+ }, 15e3);
14920
+ child.once("error", (error) => {
14921
+ clearTimeout(timer);
14922
+ reject(error);
14923
+ });
14924
+ child.once("exit", (code) => {
14925
+ clearTimeout(timer);
14926
+ reject(new Error("Project server exited before readiness (" + code + "). Run emviz <project> in the foreground for diagnostics."));
14927
+ });
14928
+ child.once("message", (message) => {
14929
+ if (!message || typeof message !== "object" || !("url" in message) || !("token" in message)) return;
14930
+ clearTimeout(timer);
14931
+ console.log(JSON.stringify(message));
14932
+ child.disconnect();
14933
+ child.unref();
14934
+ resolve();
14935
+ });
14936
+ });
14937
+ }
14938
+
14004
14939
  // src/index.ts
14005
- var args = process.argv.slice(2);
14006
- var command = args[0];
14007
14940
  function resolveTarget(value) {
14008
- return path5.resolve(process.cwd(), value ?? ".");
14941
+ return path7.resolve(process.cwd(), value ?? ".");
14009
14942
  }
14010
14943
  function sendJson(res, value) {
14011
14944
  res.setHeader("content-type", "application/json; charset=utf-8");
@@ -14016,16 +14949,9 @@ function sendText(res, statusCode, body) {
14016
14949
  res.setHeader("content-type", "text/plain; charset=utf-8");
14017
14950
  res.end(body);
14018
14951
  }
14019
- function loadApiModel(targetDir) {
14020
- const project = loadEventModelProject(targetDir);
14021
- return {
14022
- ...project,
14023
- graphSidecar: readGraphSidecar(project.root)
14024
- };
14025
- }
14026
14952
  function isGitRef(value) {
14027
14953
  try {
14028
- execFileSync("git", ["rev-parse", "--verify", `${value}^{commit}`], {
14954
+ execFileSync3("git", ["rev-parse", "--verify", `${value}^{commit}`], {
14029
14955
  cwd: process.cwd(),
14030
14956
  stdio: "ignore"
14031
14957
  });
@@ -14034,35 +14960,16 @@ function isGitRef(value) {
14034
14960
  return false;
14035
14961
  }
14036
14962
  }
14037
- function materializeGitRef(ref) {
14038
- const tempRoot = fs5.mkdtempSync(path5.join(os.tmpdir(), "emviz-diff-"));
14039
- const files = execFileSync("git", ["ls-tree", "-r", "--name-only", ref, "--", ".event-modeling", "event-model"], {
14040
- cwd: process.cwd(),
14041
- encoding: "utf8"
14042
- }).split("\n").filter(Boolean);
14043
- if (files.length === 0) throw new Error(`Git ref "${ref}" does not contain .event-modeling or event-model files.`);
14044
- for (const file of files) {
14045
- const content = execFileSync("git", ["show", `${ref}:${file}`], {
14046
- cwd: process.cwd(),
14047
- encoding: "utf8",
14048
- maxBuffer: 20 * 1024 * 1024
14049
- });
14050
- const outputPath = path5.join(tempRoot, file);
14051
- fs5.mkdirSync(path5.dirname(outputPath), { recursive: true });
14052
- fs5.writeFileSync(outputPath, content);
14053
- }
14054
- return tempRoot;
14055
- }
14056
14963
  function loadDiffSource(value, fallback) {
14057
14964
  const raw = value ?? fallback;
14058
- const resolved = path5.resolve(process.cwd(), raw);
14059
- if (fs5.existsSync(resolved)) {
14060
- if (fs5.statSync(resolved).isFile()) {
14965
+ const resolved = path7.resolve(process.cwd(), raw);
14966
+ if (fs7.existsSync(resolved)) {
14967
+ if (fs7.statSync(resolved).isFile()) {
14061
14968
  throw new Error(`Diff source must be an event-modeling project directory, not a file: ${raw}`);
14062
14969
  }
14063
14970
  return {
14064
14971
  project: loadEventModelProject(resolved),
14065
- label: path5.relative(process.cwd(), resolved) || "."
14972
+ label: path7.relative(process.cwd(), resolved) || "."
14066
14973
  };
14067
14974
  }
14068
14975
  if (isGitRef(raw)) {
@@ -14114,7 +15021,7 @@ function loadDiffServerState(baseValue, targetValue) {
14114
15021
  };
14115
15022
  }
14116
15023
  function printSyncResult(result) {
14117
- console.log(`Wrote ${path5.relative(process.cwd(), result.path)}`);
15024
+ console.log(`Wrote ${path7.relative(process.cwd(), result.path)}`);
14118
15025
  console.log(`Added: ${result.added.length}`);
14119
15026
  console.log(`Preserved: ${result.preserved.length}`);
14120
15027
  console.log(`Stale: ${result.stale.length}`);
@@ -14124,12 +15031,6 @@ async function runSync(targetDir) {
14124
15031
  const result = writeGraphSidecar(project);
14125
15032
  printSyncResult(result);
14126
15033
  }
14127
- function syncMissingGraphSidecar(targetDir) {
14128
- const project = loadEventModelProject(targetDir);
14129
- if (readGraphSidecar(project.root)) return;
14130
- console.log("Missing .event-modeling/graph.json; running initial sync...");
14131
- printSyncResult(writeGraphSidecar(project));
14132
- }
14133
15034
  var contentTypes = {
14134
15035
  ".css": "text/css; charset=utf-8",
14135
15036
  ".html": "text/html; charset=utf-8",
@@ -14140,15 +15041,15 @@ var contentTypes = {
14140
15041
  };
14141
15042
  function safeResolve(root, requestPath) {
14142
15043
  const decodedPath = decodeURIComponent(requestPath);
14143
- const resolved = path5.resolve(root, `.${decodedPath}`);
14144
- const relative = path5.relative(root, resolved);
14145
- if (relative.startsWith("..") || path5.isAbsolute(relative)) return void 0;
15044
+ const resolved = path7.resolve(root, `.${decodedPath}`);
15045
+ const relative = path7.relative(root, resolved);
15046
+ if (relative.startsWith("..") || path7.isAbsolute(relative)) return void 0;
14146
15047
  return resolved;
14147
15048
  }
14148
15049
  function serveFile(res, filePath) {
14149
- const stream = fs5.createReadStream(filePath);
15050
+ const stream = fs7.createReadStream(filePath);
14150
15051
  stream.on("error", () => sendText(res, 500, "Failed to read file"));
14151
- res.setHeader("content-type", contentTypes[path5.extname(filePath)] ?? "application/octet-stream");
15052
+ res.setHeader("content-type", contentTypes[path7.extname(filePath)] ?? "application/octet-stream");
14152
15053
  stream.pipe(res);
14153
15054
  }
14154
15055
  function serveApp(req, res, appRoot) {
@@ -14159,7 +15060,7 @@ function serveApp(req, res, appRoot) {
14159
15060
  sendText(res, 403, "Forbidden");
14160
15061
  return;
14161
15062
  }
14162
- if (fs5.existsSync(filePath) && fs5.statSync(filePath).isFile()) {
15063
+ if (fs7.existsSync(filePath) && fs7.statSync(filePath).isFile()) {
14163
15064
  serveFile(res, filePath);
14164
15065
  return;
14165
15066
  }
@@ -14167,9 +15068,9 @@ function serveApp(req, res, appRoot) {
14167
15068
  sendText(res, 404, "Not found");
14168
15069
  return;
14169
15070
  }
14170
- serveFile(res, path5.join(appRoot, "index.html"));
15071
+ serveFile(res, path7.join(appRoot, "index.html"));
14171
15072
  }
14172
- function listenWithFallback(server, port) {
15073
+ function listenWithFallback(server, port, host) {
14173
15074
  return new Promise((resolve, reject) => {
14174
15075
  const tryListen = (nextPort) => {
14175
15076
  server.once("error", (error) => {
@@ -14180,53 +15081,110 @@ function listenWithFallback(server, port) {
14180
15081
  }
14181
15082
  reject(error);
14182
15083
  });
14183
- server.listen(nextPort, "127.0.0.1", () => {
15084
+ server.listen(nextPort, host, () => {
14184
15085
  resolve(server.address().port);
14185
15086
  });
14186
15087
  };
14187
15088
  tryListen(port);
14188
15089
  });
14189
15090
  }
14190
- async function runServer(targetDir, diffState) {
14191
- if (targetDir) syncMissingGraphSidecar(targetDir);
14192
- const appRoot = path5.resolve(path5.dirname(fileURLToPath(import.meta.url)), "app");
15091
+ async function runServer(host, targetDir, diffState) {
15092
+ if (targetDir) {
15093
+ const initial = readSnapshot(targetDir);
15094
+ if (!initial.graphSidecar) {
15095
+ console.log("Missing .event-modeling/graph.json; running initial sync...");
15096
+ printSyncResult(writeGraphSidecar(initial.project));
15097
+ }
15098
+ }
15099
+ const appRoot = path7.resolve(path7.dirname(fileURLToPath(import.meta.url)), "app");
15100
+ const feedback = targetDir ? new FeedbackSession(targetDir) : void 0;
15101
+ const token = feedback?.token ?? randomUUID2();
15102
+ let listeningPort = 0;
14193
15103
  const server = http.createServer((req, res) => {
14194
- const url = new URL(req.url ?? "/", "http://localhost");
14195
- if (diffState && url.pathname === "/api/model") {
15104
+ void respond(req, res).catch((error) => {
15105
+ if (!res.headersSent) sendText(res, 500, error instanceof Error ? error.message : String(error));
15106
+ else res.end();
15107
+ });
15108
+ });
15109
+ server.requestTimeout = 1e4;
15110
+ const close = () => {
15111
+ feedback?.stop();
15112
+ server.close();
15113
+ server.closeIdleConnections();
15114
+ const timer = setTimeout(() => server.closeAllConnections(), 1e3);
15115
+ timer.unref();
15116
+ };
15117
+ const respond = async (req, res) => {
15118
+ res.setHeader("cache-control", "no-store");
15119
+ res.setHeader("referrer-policy", "no-referrer");
15120
+ if (!trustedRequest(req, listeningPort, host)) {
15121
+ sendText(res, 403, "Forbidden Host or Origin");
15122
+ return;
15123
+ }
15124
+ const url2 = new URL(req.url ?? "/", serverOrigin(host, listeningPort));
15125
+ if (!apiRequestAuthorized(req, url2.pathname, host, token)) {
15126
+ res.statusCode = 403;
15127
+ sendJson(res, { error: "Invalid session token. Open the complete viewerUrl printed by emviz in this browser." });
15128
+ return;
15129
+ }
15130
+ if (feedback && await handleFeedback(req, res, feedback, close)) return;
15131
+ if (req.method !== "GET" && req.method !== "HEAD") {
15132
+ sendText(res, 405, "Method not allowed");
15133
+ return;
15134
+ }
15135
+ if (diffState && url2.pathname === "/api/model") {
14196
15136
  sendJson(res, diffState.model);
14197
15137
  return;
14198
15138
  }
14199
- if (diffState && url.pathname === "/api/diff") {
15139
+ if (diffState && url2.pathname === "/api/diff") {
14200
15140
  sendJson(res, diffState.diff);
14201
15141
  return;
14202
15142
  }
14203
- if (diffState && url.pathname === "/api/validation") {
15143
+ if (diffState && url2.pathname === "/api/validation") {
14204
15144
  sendJson(res, diffState.validation);
14205
15145
  return;
14206
15146
  }
14207
- if (targetDir && url.pathname === "/api/model") {
15147
+ if (targetDir && url2.pathname === "/api/model") {
14208
15148
  try {
14209
- sendJson(res, loadApiModel(targetDir));
15149
+ const snapshot = feedback.snapshot("current");
15150
+ if (snapshot.stale) res.statusCode = 422;
15151
+ sendJson(res, snapshot.project);
14210
15152
  } catch (error) {
14211
15153
  res.statusCode = 500;
14212
15154
  sendJson(res, { error: error instanceof Error ? error.message : String(error) });
14213
15155
  }
14214
15156
  return;
14215
15157
  }
14216
- if (targetDir && url.pathname === "/api/validation") {
15158
+ if (targetDir && url2.pathname === "/api/validation") {
14217
15159
  try {
14218
- const project = loadEventModelProject(targetDir);
14219
- sendJson(res, validateEventModelProject(project));
15160
+ const snapshot = feedback.snapshot("current");
15161
+ if (snapshot.stale) res.statusCode = 422;
15162
+ sendJson(res, snapshot.validation);
14220
15163
  } catch (error) {
14221
15164
  res.statusCode = 500;
14222
15165
  sendJson(res, { error: error instanceof Error ? error.message : String(error) });
14223
15166
  }
14224
15167
  return;
14225
15168
  }
15169
+ if (url2.pathname.startsWith("/api/")) {
15170
+ sendText(res, 404, "Not found");
15171
+ return;
15172
+ }
14226
15173
  serveApp(req, res, appRoot);
14227
- });
14228
- const port = await listenWithFallback(server, 5173);
14229
- console.log(` \u279C Local: http://localhost:${port}/`);
15174
+ };
15175
+ const port = await listenWithFallback(server, 5173, host);
15176
+ listeningPort = port;
15177
+ const url = serverOrigin(host, port) + "/";
15178
+ const viewerUrl = isLoopbackHost(host) ? url : url + "#token=" + encodeURIComponent(token);
15179
+ if (feedback) {
15180
+ 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.` };
15181
+ if (process.send) process.send(ready);
15182
+ else console.log(JSON.stringify(ready));
15183
+ }
15184
+ process.once("SIGTERM", close);
15185
+ process.once("SIGINT", close);
15186
+ console.log(` \u279C ${isLoopbackHost(host) ? "Local" : "Remote"}: ${viewerUrl}`);
15187
+ 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.");
14230
15188
  if (diffState) {
14231
15189
  console.log(`Diff: ${diffState.diff.base.label} -> ${diffState.diff.target.label}`);
14232
15190
  } else {
@@ -14234,6 +15192,24 @@ async function runServer(targetDir, diffState) {
14234
15192
  }
14235
15193
  }
14236
15194
  async function main() {
15195
+ const rawArgs = process.argv.slice(2);
15196
+ if (["poll", "reply", "stop", "close"].includes(rawArgs[0])) {
15197
+ await runAgentCommand(rawArgs[0], rawArgs.slice(1));
15198
+ return;
15199
+ }
15200
+ const { host, args, provided } = parseHostArgs(rawArgs);
15201
+ const command = args[0];
15202
+ if (provided && ["sync", "init", "poll", "reply", "stop", "close"].includes(command)) throw new Error("--host is only supported by server commands.");
15203
+ if (command === "open") {
15204
+ if (args.length > 2) throw new Error("Usage: emviz open [project-dir] [--host <ip>]");
15205
+ await openProject(fileURLToPath(import.meta.url), resolveTarget(args[1]), host);
15206
+ return;
15207
+ }
15208
+ if (command === "serve") {
15209
+ if (args.length > 2) throw new Error("Usage: emviz serve [project-dir] [--host <ip>]");
15210
+ await runServer(host, resolveTarget(args[1]));
15211
+ return;
15212
+ }
14237
15213
  if (command === "sync") {
14238
15214
  await runSync(resolveTarget(args[1]));
14239
15215
  return;
@@ -14246,18 +15222,26 @@ async function main() {
14246
15222
  if (command === "diff") {
14247
15223
  const diffArgs = parseDiffArgs(args.slice(1));
14248
15224
  const diffState = loadDiffServerState(diffArgs.base, diffArgs.target);
14249
- await runServer(void 0, diffState);
15225
+ await runServer(host, void 0, diffState);
14250
15226
  return;
14251
15227
  }
14252
15228
  if (command === "--help" || command === "-h") {
14253
- console.log("Usage: emviz [project-dir]");
15229
+ console.log("Usage: emviz [project-dir] [--host <ip>]");
15230
+ console.log(" emviz open [project-dir] [--host <ip>]");
15231
+ console.log(" emviz serve [project-dir] [--host <ip>]");
15232
+ console.log(" emviz poll --url <url> --token <token> --agent <id>");
15233
+ console.log(" emviz reply <request-id> <text> --url <url> --token <token> --agent <id>");
15234
+ console.log(" emviz stop|close --url <url> --token <token>");
14254
15235
  console.log(" emviz sync [project-dir]");
14255
- console.log(" emviz diff [base-ref-or-dir] [project-dir]");
14256
- console.log(" emviz diff --from <base-ref-or-dir> --to <project-dir>");
15236
+ console.log(" emviz diff [base-ref-or-dir] [project-dir] [--host <ip>]");
15237
+ console.log(" emviz diff --from <base-ref-or-dir> --to <project-dir> [--host <ip>]");
14257
15238
  console.log(" emviz init [project-dir] (deprecated alias for sync)");
15239
+ console.log("Default host: 127.0.0.1. Use a concrete IPv4 or IPv6 interface address. DNS names and wildcard binds are rejected.");
15240
+ console.log("Remote browser access uses the printed viewerUrl. Agent commands use url and --token.");
14258
15241
  return;
14259
15242
  }
14260
- await runServer(command ? resolveTarget(command) : void 0);
15243
+ if (args.length > 1 || command?.startsWith("-")) throw new Error("Usage: emviz [project-dir] [--host <ip>]");
15244
+ await runServer(host, command ? resolveTarget(command) : void 0);
14261
15245
  }
14262
15246
  main().catch((error) => {
14263
15247
  console.error(error instanceof Error ? error.message : error);