agentface 0.8.0 → 0.9.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.
Files changed (2) hide show
  1. package/dist/agentface.mjs +374 -71
  2. package/package.json +1 -1
@@ -1212,7 +1212,8 @@ var HOW = {
1212
1212
  astro: "astro.config adds the integration, agentface(), whose middleware puts them\nin every page Astro makes.",
1213
1213
  vite: "vite.config adds the plugin, agentface(), which puts them in index.html\nwhen the site is built.",
1214
1214
  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."
1215
+ fastify: "The app adds agentface as its first onSend hook, which puts them in every\nHTML page it sends as text.",
1216
+ node: "The server's handler goes through agentface(), which puts them in every\nHTML page it sends."
1216
1217
  };
1217
1218
  var LINE_JS = (t) => String.raw`
1218
1219
  // Exa, a search engine AI agents read the web through, runs no script and
@@ -1477,10 +1478,180 @@ ${out}function agentface(
1477
1478
  reply.removeHeader('content-length');
1478
1479
  done(null, page);
1479
1480
  }
1481
+ `,
1482
+ node: String.raw`${insert}
1483
+ // Node's own server: the lines go into every HTML page the handler sends.
1484
+ // The handler is what http.createServer is given, or what a Vercel function
1485
+ // exports: a function of the request and the response.
1486
+ ${out}function agentface${t("<Req extends { method?: string | undefined; headers: { upgrade?: unknown } } = IncomingMessage, Res extends Held = ServerResponse>")}(
1487
+ handler${t(": (req: Req, res: Res) => unknown")},
1488
+ )${t(": (req: Req, res: Res) => unknown")} {
1489
+ return function (${t("this: unknown, ")}req${t(": Req")}, res${t(": Res")}) {
1490
+ if (req.method === 'GET' && !req.headers.upgrade) hold(res);
1491
+ return handler.call(this, req, res);
1492
+ };
1493
+ }
1494
+ ${t(`
1495
+ // What hold() uses of the response: Node's, or a host's that extends it. A
1496
+ // handler without types of its own, as one written in http.createServer(\u2026),
1497
+ // takes Node's.
1498
+ interface Held {
1499
+ statusCode: number;
1500
+ statusMessage?: string;
1501
+ getHeader(name: string): unknown;
1502
+ setHeader(name: string, value: number | string | readonly string[]): unknown;
1503
+ hasHeader(name: string): boolean;
1504
+ writeHead(...args: unknown[]): unknown;
1505
+ write(...args: unknown[]): unknown;
1506
+ end(...args: unknown[]): unknown;
1507
+ flushHeaders?(): void;
1508
+ }
1509
+ `)}
1510
+ // A header as writeHead was given it, in an object or a list of names and
1511
+ // values.
1512
+ function given(headers${t(": unknown")}, name${t(": string")}) {
1513
+ if (Array.isArray(headers)) {
1514
+ for (let i = 0; i + 1 < headers.length; i += 2) if (String(headers[i]).toLowerCase() === name) return headers[i + 1];
1515
+ } else if (headers && typeof headers === 'object') {
1516
+ for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === name) return value;
1517
+ }
1518
+ return undefined;
1519
+ }
1520
+
1521
+ // The response, holding an HTML page until it ends, to send it then with the
1522
+ // lines in it and a length to match. A page sent compressed, in part, in a
1523
+ // character set other than UTF-8 or with a status other than 200 passes
1524
+ // straight on, and so does anything else.
1525
+ function hold(res${t(": Held")}) {
1526
+ const writeHead = res.writeHead.bind(res);
1527
+ const write = res.write.bind(res);
1528
+ const end = res.end.bind(res);
1529
+ const flushHeaders = res.flushHeaders?.bind(res);
1530
+ // The page so far while it's held, and null once it passes on.
1531
+ let page${t(": (string | Uint8Array)[] | null")} = null;
1532
+ let decided = false;
1533
+ let ended = false;
1534
+ const restore = () => {
1535
+ res.writeHead = writeHead;
1536
+ res.write = write;
1537
+ res.end = end;
1538
+ if (flushHeaders) res.flushHeaders = flushHeaders;
1539
+ };
1540
+ const decide = (status${t(": number")}, headers${t("?: unknown")}) => {
1541
+ if (decided) return;
1542
+ decided = true;
1543
+ const said = (name${t(": string")}) => String(given(headers, name) ?? res.getHeader(name) ?? '');
1544
+ const type = said('content-type');
1545
+ if (
1546
+ status === 200 &&
1547
+ /^text\/html\b/i.test(type) &&
1548
+ (!/;\s*charset=/i.test(type) || /;\s*charset="?utf-?8"?\s*(?:;|$)/i.test(type)) &&
1549
+ !said('content-encoding') &&
1550
+ !said('content-range')
1551
+ )
1552
+ page = [];
1553
+ else restore();
1554
+ };
1555
+ // What's held so far goes out as it is, and the rest passes straight on:
1556
+ // for a part the page can't be read in.
1557
+ const release = () => {
1558
+ const held = page ?? [];
1559
+ page = null;
1560
+ restore();
1561
+ writeHead(res.statusCode);
1562
+ for (const part of held) write(part);
1563
+ };
1564
+ // A part of the page, held. False when it can't be read: it passes on.
1565
+ const add = (chunk${t(": unknown")}, encoding${t(": unknown")}) => {
1566
+ if (chunk === undefined || chunk === null) return true;
1567
+ if (typeof chunk === 'string' && (typeof encoding !== 'string' || /^utf-?8$/i.test(encoding))) page?.push(chunk);
1568
+ else if (chunk instanceof Uint8Array) page?.push(chunk);
1569
+ else {
1570
+ release();
1571
+ return false;
1572
+ }
1573
+ return true;
1574
+ };
1575
+ res.writeHead = function (...args${t(": unknown[]")}) {
1576
+ if (ended) return res;
1577
+ const [status, second, third] = args;
1578
+ const headers = typeof second === 'string' ? third : second;
1579
+ decide(Number(status), headers);
1580
+ if (!page) return writeHead(...args);
1581
+ res.statusCode = Number(status);
1582
+ if (typeof second === 'string') res.statusMessage = second;
1583
+ // Its headers join those set before it, as Node's own writeHead does.
1584
+ const named = new Map${t("<string, { key: string; values: string[] }>")}();
1585
+ if (Array.isArray(headers))
1586
+ for (let i = 0; i + 1 < headers.length; i += 2) {
1587
+ const key = String(headers[i]);
1588
+ const entry = named.get(key.toLowerCase()) ?? { key, values: [] };
1589
+ entry.values.push(String(headers[i + 1]));
1590
+ named.set(key.toLowerCase(), entry);
1591
+ }
1592
+ else if (headers && typeof headers === 'object')
1593
+ for (const [key, value] of Object.entries(headers))
1594
+ if (value !== undefined && value !== null)
1595
+ named.set(key.toLowerCase(), { key, values: Array.isArray(value) ? value.map(String) : [String(value)] });
1596
+ for (const { key, values } of named.values()) res.setHeader(key, values.length === 1 ? values[0] : values);
1597
+ return res;
1598
+ };
1599
+ res.write = function (...args${t(": unknown[]")}) {
1600
+ if (ended) return false;
1601
+ decide(res.statusCode);
1602
+ if (!page) return write(...args);
1603
+ const done = typeof args[args.length - 1] === 'function' ? args.pop()${t(" as () => void")} : undefined;
1604
+ if (!add(args[0], args[1])) return write(...args, ...(done ? [done] : []));
1605
+ if (done) queueMicrotask(done);
1606
+ return true;
1607
+ };
1608
+ res.end = function (...args${t(": unknown[]")}) {
1609
+ if (ended) return res;
1610
+ decide(res.statusCode);
1611
+ if (!page) return end(...args);
1612
+ const done = typeof args[args.length - 1] === 'function' ? args.pop()${t(" as () => void")} : undefined;
1613
+ if (!add(args[0], args[1])) return end(...args, ...(done ? [done] : []));
1614
+ ended = true;
1615
+ const held = page;
1616
+ void send(held, done);
1617
+ return res;
1618
+ };
1619
+ if (flushHeaders)
1620
+ res.flushHeaders = function () {
1621
+ decide(res.statusCode);
1622
+ if (!page) flushHeaders();
1623
+ };
1624
+ // The page with the lines in it, or as it was, and its length.
1625
+ async function send(held${t(": (string | Uint8Array)[]")}, done${t("?: () => void")}) {
1626
+ const encoder = new TextEncoder();
1627
+ const parts = held.map((part) => (typeof part === 'string' ? encoder.encode(part) : part));
1628
+ const bytes = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
1629
+ let at = 0;
1630
+ for (const part of parts) {
1631
+ bytes.set(part, at);
1632
+ at += part.length;
1633
+ }
1634
+ let body = bytes;
1635
+ try {
1636
+ const html = new TextDecoder().decode(bytes);
1637
+ const policy = [res.getHeader('content-security-policy') ?? []].flat().join(',');
1638
+ const lines = await agentfaceLines();
1639
+ const out = insert(html, lines, policy);
1640
+ if (out !== html) body = encoder.encode(out);
1641
+ } catch {
1642
+ // The page as it was.
1643
+ }
1644
+ restore();
1645
+ if (!res.hasHeader('transfer-encoding')) res.setHeader('content-length', body.length);
1646
+ writeHead(res.statusCode);
1647
+ end(body, done);
1648
+ }
1649
+ }
1480
1650
  `
