agentface 0.8.0 → 0.9.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.
- package/dist/agentface.mjs +901 -105
- package/package.json +1 -1
package/dist/agentface.mjs
CHANGED
|
@@ -496,6 +496,29 @@ function headEnd(html) {
|
|
|
496
496
|
return -1;
|
|
497
497
|
}
|
|
498
498
|
|
|
499
|
+
// cli/package.json
|
|
500
|
+
var package_default = {
|
|
501
|
+
name: "agentface",
|
|
502
|
+
version: "0.9.1",
|
|
503
|
+
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.",
|
|
504
|
+
repository: {
|
|
505
|
+
type: "git",
|
|
506
|
+
url: "git+https://github.com/agentfacehq/agentface-app.git",
|
|
507
|
+
directory: "adapter/cli"
|
|
508
|
+
},
|
|
509
|
+
bin: {
|
|
510
|
+
agentface: "dist/agentface.mjs"
|
|
511
|
+
},
|
|
512
|
+
files: [
|
|
513
|
+
"dist/agentface.mjs"
|
|
514
|
+
],
|
|
515
|
+
type: "module",
|
|
516
|
+
engines: {
|
|
517
|
+
node: ">=20"
|
|
518
|
+
},
|
|
519
|
+
license: "UNLICENSED"
|
|
520
|
+
};
|
|
521
|
+
|
|
499
522
|
// cli/zip.mts
|
|
500
523
|
import { deflateRawSync } from "node:zlib";
|
|
501
524
|
var CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
|
|
@@ -551,6 +574,8 @@ function zip(files2, date = /* @__PURE__ */ new Date()) {
|
|
|
551
574
|
}
|
|
552
575
|
|
|
553
576
|
// cli/heads.mts
|
|
577
|
+
var INIT = package_default.version;
|
|
578
|
+
var stamped = (tag) => tag.replace(/><\/script>$/, ` data-init="${INIT}"></script>`);
|
|
554
579
|
var EXTENSIONS = [
|
|
555
580
|
"html",
|
|
556
581
|
"htm",
|
|
@@ -724,12 +749,24 @@ var LIST = /\/s\/(site-[a-z0-9-]+)\.md(?![\w-])/;
|
|
|
724
749
|
var BODY = /<body(?=[\s>/])(?:<\?[\s\S]*?\?>|<%[\s\S]*?%>|\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^>])*>/i;
|
|
725
750
|
var onItsLine = (pattern) => new RegExp(`(\\r?\\n[ \\t]*)?${pattern.source}`, "gi");
|
|
726
751
|
var OURS = "Added by `npx agentface init`";
|
|
752
|
+
var about = (comment2, how) => [
|
|
753
|
+
`${OURS}. It asks Agentface for the two lines this`,
|
|
754
|
+
"site's pages carry for AI agents, the tag and its notice, so that a change to",
|
|
755
|
+
"them reaches the site by itself. It keeps them an hour and, while Agentface",
|
|
756
|
+
"can't be reached, uses the copy it has: at first the one below.",
|
|
757
|
+
how,
|
|
758
|
+
"`npx agentface uninstall` deletes it."
|
|
759
|
+
].join("\n").replace(/^/gm, comment2 + " ").replace(/ +$/gm, "");
|
|
727
760
|
function tagKey(source) {
|
|
728
761
|
return source.match(KEY)?.[1] ?? null;
|
|
729
762
|
}
|
|
730
763
|
function noticeKey(source) {
|
|
731
764
|
return source.match(NOTICE)?.[1] ?? null;
|
|
732
765
|
}
|
|
766
|
+
function siteOf(tag) {
|
|
767
|
+
const [, service = "", site = ""] = tag.match(/\bsrc="(https?:\/\/[^"]+?)\/s\/([^/"]+)\.js"/) ?? [];
|
|
768
|
+
return { service, site };
|
|
769
|
+
}
|
|
733
770
|
var linesIn = (source) => ({
|
|
734
771
|
tag: source.match(TAG)?.[0] ?? null,
|
|
735
772
|
notice: source.match(NOTICE)?.[0] ?? null
|
|
@@ -746,7 +783,9 @@ function updatedTag(old, tag) {
|
|
|
746
783
|
const now = attributesOf(tag);
|
|
747
784
|
const was = attributesOf(old);
|
|
748
785
|
const mine = initsOwn(was, now);
|
|
749
|
-
const
|
|
786
|
+
const init2 = (list2) => list2.some(({ name }) => name === "data-init");
|
|
787
|
+
const rest = (list2) => list2.filter(({ name }) => name !== "data-init");
|
|
788
|
+
const current2 = rest(mine).length === rest(now).length && (init2(mine) || !init2(now)) && rest(now).every(({ name, value }) => {
|
|
750
789
|
const same = mine.find((attribute2) => attribute2.name === name);
|
|
751
790
|
return same && (value === void 0 || said2(same.value) === said2(value));
|
|
752
791
|
});
|
|
@@ -755,7 +794,7 @@ function updatedTag(old, tag) {
|
|
|
755
794
|
return kept.length ? tag.replace(/^<script\b/, () => `<script ${kept.join(" ")}`) : tag;
|
|
756
795
|
}
|
|
757
796
|
function initsOwn(was, now) {
|
|
758
|
-
const names = /* @__PURE__ */ new Set(["src", "async", "defer", ...now.map(({ name }) => name)]);
|
|
797
|
+
const names = /* @__PURE__ */ new Set(["src", "async", "defer", "data-init", ...now.map(({ name }) => name)]);
|
|
759
798
|
return was.filter(({ name, value }) => name !== null && (names.has(name) || LIST.test(value ?? "")));
|
|
760
799
|
}
|
|
761
800
|
function ownersAttributes(old) {
|
|
@@ -771,8 +810,8 @@ function updatedNotice(old, notice) {
|
|
|
771
810
|
}
|
|
772
811
|
function tagToReplace(source, tag) {
|
|
773
812
|
const old = source.match(TAG)?.[0];
|
|
774
|
-
const next2 = old && updatedTag(old, tag);
|
|
775
|
-
return next2 && next2 !== old ?
|
|
813
|
+
const next2 = old && updatedTag(old, tag.replace(/\sdata-init="[^"]*"/, ""));
|
|
814
|
+
return next2 && next2 !== old ? updatedTag(old, tag) : null;
|
|
776
815
|
}
|
|
777
816
|
function staleNotice(source, notice) {
|
|
778
817
|
const key = noticeKey(notice);
|
|
@@ -919,10 +958,12 @@ function withoutLine(source) {
|
|
|
919
958
|
}
|
|
920
959
|
var GATSBY_SSR = (tag, notice) => {
|
|
921
960
|
const src = tag.match(/\bsrc="([^"]+)"/)[1];
|
|
922
|
-
const
|
|
961
|
+
const data = [...tag.matchAll(/\b(data-[a-z-]+)="([^"]+)"/g)].map(
|
|
962
|
+
([, name, value]) => `, '${name}': '${value}'`
|
|
963
|
+
);
|
|
923
964
|
const text2 = notice?.match(/>([^<]*)</)[1];
|
|
924
965
|
const load = tag.match(/^<script (async|defer)\b/)?.[1] ?? "defer";
|
|
925
|
-
const props = `key: 'agentface', ${load}: true, src: '${src}'${
|
|
966
|
+
const props = `key: 'agentface', ${load}: true, src: '${src}'${data.join("")}`;
|
|
926
967
|
return `// ${OURS}: puts the Agentface tag in every page's <head>.
|
|
927
968
|
const React = require('react');
|
|
928
969
|
|
|
@@ -934,7 +975,464 @@ ${text2 ? ` setPreBodyComponents([React.createElement('noscript', { key: 'agent
|
|
|
934
975
|
` : ""}};
|
|
935
976
|
`;
|
|
936
977
|
};
|
|
937
|
-
var
|
|
978
|
+
var phpString = (text2) => `'${text2.replace(/[\\']/g, "\\$&")}'`;
|
|
979
|
+
var PHP_LINES = (tag, notice, own2) => {
|
|
980
|
+
const { service, site } = siteOf(tag);
|
|
981
|
+
return String.raw`class AgentfaceLines
|
|
982
|
+
{
|
|
983
|
+
const SERVICE = ${phpString(service)};
|
|
984
|
+
const SITE = ${phpString(site)};
|
|
985
|
+
const TAG = ${phpString(tag)};
|
|
986
|
+
const NOTICE = ${phpString(notice ?? "")};
|
|
987
|
+
|
|
988
|
+
private static $lines = null;
|
|
989
|
+
|
|
990
|
+
// The site's tag and notice. The page being made once the copy is an hour
|
|
991
|
+
// old asks Agentface again, waiting two seconds at most, and pages made
|
|
992
|
+
// meanwhile keep the copy. While Agentface can't be reached, the copy
|
|
993
|
+
// stays, and it's asked for again five minutes later.
|
|
994
|
+
public static function lines()
|
|
995
|
+
{
|
|
996
|
+
if (self::$lines !== null) {
|
|
997
|
+
return self::$lines;
|
|
998
|
+
}
|
|
999
|
+
$kept = self::kept();
|
|
1000
|
+
if (!is_array($kept) || !isset($kept['tag'], $kept['notice'], $kept['due']) || !self::valid($kept['tag'], $kept['notice'])) {
|
|
1001
|
+
$kept = array('tag' => self::TAG, 'notice' => self::NOTICE, 'due' => 0);
|
|
1002
|
+
}
|
|
1003
|
+
if (time() >= $kept['due']) {
|
|
1004
|
+
$kept['due'] = time() + 30;
|
|
1005
|
+
self::keep($kept);
|
|
1006
|
+
$wait = 300;
|
|
1007
|
+
$body = self::fetch(self::SERVICE . '/sites/' . self::SITE);
|
|
1008
|
+
$found = is_string($body) ? json_decode($body, true) : null;
|
|
1009
|
+
if (is_array($found) && isset($found['tag'])) {
|
|
1010
|
+
$notice = isset($found['notice']) ? $found['notice'] : '';
|
|
1011
|
+
if (self::valid($found['tag'], $notice)) {
|
|
1012
|
+
$kept['tag'] = $found['tag'];
|
|
1013
|
+
$kept['notice'] = $notice;
|
|
1014
|
+
$wait = 3600;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
$kept['due'] = time() + $wait;
|
|
1018
|
+
self::keep($kept);
|
|
1019
|
+
}
|
|
1020
|
+
self::$lines = array($kept['tag'], $kept['notice']);
|
|
1021
|
+
return self::$lines;
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
// Whether lines are this site's: a tag that loads its script, and a
|
|
1025
|
+
// notice or none.
|
|
1026
|
+
private static function valid($tag, $notice)
|
|
1027
|
+
{
|
|
1028
|
+
return is_string($tag)
|
|
1029
|
+
&& preg_match('#^<script [^<>]*></script>$#D', $tag)
|
|
1030
|
+
&& strpos($tag, '/s/' . self::SITE . '.js"') !== false
|
|
1031
|
+
&& is_string($notice)
|
|
1032
|
+
&& preg_match('#^(?:<noscript>[^<>]*</noscript>)?$#D', $notice);
|
|
1033
|
+
}
|
|
1034
|
+
${own2}
|
|
1035
|
+
// A page as it goes out, sent with $status and $headers (headers_list()):
|
|
1036
|
+
// with the lines when it's HTML sent whole, and as it is otherwise.
|
|
1037
|
+
public static function sent($html, $status, $headers)
|
|
1038
|
+
{
|
|
1039
|
+
$type = (string) ini_get('default_mimetype');
|
|
1040
|
+
$policies = array();
|
|
1041
|
+
$length = false;
|
|
1042
|
+
foreach ($headers as $header) {
|
|
1043
|
+
$parts = explode(':', $header, 2);
|
|
1044
|
+
$name = strtolower(trim($parts[0]));
|
|
1045
|
+
$value = isset($parts[1]) ? trim($parts[1]) : '';
|
|
1046
|
+
if ($name === 'content-encoding') {
|
|
1047
|
+
return $html;
|
|
1048
|
+
}
|
|
1049
|
+
if ($name === 'content-type') {
|
|
1050
|
+
$type = $value;
|
|
1051
|
+
} elseif ($name === 'content-security-policy') {
|
|
1052
|
+
$policies[] = $value;
|
|
1053
|
+
} elseif ($name === 'content-length') {
|
|
1054
|
+
$length = true;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
if ($status !== 200 || stripos($type, 'text/html') !== 0) {
|
|
1058
|
+
return $html;
|
|
1059
|
+
}
|
|
1060
|
+
$page = self::insert($html, self::lines(), implode(',', $policies));
|
|
1061
|
+
if ($page !== $html && $length && !headers_sent()) {
|
|
1062
|
+
header_remove('Content-Length');
|
|
1063
|
+
}
|
|
1064
|
+
return $page;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
// Exa, a search engine AI agents read the web through, runs no script and
|
|
1068
|
+
// keeps only a page's main text, so the tag and the notice never reach an
|
|
1069
|
+
// agent that reads a page there. The line says the notice again, hidden at
|
|
1070
|
+
// the end of the page's first paragraph, where Exa keeps it. Empty for a
|
|
1071
|
+
// notice that isn't one.
|
|
1072
|
+
const STYLE = ${phpString(LINE_STYLE)};
|
|
1073
|
+
|
|
1074
|
+
private static function line($notice)
|
|
1075
|
+
{
|
|
1076
|
+
$list = '/s/' . self::SITE . '.md';
|
|
1077
|
+
if (!preg_match('#^<noscript>([^<>]*) (https?://[^\s<>"]+)</noscript>$#D', $notice, $said)
|
|
1078
|
+
|| substr($said[2], -strlen($list)) !== $list) {
|
|
1079
|
+
return '';
|
|
1080
|
+
}
|
|
1081
|
+
return ' <span class="agentface-api" style="' . self::STYLE . '">' . $said[1]
|
|
1082
|
+
. ' <a tabindex="-1" href="' . $said[2] . '">' . $said[2] . '</a></span>';
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
// The page's first paragraph as Exa reads one: a <p> of 40 characters or
|
|
1086
|
+
// more, in <main>, or in the body when <main> has none, and not in a header,
|
|
1087
|
+
// a menu, a footer, a form, an aside, a dialog or anything hidden. Those
|
|
1088
|
+
// after the page's heading come first, and one whose words are on the page
|
|
1089
|
+
// twice, such as a list's, is passed over. The byte its </p> starts at, or -1.
|
|
1090
|
+
const RAW = '#^(?:script|style|textarea|title|template|noscript)$#D';
|
|
1091
|
+
const OUTSIDE = '#^(?:header|nav|footer|form|aside|dialog|astro-island)$#D';
|
|
1092
|
+
const VOID = '#^(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$#D';
|
|
1093
|
+
const ENDS_P = '#^(?:address|article|aside|blockquote|details|dialog|div|dl|fieldset|figcaption|figure|footer|form|h[1-6]|header|hgroup|hr|main|menu|nav|ol|p|pre|section|table|ul)$#D';
|
|
1094
|
+
const TOKEN = '#\G(?:<!--.*?-->|<(/?)([a-zA-Z][\w:-]*)((?:"[^"]*"|\'[^\']*\'|[^>"\'])*)>|[^<]+|<)#s';
|
|
1095
|
+
|
|
1096
|
+
private static function firstParagraph($html, $at)
|
|
1097
|
+
{
|
|
1098
|
+
$names = array();
|
|
1099
|
+
$outs = array();
|
|
1100
|
+
$found = array();
|
|
1101
|
+
$open = null;
|
|
1102
|
+
$headed = false;
|
|
1103
|
+
$headedInMain = false;
|
|
1104
|
+
while ($at < strlen($html) && preg_match(self::TOKEN, $html, $m, 0, $at)) {
|
|
1105
|
+
$start = $at;
|
|
1106
|
+
$at += strlen($m[0]);
|
|
1107
|
+
if (substr($m[0], 0, 4) === '<!--') {
|
|
1108
|
+
continue;
|
|
1109
|
+
}
|
|
1110
|
+
if (!isset($m[2]) || $m[2] === '') {
|
|
1111
|
+
if ($open !== null) {
|
|
1112
|
+
$open['words'] .= $m[0];
|
|
1113
|
+
}
|
|
1114
|
+
continue;
|
|
1115
|
+
}
|
|
1116
|
+
$name = strtolower($m[2]);
|
|
1117
|
+
$attributes = isset($m[3]) ? $m[3] : '';
|
|
1118
|
+
if ($m[1] === '/') {
|
|
1119
|
+
if ($name === 'body') {
|
|
1120
|
+
break;
|
|
1121
|
+
}
|
|
1122
|
+
$depths = array_keys($names, $name, true);
|
|
1123
|
+
if (!$depths) {
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
$depth = $depths[count($depths) - 1];
|
|
1127
|
+
if ($open !== null && $depth <= $open['depth']) {
|
|
1128
|
+
if ($depth === $open['depth'] && $name === 'p') {
|
|
1129
|
+
$open['at'] = $start;
|
|
1130
|
+
$found[] = $open;
|
|
1131
|
+
}
|
|
1132
|
+
$open = null;
|
|
1133
|
+
}
|
|
1134
|
+
array_splice($names, $depth);
|
|
1135
|
+
array_splice($outs, $depth);
|
|
1136
|
+
continue;
|
|
1137
|
+
}
|
|
1138
|
+
if (preg_match(self::RAW, $name)) {
|
|
1139
|
+
if (!preg_match('#</' . $name . '\s*>#i', $html, $end, PREG_OFFSET_CAPTURE, $at)) {
|
|
1140
|
+
break;
|
|
1141
|
+
}
|
|
1142
|
+
$at = $end[0][1] + strlen($end[0][0]);
|
|
1143
|
+
continue;
|
|
1144
|
+
}
|
|
1145
|
+
if ($open !== null && preg_match(self::ENDS_P, $name)) {
|
|
1146
|
+
array_splice($names, $open['depth']);
|
|
1147
|
+
array_splice($outs, $open['depth']);
|
|
1148
|
+
$open = null;
|
|
1149
|
+
}
|
|
1150
|
+
$main = in_array('main', $names, true);
|
|
1151
|
+
if ($name === 'h1') {
|
|
1152
|
+
$headed = true;
|
|
1153
|
+
$headedInMain = $headedInMain || $main;
|
|
1154
|
+
}
|
|
1155
|
+
if (preg_match(self::VOID, $name) || substr($attributes, -1) === '/') {
|
|
1156
|
+
continue;
|
|
1157
|
+
}
|
|
1158
|
+
$bare = preg_replace('#"[^"]*"|\'[^\']*\'#', '', $attributes);
|
|
1159
|
+
$names[] = $name;
|
|
1160
|
+
$outs[] = preg_match(self::OUTSIDE, $name) === 1
|
|
1161
|
+
|| preg_match('#(?:^|\s)hidden\b#i', $bare) === 1
|
|
1162
|
+
|| preg_match('#\brole\s*=\s*["\']?dialog\b#i', $attributes) === 1;
|
|
1163
|
+
if ($name === 'p') {
|
|
1164
|
+
$open = array(
|
|
1165
|
+
'at' => -1,
|
|
1166
|
+
'depth' => count($names) - 1,
|
|
1167
|
+
'words' => '',
|
|
1168
|
+
'main' => $main,
|
|
1169
|
+
'first' => $main ? $headedInMain : $headed,
|
|
1170
|
+
'out' => in_array(true, $outs, true),
|
|
1171
|
+
);
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
$times = array();
|
|
1175
|
+
foreach ($found as $i => $p) {
|
|
1176
|
+
$words = trim(preg_replace('#(?:\s|\xC2\xA0)+#', ' ', $p['words']), ' ');
|
|
1177
|
+
$found[$i]['words'] = $words;
|
|
1178
|
+
$times[$words] = isset($times[$words]) ? $times[$words] + 1 : 1;
|
|
1179
|
+
}
|
|
1180
|
+
$long = array();
|
|
1181
|
+
$inMain = array();
|
|
1182
|
+
foreach ($found as $p) {
|
|
1183
|
+
// Its length in characters, which UTF-8 makes of one or more bytes.
|
|
1184
|
+
if (!$p['out'] && preg_match_all('#[^\x80-\xBF]#', $p['words']) >= 40) {
|
|
1185
|
+
$long[] = $p;
|
|
1186
|
+
if ($p['main']) {
|
|
1187
|
+
$inMain[] = $p;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
$pool = $inMain ? $inMain : $long;
|
|
1192
|
+
foreach (array(true, false) as $first) {
|
|
1193
|
+
foreach ($pool as $p) {
|
|
1194
|
+
if ($p['first'] === $first && $times[$p['words']] === 1) {
|
|
1195
|
+
return $p['at'];
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
return -1;
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
// Whether the page may hide the line with a style attribute. Under a Content
|
|
1203
|
+
// Security Policy that blocks inline styles, from the response or the page's
|
|
1204
|
+
// own <meta>, the line would be on screen, so the page gets none.
|
|
1205
|
+
private static function stylesAllowed($html, $policy)
|
|
1206
|
+
{
|
|
1207
|
+
$policies = array($policy);
|
|
1208
|
+
preg_match_all('#<meta\b[^>]*http-equiv\s*=\s*["\']?content-security-policy\b[^>]*>#i', $html, $metas);
|
|
1209
|
+
foreach ($metas[0] as $meta) {
|
|
1210
|
+
$content = preg_match('#\bcontent\s*=\s*(?:"([^"]*)"|\'([^\']*)\')#i', $meta, $said) ? $said : array();
|
|
1211
|
+
$policies[] = isset($content[1]) && $content[1] !== '' ? $content[1] : (isset($content[2]) ? $content[2] : '');
|
|
1212
|
+
}
|
|
1213
|
+
foreach (explode(',', implode(',', $policies)) as $text) {
|
|
1214
|
+
$rules = array();
|
|
1215
|
+
foreach (explode(';', $text) as $rule) {
|
|
1216
|
+
$sources = preg_split('#\s+#', strtolower(trim($rule)));
|
|
1217
|
+
$name = array_shift($sources);
|
|
1218
|
+
if ($name !== '' && !isset($rules[$name])) {
|
|
1219
|
+
$rules[$name] = $sources;
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
$sources = null;
|
|
1223
|
+
foreach (array('style-src-attr', 'style-src', 'default-src') as $name) {
|
|
1224
|
+
if ($sources === null && isset($rules[$name])) {
|
|
1225
|
+
$sources = $rules[$name];
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
if ($sources === null) {
|
|
1229
|
+
continue;
|
|
1230
|
+
}
|
|
1231
|
+
if (!in_array("'unsafe-inline'", $sources, true)) {
|
|
1232
|
+
return false;
|
|
1233
|
+
}
|
|
1234
|
+
foreach ($sources as $source) {
|
|
1235
|
+
if (preg_match('#^\'(?:nonce|sha256|sha384|sha512)-#', $source)) {
|
|
1236
|
+
return false;
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
return true;
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
// The page's own </head> or <body>: the first one outside comments and the
|
|
1244
|
+
// elements whose text can look like one, such as a script that builds a page
|
|
1245
|
+
// from a string. Where it starts and ends, or null where there's none.
|
|
1246
|
+
const SKIPPED = '<!--[\s\S]*?(?:-->|\z)|<script\b[^>]*>[\s\S]*?(?:</script\s*>|\z)|<style\b[^>]*>[\s\S]*?(?:</style\s*>|\z)|<textarea\b[^>]*>[\s\S]*?(?:</textarea\s*>|\z)|<title\b[^>]*>[\s\S]*?(?:</title\s*>|\z)|<template\b[^>]*>[\s\S]*?(?:</template\s*>|\z)|<noscript\b[^>]*>[\s\S]*?(?:</noscript\s*>|\z)';
|
|
1247
|
+
|
|
1248
|
+
private static function outside($html, $element)
|
|
1249
|
+
{
|
|
1250
|
+
$pattern = '#' . self::SKIPPED . '|(' . $element . ')#i';
|
|
1251
|
+
for ($at = 0; preg_match($pattern, $html, $m, PREG_OFFSET_CAPTURE, $at); $at = $m[0][1] + strlen($m[0][0])) {
|
|
1252
|
+
if (isset($m[1]) && $m[1][1] !== -1) {
|
|
1253
|
+
return array($m[1][1], $m[1][1] + strlen($m[1][0]));
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
return null;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
// The page with the site's lines in it: the tag last in its head, the notice
|
|
1260
|
+
// first in its body, the line at the end of its first paragraph. A page
|
|
1261
|
+
// without a head, such as a fragment, stays as it is, and so do lines put
|
|
1262
|
+
// there by hand and an AMP page, which allows no script of ours.
|
|
1263
|
+
public static function insert($html, $lines, $policy = '')
|
|
1264
|
+
{
|
|
1265
|
+
if (preg_match('#<html\b[^>]*\s(?:amp|⚡)[\s>=/]#i', $html)) {
|
|
1266
|
+
return $html;
|
|
1267
|
+
}
|
|
1268
|
+
list($tag, $notice) = $lines;
|
|
1269
|
+
$page = $html;
|
|
1270
|
+
if (strpos($page, '/s/' . self::SITE . '.js') === false) {
|
|
1271
|
+
$head = self::outside($page, '</head\s*>');
|
|
1272
|
+
if ($head === null) {
|
|
1273
|
+
return $html;
|
|
1274
|
+
}
|
|
1275
|
+
$page = substr($page, 0, $head[0]) . $tag . substr($page, $head[0]);
|
|
1276
|
+
$body = $notice !== '' ? self::outside($page, '<body\b[^>]*>') : null;
|
|
1277
|
+
if ($body !== null) {
|
|
1278
|
+
$page = substr($page, 0, $body[1]) . $notice . substr($page, $body[1]);
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
$line = self::line($notice);
|
|
1282
|
+
$body = self::outside($page, '<body\b[^>]*>');
|
|
1283
|
+
if ($line === '' || $body === null || strpos($page, 'class="agentface-api"') !== false || !self::stylesAllowed($page, $policy)) {
|
|
1284
|
+
return $page;
|
|
1285
|
+
}
|
|
1286
|
+
$at = self::firstParagraph($page, $body[1]);
|
|
1287
|
+
return $at === -1 ? $page : substr($page, 0, $at) . $line . substr($page, $at);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
`;
|
|
1291
|
+
};
|
|
1292
|
+
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" : ""}.`;
|
|
1293
|
+
var MU_PLUGIN = (tag, notice) => String.raw`<?php
|
|
1294
|
+
/**
|
|
1295
|
+
* Plugin Name: Agentface
|
|
1296
|
+
* Description: ${DOES(notice)}
|
|
1297
|
+
*/
|
|
1298
|
+
${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.")}
|
|
1299
|
+
if (!defined('ABSPATH')) {
|
|
1300
|
+
exit;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
${PHP_LINES(
|
|
1304
|
+
tag,
|
|
1305
|
+
notice,
|
|
1306
|
+
String.raw`
|
|
1307
|
+
// The copy, in the site's options.
|
|
1308
|
+
private static function kept()
|
|
1309
|
+
{
|
|
1310
|
+
return get_option('agentface_lines');
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
private static function keep($kept)
|
|
1314
|
+
{
|
|
1315
|
+
update_option('agentface_lines', $kept, true);
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
// What Agentface answered at $url, or null.
|
|
1319
|
+
private static function fetch($url)
|
|
1320
|
+
{
|
|
1321
|
+
$response = wp_remote_get($url, array(
|
|
1322
|
+
'timeout' => 2,
|
|
1323
|
+
'user-agent' => 'agentface-lines/${INIT}',
|
|
1324
|
+
'headers' => array('Accept' => 'application/json'),
|
|
1325
|
+
));
|
|
1326
|
+
return !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200
|
|
1327
|
+
? wp_remote_retrieve_body($response)
|
|
1328
|
+
: null;
|
|
1329
|
+
}
|
|
1330
|
+
`
|
|
1331
|
+
)}
|
|
1332
|
+
// The lines are asked for before the page is made, and go in as it goes out.
|
|
1333
|
+
// A page sent in parts gets them in the part that has the end of its head,
|
|
1334
|
+
// without the line Exa keeps.
|
|
1335
|
+
add_action('template_redirect', function () {
|
|
1336
|
+
AgentfaceLines::lines();
|
|
1337
|
+
ob_start(function ($html, $phase) {
|
|
1338
|
+
return $phase & PHP_OUTPUT_HANDLER_CLEAN ? $html : AgentfaceLines::sent($html, http_response_code(), headers_list());
|
|
1339
|
+
});
|
|
1340
|
+
}, PHP_INT_MIN);
|
|
1341
|
+
`;
|
|
1342
|
+
var PRESTASHOP_MODULE = (tag, notice) => String.raw`<?php
|
|
1343
|
+
${about("//", "PrestaShop runs it once it's installed in Modules > Module Manager, and it\nputs them in each page the shop makes.")}
|
|
1344
|
+
if (!defined('_PS_VERSION_')) {
|
|
1345
|
+
exit;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
${PHP_LINES(
|
|
1349
|
+
tag,
|
|
1350
|
+
notice,
|
|
1351
|
+
String.raw`
|
|
1352
|
+
// The copy, in the shop's settings. Its tags are escaped, since PrestaShop
|
|
1353
|
+
// takes tags out of a setting's text.
|
|
1354
|
+
private static function kept()
|
|
1355
|
+
{
|
|
1356
|
+
return json_decode((string) Configuration::getGlobalValue('AGENTFACE_LINES'), true);
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
private static function keep($kept)
|
|
1360
|
+
{
|
|
1361
|
+
Configuration::updateGlobalValue('AGENTFACE_LINES', json_encode($kept, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT));
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
// What Agentface answered at $url, or null.
|
|
1365
|
+
private static function fetch($url)
|
|
1366
|
+
{
|
|
1367
|
+
if (!function_exists('curl_init')) {
|
|
1368
|
+
return null;
|
|
1369
|
+
}
|
|
1370
|
+
$curl = curl_init($url);
|
|
1371
|
+
curl_setopt_array($curl, array(
|
|
1372
|
+
CURLOPT_RETURNTRANSFER => true,
|
|
1373
|
+
CURLOPT_CONNECTTIMEOUT => 2,
|
|
1374
|
+
CURLOPT_TIMEOUT => 2,
|
|
1375
|
+
CURLOPT_USERAGENT => 'agentface-lines/${INIT}',
|
|
1376
|
+
CURLOPT_HTTPHEADER => array('Accept: application/json'),
|
|
1377
|
+
));
|
|
1378
|
+
$body = curl_exec($curl);
|
|
1379
|
+
return is_string($body) && curl_getinfo($curl, CURLINFO_HTTP_CODE) === 200 ? $body : null;
|
|
1380
|
+
}
|
|
1381
|
+
`
|
|
1382
|
+
)}
|
|
1383
|
+
class Agentface extends Module
|
|
1384
|
+
{
|
|
1385
|
+
public function __construct()
|
|
1386
|
+
{
|
|
1387
|
+
$this->name = 'agentface';
|
|
1388
|
+
$this->tab = 'front_office_features';
|
|
1389
|
+
$this->version = '1.0.0';
|
|
1390
|
+
$this->author = 'Agentface';
|
|
1391
|
+
$this->need_instance = 0;
|
|
1392
|
+
$this->ps_versions_compliancy = ['min' => '1.7.1.0', 'max' => _PS_VERSION_];
|
|
1393
|
+
parent::__construct();
|
|
1394
|
+
$this->displayName = 'Agentface';
|
|
1395
|
+
$this->description = "${DOES(notice)}";
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
public function install()
|
|
1399
|
+
{
|
|
1400
|
+
return parent::install() && $this->registerHook('actionOutputHTMLBefore');
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
public function uninstall()
|
|
1404
|
+
{
|
|
1405
|
+
Configuration::deleteByName('AGENTFACE_LINES');
|
|
1406
|
+
return parent::uninstall();
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
public function hookActionOutputHTMLBefore($params)
|
|
1410
|
+
{
|
|
1411
|
+
$params['html'] = AgentfaceLines::sent($params['html'], http_response_code(), headers_list());
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
// A shop that installed the module an earlier init wrote still calls it in
|
|
1415
|
+
// every page's head and body, where it put the tag and the notice. The
|
|
1416
|
+
// first page it's called for moves it to the hook above, and gets them
|
|
1417
|
+
// there as before.
|
|
1418
|
+
public function hookDisplayHeader()
|
|
1419
|
+
{
|
|
1420
|
+
if ($this->registerHook('actionOutputHTMLBefore')) {
|
|
1421
|
+
$this->unregisterHook('displayHeader');
|
|
1422
|
+
$this->unregisterHook('displayAfterBodyOpeningTag');
|
|
1423
|
+
}
|
|
1424
|
+
$lines = AgentfaceLines::lines();
|
|
1425
|
+
return $lines[0] . "\n";
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
public function hookDisplayAfterBodyOpeningTag()
|
|
1429
|
+
{
|
|
1430
|
+
$lines = AgentfaceLines::lines();
|
|
1431
|
+
return $lines[1] === '' ? '' : $lines[1] . "\n";
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
`;
|
|
1435
|
+
var MU_PLUGIN_HOOKS = (tag, notice) => `<?php
|
|
938
1436
|
/**
|
|
939
1437
|
* Plugin Name: Agentface
|
|
940
1438
|
* Description: Puts the Agentface tag in every page's head${notice ? ", and its notice first in the body" : ""}.
|
|
@@ -949,7 +1447,7 @@ add_action('wp_body_open', function () {
|
|
|
949
1447
|
echo '${notice}' . "\\n";
|
|
950
1448
|
}, PHP_INT_MIN);
|
|
951
1449
|
` : ""}`;
|
|
952
|
-
var
|
|
1450
|
+
var PRESTASHOP_MODULE_HOOKS = (tag, notice) => `<?php
|
|
953
1451
|
// ${OURS}. PrestaShop runs it on every page once it's installed in Modules > Module Manager, and \`npx agentface uninstall\` deletes it.
|
|
954
1452
|
if (!defined('_PS_VERSION_')) {
|
|
955
1453
|
exit;
|
|
@@ -1014,7 +1512,9 @@ async function findTags(dir) {
|
|
|
1014
1512
|
}
|
|
1015
1513
|
return tagged;
|
|
1016
1514
|
}
|
|
1017
|
-
var
|
|
1515
|
+
var VERSIONS = /\s+data-init=(?:"[^"]*"|'[^']*'|\{[^{}]*\})|,\s*['"]data-init['"]\s*:\s*['"][^'"]*['"]|(?<=agentface-lines)\/[0-9.]+/g;
|
|
1516
|
+
var loose = (text2) => text2.replace(VERSIONS, "").replace(/\s+/g, "").replace(/['"`]/g, '"').replace(/;/g, "").replace(/,(?=[\])}])/g, "");
|
|
1517
|
+
var namesInit = (text2) => /data-init|agentface-lines\/[0-9]/.test(text2);
|
|
1018
1518
|
var sameFile = (source, content) => loose(source) === loose(content);
|
|
1019
1519
|
function tagIn(source, tag) {
|
|
1020
1520
|
const old = source.match(TAG)?.[0];
|
|
@@ -1024,7 +1524,9 @@ function madeByInit(source) {
|
|
|
1024
1524
|
const gatsby = (pattern) => source.match(pattern)?.[1];
|
|
1025
1525
|
const load = gatsby(/key:\s*['"]agentface['"],\s*(async|defer):\s*true/);
|
|
1026
1526
|
const src = gatsby(/\bsrc:\s*['"]([^'"]+)['"]/);
|
|
1027
|
-
const
|
|
1527
|
+
const data = [...source.matchAll(/['"](data-[a-z-]+)['"]:\s*['"]([^'"]+)['"]/g)].map(
|
|
1528
|
+
([, name, value]) => ` ${name}="${value}"`
|
|
1529
|
+
);
|
|
1028
1530
|
const text2 = gatsby(
|
|
1029
1531
|
/createElement\(\s*['"]noscript['"],\s*\{\s*key:\s*['"]agentface['"],?\s*\},\s*['"]([^'"]*)['"],?\s*\)/
|
|
1030
1532
|
);
|
|
@@ -1032,9 +1534,11 @@ function madeByInit(source) {
|
|
|
1032
1534
|
[NEXT_DOCUMENT, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
|
|
1033
1535
|
[MU_PLUGIN, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
|
|
1034
1536
|
[PRESTASHOP_MODULE, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
|
|
1537
|
+
[MU_PLUGIN_HOOKS, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
|
|
1538
|
+
[PRESTASHOP_MODULE_HOOKS, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
|
|
1035
1539
|
[
|
|
1036
1540
|
GATSBY_SSR,
|
|
1037
|
-
load && src && `<script ${load} src="${src}"${
|
|
1541
|
+
load && src && `<script ${load} src="${src}"${data.join("")}></script>`,
|
|
1038
1542
|
text2 && `<noscript>${text2}</noscript>`
|
|
1039
1543
|
]
|
|
1040
1544
|
];
|
|
@@ -1196,23 +1700,12 @@ var exists2 = (file) => stat3(file).then(
|
|
|
1196
1700
|
);
|
|
1197
1701
|
var posix = path3.posix;
|
|
1198
1702
|
var BACKTICK = "`";
|
|
1199
|
-
function siteOf(tag) {
|
|
1200
|
-
const [, service = "", site = ""] = tag.match(/\bsrc="(https?:\/\/[^"]+?)\/s\/([^/"]+)\.js"/) ?? [];
|
|
1201
|
-
return { service, site };
|
|
1202
|
-
}
|
|
1203
|
-
var about = (comment2, how) => [
|
|
1204
|
-
`${OURS}. It asks Agentface for the two lines this`,
|
|
1205
|
-
"site's pages carry for AI agents, the tag and its notice, so that a change to",
|
|
1206
|
-
"them reaches the site by itself. It keeps them an hour and, while Agentface",
|
|
1207
|
-
"can't be reached, uses the copy it has: at first the one below.",
|
|
1208
|
-
how,
|
|
1209
|
-
"`npx agentface uninstall` deletes it."
|
|
1210
|
-
].join("\n").replace(/^/gm, comment2 + " ").replace(/ +$/gm, "");
|
|
1211
1703
|
var HOW = {
|
|
1212
1704
|
astro: "astro.config adds the integration, agentface(), whose middleware puts them\nin every page Astro makes.",
|
|
1213
1705
|
vite: "vite.config adds the plugin, agentface(), which puts them in index.html\nwhen the site is built.",
|
|
1214
1706
|
hono: "The app uses agentface() first, which puts them in every HTML page it sends.",
|
|
1215
|
-
fastify: "The app adds agentface as its first onSend hook, which puts them in every\nHTML page it sends as text."
|
|
1707
|
+
fastify: "The app adds agentface as its first onSend hook, which puts them in every\nHTML page it sends as text.",
|
|
1708
|
+
node: "The server's handler goes through agentface(), which puts them in every\nHTML page it sends."
|
|
1216
1709
|
};
|
|
1217
1710
|
var LINE_JS = (t) => String.raw`
|
|
1218
1711
|
// Exa, a search engine AI agents read the web through, runs no script and
|
|
@@ -1477,10 +1970,180 @@ ${out}function agentface(
|
|
|
1477
1970
|
reply.removeHeader('content-length');
|
|
1478
1971
|
done(null, page);
|
|
1479
1972
|
}
|
|
1973
|
+
`,
|
|
1974
|
+
node: String.raw`${insert}
|
|
1975
|
+
// Node's own server: the lines go into every HTML page the handler sends.
|
|
1976
|
+
// The handler is what http.createServer is given, or what a Vercel function
|
|
1977
|
+
// exports: a function of the request and the response.
|
|
1978
|
+
${out}function agentface${t("<Req extends { method?: string | undefined; headers: { upgrade?: unknown } } = IncomingMessage, Res extends Held = ServerResponse>")}(
|
|
1979
|
+
handler${t(": (req: Req, res: Res) => unknown")},
|
|
1980
|
+
)${t(": (req: Req, res: Res) => unknown")} {
|
|
1981
|
+
return function (${t("this: unknown, ")}req${t(": Req")}, res${t(": Res")}) {
|
|
1982
|
+
if (req.method === 'GET' && !req.headers.upgrade) hold(res);
|
|
1983
|
+
return handler.call(this, req, res);
|
|
1984
|
+
};
|
|
1985
|
+
}
|
|
1986
|
+
${t(`
|
|
1987
|
+
// What hold() uses of the response: Node's, or a host's that extends it. A
|
|
1988
|
+
// handler without types of its own, as one written in http.createServer(\u2026),
|
|
1989
|
+
// takes Node's.
|
|
1990
|
+
interface Held {
|
|
1991
|
+
statusCode: number;
|
|
1992
|
+
statusMessage?: string;
|
|
1993
|
+
getHeader(name: string): unknown;
|
|
1994
|
+
setHeader(name: string, value: number | string | readonly string[]): unknown;
|
|
1995
|
+
hasHeader(name: string): boolean;
|
|
1996
|
+
writeHead(...args: unknown[]): unknown;
|
|
1997
|
+
write(...args: unknown[]): unknown;
|
|
1998
|
+
end(...args: unknown[]): unknown;
|
|
1999
|
+
flushHeaders?(): void;
|
|
2000
|
+
}
|
|
2001
|
+
`)}
|
|
2002
|
+
// A header as writeHead was given it, in an object or a list of names and
|
|
2003
|
+
// values.
|
|
2004
|
+
function given(headers${t(": unknown")}, name${t(": string")}) {
|
|
2005
|
+
if (Array.isArray(headers)) {
|
|
2006
|
+
for (let i = 0; i + 1 < headers.length; i += 2) if (String(headers[i]).toLowerCase() === name) return headers[i + 1];
|
|
2007
|
+
} else if (headers && typeof headers === 'object') {
|
|
2008
|
+
for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === name) return value;
|
|
2009
|
+
}
|
|
2010
|
+
return undefined;
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
// The response, holding an HTML page until it ends, to send it then with the
|
|
2014
|
+
// lines in it and a length to match. A page sent compressed, in part, in a
|
|
2015
|
+
// character set other than UTF-8 or with a status other than 200 passes
|
|
2016
|
+
// straight on, and so does anything else.
|
|
2017
|
+
function hold(res${t(": Held")}) {
|
|
2018
|
+
const writeHead = res.writeHead.bind(res);
|
|
2019
|
+
const write = res.write.bind(res);
|
|
2020
|
+
const end = res.end.bind(res);
|
|
2021
|
+
const flushHeaders = res.flushHeaders?.bind(res);
|
|
2022
|
+
// The page so far while it's held, and null once it passes on.
|
|
2023
|
+
let page${t(": (string | Uint8Array)[] | null")} = null;
|
|
2024
|
+
let decided = false;
|
|
2025
|
+
let ended = false;
|
|
2026
|
+
const restore = () => {
|
|
2027
|
+
res.writeHead = writeHead;
|
|
2028
|
+
res.write = write;
|
|
2029
|
+
res.end = end;
|
|
2030
|
+
if (flushHeaders) res.flushHeaders = flushHeaders;
|
|
2031
|
+
};
|
|
2032
|
+
const decide = (status${t(": number")}, headers${t("?: unknown")}) => {
|
|
2033
|
+
if (decided) return;
|
|
2034
|
+
decided = true;
|
|
2035
|
+
const said = (name${t(": string")}) => String(given(headers, name) ?? res.getHeader(name) ?? '');
|
|
2036
|
+
const type = said('content-type');
|
|
2037
|
+
if (
|
|
2038
|
+
status === 200 &&
|
|
2039
|
+
/^text\/html\b/i.test(type) &&
|
|
2040
|
+
(!/;\s*charset=/i.test(type) || /;\s*charset="?utf-?8"?\s*(?:;|$)/i.test(type)) &&
|
|
2041
|
+
!said('content-encoding') &&
|
|
2042
|
+
!said('content-range')
|
|
2043
|
+
)
|
|
2044
|
+
page = [];
|
|
2045
|
+
else restore();
|
|
2046
|
+
};
|
|
2047
|
+
// What's held so far goes out as it is, and the rest passes straight on:
|
|
2048
|
+
// for a part the page can't be read in.
|
|
2049
|
+
const release = () => {
|
|
2050
|
+
const held = page ?? [];
|
|
2051
|
+
page = null;
|
|
2052
|
+
restore();
|
|
2053
|
+
writeHead(res.statusCode);
|
|
2054
|
+
for (const part of held) write(part);
|
|
2055
|
+
};
|
|
2056
|
+
// A part of the page, held. False when it can't be read: it passes on.
|
|
2057
|
+
const add = (chunk${t(": unknown")}, encoding${t(": unknown")}) => {
|
|
2058
|
+
if (chunk === undefined || chunk === null) return true;
|
|
2059
|
+
if (typeof chunk === 'string' && (typeof encoding !== 'string' || /^utf-?8$/i.test(encoding))) page?.push(chunk);
|
|
2060
|
+
else if (chunk instanceof Uint8Array) page?.push(chunk);
|
|
2061
|
+
else {
|
|
2062
|
+
release();
|
|
2063
|
+
return false;
|
|
2064
|
+
}
|
|
2065
|
+
return true;
|
|
2066
|
+
};
|
|
2067
|
+
res.writeHead = function (...args${t(": unknown[]")}) {
|
|
2068
|
+
if (ended) return res;
|
|
2069
|
+
const [status, second, third] = args;
|
|
2070
|
+
const headers = typeof second === 'string' ? third : second;
|
|
2071
|
+
decide(Number(status), headers);
|
|
2072
|
+
if (!page) return writeHead(...args);
|
|
2073
|
+
res.statusCode = Number(status);
|
|
2074
|
+
if (typeof second === 'string') res.statusMessage = second;
|
|
2075
|
+
// Its headers join those set before it, as Node's own writeHead does.
|
|
2076
|
+
const named = new Map${t("<string, { key: string; values: string[] }>")}();
|
|
2077
|
+
if (Array.isArray(headers))
|
|
2078
|
+
for (let i = 0; i + 1 < headers.length; i += 2) {
|
|
2079
|
+
const key = String(headers[i]);
|
|
2080
|
+
const entry = named.get(key.toLowerCase()) ?? { key, values: [] };
|
|
2081
|
+
entry.values.push(String(headers[i + 1]));
|
|
2082
|
+
named.set(key.toLowerCase(), entry);
|
|
2083
|
+
}
|
|
2084
|
+
else if (headers && typeof headers === 'object')
|
|
2085
|
+
for (const [key, value] of Object.entries(headers))
|
|
2086
|
+
if (value !== undefined && value !== null)
|
|
2087
|
+
named.set(key.toLowerCase(), { key, values: Array.isArray(value) ? value.map(String) : [String(value)] });
|
|
2088
|
+
for (const { key, values } of named.values()) res.setHeader(key, values.length === 1 ? values[0] : values);
|
|
2089
|
+
return res;
|
|
2090
|
+
};
|
|
2091
|
+
res.write = function (...args${t(": unknown[]")}) {
|
|
2092
|
+
if (ended) return false;
|
|
2093
|
+
decide(res.statusCode);
|
|
2094
|
+
if (!page) return write(...args);
|
|
2095
|
+
const done = typeof args[args.length - 1] === 'function' ? args.pop()${t(" as () => void")} : undefined;
|
|
2096
|
+
if (!add(args[0], args[1])) return write(...args, ...(done ? [done] : []));
|
|
2097
|
+
if (done) queueMicrotask(done);
|
|
2098
|
+
return true;
|
|
2099
|
+
};
|
|
2100
|
+
res.end = function (...args${t(": unknown[]")}) {
|
|
2101
|
+
if (ended) return res;
|
|
2102
|
+
decide(res.statusCode);
|
|
2103
|
+
if (!page) return end(...args);
|
|
2104
|
+
const done = typeof args[args.length - 1] === 'function' ? args.pop()${t(" as () => void")} : undefined;
|
|
2105
|
+
if (!add(args[0], args[1])) return end(...args, ...(done ? [done] : []));
|
|
2106
|
+
ended = true;
|
|
2107
|
+
const held = page;
|
|
2108
|
+
void send(held, done);
|
|
2109
|
+
return res;
|
|
2110
|
+
};
|
|
2111
|
+
if (flushHeaders)
|
|
2112
|
+
res.flushHeaders = function () {
|
|
2113
|
+
decide(res.statusCode);
|
|
2114
|
+
if (!page) flushHeaders();
|
|
2115
|
+
};
|
|
2116
|
+
// The page with the lines in it, or as it was, and its length.
|
|
2117
|
+
async function send(held${t(": (string | Uint8Array)[]")}, done${t("?: () => void")}) {
|
|
2118
|
+
const encoder = new TextEncoder();
|
|
2119
|
+
const parts = held.map((part) => (typeof part === 'string' ? encoder.encode(part) : part));
|
|
2120
|
+
const bytes = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
|
|
2121
|
+
let at = 0;
|
|
2122
|
+
for (const part of parts) {
|
|
2123
|
+
bytes.set(part, at);
|
|
2124
|
+
at += part.length;
|
|
2125
|
+
}
|
|
2126
|
+
let body = bytes;
|
|
2127
|
+
try {
|
|
2128
|
+
const html = new TextDecoder().decode(bytes);
|
|
2129
|
+
const policy = [res.getHeader('content-security-policy') ?? []].flat().join(',');
|
|
2130
|
+
const lines = await agentfaceLines();
|
|
2131
|
+
const out = insert(html, lines, policy);
|
|
2132
|
+
if (out !== html) body = encoder.encode(out);
|
|
2133
|
+
} catch {
|
|
2134
|
+
// The page as it was.
|
|
2135
|
+
}
|
|
2136
|
+
restore();
|
|
2137
|
+
if (!res.hasHeader('transfer-encoding')) res.setHeader('content-length', body.length);
|
|
2138
|
+
writeHead(res.statusCode);
|
|
2139
|
+
end(body, done);
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
1480
2142
|
`
|
|
1481
2143
|
};
|
|
2144
|
+
const types = kind === "node" ? t("import type { IncomingMessage, ServerResponse } from 'node:http';\n\n") : "";
|
|
1482
2145
|
return String.raw`${about("//", HOW[kind])}
|
|
1483
|
-
const SERVICE = '${service}';
|
|
2146
|
+
${types}const SERVICE = '${service}';
|
|
1484
2147
|
const SITE = '${site}';
|
|
1485
2148
|
const TAG = '${tag}';
|
|
1486
2149
|
const NOTICE = '${notice ?? ""}';
|
|
@@ -1495,7 +2158,7 @@ async function ask() {
|
|
|
1495
2158
|
let wait = 300_000;
|
|
1496
2159
|
try {
|
|
1497
2160
|
const response = await fetch(SERVICE + '/sites/' + SITE, {
|
|
1498
|
-
headers: { accept: 'application/json', 'user-agent': 'agentface-lines' },
|
|
2161
|
+
headers: { accept: 'application/json', 'user-agent': 'agentface-lines/${INIT}' },
|
|
1499
2162
|
signal: AbortSignal.timeout(2000),
|
|
1500
2163
|
});
|
|
1501
2164
|
const body = (response.ok ? await response.json() : null)${t(" as { tag?: unknown; notice?: unknown } | null")};
|
|
@@ -1578,7 +2241,7 @@ def _ask():
|
|
|
1578
2241
|
try:
|
|
1579
2242
|
request = urllib.request.Request(
|
|
1580
2243
|
SERVICE + "/sites/" + SITE,
|
|
1581
|
-
headers={"Accept": "application/json", "User-Agent": "agentface-lines"},
|
|
2244
|
+
headers={"Accept": "application/json", "User-Agent": "agentface-lines/${INIT}"},
|
|
1582
2245
|
)
|
|
1583
2246
|
with urllib.request.urlopen(request, timeout=2) as response:
|
|
1584
2247
|
body = json.loads(response.read().decode("utf-8"))
|
|
@@ -1986,7 +2649,7 @@ module Agentface
|
|
|
1986
2649
|
uri = URI("#{SERVICE}/sites/#{SITE}")
|
|
1987
2650
|
options = { use_ssl: uri.scheme == "https", open_timeout: 2, read_timeout: 2 }
|
|
1988
2651
|
response = Net::HTTP.start(uri.host, uri.port, **options) do |http|
|
|
1989
|
-
http.get(uri.request_uri, "Accept" => "application/json", "User-Agent" => "agentface-lines")
|
|
2652
|
+
http.get(uri.request_uri, "Accept" => "application/json", "User-Agent" => "agentface-lines/${INIT}")
|
|
1990
2653
|
end
|
|
1991
2654
|
if response.is_a?(Net::HTTPSuccess)
|
|
1992
2655
|
body = JSON.parse(response.body)
|
|
@@ -2306,7 +2969,7 @@ ${about(" #", "The endpoint plugs Agentface before its router, which puts them
|
|
|
2306
2969
|
|
|
2307
2970
|
defp ask do
|
|
2308
2971
|
url = String.to_charlist(@service <> "/sites/" <> @site)
|
|
2309
|
-
headers = [{~c"accept", ~c"application/json"}, {~c"user-agent", ~c"agentface-lines"}]
|
|
2972
|
+
headers = [{~c"accept", ~c"application/json"}, {~c"user-agent", ~c"agentface-lines/${INIT}"}]
|
|
2310
2973
|
|
|
2311
2974
|
with {:ok, _} <- Application.ensure_all_started(:inets),
|
|
2312
2975
|
{:ok, _} <- Application.ensure_all_started(:ssl),
|
|
@@ -2716,7 +3379,7 @@ func fetch() ([2]string, bool) {
|
|
|
2716
3379
|
return [2]string{}, false
|
|
2717
3380
|
}
|
|
2718
3381
|
req.Header.Set("Accept", "application/json")
|
|
2719
|
-
req.Header.Set("User-Agent", "agentface-lines")
|
|
3382
|
+
req.Header.Set("User-Agent", "agentface-lines/${INIT}")
|
|
2720
3383
|
res, err := client.Do(req)
|
|
2721
3384
|
if err != nil {
|
|
2722
3385
|
return [2]string{}, false
|
|
@@ -3284,16 +3947,16 @@ async function commonJs(p, file, source) {
|
|
|
3284
3947
|
if (file.endsWith(".cjs")) return true;
|
|
3285
3948
|
if (!file.endsWith(".js") || new RegExp(IMPORT.source, "m").test(source)) return false;
|
|
3286
3949
|
const pkg = JSON.parse(await p.read("package.json") ?? "{}");
|
|
3287
|
-
return pkg.type !== "module" && /\brequire\(
|
|
3950
|
+
return pkg.type !== "module" && /\brequire\(|^module\.exports\b/m.test(source);
|
|
3288
3951
|
}
|
|
3289
|
-
async function jsHelper(p, file, source, kind) {
|
|
3952
|
+
async function jsHelper(p, file, source, kind, prefix = "") {
|
|
3290
3953
|
const cjs = await commonJs(p, file, source);
|
|
3291
3954
|
const ts = /\.[cm]?tsx?$/.test(file);
|
|
3292
3955
|
const folder = posix.dirname(file) === "." ? "" : posix.dirname(file) + "/";
|
|
3293
3956
|
const deno = p.list.includes("deno.json") || p.list.includes("deno.jsonc");
|
|
3294
|
-
const name = cjs ? "agentface.cjs" : ts ? "agentface.ts" : file.endsWith(".mjs") ? "agentface.mjs" : "agentface.js";
|
|
3957
|
+
const name = prefix + (cjs ? "agentface.cjs" : ts ? "agentface.ts" : file.endsWith(".mjs") ? "agentface.mjs" : "agentface.js");
|
|
3295
3958
|
const helper = await own(p, folder + name, script(kind, { ts, cjs }));
|
|
3296
|
-
const from = "./" + (ts && !deno ? "agentface.js" : name);
|
|
3959
|
+
const from = "./" + (ts && !deno ? prefix + "agentface.js" : name);
|
|
3297
3960
|
return helper && { helper, cjs, from };
|
|
3298
3961
|
}
|
|
3299
3962
|
function chained(source, call, chain, cjs, from, after) {
|
|
@@ -3398,6 +4061,126 @@ async function fastify(p) {
|
|
|
3398
4061
|
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.`
|
|
3399
4062
|
});
|
|
3400
4063
|
}
|
|
4064
|
+
var escaped = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4065
|
+
var wrapped = (source, start, last) => source.slice(0, start) + "agentface(" + source.slice(start, last + 1) + ")" + source.slice(last + 1);
|
|
4066
|
+
function functionEnd(source, at) {
|
|
4067
|
+
const rest = source.slice(at);
|
|
4068
|
+
const declared = /^(?:async\s+)?function\b\s*\*?\s*[\w$]*\s*(?=\()/.exec(rest);
|
|
4069
|
+
const arrow = !declared && /^(?:async\s*)?\(/.exec(rest);
|
|
4070
|
+
if (declared || arrow) {
|
|
4071
|
+
const params = bracket(
|
|
4072
|
+
source,
|
|
4073
|
+
at + (declared ? declared[0].length : arrow[0].length - 1)
|
|
4074
|
+
);
|
|
4075
|
+
if (!params) return void 0;
|
|
4076
|
+
const after = source.slice(params.close + 1);
|
|
4077
|
+
const body = (declared ? /^\s*(?::[^{};=]*)?/ : /^\s*(?::[^{};=]*)?=>\s*/).exec(after);
|
|
4078
|
+
const open = params.close + 1 + (body?.[0].length ?? 0);
|
|
4079
|
+
if (!body || source[open] !== "{") return void 0;
|
|
4080
|
+
return bracket(source, open)?.close;
|
|
4081
|
+
}
|
|
4082
|
+
const name = /^[\w$]+(?:\.[\w$]+)*/.exec(rest);
|
|
4083
|
+
return name && /^[ \t]*(?:;|\r?\n|$)/.test(rest.slice(name[0].length)) ? at + name[0].length - 1 : void 0;
|
|
4084
|
+
}
|
|
4085
|
+
function requireFirst(source, line) {
|
|
4086
|
+
if (source.includes(line)) return source;
|
|
4087
|
+
const last = lastMatch(source, REQUIRE);
|
|
4088
|
+
if (last)
|
|
4089
|
+
return source.slice(0, last.index + last[0].length) + eolOf(source) + line + source.slice(last.index + last[0].length);
|
|
4090
|
+
const at = /^(['"])use strict\1;?[^\n]*\n/.exec(source)?.[0].length ?? 0;
|
|
4091
|
+
return source.slice(0, at) + line + eolOf(source) + source.slice(at);
|
|
4092
|
+
}
|
|
4093
|
+
var withHelper = (source, text2, cjs, from) => cjs ? requireFirst(text2, `const { agentface } = require('${from}');`) : addImport(text2, importLine(source, "{ agentface }", from));
|
|
4094
|
+
function vercelEntry(source, cjs, from) {
|
|
4095
|
+
if (/(?<![\w$.])agentface\(/.test(source)) return source;
|
|
4096
|
+
const made = /^export\s+default\s+/m.exec(source) ?? /^module\.exports\s*=\s*/m.exec(source);
|
|
4097
|
+
if (!made) return null;
|
|
4098
|
+
const at = made.index + made[0].length;
|
|
4099
|
+
const last = functionEnd(source, at);
|
|
4100
|
+
if (last === void 0) return null;
|
|
4101
|
+
const name = /^(?:async\s+)?function\b\s*\*?\s*([\w$]+)/.exec(source.slice(at))?.[1];
|
|
4102
|
+
const elsewhere = source.slice(0, at) + source.slice(last + 1);
|
|
4103
|
+
if (name && new RegExp(`(?<![\\w$.])${escaped(name)}(?![\\w$])`).test(elsewhere)) return null;
|
|
4104
|
+
return withHelper(source, wrapped(source, at, last), cjs, from);
|
|
4105
|
+
}
|
|
4106
|
+
var HTTP = String.raw`['"](?:node:)?https?['"]`;
|
|
4107
|
+
function serverEntry(source, cjs, from) {
|
|
4108
|
+
if (/(?<![\w$.])agentface\(/.test(source)) return source;
|
|
4109
|
+
const calls = [];
|
|
4110
|
+
const named = (list2, as) => {
|
|
4111
|
+
const found = list2.match(new RegExp(String.raw`\bcreateServer\b(?:${as.source}([\w$]+))?`));
|
|
4112
|
+
if (found) calls.push(escaped(found[1] ?? "createServer"));
|
|
4113
|
+
};
|
|
4114
|
+
for (const m of source.matchAll(
|
|
4115
|
+
new RegExp(
|
|
4116
|
+
String.raw`\bimport\s+(?:([\w$]+)\s*,?\s*)?(?:\*\s*as\s+([\w$]+)|\{([^}]*)\})?\s*from\s*${HTTP}`,
|
|
4117
|
+
"g"
|
|
4118
|
+
)
|
|
4119
|
+
)) {
|
|
4120
|
+
for (const space of [m[1], m[2]]) if (space) calls.push(escaped(space) + String.raw`\.createServer`);
|
|
4121
|
+
if (m[3]) named(m[3], /\s+as\s+/);
|
|
4122
|
+
}
|
|
4123
|
+
for (const m of source.matchAll(
|
|
4124
|
+
new RegExp(
|
|
4125
|
+
String.raw`\b(?:const|let|var)\s+(?:([\w$]+)|\{([^}]*)\})\s*=\s*require\(\s*${HTTP}\s*\)`,
|
|
4126
|
+
"g"
|
|
4127
|
+
)
|
|
4128
|
+
)) {
|
|
4129
|
+
if (m[1]) calls.push(escaped(m[1]) + String.raw`\.createServer`);
|
|
4130
|
+
if (m[2]) named(m[2], /\s*:\s*/);
|
|
4131
|
+
}
|
|
4132
|
+
calls.push(String.raw`require\(\s*${HTTP}\s*\)\.createServer`);
|
|
4133
|
+
const call = new RegExp(String.raw`(?<![\w$.])(?:${calls.join("|")})\s*\(`, "g");
|
|
4134
|
+
for (let m; m = call.exec(source); ) {
|
|
4135
|
+
const open = m.index + m[0].length - 1;
|
|
4136
|
+
const args = bracket(source, open);
|
|
4137
|
+
if (!args || args.commas.length > 1) continue;
|
|
4138
|
+
const begin = args.commas.length ? args.commas[0] + 1 : open + 1;
|
|
4139
|
+
const piece = source.slice(begin, args.close);
|
|
4140
|
+
const start = begin + piece.search(/\S/);
|
|
4141
|
+
const last = begin + piece.trimEnd().length - 1;
|
|
4142
|
+
if (start > last || !args.commas.length && source[start] === "{") continue;
|
|
4143
|
+
return withHelper(source, wrapped(source, start, last), cjs, from);
|
|
4144
|
+
}
|
|
4145
|
+
return null;
|
|
4146
|
+
}
|
|
4147
|
+
async function vercelPages(p) {
|
|
4148
|
+
let config2;
|
|
4149
|
+
try {
|
|
4150
|
+
config2 = JSON.parse(await p.read("vercel.json") ?? "null");
|
|
4151
|
+
} catch {
|
|
4152
|
+
return null;
|
|
4153
|
+
}
|
|
4154
|
+
const rules = (list2) => Array.isArray(list2) ? list2 : [];
|
|
4155
|
+
const routes2 = [
|
|
4156
|
+
...rules(config2?.rewrites).map((rule) => [rule?.source, rule?.destination]),
|
|
4157
|
+
...rules(config2?.routes).map((rule) => [rule?.src, rule?.dest])
|
|
4158
|
+
];
|
|
4159
|
+
for (const [from, to] of routes2) {
|
|
4160
|
+
if (typeof from !== "string" || typeof to !== "string" || /^\/api(?:\/|$)/.test(from)) continue;
|
|
4161
|
+
const route = /^\/(api(?:\/[\w.-]+)*)\/?(?:[?#]|$)/.exec(to)?.[1].replace(/\.[cm]?[jt]s$/, "");
|
|
4162
|
+
const file = route && p.list.find((f) => new RegExp(`^${escaped(route)}(?:/index)?\\.[cm]?[jt]s$`).test(f));
|
|
4163
|
+
const source = file ? await p.read(file) : null;
|
|
4164
|
+
if (file && source && vercelEntry(source, false, "") !== null) return { file, source };
|
|
4165
|
+
}
|
|
4166
|
+
return null;
|
|
4167
|
+
}
|
|
4168
|
+
async function node(p) {
|
|
4169
|
+
const vercel = await vercelPages(p);
|
|
4170
|
+
const found = vercel ?? await entry(p, (source) => serverEntry(source, false, "") !== null);
|
|
4171
|
+
if (!found) return null;
|
|
4172
|
+
const edit = vercel ? vercelEntry : serverEntry;
|
|
4173
|
+
const made = await jsHelper(p, found.file, found.source, "node", vercel ? "_" : "");
|
|
4174
|
+
if (!made || edit(found.source, made.cjs, made.from) === null) return null;
|
|
4175
|
+
return result(p, vercel ? "Vercel function" : "Node.js", {
|
|
4176
|
+
creates: [made.helper],
|
|
4177
|
+
edits: [
|
|
4178
|
+
...cleaned(p.found),
|
|
4179
|
+
{ file: found.file, source: found.source, edit: (text2) => edit(text2, made.cjs, made.from) ?? text2 }
|
|
4180
|
+
],
|
|
4181
|
+
note: NOTE.request(made.helper.file)
|
|
4182
|
+
});
|
|
4183
|
+
}
|
|
3401
4184
|
function addPythonImport(source, line) {
|
|
3402
4185
|
if (new RegExp(`^${line.replace(/[.]/g, "\\.")}\\s*$`, "m").test(source)) return source;
|
|
3403
4186
|
const lines = source.split("\n");
|
|
@@ -3752,7 +4535,7 @@ const SITE = '${site}';
|
|
|
3752
4535
|
async function ask() {
|
|
3753
4536
|
try {
|
|
3754
4537
|
const response = await fetch(SERVICE + '/sites/' + SITE, {
|
|
3755
|
-
headers: { accept: 'application/json', 'user-agent': 'agentface-lines' },
|
|
4538
|
+
headers: { accept: 'application/json', 'user-agent': 'agentface-lines/${INIT}' },
|
|
3756
4539
|
signal: AbortSignal.timeout(2000),
|
|
3757
4540
|
});
|
|
3758
4541
|
const body = response.ok ? await response.json() : null;
|
|
@@ -3962,10 +4745,10 @@ async function next(p) {
|
|
|
3962
4745
|
});
|
|
3963
4746
|
}
|
|
3964
4747
|
var WRITERS = [
|
|
3965
|
-
...["astro", "vite", "hono", "fastify"].flatMap((kind) => [
|
|
4748
|
+
...["astro", "vite", "hono", "fastify", "node"].flatMap((kind) => [
|
|
3966
4749
|
script(kind),
|
|
3967
4750
|
script(kind, { ts: true }),
|
|
3968
|
-
...kind === "fastify" || kind === "hono" ? [script(kind, { cjs: true })] : []
|
|
4751
|
+
...kind === "fastify" || kind === "hono" || kind === "node" ? [script(kind, { cjs: true })] : []
|
|
3969
4752
|
]),
|
|
3970
4753
|
DJANGO,
|
|
3971
4754
|
ASGI,
|
|
@@ -3986,7 +4769,7 @@ function ownFile(source) {
|
|
|
3986
4769
|
const { tag, notice } = linesIn(source);
|
|
3987
4770
|
return Boolean(tag && WRITERS.some((write) => sameFile(source, write(tag, notice))));
|
|
3988
4771
|
}
|
|
3989
|
-
var FRAMEWORKS2 = [rails, phoenix, django, fastapi, go, next, astro, hono, fastify, vite];
|
|
4772
|
+
var FRAMEWORKS2 = [rails, phoenix, django, fastapi, go, next, astro, hono, fastify, vite, node];
|
|
3990
4773
|
async function withFramework(dir, found) {
|
|
3991
4774
|
if (found.manual && !found.manual.none) return found;
|
|
3992
4775
|
if (["WordPress", "PrestaShop", "PrestaShop theme"].includes(found.framework)) return found;
|
|
@@ -3999,10 +4782,12 @@ async function withFramework(dir, found) {
|
|
|
3999
4782
|
}
|
|
4000
4783
|
return found;
|
|
4001
4784
|
}
|
|
4785
|
+
var IMPORTED = /import \{ agentface \} from ['"]\.\/(?:src\/)?_?agentface\.[cm]?[jt]s['"];?/;
|
|
4786
|
+
var REQUIRED = /const \{ agentface \} = require\(['"]\.\/_?agentface\.c?js['"]\);/;
|
|
4002
4787
|
var UNDO = [
|
|
4003
4788
|
/plug Agentface(?![\w.])/,
|
|
4004
|
-
|
|
4005
|
-
|
|
4789
|
+
IMPORTED,
|
|
4790
|
+
REQUIRED,
|
|
4006
4791
|
".use(agentface())",
|
|
4007
4792
|
".addHook('onSend', agentface)",
|
|
4008
4793
|
/^[ \t]*\w+\.add_middleware\(agentface\.Middleware\)/,
|
|
@@ -4014,6 +4799,15 @@ var UNDO = [
|
|
|
4014
4799
|
NEXT_NOTICE,
|
|
4015
4800
|
new RegExp(NEXT_IMPORTED.source.slice(1), "m")
|
|
4016
4801
|
];
|
|
4802
|
+
function unwrapped(text2) {
|
|
4803
|
+
for (let at; (at = text2.search(/(?<![\w$.])agentface\((?!\s*\))/)) !== -1; ) {
|
|
4804
|
+
const open = at + "agentface".length;
|
|
4805
|
+
const close = bracket(text2, open)?.close;
|
|
4806
|
+
if (close === void 0) break;
|
|
4807
|
+
text2 = text2.slice(0, at) + text2.slice(open + 1, close) + text2.slice(close + 1);
|
|
4808
|
+
}
|
|
4809
|
+
return text2;
|
|
4810
|
+
}
|
|
4017
4811
|
async function undoFrameworks(dir) {
|
|
4018
4812
|
const { list: list2 } = await project(dir);
|
|
4019
4813
|
const edits = [];
|
|
@@ -4031,6 +4825,7 @@ async function undoFrameworks(dir) {
|
|
|
4031
4825
|
text2 = text2.replace(/(\bdefineConfig\(|export default )\{\r?\n\}/, "$1{}");
|
|
4032
4826
|
text2 = text2.replace(/^[ \t]*['"]agentface\.Middleware['"],[ \t]*\r?\n/m, "").replace(/['"]agentface\.Middleware['"],\s*/, "").replace(/,\s*['"]agentface\.Middleware['"]/, "");
|
|
4033
4827
|
if (NEXT_CONFIGS.includes(file)) text2 = withoutNextConfig(text2);
|
|
4828
|
+
if (IMPORTED.test(source) || REQUIRED.test(source)) text2 = unwrapped(text2);
|
|
4034
4829
|
if (file.endsWith(".go")) {
|
|
4035
4830
|
text2 = text2.replace(/agentface\.Handler\(http\.DefaultServeMux\)/g, "nil");
|
|
4036
4831
|
for (let at; (at = text2.indexOf("agentface.Handler(")) !== -1; ) {
|
|
@@ -8661,20 +9456,20 @@ var defaultTreeAdapter = {
|
|
|
8661
9456
|
return templateElement.content;
|
|
8662
9457
|
},
|
|
8663
9458
|
setDocumentType(document, name, publicId, systemId) {
|
|
8664
|
-
const doctypeNode = document.childNodes.find((
|
|
9459
|
+
const doctypeNode = document.childNodes.find((node2) => node2.nodeName === "#documentType");
|
|
8665
9460
|
if (doctypeNode) {
|
|
8666
9461
|
doctypeNode.name = name;
|
|
8667
9462
|
doctypeNode.publicId = publicId;
|
|
8668
9463
|
doctypeNode.systemId = systemId;
|
|
8669
9464
|
} else {
|
|
8670
|
-
const
|
|
9465
|
+
const node2 = {
|
|
8671
9466
|
nodeName: "#documentType",
|
|
8672
9467
|
name,
|
|
8673
9468
|
publicId,
|
|
8674
9469
|
systemId,
|
|
8675
9470
|
parentNode: null
|
|
8676
9471
|
};
|
|
8677
|
-
defaultTreeAdapter.appendChild(document,
|
|
9472
|
+
defaultTreeAdapter.appendChild(document, node2);
|
|
8678
9473
|
}
|
|
8679
9474
|
},
|
|
8680
9475
|
setDocumentMode(document, mode) {
|
|
@@ -8683,11 +9478,11 @@ var defaultTreeAdapter = {
|
|
|
8683
9478
|
getDocumentMode(document) {
|
|
8684
9479
|
return document.mode;
|
|
8685
9480
|
},
|
|
8686
|
-
detachNode(
|
|
8687
|
-
if (
|
|
8688
|
-
const idx =
|
|
8689
|
-
|
|
8690
|
-
|
|
9481
|
+
detachNode(node2) {
|
|
9482
|
+
if (node2.parentNode) {
|
|
9483
|
+
const idx = node2.parentNode.childNodes.indexOf(node2);
|
|
9484
|
+
node2.parentNode.childNodes.splice(idx, 1);
|
|
9485
|
+
node2.parentNode = null;
|
|
8691
9486
|
}
|
|
8692
9487
|
},
|
|
8693
9488
|
insertText(parentNode, text2) {
|
|
@@ -8717,14 +9512,14 @@ var defaultTreeAdapter = {
|
|
|
8717
9512
|
}
|
|
8718
9513
|
},
|
|
8719
9514
|
//Tree traversing
|
|
8720
|
-
getFirstChild(
|
|
8721
|
-
return
|
|
9515
|
+
getFirstChild(node2) {
|
|
9516
|
+
return node2.childNodes[0];
|
|
8722
9517
|
},
|
|
8723
|
-
getChildNodes(
|
|
8724
|
-
return
|
|
9518
|
+
getChildNodes(node2) {
|
|
9519
|
+
return node2.childNodes;
|
|
8725
9520
|
},
|
|
8726
|
-
getParentNode(
|
|
8727
|
-
return
|
|
9521
|
+
getParentNode(node2) {
|
|
9522
|
+
return node2.parentNode;
|
|
8728
9523
|
},
|
|
8729
9524
|
getAttrList(element) {
|
|
8730
9525
|
return element.attrs;
|
|
@@ -8752,27 +9547,27 @@ var defaultTreeAdapter = {
|
|
|
8752
9547
|
return doctypeNode.systemId;
|
|
8753
9548
|
},
|
|
8754
9549
|
//Node types
|
|
8755
|
-
isTextNode(
|
|
8756
|
-
return
|
|
9550
|
+
isTextNode(node2) {
|
|
9551
|
+
return node2.nodeName === "#text";
|
|
8757
9552
|
},
|
|
8758
|
-
isCommentNode(
|
|
8759
|
-
return
|
|
9553
|
+
isCommentNode(node2) {
|
|
9554
|
+
return node2.nodeName === "#comment";
|
|
8760
9555
|
},
|
|
8761
|
-
isDocumentTypeNode(
|
|
8762
|
-
return
|
|
9556
|
+
isDocumentTypeNode(node2) {
|
|
9557
|
+
return node2.nodeName === "#documentType";
|
|
8763
9558
|
},
|
|
8764
|
-
isElementNode(
|
|
8765
|
-
return Object.prototype.hasOwnProperty.call(
|
|
9559
|
+
isElementNode(node2) {
|
|
9560
|
+
return Object.prototype.hasOwnProperty.call(node2, "tagName");
|
|
8766
9561
|
},
|
|
8767
9562
|
// Source code location
|
|
8768
|
-
setNodeSourceCodeLocation(
|
|
8769
|
-
|
|
9563
|
+
setNodeSourceCodeLocation(node2, location) {
|
|
9564
|
+
node2.sourceCodeLocation = location;
|
|
8770
9565
|
},
|
|
8771
|
-
getNodeSourceCodeLocation(
|
|
8772
|
-
return
|
|
9566
|
+
getNodeSourceCodeLocation(node2) {
|
|
9567
|
+
return node2.sourceCodeLocation;
|
|
8773
9568
|
},
|
|
8774
|
-
updateNodeSourceCodeLocation(
|
|
8775
|
-
|
|
9569
|
+
updateNodeSourceCodeLocation(node2, endLocation) {
|
|
9570
|
+
node2.sourceCodeLocation = { ...node2.sourceCodeLocation, ...endLocation };
|
|
8776
9571
|
}
|
|
8777
9572
|
};
|
|
8778
9573
|
|
|
@@ -9232,19 +10027,19 @@ var Parser = class {
|
|
|
9232
10027
|
}
|
|
9233
10028
|
//Stack events
|
|
9234
10029
|
/** @internal */
|
|
9235
|
-
onItemPush(
|
|
10030
|
+
onItemPush(node2, tid, isTop) {
|
|
9236
10031
|
var _a, _b;
|
|
9237
|
-
(_b = (_a = this.treeAdapter).onItemPush) === null || _b === void 0 ? void 0 : _b.call(_a,
|
|
10032
|
+
(_b = (_a = this.treeAdapter).onItemPush) === null || _b === void 0 ? void 0 : _b.call(_a, node2);
|
|
9238
10033
|
if (isTop && this.openElements.stackTop > 0)
|
|
9239
|
-
this._setContextModes(
|
|
10034
|
+
this._setContextModes(node2, tid);
|
|
9240
10035
|
}
|
|
9241
10036
|
/** @internal */
|
|
9242
|
-
onItemPop(
|
|
10037
|
+
onItemPop(node2, isTop) {
|
|
9243
10038
|
var _a, _b;
|
|
9244
10039
|
if (this.options.sourceCodeLocationInfo) {
|
|
9245
|
-
this._setEndLocation(
|
|
10040
|
+
this._setEndLocation(node2, this.currentToken);
|
|
9246
10041
|
}
|
|
9247
|
-
(_b = (_a = this.treeAdapter).onItemPop) === null || _b === void 0 ? void 0 : _b.call(_a,
|
|
10042
|
+
(_b = (_a = this.treeAdapter).onItemPop) === null || _b === void 0 ? void 0 : _b.call(_a, node2, this.openElements.current);
|
|
9248
10043
|
if (isTop) {
|
|
9249
10044
|
let current2;
|
|
9250
10045
|
let currentTagId;
|
|
@@ -9281,13 +10076,13 @@ var Parser = class {
|
|
|
9281
10076
|
}
|
|
9282
10077
|
/** @protected */
|
|
9283
10078
|
_findFormInFragmentContext() {
|
|
9284
|
-
let
|
|
9285
|
-
while (
|
|
9286
|
-
if (this.treeAdapter.getTagName(
|
|
9287
|
-
this.formElement =
|
|
10079
|
+
let node2 = this.fragmentContext;
|
|
10080
|
+
while (node2) {
|
|
10081
|
+
if (this.treeAdapter.getTagName(node2) === TAG_NAMES.FORM) {
|
|
10082
|
+
this.formElement = node2;
|
|
9288
10083
|
break;
|
|
9289
10084
|
}
|
|
9290
|
-
|
|
10085
|
+
node2 = this.treeAdapter.getParentNode(node2);
|
|
9291
10086
|
}
|
|
9292
10087
|
}
|
|
9293
10088
|
_initTokenizerForFragmentParsing() {
|
|
@@ -9329,7 +10124,7 @@ var Parser = class {
|
|
|
9329
10124
|
this.treeAdapter.setDocumentType(this.document, name, publicId, systemId);
|
|
9330
10125
|
if (token.location) {
|
|
9331
10126
|
const documentChildren = this.treeAdapter.getChildNodes(this.document);
|
|
9332
|
-
const docTypeNode = documentChildren.find((
|
|
10127
|
+
const docTypeNode = documentChildren.find((node2) => this.treeAdapter.isDocumentTypeNode(node2));
|
|
9333
10128
|
if (docTypeNode) {
|
|
9334
10129
|
this.treeAdapter.setNodeSourceCodeLocation(docTypeNode, token.location);
|
|
9335
10130
|
}
|
|
@@ -12392,41 +13187,41 @@ function mark(source, first) {
|
|
|
12392
13187
|
return { text: text2, offsets };
|
|
12393
13188
|
}
|
|
12394
13189
|
var unmark = (text2) => text2.replace(MARKED, "");
|
|
12395
|
-
var elements = (
|
|
12396
|
-
for (const child of
|
|
13190
|
+
var elements = (node2, out = []) => {
|
|
13191
|
+
for (const child of node2.childNodes ?? [])
|
|
12397
13192
|
if (child.tagName) {
|
|
12398
13193
|
out.push(child);
|
|
12399
13194
|
elements(child, out);
|
|
12400
13195
|
}
|
|
12401
13196
|
return out;
|
|
12402
13197
|
};
|
|
12403
|
-
var text = (
|
|
12404
|
-
var attribute = (
|
|
12405
|
-
var outside = (
|
|
12406
|
-
for (let at =
|
|
13198
|
+
var text = (node2) => node2.nodeName === "#text" ? node2.value ?? "" : (node2.childNodes ?? []).map(text).join("");
|
|
13199
|
+
var attribute = (node2, name) => node2.attrs?.find((attr) => attr.name === name)?.value;
|
|
13200
|
+
var outside = (node2) => {
|
|
13201
|
+
for (let at = node2; at; at = at.parentNode)
|
|
12407
13202
|
if (OUTSIDE.has(at.tagName ?? "") || attribute(at, "hidden") !== void 0 || attribute(at, "role") === "dialog")
|
|
12408
13203
|
return true;
|
|
12409
13204
|
return false;
|
|
12410
13205
|
};
|
|
12411
|
-
var isLine = (
|
|
13206
|
+
var isLine = (node2) => node2.tagName === "span" && (attribute(node2, "class") ?? "").split(/\s+/).includes("agentface-api");
|
|
12412
13207
|
function readPage(html) {
|
|
12413
13208
|
const all = elements(parse(html));
|
|
12414
13209
|
const marks = /* @__PURE__ */ new Map();
|
|
12415
|
-
for (const
|
|
12416
|
-
const value = attribute(
|
|
13210
|
+
for (const node2 of all) {
|
|
13211
|
+
const value = attribute(node2, MARK);
|
|
12417
13212
|
if (value) marks.set(Number(value), (marks.get(Number(value)) ?? 0) + 1);
|
|
12418
13213
|
}
|
|
12419
13214
|
const paragraphsIn = (root) => {
|
|
12420
13215
|
const inside = elements(root);
|
|
12421
|
-
const heading = inside.findIndex((
|
|
13216
|
+
const heading = inside.findIndex((node2) => node2.tagName === "h1");
|
|
12422
13217
|
const found = inside.filter(
|
|
12423
|
-
(
|
|
13218
|
+
(node2) => node2.tagName === "p" && text(node2).trim().length >= SHORTEST && !outside(node2)
|
|
12424
13219
|
);
|
|
12425
|
-
const after = found.filter((
|
|
12426
|
-
return [...after, ...found.filter((
|
|
13220
|
+
const after = found.filter((node2) => heading >= 0 && inside.indexOf(node2) > heading);
|
|
13221
|
+
return [...after, ...found.filter((node2) => !after.includes(node2))];
|
|
12427
13222
|
};
|
|
12428
|
-
const main2 = all.find((
|
|
12429
|
-
const body = all.find((
|
|
13223
|
+
const main2 = all.find((node2) => node2.tagName === "main");
|
|
13224
|
+
const body = all.find((node2) => node2.tagName === "body");
|
|
12430
13225
|
let paragraphs = main2 ? paragraphsIn(main2) : [];
|
|
12431
13226
|
if (!paragraphs.length && body) paragraphs = paragraphsIn(body);
|
|
12432
13227
|
const lines = all.filter(isLine);
|
|
@@ -12435,9 +13230,9 @@ function readPage(html) {
|
|
|
12435
13230
|
lines: lines.length,
|
|
12436
13231
|
// Whether the page's one line ends its first paragraph after its heading.
|
|
12437
13232
|
first: lines.length === 1 && !!paragraphs[0] && elements(paragraphs[0]).some(isLine),
|
|
12438
|
-
paragraphs: paragraphs.map((
|
|
12439
|
-
const value = attribute(
|
|
12440
|
-
return { mark: value ? Number(value) : null, text: text(
|
|
13233
|
+
paragraphs: paragraphs.map((node2) => {
|
|
13234
|
+
const value = attribute(node2, MARK);
|
|
13235
|
+
return { mark: value ? Number(value) : null, text: text(node2).replace(/\s+/g, " ").trim() };
|
|
12441
13236
|
})
|
|
12442
13237
|
};
|
|
12443
13238
|
}
|
|
@@ -12531,8 +13326,8 @@ function routeOf(found, path6) {
|
|
|
12531
13326
|
}
|
|
12532
13327
|
function links(html, origin) {
|
|
12533
13328
|
const out = [];
|
|
12534
|
-
for (const
|
|
12535
|
-
const href =
|
|
13329
|
+
for (const node2 of elements(parse(html))) {
|
|
13330
|
+
const href = node2.tagName === "a" ? attribute(node2, "href") : void 0;
|
|
12536
13331
|
if (!href) continue;
|
|
12537
13332
|
let url;
|
|
12538
13333
|
try {
|
|
@@ -12916,7 +13711,7 @@ async function lookupSite(service, id, fetcher = fetch) {
|
|
|
12916
13711
|
{ unknownSite: true }
|
|
12917
13712
|
);
|
|
12918
13713
|
if (!response.ok) throw new Error(body?.message ?? `Agentface answered HTTP ${response.status}`);
|
|
12919
|
-
return { ...body.site, tag: body.tag, notice: body.notice ?? null };
|
|
13714
|
+
return { ...body.site, tag: stamped(body.tag), notice: body.notice ?? null };
|
|
12920
13715
|
}
|
|
12921
13716
|
async function register(service, url, fetcher = fetch) {
|
|
12922
13717
|
const { response, body } = await reach(
|
|
@@ -12927,7 +13722,7 @@ async function register(service, url, fetcher = fetch) {
|
|
|
12927
13722
|
);
|
|
12928
13723
|
if (!response.ok || !body?.site?.id)
|
|
12929
13724
|
throw new Error(body?.message ?? `Agentface could not register ${url} (HTTP ${response.status})`);
|
|
12930
|
-
return { ...body.site, expiresAt: body.expiresAt, tag: body.tag, notice: body.notice ?? null };
|
|
13725
|
+
return { ...body.site, expiresAt: body.expiresAt, tag: stamped(body.tag), notice: body.notice ?? null };
|
|
12931
13726
|
}
|
|
12932
13727
|
async function confirm(service, id, fetcher = fetch) {
|
|
12933
13728
|
const { response, body } = await reach(
|
|
@@ -13182,7 +13977,7 @@ ${manual.steps(site.tag, site.notice)}`);
|
|
|
13182
13977
|
return { site, files: [], written: false };
|
|
13183
13978
|
}
|
|
13184
13979
|
function prestaShopSteps(file) {
|
|
13185
|
-
const what = `That file is a PrestaShop module of Agentface's own, which puts the tag on every page of the shop whatever its theme, and which updates of PrestaShop and of the theme leave alone.`;
|
|
13980
|
+
const what = `That file is a PrestaShop module of Agentface's own, which puts the tag on every page of the shop whatever its theme, and which updates of PrestaShop and of the 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.`;
|
|
13186
13981
|
const cache = "If the shop has a cache module, clear its cache, so that the pages show the tag.";
|
|
13187
13982
|
if (file.endsWith(".zip"))
|
|
13188
13983
|
return `${what} In the shop's back office, open Modules > Module Manager, click Upload a module and choose ${file}: PrestaShop installs it. ${cache}`;
|
|
@@ -13251,7 +14046,8 @@ async function init({
|
|
|
13251
14046
|
before.set(file, source);
|
|
13252
14047
|
const old = typeof source === "string" ? source : null;
|
|
13253
14048
|
const made = content(old === null ? site.tag : tagIn(old, site.tag), site.notice);
|
|
13254
|
-
|
|
14049
|
+
const same = old !== null && typeof made === "string" && sameFile(old, made) && (namesInit(old) || !namesInit(made));
|
|
14050
|
+
after.set(file, same ? old : made);
|
|
13255
14051
|
}
|
|
13256
14052
|
for (const { file, source, edit } of found.edits ?? []) {
|
|
13257
14053
|
if (!before.has(file)) before.set(file, source);
|
|
@@ -13333,7 +14129,7 @@ async function init({
|
|
|
13333
14129
|
if (found.framework === "PrestaShop theme") log(PRESTASHOP_THEME);
|
|
13334
14130
|
if (found.framework === "WordPress")
|
|
13335
14131
|
log(
|
|
13336
|
-
`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. 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.`
|
|
14132
|
+
`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.`
|
|
13337
14133
|
);
|
|
13338
14134
|
if (warning) log(warning);
|
|
13339
14135
|
if (!pr) {
|