agentface 0.5.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agentface.mjs +563 -41
- package/package.json +1 -1
package/dist/agentface.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { parseArgs } from "node:util";
|
|
|
5
5
|
|
|
6
6
|
// cli/init.mts
|
|
7
7
|
import { execFile as execFile2 } from "node:child_process";
|
|
8
|
-
import { mkdir, readFile as readFile2, rm, writeFile } from "node:fs/promises";
|
|
8
|
+
import { mkdir, readFile as readFile2, rm, rmdir, writeFile } from "node:fs/promises";
|
|
9
9
|
import path2 from "node:path";
|
|
10
10
|
|
|
11
11
|
// worker/origin.ts
|
|
@@ -57,6 +57,60 @@ function headEnd(html) {
|
|
|
57
57
|
return -1;
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
// cli/zip.mts
|
|
61
|
+
import { deflateRawSync } from "node:zlib";
|
|
62
|
+
var CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
|
|
63
|
+
let c = n;
|
|
64
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
65
|
+
return c >>> 0;
|
|
66
|
+
});
|
|
67
|
+
function crc32(data) {
|
|
68
|
+
let c = 4294967295;
|
|
69
|
+
for (const byte of data) c = CRC_TABLE[(c ^ byte) & 255] ^ c >>> 8;
|
|
70
|
+
return (c ^ 4294967295) >>> 0;
|
|
71
|
+
}
|
|
72
|
+
function zip(files2, date = /* @__PURE__ */ new Date()) {
|
|
73
|
+
const time = date.getHours() << 11 | date.getMinutes() << 5 | date.getSeconds() >> 1;
|
|
74
|
+
const day = date.getFullYear() - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate();
|
|
75
|
+
const parts = [];
|
|
76
|
+
const directory = [];
|
|
77
|
+
let offset = 0;
|
|
78
|
+
for (const [name, text] of Object.entries(files2)) {
|
|
79
|
+
const data = Buffer.from(text);
|
|
80
|
+
const packed = deflateRawSync(data);
|
|
81
|
+
const path3 = Buffer.from(name);
|
|
82
|
+
const shared = Buffer.alloc(26);
|
|
83
|
+
shared.writeUInt16LE(20, 0);
|
|
84
|
+
shared.writeUInt16LE(2048, 2);
|
|
85
|
+
shared.writeUInt16LE(8, 4);
|
|
86
|
+
shared.writeUInt16LE(time, 6);
|
|
87
|
+
shared.writeUInt16LE(day, 8);
|
|
88
|
+
shared.writeUInt32LE(crc32(data), 10);
|
|
89
|
+
shared.writeUInt32LE(packed.length, 14);
|
|
90
|
+
shared.writeUInt32LE(data.length, 18);
|
|
91
|
+
shared.writeUInt16LE(path3.length, 22);
|
|
92
|
+
const local = Buffer.alloc(4);
|
|
93
|
+
local.writeUInt32LE(67324752);
|
|
94
|
+
parts.push(local, shared, path3, packed);
|
|
95
|
+
const entry = Buffer.alloc(46);
|
|
96
|
+
entry.writeUInt32LE(33639248, 0);
|
|
97
|
+
entry.writeUInt16LE(788, 4);
|
|
98
|
+
shared.copy(entry, 6);
|
|
99
|
+
entry.writeUInt32LE(33188 * 65536, 38);
|
|
100
|
+
entry.writeUInt32LE(offset, 42);
|
|
101
|
+
directory.push(entry, path3);
|
|
102
|
+
offset += 4 + shared.length + path3.length + packed.length;
|
|
103
|
+
}
|
|
104
|
+
const size = directory.reduce((total, part) => total + part.length, 0);
|
|
105
|
+
const end = Buffer.alloc(22);
|
|
106
|
+
end.writeUInt32LE(101010256, 0);
|
|
107
|
+
end.writeUInt16LE(Object.keys(files2).length, 8);
|
|
108
|
+
end.writeUInt16LE(Object.keys(files2).length, 10);
|
|
109
|
+
end.writeUInt32LE(size, 12);
|
|
110
|
+
end.writeUInt32LE(offset, 16);
|
|
111
|
+
return Buffer.concat([...parts, ...directory, end]);
|
|
112
|
+
}
|
|
113
|
+
|
|
60
114
|
// cli/heads.mts
|
|
61
115
|
var EXTENSIONS = [
|
|
62
116
|
"html",
|
|
@@ -74,6 +128,7 @@ var EXTENSIONS = [
|
|
|
74
128
|
"jinja2",
|
|
75
129
|
"j2",
|
|
76
130
|
"tmpl",
|
|
131
|
+
"tpl",
|
|
77
132
|
"astro"
|
|
78
133
|
];
|
|
79
134
|
var MARKUP = new RegExp(`\\.(?:${EXTENSIONS.join("|")})$`, "i");
|
|
@@ -135,6 +190,64 @@ var exists = (file) => stat(file).then(
|
|
|
135
190
|
() => true,
|
|
136
191
|
() => false
|
|
137
192
|
);
|
|
193
|
+
var THEME = /^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name\s*:/im;
|
|
194
|
+
async function isWordPress(dir) {
|
|
195
|
+
if (THEME.test((await read(path.join(dir, "style.css")) ?? "").slice(0, 8192))) return true;
|
|
196
|
+
for (const name of ["wp-content", "wp-includes"]) if (await exists(path.join(dir, name))) return true;
|
|
197
|
+
for (let at = path.resolve(dir); ; at = path.dirname(at)) {
|
|
198
|
+
if (path.basename(at) === "wp-content" || await exists(path.join(at, "wp-config.php"))) return true;
|
|
199
|
+
if (path.dirname(at) === at) return false;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async function contentFolder(dir) {
|
|
203
|
+
const here = path.resolve(dir);
|
|
204
|
+
for (let at = here; ; at = path.dirname(at)) {
|
|
205
|
+
if (path.basename(at) === "wp-content") return at;
|
|
206
|
+
const content = path.join(at, "wp-content");
|
|
207
|
+
if ((at === here || await exists(path.join(at, "wp-config.php"))) && await exists(content))
|
|
208
|
+
return content;
|
|
209
|
+
if (path.dirname(at) === at) return null;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
async function wordPressFile(dir) {
|
|
213
|
+
const content = await contentFolder(dir);
|
|
214
|
+
return content && path.relative(dir, path.join(content, "mu-plugins", "agentface.php")).split(path.sep).join("/");
|
|
215
|
+
}
|
|
216
|
+
var wordPressPage = (html) => /\/wp-(?:content|includes)\/|["']https:\/\/api\.w\.org\/["']|<meta\b[^>]*\bcontent=["']WordPress\b/i.test(
|
|
217
|
+
html
|
|
218
|
+
);
|
|
219
|
+
var WORDPRESS_STEPS = (tag, notice) => [
|
|
220
|
+
'In the WordPress admin, open Plugins > Add New Plugin, search for WPCode, then install and activate "WPCode \u2013 Insert Headers and Footers".',
|
|
221
|
+
"Open Code Snippets > Header & Footer.",
|
|
222
|
+
`Paste this line in the Header box:
|
|
223
|
+
|
|
224
|
+
${tag}`,
|
|
225
|
+
...notice ? [`Paste this line in the Body box:
|
|
226
|
+
|
|
227
|
+
${notice}`] : [],
|
|
228
|
+
"Click Save Changes. If the site has a caching plugin, clear its cache, so the homepage shows the change."
|
|
229
|
+
].map((step, i) => ` ${i + 1}. ${step}`).join("\n\n") + "\n";
|
|
230
|
+
var wordPressManual = (lead) => ({
|
|
231
|
+
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.`,
|
|
232
|
+
how: "Or add it with a plugin that has boxes for the site's head and body, such as the free WPCode",
|
|
233
|
+
steps: WORDPRESS_STEPS
|
|
234
|
+
});
|
|
235
|
+
var SHOP = /\b_PS_[A-Z_]+_\b/;
|
|
236
|
+
var PRESTASHOP_MODULE_FILE = "agentface/agentface.php";
|
|
237
|
+
async function shopFolder(dir) {
|
|
238
|
+
for (let at = path.resolve(dir); ; at = path.dirname(at)) {
|
|
239
|
+
if (SHOP.test(await read(path.join(at, "config", "defines.inc.php")) ?? "")) return at;
|
|
240
|
+
if (path.dirname(at) === at) return null;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
async function prestaShopFile(dir) {
|
|
244
|
+
const shop = await shopFolder(dir);
|
|
245
|
+
return shop && path.relative(dir, path.join(shop, "modules", PRESTASHOP_MODULE_FILE)).split(path.sep).join("/");
|
|
246
|
+
}
|
|
247
|
+
async function prestaShopTheme(dir) {
|
|
248
|
+
return /^name\s*:/m.test(await read(path.join(dir, "config", "theme.yml")) ?? "") && await exists(path.join(dir, "templates"));
|
|
249
|
+
}
|
|
250
|
+
var prestaShopPage = (html) => /\bvar\s+prestashop\s*=/.test(html);
|
|
138
251
|
var KEY = /\/s\/(site-[a-z0-9-]+)\.js(?=[?#"'`\s]|$)/;
|
|
139
252
|
var ATTRIBUTES2 = String.raw`(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|[^>])*?`;
|
|
140
253
|
var TAG = new RegExp(
|
|
@@ -155,12 +268,14 @@ function indentUnit(source) {
|
|
|
155
268
|
return source.match(/^(\t| {2,4})\S/m)?.[1] ?? " ";
|
|
156
269
|
}
|
|
157
270
|
var indentOf = (line) => line.match(/^[ \t]*/)[0];
|
|
271
|
+
var NONCE = /\snonce\s*=\s*(\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^\s>]+)/i;
|
|
158
272
|
function addTag(source, tag) {
|
|
159
273
|
let first = true;
|
|
160
274
|
const replaced = source.replace(onItsLine(TAG), (match, line) => {
|
|
161
275
|
if (!first) return "";
|
|
162
276
|
first = false;
|
|
163
|
-
|
|
277
|
+
const nonce = match.match(NONCE)?.[1];
|
|
278
|
+
return (line ?? "") + (nonce ? tag.replace(/^<script\b/, () => `<script nonce=${nonce}`) : tag);
|
|
164
279
|
});
|
|
165
280
|
if (!first) return replaced;
|
|
166
281
|
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
|
@@ -280,6 +395,61 @@ ${text ? ` setPreBodyComponents([React.createElement('noscript', { key: 'agentf
|
|
|
280
395
|
` : ""}};
|
|
281
396
|
`;
|
|
282
397
|
};
|
|
398
|
+
var MU_PLUGIN = (tag, notice) => `<?php
|
|
399
|
+
/**
|
|
400
|
+
* Plugin Name: Agentface
|
|
401
|
+
* Description: Puts the Agentface tag in every page's head${notice ? ", and its notice first in the body" : ""}.
|
|
402
|
+
*/
|
|
403
|
+
// ${OURS}. WordPress runs it on every page, and \`npx agentface uninstall\` deletes it.
|
|
404
|
+
|
|
405
|
+
add_action('wp_head', function () {
|
|
406
|
+
echo '${tag}' . "\\n";
|
|
407
|
+
}, PHP_INT_MAX);
|
|
408
|
+
${notice ? `
|
|
409
|
+
add_action('wp_body_open', function () {
|
|
410
|
+
echo '${notice}' . "\\n";
|
|
411
|
+
}, PHP_INT_MIN);
|
|
412
|
+
` : ""}`;
|
|
413
|
+
var PRESTASHOP_MODULE = (tag, notice) => `<?php
|
|
414
|
+
// ${OURS}. PrestaShop runs it on every page once it's installed in Modules > Module Manager, and \`npx agentface uninstall\` deletes it.
|
|
415
|
+
if (!defined('_PS_VERSION_')) {
|
|
416
|
+
exit;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
class Agentface extends Module
|
|
420
|
+
{
|
|
421
|
+
public function __construct()
|
|
422
|
+
{
|
|
423
|
+
$this->name = 'agentface';
|
|
424
|
+
$this->tab = 'front_office_features';
|
|
425
|
+
$this->version = '1.0.0';
|
|
426
|
+
$this->author = 'Agentface';
|
|
427
|
+
$this->need_instance = 0;
|
|
428
|
+
$this->ps_versions_compliancy = ['min' => '1.7.0.0', 'max' => _PS_VERSION_];
|
|
429
|
+
parent::__construct();
|
|
430
|
+
$this->displayName = 'Agentface';
|
|
431
|
+
$this->description = "Puts the Agentface tag in every page's head${notice ? ", and its notice first in the body" : ""}.";
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
public function install()
|
|
435
|
+
{
|
|
436
|
+
return parent::install()
|
|
437
|
+
&& $this->registerHook('displayHeader')${notice ? `
|
|
438
|
+
&& $this->registerHook('displayAfterBodyOpeningTag')` : ""};
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
public function hookDisplayHeader()
|
|
442
|
+
{
|
|
443
|
+
return '${tag}' . "\\n";
|
|
444
|
+
}
|
|
445
|
+
${notice ? `
|
|
446
|
+
public function hookDisplayAfterBodyOpeningTag()
|
|
447
|
+
{
|
|
448
|
+
return '${notice}' . "\\n";
|
|
449
|
+
}
|
|
450
|
+
` : ""}}
|
|
451
|
+
`;
|
|
452
|
+
var prestaShopZip = (tag, notice) => zip({ [PRESTASHOP_MODULE_FILE]: PRESTASHOP_MODULE(tag, notice) });
|
|
283
453
|
async function project(dir) {
|
|
284
454
|
const pkg = JSON.parse(await read(path.join(dir, "package.json")) ?? "null");
|
|
285
455
|
const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
@@ -287,12 +457,14 @@ async function project(dir) {
|
|
|
287
457
|
const skip = new Set(SKIP);
|
|
288
458
|
if (generator === "Hugo") for (const name of ["public", "resources", "themes"]) skip.add(name);
|
|
289
459
|
if (deps.gatsby) skip.add("public");
|
|
290
|
-
const framework = FRAMEWORKS.find(([dependency]) => deps[dependency])?.[1] ?? generator ?? (pkg ? "JavaScript" : "HTML");
|
|
460
|
+
const framework = (await prestaShopTheme(dir) ? "PrestaShop theme" : null) ?? FRAMEWORKS.find(([dependency]) => deps[dependency])?.[1] ?? generator ?? (pkg ? "JavaScript" : "HTML");
|
|
291
461
|
const { files: list2, git } = await files(dir, skip);
|
|
292
462
|
return { deps, framework, list: list2, git };
|
|
293
463
|
}
|
|
294
464
|
async function findTags(dir) {
|
|
295
465
|
const { list: list2 } = await project(dir);
|
|
466
|
+
const plugin = await isWordPress(dir) && await wordPressFile(dir) || await prestaShopFile(dir);
|
|
467
|
+
if (plugin && !list2.includes(plugin)) list2.push(plugin);
|
|
296
468
|
const tagged = [];
|
|
297
469
|
for (const file of list2) {
|
|
298
470
|
const source = await contents(dir, file);
|
|
@@ -309,6 +481,8 @@ function madeByInit(source) {
|
|
|
309
481
|
const text = gatsby(/createElement\('noscript', \{ key: 'agentface' \}, '([^']*)'\)/);
|
|
310
482
|
const made = [
|
|
311
483
|
[NEXT_DOCUMENT, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
|
|
484
|
+
[MU_PLUGIN, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
|
|
485
|
+
[PRESTASHOP_MODULE, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
|
|
312
486
|
[
|
|
313
487
|
GATSBY_SSR,
|
|
314
488
|
load && src && `<script ${load} src="${src}"${about ? ` ${attribute}="${about}"` : ""}></script>`,
|
|
@@ -327,7 +501,7 @@ function removeTag(source) {
|
|
|
327
501
|
source
|
|
328
502
|
);
|
|
329
503
|
}
|
|
330
|
-
async function byHand(dir, list2, framework,
|
|
504
|
+
async function byHand(dir, list2, framework, manual) {
|
|
331
505
|
const tagged = [];
|
|
332
506
|
const noticed = [];
|
|
333
507
|
for (const file of list2) {
|
|
@@ -341,23 +515,52 @@ async function byHand(dir, list2, framework, reason, how) {
|
|
|
341
515
|
heads: [],
|
|
342
516
|
bodies: [],
|
|
343
517
|
creates: [],
|
|
344
|
-
manual
|
|
518
|
+
manual,
|
|
345
519
|
tagged,
|
|
346
520
|
noticed,
|
|
347
521
|
key: tagged[0]?.key ?? null
|
|
348
522
|
};
|
|
349
523
|
}
|
|
350
524
|
async function findHeads(dir) {
|
|
525
|
+
if (await isWordPress(dir)) {
|
|
526
|
+
const file = await wordPressFile(dir);
|
|
527
|
+
if (file) {
|
|
528
|
+
const source = await read(path.join(dir, file));
|
|
529
|
+
return {
|
|
530
|
+
framework: "WordPress",
|
|
531
|
+
heads: [],
|
|
532
|
+
bodies: [],
|
|
533
|
+
creates: [{ file, content: MU_PLUGIN, source }],
|
|
534
|
+
key: source === null ? null : tagKey(source)
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
return byHand(
|
|
538
|
+
dir,
|
|
539
|
+
(await project(dir)).list,
|
|
540
|
+
"WordPress",
|
|
541
|
+
wordPressManual(
|
|
542
|
+
"This folder is a WordPress theme, or part of a WordPress site, but init can't find the site's wp-content folder from here."
|
|
543
|
+
)
|
|
544
|
+
);
|
|
545
|
+
}
|
|
546
|
+
const moduleFile = await prestaShopFile(dir);
|
|
547
|
+
if (moduleFile) {
|
|
548
|
+
const source = await read(path.join(dir, moduleFile));
|
|
549
|
+
return {
|
|
550
|
+
framework: "PrestaShop",
|
|
551
|
+
heads: [],
|
|
552
|
+
bodies: [],
|
|
553
|
+
creates: [{ file: moduleFile, content: PRESTASHOP_MODULE, source }],
|
|
554
|
+
key: source === null ? null : tagKey(source)
|
|
555
|
+
};
|
|
556
|
+
}
|
|
351
557
|
const { deps, framework, list: list2, git } = await project(dir);
|
|
352
558
|
for (const [dependency, [name, where]] of Object.entries(CONFIG_HEAD))
|
|
353
559
|
if (deps[dependency])
|
|
354
|
-
return byHand(
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
`${name} sets the page head in its config, which init can't edit yet.`,
|
|
359
|
-
`Add it by hand through ${where}, with this tag's src`
|
|
360
|
-
);
|
|
560
|
+
return byHand(dir, list2, name, {
|
|
561
|
+
reason: `${name} sets the page head in its config, which init can't edit yet.`,
|
|
562
|
+
how: `Add it by hand through ${where}, with this tag's src`
|
|
563
|
+
});
|
|
361
564
|
const heads = [];
|
|
362
565
|
const bodies = [];
|
|
363
566
|
for (const file of list2) {
|
|
@@ -384,27 +587,234 @@ async function findHeads(dir) {
|
|
|
384
587
|
for (const file of own) if (await exists(path.join(dir, file))) present.push(file);
|
|
385
588
|
const text = present.length === 1 ? await read(path.join(dir, present[0])) : null;
|
|
386
589
|
if (present.length && !(present[0] === "gatsby-ssr.js" && text?.includes(OURS)))
|
|
387
|
-
return byHand(
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
`This Gatsby site has its own ${present[0]}, which init can't edit yet.`,
|
|
392
|
-
"Add it by hand through setHeadComponents in onRenderBody, with this tag's src"
|
|
393
|
-
);
|
|
590
|
+
return byHand(dir, list2, framework, {
|
|
591
|
+
reason: `This Gatsby site has its own ${present[0]}, which init can't edit yet.`,
|
|
592
|
+
how: "Add it by hand through setHeadComponents in onRenderBody, with this tag's src"
|
|
593
|
+
});
|
|
394
594
|
creates.push({ file: "gatsby-ssr.js", content: GATSBY_SSR, source: text });
|
|
395
595
|
}
|
|
396
596
|
if (!heads.length && !creates.length)
|
|
397
|
-
return byHand(
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
"Add this line by hand, last in the <head> of the layout or template every page uses"
|
|
403
|
-
);
|
|
597
|
+
return byHand(dir, list2, framework, {
|
|
598
|
+
reason: `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.`,
|
|
599
|
+
how: "Add this line by hand, last in the <head> of the layout or template every page uses",
|
|
600
|
+
none: true
|
|
601
|
+
});
|
|
404
602
|
const sources = [...heads.map(({ source }) => source), ...creates.map(({ source }) => source ?? "")];
|
|
405
603
|
return { framework, heads, bodies, creates, key: sources.map(tagKey).find(Boolean) ?? null };
|
|
406
604
|
}
|
|
407
605
|
|
|
606
|
+
// worker/html.ts
|
|
607
|
+
var ATTRIBUTE = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
|
|
608
|
+
function attributesOf(text) {
|
|
609
|
+
const values = {};
|
|
610
|
+
for (const [, name, ...value] of text.matchAll(ATTRIBUTE))
|
|
611
|
+
values[name.toLowerCase()] ??= decodeEntities(value.find((v) => v !== void 0) ?? "");
|
|
612
|
+
return values;
|
|
613
|
+
}
|
|
614
|
+
function decodeEntities(s) {
|
|
615
|
+
return s.replace(/&(#x?[0-9a-f]+|amp|lt|gt|quot|apos|nbsp);/gi, (m, e) => {
|
|
616
|
+
const named = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }[e.toLowerCase()];
|
|
617
|
+
if (named) return named;
|
|
618
|
+
const code = e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
|
619
|
+
return code >= 0 && code <= 1114111 ? String.fromCodePoint(code) : m;
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// worker/http.ts
|
|
624
|
+
var USER_AGENT = "AgentfaceFetcher/0.1 (+https://agentface.com)";
|
|
625
|
+
async function readStart(response, limit) {
|
|
626
|
+
if (!response.body) return "";
|
|
627
|
+
const reader = response.body.getReader();
|
|
628
|
+
const chunks = [];
|
|
629
|
+
let length = 0;
|
|
630
|
+
while (length < limit) {
|
|
631
|
+
const { done, value } = await reader.read();
|
|
632
|
+
if (done) break;
|
|
633
|
+
chunks.push(value);
|
|
634
|
+
length += value.byteLength;
|
|
635
|
+
}
|
|
636
|
+
await reader.cancel().catch(() => {
|
|
637
|
+
});
|
|
638
|
+
return new TextDecoder().decode(concat(chunks, length).subarray(0, limit));
|
|
639
|
+
}
|
|
640
|
+
function concat(chunks, length) {
|
|
641
|
+
const bytes = new Uint8Array(length);
|
|
642
|
+
let offset = 0;
|
|
643
|
+
for (const chunk of chunks) {
|
|
644
|
+
bytes.set(chunk, offset);
|
|
645
|
+
offset += chunk.byteLength;
|
|
646
|
+
}
|
|
647
|
+
return bytes;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// cli/policy.mts
|
|
651
|
+
function parsePolicy(text, where) {
|
|
652
|
+
const directives = /* @__PURE__ */ new Map();
|
|
653
|
+
for (const part of text.split(";")) {
|
|
654
|
+
const [name, ...sources] = part.trim().split(/[\t\n\f\r ]+/);
|
|
655
|
+
if (name && !directives.has(name.toLowerCase())) directives.set(name.toLowerCase(), sources);
|
|
656
|
+
}
|
|
657
|
+
return { where, directives };
|
|
658
|
+
}
|
|
659
|
+
var NOT_MARKUP = /<!--[\s\S]*?(?:-->|$)|<(script|style|noscript|template|textarea|title)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi;
|
|
660
|
+
var META = /<meta\b((?:"[^"]*"|'[^']*'|[^>"'])*)>/gi;
|
|
661
|
+
function pagePolicies(header, html) {
|
|
662
|
+
const policies = (header ?? "").split(",").filter((text) => text.trim()).map((text) => parsePolicy(text, "header"));
|
|
663
|
+
const end = headEnd(html);
|
|
664
|
+
const head = (end === -1 ? html : html.slice(0, end)).replace(NOT_MARKUP, "");
|
|
665
|
+
for (const [, text] of head.matchAll(META)) {
|
|
666
|
+
const attributes = attributesOf(text);
|
|
667
|
+
if (attributes["http-equiv"]?.trim().toLowerCase() === "content-security-policy" && attributes.content)
|
|
668
|
+
policies.push(parsePolicy(attributes.content, "meta"));
|
|
669
|
+
}
|
|
670
|
+
return policies.filter((policy) => policy.directives.size);
|
|
671
|
+
}
|
|
672
|
+
var scheme = (url) => url.protocol.slice(0, -1);
|
|
673
|
+
var DEFAULT_PORT = { http: "80", https: "443", ws: "80", wss: "443" };
|
|
674
|
+
var schemeMatches = (a, b) => a === b || a === "http" && b === "https" || a === "ws" && ["wss", "http", "https"].includes(b) || a === "wss" && b === "https";
|
|
675
|
+
var decode = (segment) => {
|
|
676
|
+
try {
|
|
677
|
+
return decodeURIComponent(segment);
|
|
678
|
+
} catch {
|
|
679
|
+
return segment;
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
function pathMatches(a, b) {
|
|
683
|
+
if (!a || a === "/" && !b) return true;
|
|
684
|
+
const exact = !a.endsWith("/");
|
|
685
|
+
const listA = a.split("/");
|
|
686
|
+
const listB = b.split("/");
|
|
687
|
+
if (listA.length > listB.length || exact && listA.length !== listB.length) return false;
|
|
688
|
+
if (!exact) listA.pop();
|
|
689
|
+
return listA.every((segment, i) => decode(segment) === decode(listB[i]));
|
|
690
|
+
}
|
|
691
|
+
var HOST_SOURCE = /^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::(\d+|\*))?(\/[^?#]*)?$/i;
|
|
692
|
+
function sourceMatches(source, url, page) {
|
|
693
|
+
const lower = source.toLowerCase();
|
|
694
|
+
if (lower === "*") return ["http", "https", "ws", "wss", scheme(page)].includes(scheme(url));
|
|
695
|
+
if (lower === "'self'")
|
|
696
|
+
return url.hostname === page.hostname && (url.origin === page.origin || scheme(page) === "http" && scheme(url) === "https" && !url.port);
|
|
697
|
+
if (/^[a-z][a-z0-9+.-]*:$/.test(lower)) return schemeMatches(lower.slice(0, -1), scheme(url));
|
|
698
|
+
const [, sourceScheme, host, port, path3] = source.match(HOST_SOURCE) ?? [];
|
|
699
|
+
if (!host) return false;
|
|
700
|
+
if (!schemeMatches(sourceScheme?.toLowerCase() ?? scheme(page), scheme(url))) return false;
|
|
701
|
+
const name = host.toLowerCase();
|
|
702
|
+
if (name.startsWith("*.") ? !url.hostname.endsWith(name.slice(1)) : name !== "*" && name !== url.hostname)
|
|
703
|
+
return false;
|
|
704
|
+
if (port === void 0 ? url.port !== "" : port !== "*" && port !== (url.port || DEFAULT_PORT[scheme(url)]))
|
|
705
|
+
return false;
|
|
706
|
+
return pathMatches(path3 ?? "", url.pathname);
|
|
707
|
+
}
|
|
708
|
+
var keyword = (sources, word) => sources.some((source) => source.toLowerCase() === word);
|
|
709
|
+
var hasNonce = (sources, nonce) => sources.some((source) => /^'nonce-/i.test(source) && source.slice(7, -1) === nonce && source.endsWith("'"));
|
|
710
|
+
var governing = (policy, names) => names.find((name) => policy.directives.has(name));
|
|
711
|
+
function fix(policy, decides, name, origin) {
|
|
712
|
+
const sources = policy.directives.get(decides).filter((source) => source.toLowerCase() !== "'none'");
|
|
713
|
+
return { name, line: [name, ...sources, origin].join(" "), created: decides !== name };
|
|
714
|
+
}
|
|
715
|
+
function blockedBy(policies, load) {
|
|
716
|
+
const page = new URL(load.page);
|
|
717
|
+
const script = new URL(load.script);
|
|
718
|
+
const events = new URL(load.events);
|
|
719
|
+
const blocked = [];
|
|
720
|
+
for (const policy of policies) {
|
|
721
|
+
const result = { where: policy.where, script: false, connect: false, nonce: null, fixes: [] };
|
|
722
|
+
const scripts = governing(policy, ["script-src-elem", "script-src", "default-src"]);
|
|
723
|
+
if (scripts) {
|
|
724
|
+
const sources = policy.directives.get(scripts);
|
|
725
|
+
const dynamic = keyword(sources, "'strict-dynamic'");
|
|
726
|
+
const allowed = load.nonce && hasNonce(sources, load.nonce) || (dynamic ? load.added : sources.some((source) => sourceMatches(source, script, page)));
|
|
727
|
+
if (!allowed) {
|
|
728
|
+
result.script = true;
|
|
729
|
+
if (dynamic) result.nonce = { directive: scripts, named: sources.some((s) => /^'nonce-/i.test(s)) };
|
|
730
|
+
else
|
|
731
|
+
result.fixes.push(
|
|
732
|
+
fix(policy, scripts, scripts === "default-src" ? "script-src" : scripts, script.origin)
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
const connects = governing(policy, ["connect-src", "default-src"]);
|
|
737
|
+
if (connects && !policy.directives.get(connects).some((source) => sourceMatches(source, events, page))) {
|
|
738
|
+
result.connect = true;
|
|
739
|
+
result.fixes.push(fix(policy, connects, "connect-src", events.origin));
|
|
740
|
+
}
|
|
741
|
+
if (result.script || result.connect) blocked.push(result);
|
|
742
|
+
}
|
|
743
|
+
return blocked;
|
|
744
|
+
}
|
|
745
|
+
var WHERE = {
|
|
746
|
+
header: "In the Content-Security-Policy header the site sends with its pages",
|
|
747
|
+
meta: "In the Content-Security-Policy <meta> tag in the head of its pages"
|
|
748
|
+
};
|
|
749
|
+
var and = (names) => names.join(" and ");
|
|
750
|
+
var or = (names) => names.join(" or ");
|
|
751
|
+
function advice(blocked, host) {
|
|
752
|
+
const script = blocked.some((b) => b.script);
|
|
753
|
+
const connect = blocked.some((b) => b.connect);
|
|
754
|
+
const effect = script && connect ? "load the Agentface script or send its events" : script ? "load the Agentface script" : "send the Agentface script's events";
|
|
755
|
+
const paragraphs = blocked.map(({ where, nonce, fixes }) => {
|
|
756
|
+
let text = !nonce ? "" : nonce.named ? `${WHERE[where]}, ${nonce.directive} has 'strict-dynamic': browsers then ignore the hosts it lists, and load only a script that carries the nonce the page gives its own scripts, or that such a script adds. Give the Agentface tag that nonce, the way the site gives it to its other script tags.` : `${WHERE[where]}, ${nonce.directive} has 'strict-dynamic' and no nonce: browsers then ignore the hosts it lists, and load only a script it lists by hash, or that such a script adds. Add a nonce to ${nonce.directive}, as 'nonce-' and a random value the server makes anew for each page, and give the Agentface tag the same value in its nonce attribute. Or add the tag from a script the page already runs.`;
|
|
757
|
+
const existing = fixes.filter((f) => !f.created).map(({ name }) => name);
|
|
758
|
+
const created = fixes.filter((f) => f.created).map(({ name }) => name);
|
|
759
|
+
const what = [
|
|
760
|
+
existing.length && `${host} at the end of ${and(existing)}, after the hosts ${existing.length === 1 ? "it already lists" : "they already list"}`,
|
|
761
|
+
created.length && `${created.length === 1 ? "a " : ""}${and(created)} ${created.length === 1 ? "line" : "lines"} with ${existing.length ? "it" : host}`
|
|
762
|
+
].filter(Boolean);
|
|
763
|
+
if (fixes.length)
|
|
764
|
+
text += `${nonce ? " Also" : `${WHERE[where]},`} add ${what.join(", and ")}, so ${fixes.length === 1 ? "it reads" : "they read"}:
|
|
765
|
+
|
|
766
|
+
` + fixes.map(({ line }) => ` ${line}`).join("\n");
|
|
767
|
+
if (created.length)
|
|
768
|
+
text += `
|
|
769
|
+
|
|
770
|
+
It has no ${or(created)} yet, so ${created.length === 1 ? "the new line starts" : "each new line starts"} with what its default-src allows: the rest of the site works as before.`;
|
|
771
|
+
return text;
|
|
772
|
+
});
|
|
773
|
+
return { effect, fixes: paragraphs.join("\n\n") + "\n" };
|
|
774
|
+
}
|
|
775
|
+
async function readHomepage(origin, fetcher) {
|
|
776
|
+
try {
|
|
777
|
+
const response = await fetcher(origin + "/", {
|
|
778
|
+
headers: { accept: "text/html", "user-agent": USER_AGENT },
|
|
779
|
+
redirect: "follow",
|
|
780
|
+
signal: AbortSignal.timeout(1e4)
|
|
781
|
+
});
|
|
782
|
+
if (!response.ok) {
|
|
783
|
+
await response.body?.cancel();
|
|
784
|
+
return { unread: `it answered HTTP ${response.status}` };
|
|
785
|
+
}
|
|
786
|
+
const html = await readStart(response, 2e5);
|
|
787
|
+
const policies = pagePolicies(response.headers.get("content-security-policy"), html);
|
|
788
|
+
return { url: response.url || origin + "/", html, policies };
|
|
789
|
+
} catch (error) {
|
|
790
|
+
const { name, message, cause } = error;
|
|
791
|
+
return {
|
|
792
|
+
unread: name === "TimeoutError" ? "it didn't answer within 10 seconds" : `the request failed (${cause?.message ?? message})`
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
var SCRIPT = /<script\b((?:"[^"]*"|'[^']*'|[^>"'])*)>/gi;
|
|
797
|
+
function liveNonce(html, id) {
|
|
798
|
+
for (const [, text] of html.matchAll(SCRIPT)) {
|
|
799
|
+
const attributes = attributesOf(text);
|
|
800
|
+
if ((attributes.src ?? "").split(/[?#]/)[0].endsWith(`/s/${id}.js`)) return attributes.nonce || null;
|
|
801
|
+
}
|
|
802
|
+
return void 0;
|
|
803
|
+
}
|
|
804
|
+
function tagBlocked(homepage, site, { added = false } = {}) {
|
|
805
|
+
const src = site.tag.match(/\bsrc="([^"]+)"/)?.[1];
|
|
806
|
+
if ("unread" in homepage || !homepage.policies.length || !src) return null;
|
|
807
|
+
const nonce = liveNonce(homepage.html, site.id);
|
|
808
|
+
const blocked = blockedBy(homepage.policies, {
|
|
809
|
+
page: homepage.url,
|
|
810
|
+
script: src,
|
|
811
|
+
events: new URL("/e", src).href,
|
|
812
|
+
nonce,
|
|
813
|
+
added: nonce === void 0 && added
|
|
814
|
+
});
|
|
815
|
+
return blocked.length ? advice(blocked, new URL(src).origin) : null;
|
|
816
|
+
}
|
|
817
|
+
|
|
408
818
|
// cli/init.mts
|
|
409
819
|
var DEFAULT_SERVICE = "https://cdn.agentfacehq.com";
|
|
410
820
|
var BRANCH = "agentface";
|
|
@@ -568,18 +978,29 @@ async function siteFor({
|
|
|
568
978
|
}
|
|
569
979
|
var serviceFlag = (service) => service === DEFAULT_SERVICE ? "" : ` --service ${service}`;
|
|
570
980
|
var list = (files2) => files2.length <= 3 ? files2.join(", ") : `${files2.slice(0, 3).join(", ")} and ${files2.length - 3} more`;
|
|
571
|
-
function nextSteps(site, service) {
|
|
572
|
-
const
|
|
981
|
+
function nextSteps(site, service, own) {
|
|
982
|
+
const saved = own === "plugin";
|
|
983
|
+
const check2 = `npx agentface check${saved ? ` --site ${site.id}` : ""}${serviceFlag(service)}`;
|
|
984
|
+
if (own === "file")
|
|
985
|
+
return site.expiresAt ? `Then run \`${check2}\` here: once ${site.origin}'s homepage has the tag, that confirms the site is yours. Agentface also confirms it by itself when the site's first events arrive, but a quiet site may send none in time: until it's confirmed, Agentface deletes ${site.id} at ${when(site.expiresAt)}. If that happens first, run \`npx agentface init\` again.` : `Then \`${check2}\` shows whether ${site.origin}'s homepage has the tag.`;
|
|
986
|
+
if (saved)
|
|
987
|
+
return site.expiresAt ? `Then run \`${check2}\`: once ${site.origin}'s homepage has the tag, that confirms the site is yours. Agentface also confirms it by itself when the site's first events arrive, but a quiet site may send none in time: until it's confirmed, Agentface deletes ${site.id} at ${when(site.expiresAt)}. To see these steps again without registering the site another time, run \`npx agentface init ${site.id}${serviceFlag(service)}\`.` : `Then \`${check2}\` shows whether ${site.origin}'s homepage has the tag.`;
|
|
573
988
|
return site.expiresAt ? `Deploy it as usual, then run \`${check2}\` here: once ${site.origin}'s homepage has the tag, in its HTML or in the Google Tag Manager container it loads, that confirms the site is yours. Agentface also confirms it by itself when the site's first events arrive, but a quiet site may send none in time: until it's confirmed, Agentface deletes ${site.id} at ${when(site.expiresAt)}. If that happens first, run \`npx agentface init\` again.` : `Deploy it as usual. \`${check2}\` shows whether ${site.origin}'s homepage has the tag.`;
|
|
574
989
|
}
|
|
575
|
-
function
|
|
990
|
+
function policyWarning(site, advice2) {
|
|
991
|
+
return advice2 ? `${site.origin}'s Content Security Policy, the list of hosts its pages may use, doesn't let them ${advice2.effect}. ${advice2.fixes}` : null;
|
|
992
|
+
}
|
|
993
|
+
var markdown = (warning) => warning.trim().replaceAll("<meta>", "`<meta>`").replace(/(?:^ {2}\S.*\n?)+/gm, (lines) => "```\n" + lines.replace(/^ {2}/gm, "").trimEnd() + "\n```\n").trimEnd();
|
|
994
|
+
function prBody(site, files2, service = DEFAULT_SERVICE, warning = null) {
|
|
576
995
|
const src = site.tag.match(/\bsrc="([^"]+)"/)?.[1];
|
|
577
996
|
const notice = site.notice ? ` A \`<noscript>\` line first in the body links agents that read pages without running them, and so never get the tools, to a list of them. Browsers that run scripts don't show it.` : "";
|
|
578
997
|
return `Adds the Agentface tag to ${site.origin}, so AI agents that use the site in a browser get tools made for them.
|
|
579
998
|
|
|
580
|
-
**What it does.** It changes ${files2.map((file) => `\`${file}\``).join(", ")}. One \`<script defer>\` line in the head loads ${src} on every page. It gives browser agents tools for this site (read a page as Markdown, search the site, fill in forms, close pop-ups) and reports how
|
|
999
|
+
**What it does.** It changes ${files2.map((file) => `\`${file}\``).join(", ")}. One \`<script defer>\` line in the head loads ${src} on every page. It gives browser agents tools for this site (read a page as Markdown, search the site, fill in forms, close pop-ups) and reports how they are used: which tools, how long they took and their error codes. A visit that calls a tool is an agent's, and for those it also reports the pages opened and what was clicked, typed and asked, for the site's owner to read. A password, a payment detail and a one-time code are never sent, and a visit that calls no tool sends nothing it typed, clicked or read.${notice} People visiting the site see no change, and it sets no cookies.
|
|
1000
|
+
|
|
1001
|
+
${warning ? `**Content Security Policy.** ${markdown(warning)}
|
|
581
1002
|
|
|
582
|
-
**Check it.** ${nextSteps(site, service)}
|
|
1003
|
+
` : ""}**Check it.** ${nextSteps(site, service)}
|
|
583
1004
|
|
|
584
1005
|
**Uninstall.** Revert this pull request, or delete ${site.notice ? "the two lines" : "the line"}.
|
|
585
1006
|
`;
|
|
@@ -594,19 +1015,22 @@ function noticeByHand(site, noticed, log) {
|
|
|
594
1015
|
`
|
|
595
1016
|
);
|
|
596
1017
|
}
|
|
597
|
-
function byHand2({ manual, tagged, noticed }, site, service, dryRun, log) {
|
|
1018
|
+
function byHand2({ manual, tagged, noticed }, site, service, dryRun, warning, log) {
|
|
1019
|
+
if (manual.steps) return withPlugin({ manual, tagged }, site, service, dryRun, warning, log);
|
|
598
1020
|
const current = tagged.filter(({ key }) => key === site.id).map(({ file }) => file);
|
|
599
1021
|
if (current.length) {
|
|
600
1022
|
log(
|
|
601
1023
|
`${list(current)} already ${current.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`
|
|
602
1024
|
);
|
|
603
1025
|
noticeByHand(site, noticed, log);
|
|
1026
|
+
if (warning) log(warning);
|
|
604
1027
|
log(nextSteps(site, service));
|
|
605
1028
|
return { site, files: [], written: false };
|
|
606
1029
|
}
|
|
607
1030
|
log(manual.reason);
|
|
608
1031
|
if (dryRun) {
|
|
609
1032
|
log(`${manual.how}. Without --dry-run, init prints the tag with the site's key.`);
|
|
1033
|
+
if (warning) log(warning);
|
|
610
1034
|
return { site, files: [], written: false };
|
|
611
1035
|
}
|
|
612
1036
|
const old = tagged.map(({ file }) => file);
|
|
@@ -618,9 +1042,37 @@ function byHand2({ manual, tagged, noticed }, site, service, dryRun, log) {
|
|
|
618
1042
|
);
|
|
619
1043
|
if (!old.length) log(GTM_HOW);
|
|
620
1044
|
noticeByHand(site, noticed, log);
|
|
1045
|
+
if (warning) log(warning);
|
|
621
1046
|
log(nextSteps(site, service));
|
|
622
1047
|
return { site, files: [], written: false };
|
|
623
1048
|
}
|
|
1049
|
+
function withPlugin({ manual, tagged }, site, service, dryRun, warning, log) {
|
|
1050
|
+
log(manual.reason);
|
|
1051
|
+
if (dryRun) {
|
|
1052
|
+
log(`${manual.how}. Without --dry-run, init prints the steps, with the tag for the site's key.`);
|
|
1053
|
+
if (warning) log(warning);
|
|
1054
|
+
return { site, files: [], written: false };
|
|
1055
|
+
}
|
|
1056
|
+
log(`${manual.how}:
|
|
1057
|
+
|
|
1058
|
+
${manual.steps(site.tag, site.notice)}`);
|
|
1059
|
+
const files2 = tagged.map(({ file }) => file);
|
|
1060
|
+
if (files2.length)
|
|
1061
|
+
log(
|
|
1062
|
+
`${list(files2)} ${files2.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.`
|
|
1063
|
+
);
|
|
1064
|
+
if (warning) log(warning);
|
|
1065
|
+
log(nextSteps(site, service, "plugin"));
|
|
1066
|
+
return { site, files: [], written: false };
|
|
1067
|
+
}
|
|
1068
|
+
function prestaShopSteps(file) {
|
|
1069
|
+
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.`;
|
|
1070
|
+
const cache = "If the shop has a cache module, clear its cache, so that the pages show the tag.";
|
|
1071
|
+
if (file.endsWith(".zip"))
|
|
1072
|
+
return `${what} In the shop's back office, open Modules > Module Manager, click Upload a module and choose ${file}: PrestaShop installs it. ${cache}`;
|
|
1073
|
+
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}`;
|
|
1074
|
+
}
|
|
1075
|
+
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.";
|
|
624
1076
|
async function readyForPr(dir, exec) {
|
|
625
1077
|
if (await exec("git", ["status", "--porcelain"], { cwd: dir }))
|
|
626
1078
|
throw new Error("Commit or stash your changes first: the pull request should contain only Agentface.");
|
|
@@ -641,41 +1093,64 @@ async function init({
|
|
|
641
1093
|
exec = run,
|
|
642
1094
|
log = console.log
|
|
643
1095
|
}) {
|
|
644
|
-
|
|
1096
|
+
let found = await findHeads(dir);
|
|
645
1097
|
if (found.manual && pr)
|
|
646
1098
|
throw new Error(
|
|
647
1099
|
`${found.manual.reason} --pr only commits what init writes: run init without it to get the tag to add by hand.`
|
|
648
1100
|
);
|
|
649
1101
|
if (pr && !dryRun) await readyForPr(dir, exec);
|
|
650
1102
|
const site = await siteFor({ id, url, dir, found, service, fetcher, exec, dryRun, log });
|
|
651
|
-
|
|
1103
|
+
const homepage = await readHomepage(site.origin, fetcher);
|
|
1104
|
+
const warning = policyWarning(site, tagBlocked(homepage, site));
|
|
1105
|
+
if (found.manual?.none && "html" in homepage && wordPressPage(homepage.html))
|
|
1106
|
+
found = {
|
|
1107
|
+
...found,
|
|
1108
|
+
framework: "WordPress",
|
|
1109
|
+
manual: wordPressManual(`${site.origin}'s homepage comes from WordPress.`)
|
|
1110
|
+
};
|
|
1111
|
+
else if (found.manual?.none && "html" in homepage && prestaShopPage(homepage.html))
|
|
1112
|
+
found = {
|
|
1113
|
+
framework: "PrestaShop",
|
|
1114
|
+
heads: [],
|
|
1115
|
+
bodies: [],
|
|
1116
|
+
creates: [{ file: "agentface.zip", content: prestaShopZip }],
|
|
1117
|
+
key: null
|
|
1118
|
+
};
|
|
1119
|
+
if (found.manual) return byHand2(found, site, service, dryRun, warning, log);
|
|
652
1120
|
const before = /* @__PURE__ */ new Map();
|
|
653
1121
|
const after = /* @__PURE__ */ new Map();
|
|
1122
|
+
const edited = /* @__PURE__ */ new Map();
|
|
654
1123
|
for (const { file, source } of found.heads) {
|
|
655
1124
|
before.set(file, source);
|
|
656
|
-
|
|
1125
|
+
edited.set(file, addTag(source, site.tag));
|
|
657
1126
|
}
|
|
658
1127
|
if (site.notice)
|
|
659
1128
|
for (const { file, source } of found.bodies) {
|
|
660
1129
|
before.set(file, source);
|
|
661
|
-
|
|
1130
|
+
edited.set(file, addNotice(edited.get(file) ?? source, site.notice) ?? edited.get(file) ?? source);
|
|
662
1131
|
}
|
|
1132
|
+
for (const [file, content] of edited) after.set(file, content);
|
|
663
1133
|
for (const { file, content, source } of found.creates) {
|
|
664
1134
|
before.set(file, source);
|
|
665
1135
|
after.set(file, content(site.tag, site.notice));
|
|
666
1136
|
}
|
|
667
1137
|
const writes = [...after].filter(([file, content]) => content !== before.get(file));
|
|
668
1138
|
const files2 = writes.map(([file]) => file);
|
|
1139
|
+
const own = found.creates.some(({ file }) => file.endsWith(".zip")) ? "plugin" : found.framework === "WordPress" || found.framework === "PrestaShop" ? "file" : void 0;
|
|
1140
|
+
const shop = found.framework === "PrestaShop" ? prestaShopSteps(found.creates[0].file) : null;
|
|
669
1141
|
const noticed = site.notice && (found.bodies.length || found.creates.length);
|
|
670
1142
|
const what = `the Agentface tag${noticed ? " and its notice" : ""}`;
|
|
671
1143
|
if (!writes.length) {
|
|
672
1144
|
const tagged = [...found.heads, ...found.creates].map(({ file }) => file);
|
|
673
1145
|
log(`${list(tagged)} already ${tagged.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`);
|
|
674
|
-
log(
|
|
1146
|
+
if (shop) log(shop);
|
|
1147
|
+
if (warning) log(warning);
|
|
1148
|
+
log(nextSteps(site, service, own));
|
|
675
1149
|
return { site, files: files2, written: false };
|
|
676
1150
|
}
|
|
677
1151
|
if (dryRun) {
|
|
678
1152
|
log(`Would add ${what} to ${list(files2)} (${found.framework}) for ${site.origin}.`);
|
|
1153
|
+
if (warning) log(warning);
|
|
679
1154
|
return { site, files: files2, written: false };
|
|
680
1155
|
}
|
|
681
1156
|
let returnTo;
|
|
@@ -688,8 +1163,15 @@ async function init({
|
|
|
688
1163
|
await writeFile(path2.join(dir, file), content);
|
|
689
1164
|
}
|
|
690
1165
|
log(`Added ${what} to ${list(files2)} (${found.framework}) for ${site.origin}.`);
|
|
1166
|
+
if (shop) log(shop);
|
|
1167
|
+
if (found.framework === "PrestaShop theme") log(PRESTASHOP_THEME);
|
|
1168
|
+
if (found.framework === "WordPress")
|
|
1169
|
+
log(
|
|
1170
|
+
`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.`
|
|
1171
|
+
);
|
|
1172
|
+
if (warning) log(warning);
|
|
691
1173
|
if (!pr) {
|
|
692
|
-
log(nextSteps(site, service));
|
|
1174
|
+
log(nextSteps(site, service, own));
|
|
693
1175
|
return { site, files: files2, written: true };
|
|
694
1176
|
}
|
|
695
1177
|
try {
|
|
@@ -716,7 +1198,7 @@ async function init({
|
|
|
716
1198
|
"--title",
|
|
717
1199
|
"Add Agentface for AI agents",
|
|
718
1200
|
"--body",
|
|
719
|
-
prBody(site, files2, service)
|
|
1201
|
+
prBody(site, files2, service, warning)
|
|
720
1202
|
],
|
|
721
1203
|
{ cwd: dir }
|
|
722
1204
|
);
|
|
@@ -736,13 +1218,36 @@ async function check({
|
|
|
736
1218
|
if (!id) {
|
|
737
1219
|
const found = await findHeads(dir);
|
|
738
1220
|
id = found.key;
|
|
1221
|
+
if (!id && found.manual?.steps)
|
|
1222
|
+
throw new Error(
|
|
1223
|
+
"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/."
|
|
1224
|
+
);
|
|
739
1225
|
if (!id)
|
|
740
1226
|
throw new Error(
|
|
741
1227
|
'No Agentface tag in this project. Run "npx agentface init" first, or pass the site key with --site.'
|
|
742
1228
|
);
|
|
743
1229
|
}
|
|
744
1230
|
const site = await lookupSite(service, id, fetcher);
|
|
745
|
-
const result = await
|
|
1231
|
+
const [result, homepage] = await Promise.all([
|
|
1232
|
+
confirm(service, id, fetcher),
|
|
1233
|
+
readHomepage(site.origin, fetcher)
|
|
1234
|
+
]);
|
|
1235
|
+
if (result.ok && "unread" in homepage) {
|
|
1236
|
+
log(
|
|
1237
|
+
`${site.expiresAt ? `Confirmed: ${site.origin}'s homepage has the tag, so ${id} is yours and Agentface keeps it. But` : `${site.origin}'s homepage has the tag for ${id}, but`} check couldn't read the homepage from here to see whether the site's Content Security Policy lets browsers load the tag: ${homepage.unread}. Run \`npx agentface check${serviceFlag(service)}\` again. If it keeps failing, open the homepage in a browser: its developer console names anything the policy blocks.`
|
|
1238
|
+
);
|
|
1239
|
+
return 1;
|
|
1240
|
+
}
|
|
1241
|
+
const advice2 = tagBlocked(homepage, site, { added: result.ok });
|
|
1242
|
+
if (result.ok && advice2) {
|
|
1243
|
+
log(
|
|
1244
|
+
`Blocked: ${site.origin}'s homepage has the tag for ${id}, but the site's Content Security Policy, the list of hosts its pages may use, doesn't let them ${advice2.effect}. ${advice2.fixes}`
|
|
1245
|
+
);
|
|
1246
|
+
log(
|
|
1247
|
+
`${site.expiresAt ? `The tag still confirms the site is yours, so Agentface keeps ${id}. ` : ""}Deploy the change to the policy, then run \`npx agentface check${serviceFlag(service)}\` again.`
|
|
1248
|
+
);
|
|
1249
|
+
return 1;
|
|
1250
|
+
}
|
|
746
1251
|
if (result.ok) {
|
|
747
1252
|
log(
|
|
748
1253
|
site.expiresAt ? `Confirmed: ${site.origin}'s homepage has the tag, so ${id} is yours and Agentface keeps it.` : `${site.origin}'s homepage has the tag for ${id}.`
|
|
@@ -750,8 +1255,15 @@ async function check({
|
|
|
750
1255
|
return 0;
|
|
751
1256
|
}
|
|
752
1257
|
log(result.message);
|
|
1258
|
+
const module = await prestaShopFile(dir);
|
|
1259
|
+
if (module && await readFile2(path2.join(dir, module)).catch(() => null))
|
|
1260
|
+
log(
|
|
1261
|
+
`PrestaShop runs ${module} only once it's installed. If it isn't yet, open Modules > Module Manager in the shop's back office, search for Agentface and click Install.`
|
|
1262
|
+
);
|
|
753
1263
|
if (result.status === 422 && site.expiresAt)
|
|
754
1264
|
log(`Until it's confirmed, Agentface deletes ${id} at ${when(site.expiresAt)}.`);
|
|
1265
|
+
const warning = policyWarning(site, advice2);
|
|
1266
|
+
if (warning) log(warning);
|
|
755
1267
|
return 1;
|
|
756
1268
|
}
|
|
757
1269
|
async function uninstall({
|
|
@@ -762,6 +1274,11 @@ async function uninstall({
|
|
|
762
1274
|
log = console.log
|
|
763
1275
|
}) {
|
|
764
1276
|
const tagged = await findTags(dir);
|
|
1277
|
+
const plugin = await isWordPress(dir) && await wordPressFile(dir);
|
|
1278
|
+
if (plugin !== false && !tagged.some(({ file }) => file === plugin))
|
|
1279
|
+
log(
|
|
1280
|
+
"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."
|
|
1281
|
+
);
|
|
765
1282
|
if (!tagged.length) {
|
|
766
1283
|
log("No Agentface tag in this project.");
|
|
767
1284
|
return { files: [], deleted: [], byHand: [] };
|
|
@@ -776,9 +1293,14 @@ async function uninstall({
|
|
|
776
1293
|
else edits.push([file, content]);
|
|
777
1294
|
}
|
|
778
1295
|
const files2 = edits.map(([file]) => file);
|
|
1296
|
+
const module = await prestaShopFile(dir);
|
|
779
1297
|
if (!dryRun) {
|
|
780
1298
|
for (const [file, content] of edits) await writeFile(path2.join(dir, file), content);
|
|
781
|
-
for (const file of deleted)
|
|
1299
|
+
for (const file of deleted) {
|
|
1300
|
+
await rm(path2.join(dir, file));
|
|
1301
|
+
if (file === module) await rmdir(path2.dirname(path2.join(dir, file))).catch(() => {
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
782
1304
|
}
|
|
783
1305
|
const would = (done, undone) => dryRun ? undone : done;
|
|
784
1306
|
if (files2.length) log(`${would("Removed", "Would remove")} the Agentface tag from ${list(files2)}.`);
|