1481
1651
  };
1652
+ const types = kind === "node" ? t("import type { IncomingMessage, ServerResponse } from 'node:http';\n\n") : "";
1482
1653
  return String.raw`${about("//", HOW[kind])}
1483
- const SERVICE = '${service}';
1654
+ ${types}const SERVICE = '${service}';
1484
1655
  const SITE = '${site}';
1485
1656
  const TAG = '${tag}';
1486
1657
  const NOTICE = '${notice ?? ""}';
@@ -3284,16 +3455,16 @@ async function commonJs(p, file, source) {
3284
3455
  if (file.endsWith(".cjs")) return true;
3285
3456
  if (!file.endsWith(".js") || new RegExp(IMPORT.source, "m").test(source)) return false;
3286
3457
  const pkg = JSON.parse(await p.read("package.json") ?? "{}");
3287
- return pkg.type !== "module" && /\brequire\(/.test(source);
3458
+ return pkg.type !== "module" && /\brequire\(|^module\.exports\b/m.test(source);
3288
3459
  }
3289
- async function jsHelper(p, file, source, kind) {
3460
+ async function jsHelper(p, file, source, kind, prefix = "") {
3290
3461
  const cjs = await commonJs(p, file, source);
3291
3462
  const ts = /\.[cm]?tsx?$/.test(file);
3292
3463
  const folder = posix.dirname(file) === "." ? "" : posix.dirname(file) + "/";
3293
3464
  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";
3465
+ const name = prefix + (cjs ? "agentface.cjs" : ts ? "agentface.ts" : file.endsWith(".mjs") ? "agentface.mjs" : "agentface.js");
3295
3466
  const helper = await own(p, folder + name, script(kind, { ts, cjs }));
3296
- const from = "./" + (ts && !deno ? "agentface.js" : name);
3467
+ const from = "./" + (ts && !deno ? prefix + "agentface.js" : name);
3297
3468
  return helper && { helper, cjs, from };
3298
3469
  }
3299
3470
  function chained(source, call, chain, cjs, from, after) {
@@ -3398,6 +3569,126 @@ async function fastify(p) {
3398
3569
  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
3570
  });
3400
3571
  }
3572
+ var escaped = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3573
+ var wrapped = (source, start, last) => source.slice(0, start) + "agentface(" + source.slice(start, last + 1) + ")" + source.slice(last + 1);
3574
+ function functionEnd(source, at) {
3575
+ const rest = source.slice(at);
3576
+ const declared = /^(?:async\s+)?function\b\s*\*?\s*[\w$]*\s*(?=\()/.exec(rest);
3577
+ const arrow = !declared && /^(?:async\s*)?\(/.exec(rest);
3578
+ if (declared || arrow) {
3579
+ const params = bracket(
3580
+ source,
3581
+ at + (declared ? declared[0].length : arrow[0].length - 1)
3582
+ );
3583
+ if (!params) return void 0;
3584
+ const after = source.slice(params.close + 1);
3585
+ const body = (declared ? /^\s*(?::[^{};=]*)?/ : /^\s*(?::[^{};=]*)?=>\s*/).exec(after);
3586
+ const open = params.close + 1 + (body?.[0].length ?? 0);
3587
+ if (!body || source[open] !== "{") return void 0;
3588
+ return bracket(source, open)?.close;
3589
+ }
3590
+ const name = /^[\w$]+(?:\.[\w$]+)*/.exec(rest);
3591
+ return name && /^[ \t]*(?:;|\r?\n|$)/.test(rest.slice(name[0].length)) ? at + name[0].length - 1 : void 0;
3592
+ }
3593
+ function requireFirst(source, line) {
3594
+ if (source.includes(line)) return source;
3595
+ const last = lastMatch(source, REQUIRE);
3596
+ if (last)
3597
+ return source.slice(0, last.index + last[0].length) + eolOf(source) + line + source.slice(last.index + last[0].length);
3598
+ const at = /^(['"])use strict\1;?[^\n]*\n/.exec(source)?.[0].length ?? 0;
3599
+ return source.slice(0, at) + line + eolOf(source) + source.slice(at);
3600
+ }
3601
+ var withHelper = (source, text2, cjs, from) => cjs ? requireFirst(text2, `const { agentface } = require('${from}');`) : addImport(text2, importLine(source, "{ agentface }", from));
3602
+ function vercelEntry(source, cjs, from) {
3603
+ if (/(?<![\w$.])agentface\(/.test(source)) return source;
3604
+ const made = /^export\s+default\s+/m.exec(source) ?? /^module\.exports\s*=\s*/m.exec(source);
3605
+ if (!made) return null;
3606
+ const at = made.index + made[0].length;
3607
+ const last = functionEnd(source, at);
3608
+ if (last === void 0) return null;
3609
+ const name = /^(?:async\s+)?function\b\s*\*?\s*([\w$]+)/.exec(source.slice(at))?.[1];
3610
+ const elsewhere = source.slice(0, at) + source.slice(last + 1);
3611
+ if (name && new RegExp(`(?<![\\w$.])${escaped(name)}(?![\\w$])`).test(elsewhere)) return null;
3612
+ return withHelper(source, wrapped(source, at, last), cjs, from);
3613
+ }
3614
+ var HTTP = String.raw`['"](?:node:)?https?['"]`;
3615
+ function serverEntry(source, cjs, from) {
3616
+ if (/(?<![\w$.])agentface\(/.test(source)) return source;
3617
+ const calls = [];
3618
+ const named = (list2, as) => {
3619
+ const found = list2.match(new RegExp(String.raw`\bcreateServer\b(?:${as.source}([\w$]+))?`));
3620
+ if (found) calls.push(escaped(found[1] ?? "createServer"));
3621
+ };
3622
+ for (const m of source.matchAll(
3623
+ new RegExp(
3624
+ String.raw`\bimport\s+(?:([\w$]+)\s*,?\s*)?(?:\*\s*as\s+([\w$]+)|\{([^}]*)\})?\s*from\s*${HTTP}`,
3625
+ "g"
3626
+ )
3627
+ )) {
3628
+ for (const space of [m[1], m[2]]) if (space) calls.push(escaped(space) + String.raw`\.createServer`);
3629
+ if (m[3]) named(m[3], /\s+as\s+/);
3630
+ }
3631
+ for (const m of source.matchAll(
3632
+ new RegExp(
3633
+ String.raw`\b(?:const|let|var)\s+(?:([\w$]+)|\{([^}]*)\})\s*=\s*require\(\s*${HTTP}\s*\)`,
3634
+ "g"
3635
+ )
3636
+ )) {
3637
+ if (m[1]) calls.push(escaped(m[1]) + String.raw`\.createServer`);
3638
+ if (m[2]) named(m[2], /\s*:\s*/);
3639
+ }
3640
+ calls.push(String.raw`require\(\s*${HTTP}\s*\)\.createServer`);
3641
+ const call = new RegExp(String.raw`(?<![\w$.])(?:${calls.join("|")})\s*\(`, "g");
3642
+ for (let m; m = call.exec(source); ) {
3643
+ const open = m.index + m[0].length - 1;
3644
+ const args = bracket(source, open);
3645
+ if (!args || args.commas.length > 1) continue;
3646
+ const begin = args.commas.length ? args.commas[0] + 1 : open + 1;
3647
+ const piece = source.slice(begin, args.close);
3648
+ const start = begin + piece.search(/\S/);
3649
+ const last = begin + piece.trimEnd().length - 1;
3650
+ if (start > last || !args.commas.length && source[start] === "{") continue;
3651
+ return withHelper(source, wrapped(source, start, last), cjs, from);
3652
+ }
3653
+ return null;
3654
+ }
3655
+ async function vercelPages(p) {
3656
+ let config2;
3657
+ try {
3658
+ config2 = JSON.parse(await p.read("vercel.json") ?? "null");
3659
+ } catch {
3660
+ return null;
3661
+ }
3662
+ const rules = (list2) => Array.isArray(list2) ? list2 : [];
3663
+ const routes2 = [
3664
+ ...rules(config2?.rewrites).map((rule) => [rule?.source, rule?.destination]),
3665
+ ...rules(config2?.routes).map((rule) => [rule?.src, rule?.dest])
3666
+ ];
3667
+ for (const [from, to] of routes2) {
3668
+ if (typeof from !== "string" || typeof to !== "string" || /^\/api(?:\/|$)/.test(from)) continue;
3669
+ const route = /^\/(api(?:\/[\w.-]+)*)\/?(?:[?#]|$)/.exec(to)?.[1].replace(/\.[cm]?[jt]s$/, "");
3670
+ const file = route && p.list.find((f) => new RegExp(`^${escaped(route)}(?:/index)?\\.[cm]?[jt]s$`).test(f));
3671
+ const source = file ? await p.read(file) : null;
3672
+ if (file && source && vercelEntry(source, false, "") !== null) return { file, source };
3673
+ }
3674
+ return null;
3675
+ }
3676
+ async function node(p) {
3677
+ const vercel = await vercelPages(p);
3678
+ const found = vercel ?? await entry(p, (source) => serverEntry(source, false, "") !== null);
3679
+ if (!found) return null;
3680
+ const edit = vercel ? vercelEntry : serverEntry;
3681
+ const made = await jsHelper(p, found.file, found.source, "node", vercel ? "_" : "");
3682
+ if (!made || edit(found.source, made.cjs, made.from) === null) return null;
3683
+ return result(p, vercel ? "Vercel function" : "Node.js", {
3684
+ creates: [made.helper],
3685
+ edits: [
3686
+ ...cleaned(p.found),
3687
+ { file: found.file, source: found.source, edit: (text2) => edit(text2, made.cjs, made.from) ?? text2 }
3688
+ ],
3689
+ note: NOTE.request(made.helper.file)
3690
+ });
3691
+ }
3401
3692
  function addPythonImport(source, line) {
3402
3693
  if (new RegExp(`^${line.replace(/[.]/g, "\\.")}\\s*$`, "m").test(source)) return source;
3403
3694
  const lines = source.split("\n");
@@ -3962,10 +4253,10 @@ async function next(p) {
3962
4253
  });
3963
4254
  }
3964
4255
  var WRITERS = [
3965
- ...["astro", "vite", "hono", "fastify"].flatMap((kind) => [
4256
+ ...["astro", "vite", "hono", "fastify", "node"].flatMap((kind) => [
3966
4257
  script(kind),
3967
4258
  script(kind, { ts: true }),
3968
- ...kind === "fastify" || kind === "hono" ? [script(kind, { cjs: true })] : []
4259
+ ...kind === "fastify" || kind === "hono" || kind === "node" ? [script(kind, { cjs: true })] : []
3969
4260
  ]),
3970
4261
  DJANGO,
3971
4262
  ASGI,
@@ -3986,7 +4277,7 @@ function ownFile(source) {
3986
4277
  const { tag, notice } = linesIn(source);
3987
4278
  return Boolean(tag && WRITERS.some((write) => sameFile(source, write(tag, notice))));
3988
4279
  }
3989
- var FRAMEWORKS2 = [rails, phoenix, django, fastapi, go, next, astro, hono, fastify, vite];
4280
+ var FRAMEWORKS2 = [rails, phoenix, django, fastapi, go, next, astro, hono, fastify, vite, node];
3990
4281
  async function withFramework(dir, found) {
3991
4282
  if (found.manual && !found.manual.none) return found;
3992
4283
  if (["WordPress", "PrestaShop", "PrestaShop theme"].includes(found.framework)) return found;
@@ -3999,10 +4290,12 @@ async function withFramework(dir, found) {
3999
4290
  }
4000
4291
  return found;
4001
4292
  }
4293
+ var IMPORTED = /import \{ agentface \} from ['"]\.\/(?:src\/)?_?agentface\.[cm]?[jt]s['"];?/;
4294
+ var REQUIRED = /const \{ agentface \} = require\(['"]\.\/_?agentface\.c?js['"]\);/;
4002
4295
  var UNDO = [
4003
4296
  /plug Agentface(?![\w.])/,
4004
- /import \{ agentface \} from ['"]\.\/(?:src\/)?agentface\.[cm]?[jt]s['"];?/,
4005
- /const \{ agentface \} = require\(['"]\.\/agentface\.c?js['"]\);/,
4297
+ IMPORTED,
4298
+ REQUIRED,
4006
4299
  ".use(agentface())",
4007
4300
  ".addHook('onSend', agentface)",
4008
4301
  /^[ \t]*\w+\.add_middleware\(agentface\.Middleware\)/,
@@ -4014,6 +4307,15 @@ var UNDO = [
4014
4307
  NEXT_NOTICE,
4015
4308
  new RegExp(NEXT_IMPORTED.source.slice(1), "m")
4016
4309
  ];
4310
+ function unwrapped(text2) {
4311
+ for (let at; (at = text2.search(/(?<![\w$.])agentface\((?!\s*\))/)) !== -1; ) {
4312
+ const open = at + "agentface".length;
4313
+ const close = bracket(text2, open)?.close;
4314
+ if (close === void 0) break;
4315
+ text2 = text2.slice(0, at) + text2.slice(open + 1, close) + text2.slice(close + 1);
4316
+ }
4317
+ return text2;
4318
+ }
4017
4319
  async function undoFrameworks(dir) {
4018
4320
  const { list: list2 } = await project(dir);
4019
4321
  const edits = [];
@@ -4031,6 +4333,7 @@ async function undoFrameworks(dir) {
4031
4333
  text2 = text2.replace(/(\bdefineConfig\(|export default )\{\r?\n\}/, "$1{}");
4032
4334
  text2 = text2.replace(/^[ \t]*['"]agentface\.Middleware['"],[ \t]*\r?\n/m, "").replace(/['"]agentface\.Middleware['"],\s*/, "").replace(/,\s*['"]agentface\.Middleware['"]/, "");
4033
4335
  if (NEXT_CONFIGS.includes(file)) text2 = withoutNextConfig(text2);
4336
+ if (IMPORTED.test(source) || REQUIRED.test(source)) text2 = unwrapped(text2);
4034
4337
  if (file.endsWith(".go")) {
4035
4338
  text2 = text2.replace(/agentface\.Handler\(http\.DefaultServeMux\)/g, "nil");
4036
4339
  for (let at; (at = text2.indexOf("agentface.Handler(")) !== -1; ) {
@@ -8661,20 +8964,20 @@ var defaultTreeAdapter = {
8661
8964
  return templateElement.content;
8662
8965
  },
8663
8966
  setDocumentType(document, name, publicId, systemId) {
8664
- const doctypeNode = document.childNodes.find((node) => node.nodeName === "#documentType");
8967
+ const doctypeNode = document.childNodes.find((node2) => node2.nodeName === "#documentType");
8665
8968
  if (doctypeNode) {
8666
8969
  doctypeNode.name = name;
8667
8970
  doctypeNode.publicId = publicId;
8668
8971
  doctypeNode.systemId = systemId;
8669
8972
  } else {
8670
- const node = {
8973
+ const node2 = {
8671
8974
  nodeName: "#documentType",
8672
8975
  name,
8673
8976
  publicId,
8674
8977
  systemId,
8675
8978
  parentNode: null
8676
8979
  };
8677
- defaultTreeAdapter.appendChild(document, node);
8980
+ defaultTreeAdapter.appendChild(document, node2);
8678
8981
  }
8679
8982
  },
8680
8983
  setDocumentMode(document, mode) {
@@ -8683,11 +8986,11 @@ var defaultTreeAdapter = {
8683
8986
  getDocumentMode(document) {
8684
8987
  return document.mode;
8685
8988
  },
8686
- detachNode(node) {
8687
- if (node.parentNode) {
8688
- const idx = node.parentNode.childNodes.indexOf(node);
8689
- node.parentNode.childNodes.splice(idx, 1);
8690
- node.parentNode = null;
8989
+ detachNode(node2) {
8990
+ if (node2.parentNode) {
8991
+ const idx = node2.parentNode.childNodes.indexOf(node2);
8992
+ node2.parentNode.childNodes.splice(idx, 1);
8993
+ node2.parentNode = null;
8691
8994
  }
8692
8995
  },
8693
8996
  insertText(parentNode, text2) {
@@ -8717,14 +9020,14 @@ var defaultTreeAdapter = {
8717
9020
  }
8718
9021
  },
8719
9022
  //Tree traversing
8720
- getFirstChild(node) {
8721
- return node.childNodes[0];
9023
+ getFirstChild(node2) {
9024
+ return node2.childNodes[0];
8722
9025
  },
8723
- getChildNodes(node) {
8724
- return node.childNodes;
9026
+ getChildNodes(node2) {
9027
+ return node2.childNodes;
8725
9028
  },
8726
- getParentNode(node) {
8727
- return node.parentNode;
9029
+ getParentNode(node2) {
9030
+ return node2.parentNode;
8728
9031
  },
8729
9032
  getAttrList(element) {
8730
9033
  return element.attrs;
@@ -8752,27 +9055,27 @@ var defaultTreeAdapter = {
8752
9055
  return doctypeNode.systemId;
8753
9056
  },
8754
9057
  //Node types
8755
- isTextNode(node) {
8756
- return node.nodeName === "#text";
9058
+ isTextNode(node2) {
9059
+ return node2.nodeName === "#text";
8757
9060
  },
8758
- isCommentNode(node) {
8759
- return node.nodeName === "#comment";
9061
+ isCommentNode(node2) {
9062
+ return node2.nodeName === "#comment";
8760
9063
  },
8761
- isDocumentTypeNode(node) {
8762
- return node.nodeName === "#documentType";
9064
+ isDocumentTypeNode(node2) {
9065
+ return node2.nodeName === "#documentType";
8763
9066
  },
8764
- isElementNode(node) {
8765
- return Object.prototype.hasOwnProperty.call(node, "tagName");
9067
+ isElementNode(node2) {
9068
+ return Object.prototype.hasOwnProperty.call(node2, "tagName");
8766
9069
  },
8767
9070
  // Source code location
8768
- setNodeSourceCodeLocation(node, location) {
8769
- node.sourceCodeLocation = location;
9071
+ setNodeSourceCodeLocation(node2, location) {
9072
+ node2.sourceCodeLocation = location;
8770
9073
  },
8771
- getNodeSourceCodeLocation(node) {
8772
- return node.sourceCodeLocation;
9074
+ getNodeSourceCodeLocation(node2) {
9075
+ return node2.sourceCodeLocation;
8773
9076
  },
8774
- updateNodeSourceCodeLocation(node, endLocation) {
8775
- node.sourceCodeLocation = { ...node.sourceCodeLocation, ...endLocation };
9077
+ updateNodeSourceCodeLocation(node2, endLocation) {
9078
+ node2.sourceCodeLocation = { ...node2.sourceCodeLocation, ...endLocation };
8776
9079
  }
8777
9080
  };
8778
9081
 
@@ -9232,19 +9535,19 @@ var Parser = class {
9232
9535
  }
9233
9536
  //Stack events
9234
9537
  /** @internal */
9235
- onItemPush(node, tid, isTop) {
9538
+ onItemPush(node2, tid, isTop) {
9236
9539
  var _a, _b;
9237
- (_b = (_a = this.treeAdapter).onItemPush) === null || _b === void 0 ? void 0 : _b.call(_a, node);
9540
+ (_b = (_a = this.treeAdapter).onItemPush) === null || _b === void 0 ? void 0 : _b.call(_a, node2);
9238
9541
  if (isTop && this.openElements.stackTop > 0)
9239
- this._setContextModes(node, tid);
9542
+ this._setContextModes(node2, tid);
9240
9543
  }
9241
9544
  /** @internal */
9242
- onItemPop(node, isTop) {
9545
+ onItemPop(node2, isTop) {
9243
9546
  var _a, _b;
9244
9547
  if (this.options.sourceCodeLocationInfo) {
9245
- this._setEndLocation(node, this.currentToken);
9548
+ this._setEndLocation(node2, this.currentToken);
9246
9549
  }
9247
- (_b = (_a = this.treeAdapter).onItemPop) === null || _b === void 0 ? void 0 : _b.call(_a, node, this.openElements.current);
9550
+ (_b = (_a = this.treeAdapter).onItemPop) === null || _b === void 0 ? void 0 : _b.call(_a, node2, this.openElements.current);
9248
9551
  if (isTop) {
9249
9552
  let current2;
9250
9553
  let currentTagId;
@@ -9281,13 +9584,13 @@ var Parser = class {
9281
9584
  }
9282
9585
  /** @protected */
9283
9586
  _findFormInFragmentContext() {
9284
- let node = this.fragmentContext;
9285
- while (node) {
9286
- if (this.treeAdapter.getTagName(node) === TAG_NAMES.FORM) {
9287
- this.formElement = node;
9587
+ let node2 = this.fragmentContext;
9588
+ while (node2) {
9589
+ if (this.treeAdapter.getTagName(node2) === TAG_NAMES.FORM) {
9590
+ this.formElement = node2;
9288
9591
  break;
9289
9592
  }
9290
- node = this.treeAdapter.getParentNode(node);
9593
+ node2 = this.treeAdapter.getParentNode(node2);
9291
9594
  }
9292
9595
  }
9293
9596
  _initTokenizerForFragmentParsing() {
@@ -9329,7 +9632,7 @@ var Parser = class {
9329
9632
  this.treeAdapter.setDocumentType(this.document, name, publicId, systemId);
9330
9633
  if (token.location) {
9331
9634
  const documentChildren = this.treeAdapter.getChildNodes(this.document);
9332
- const docTypeNode = documentChildren.find((node) => this.treeAdapter.isDocumentTypeNode(node));
9635
+ const docTypeNode = documentChildren.find((node2) => this.treeAdapter.isDocumentTypeNode(node2));
9333
9636
  if (docTypeNode) {
9334
9637
  this.treeAdapter.setNodeSourceCodeLocation(docTypeNode, token.location);
9335
9638
  }
@@ -12392,41 +12695,41 @@ function mark(source, first) {
12392
12695
  return { text: text2, offsets };
12393
12696
  }
12394
12697
  var unmark = (text2) => text2.replace(MARKED, "");
12395
- var elements = (node, out = []) => {
12396
- for (const child of node.childNodes ?? [])
12698
+ var elements = (node2, out = []) => {
12699
+ for (const child of node2.childNodes ?? [])
12397
12700
  if (child.tagName) {
12398
12701
  out.push(child);
12399
12702
  elements(child, out);
12400
12703
  }
12401
12704
  return out;
12402
12705
  };
12403
- var text = (node) => node.nodeName === "#text" ? node.value ?? "" : (node.childNodes ?? []).map(text).join("");
12404
- var attribute = (node, name) => node.attrs?.find((attr) => attr.name === name)?.value;
12405
- var outside = (node) => {
12406
- for (let at = node; at; at = at.parentNode)
12706
+ var text = (node2) => node2.nodeName === "#text" ? node2.value ?? "" : (node2.childNodes ?? []).map(text).join("");
12707
+ var attribute = (node2, name) => node2.attrs?.find((attr) => attr.name === name)?.value;
12708
+ var outside = (node2) => {
12709
+ for (let at = node2; at; at = at.parentNode)
12407
12710
  if (OUTSIDE.has(at.tagName ?? "") || attribute(at, "hidden") !== void 0 || attribute(at, "role") === "dialog")
12408
12711
  return true;
12409
12712
  return false;
12410
12713
  };
12411
- var isLine = (node) => node.tagName === "span" && (attribute(node, "class") ?? "").split(/\s+/).includes("agentface-api");
12714
+ var isLine = (node2) => node2.tagName === "span" && (attribute(node2, "class") ?? "").split(/\s+/).includes("agentface-api");
12412
12715
  function readPage(html) {
12413
12716
  const all = elements(parse(html));
12414
12717
  const marks = /* @__PURE__ */ new Map();
12415
- for (const node of all) {
12416
- const value = attribute(node, MARK);
12718
+ for (const node2 of all) {
12719
+ const value = attribute(node2, MARK);
12417
12720
  if (value) marks.set(Number(value), (marks.get(Number(value)) ?? 0) + 1);
12418
12721
  }
12419
12722
  const paragraphsIn = (root) => {
12420
12723
  const inside = elements(root);
12421
- const heading = inside.findIndex((node) => node.tagName === "h1");
12724
+ const heading = inside.findIndex((node2) => node2.tagName === "h1");
12422
12725
  const found = inside.filter(
12423
- (node) => node.tagName === "p" && text(node).trim().length >= SHORTEST && !outside(node)
12726
+ (node2) => node2.tagName === "p" && text(node2).trim().length >= SHORTEST && !outside(node2)
12424
12727
  );
12425
- const after = found.filter((node) => heading >= 0 && inside.indexOf(node) > heading);
12426
- return [...after, ...found.filter((node) => !after.includes(node))];
12728
+ const after = found.filter((node2) => heading >= 0 && inside.indexOf(node2) > heading);
12729
+ return [...after, ...found.filter((node2) => !after.includes(node2))];
12427
12730
  };
12428
- const main2 = all.find((node) => node.tagName === "main");
12429
- const body = all.find((node) => node.tagName === "body");
12731
+ const main2 = all.find((node2) => node2.tagName === "main");
12732
+ const body = all.find((node2) => node2.tagName === "body");
12430
12733
  let paragraphs = main2 ? paragraphsIn(main2) : [];
12431
12734
  if (!paragraphs.length && body) paragraphs = paragraphsIn(body);
12432
12735
  const lines = all.filter(isLine);
@@ -12435,9 +12738,9 @@ function readPage(html) {
12435
12738
  lines: lines.length,
12436
12739
  // Whether the page's one line ends its first paragraph after its heading.
12437
12740
  first: lines.length === 1 && !!paragraphs[0] && elements(paragraphs[0]).some(isLine),
12438
- paragraphs: paragraphs.map((node) => {
12439
- const value = attribute(node, MARK);
12440
- return { mark: value ? Number(value) : null, text: text(node).replace(/\s+/g, " ").trim() };
12741
+ paragraphs: paragraphs.map((node2) => {
12742
+ const value = attribute(node2, MARK);
12743
+ return { mark: value ? Number(value) : null, text: text(node2).replace(/\s+/g, " ").trim() };
12441
12744
  })
12442
12745
  };
12443
12746
  }
@@ -12531,8 +12834,8 @@ function routeOf(found, path6) {
12531
12834
  }
12532
12835
  function links(html, origin) {
12533
12836
  const out = [];
12534
- for (const node of elements(parse(html))) {
12535
- const href = node.tagName === "a" ? attribute(node, "href") : void 0;
12837
+ for (const node2 of elements(parse(html))) {
12838
+ const href = node2.tagName === "a" ? attribute(node2, "href") : void 0;
12536
12839
  if (!href) continue;
12537
12840
  let url;
12538
12841
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentface",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "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.",
5
5
  "repository": {
6
6
  "type": "git",