#!/usr/bin/env node
// Totems install helper. No packages needed. `plan` only reads. `apply` adds one line. `check` asks Totems about one public page.
import fs from "node:fs"; import path from "node:path";
const skip = new Set(["node_modules", ".git", ".next", "dist", "build", "out", ".astro", "vendor", "coverage", ".vercel"]);
export function readArgs(a) { const o = {}; for (let i = 0; i < a.length; i++) if (a[i].startsWith("--")) o[a[i].slice(2)] = a[++i] ?? ""; return o; }
export function checkInput({ src, key }) {
let u; try { u = new URL(src); } catch { throw new Error("The script address is not a web address."); }
if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || !u.pathname.endsWith("/t.js")) throw new Error("The script address must start with https:// and end with /t.js.");
if (!/^mk_[A-Za-z0-9_-]{6,80}$/.test(key ?? "")) throw new Error("The site key starts with mk_. Never use an API key here.");
}
export const line = ({ src, key }) => ``;
const jsx = ({ src, key }) => ``;
const has = (d, f) => fs.existsSync(path.join(d, f)), read = (d, f) => fs.readFileSync(path.join(d, f), "utf8");
const first = (d, list) => list.find((f) => has(d, f)) ?? null;
function files(dir, depth = 5, base = dir) {
if (depth < 0) return [];
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isSymbolicLink() || skip.has(e.name) || (e.name.startsWith(".") && e.name !== ".htaccess") ? [] : e.isDirectory() ? files(path.join(dir, e.name), depth - 1, base) : [path.relative(base, path.join(dir, e.name))]));
}
/** The kind of site and the one shared file that holds the head. */
export function detect(dir) {
let deps = {}; try { const p = JSON.parse(read(dir, "package.json")); deps = { ...p.dependencies, ...p.devDependencies }; } catch { /* not a Node project */ }
if (deps.next) {
const f = first(dir, ["app/layout.tsx", "src/app/layout.tsx", "app/layout.jsx", "src/app/layout.jsx", "app/layout.js", "src/app/layout.js"]); if (f) return { kind: "next-app", file: f };
const p = first(dir, ["pages/_document.tsx", "src/pages/_document.tsx", "pages/_document.jsx", "src/pages/_document.jsx", "pages/_document.js", "src/pages/_document.js"]); return { kind: "next-pages", file: p };
}
if (deps.astro) { const l = files(dir).filter((f) => /layouts\/.*\.astro$/.test(f) && /<\/head>/i.test(read(dir, f))); return { kind: "astro", file: l.length === 1 ? l[0] : l.find((f) => /(Base|Main|Layout|BaseHead)\.astro$/.test(f)) ?? l[0] ?? null, choices: l }; }
if (has(dir, "style.css") && has(dir, "functions.php") && /Theme Name:/i.test(read(dir, "style.css"))) return { kind: "wordpress", file: "functions.php" };
if (deps.vite && has(dir, "index.html")) return { kind: "vite", file: "index.html" };
const html = files(dir, 3).filter((f) => /\.html?$/i.test(f) && /<\/head>/i.test(read(dir, f)));
if (html.length) return { kind: "html", file: html.includes("index.html") ? "index.html" : html[0], choices: html };
return { kind: "unknown", file: null };
}
export const installed = (text, key) => (text.match(new RegExp(`data-key=["']${key}["']`, "g")) ?? []).length;
/** The new text of one file, or null when there is no safe place. */
export function edit(kind, text, o) {
if (installed(text, o.key)) return text;
if (kind === "wordpress") {
const body = `\n// Totems tracking\nadd_action('wp_head', function () {\n echo '${line(o)}' . "\\n";\n});\n`;
const end = /\?>\s*$/.exec(text); return end ? `${text.slice(0, end.index).trimEnd()}\n${body}` : `${text.trimEnd()}\n${body}`;
}
const tag = kind.startsWith("next") ? jsx(o) : line(o);
const close = kind === "next-pages" ? /([ \t]*)<\/Head>/ : /([ \t]*)<\/head>/i, m = close.exec(text);
const inline = kind === "astro" ? tag.replace("