agentface 0.10.1 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/agentface.mjs +1140 -617
  2. package/package.json +1 -1
@@ -3128,14 +3128,14 @@ var require_lib = __commonJS({
3128
3128
  super.checkParams(node2, false, true);
3129
3129
  this.scope.exit();
3130
3130
  }
3131
- forwardNoArrowParamsConversionAt(node2, parse5) {
3131
+ forwardNoArrowParamsConversionAt(node2, parse6) {
3132
3132
  let result2;
3133
3133
  if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node2.start))) {
3134
3134
  this.state.noArrowParamsConversionAt.push(this.state.start);
3135
- result2 = parse5();
3135
+ result2 = parse6();
3136
3136
  this.state.noArrowParamsConversionAt.pop();
3137
3137
  } else {
3138
- result2 = parse5();
3138
+ result2 = parse6();
3139
3139
  }
3140
3140
  return result2;
3141
3141
  }
@@ -13053,8 +13053,8 @@ var require_lib = __commonJS({
13053
13053
  this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
13054
13054
  if (!res) return;
13055
13055
  const startPos = this.offsetToSourcePos(startLoc.index);
13056
- const parse5 = () => res.returnType && this.tsIsArrowReturnTypeRestrictedAt(startPos) ? this.tsParseWithDeferredArrowErrors(() => super.parseArrowExpression(res, null, true)) : super.parseArrowExpression(res, null, true);
13057
- return this.tsIsArrowReturnTypeRestrictedAt(startPos) ? this.tsParseWithRestrictedArrowReturnType(parse5, this.hasPlugin("jsx") || this.state.tsArrowReturnTypeAllowed) : parse5();
13056
+ const parse6 = () => res.returnType && this.tsIsArrowReturnTypeRestrictedAt(startPos) ? this.tsParseWithDeferredArrowErrors(() => super.parseArrowExpression(res, null, true)) : super.parseArrowExpression(res, null, true);
13057
+ return this.tsIsArrowReturnTypeRestrictedAt(startPos) ? this.tsParseWithRestrictedArrowReturnType(parse6, this.hasPlugin("jsx") || this.state.tsArrowReturnTypeAllowed) : parse6();
13058
13058
  }
13059
13059
  tsParseTypeArgumentsInExpression() {
13060
13060
  if (this.reScan_lt() !== 47) return;
@@ -13598,12 +13598,12 @@ var require_lib = __commonJS({
13598
13598
  this.state.tsArrowReturnTypeAllowed = allowsReturnType;
13599
13599
  this.state.tsGenericArrowParams = genericParams;
13600
13600
  }
13601
- tsParseWithRestrictedArrowReturnType(parse5, allowsReturnType = false, genericParams = false) {
13601
+ tsParseWithRestrictedArrowReturnType(parse6, allowsReturnType = false, genericParams = false) {
13602
13602
  const oldAllowed = this.state.tsArrowReturnTypeAllowed;
13603
13603
  const oldGeneric = this.state.tsGenericArrowParams;
13604
13604
  const oldStart = this.state.tsArrowReturnTypeRestrictionAt;
13605
13605
  this.tsRestrictArrowReturnTypeAt(this.state.start, allowsReturnType, genericParams);
13606
- const result2 = parse5();
13606
+ const result2 = parse6();
13607
13607
  this.state.tsArrowReturnTypeRestrictionAt = oldStart;
13608
13608
  this.state.tsArrowReturnTypeAllowed = oldAllowed;
13609
13609
  this.state.tsGenericArrowParams = oldGeneric;
@@ -13780,11 +13780,11 @@ var require_lib = __commonJS({
13780
13780
  this.state.tsGenericArrowParams = oldGeneric;
13781
13781
  return node2;
13782
13782
  }
13783
- tsParseWithDeferredArrowErrors(parse5) {
13784
- if (this.optionFlags & 2048) return parse5();
13783
+ tsParseWithDeferredArrowErrors(parse6) {
13784
+ if (this.optionFlags & 2048) return parse6();
13785
13785
  this.optionFlags |= 2048;
13786
13786
  try {
13787
- return parse5();
13787
+ return parse6();
13788
13788
  } finally {
13789
13789
  this.optionFlags &= ~2048;
13790
13790
  }
@@ -13797,19 +13797,19 @@ var require_lib = __commonJS({
13797
13797
  tsParseMaybeArrowWithRestrictedReturnType(startPos, refExpressionErrors, afterLeftParse) {
13798
13798
  if (!this.noArrowAt.has(startPos)) {
13799
13799
  const allowsReturnType = this.state.tsArrowReturnTypeAllowed;
13800
- const parse5 = () => this.tsParseMaybeAssign(refExpressionErrors, afterLeftParse);
13800
+ const parse6 = () => this.tsParseMaybeAssign(refExpressionErrors, afterLeftParse);
13801
13801
  let state = this.state.clone();
13802
13802
  const {
13803
13803
  tokensLength
13804
13804
  } = state;
13805
13805
  this.tsArrowReturnTypeAt.delete(startPos);
13806
- let result2 = this.tryParse(parse5, state);
13806
+ let result2 = this.tryParse(parse6, state);
13807
13807
  const returnTypeStart = this.tsArrowReturnTypeAt.get(startPos);
13808
13808
  if (result2.thrown && returnTypeStart !== void 0 && !tsIsInvalidArrowParamsError(result2.error, returnTypeStart) && !(this.optionFlags & 2048)) {
13809
13809
  state = this.state.clone();
13810
13810
  this.optionFlags |= 2048;
13811
13811
  try {
13812
- result2 = this.tryParse(parse5, state);
13812
+ result2 = this.tryParse(parse6, state);
13813
13813
  } finally {
13814
13814
  this.optionFlags &= ~2048;
13815
13815
  }
@@ -14159,8 +14159,8 @@ var require_lib = __commonJS({
14159
14159
  const startPos = this.offsetToSourcePos(node2.start);
14160
14160
  if (this.tsIsArrowReturnTypeRestrictedAt(startPos)) {
14161
14161
  const genericParams = this.state.tsGenericArrowParams;
14162
- const parse5 = () => super.parseArrowExpression(node2, params, isAsync, trailingCommaLoc);
14163
- return this.tsParseWithRestrictedArrowReturnType(genericParams && node2.returnType ? () => this.tsParseWithDeferredArrowErrors(parse5) : parse5, this.state.tsArrowReturnTypeAllowed || !genericParams && tsHasUnambiguousArrowParams(params));
14162
+ const parse6 = () => super.parseArrowExpression(node2, params, isAsync, trailingCommaLoc);
14163
+ return this.tsParseWithRestrictedArrowReturnType(genericParams && node2.returnType ? () => this.tsParseWithDeferredArrowErrors(parse6) : parse6, this.state.tsArrowReturnTypeAllowed || !genericParams && tsHasUnambiguousArrowParams(params));
14164
14164
  }
14165
14165
  return super.parseArrowExpression(node2, params, isAsync, trailingCommaLoc);
14166
14166
  }
@@ -14940,7 +14940,7 @@ var require_lib = __commonJS({
14940
14940
  return result2;
14941
14941
  }
14942
14942
  };
14943
- function parse4(input, options) {
14943
+ function parse5(input, options) {
14944
14944
  var _options;
14945
14945
  if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
14946
14946
  options = Object.assign({}, options);
@@ -15027,7 +15027,7 @@ var require_lib = __commonJS({
15027
15027
  }
15028
15028
  return cls;
15029
15029
  }
15030
- exports.parse = parse4;
15030
+ exports.parse = parse5;
15031
15031
  exports.parseExpression = parseExpression;
15032
15032
  exports.tokTypes = tokTypes;
15033
15033
  }
@@ -15075,7 +15075,7 @@ var require_ms = __commonJS({
15075
15075
  options = options || {};
15076
15076
  var type = typeof val;
15077
15077
  if (type === "string" && val.length > 0) {
15078
- return parse4(val);
15078
+ return parse5(val);
15079
15079
  } else if (type === "number" && isFinite(val)) {
15080
15080
  return options.long ? fmtLong(val) : fmtShort(val);
15081
15081
  }
@@ -15083,7 +15083,7 @@ var require_ms = __commonJS({
15083
15083
  "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
15084
15084
  );
15085
15085
  };
15086
- function parse4(str) {
15086
+ function parse5(str) {
15087
15087
  str = String(str);
15088
15088
  if (str.length > 100) {
15089
15089
  return;
@@ -32701,18 +32701,18 @@ var require_trace_mapping_umd = __commonJS({
32701
32701
  state.lastNeedle = needle;
32702
32702
  return state.lastIndex = binarySearch(haystack, needle, low, high);
32703
32703
  }
32704
- function parse4(map) {
32704
+ function parse5(map) {
32705
32705
  return typeof map === "string" ? JSON.parse(map) : map;
32706
32706
  }
32707
32707
  var FlattenMap = function(map, mapUrl) {
32708
- const parsed = parse4(map);
32708
+ const parsed = parse5(map);
32709
32709
  if (!("sections" in parsed)) {
32710
32710
  return new TraceMap(parsed, mapUrl);
32711
32711
  }
32712
32712
  const mappings = [];
32713
32713
  const sources = [];
32714
32714
  const sourcesContent = [];
32715
- const names = [];
32715
+ const names2 = [];
32716
32716
  const ignoreList = [];
32717
32717
  recurse(
32718
32718
  parsed,
@@ -32720,7 +32720,7 @@ var require_trace_mapping_umd = __commonJS({
32720
32720
  mappings,
32721
32721
  sources,
32722
32722
  sourcesContent,
32723
- names,
32723
+ names2,
32724
32724
  ignoreList,
32725
32725
  0,
32726
32726
  0,
@@ -32730,7 +32730,7 @@ var require_trace_mapping_umd = __commonJS({
32730
32730
  const joined = {
32731
32731
  version: 3,
32732
32732
  file: parsed.file,
32733
- names,
32733
+ names: names2,
32734
32734
  sources,
32735
32735
  sourcesContent,
32736
32736
  mappings,
@@ -32738,7 +32738,7 @@ var require_trace_mapping_umd = __commonJS({
32738
32738
  };
32739
32739
  return presortedDecodedMap(joined);
32740
32740
  };
32741
- function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
32741
+ function recurse(input, mapUrl, mappings, sources, sourcesContent, names2, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
32742
32742
  const { sections } = input;
32743
32743
  for (let i = 0; i < sections.length; i++) {
32744
32744
  const { map, offset } = sections[i];
@@ -32759,7 +32759,7 @@ var require_trace_mapping_umd = __commonJS({
32759
32759
  mappings,
32760
32760
  sources,
32761
32761
  sourcesContent,
32762
- names,
32762
+ names2,
32763
32763
  ignoreList,
32764
32764
  lineOffset + offset.line,
32765
32765
  columnOffset + offset.column,
@@ -32768,16 +32768,16 @@ var require_trace_mapping_umd = __commonJS({
32768
32768
  );
32769
32769
  }
32770
32770
  }
32771
- function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
32772
- const parsed = parse4(input);
32771
+ function addSection(input, mapUrl, mappings, sources, sourcesContent, names2, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
32772
+ const parsed = parse5(input);
32773
32773
  if ("sections" in parsed) return recurse(...arguments);
32774
32774
  const map = new TraceMap(parsed, mapUrl);
32775
32775
  const sourcesOffset = sources.length;
32776
- const namesOffset = names.length;
32776
+ const namesOffset = names2.length;
32777
32777
  const decoded = decodedMappings(map);
32778
32778
  const { resolvedSources, sourcesContent: contents2, ignoreList: ignores } = map;
32779
32779
  append(sources, resolvedSources);
32780
- append(names, map.names);
32780
+ append(names2, map.names);
32781
32781
  if (contents2) append(sourcesContent, contents2);
32782
32782
  else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);
32783
32783
  if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset);
@@ -32819,11 +32819,11 @@ var require_trace_mapping_umd = __commonJS({
32819
32819
  constructor(map, mapUrl) {
32820
32820
  const isString = typeof map === "string";
32821
32821
  if (!isString && map._decodedMemo) return map;
32822
- const parsed = parse4(map);
32823
- const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
32822
+ const parsed = parse5(map);
32823
+ const { version, file, names: names2, sourceRoot, sources, sourcesContent } = parsed;
32824
32824
  this.version = version;
32825
32825
  this.file = file;
32826
- this.names = names || [];
32826
+ this.names = names2 || [];
32827
32827
  this.sourceRoot = sourceRoot;
32828
32828
  this.sources = sources;
32829
32829
  this.sourcesContent = sourcesContent;
@@ -32889,12 +32889,12 @@ var require_trace_mapping_umd = __commonJS({
32889
32889
  if (index === -1) return OMapping(null, null, null, null);
32890
32890
  const segment = segments[index];
32891
32891
  if (segment.length === 1) return OMapping(null, null, null, null);
32892
- const { names, resolvedSources } = map;
32892
+ const { names: names2, resolvedSources } = map;
32893
32893
  return OMapping(
32894
32894
  resolvedSources[segment[SOURCES_INDEX]],
32895
32895
  segment[SOURCE_LINE] + 1,
32896
32896
  segment[SOURCE_COLUMN],
32897
- segment.length === 5 ? names[segment[NAMES_INDEX]] : null
32897
+ segment.length === 5 ? names2[segment[NAMES_INDEX]] : null
32898
32898
  );
32899
32899
  }
32900
32900
  function generatedPositionFor(map, needle) {
@@ -32907,7 +32907,7 @@ var require_trace_mapping_umd = __commonJS({
32907
32907
  }
32908
32908
  function eachMapping(map, cb) {
32909
32909
  const decoded = decodedMappings(map);
32910
- const { names, resolvedSources } = map;
32910
+ const { names: names2, resolvedSources } = map;
32911
32911
  for (let i = 0; i < decoded.length; i++) {
32912
32912
  const line = decoded[i];
32913
32913
  for (let j = 0; j < line.length; j++) {
@@ -32923,7 +32923,7 @@ var require_trace_mapping_umd = __commonJS({
32923
32923
  originalLine = seg[2] + 1;
32924
32924
  originalColumn = seg[3];
32925
32925
  }
32926
- if (seg.length === 5) name = names[seg[4]];
32926
+ if (seg.length === 5) name = names2[seg[4]];
32927
32927
  cb({
32928
32928
  generatedLine,
32929
32929
  generatedColumn,
@@ -33217,7 +33217,7 @@ var require_gen_mapping_umd = __commonJS({
33217
33217
  _mappings: mappings,
33218
33218
  _sources: sources,
33219
33219
  _sourcesContent: sourcesContent,
33220
- _names: names,
33220
+ _names: names2,
33221
33221
  _ignoreList: ignoreList
33222
33222
  // _originalScopes: originalScopes,
33223
33223
  // _generatedRanges: generatedRanges,
@@ -33226,7 +33226,7 @@ var require_gen_mapping_umd = __commonJS({
33226
33226
  return {
33227
33227
  version: 3,
33228
33228
  file: map.file || void 0,
33229
- names: names.array,
33229
+ names: names2.array,
33230
33230
  sourceRoot: map.sourceRoot || void 0,
33231
33231
  sources: sources.array,
33232
33232
  sourcesContent,
@@ -33256,7 +33256,7 @@ var require_gen_mapping_umd = __commonJS({
33256
33256
  }
33257
33257
  function allMappings(map) {
33258
33258
  const out = [];
33259
- const { _mappings: mappings, _sources: sources, _names: names } = cast2(map);
33259
+ const { _mappings: mappings, _sources: sources, _names: names2 } = cast2(map);
33260
33260
  for (let i = 0; i < mappings.length; i++) {
33261
33261
  const line = mappings[i];
33262
33262
  for (let j = 0; j < line.length; j++) {
@@ -33268,7 +33268,7 @@ var require_gen_mapping_umd = __commonJS({
33268
33268
  if (seg.length !== 1) {
33269
33269
  source = sources.array[seg[SOURCES_INDEX]];
33270
33270
  original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };
33271
- if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];
33271
+ if (seg.length === 5) name = names2.array[seg[NAMES_INDEX]];
33272
33272
  }
33273
33273
  out.push({ generated, source, original, name });
33274
33274
  }
@@ -33280,7 +33280,7 @@ var require_gen_mapping_umd = __commonJS({
33280
33280
  _mappings: mappings,
33281
33281
  _sources: sources,
33282
33282
  _sourcesContent: sourcesContent,
33283
- _names: names
33283
+ _names: names2
33284
33284
  // _originalScopes: originalScopes,
33285
33285
  } = cast2(map);
33286
33286
  const line = getIndex(mappings, genLine);
@@ -33292,7 +33292,7 @@ var require_gen_mapping_umd = __commonJS({
33292
33292
  assert(sourceLine);
33293
33293
  assert(sourceColumn);
33294
33294
  const sourcesIndex = put(sources, source);
33295
- const namesIndex = name ? put(names, name) : NO_NAME;
33295
+ const namesIndex = name ? put(names2, name) : NO_NAME;
33296
33296
  if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
33297
33297
  if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
33298
33298
  return;
@@ -33592,18 +33592,18 @@ var require_trace_mapping_umd2 = __commonJS({
33592
33592
  state.lastNeedle = needle;
33593
33593
  return state.lastIndex = binarySearch(haystack, needle, low, high);
33594
33594
  }
33595
- function parse4(map) {
33595
+ function parse5(map) {
33596
33596
  return typeof map === "string" ? JSON.parse(map) : map;
33597
33597
  }
33598
33598
  var FlattenMap = function(map, mapUrl) {
33599
- const parsed = parse4(map);
33599
+ const parsed = parse5(map);
33600
33600
  if (!("sections" in parsed)) {
33601
33601
  return new TraceMap(parsed, mapUrl);
33602
33602
  }
33603
33603
  const mappings = [];
33604
33604
  const sources = [];
33605
33605
  const sourcesContent = [];
33606
- const names = [];
33606
+ const names2 = [];
33607
33607
  const ignoreList = [];
33608
33608
  recurse(
33609
33609
  parsed,
@@ -33611,7 +33611,7 @@ var require_trace_mapping_umd2 = __commonJS({
33611
33611
  mappings,
33612
33612
  sources,
33613
33613
  sourcesContent,
33614
- names,
33614
+ names2,
33615
33615
  ignoreList,
33616
33616
  0,
33617
33617
  0,
@@ -33621,7 +33621,7 @@ var require_trace_mapping_umd2 = __commonJS({
33621
33621
  const joined = {
33622
33622
  version: 3,
33623
33623
  file: parsed.file,
33624
- names,
33624
+ names: names2,
33625
33625
  sources,
33626
33626
  sourcesContent,
33627
33627
  mappings,
@@ -33629,7 +33629,7 @@ var require_trace_mapping_umd2 = __commonJS({
33629
33629
  };
33630
33630
  return presortedDecodedMap(joined);
33631
33631
  };
33632
- function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
33632
+ function recurse(input, mapUrl, mappings, sources, sourcesContent, names2, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
33633
33633
  const { sections } = input;
33634
33634
  for (let i = 0; i < sections.length; i++) {
33635
33635
  const { map, offset } = sections[i];
@@ -33650,7 +33650,7 @@ var require_trace_mapping_umd2 = __commonJS({
33650
33650
  mappings,
33651
33651
  sources,
33652
33652
  sourcesContent,
33653
- names,
33653
+ names2,
33654
33654
  ignoreList,
33655
33655
  lineOffset + offset.line,
33656
33656
  columnOffset + offset.column,
@@ -33659,16 +33659,16 @@ var require_trace_mapping_umd2 = __commonJS({
33659
33659
  );
33660
33660
  }
33661
33661
  }
33662
- function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
33663
- const parsed = parse4(input);
33662
+ function addSection(input, mapUrl, mappings, sources, sourcesContent, names2, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
33663
+ const parsed = parse5(input);
33664
33664
  if ("sections" in parsed) return recurse(...arguments);
33665
33665
  const map = new TraceMap(parsed, mapUrl);
33666
33666
  const sourcesOffset = sources.length;
33667
- const namesOffset = names.length;
33667
+ const namesOffset = names2.length;
33668
33668
  const decoded = decodedMappings(map);
33669
33669
  const { resolvedSources, sourcesContent: contents2, ignoreList: ignores } = map;
33670
33670
  append(sources, resolvedSources);
33671
- append(names, map.names);
33671
+ append(names2, map.names);
33672
33672
  if (contents2) append(sourcesContent, contents2);
33673
33673
  else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);
33674
33674
  if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset);
@@ -33710,11 +33710,11 @@ var require_trace_mapping_umd2 = __commonJS({
33710
33710
  constructor(map, mapUrl) {
33711
33711
  const isString = typeof map === "string";
33712
33712
  if (!isString && map._decodedMemo) return map;
33713
- const parsed = parse4(map);
33714
- const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
33713
+ const parsed = parse5(map);
33714
+ const { version, file, names: names2, sourceRoot, sources, sourcesContent } = parsed;
33715
33715
  this.version = version;
33716
33716
  this.file = file;
33717
- this.names = names || [];
33717
+ this.names = names2 || [];
33718
33718
  this.sourceRoot = sourceRoot;
33719
33719
  this.sources = sources;
33720
33720
  this.sourcesContent = sourcesContent;
@@ -33780,12 +33780,12 @@ var require_trace_mapping_umd2 = __commonJS({
33780
33780
  if (index === -1) return OMapping(null, null, null, null);
33781
33781
  const segment = segments[index];
33782
33782
  if (segment.length === 1) return OMapping(null, null, null, null);
33783
- const { names, resolvedSources } = map;
33783
+ const { names: names2, resolvedSources } = map;
33784
33784
  return OMapping(
33785
33785
  resolvedSources[segment[SOURCES_INDEX]],
33786
33786
  segment[SOURCE_LINE] + 1,
33787
33787
  segment[SOURCE_COLUMN],
33788
- segment.length === 5 ? names[segment[NAMES_INDEX]] : null
33788
+ segment.length === 5 ? names2[segment[NAMES_INDEX]] : null
33789
33789
  );
33790
33790
  }
33791
33791
  function generatedPositionFor(map, needle) {
@@ -33798,7 +33798,7 @@ var require_trace_mapping_umd2 = __commonJS({
33798
33798
  }
33799
33799
  function eachMapping(map, cb) {
33800
33800
  const decoded = decodedMappings(map);
33801
- const { names, resolvedSources } = map;
33801
+ const { names: names2, resolvedSources } = map;
33802
33802
  for (let i = 0; i < decoded.length; i++) {
33803
33803
  const line = decoded[i];
33804
33804
  for (let j = 0; j < line.length; j++) {
@@ -33814,7 +33814,7 @@ var require_trace_mapping_umd2 = __commonJS({
33814
33814
  originalLine = seg[2] + 1;
33815
33815
  originalColumn = seg[3];
33816
33816
  }
33817
- if (seg.length === 5) name = names[seg[4]];
33817
+ if (seg.length === 5) name = names2[seg[4]];
33818
33818
  cb({
33819
33819
  generatedLine,
33820
33820
  generatedColumn,
@@ -42273,12 +42273,12 @@ var require_literal = __commonJS({
42273
42273
  function literalTemplate(formatter, tpl, opts) {
42274
42274
  const {
42275
42275
  metadata,
42276
- names
42276
+ names: names2
42277
42277
  } = buildLiteralData(formatter, tpl, opts);
42278
42278
  return (arg) => {
42279
42279
  const defaultReplacements = {};
42280
42280
  arg.forEach((replacement, i) => {
42281
- defaultReplacements[names[i]] = replacement;
42281
+ defaultReplacements[names2[i]] = replacement;
42282
42282
  });
42283
42283
  return (arg2) => {
42284
42284
  const replacements = (0, _options.normalizeReplacements)(arg2);
@@ -42300,31 +42300,31 @@ var require_literal = __commonJS({
42300
42300
  prefix = "$$" + prefix;
42301
42301
  } while (raw.includes(prefix));
42302
42302
  const {
42303
- names,
42303
+ names: names2,
42304
42304
  code
42305
42305
  } = buildTemplateCode(tpl, prefix);
42306
42306
  const metadata = (0, _parse.default)(formatter, formatter.code(code), {
42307
42307
  parser: opts.parser,
42308
- placeholderWhitelist: new Set(names.concat(opts.placeholderWhitelist ? Array.from(opts.placeholderWhitelist) : [])),
42308
+ placeholderWhitelist: new Set(names2.concat(opts.placeholderWhitelist ? Array.from(opts.placeholderWhitelist) : [])),
42309
42309
  placeholderPattern: opts.placeholderPattern,
42310
42310
  preserveComments: opts.preserveComments,
42311
42311
  syntacticPlaceholders: opts.syntacticPlaceholders
42312
42312
  });
42313
42313
  return {
42314
42314
  metadata,
42315
- names
42315
+ names: names2
42316
42316
  };
42317
42317
  }
42318
42318
  function buildTemplateCode(tpl, prefix) {
42319
- const names = [];
42319
+ const names2 = [];
42320
42320
  let code = tpl[0];
42321
42321
  for (let i = 1; i < tpl.length; i++) {
42322
42322
  const value = `${prefix}${i - 1}`;
42323
- names.push(value);
42323
+ names2.push(value);
42324
42324
  code += value + tpl[i];
42325
42325
  }
42326
42326
  return {
42327
- names,
42327
+ names: names2,
42328
42328
  code
42329
42329
  };
42330
42330
  }
@@ -45159,6 +45159,7 @@ var import_parser = __toESM(require_lib(), 1);
45159
45159
  import { execFile as execFile2 } from "node:child_process";
45160
45160
  import { readdir, readFile as readFile2, stat as stat2 } from "node:fs/promises";
45161
45161
  import path2 from "node:path";
45162
+ import { deflateRawSync } from "node:zlib";
45162
45163
 
45163
45164
  // worker/head.ts
45164
45165
  var ATTRIBUTES = String.raw`(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^>"'{/]|\/(?!>))*`;
@@ -45175,7 +45176,7 @@ function headEnd(html) {
45175
45176
  // cli/package.json
45176
45177
  var package_default = {
45177
45178
  name: "agentface",
45178
- version: "0.10.1",
45179
+ version: "0.11.1",
45179
45180
  description: "Add the Agentface tag to a website's pages, so AI agents get tools made for it, and use your agentface account from a shell.",
45180
45181
  repository: {
45181
45182
  type: "git",
@@ -45195,235 +45196,8 @@ var package_default = {
45195
45196
  license: "UNLICENSED"
45196
45197
  };
45197
45198
 
45198
- // cli/zip.mts
45199
- import { deflateRawSync } from "node:zlib";
45200
- var CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
45201
- let c = n;
45202
- for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
45203
- return c >>> 0;
45204
- });
45205
- function crc32(data) {
45206
- let c = 4294967295;
45207
- for (const byte of data) c = CRC_TABLE[(c ^ byte) & 255] ^ c >>> 8;
45208
- return (c ^ 4294967295) >>> 0;
45209
- }
45210
- function zip(files2, date = /* @__PURE__ */ new Date()) {
45211
- const time = date.getHours() << 11 | date.getMinutes() << 5 | date.getSeconds() >> 1;
45212
- const day = date.getFullYear() - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate();
45213
- const parts = [];
45214
- const directory = [];
45215
- let offset = 0;
45216
- for (const [name, text2] of Object.entries(files2)) {
45217
- const data = Buffer.from(text2);
45218
- const packed = deflateRawSync(data);
45219
- const path6 = Buffer.from(name);
45220
- const shared = Buffer.alloc(26);
45221
- shared.writeUInt16LE(20, 0);
45222
- shared.writeUInt16LE(2048, 2);
45223
- shared.writeUInt16LE(8, 4);
45224
- shared.writeUInt16LE(time, 6);
45225
- shared.writeUInt16LE(day, 8);
45226
- shared.writeUInt32LE(crc32(data), 10);
45227
- shared.writeUInt32LE(packed.length, 14);
45228
- shared.writeUInt32LE(data.length, 18);
45229
- shared.writeUInt16LE(path6.length, 22);
45230
- const local = Buffer.alloc(4);
45231
- local.writeUInt32LE(67324752);
45232
- parts.push(local, shared, path6, packed);
45233
- const entry2 = Buffer.alloc(46);
45234
- entry2.writeUInt32LE(33639248, 0);
45235
- entry2.writeUInt16LE(788, 4);
45236
- shared.copy(entry2, 6);
45237
- entry2.writeUInt32LE(33188 * 65536, 38);
45238
- entry2.writeUInt32LE(offset, 42);
45239
- directory.push(entry2, path6);
45240
- offset += 4 + shared.length + path6.length + packed.length;
45241
- }
45242
- const size = directory.reduce((total, part) => total + part.length, 0);
45243
- const end = Buffer.alloc(22);
45244
- end.writeUInt32LE(101010256, 0);
45245
- end.writeUInt16LE(Object.keys(files2).length, 8);
45246
- end.writeUInt16LE(Object.keys(files2).length, 10);
45247
- end.writeUInt32LE(size, 12);
45248
- end.writeUInt32LE(offset, 16);
45249
- return Buffer.concat([...parts, ...directory, end]);
45250
- }
45251
-
45252
- // cli/heads.mts
45199
+ // cli/ours.mts
45253
45200
  var INIT = package_default.version;
45254
- var stamped = (tag) => tag.replace(/><\/script>$/, ` data-init="${INIT}"></script>`);
45255
- var EXTENSIONS = [
45256
- "html",
45257
- "htm",
45258
- "php",
45259
- "njk",
45260
- "liquid",
45261
- "hbs",
45262
- "handlebars",
45263
- "mustache",
45264
- "ejs",
45265
- "erb",
45266
- "twig",
45267
- "jinja",
45268
- "jinja2",
45269
- "j2",
45270
- "tmpl",
45271
- "tpl",
45272
- "astro",
45273
- "heex"
45274
- ];
45275
- var MARKUP = new RegExp(`\\.(?:${EXTENSIONS.join("|")})$`, "i");
45276
- var COMPONENT = /\.(?:[cm]?[jt]sx?|vue|svelte|mdx)$/i;
45277
- var LAYOUTS = [
45278
- /(?:^|\/)app\/(?:.+\/)?layout\.[cm]?[jt]sx?$/,
45279
- /(?:^|\/)pages\/_document\.[cm]?[jt]sx?$/,
45280
- /(?:^|\/)app\/root\.[cm]?[jt]sx?$/,
45281
- /(?:^|\/)routes\/__root\.[cm]?[jt]sx?$/,
45282
- /(?:^|\/)src\/html\.[cm]?[jt]sx?$/
45283
- ];
45284
- var SKIP = /* @__PURE__ */ new Set([
45285
- "node_modules",
45286
- "bower_components",
45287
- "vendor",
45288
- "dist",
45289
- "build",
45290
- "out",
45291
- "_site",
45292
- "coverage",
45293
- "tmp",
45294
- "temp",
45295
- "test",
45296
- "tests",
45297
- "__tests__",
45298
- "__mocks__",
45299
- "fixtures",
45300
- "__fixtures__",
45301
- "e2e",
45302
- "cypress",
45303
- "playwright",
45304
- "storybook-static",
45305
- "wp-admin",
45306
- "wp-includes",
45307
- // A Python environment's packages, and Elixir's builds.
45308
- "site-packages",
45309
- "dist-packages",
45310
- "__pycache__",
45311
- "_build"
45312
- ]);
45313
- var MAIL = /mail/i;
45314
- var PRINTED = /(?:^|[-_.])(?:pdfs?|invoices?|receipts?|print(?:able)?)(?=$|[-_.])/i;
45315
- var notMail = (name) => !MAIL.test(name) && !PRINTED.test(name);
45316
- var AMP = /<html\b[^>]*\s(?:amp|⚡)[\s>=/]/i;
45317
- var CODE = /<\?(?!xml\b)[\s\S]*?(?:\?>|$)|<%[\s\S]*?(?:%>|$)/g;
45318
- function inCode(source, at) {
45319
- for (const code of source.matchAll(CODE)) {
45320
- if (code.index > at) return false;
45321
- if (at < code.index + code[0].length) return true;
45322
- }
45323
- return false;
45324
- }
45325
- var MAX_FILES = 2e4;
45326
- var MAX_BYTES = 1e6;
45327
- var CONFIG_HEAD = {
45328
- nuxt: ["Nuxt", "`app.head.script` in nuxt.config"],
45329
- "@docusaurus/core": ["Docusaurus", "`scripts` in docusaurus.config"],
45330
- vitepress: ["VitePress", "`head` in .vitepress/config"]
45331
- };
45332
- var FRAMEWORKS = [
45333
- ["next", "Next.js"],
45334
- ["@tanstack/react-start", "TanStack Start"],
45335
- ["@react-router/dev", "React Router"],
45336
- ["@remix-run/dev", "Remix"],
45337
- ["gatsby", "Gatsby"],
45338
- ["@sveltejs/kit", "SvelteKit"],
45339
- ["astro", "Astro"],
45340
- ["@11ty/eleventy", "Eleventy"],
45341
- ["@angular/core", "Angular"],
45342
- ["react-scripts", "Create React App"],
45343
- ["@vue/cli-service", "Vue CLI"],
45344
- ["vite", "Vite"]
45345
- ];
45346
- var read = (file) => readFile2(file, "utf8").catch(() => null);
45347
- var exists = (file) => stat2(file).then(
45348
- () => true,
45349
- () => false
45350
- );
45351
- var THEME = /^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name\s*:/im;
45352
- async function isWordPress(dir) {
45353
- if (THEME.test((await read(path2.join(dir, "style.css")) ?? "").slice(0, 8192))) return true;
45354
- for (const name of ["wp-content", "wp-includes"]) if (await exists(path2.join(dir, name))) return true;
45355
- for (let at = path2.resolve(dir); ; at = path2.dirname(at)) {
45356
- if (path2.basename(at) === "wp-content" || await exists(path2.join(at, "wp-config.php"))) return true;
45357
- if (path2.dirname(at) === at) return false;
45358
- }
45359
- }
45360
- async function contentFolder(dir) {
45361
- const here = path2.resolve(dir);
45362
- for (let at = here; ; at = path2.dirname(at)) {
45363
- if (path2.basename(at) === "wp-content") return at;
45364
- const content = path2.join(at, "wp-content");
45365
- if ((at === here || await exists(path2.join(at, "wp-config.php"))) && await exists(content))
45366
- return content;
45367
- if (path2.dirname(at) === at) return null;
45368
- }
45369
- }
45370
- async function wordPressFile(dir) {
45371
- const content = await contentFolder(dir);
45372
- return content && path2.relative(dir, path2.join(content, "mu-plugins", "agentface.php")).split(path2.sep).join("/");
45373
- }
45374
- var wordPressPage = (html) => /\/wp-(?:content|includes)\/|["']https:\/\/api\.w\.org\/["']|<meta\b[^>]*\bcontent=["']WordPress\b/i.test(
45375
- html
45376
- );
45377
- var WORDPRESS_STEPS = (tag, notice) => [
45378
- 'In the WordPress admin, open Plugins > Add New Plugin, search for WPCode, then install and activate "WPCode \u2013 Insert Headers and Footers".',
45379
- "Open Code Snippets > Header & Footer.",
45380
- `Paste this line in the Header box. If the box has an Agentface line from an earlier run, replace that line with it:
45381
-
45382
- ${tag}`,
45383
- ...notice ? [
45384
- `Paste this line in the Body box. If the box has an Agentface line from an earlier run, replace that line with it:
45385
-
45386
- ${notice}`
45387
- ] : [],
45388
- "Click Save Changes. If the site has a caching plugin, clear its cache, so the homepage shows the change."
45389
- ].map((step, i) => ` ${i + 1}. ${step}`).join("\n\n") + "\n";
45390
- var wordPressManual = (lead) => ({
45391
- reason: `${lead} Run in the site's folder, the one with wp-config.php, init adds a plugin of its own that puts the tag on every page. It never edits WordPress's, its plugins' or its theme's files: updates put them back and take the tag away, and a header plugin or page builder, such as Elementor's, can replace the theme's header, so that a tag put there reaches no page.`,
45392
- how: "Or add it with a plugin that has boxes for the site's head and body, such as the free WPCode",
45393
- steps: WORDPRESS_STEPS
45394
- });
45395
- var SHOP = /\b_PS_[A-Z_]+_\b/;
45396
- var PRESTASHOP_MODULE_FILE = "agentface/agentface.php";
45397
- async function shopFolder(dir) {
45398
- for (let at = path2.resolve(dir); ; at = path2.dirname(at)) {
45399
- if (SHOP.test(await read(path2.join(at, "config", "defines.inc.php")) ?? "")) return at;
45400
- if (path2.dirname(at) === at) return null;
45401
- }
45402
- }
45403
- async function prestaShopFile(dir) {
45404
- const shop = await shopFolder(dir);
45405
- return shop && path2.relative(dir, path2.join(shop, "modules", PRESTASHOP_MODULE_FILE)).split(path2.sep).join("/");
45406
- }
45407
- async function prestaShopTheme(dir) {
45408
- return /^name\s*:/m.test(await read(path2.join(dir, "config", "theme.yml")) ?? "") && await exists(path2.join(dir, "templates"));
45409
- }
45410
- var prestaShopPage = (html) => /\bvar\s+prestashop\s*=/.test(html);
45411
- var KEY = /\/s\/(site-[a-z0-9-]+)\.js(?=[?#"'`\s]|$)/;
45412
- var BRACES = String.raw`\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}`;
45413
- var ATTRIBUTES2 = `(?:${BRACES}|[^>])*?`;
45414
- var TAG = new RegExp(
45415
- `<script\\b${ATTRIBUTES2}${KEY.source}${ATTRIBUTES2}(?:\\/>|>\\s*<\\/script\\s*>)`,
45416
- "gi"
45417
- );
45418
- var ATTRIBUTE = new RegExp(
45419
- `(${BRACES})|([^\\s"'<>/={}]+)(?:\\s*=\\s*(${BRACES}|"[^"]*"|'[^']*'|[^\\s"'<>=]+))?`,
45420
- "g"
45421
- );
45422
- var NOTICE = /<noscript\b[^>]*>[^<]*\/s\/(site-[a-z0-9-]+)\.md[^<]*<\/noscript\s*>/i;
45423
- var MADE_NOTICE = /createElement\(\s*['"]noscript['"][^()]*\/s\/(site-[a-z0-9-]+)\.md/;
45424
- var LIST = /\/s\/(site-[a-z0-9-]+)\.md(?![\w-])/;
45425
- var BODY = /<body(?=[\s>/])(?:<\?[\s\S]*?\?>|<%[\s\S]*?%>|\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^>])*>/i;
45426
- var onItsLine = (pattern) => new RegExp(`(\\r?\\n[ \\t]*)?${pattern.source}`, "gi");
45427
45201
  var OURS = "Added by `npx agentface init`";
45428
45202
  var about = (comment2, how) => [
45429
45203
  `${OURS}. It asks Agentface for the two lines this`,
@@ -45433,224 +45207,12 @@ var about = (comment2, how) => [
45433
45207
  how,
45434
45208
  "`npx agentface uninstall` deletes it."
45435
45209
  ].join("\n").replace(/^/gm, comment2 + " ").replace(/ +$/gm, "");
45436
- function tagKey(source) {
45437
- return source.match(KEY)?.[1] ?? null;
45438
- }
45439
- function noticeKey(source) {
45440
- return source.match(NOTICE)?.[1] ?? null;
45441
- }
45442
45210
  function siteOf(tag) {
45443
45211
  const [, service = "", site = ""] = tag.match(/\bsrc="(https?:\/\/[^"]+?)\/s\/([^/"]+)\.js"/) ?? [];
45444
45212
  return { service, site };
45445
45213
  }
45446
- var linesIn = (source) => ({
45447
- tag: source.match(TAG)?.[0] ?? null,
45448
- notice: source.match(NOTICE)?.[0] ?? null
45449
- });
45450
- var squash = (text2) => text2.replace(/\s+/g, " ").trim();
45451
- var said2 = (value = "") => squash(value.replace(/^\{\s*(["'`][\s\S]*["'`])\s*\}$/, "$1").replace(/^(["'`])([\s\S]*)\1$/, "$2"));
45452
- function attributesOf(tag) {
45453
- const inside = tag.replace(/^<script\b/i, "").replace(/(?:\/>|>\s*<\/script\s*>)$/i, "");
45454
- return [...inside.matchAll(ATTRIBUTE)].map(
45455
- ([, braces, name, value]) => braces ? { name: null, value: void 0, text: braces } : { name: name.toLowerCase(), value, text: value === void 0 ? name : `${name}=${value}` }
45456
- );
45457
- }
45458
- function updatedTag(old, tag) {
45459
- const now = attributesOf(tag);
45460
- const was = attributesOf(old);
45461
- const mine = initsOwn(was, now);
45462
- const init2 = (list2) => list2.some(({ name }) => name === "data-init");
45463
- const rest = (list2) => list2.filter(({ name }) => name !== "data-init");
45464
- const current2 = rest(mine).length === rest(now).length && (init2(mine) || !init2(now)) && rest(now).every(({ name, value }) => {
45465
- const same = mine.find((attribute2) => attribute2.name === name);
45466
- return same && (value === void 0 || said2(same.value) === said2(value));
45467
- });
45468
- if (current2) return old;
45469
- const kept = was.filter((attribute2) => !mine.includes(attribute2)).map(({ text: text2 }) => text2);
45470
- return kept.length ? tag.replace(/^<script\b/, () => `<script ${kept.join(" ")}`) : tag;
45471
- }
45472
- function initsOwn(was, now) {
45473
- const names = /* @__PURE__ */ new Set(["src", "async", "defer", "data-init", ...now.map(({ name }) => name)]);
45474
- return was.filter(({ name, value }) => name !== null && (names.has(name) || LIST.test(value ?? "")));
45475
- }
45476
- function ownersAttributes(old) {
45477
- const was = attributesOf(old);
45478
- const mine = initsOwn(was, []);
45479
- return was.filter((attribute2) => !mine.includes(attribute2)).map(({ text: text2 }) => text2);
45480
- }
45481
- function updatedNotice(old, notice) {
45482
- const parts = (line) => line.match(/^<noscript\b([^>]*)>([^<]*)<\/noscript\s*>$/i) ?? [];
45483
- const [, attributes = "", text2 = ""] = parts(old);
45484
- if (squash(text2) === squash(parts(notice)[2] ?? "")) return old;
45485
- return squash(attributes) ? notice.replace(/^<noscript\b/, () => `<noscript ${squash(attributes)}`) : notice;
45486
- }
45487
- function tagToReplace(source, tag) {
45488
- const old = source.match(TAG)?.[0];
45489
- const next2 = old && updatedTag(old, tag.replace(/\sdata-init="[^"]*"/, ""));
45490
- return next2 && next2 !== old ? updatedTag(old, tag) : null;
45491
- }
45492
- function staleNotice(source, notice) {
45493
- const key = noticeKey(notice);
45494
- return [...source.matchAll(new RegExp(NOTICE.source, "gi"))].some(
45495
- ([old, its]) => its === key && updatedNotice(old, notice) !== old
45496
- );
45497
- }
45498
- function oldWords(source, words, key) {
45499
- const rest = source.replace(TAG, "").replace(new RegExp(NOTICE.source, "gi"), "");
45500
- for (const match of rest.matchAll(new RegExp(LIST.source, "g"))) {
45501
- if (match[1] !== key) continue;
45502
- const before = rest.slice(Math.max(0, match.index - 400), match.index);
45503
- const written = before.match(/([^"'`<>{}]*?)\s*https?:\/\/[^\s"'`<>{}]*$/)?.[1];
45504
- if (written && squash(written) && squash(written) !== squash(words)) return true;
45505
- }
45506
- return false;
45507
- }
45508
- function indentUnit(source) {
45509
- return source.match(/^(\t| {2,4})\S/m)?.[1] ?? " ";
45510
- }
45511
- var indentOf = (line) => line.match(/^[ \t]*/)[0];
45512
- function addTag(source, tag) {
45513
- let first = true;
45514
- const replaced = source.replace(onItsLine(TAG), (match, line) => {
45515
- if (!first) return "";
45516
- first = false;
45517
- return (line ?? "") + updatedTag(match.slice(line?.length ?? 0), tag);
45518
- });
45519
- if (!first) return replaced;
45520
- const eol = source.includes("\r\n") ? "\r\n" : "\n";
45521
- const at = headEnd(source);
45522
- const close = at !== -1 && /^<\/head\s*>/i.test(source.slice(at)) ? at : -1;
45523
- if (close !== -1) {
45524
- const lineStart = source.lastIndexOf("\n", close - 1) + 1;
45525
- const before = source.slice(lineStart, close);
45526
- if (!/^[ \t]*$/.test(before)) return source.slice(0, close) + tag + source.slice(close);
45527
- const previous = source.slice(0, lineStart).split(/\r?\n/).findLast((line) => line.trim());
45528
- const sibling = indentOf(previous ?? "");
45529
- const indent = previous && !/<head\b[^>]*>\s*$/i.test(previous) && sibling.startsWith(before) ? sibling : before + indentUnit(source);
45530
- return source.slice(0, lineStart) + indent + tag + eol + source.slice(lineStart);
45531
- }
45532
- const html = /<html\b[^>]*>/.exec(source);
45533
- if (!html) return null;
45534
- const end = html.index + html[0].length;
45535
- const child = source.slice(end).match(/^\r?\n([ \t]*)\S/)?.[1];
45536
- if (child === void 0) return source.slice(0, end) + `<head>${tag}</head>` + source.slice(end);
45537
- const outer = indentOf(source.slice(source.lastIndexOf("\n", html.index) + 1));
45538
- const step = child.length > outer.length && child.startsWith(outer) ? child.slice(outer.length) : indentUnit(source);
45539
- const lines = [`${child}<head>`, `${child}${step}${tag}`, `${child}</head>`];
45540
- return source.slice(0, end) + eol + lines.join(eol) + source.slice(end);
45541
- }
45542
- function addNotice(source, notice) {
45543
- let first = true;
45544
- const replaced = source.replace(onItsLine(NOTICE), (match, line) => {
45545
- if (!first) return "";
45546
- first = false;
45547
- return (line ?? "") + updatedNotice(match.slice(line?.length ?? 0), notice);
45548
- });
45549
- if (!first) return replaced;
45550
- const body = BODY.exec(source);
45551
- if (!body) return null;
45552
- const end = body.index + body[0].length;
45553
- const next2 = source.slice(end).match(/^[ \t]*\r?\n([ \t]*)(.*)/);
45554
- if (!next2) return source.slice(0, end) + notice + source.slice(end);
45555
- const eol = source.includes("\r\n") ? "\r\n" : "\n";
45556
- const outer = indentOf(source.slice(source.lastIndexOf("\n", body.index) + 1));
45557
- const indent = next2[2].trim() && !/^<\/body\b/i.test(next2[2]) ? next2[1] : outer + indentUnit(source);
45558
- return source.slice(0, end) + eol + indent + notice + source.slice(end);
45559
- }
45560
- function gitFiles(dir) {
45561
- return new Promise((resolve2) => {
45562
- execFile2(
45563
- "git",
45564
- ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
45565
- { cwd: dir, maxBuffer: 64 * 1024 * 1024 },
45566
- (error, stdout) => resolve2(error ? null : [...new Set(stdout.split("\0").filter(Boolean))].sort())
45567
- );
45568
- });
45569
- }
45570
- async function files(dir, skip) {
45571
- const kept = (name) => (!name.startsWith(".") || name === ".vitepress") && !skip.has(name) && notMail(name);
45572
- const tracked = await gitFiles(dir);
45573
- if (tracked)
45574
- return {
45575
- git: true,
45576
- files: tracked.filter((file) => file.split("/").slice(0, -1).every(kept)).slice(0, MAX_FILES)
45577
- };
45578
- const found = [];
45579
- const visit = async (rel) => {
45580
- const entries = await readdir(path2.join(dir, rel), { withFileTypes: true }).catch(() => []);
45581
- for (const entry2 of entries.sort((a, b) => a.name.localeCompare(b.name))) {
45582
- const file = rel ? `${rel}/${entry2.name}` : entry2.name;
45583
- if (entry2.isDirectory()) {
45584
- if (kept(entry2.name)) await visit(file);
45585
- } else if (entry2.isFile() && found.length < MAX_FILES) found.push(file);
45586
- }
45587
- };
45588
- await visit("");
45589
- return { git: false, files: found };
45590
- }
45591
- async function contents(dir, file) {
45592
- const info = await stat2(path2.join(dir, file)).catch(() => null);
45593
- return info?.isFile() && info.size <= MAX_BYTES ? read(path2.join(dir, file)) : null;
45594
- }
45595
- async function siteGenerator(dir) {
45596
- for (const file of ["hugo.toml", "hugo.yaml", "hugo.json", "config.toml"])
45597
- if (/\bbaseURL\b/i.test(await read(path2.join(dir, file)) ?? "")) return "Hugo";
45598
- if (await exists(path2.join(dir, "_config.yml")) || await exists(path2.join(dir, "_layouts")))
45599
- return "Jekyll";
45600
- return null;
45601
- }
45602
- var NEXT_DOCUMENT = (tag, notice) => `// ${OURS}: Next.js's own document, plus the Agentface tag.
45603
- import { Html, Head, Main, NextScript } from 'next/document';
45604
-
45605
- export default function Document() {
45606
- return (
45607
- <Html>
45608
- <Head>
45609
- ${tag}
45610
- </Head>
45611
- <body>
45612
- ${notice ? ` ${notice}
45613
- ` : ""} <Main />
45614
- <NextScript />
45615
- </body>
45616
- </Html>
45617
- );
45618
- }
45619
- `;
45620
- var LINE_NAME = "AgentfaceApi";
45621
- var LINE_USE = new RegExp(`<${LINE_NAME}\\s*/>`);
45622
- var LINE_IMPORT = new RegExp(
45623
- `^import\\s+${LINE_NAME}\\s+from\\s*(['"])\\.\\.?\\/(?:[^'"\\n]*\\/)?agentface\\1;?[ \\t]*$`,
45624
- "m"
45625
- );
45626
- var usesLine = (source) => LINE_USE.test(source) && LINE_IMPORT.test(source);
45627
- var JSX_CODE = /\.(?:jsx|tsx|js|mjs|cjs)$/i;
45628
- function withoutLine(source) {
45629
- if (!usesLine(source)) return source;
45630
- return source.replace(new RegExp(`\\r?\\n[ \\t]*<${LINE_NAME}\\s*\\/>(?=[ \\t]*\\r?\\n)`, "g"), "").replace(new RegExp(`<${LINE_NAME}\\s*\\/>`, "g"), "").replace(
45631
- new RegExp(`^import\\s+${LINE_NAME}\\s+from\\s*(['"])[^'"\\n]+\\1;?[ \\t]*\\r?\\n(\\r?\\n)?`, "m"),
45632
- (match, quote, blank, offset) => blank && offset ? blank : ""
45633
- );
45634
- }
45635
- var GATSBY_SSR = (tag, notice) => {
45636
- const src = tag.match(/\bsrc="([^"]+)"/)[1];
45637
- const data = [...tag.matchAll(/\b(data-[a-z-]+)="([^"]+)"/g)].map(
45638
- ([, name, value]) => `, '${name}': '${value}'`
45639
- );
45640
- const text2 = notice?.match(/>([^<]*)</)[1];
45641
- const load = tag.match(/^<script (async|defer)\b/)?.[1] ?? "defer";
45642
- const props = `key: 'agentface', ${load}: true, src: '${src}'${data.join("")}`;
45643
- return `// ${OURS}: puts the Agentface tag in every page's <head>.
45644
- const React = require('react');
45645
45214
 
45646
- exports.onRenderBody = ({ setHeadComponents${text2 ? ", setPreBodyComponents" : ""} }) => {
45647
- setHeadComponents([
45648
- React.createElement('script', { ${props} }),
45649
- ]);
45650
- ${text2 ? ` setPreBodyComponents([React.createElement('noscript', { key: 'agentface' }, '${text2}')]);
45651
- ` : ""}};
45652
- `;
45653
- };
45215
+ // cli/php.mts
45654
45216
  var phpString = (text2) => `'${text2.replace(/[\\']/g, "\\$&")}'`;
45655
45217
  var PHP_LINES = (tag, notice, own2) => {
45656
45218
  const { service, site } = siteOf(tag);
@@ -45966,20 +45528,7 @@ ${own2}
45966
45528
  `;
45967
45529
  };
45968
45530
  var DOES = (notice) => `Puts the Agentface tag in every page's head${notice ? ", its notice first in the body, and the notice again, hidden, at the end of the first paragraph" : ""}.`;
45969
- var MU_PLUGIN = (tag, notice) => String.raw`<?php
45970
- /**
45971
- * Plugin Name: Agentface
45972
- * Description: ${DOES(notice)}
45973
- */
45974
- ${about("//", "WordPress runs it on every page by itself, as a must-use plugin, and it puts\nthem in each page made from the theme.")}
45975
- if (!defined('ABSPATH')) {
45976
- exit;
45977
- }
45978
-
45979
- ${PHP_LINES(
45980
- tag,
45981
- notice,
45982
- String.raw`
45531
+ var WORDPRESS_OWN = String.raw`
45983
45532
  // The copy, in the site's options.
45984
45533
  private static function kept()
45985
45534
  {
@@ -46003,9 +45552,8 @@ ${PHP_LINES(
46003
45552
  ? wp_remote_retrieve_body($response)
46004
45553
  : null;
46005
45554
  }
46006
- `
46007
- )}
46008
- // The lines are asked for before the page is made, and go in as it goes out.
45555
+ `;
45556
+ var WORDPRESS_HOOK = `// The lines are asked for before the page is made, and go in as it goes out.
46009
45557
  // A page sent in parts gets them in the part that has the end of its head,
46010
45558
  // without the line Exa keeps.
46011
45559
  add_action('template_redirect', function () {
@@ -46015,6 +45563,56 @@ add_action('template_redirect', function () {
46015
45563
  });
46016
45564
  }, PHP_INT_MIN);
46017
45565
  `;
45566
+ var MU_PLUGIN = (tag, notice) => String.raw`<?php
45567
+ /**
45568
+ * Plugin Name: Agentface
45569
+ * Description: ${DOES(notice)}
45570
+ */
45571
+ ${about("//", "WordPress runs it on every page by itself, as a must-use plugin, and it puts\nthem in each page made from the theme.")}
45572
+ if (!defined('ABSPATH')) {
45573
+ exit;
45574
+ }
45575
+
45576
+ ${PHP_LINES(tag, notice, WORDPRESS_OWN)}
45577
+ ${WORDPRESS_HOOK}`;
45578
+ var WORDPRESS_PLUGIN = (tag, notice) => String.raw`<?php
45579
+ /**
45580
+ * Plugin Name: Agentface
45581
+ * Plugin URI: https://agentface.com
45582
+ * Description: ${DOES(notice)}
45583
+ * Version: ${INIT}
45584
+ * Requires PHP: 5.6
45585
+ * Author: Agentface
45586
+ */
45587
+ // Agentface's plugin for WordPress, made by agentface ${INIT}. It asks
45588
+ // Agentface for the two lines this site's pages carry for AI agents, the tag
45589
+ // and its notice, so that a change to them reaches the site by itself. It
45590
+ // keeps them an hour and, while Agentface can't be reached, uses the copy it
45591
+ // has: at first the one below. WordPress runs it on every page once it's
45592
+ // activated in Plugins, and it puts them in each page made from the theme.
45593
+ // Deactivating and deleting it there takes it off.
45594
+ if (!defined('ABSPATH')) {
45595
+ exit;
45596
+ }
45597
+
45598
+ // The must-use plugin that npx agentface init adds to a site's own files does
45599
+ // all of this too, and WordPress runs it first: with it there, this one does
45600
+ // nothing.
45601
+ if (!class_exists('AgentfaceLines', false)) {
45602
+ ${PHP_LINES(tag, notice, WORDPRESS_OWN)}
45603
+ ${WORDPRESS_HOOK}}
45604
+ `;
45605
+ var WORDPRESS_UNINSTALL = `<?php
45606
+ if (!defined('WP_UNINSTALL_PLUGIN')) {
45607
+ exit;
45608
+ }
45609
+
45610
+ delete_option('agentface_lines');
45611
+ `;
45612
+ var wordPressFiles = (tag, notice) => ({
45613
+ "agentface/agentface.php": WORDPRESS_PLUGIN(tag, notice),
45614
+ "agentface/uninstall.php": WORDPRESS_UNINSTALL
45615
+ });
46018
45616
  var PRESTASHOP_MODULE = (tag, notice) => String.raw`<?php
46019
45617
  ${about("//", "PrestaShop runs it once it's installed in Modules > Module Manager, and it\nputs them in each page the shop makes.")}
46020
45618
  if (!defined('_PS_VERSION_')) {
@@ -46162,7 +45760,539 @@ ${notice ? `
46162
45760
  }
46163
45761
  ` : ""}}
46164
45762
  `;
46165
- var prestaShopZip = (tag, notice) => zip({ [PRESTASHOP_MODULE_FILE]: PRESTASHOP_MODULE(tag, notice) });
45763
+ var PRESTASHOP_MODULE_FILE = "agentface/agentface.php";
45764
+ var prestaShopFiles = (tag, notice) => ({
45765
+ [PRESTASHOP_MODULE_FILE]: PRESTASHOP_MODULE(tag, notice)
45766
+ });
45767
+
45768
+ // cli/zip.mts
45769
+ var CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
45770
+ let c = n;
45771
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
45772
+ return c >>> 0;
45773
+ });
45774
+ function crc32(data) {
45775
+ let c = 4294967295;
45776
+ for (const byte of data) c = CRC_TABLE[(c ^ byte) & 255] ^ c >>> 8;
45777
+ return (c ^ 4294967295) >>> 0;
45778
+ }
45779
+ var concat = (parts) => {
45780
+ const all = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
45781
+ let at = 0;
45782
+ for (const part of parts) {
45783
+ all.set(part, at);
45784
+ at += part.length;
45785
+ }
45786
+ return all;
45787
+ };
45788
+ function zip(files2, { date = /* @__PURE__ */ new Date(), deflate } = {}) {
45789
+ const encoder = new TextEncoder();
45790
+ const time = date.getHours() << 11 | date.getMinutes() << 5 | date.getSeconds() >> 1;
45791
+ const day = date.getFullYear() - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate();
45792
+ const parts = [];
45793
+ const directory = [];
45794
+ let offset = 0;
45795
+ for (const [name, text2] of Object.entries(files2)) {
45796
+ const data = encoder.encode(text2);
45797
+ const packed = deflate ? deflate(data) : data;
45798
+ const path6 = encoder.encode(name);
45799
+ const shared = new Uint8Array(26);
45800
+ const fields = new DataView(shared.buffer);
45801
+ fields.setUint16(0, 20, true);
45802
+ fields.setUint16(2, 2048, true);
45803
+ fields.setUint16(4, deflate ? 8 : 0, true);
45804
+ fields.setUint16(6, time, true);
45805
+ fields.setUint16(8, day, true);
45806
+ fields.setUint32(10, crc32(data), true);
45807
+ fields.setUint32(14, packed.length, true);
45808
+ fields.setUint32(18, data.length, true);
45809
+ fields.setUint16(22, path6.length, true);
45810
+ const local = new Uint8Array(4);
45811
+ new DataView(local.buffer).setUint32(0, 67324752, true);
45812
+ parts.push(local, shared, path6, packed);
45813
+ const entry2 = new Uint8Array(46);
45814
+ const entryFields = new DataView(entry2.buffer);
45815
+ entryFields.setUint32(0, 33639248, true);
45816
+ entryFields.setUint16(4, 788, true);
45817
+ entry2.set(shared, 6);
45818
+ entryFields.setUint32(38, 33188 * 65536, true);
45819
+ entryFields.setUint32(42, offset, true);
45820
+ directory.push(entry2, path6);
45821
+ offset += 4 + shared.length + path6.length + packed.length;
45822
+ }
45823
+ const size = directory.reduce((total, part) => total + part.length, 0);
45824
+ const end = new Uint8Array(22);
45825
+ const endFields = new DataView(end.buffer);
45826
+ endFields.setUint32(0, 101010256, true);
45827
+ endFields.setUint16(8, Object.keys(files2).length, true);
45828
+ endFields.setUint16(10, Object.keys(files2).length, true);
45829
+ endFields.setUint32(12, size, true);
45830
+ endFields.setUint32(16, offset, true);
45831
+ return concat([...parts, ...directory, end]);
45832
+ }
45833
+
45834
+ // cli/heads.mts
45835
+ var stamped = (tag) => tag.replace(/><\/script>$/, ` data-init="${INIT}"></script>`);
45836
+ var EXTENSIONS = [
45837
+ "html",
45838
+ "htm",
45839
+ "php",
45840
+ "njk",
45841
+ "liquid",
45842
+ "hbs",
45843
+ "handlebars",
45844
+ "mustache",
45845
+ "ejs",
45846
+ "erb",
45847
+ "twig",
45848
+ "jinja",
45849
+ "jinja2",
45850
+ "j2",
45851
+ "tmpl",
45852
+ "tpl",
45853
+ "astro",
45854
+ "heex"
45855
+ ];
45856
+ var MARKUP = new RegExp(`\\.(?:${EXTENSIONS.join("|")})$`, "i");
45857
+ var COMPONENT = /\.(?:[cm]?[jt]sx?|vue|svelte|mdx)$/i;
45858
+ var LAYOUTS = [
45859
+ /(?:^|\/)app\/(?:.+\/)?layout\.[cm]?[jt]sx?$/,
45860
+ /(?:^|\/)pages\/_document\.[cm]?[jt]sx?$/,
45861
+ /(?:^|\/)app\/root\.[cm]?[jt]sx?$/,
45862
+ /(?:^|\/)routes\/__root\.[cm]?[jt]sx?$/,
45863
+ /(?:^|\/)src\/html\.[cm]?[jt]sx?$/
45864
+ ];
45865
+ var PAGES = {
45866
+ "Next.js": [/^public\//, "the templates in public/"],
45867
+ "TanStack Start": [/^public\//, "the templates in public/"],
45868
+ "React Router": [/^public\//, "the templates in public/"],
45869
+ Remix: [/^public\//, "the templates in public/"],
45870
+ Gatsby: [/^static\//, "the templates in static/"],
45871
+ SvelteKit: [
45872
+ /^(?:src\/(?:app|error)\.html$|static\/)/,
45873
+ "src/app.html, src/error.html and the templates in static/"
45874
+ ],
45875
+ Astro: [/\.astro$|^(?:public|src\/pages)\//, ".astro files and the templates in public/ and src/pages/"],
45876
+ "Create React App": [/^public\//, "the templates in public/"],
45877
+ "Vue CLI": [/^public\//, "the templates in public/"],
45878
+ Angular: [
45879
+ /(?:^|\/)src\/(?:index\.html$|assets\/)|^public\//,
45880
+ "src/index.html and the templates in src/assets/ and public/"
45881
+ ]
45882
+ };
45883
+ var NAMED = {
45884
+ "Vue CLI": [
45885
+ ["vue.config.js", "vue.config.cjs", "vue.config.mjs", "package.json"],
45886
+ /\btemplate['"]?\s*:\s*(['"`])([^'"`\n]+)\1/g
45887
+ ],
45888
+ Angular: [["angular.json"], /"(?:index|input)"\s*:\s*(")([^"\n]+)\1/g],
45889
+ SvelteKit: [
45890
+ ["svelte.config.js", "svelte.config.mjs", "svelte.config.cjs", "svelte.config.ts"],
45891
+ /\b(?:app|error)Template\s*:\s*(['"`])([^'"`\n]+)\1/g
45892
+ ]
45893
+ };
45894
+ var COMMENT = /(['"`])(?:\\[\s\S]|(?!\1)[^\\])*\1|\/\/[^\n]*|\/\*[\s\S]*?\*\//g;
45895
+ var uncommented = (text2) => text2.replace(COMMENT, (match, quote) => quote ? match : "");
45896
+ async function namedTemplates(dir, framework) {
45897
+ const named = /* @__PURE__ */ new Set();
45898
+ if (!NAMED[framework]) return named;
45899
+ const [files2, name] = NAMED[framework];
45900
+ for (const file of files2)
45901
+ for (const [, , template] of uncommented(await read(path2.join(dir, file)) ?? "").matchAll(name))
45902
+ named.add(path2.posix.normalize(template));
45903
+ return named;
45904
+ }
45905
+ var SKIP = /* @__PURE__ */ new Set([
45906
+ "node_modules",
45907
+ "bower_components",
45908
+ "vendor",
45909
+ "dist",
45910
+ "build",
45911
+ "out",
45912
+ "_site",
45913
+ "coverage",
45914
+ "tmp",
45915
+ "temp",
45916
+ "test",
45917
+ "tests",
45918
+ "__tests__",
45919
+ "__mocks__",
45920
+ "fixtures",
45921
+ "__fixtures__",
45922
+ "e2e",
45923
+ "cypress",
45924
+ "playwright",
45925
+ "storybook-static",
45926
+ "wp-admin",
45927
+ "wp-includes",
45928
+ // A Python environment's packages, and Elixir's builds.
45929
+ "site-packages",
45930
+ "dist-packages",
45931
+ "__pycache__",
45932
+ "_build"
45933
+ ]);
45934
+ var MAIL = /mail/i;
45935
+ var PRINTED = /(?:^|[-_.])(?:pdfs?|invoices?|receipts?|print(?:able)?)(?=$|[-_.])/i;
45936
+ var notMail = (name) => !MAIL.test(name) && !PRINTED.test(name);
45937
+ var AMP = /<html\b[^>]*\s(?:amp|⚡)[\s>=/]/i;
45938
+ var CODE = /<\?(?!xml\b)[\s\S]*?(?:\?>|$)|<%[\s\S]*?(?:%>|$)/g;
45939
+ function inCode(source, at) {
45940
+ for (const code of source.matchAll(CODE)) {
45941
+ if (code.index > at) return false;
45942
+ if (at < code.index + code[0].length) return true;
45943
+ }
45944
+ return false;
45945
+ }
45946
+ var MAX_FILES = 2e4;
45947
+ var MAX_BYTES = 1e6;
45948
+ var CONFIG_HEAD = {
45949
+ nuxt: ["Nuxt", "`app.head.script` in nuxt.config"],
45950
+ "@docusaurus/core": ["Docusaurus", "`scripts` in docusaurus.config"],
45951
+ vitepress: ["VitePress", "`head` in .vitepress/config"]
45952
+ };
45953
+ var FRAMEWORKS = [
45954
+ ["next", "Next.js"],
45955
+ ["@tanstack/react-start", "TanStack Start"],
45956
+ ["@react-router/dev", "React Router"],
45957
+ ["@remix-run/dev", "Remix"],
45958
+ ["gatsby", "Gatsby"],
45959
+ ["@sveltejs/kit", "SvelteKit"],
45960
+ ["astro", "Astro"],
45961
+ ["@11ty/eleventy", "Eleventy"],
45962
+ ["@angular/core", "Angular"],
45963
+ ["react-scripts", "Create React App"],
45964
+ ["@vue/cli-service", "Vue CLI"],
45965
+ ["vite", "Vite"]
45966
+ ];
45967
+ var read = (file) => readFile2(file, "utf8").catch(() => null);
45968
+ var exists = (file) => stat2(file).then(
45969
+ () => true,
45970
+ () => false
45971
+ );
45972
+ var THEME = /^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name\s*:/im;
45973
+ async function isWordPress(dir) {
45974
+ if (THEME.test((await read(path2.join(dir, "style.css")) ?? "").slice(0, 8192))) return true;
45975
+ for (const name of ["wp-content", "wp-includes"]) if (await exists(path2.join(dir, name))) return true;
45976
+ for (let at = path2.resolve(dir); ; at = path2.dirname(at)) {
45977
+ if (path2.basename(at) === "wp-content" || await exists(path2.join(at, "wp-config.php"))) return true;
45978
+ if (path2.dirname(at) === at) return false;
45979
+ }
45980
+ }
45981
+ async function contentFolder(dir) {
45982
+ const here = path2.resolve(dir);
45983
+ for (let at = here; ; at = path2.dirname(at)) {
45984
+ if (path2.basename(at) === "wp-content") return at;
45985
+ const content = path2.join(at, "wp-content");
45986
+ if ((at === here || await exists(path2.join(at, "wp-config.php"))) && await exists(content))
45987
+ return content;
45988
+ if (path2.dirname(at) === at) return null;
45989
+ }
45990
+ }
45991
+ async function wordPressFile(dir) {
45992
+ const content = await contentFolder(dir);
45993
+ return content && path2.relative(dir, path2.join(content, "mu-plugins", "agentface.php")).split(path2.sep).join("/");
45994
+ }
45995
+ var wordPressPage = (html) => /\/wp-(?:content|includes)\/|["']https:\/\/api\.w\.org\/["']|<meta\b[^>]*\bcontent=["']WordPress\b/i.test(
45996
+ html
45997
+ );
45998
+ var wordPressManual = (lead) => ({
45999
+ reason: `${lead} Run in the site's folder, the one with wp-config.php, init adds a plugin of its own that puts the tag on every page, with nothing to activate. It never edits WordPress's, its plugins' or its theme's files: updates put them back and take the tag away, and a header plugin or page builder, such as Elementor's, can replace the theme's header, so that a tag put there reaches no page.`,
46000
+ how: "Upload the plugin init writes here as a zip",
46001
+ upload: true
46002
+ });
46003
+ var wordPressZip = (tag, notice) => zip(wordPressFiles(tag, notice), { deflate: deflateRawSync });
46004
+ var prestaShopZip = (tag, notice) => zip(prestaShopFiles(tag, notice), { deflate: deflateRawSync });
46005
+ var SHOP = /\b_PS_[A-Z_]+_\b/;
46006
+ async function shopFolder(dir) {
46007
+ for (let at = path2.resolve(dir); ; at = path2.dirname(at)) {
46008
+ if (SHOP.test(await read(path2.join(at, "config", "defines.inc.php")) ?? "")) return at;
46009
+ if (path2.dirname(at) === at) return null;
46010
+ }
46011
+ }
46012
+ async function prestaShopFile(dir) {
46013
+ const shop = await shopFolder(dir);
46014
+ return shop && path2.relative(dir, path2.join(shop, "modules", PRESTASHOP_MODULE_FILE)).split(path2.sep).join("/");
46015
+ }
46016
+ async function prestaShopTheme(dir) {
46017
+ return /^name\s*:/m.test(await read(path2.join(dir, "config", "theme.yml")) ?? "") && await exists(path2.join(dir, "templates"));
46018
+ }
46019
+ var prestaShopPage = (html) => /\bvar\s+prestashop\s*=/.test(html);
46020
+ var KEY = /\/s\/(site-[a-z0-9-]+)\.js(?=[?#"'`\s]|$)/;
46021
+ var BRACES = String.raw`\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}`;
46022
+ var ATTRIBUTES2 = `(?:${BRACES}|[^>])*?`;
46023
+ var TAG = new RegExp(
46024
+ `<script\\b${ATTRIBUTES2}${KEY.source}${ATTRIBUTES2}(?:\\/>|>\\s*<\\/script\\s*>)`,
46025
+ "gi"
46026
+ );
46027
+ var ATTRIBUTE = new RegExp(
46028
+ `(${BRACES})|([^\\s"'<>/={}]+)(?:\\s*=\\s*(${BRACES}|"[^"]*"|'[^']*'|[^\\s"'<>=]+))?`,
46029
+ "g"
46030
+ );
46031
+ var NOTICE = /<noscript\b[^>]*>[^<]*\/s\/(site-[a-z0-9-]+)\.md[^<]*<\/noscript\s*>/i;
46032
+ var MADE_NOTICE = /createElement\(\s*['"]noscript['"][^()]*\/s\/(site-[a-z0-9-]+)\.md/;
46033
+ var LIST = /\/s\/(site-[a-z0-9-]+)\.md(?![\w-])/;
46034
+ var BODY = /<body(?=[\s>/])(?:<\?[\s\S]*?\?>|<%[\s\S]*?%>|\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^>])*>/i;
46035
+ var onItsLine = (pattern) => new RegExp(`(\\r?\\n[ \\t]*)?${pattern.source}`, "gi");
46036
+ function tagKey(source) {
46037
+ return source.match(KEY)?.[1] ?? null;
46038
+ }
46039
+ function noticeKey(source) {
46040
+ return source.match(NOTICE)?.[1] ?? null;
46041
+ }
46042
+ var linesIn = (source) => ({
46043
+ tag: source.match(TAG)?.[0] ?? null,
46044
+ notice: source.match(NOTICE)?.[0] ?? null
46045
+ });
46046
+ var squash = (text2) => text2.replace(/\s+/g, " ").trim();
46047
+ var said2 = (value = "") => squash(value.replace(/^\{\s*(["'`][\s\S]*["'`])\s*\}$/, "$1").replace(/^(["'`])([\s\S]*)\1$/, "$2"));
46048
+ function attributesOf(tag) {
46049
+ const inside = tag.replace(/^<script\b/i, "").replace(/(?:\/>|>\s*<\/script\s*>)$/i, "");
46050
+ return [...inside.matchAll(ATTRIBUTE)].map(
46051
+ ([, braces, name, value]) => braces ? { name: null, value: void 0, text: braces } : { name: name.toLowerCase(), value, text: value === void 0 ? name : `${name}=${value}` }
46052
+ );
46053
+ }
46054
+ function updatedTag(old, tag) {
46055
+ const now = attributesOf(tag);
46056
+ const was = attributesOf(old);
46057
+ const mine = initsOwn(was, now);
46058
+ const init2 = (list2) => list2.some(({ name }) => name === "data-init");
46059
+ const rest = (list2) => list2.filter(({ name }) => name !== "data-init");
46060
+ const current2 = rest(mine).length === rest(now).length && (init2(mine) || !init2(now)) && rest(now).every(({ name, value }) => {
46061
+ const same = mine.find((attribute2) => attribute2.name === name);
46062
+ return same && (value === void 0 || said2(same.value) === said2(value));
46063
+ });
46064
+ if (current2) return old;
46065
+ const kept = was.filter((attribute2) => !mine.includes(attribute2)).map(({ text: text2 }) => text2);
46066
+ return kept.length ? tag.replace(/^<script\b/, () => `<script ${kept.join(" ")}`) : tag;
46067
+ }
46068
+ function initsOwn(was, now) {
46069
+ const names2 = /* @__PURE__ */ new Set(["src", "async", "defer", "data-init", ...now.map(({ name }) => name)]);
46070
+ return was.filter(({ name, value }) => name !== null && (names2.has(name) || LIST.test(value ?? "")));
46071
+ }
46072
+ function ownersAttributes(old) {
46073
+ const was = attributesOf(old);
46074
+ const mine = initsOwn(was, []);
46075
+ return was.filter((attribute2) => !mine.includes(attribute2)).map(({ text: text2 }) => text2);
46076
+ }
46077
+ function updatedNotice(old, notice) {
46078
+ const parts = (line) => line.match(/^<noscript\b([^>]*)>([^<]*)<\/noscript\s*>$/i) ?? [];
46079
+ const [, attributes = "", text2 = ""] = parts(old);
46080
+ if (squash(text2) === squash(parts(notice)[2] ?? "")) return old;
46081
+ return squash(attributes) ? notice.replace(/^<noscript\b/, () => `<noscript ${squash(attributes)}`) : notice;
46082
+ }
46083
+ function tagToReplace(source, tag) {
46084
+ const old = source.match(TAG)?.[0];
46085
+ const next2 = old && updatedTag(old, tag.replace(/\sdata-init="[^"]*"/, ""));
46086
+ return next2 && next2 !== old ? updatedTag(old, tag) : null;
46087
+ }
46088
+ function staleNotice(source, notice) {
46089
+ const key = noticeKey(notice);
46090
+ return [...source.matchAll(new RegExp(NOTICE.source, "gi"))].some(
46091
+ ([old, its]) => its === key && updatedNotice(old, notice) !== old
46092
+ );
46093
+ }
46094
+ function oldWords(source, words, key) {
46095
+ const rest = source.replace(TAG, "").replace(new RegExp(NOTICE.source, "gi"), "");
46096
+ for (const match of rest.matchAll(new RegExp(LIST.source, "g"))) {
46097
+ if (match[1] !== key) continue;
46098
+ const before = rest.slice(Math.max(0, match.index - 400), match.index);
46099
+ const written = before.match(/([^"'`<>{}]*?)\s*https?:\/\/[^\s"'`<>{}]*$/)?.[1];
46100
+ if (written && squash(written) && squash(written) !== squash(words)) return true;
46101
+ }
46102
+ return false;
46103
+ }
46104
+ function indentUnit(source) {
46105
+ return source.match(/^(\t| {2,4})\S/m)?.[1] ?? " ";
46106
+ }
46107
+ var indentOf = (line) => line.match(/^[ \t]*/)[0];
46108
+ var updatedTags = (source, tag) => source.replace(TAG, (old) => old.startsWith("<script") ? updatedTag(old, tag) : old);
46109
+ function addTag(source, tag) {
46110
+ let first = true;
46111
+ const replaced = source.replace(onItsLine(TAG), (match, line) => {
46112
+ if (!first) return "";
46113
+ first = false;
46114
+ return (line ?? "") + updatedTag(match.slice(line?.length ?? 0), tag);
46115
+ });
46116
+ if (!first) return replaced;
46117
+ const eol = source.includes("\r\n") ? "\r\n" : "\n";
46118
+ const at = headEnd(source);
46119
+ const close = at !== -1 && /^<\/head\s*>/i.test(source.slice(at)) ? at : -1;
46120
+ if (close !== -1) {
46121
+ const lineStart = source.lastIndexOf("\n", close - 1) + 1;
46122
+ const before = source.slice(lineStart, close);
46123
+ if (!/^[ \t]*$/.test(before)) return source.slice(0, close) + tag + source.slice(close);
46124
+ const previous = source.slice(0, lineStart).split(/\r?\n/).findLast((line) => line.trim());
46125
+ const sibling = indentOf(previous ?? "");
46126
+ const indent = previous && !/<head\b[^>]*>\s*$/i.test(previous) && sibling.startsWith(before) ? sibling : before + indentUnit(source);
46127
+ return source.slice(0, lineStart) + indent + tag + eol + source.slice(lineStart);
46128
+ }
46129
+ const html = /<html\b[^>]*>/.exec(source);
46130
+ if (!html) return null;
46131
+ const end = html.index + html[0].length;
46132
+ const child = source.slice(end).match(/^\r?\n([ \t]*)\S/)?.[1];
46133
+ if (child === void 0) return source.slice(0, end) + `<head>${tag}</head>` + source.slice(end);
46134
+ const outer = indentOf(source.slice(source.lastIndexOf("\n", html.index) + 1));
46135
+ const step = child.length > outer.length && child.startsWith(outer) ? child.slice(outer.length) : indentUnit(source);
46136
+ const lines = [`${child}<head>`, `${child}${step}${tag}`, `${child}</head>`];
46137
+ return source.slice(0, end) + eol + lines.join(eol) + source.slice(end);
46138
+ }
46139
+ function addNotice(source, notice) {
46140
+ let first = true;
46141
+ const replaced = source.replace(onItsLine(NOTICE), (match, line) => {
46142
+ if (!first) return "";
46143
+ first = false;
46144
+ return (line ?? "") + updatedNotice(match.slice(line?.length ?? 0), notice);
46145
+ });
46146
+ if (!first) return replaced;
46147
+ const body = BODY.exec(source);
46148
+ if (!body) return null;
46149
+ const end = body.index + body[0].length;
46150
+ const next2 = source.slice(end).match(/^[ \t]*\r?\n([ \t]*)(.*)/);
46151
+ if (!next2) return source.slice(0, end) + notice + source.slice(end);
46152
+ const eol = source.includes("\r\n") ? "\r\n" : "\n";
46153
+ const outer = indentOf(source.slice(source.lastIndexOf("\n", body.index) + 1));
46154
+ const indent = next2[2].trim() && !/^<\/body\b/i.test(next2[2]) ? next2[1] : outer + indentUnit(source);
46155
+ return source.slice(0, end) + eol + indent + notice + source.slice(end);
46156
+ }
46157
+ function gitFiles(dir) {
46158
+ return new Promise((resolve2) => {
46159
+ execFile2(
46160
+ "git",
46161
+ ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
46162
+ { cwd: dir, maxBuffer: 64 * 1024 * 1024 },
46163
+ (error, stdout) => resolve2(error ? null : [...new Set(stdout.split("\0").filter(Boolean))].sort())
46164
+ );
46165
+ });
46166
+ }
46167
+ async function files(dir, skip) {
46168
+ const kept = (name) => (!name.startsWith(".") || name === ".vitepress") && !skip.has(name) && notMail(name);
46169
+ const tracked = await gitFiles(dir);
46170
+ if (tracked)
46171
+ return {
46172
+ git: true,
46173
+ files: tracked.filter((file) => file.split("/").slice(0, -1).every(kept)).slice(0, MAX_FILES)
46174
+ };
46175
+ const found = [];
46176
+ const visit = async (rel) => {
46177
+ const entries = await readdir(path2.join(dir, rel), { withFileTypes: true }).catch(() => []);
46178
+ for (const entry2 of entries.sort((a, b) => a.name.localeCompare(b.name))) {
46179
+ const file = rel ? `${rel}/${entry2.name}` : entry2.name;
46180
+ if (entry2.isDirectory()) {
46181
+ if (kept(entry2.name)) await visit(file);
46182
+ } else if (entry2.isFile() && found.length < MAX_FILES) found.push(file);
46183
+ }
46184
+ };
46185
+ await visit("");
46186
+ return { git: false, files: found };
46187
+ }
46188
+ async function contents(dir, file) {
46189
+ const info = await stat2(path2.join(dir, file)).catch(() => null);
46190
+ return info?.isFile() && info.size <= MAX_BYTES ? read(path2.join(dir, file)) : null;
46191
+ }
46192
+ async function siteGenerator(dir) {
46193
+ for (const file of ["hugo.toml", "hugo.yaml", "hugo.json", "config.toml"])
46194
+ if (/\bbaseURL\b/i.test(await read(path2.join(dir, file)) ?? "")) return "Hugo";
46195
+ if (await exists(path2.join(dir, "_config.yml")) || await exists(path2.join(dir, "_layouts")))
46196
+ return "Jekyll";
46197
+ return null;
46198
+ }
46199
+ var NEXT_DOCUMENT = (tag, notice) => `// ${OURS}: Next.js's own document, plus the Agentface tag.
46200
+ import { Html, Head, Main, NextScript } from 'next/document';
46201
+
46202
+ export default function Document() {
46203
+ return (
46204
+ <Html>
46205
+ <Head>
46206
+ ${tag}
46207
+ </Head>
46208
+ <body>
46209
+ ${notice ? ` ${notice}
46210
+ ` : ""} <Main />
46211
+ <NextScript />
46212
+ </body>
46213
+ </Html>
46214
+ );
46215
+ }
46216
+ `;
46217
+ var LINE_NAME = "AgentfaceApi";
46218
+ var LINE_USE = new RegExp(`<${LINE_NAME}\\s*/>`);
46219
+ function importsComponents(file, from) {
46220
+ if (from === null) return false;
46221
+ const at = /^\.\.?\//.test(from) ? path2.posix.join(path2.posix.dirname(file), from) : from.replace(/^[@~#]*\//, "");
46222
+ return /^(?:src\/)?components\/agentface(?:\.[cm]?[jt]sx?)?$/.test(at);
46223
+ }
46224
+ var LINE_IMPORT = new RegExp(`^import\\s+${LINE_NAME}\\s+from\\s*(['"])([^'"\\n]+)\\1;?[ \\t]*$`, "gm");
46225
+ var usesLine = (source, file) => LINE_USE.test(source) && [...source.matchAll(LINE_IMPORT)].some(([, , from]) => importsComponents(file, from));
46226
+ var JSX_CODE = /\.(?:jsx|tsx|js|mjs|cjs)$/i;
46227
+ var TAG_USED = new RegExp(`${TAG.source}|<AgentfaceTag\\b`, "i");
46228
+ var hasTag = (source) => TAG_USED.test(source);
46229
+ var NOT_LOADING = /\.(?:test|spec|stories)\.[cm]?[jt]sx?$|\.mdx?$/i;
46230
+ var loadsTag = (file, source) => !NOT_LOADING.test(file) && !source.includes(OURS) && hasTag(source);
46231
+ function topNames(source) {
46232
+ const names2 = /* @__PURE__ */ new Map();
46233
+ const add = (name, from) => names2.set(name, [...names2.get(name) ?? [], from]);
46234
+ let program;
46235
+ try {
46236
+ program = (0, import_parser.parse)(source, {
46237
+ sourceType: "unambiguous",
46238
+ plugins: ["typescript", "jsx"],
46239
+ errorRecovery: true
46240
+ }).program;
46241
+ } catch {
46242
+ for (const [, clause, , from] of source.matchAll(
46243
+ /^[ \t]*import\s+(?:type\s+)?([^'";]*?)\s*from\s*(['"])([^'"\n]+)\2/gm
46244
+ ))
46245
+ for (const [name] of clause.matchAll(/[A-Za-z_$][\w$]*/g)) if (name !== "as") add(name, from);
46246
+ for (const [, name] of source.matchAll(/\b(?:function\*?|class|const|let|var)\s+([A-Za-z_$][\w$]*)/g))
46247
+ add(name, null);
46248
+ return names2;
46249
+ }
46250
+ const declared = (node2) => {
46251
+ if (!node2) return;
46252
+ if (node2.type === "Identifier") add(node2.name, null);
46253
+ else if (node2.type === "ObjectPattern")
46254
+ for (const property of node2.properties)
46255
+ declared(property.type === "RestElement" ? property : property.value);
46256
+ else if (node2.type === "ArrayPattern") node2.elements.forEach(declared);
46257
+ else if (node2.type === "AssignmentPattern") declared(node2.left);
46258
+ else if (node2.type === "RestElement") declared(node2.argument);
46259
+ };
46260
+ for (const statement of program.body) {
46261
+ const node2 = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration : statement;
46262
+ if (!node2) continue;
46263
+ if (node2.type === "ImportDeclaration")
46264
+ for (const specifier of node2.specifiers) add(specifier.local.name, node2.source.value);
46265
+ else if (node2.type === "VariableDeclaration") for (const { id } of node2.declarations) declared(id);
46266
+ else if ("id" in node2 && node2.id?.type === "Identifier") add(node2.id.name, null);
46267
+ }
46268
+ return names2;
46269
+ }
46270
+ function withoutLine(source, file) {
46271
+ if (!usesLine(source, file)) return source;
46272
+ return source.replace(new RegExp(`\\r?\\n[ \\t]*<${LINE_NAME}\\s*\\/>(?=[ \\t]*\\r?\\n)`, "g"), "").replace(new RegExp(`<${LINE_NAME}\\s*\\/>`, "g"), "").replace(
46273
+ new RegExp(`^import\\s+${LINE_NAME}\\s+from\\s*(['"])[^'"\\n]+\\1;?[ \\t]*\\r?\\n(\\r?\\n)?`, "m"),
46274
+ (match, quote, blank, offset) => blank && offset ? blank : ""
46275
+ );
46276
+ }
46277
+ var GATSBY_SSR = (tag, notice) => {
46278
+ const src = tag.match(/\bsrc="([^"]+)"/)[1];
46279
+ const data = [...tag.matchAll(/\b(data-[a-z-]+)="([^"]+)"/g)].map(
46280
+ ([, name, value]) => `, '${name}': '${value}'`
46281
+ );
46282
+ const text2 = notice?.match(/>([^<]*)</)[1];
46283
+ const load = tag.match(/^<script (async|defer)\b/)?.[1] ?? "defer";
46284
+ const props = `key: 'agentface', ${load}: true, src: '${src}'${data.join("")}`;
46285
+ return `// ${OURS}: puts the Agentface tag in every page's <head>.
46286
+ const React = require('react');
46287
+
46288
+ exports.onRenderBody = ({ setHeadComponents${text2 ? ", setPreBodyComponents" : ""} }) => {
46289
+ setHeadComponents([
46290
+ React.createElement('script', { ${props} }),
46291
+ ]);
46292
+ ${text2 ? ` setPreBodyComponents([React.createElement('noscript', { key: 'agentface' }, '${text2}')]);
46293
+ ` : ""}};
46294
+ `;
46295
+ };
46166
46296
  async function project(dir) {
46167
46297
  const pkg = JSON.parse(await read(path2.join(dir, "package.json")) ?? "null");
46168
46298
  const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
@@ -46175,6 +46305,10 @@ async function project(dir) {
46175
46305
  const { files: list2, git } = await files(dir, skip);
46176
46306
  return { deps, framework, list: list2, git };
46177
46307
  }
46308
+ function otherPackages(list2) {
46309
+ const folders = list2.filter((file) => file.endsWith("/package.json")).map((file) => file.slice(0, -"package.json".length));
46310
+ return folders.filter((folder) => !folders.some((outer) => outer !== folder && folder.startsWith(outer)));
46311
+ }
46178
46312
  async function findTags(dir) {
46179
46313
  const { list: list2 } = await project(dir);
46180
46314
  const plugin = await isWordPress(dir) && await wordPressFile(dir) || await prestaShopFile(dir);
@@ -46184,7 +46318,7 @@ async function findTags(dir) {
46184
46318
  const source = await contents(dir, file);
46185
46319
  if (source === null) continue;
46186
46320
  const key = tagKey(source) ?? noticeKey(source);
46187
- if (key || JSX_CODE.test(file) && usesLine(source)) tagged.push({ file, source, key });
46321
+ if (key || JSX_CODE.test(file) && usesLine(source, file)) tagged.push({ file, source, key });
46188
46322
  }
46189
46323
  return tagged;
46190
46324
  }
@@ -46246,9 +46380,9 @@ function madeByInit(source) {
46246
46380
  ];
46247
46381
  return made.some(([write, tag, notice]) => tag && sameFile(source, write(tag, notice ?? null)));
46248
46382
  }
46249
- function removeTag(source) {
46383
+ function removeTag(source, keep = {}) {
46250
46384
  if (source.includes(OURS) && madeByInit(source)) return null;
46251
- return [TAG, NOTICE].reduce(
46385
+ return [keep.tag ? null : TAG, keep.notice ? null : NOTICE].filter((pattern) => pattern !== null).reduce(
46252
46386
  (text2, pattern) => text2.replace(onItsLine(pattern), (match, line, ...rest) => {
46253
46387
  const after = rest.at(-1).slice(rest.at(-2) + match.length);
46254
46388
  return line && !/^[ \t]*(?:\r?\n|$)/.test(after) ? line : "";
@@ -46322,26 +46456,61 @@ async function findHeads(dir) {
46322
46456
  const noticed = [];
46323
46457
  const amp = [];
46324
46458
  const code = [];
46459
+ const packages = otherPackages(list2);
46460
+ const apart = /* @__PURE__ */ new Set();
46461
+ const served = PAGES[framework]?.[0];
46462
+ const named = await namedTemplates(dir, framework);
46463
+ const tagged = [];
46464
+ const elsewhere = [];
46465
+ const placed = [];
46325
46466
  for (const file of list2) {
46326
46467
  const markup = MARKUP.test(file);
46468
+ const other = packages.find((folder) => file.startsWith(folder));
46469
+ if (markup && !other && served && !served.test(file) && !named.has(file)) continue;
46327
46470
  const page2 = (markup || LAYOUTS.some((layout) => layout.test(file))) && notMail(path2.posix.basename(file));
46328
46471
  if (!page2 && !markup && !COMPONENT.test(file)) continue;
46472
+ if (other && !page2) continue;
46329
46473
  const text2 = await contents(dir, file);
46330
46474
  if (text2 === null) continue;
46331
46475
  let head = page2 && (markup ? /<\/head\s*>/i.test(text2) : /<\/head\s*>|<html\b/i.test(text2));
46476
+ if (other) {
46477
+ if (head) apart.add(other);
46478
+ continue;
46479
+ }
46332
46480
  let body = page2 && BODY.test(text2);
46481
+ let left = false;
46333
46482
  if (head && markup && AMP.test(text2)) {
46334
46483
  amp.push(file);
46335
46484
  head = body = false;
46485
+ left = true;
46336
46486
  } else if (head && markup && inCode(text2, headEnd(text2))) {
46337
46487
  code.push(file);
46338
46488
  head = body = false;
46489
+ left = true;
46339
46490
  }
46340
46491
  if (head) heads.push({ file, source: text2 });
46492
+ else if (!amp.includes(file) && !code.includes(file) && loadsTag(file, text2))
46493
+ placed.push({ file, source: text2 });
46341
46494
  if (body) bodies.push({ file, source: text2 });
46342
46495
  const notice = body ? null : noticeKey(text2);
46343
46496
  if (notice) noticed.push({ file, key: notice, source: text2 });
46497
+ const key = head ? null : tagKey(text2);
46498
+ if (key) elsewhere.push(key);
46499
+ if (key && !left && !text2.includes(OURS)) tagged.push({ file, key, source: text2 });
46344
46500
  }
46501
+ const skipped = leftOut(amp, code, [...apart]);
46502
+ if (placed.length && !heads.some(({ source }) => hasTag(source)))
46503
+ return {
46504
+ framework,
46505
+ heads: [],
46506
+ bodies: bodies.filter(({ source }) => noticeKey(source)),
46507
+ creates: [],
46508
+ noticed,
46509
+ scoped: { files: placed, left: heads.map(({ file }) => file) },
46510
+ key: placed.map(({ source }) => tagKey(source)).find(Boolean) ?? elsewhere[0] ?? null,
46511
+ ...skipped && { skipped },
46512
+ ...apart.size && { apart: [...apart] }
46513
+ };
46345
46514
  const creates = [];
46346
46515
  if (deps.next && !heads.some(({ file }) => /(?:^|\/)app\//.test(file))) {
46347
46516
  if (!heads.some(({ file }) => /pages\/_document\./.test(file))) {
@@ -46363,10 +46532,10 @@ async function findHeads(dir) {
46363
46532
  });
46364
46533
  creates.push({ file: "gatsby-ssr.js", content: GATSBY_SSR, source: text2 });
46365
46534
  }
46366
- const skipped = leftOut(amp, code);
46535
+ const only = PAGES[framework] ? ` For ${framework}, it reads only ${PAGES[framework][1]}, as ${framework} makes no page of any other HTML file.` : "";
46367
46536
  if (!heads.length && !creates.length)
46368
46537
  return byHand(dir, list2, framework, {
46369
- reason: skipped ? `init found no <head> it can put the tag in. ${skipped}` : `init found no <head> to put the tag in. It looks in this folder${git ? ", leaving out what git ignores," : ""} for templates that close a </head> (${EXTENSIONS.map((ext) => "." + ext).join(", ")}) and for the root layouts of Next.js, Remix, React Router, TanStack Start and Gatsby. A head that comes from a theme or a package needs its template copied into the project first.`,
46538
+ reason: skipped ? `init found no <head> it can put the tag in. ${skipped}` : `init found no <head> to put the tag in. It looks in this folder${git ? ", leaving out what git ignores," : ""} for templates that close a </head> (${EXTENSIONS.map((ext) => "." + ext).join(", ")}) and for the root layouts of Next.js, Remix, React Router, TanStack Start and Gatsby.${only} A head that comes from a theme or a package needs its template copied into the project first.`,
46370
46539
  how: "Add this line by hand, last in the <head> of the layout or template every page uses",
46371
46540
  none: true
46372
46541
  });
@@ -46377,12 +46546,18 @@ async function findHeads(dir) {
46377
46546
  bodies,
46378
46547
  creates,
46379
46548
  noticed,
46380
- key: sources.map(tagKey).find(Boolean) ?? null,
46381
- ...skipped && { skipped }
46549
+ tagged,
46550
+ key: sources.map(tagKey).find(Boolean) ?? elsewhere[0] ?? null,
46551
+ ...skipped && { skipped },
46552
+ ...apart.size && { apart: [...apart] }
46382
46553
  };
46383
46554
  }
46384
- function leftOut(amp, code) {
46385
- const names = (files2) => files2.slice(0, 5).join(", ") + (files2.length > 5 ? " and others" : "");
46555
+ var names = (files2) => files2.slice(0, 5).join(", ") + (files2.length > 5 ? " and others" : "");
46556
+ function otherApps(folders) {
46557
+ if (!folders.length) return null;
46558
+ return folders.length === 1 ? `init left out ${folders[0]}, which has a package.json of its own, as another app. If its pages are this site's too, run init in that folder.` : `init left out ${names(folders)}, which have a package.json of their own, as other apps. If the pages of one are this site's too, run init in its folder.`;
46559
+ }
46560
+ function leftOut(amp, code, packages) {
46386
46561
  const said3 = [];
46387
46562
  if (amp.length)
46388
46563
  said3.push(`init left out ${names(amp)}: AMP pages allow no script of ours, so they get no tag.`);
@@ -46390,10 +46565,13 @@ function leftOut(amp, code) {
46390
46565
  said3.push(
46391
46566
  `init left out ${names(code)}, whose head is printed by server code, such as PHP's echo, where the tag's quotes would end a string. Add the tag there by hand, outside the string, or written so that the code prints its quotes as they are.`
46392
46567
  );
46568
+ const apart = otherApps(packages);
46569
+ if (apart) said3.push(apart);
46393
46570
  return said3.length ? said3.join(" ") : null;
46394
46571
  }
46395
46572
 
46396
46573
  // cli/frameworks.mts
46574
+ var import_parser5 = __toESM(require_lib(), 1);
46397
46575
  import { readFile as readFile3, stat as stat3 } from "node:fs/promises";
46398
46576
  import path3 from "node:path";
46399
46577
 
@@ -56843,10 +57021,10 @@ function addImport(source, line) {
56843
57021
  const end = last.index + last[0].length;
56844
57022
  return source.slice(0, end) + eolOf(source) + line + source.slice(end);
56845
57023
  }
56846
- function importLine(source, names, from) {
57024
+ function importLine(source, names2, from) {
56847
57025
  const last = lastMatch(source, IMPORT)?.[0] ?? `import x from '';`;
56848
57026
  const quote = last.match(/['"]/)?.[0] ?? "'";
56849
- return `import ${names} from ${quote}${from}${quote}${last.trimEnd().endsWith(";") ? ";" : ""}`;
57027
+ return `import ${names2} from ${quote}${from}${quote}${last.trimEnd().endsWith(";") ? ";" : ""}`;
56850
57028
  }
56851
57029
  var MARKUP2 = /\.(?:html?|tmpl|tpl|gohtml|ejs|hbs|handlebars|mustache|njk|liquid|twig|jinja2?|j2|eta|pug)$/i;
56852
57030
  function cleaned(found, markup = MARKUP2) {
@@ -56862,7 +57040,18 @@ async function own(p, file, content) {
56862
57040
  return { file, content, source };
56863
57041
  }
56864
57042
  var keyOf = (sources) => sources.map((source) => source ? tagKey(source) : null).find(Boolean) ?? null;
56865
- function result(p, framework, { creates, edits, heads = [], bodies = [], note, line }) {
57043
+ function result(p, framework, {
57044
+ creates,
57045
+ edits,
57046
+ heads = [],
57047
+ bodies = [],
57048
+ note,
57049
+ line,
57050
+ tagged = p.found.tagged ?? [],
57051
+ key = null,
57052
+ scoped
57053
+ }) {
57054
+ const writes = (file) => [...creates, ...edits ?? []].some((made) => made.file === file);
56866
57055
  return {
56867
57056
  framework,
56868
57057
  heads,
@@ -56870,14 +57059,23 @@ function result(p, framework, { creates, edits, heads = [], bodies = [], note, l
56870
57059
  creates,
56871
57060
  edits,
56872
57061
  line,
57062
+ ...scoped && { scoped },
56873
57063
  // Not the file init writes, which holds a copy of the notice.
56874
- noticed: (p.found.noticed ?? []).filter(({ file }) => !creates.some((create) => create.file === file)),
57064
+ noticed: (p.found.noticed ?? []).filter(({ file }) => !writes(file)),
57065
+ tagged: tagged.filter(({ file }) => !writes(file)),
56875
57066
  note,
56876
- key: keyOf([
57067
+ // Of what findHeads left out, only the other apps, which a run of init
57068
+ // in their own folder would set up. The framework's own pages are the
57069
+ // file's, which puts the lines in them as they go out.
57070
+ skipped: otherApps(p.found.apart ?? []) ?? void 0,
57071
+ // `key` when the framework names one, else the site init's files or the
57072
+ // pages name, else the one a tag elsewhere in the site's code names
57073
+ // (findHeads).
57074
+ key: key ?? keyOf([
56877
57075
  ...creates.map(({ source }) => source),
56878
57076
  ...(edits ?? []).map(({ source }) => source),
56879
57077
  ...heads.map(({ source }) => source)
56880
- ])
57078
+ ]) ?? p.found.key
56881
57079
  };
56882
57080
  }
56883
57081
  var NOTE = {
@@ -57045,13 +57243,99 @@ function fastifyEntry(source, cjs, from) {
57045
57243
  if (call === void 0) return null;
57046
57244
  return chained(source, call, ".addHook('onSend', agentface)", cjs, from, required?.index);
57047
57245
  }
57246
+ var FASTIFY_STATIC = /^(?:@fastify\/static|fastify-static)$/;
57247
+ var STATIC_NAMED = /(['"])(?:@fastify\/static|fastify-static)\1/;
57248
+ function* nodesOf(node2) {
57249
+ if (Array.isArray(node2)) for (const item of node2) yield* nodesOf(item);
57250
+ else if (node2 && typeof node2 === "object" && typeof node2.type === "string") {
57251
+ yield node2;
57252
+ for (const [key, value] of Object.entries(node2))
57253
+ if (key !== "loc" && !key.endsWith("Comments")) yield* nodesOf(value);
57254
+ }
57255
+ }
57256
+ function loadsStatic(node2) {
57257
+ if (node2?.type === "AwaitExpression") return loadsStatic(node2.argument);
57258
+ if (node2?.type !== "CallExpression") return false;
57259
+ const [name] = node2.arguments;
57260
+ const loads = node2.callee.type === "Import" || node2.callee.type === "Identifier" && node2.callee.name === "require";
57261
+ return loads && name?.type === "StringLiteral" && FASTIFY_STATIC.test(name.value);
57262
+ }
57263
+ function rootFolder(node2, file) {
57264
+ const here = posix.dirname(file) === "." ? "" : posix.dirname(file);
57265
+ const meta = (n, name2) => n.type === "MemberExpression" && n.object.type === "MetaProperty" && n.property.type === "Identifier" && n.property.name === name2;
57266
+ const start = (n) => n.type === "Identifier" && n.name === "__dirname" || meta(n, "dirname") ? here : n.type === "CallExpression" && n.callee.type === "MemberExpression" && n.callee.object.type === "Identifier" && n.callee.object.name === "process" && n.callee.property.type === "Identifier" && n.callee.property.name === "cwd" ? "" : null;
57267
+ const inside = (folder) => {
57268
+ const normal2 = posix.normalize(folder || ".");
57269
+ return normal2 === "." ? "" : /^(?:\.\.(?:\/|$)|\/)/.test(normal2) ? null : normal2.replace(/\/$/, "");
57270
+ };
57271
+ if (node2.type === "StringLiteral") return node2.value.startsWith("/") ? null : inside(node2.value);
57272
+ if (node2.type !== "CallExpression") return null;
57273
+ const { callee } = node2;
57274
+ const name = callee.type === "Identifier" ? callee.name : callee.type === "MemberExpression" && callee.property.type === "Identifier" ? callee.property.name : null;
57275
+ const args = node2.arguments;
57276
+ if (name === "join" || name === "resolve") {
57277
+ const from = args[0] ? start(args[0]) : null;
57278
+ const parts = from === null ? args : args.slice(1);
57279
+ const words = parts.map((part) => part.type === "StringLiteral" ? part.value : null);
57280
+ if (words.some((word) => word === null || name === "resolve" && word.startsWith("/"))) return null;
57281
+ return inside(posix.join(from ?? "", ...words));
57282
+ }
57283
+ const [url] = args;
57284
+ if (name === "fileURLToPath" && url?.type === "NewExpression") {
57285
+ const [where, base] = url.arguments;
57286
+ if (where?.type === "StringLiteral" && base && meta(base, "url"))
57287
+ return inside(posix.join(here, where.value));
57288
+ }
57289
+ return null;
57290
+ }
57291
+ async function staticRoots(p, code) {
57292
+ const roots = /* @__PURE__ */ new Set();
57293
+ const unknown = /* @__PURE__ */ new Set();
57294
+ for (const file of code) {
57295
+ const source = await p.read(file);
57296
+ if (!source || !STATIC_NAMED.test(source)) continue;
57297
+ let tree;
57298
+ try {
57299
+ tree = (0, import_parser5.parse)(source, { sourceType: "unambiguous", plugins: ["typescript", "jsx"] });
57300
+ } catch {
57301
+ unknown.add(file);
57302
+ continue;
57303
+ }
57304
+ const names2 = /* @__PURE__ */ new Set();
57305
+ for (const node2 of nodesOf(tree)) {
57306
+ if (node2.type === "ImportDeclaration" && FASTIFY_STATIC.test(node2.source.value))
57307
+ for (const specifier of node2.specifiers) names2.add(specifier.local.name);
57308
+ if (node2.type === "VariableDeclarator" && node2.id.type === "Identifier" && loadsStatic(node2.init))
57309
+ names2.add(node2.id.name);
57310
+ }
57311
+ for (const node2 of nodesOf(tree)) {
57312
+ if (node2.type !== "CallExpression" || node2.callee.type !== "MemberExpression" || node2.callee.property.type !== "Identifier" || node2.callee.property.name !== "register")
57313
+ continue;
57314
+ const [plugin, options] = node2.arguments;
57315
+ if (!(plugin?.type === "Identifier" ? names2.has(plugin.name) : loadsStatic(plugin))) continue;
57316
+ const root = options?.type === "ObjectExpression" ? options.properties.find(
57317
+ (property) => property.type === "ObjectProperty" && !property.computed && (property.key.type === "Identifier" && property.key.name === "root" || property.key.type === "StringLiteral" && property.key.value === "root")
57318
+ ) : void 0;
57319
+ const value = root?.type === "ObjectProperty" ? root.value : null;
57320
+ for (const folder of value?.type === "ArrayExpression" ? value.elements : [value]) {
57321
+ const at = folder && folder.type !== "SpreadElement" ? rootFolder(folder, file) : null;
57322
+ if (at === null) unknown.add(file);
57323
+ else roots.add(at);
57324
+ }
57325
+ }
57326
+ }
57327
+ return { roots: [...roots], unknown: [...unknown] };
57328
+ }
57048
57329
  async function fastify(p) {
57049
57330
  if (!p.deps.fastify) return null;
57050
57331
  const found = await entry(p, (source) => fastifyEntry(source, false, "") !== null);
57051
57332
  if (!found) return null;
57052
57333
  const made = await jsHelper(p, found.file, found.source, "fastify");
57053
57334
  if (!made || fastifyEntry(found.source, made.cjs, made.from) === null) return null;
57054
- const plain = ({ file }) => /\.html?$/i.test(file);
57335
+ const code = p.list.filter((file) => /\.(?:[cm]?[jt]sx?)$/.test(file) && !/\.d\.[cm]?ts$/.test(file));
57336
+ const { roots, unknown } = await staticRoots(p, code);
57337
+ const plain = ({ file }) => /\.html?$/i.test(file) && roots.some((folder) => !folder || file.startsWith(folder + "/"));
57338
+ const unsure = unknown.length ? ` init can't tell which folder ${unknown.join(", ")} ${unknown.length === 1 ? "serves" : "serve"} files from with @fastify/static, so it put the lines in no HTML file there: a page Fastify sends from that folder as it is needs the tag and the notice ${made.helper.file} holds, last in its <head> and first in its <body>.` : "";
57055
57339
  return result(p, "Fastify", {
57056
57340
  heads: p.found.heads.filter(plain),
57057
57341
  bodies: p.found.bodies.filter(plain),
@@ -57064,7 +57348,7 @@ async function fastify(p) {
57064
57348
  edit: (text2) => fastifyEntry(text2, made.cjs, made.from) ?? text2
57065
57349
  }
57066
57350
  ],
57067
- note: `${made.helper.file} asks Agentface for the tag and its notice as the app starts, and again once its copy is an hour old: when what they say changes, the pages change by themselves, with nothing to run or deploy. While Agentface can't be reached, the pages keep the lines they had. Plain HTML files, which Fastify sends as they are, keep the lines in them.`
57351
+ note: `${made.helper.file} asks Agentface for the tag and its notice as the app starts, and again once its copy is an hour old: when what they say changes, the pages change by themselves, with nothing to run or deploy. While Agentface can't be reached, the pages keep the lines they had. Plain HTML files, which Fastify sends as they are, keep the lines in them.${unsure}`
57068
57352
  });
57069
57353
  }
57070
57354
  var escaped = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -57249,6 +57533,7 @@ async function django(p) {
57249
57533
  if (!helper) return null;
57250
57534
  const { file, source } = settings;
57251
57535
  const templates = (template) => /(?:^|\/)templates\//.test(template);
57536
+ const raw = (page2) => /(?:^|\/)static\//.test(page2);
57252
57537
  return result(p, "Django", {
57253
57538
  creates: [helper],
57254
57539
  edits: [
@@ -57259,8 +57544,8 @@ async function django(p) {
57259
57544
  }),
57260
57545
  { file, source, edit: (text2) => middlewareList(text2) ?? text2 }
57261
57546
  ],
57262
- heads: p.found.heads.filter(({ file: file2 }) => !templates(file2)),
57263
- bodies: p.found.bodies.filter(({ file: file2 }) => !templates(file2)),
57547
+ heads: p.found.heads.filter(({ file: file2 }) => raw(file2)),
57548
+ bodies: p.found.bodies.filter(({ file: file2 }) => raw(file2)),
57264
57549
  note: `${NOTE.request(helper.file)} It's a middleware, first in ${file}'s MIDDLEWARE, which puts them in every HTML page Django sends whole.`
57265
57550
  });
57266
57551
  }
@@ -57297,6 +57582,7 @@ async function fastapi(p) {
57297
57582
  const helper = await own(p, folder + "agentface.py", ASGI);
57298
57583
  if (!helper) return null;
57299
57584
  const templates = (template) => /(?:^|\/)templates\//.test(template);
57585
+ const raw = (page2) => /(?:^|\/)static\//.test(page2);
57300
57586
  return result(p, "FastAPI", {
57301
57587
  creates: [helper],
57302
57588
  edits: [
@@ -57307,8 +57593,8 @@ async function fastapi(p) {
57307
57593
  }),
57308
57594
  { file, source, edit: (text2) => fastapiModule(text2, imported) ?? text2 }
57309
57595
  ],
57310
- heads: p.found.heads.filter(({ file: file2 }) => !templates(file2)),
57311
- bodies: p.found.bodies.filter(({ file: file2 }) => !templates(file2)),
57596
+ heads: p.found.heads.filter(({ file: file2 }) => raw(file2)),
57597
+ bodies: p.found.bodies.filter(({ file: file2 }) => raw(file2)),
57312
57598
  note: `${NOTE.request(helper.file)} ${file} adds it as the app's middleware, which puts them in every HTML page the app sends whole.`
57313
57599
  });
57314
57600
  }
@@ -57316,6 +57602,7 @@ async function rails(p) {
57316
57602
  if (!/^\s*gem\s+['"]rails['"]/m.test(await p.read("Gemfile") ?? "")) return null;
57317
57603
  const views = ({ file }) => file.startsWith("app/views/");
57318
57604
  if (!p.found.heads.some(views)) return null;
57605
+ const raw = ({ file }) => file.startsWith("public/");
57319
57606
  const helper = await own(p, "config/initializers/agentface.rb", RAILS);
57320
57607
  if (!helper) return null;
57321
57608
  return result(p, "Rails", {
@@ -57324,8 +57611,8 @@ async function rails(p) {
57324
57611
  { ...p.found, heads: p.found.heads.filter(views), bodies: p.found.bodies.filter(views) },
57325
57612
  /\.erb$/
57326
57613
  ),
57327
- heads: p.found.heads.filter((head) => !views(head)),
57328
- bodies: p.found.bodies.filter((body) => !views(body)),
57614
+ heads: p.found.heads.filter(raw),
57615
+ bodies: p.found.bodies.filter(raw),
57329
57616
  note: `${NOTE.request(helper.file)} It adds a Rack middleware that puts them in every HTML page Rails sends whole; the pages in public/ keep the lines in them. With a nonce in the site's Content Security Policy, the tag carries the page's.`
57330
57617
  });
57331
57618
  }
@@ -57349,6 +57636,7 @@ async function phoenix(p) {
57349
57636
  if (!mix || !/\{:phoenix,/.test(mix) || mixApplications(mix) === null) return null;
57350
57637
  const heex = ({ file: file2 }) => file2.endsWith(".heex");
57351
57638
  if (!p.found.heads.some(heex)) return null;
57639
+ const raw = ({ file: file2 }) => file2.startsWith("priv/static/");
57352
57640
  let endpoint = null;
57353
57641
  for (const file2 of p.list.filter((file3) => file3.startsWith("lib/") && file3.endsWith(".ex"))) {
57354
57642
  const source2 = await p.read(file2);
@@ -57371,8 +57659,8 @@ async function phoenix(p) {
57371
57659
  { file, source, edit: (text2) => endpointPlug(text2) ?? text2 },
57372
57660
  { file: "mix.exs", source: mix, edit: (text2) => mixApplications(text2) ?? text2 }
57373
57661
  ],
57374
- heads: p.found.heads.filter((head) => !heex(head)),
57375
- bodies: p.found.bodies.filter((body) => !heex(body)),
57662
+ heads: p.found.heads.filter(raw),
57663
+ bodies: p.found.bodies.filter(raw),
57376
57664
  note: `${NOTE.request(helper.file)} ${file} plugs it in before the router, which puts them in every HTML page it sends whole, and mix.exs starts :inets and :ssl for it, which it asks with.`
57377
57665
  });
57378
57666
  }
@@ -57459,6 +57747,85 @@ async function go(p) {
57459
57747
  var NEXT_TAG = "<AgentfaceTag />";
57460
57748
  var NEXT_TAG_USED = new RegExp(`<AgentfaceTag\\b${ATTRIBUTES2}\\/>`);
57461
57749
  var NEXT_NOTICE = "<AgentfaceNotice />";
57750
+ var NEXT_USES = {
57751
+ AgentfaceNotice: (text2) => text2.includes(NEXT_NOTICE),
57752
+ AgentfaceTag: (text2) => NEXT_TAG_USED.test(text2)
57753
+ };
57754
+ var NEXT_NAMES = Object.keys(NEXT_USES);
57755
+ function nextComponentsFile(list2) {
57756
+ const src = list2.some((file) => /^src\/(?:app|pages)\//.test(file));
57757
+ return `${src ? "src/" : ""}components/agentface.${list2.includes("tsconfig.json") ? "tsx" : "jsx"}`;
57758
+ }
57759
+ function looseJson(text2) {
57760
+ let json2 = "";
57761
+ for (let at = 0; at < text2.length; at++) {
57762
+ if (text2[at] === '"') {
57763
+ const string = /"(?:[^"\\\n]|\\.)*"/y;
57764
+ string.lastIndex = at;
57765
+ const quoted = string.exec(text2)?.[0];
57766
+ if (!quoted) return null;
57767
+ json2 += quoted;
57768
+ at += quoted.length - 1;
57769
+ } else if (text2.startsWith("//", at)) {
57770
+ const end = text2.indexOf("\n", at);
57771
+ if (end === -1) break;
57772
+ at = end - 1;
57773
+ } else if (text2.startsWith("/*", at)) {
57774
+ const end = text2.indexOf("*/", at + 2);
57775
+ if (end === -1) return null;
57776
+ at = end + 1;
57777
+ } else json2 += text2[at];
57778
+ }
57779
+ try {
57780
+ return JSON.parse(json2.replace(/,(\s*[}\]])/g, "$1"));
57781
+ } catch {
57782
+ return null;
57783
+ }
57784
+ }
57785
+ async function aliasesOf(dir, list2) {
57786
+ const config2 = ["tsconfig.json", "jsconfig.json"].find((name) => list2.includes(name));
57787
+ if (!config2) return null;
57788
+ const read2 = looseJson(await readFile3(path3.join(dir, config2), "utf8").catch(() => null) ?? "");
57789
+ const options = read2?.compilerOptions;
57790
+ if (!options?.paths) return null;
57791
+ const paths = Object.entries(options.paths).map(([name, to]) => [
57792
+ name,
57793
+ Array.isArray(to) ? to.filter((at) => typeof at === "string") : []
57794
+ ]).sort(([a], [b]) => b.length - a.length);
57795
+ return { base: typeof options.baseUrl === "string" ? options.baseUrl : ".", paths };
57796
+ }
57797
+ function importBases(aliases, file, from) {
57798
+ if (/^\.\.?\//.test(from)) return [posix.join(posix.dirname(file), from)];
57799
+ for (const [name, to] of aliases?.paths ?? []) {
57800
+ const star = name.endsWith("*");
57801
+ const start = star ? name.slice(0, -1) : name;
57802
+ if (star ? from.startsWith(start) : from === name)
57803
+ return to.map((at) => posix.join(aliases.base, star ? at.replace("*", from.slice(start.length)) : at));
57804
+ }
57805
+ const bare2 = from.replace(/^[@~#]*\//, "");
57806
+ return bare2 !== from ? [`src/${bare2}`, bare2] : [];
57807
+ }
57808
+ var EXTENSIONS2 = ["tsx", "ts", "jsx", "js", "mjs", "cjs"];
57809
+ function importedFile(list2, aliases, file, from) {
57810
+ for (const base of importBases(aliases, file, from))
57811
+ for (const name of [base, ...EXTENSIONS2.flatMap((ext) => [`${base}.${ext}`, `${base}/index.${ext}`])])
57812
+ if (list2.includes(name)) return name;
57813
+ return null;
57814
+ }
57815
+ async function oursIn(dir, list2) {
57816
+ const aliases = await aliasesOf(dir, list2);
57817
+ const ours = nextComponentsFile(list2).replace(/\.[jt]sx$/, "");
57818
+ const bare2 = (name) => name.replace(/\.[cm]?[jt]sx?$/, "");
57819
+ return (file, from) => {
57820
+ if (from === null) return false;
57821
+ const found = importedFile(list2, aliases, file, from);
57822
+ return found ? bare2(found) === ours : importBases(aliases, file, from).includes(ours);
57823
+ };
57824
+ }
57825
+ function sitesOwn(source, file, ours) {
57826
+ const names2 = topNames(source);
57827
+ return new Set(NEXT_NAMES.filter((name) => (names2.get(name) ?? []).some((from) => !ours(file, from))));
57828
+ }
57462
57829
  function nextTag(old) {
57463
57830
  const kept = old ? ownersAttributes(old) : [];
57464
57831
  return kept.length ? `<AgentfaceTag ${kept.join(" ")} />` : NEXT_TAG;
@@ -57618,11 +57985,29 @@ export default function Document() {
57618
57985
  );
57619
57986
  }
57620
57987
  `;
57621
- var NEXT_IMPORTED = /^import\s*\{\s*AgentfaceNotice,\s*AgentfaceTag,?\s*\}\s*from ['"][^'"]*agentface['"];?/;
57622
- function nextImport(source, from) {
57623
- if (new RegExp(NEXT_IMPORTED.source, "m").test(source)) return source;
57624
- const line = importLine(source, NEXT_IMPORT, from);
57625
- if (source.includes(line) || lastMatch(source, IMPORT)) return addImport(source, line);
57988
+ var NEXT_IMPORTED = /^import\s*\{\s*(Agentface(?:Notice|Tag))\s*(?:,\s*(Agentface(?:Notice|Tag))\s*)?,?\s*\}\s*from\s*(['"])([^'"\n]+)\3(;?)/gm;
57989
+ var nextImported = (source, file, ours) => [...source.matchAll(NEXT_IMPORTED)].find((match) => ours(file, match[4])) ?? null;
57990
+ function withoutImport(source, imported) {
57991
+ const rest = source.slice(imported.index + imported[0].length).replace(/^[ \t]*\r?\n/, "");
57992
+ return source.slice(0, imported.index) + (imported.index === 0 ? rest.replace(/^\r?\n/, "") : rest);
57993
+ }
57994
+ function nextImport(source, from, file, ours) {
57995
+ const names2 = topNames(source);
57996
+ const own2 = sitesOwn(source, file, ours);
57997
+ const imported = nextImported(source, file, ours);
57998
+ const had = imported ? [imported[1], imported[2]].filter(Boolean) : [];
57999
+ const wanted = NEXT_NAMES.filter(
58000
+ (name) => !own2.has(name) && (had.includes(name) || NEXT_USES[name](source) && !names2.has(name))
58001
+ );
58002
+ if (imported) {
58003
+ if (wanted.length === had.length && wanted.every((name) => had.includes(name))) return source;
58004
+ if (!wanted.length) return withoutImport(source, imported);
58005
+ const [written, , , quote, where, semicolon] = imported;
58006
+ return source.slice(0, imported.index) + `import { ${wanted.join(", ")} } from ${quote}${where}${quote}${semicolon}` + source.slice(imported.index + written.length);
58007
+ }
58008
+ if (!wanted.length) return source;
58009
+ const line = importLine(source, `{ ${wanted.join(", ")} }`, from);
58010
+ if (lastMatch(source, IMPORT)) return addImport(source, line);
57626
58011
  return line + eolOf(source) + eolOf(source) + source;
57627
58012
  }
57628
58013
  var REQUIRE = /^(?:const|let|var)\s[^\n]*=\s*require\([^\n]*\)[^\n]*$/gm;
@@ -57672,11 +58057,15 @@ function relative(from, to) {
57672
58057
  const rel = posix.relative(posix.dirname(from), to);
57673
58058
  return rel.startsWith(".") ? rel : "./" + rel;
57674
58059
  }
57675
- var nextCalls = (head, body, from) => (source, withNotice) => {
57676
- let text2 = removeTag(source) ?? source;
57677
- if (head && !NEXT_TAG_USED.test(text2)) text2 = addTag(text2, nextTag(linesIn(source).tag)) ?? text2;
57678
- if (body && withNotice && !text2.includes(NEXT_NOTICE)) text2 = addNotice(text2, NEXT_NOTICE) ?? text2;
57679
- return NEXT_TAG_USED.test(text2) || text2.includes(NEXT_NOTICE) ? nextImport(text2, from) : text2;
58060
+ var nextCalls = (head, body, from, file, ours) => (source, withNotice) => {
58061
+ const own2 = sitesOwn(source, file, ours);
58062
+ const tag = own2.has("AgentfaceTag");
58063
+ const notice = own2.has("AgentfaceNotice");
58064
+ let text2 = removeTag(source, { tag, notice }) ?? source;
58065
+ if (head && !tag && !NEXT_TAG_USED.test(text2)) text2 = addTag(text2, nextTag(linesIn(source).tag)) ?? text2;
58066
+ if (body && withNotice && !notice && !text2.includes(NEXT_NOTICE))
58067
+ text2 = addNotice(text2, NEXT_NOTICE) ?? text2;
58068
+ return nextImport(text2, from, file, ours);
57680
58069
  };
57681
58070
  function layouts(p, mine, edit) {
57682
58071
  const files2 = /* @__PURE__ */ new Map();
@@ -57699,12 +58088,12 @@ function layouts(p, mine, edit) {
57699
58088
  }
57700
58089
  async function next(p) {
57701
58090
  if (!p.deps.next) return null;
57702
- const src = p.list.some((file2) => /^src\/(?:app|pages)\//.test(file2));
57703
- const ts = p.list.includes("tsconfig.json");
57704
- const file = `${src ? "src/" : ""}components/agentface.${ts ? "tsx" : "jsx"}`;
57705
- const components = await own(p, file, ts ? NEXT_COMPONENTS_TS : NEXT_COMPONENTS);
58091
+ const file = nextComponentsFile(p.list);
58092
+ const components = await own(p, file, file.endsWith(".tsx") ? NEXT_COMPONENTS_TS : NEXT_COMPONENTS);
57706
58093
  if (!components) return null;
57707
58094
  const from = (at) => relative(at, file.replace(/\.[jt]sx$/, ""));
58095
+ const ours = await oursIn(p.dir, p.list);
58096
+ const aliases = await aliasesOf(p.dir, p.list);
57708
58097
  const document2 = /(?:^|\/)pages\/_document\.js$/;
57709
58098
  const written = p.found.heads.filter((head) => document2.test(head.file) && removeTag(head.source) === null);
57710
58099
  const documents = [...p.found.creates.filter((create) => document2.test(create.file)), ...written].map(
@@ -57714,27 +58103,76 @@ async function next(p) {
57714
58103
  source
57715
58104
  })
57716
58105
  );
58106
+ const isLayout = (name) => NEXT_LAYOUT.test(name) && !written.some((head) => head.file === name);
58107
+ const sources = new Map([...p.found.heads, ...p.found.bodies].map(({ file: file2, source }) => [file2, source]));
58108
+ const all = [...sources.keys()].filter(isLayout);
58109
+ const withTag = all.filter((file2) => hasTag(sources.get(file2)));
58110
+ const placed = p.found.scoped?.files ?? [];
58111
+ const scoped = placed.length > 0 || (withTag.length > 0 || written.length > 0) && withTag.length < all.length;
58112
+ const left = scoped ? [.../* @__PURE__ */ new Set([...p.found.scoped?.left ?? [], ...all.filter((file2) => !withTag.includes(file2))])] : [];
57717
58113
  const {
57718
- edits,
58114
+ edits: every,
57719
58115
  heads: rest,
57720
58116
  bodies
57721
58117
  } = layouts(
57722
58118
  p,
57723
- (name) => NEXT_LAYOUT.test(name) && !written.some((head) => head.file === name),
57724
- (layout) => nextCalls(layout.head, layout.body, from(layout.file))
58119
+ isLayout,
58120
+ (layout) => nextCalls(layout.head, layout.body, from(layout.file), layout.file, ours)
57725
58121
  );
57726
- if (!edits.length && !documents.length) return null;
57727
- const line = { file, code: p.list.filter((name) => JSX_CODE.test(name)) };
58122
+ const edits = every.filter(({ file: file2 }) => !left.includes(file2));
58123
+ const rendersOurs = placed.some(
58124
+ ({ file: at, source }) => NEXT_TAG_USED.test(source) && (topNames(source).get("AgentfaceTag") ?? []).some((name) => ours(at, name))
58125
+ );
58126
+ if (!edits.length && !documents.length && !rendersOurs) return null;
57728
58127
  const config2 = NEXT_CONFIGS.find((name) => p.list.includes(name));
57729
58128
  const settings = config2 ? await p.read(config2) : null;
57730
- const ask = await own(p, NEXT_HELPER, (tag) => {
57731
- const { service, site } = siteOf(tag);
58129
+ const ask = await own(p, NEXT_HELPER, (tag2) => {
58130
+ const { service, site } = siteOf(tag2);
57732
58131
  return NEXT_ASK(service, site);
57733
58132
  });
57734
58133
  const types = config2?.endsWith("ts") ? await own(p, NEXT_TYPES, () => NEXT_ASK_TYPES) : null;
57735
58134
  const made = !config2 ? await own(p, NEXT_NEW_CONFIG, () => NEXT_CONFIG) : null;
57736
58135
  const asks = ask && (config2 ? settings !== null && nextConfig(settings) !== null && types !== void 0 : made !== void 0);
57737
- const what = `${file} renders the tag, its notice and the same notice at the end of each page's first paragraph, for agents that read pages through Exa`;
58136
+ const owned = edits.map(({ file: at, source }) => ({ at, source, own: sitesOwn(source, at, ours) }));
58137
+ const is = (list2, at) => list2.some((found) => found.file === at);
58138
+ const tag = documents.length > 0 || owned.some(({ at, own: own2 }) => is(p.found.heads, at) && !own2.has("AgentfaceTag"));
58139
+ const notice = documents.length > 0 || owned.some(({ at, own: own2 }) => is(p.found.bodies, at) && !own2.has("AgentfaceNotice"));
58140
+ const renders = tag ? notice ? "the tag, its notice and the same notice" : "the tag, and its notice" : notice ? "the tag's notice, and the same notice" : "the tag's notice";
58141
+ const only = scoped || owned.some(({ own: own2 }) => own2.has("AgentfaceTag"));
58142
+ const line = { file, code: p.list.filter((name) => JSX_CODE.test(name)), ...only && { scoped: true } };
58143
+ const where = only ? "the first paragraph of each page that loads the tag" : "each page's first paragraph";
58144
+ const what = scoped ? `${file} renders the tag and its notice where the site's code uses them, and the same notice at the end of ${where}, for agents that read pages through Exa` : `${file} renders ${renders} at the end of ${where}, for agents that read pages through Exa`;
58145
+ const theirs = owned.map(({ at, own: own2 }) => {
58146
+ const names2 = ["AgentfaceTag", "AgentfaceNotice"].filter((name) => own2.has(name));
58147
+ if (!names2.length) return "";
58148
+ const one = names2.length === 1;
58149
+ const lines = names2.map((name) => name === "AgentfaceTag" ? "tag" : "notice").join(" and the ");
58150
+ return ` ${at} renders ${names2.map((name) => `an ${name}`).join(" and ")} of the site's own, not ${one ? "the one" : "those"} in ${file}, so init left ${one ? "it as it is" : "them as they are"}: the ${lines} ${one ? "it renders keeps" : "they render keep"} saying what ${one ? "it says" : "they say"} now, whatever Agentface says later. To have ${one ? `that ${lines}` : "them"} change with the next deploy too, render the ${names2.join(" and ")} of ${file} in ${one ? "its" : "their"} place.`;
58151
+ }).join("");
58152
+ const fileOf = (at, from2) => importedFile(p.list, aliases, at, from2);
58153
+ const theirTags = owned.map(
58154
+ ({ at, source, own: own2 }) => own2.has("AgentfaceTag") ? (topNames(source).get("AgentfaceTag") ?? []).filter((from2) => !ours(at, from2)).flatMap((from2) => {
58155
+ if (from2 !== null) return [fileOf(at, from2)];
58156
+ const loads = [...source.matchAll(/\bimport\(\s*(['"])([^'"\n]+)\1\s*\)/g)];
58157
+ if (loads.length) return loads.map(([, , name]) => fileOf(at, name));
58158
+ return tagKey(source) ? [] : [null];
58159
+ }) : []
58160
+ );
58161
+ const needed = theirTags.flat();
58162
+ const near = new Set(
58163
+ owned.filter(({ at, own: own2 }) => is(p.found.heads, at) && !own2.has("AgentfaceTag")).flatMap(
58164
+ ({ at, source }) => [...topNames(source).values()].flat().map((from2) => from2 === null ? null : fileOf(at, from2))
58165
+ )
58166
+ );
58167
+ const tagged = tag && !scoped ? (p.found.tagged ?? []).filter(
58168
+ ({ file: name }) => !needed.includes(name) && (!needed.includes(null) || near.has(name))
58169
+ ) : [];
58170
+ const key = owned.flatMap(
58171
+ ({ source, own: own2 }, at) => own2.has("AgentfaceTag") ? [
58172
+ tagKey(source),
58173
+ ...theirTags[at].map((name) => p.found.tagged?.find((found) => found.file === name)?.key)
58174
+ ] : []
58175
+ ).find(Boolean) ?? null;
57738
58176
  return result(p, "Next.js", {
57739
58177
  creates: [
57740
58178
  components,
@@ -57748,7 +58186,12 @@ async function next(p) {
57748
58186
  heads: rest,
57749
58187
  bodies,
57750
58188
  line,
57751
- note: asks ? `${what}. ${config2 ?? NEXT_NEW_CONFIG} asks Agentface what they say each time the site is built (${NEXT_HELPER}): when that changes, the next deploy brings the change, with nothing to edit. While Agentface can't be reached, they say what init wrote.` : `${what}, in the words init wrote: init can't tell where ${config2}'s settings are, so it can't have the site ask Agentface for them as it is built. Run init again to bring them up to date.`
58189
+ tagged,
58190
+ key,
58191
+ ...scoped && {
58192
+ scoped: { files: [...placed, ...withTag.map((at) => ({ file: at, source: sources.get(at) }))], left }
58193
+ },
58194
+ note: (asks ? `${what}. ${config2 ?? NEXT_NEW_CONFIG} asks Agentface what they say each time the site is built (${NEXT_HELPER}): when that changes, the next deploy brings the change, with nothing to edit. While Agentface can't be reached, they say what init wrote.` : `${what}, in the words init wrote: init can't tell where ${config2}'s settings are, so it can't have the site ask Agentface for them as it is built. Run init again to bring them up to date.`) + theirs
57752
58195
  });
57753
58196
  }
57754
58197
  var WRITERS = [
@@ -57782,11 +58225,13 @@ var FRAMEWORKS2 = [rails, phoenix, django, fastapi, go, next, astro, hono, fasti
57782
58225
  async function withFramework(dir, found) {
57783
58226
  if (found.manual && !found.manual.none) return found;
57784
58227
  if (["WordPress", "PrestaShop", "PrestaShop theme"].includes(found.framework)) return found;
57785
- const { deps, list: list2 } = await project(dir);
58228
+ const { deps, list: all } = await project(dir);
58229
+ const packages = otherPackages(all);
58230
+ const list2 = all.filter((file) => !packages.some((folder) => file.startsWith(folder)));
57786
58231
  const read2 = (file) => readFile3(path3.join(dir, file), "utf8").catch(() => null);
57787
58232
  const p = { dir, deps, list: list2, found, read: read2 };
57788
58233
  let selected = found;
57789
- for (const framework of FRAMEWORKS2) {
58234
+ for (const framework of found.scoped ? [next] : FRAMEWORKS2) {
57790
58235
  const made = await framework(p);
57791
58236
  if (made) {
57792
58237
  selected = made;
@@ -57806,10 +58251,7 @@ var UNDO = [
57806
58251
  ".use(agentface())",
57807
58252
  ".addHook('onSend', agentface)",
57808
58253
  /^[ \t]*\w+\.add_middleware\(agentface\.Middleware\)/,
57809
- /(?:^\r?\n)?^(?:from \. import agentface|import agentface)$/,
57810
- NEXT_TAG_USED,
57811
- NEXT_NOTICE,
57812
- new RegExp(NEXT_IMPORTED.source.slice(1), "m")
58254
+ /(?:^\r?\n)?^(?:from \. import agentface|import agentface)$/
57813
58255
  ];
57814
58256
  function unwrapped(text2) {
57815
58257
  for (let at; (at = text2.search(/(?<![\w$.])agentface\((?!\s*\))/)) !== -1; ) {
@@ -57822,6 +58264,7 @@ function unwrapped(text2) {
57822
58264
  }
57823
58265
  async function undoFrameworks(dir) {
57824
58266
  const { list: list2 } = await project(dir);
58267
+ const ours = await oursIn(dir, list2);
57825
58268
  const edits = [];
57826
58269
  const deletes = [];
57827
58270
  const keep = /* @__PURE__ */ new Set();
@@ -57843,8 +58286,12 @@ async function undoFrameworks(dir) {
57843
58286
  }
57844
58287
  continue;
57845
58288
  }
57846
- let text2 = source.replace(new RegExp(`${NEXT_IMPORTED.source}\\r?\\n\\r?\\n`), "");
58289
+ const imported = nextImported(source, file, ours);
58290
+ let text2 = imported ? withoutImport(source, imported) : source;
57847
58291
  text2 = UNDO.reduce((done, piece) => without(done, piece), text2);
58292
+ const own2 = /<Agentface(?:Tag|Notice)\b/.test(source) ? sitesOwn(source, file, ours) : /* @__PURE__ */ new Set();
58293
+ if (!own2.has("AgentfaceTag")) text2 = without(text2, NEXT_TAG_USED);
58294
+ if (!own2.has("AgentfaceNotice")) text2 = without(text2, NEXT_NOTICE);
57848
58295
  text2 = text2.replace(/^[ \t]*['"]agentface\.Middleware['"],[ \t]*\r?\n/m, "").replace(/['"]agentface\.Middleware['"],\s*/, "").replace(/,\s*['"]agentface\.Middleware['"]/, "");
57849
58296
  if (NEXT_CONFIGS.includes(file)) text2 = withoutNextConfig(text2);
57850
58297
  if (IMPORTED.test(source) || REQUIRED.test(source)) text2 = unwrapped(text2);
@@ -57901,6 +58348,7 @@ function decodeEntities(s) {
57901
58348
 
57902
58349
  // worker/http.ts
57903
58350
  var USER_AGENT = "AgentfaceFetcher/0.1 (+https://agentface.com)";
58351
+ var HOMEPAGE_BYTES = 2e6;
57904
58352
  async function readStart(response, limit) {
57905
58353
  if (!response.body) return "";
57906
58354
  const reader = response.body.getReader();
@@ -57914,9 +58362,9 @@ async function readStart(response, limit) {
57914
58362
  }
57915
58363
  await reader.cancel().catch(() => {
57916
58364
  });
57917
- return new TextDecoder().decode(concat(chunks, length).subarray(0, limit));
58365
+ return new TextDecoder().decode(concat2(chunks, length).subarray(0, limit));
57918
58366
  }
57919
- function concat(chunks, length) {
58367
+ function concat2(chunks, length) {
57920
58368
  const bytes = new Uint8Array(length);
57921
58369
  let offset = 0;
57922
58370
  for (const chunk of chunks) {
@@ -57992,7 +58440,7 @@ function sourceMatches(source, url, page2) {
57992
58440
  }
57993
58441
  var keyword = (sources, word) => sources.some((source) => source.toLowerCase() === word);
57994
58442
  var hasNonce = (sources, nonce) => sources.some((source) => /^'nonce-/i.test(source) && source.slice(7, -1) === nonce && source.endsWith("'"));
57995
- var governing = (policy, names) => names.find((name) => policy.directives.has(name));
58443
+ var governing = (policy, names2) => names2.find((name) => policy.directives.has(name));
57996
58444
  function fix(policy, decides, name, origin) {
57997
58445
  const sources = policy.directives.get(decides).filter((source) => source.toLowerCase() !== "'none'");
57998
58446
  return { name, line: [name, ...sources, origin].join(" "), created: decides !== name };
@@ -58031,8 +58479,8 @@ var WHERE = {
58031
58479
  header: "In the Content-Security-Policy header the site sends with its pages",
58032
58480
  meta: "In the Content-Security-Policy <meta> tag in the head of its pages"
58033
58481
  };
58034
- var and = (names) => names.join(" and ");
58035
- var or = (names) => names.join(" or ");
58482
+ var and = (names2) => names2.join(" and ");
58483
+ var or = (names2) => names2.join(" or ");
58036
58484
  function advice(blocked, host) {
58037
58485
  const script2 = blocked.some((b) => b.script);
58038
58486
  const connect2 = blocked.some((b) => b.connect);
@@ -58068,7 +58516,7 @@ async function readHomepage(origin, fetcher) {
58068
58516
  await response.body?.cancel();
58069
58517
  return { unread: `it answered HTTP ${response.status}` };
58070
58518
  }
58071
- const html = await readStart(response, 2e5);
58519
+ const html = await readStart(response, HOMEPAGE_BYTES);
58072
58520
  const policies = pagePolicies(response.headers.get("content-security-policy"), html);
58073
58521
  return { url: response.url || origin + "/", html, policies };
58074
58522
  } catch (error) {
@@ -58165,7 +58613,7 @@ function readPage(html) {
58165
58613
  })
58166
58614
  };
58167
58615
  }
58168
- function choose(pages) {
58616
+ function choose(pages, outside2 = []) {
58169
58617
  const chosen = [];
58170
58618
  const before = [];
58171
58619
  const results = pages.map(({ path: path6, page: page2 }) => {
@@ -58174,7 +58622,7 @@ function choose(pages) {
58174
58622
  if (page2.lines) return { path: path6, mark: null, has: "already" };
58175
58623
  if (shared.length) return { path: path6, mark: shared[0], has: "shared", times: shared.length };
58176
58624
  const pick = page2.paragraphs.find(
58177
- ({ mark: mark2 }) => mark2 !== null && page2.marks.get(mark2) === 1 && !before.some((marks) => marks.has(mark2)) && // Nor one that a page read after it shows beside one chosen already,
58625
+ ({ mark: mark2 }) => mark2 !== null && page2.marks.get(mark2) === 1 && !before.some((marks) => marks.has(mark2)) && !outside2.some((other) => other.marks.has(mark2)) && // Nor one that a page read after it shows beside one chosen already,
58178
58626
  // as a page that compares two products would.
58179
58627
  !pages.some(
58180
58628
  ({ page: other }) => other.marks.has(mark2) && chosen.some((done) => other.marks.has(done))
@@ -58209,8 +58657,9 @@ function endParagraph(source, offset) {
58209
58657
  return source.slice(0, at) + `
58210
58658
  ${indent}<${LINE_NAME} />` + source.slice(at);
58211
58659
  }
58660
+ var ownLine = (source, file) => (topNames(source).get(LINE_NAME) ?? []).some((from) => !importsComponents(file, from));
58212
58661
  function withImport(source, from) {
58213
- if (new RegExp(`\\bimport\\s+${LINE_NAME}\\b`).test(source)) return source;
58662
+ if (topNames(source).has(LINE_NAME)) return source;
58214
58663
  const imports = [...source.matchAll(/^import\b[^'"]*?(['"])[^'"\n]+\1(;?)[ \t]*$/gm)];
58215
58664
  const last = imports.at(-1);
58216
58665
  if (last) {
@@ -58464,7 +58913,8 @@ async function placeLine({
58464
58913
  component,
58465
58914
  log,
58466
58915
  policies = [],
58467
- start = nextDev
58916
+ start = nextDev,
58917
+ only
58468
58918
  }) {
58469
58919
  const blocked = () => log(
58470
58920
  "The site's Content Security Policy blocks inline styles, so people would see the line agents read through Exa: it is in no page."
@@ -58480,7 +58930,7 @@ async function placeLine({
58480
58930
  for (const file of code) {
58481
58931
  if (file === component || !JSX_CODE.test(file)) continue;
58482
58932
  const source = await readFile4(path4.join(dir, file), "utf8").catch(() => null);
58483
- if (source === null || !new RegExp(OPEN.source).test(source)) continue;
58933
+ if (source === null || !new RegExp(OPEN.source).test(source) || ownLine(source, file)) continue;
58484
58934
  const { text: text2, offsets } = mark(source, next2);
58485
58935
  offsets.forEach((offset, i) => where.set(next2 + i, { file, offset }));
58486
58936
  next2 += offsets.length;
@@ -58547,8 +58997,17 @@ async function placeLine({
58547
58997
  blocked();
58548
58998
  return { files: [] };
58549
58999
  }
58550
- const read2 = pages.map(({ path: at2, html }) => ({ path: at2, page: readPage(html) }));
58551
- const { chosen, results } = choose(read2);
59000
+ const loads = (html) => !only || html.includes(`/s/${only}.js`);
59001
+ const read2 = pages.filter(({ html }) => loads(html)).map(({ path: at2, html }) => ({ path: at2, page: readPage(html) }));
59002
+ const outside2 = pages.filter(({ html }) => !loads(html));
59003
+ if (outside2.length)
59004
+ log(
59005
+ `Left the line agents read through Exa out of ${outside2.map(({ path: at2 }) => at2).join(", ")}, which ${outside2.length === 1 ? "doesn't" : "don't"} load the Agentface tag.`
59006
+ );
59007
+ const { chosen, results } = choose(
59008
+ read2,
59009
+ outside2.map(({ html }) => readPage(html))
59010
+ );
58552
59011
  const edit = (marks) => {
58553
59012
  const edits2 = /* @__PURE__ */ new Map();
58554
59013
  const byFile = /* @__PURE__ */ new Map();
@@ -58663,8 +59122,8 @@ async function confirm(service, id, fetcher = fetch) {
58663
59122
  return { ok: response.ok, status: response.status, message: body?.message ?? `HTTP ${response.status}` };
58664
59123
  }
58665
59124
  var option = (source, name) => source?.match(new RegExp(`^\\s*${name}["']?\\s*[:=]\\s*["'\`]?([^"'\`\\s]+)`, "m"))?.[1] ?? null;
58666
- var config = async (dir, names) => {
58667
- for (const name of names) {
59125
+ var config = async (dir, names2) => {
59126
+ for (const name of names2) {
58668
59127
  const source = await readFile5(path5.join(dir, name), "utf8").catch(() => null);
58669
59128
  if (source !== null) return { source, name };
58670
59129
  }
@@ -58675,12 +59134,12 @@ async function siteUrl(dir, exec = run) {
58675
59134
  const host = (await readFile5(path5.join(dir, file), "utf8").catch(() => "")).trim().split(/\s+/)[0];
58676
59135
  if (host) return { url: `https://${host}/`, from: file };
58677
59136
  }
58678
- for (const [names, key] of [
59137
+ for (const [names2, key] of [
58679
59138
  [["astro.config.mjs", "astro.config.ts", "astro.config.mts", "astro.config.js"], "site"],
58680
59139
  [["hugo.toml", "config.toml"], "baseURL"],
58681
59140
  [["_config.yml"], "url"]
58682
59141
  ]) {
58683
- const { source, name } = await config(dir, names);
59142
+ const { source, name } = await config(dir, names2);
58684
59143
  const url = key === "site" && source ? astroSite(source) : option(source, key);
58685
59144
  if (/^https?:\/\//i.test(url ?? "")) return { url, from: name };
58686
59145
  }
@@ -58777,6 +59236,18 @@ async function siteFor({
58777
59236
  }
58778
59237
  var serviceFlag = (service) => service === DEFAULT_SERVICE ? "" : ` --service ${service}`;
58779
59238
  var list = (files2) => files2.length <= 3 ? files2.join(", ") : `${files2.slice(0, 3).join(", ")} and ${files2.length - 3} more`;
59239
+ function leftWithout(found) {
59240
+ const said3 = [found.skipped];
59241
+ if (found.scoped) {
59242
+ const files2 = found.scoped.files.map(({ file }) => file);
59243
+ const { left } = found.scoped;
59244
+ const without2 = left.length ? `${list(left)} ${left.length === 1 ? "doesn't" : "don't"}` : "no page head does";
59245
+ said3.push(
59246
+ `${list(files2)} ${files2.length === 1 ? "has" : "have"} the Agentface tag and ${without2}: init kept it where it is and added it nowhere else, so pages that didn't load it still don't.`
59247
+ );
59248
+ }
59249
+ return said3.filter(Boolean).join(" ") || null;
59250
+ }
58780
59251
  function nextSteps(site, service, own2) {
58781
59252
  const saved = own2 === "plugin";
58782
59253
  const check2 = `npx agentface check${saved ? ` --site ${site.id}` : ""}${serviceFlag(service)}`;
@@ -58912,6 +59383,16 @@ function prestaShopSteps(file) {
58912
59383
  return `${what} In the shop's back office, open Modules > Module Manager, click Upload a module and choose ${file}: PrestaShop installs it. ${cache}`;
58913
59384
  return `${what} If this folder is a copy of the shop rather than the live one, first upload the agentface folder to the shop's modules folder there. PrestaShop runs a module only once it's installed: in the shop's back office, open Modules > Module Manager, search for Agentface and click Install. ${cache}`;
58914
59385
  }
59386
+ function wordPressSteps(file) {
59387
+ return `That file is a WordPress plugin of Agentface's own, which puts the tag on every page made from the theme, whatever made its head and body, and which updates of WordPress, its plugins and its theme leave alone. It asks Agentface for the tag and its notice and keeps them an hour, so that when what they say changes, the pages change by themselves, with nothing to run. In the WordPress admin, open Plugins > Add New Plugin, click Upload Plugin, choose ${file} and click Install Now, then Activate Plugin. If the site has a caching plugin, clear its cache, so that the pages show the tag.`;
59388
+ }
59389
+ var wordPressUpload = (id) => ({
59390
+ framework: "WordPress",
59391
+ heads: [],
59392
+ bodies: [],
59393
+ creates: [{ file: `agentface-${id}.zip`, content: wordPressZip }],
59394
+ key: null
59395
+ });
58915
59396
  var PRESTASHOP_THEME = "If this theme isn't yours, such as PrestaShop's own Classic, its next update puts those layouts back without the tag. Run init in the shop's folder instead, the one with config/defines.inc.php: there it adds a module that no update replaces.";
58916
59397
  async function readyForPr(dir, exec) {
58917
59398
  if (await exec("git", ["status", "--porcelain"], { cwd: dir }))
@@ -58937,7 +59418,7 @@ async function init({
58937
59418
  let found = await withFramework(dir, await findHeads(dir));
58938
59419
  if (found.manual && pr)
58939
59420
  throw new Error(
58940
- `${found.manual.reason} --pr only commits what init writes: run init without it to get the tag to add by hand.`
59421
+ `${found.manual.reason} --pr only commits what init writes: run init without it to get ${found.manual.upload ? "the plugin to upload" : "the tag to add by hand"}.`
58941
59422
  );
58942
59423
  if (pr && !dryRun) await readyForPr(dir, exec);
58943
59424
  const site = await siteFor({ id, url, dir, found, service, fetcher, exec, dryRun, log });
@@ -58949,7 +59430,12 @@ async function init({
58949
59430
  framework: "WordPress",
58950
59431
  manual: wordPressManual(`${site.origin}'s homepage comes from WordPress.`)
58951
59432
  };
58952
- else if (found.manual?.none && "html" in homepage && prestaShopPage(homepage.html))
59433
+ let stale = [];
59434
+ if (found.manual?.upload) {
59435
+ log(found.manual.reason);
59436
+ stale = found.tagged.map(({ file }) => file);
59437
+ found = wordPressUpload(site.id);
59438
+ } else if (found.manual?.none && "html" in homepage && prestaShopPage(homepage.html))
58953
59439
  found = {
58954
59440
  framework: "PrestaShop",
58955
59441
  heads: [],
@@ -58981,6 +59467,7 @@ Add a second snippet to All pages, placed in Body \u2013 start:
58981
59467
  };
58982
59468
  }
58983
59469
  if (found.manual) return byHand2(found, site, service, dryRun, warning, log);
59470
+ const without2 = leftWithout(found);
58984
59471
  const before = /* @__PURE__ */ new Map();
58985
59472
  const after = /* @__PURE__ */ new Map();
58986
59473
  const edited = /* @__PURE__ */ new Map();
@@ -58988,6 +59475,13 @@ Add a second snippet to All pages, placed in Body \u2013 start:
58988
59475
  before.set(file, source);
58989
59476
  edited.set(file, addTag(source, site.tag));
58990
59477
  }
59478
+ for (const { file, source } of found.scoped?.files ?? []) {
59479
+ const updated = updatedTags(source, site.tag);
59480
+ if (updated !== source && !found.edits?.some((edit) => edit.file === file)) {
59481
+ before.set(file, source);
59482
+ edited.set(file, updated);
59483
+ }
59484
+ }
58991
59485
  if (site.notice)
58992
59486
  for (const { file, source } of found.bodies) {
58993
59487
  before.set(file, source);
@@ -59010,21 +59504,36 @@ Add a second snippet to All pages, placed in Body \u2013 start:
59010
59504
  const writes = [...after].filter(([file, content]) => content !== before.get(file));
59011
59505
  const files2 = writes.map(([file]) => file);
59012
59506
  const own2 = found.creates.some(({ file }) => file.endsWith(".zip")) ? "plugin" : found.framework === "WordPress" || found.framework === "PrestaShop" ? "file" : void 0;
59013
- const shop = found.framework === "PrestaShop" ? prestaShopSteps(found.creates[0].file) : null;
59507
+ const shop = found.framework === "PrestaShop" ? prestaShopSteps(found.creates[0].file) : found.framework === "WordPress" && own2 === "plugin" ? wordPressSteps(found.creates[0].file) : null;
59508
+ const twice = stale.length ? `${list(stale)} ${stale.length === 1 ? "has" : "have"} an Agentface tag already, from an earlier init or added by hand. Take it out, so that no page loads the tag twice: \`npx agentface uninstall\` does it.` : null;
59509
+ const beside = (found.tagged ?? []).map(({ file }) => file);
59510
+ const also = beside.length ? `${list(beside)} ${beside.length === 1 ? "has" : "have"} an Agentface tag too, from an earlier init or added by hand, and ${notAPage(beside)}. Take the tag out there, so that no page loads it twice.` : null;
59014
59511
  const noticed = site.notice && (found.bodies.length || found.creates.length);
59015
59512
  const what = `the Agentface tag${noticed ? " and its notice" : ""}`;
59016
- const had = [...found.heads, ...found.bodies, ...found.creates, ...found.edits ?? []].some(
59513
+ const had = [
59514
+ ...found.heads,
59515
+ ...found.bodies,
59516
+ ...found.creates,
59517
+ ...found.edits ?? [],
59518
+ ...found.scoped?.files ?? []
59519
+ ].some(
59017
59520
  ({ file, source }) => files2.includes(file) && typeof source === "string" && (tagKey(source) === site.id || noticeKey(source) === site.id || source.includes(OURS) && source.includes(`'${site.id}'`))
59018
59521
  );
59019
59522
  const elsewhere = () => noticeToReplace(site, found.noticed ?? [], notAPage, log);
59020
59523
  if (!writes.length && !(line && !dryRun)) {
59021
59524
  const tagged = [
59022
- ...new Set([...found.heads, ...found.creates, ...found.edits ?? []].map(({ file }) => file))
59525
+ ...new Set(
59526
+ [...found.scoped?.files ?? [], ...found.heads, ...found.creates, ...found.edits ?? []].map(
59527
+ ({ file }) => file
59528
+ )
59529
+ )
59023
59530
  ];
59024
59531
  log(`${list(tagged)} already ${tagged.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`);
59025
- if (found.skipped) log(found.skipped);
59532
+ if (without2) log(without2);
59026
59533
  elsewhere();
59027
59534
  if (shop) log(shop);
59535
+ if (twice) log(twice);
59536
+ if (also) log(also);
59028
59537
  if (warning) log(warning);
59029
59538
  log(nextSteps(site, service, own2));
59030
59539
  return { site, files: files2, written: false };
@@ -59033,12 +59542,13 @@ Add a second snippet to All pages, placed in Body \u2013 start:
59033
59542
  log(
59034
59543
  had ? `Would update ${what} in ${list(files2)} (${found.framework}) for ${site.origin}, to what init writes today.` : `Would add ${what} to ${list(files2)} (${found.framework}) for ${site.origin}.`
59035
59544
  );
59036
- if (found.skipped) log(found.skipped);
59545
+ if (without2) log(without2);
59037
59546
  if (line)
59038
59547
  log(
59039
59548
  "Would then run the site with next dev, to put the line agents read through Exa at the end of each page's first paragraph."
59040
59549
  );
59041
59550
  elsewhere();
59551
+ if (also) log(also);
59042
59552
  if (warning) log(warning);
59043
59553
  return { site, files: files2, written: false };
59044
59554
  }
@@ -59057,15 +59567,26 @@ Add a second snippet to All pages, placed in Body \u2013 start:
59057
59567
  );
59058
59568
  else {
59059
59569
  const tagged = [
59060
- ...new Set([...found.heads, ...found.creates, ...found.edits ?? []].map(({ file }) => file))
59570
+ ...new Set(
59571
+ [...found.scoped?.files ?? [], ...found.heads, ...found.creates, ...found.edits ?? []].map(
59572
+ ({ file }) => file
59573
+ )
59574
+ )
59061
59575
  ];
59062
59576
  log(`${list(tagged)} already ${tagged.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`);
59063
59577
  }
59064
- if (found.skipped) log(found.skipped);
59578
+ if (without2) log(without2);
59065
59579
  let lined = [];
59066
59580
  if (line) {
59067
59581
  const policies = "policies" in homepage ? homepage.policies : [];
59068
- lined = (await place({ dir, code: line.code, component: line.file, log, policies })).files;
59582
+ lined = (await place({
59583
+ dir,
59584
+ code: line.code,
59585
+ component: line.file,
59586
+ log,
59587
+ policies,
59588
+ ...line.scoped && { only: site.id }
59589
+ })).files;
59069
59590
  for (const file of lined) if (!files2.includes(file)) files2.push(file);
59070
59591
  }
59071
59592
  if (!files2.length) {
@@ -59078,8 +59599,10 @@ Add a second snippet to All pages, placed in Body \u2013 start:
59078
59599
  elsewhere();
59079
59600
  if (found.note) log(found.note);
59080
59601
  if (shop) log(shop);
59602
+ if (twice) log(twice);
59603
+ if (also) log(also);
59081
59604
  if (found.framework === "PrestaShop theme") log(PRESTASHOP_THEME);
59082
- if (found.framework === "WordPress")
59605
+ if (found.framework === "WordPress" && own2 === "file")
59083
59606
  log(
59084
59607
  `WordPress runs that file on every page by itself, as a must-use plugin: there's nothing to activate, and updates of WordPress, its plugins and its theme leave it alone. It asks Agentface for the tag and its notice and keeps them an hour, so that when what they say changes, the pages change by themselves, with nothing to run. If this folder is a copy of the site rather than the live one, upload the file to the same folder there. If the site has a caching plugin, clear its cache, so that the pages show the tag.`
59085
59608
  );
@@ -59118,7 +59641,7 @@ Add a second snippet to All pages, placed in Body \u2013 start:
59118
59641
  service,
59119
59642
  warning,
59120
59643
  had,
59121
- [found.note, found.skipped].filter(Boolean).join(" ") || null,
59644
+ [found.note, without2, also].filter(Boolean).join(" ") || null,
59122
59645
  lined.length ? line.file : null
59123
59646
  )
59124
59647
  ],
@@ -59140,9 +59663,9 @@ async function check({
59140
59663
  if (!id) {
59141
59664
  const found = await withFramework(dir, await findHeads(dir));
59142
59665
  id = found.key;
59143
- if (!id && found.manual?.steps)
59666
+ if (!id && found.manual?.upload)
59144
59667
  throw new Error(
59145
- "On WordPress the tag isn't in the site's files, so check can't find the site key here. Pass it: npx agentface check --site <site key>. It's in the tag init printed, after /s/."
59668
+ "On WordPress the tag isn't in the site's files, so check can't find the site key here. Pass it: npx agentface check --site <site key>. It's in the check command init printed, and on the site's page in agentface."
59146
59669
  );
59147
59670
  if (!id)
59148
59671
  throw new Error(
@@ -59203,7 +59726,7 @@ async function uninstall({
59203
59726
  const plugin = await isWordPress(dir) && await wordPressFile(dir);
59204
59727
  if (plugin !== false && !tagged.some(({ file }) => file === plugin))
59205
59728
  log(
59206
- "On WordPress, take the Agentface tag and its notice out of the plugin's boxes for the head and the body, where init said to paste them, and save: in WPCode, that's Code Snippets > Header & Footer."
59729
+ "On WordPress, open Plugins in the WordPress admin, then deactivate and delete Agentface. If the tag and its notice were pasted into another plugin's boxes for the head and the body instead, such as WPCode's, take them out there and save."
59207
59730
  );
59208
59731
  const undone = await undoFrameworks(dir);
59209
59732
  if (!tagged.length && !undone.edits.length && !undone.deletes.length) {
@@ -59219,7 +59742,7 @@ async function uninstall({
59219
59742
  continue;
59220
59743
  }
59221
59744
  const removed = ownFile(source) ? null : removeTag(changed.get(file) ?? source);
59222
- const content = removed === null ? null : withoutLine(removed);
59745
+ const content = removed === null ? null : withoutLine(removed, file);
59223
59746
  if (content === null) {
59224
59747
  deleted.push(file);
59225
59748
  changed.delete(file);