tencil 0.4.0 → 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/cli.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { _ as parsePairingInput, a as detectAgents, c as savedProvider, f as VERSION, g as exchangePairingCredential, h as createLocalPairingCode, i as PROVIDERS, m as DEFAULT_T3_URL, n as probeDaemon, o as providerLabel, p as CredentialStore, r as startDaemon, s as saveProvider, t as DEFAULT_PORT, u as defaultDataDir, v as withoutNpmEnv, y as loadAgentSdk } from "./server-9m0nvaLs.mjs";
2
+ import { _ as parsePairingInput, a as detectAgents, c as savedProvider, f as VERSION, g as exchangePairingCredential, h as createLocalPairingCode, i as PROVIDERS, m as DEFAULT_T3_URL, n as probeDaemon, o as providerLabel, p as CredentialStore, r as startDaemon, s as saveProvider, t as DEFAULT_PORT, u as defaultDataDir, v as withoutNpmEnv, y as loadAgentSdk } from "./server-COf9gtqR.mjs";
3
+ import { t as DEFAULT_CLOUD_URL } from "./cloud-CiwIrP1h.mjs";
3
4
  import { execFileSync, spawn, spawnSync } from "node:child_process";
4
- import { cpSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
6
  import { readFile, readdir, writeFile } from "node:fs/promises";
6
7
  import { basename, dirname, join, relative, resolve } from "node:path";
7
8
  import { parseArgs } from "node:util";
@@ -630,6 +631,34 @@ function addTencilToBody(source) {
630
631
  else edited = `${source.slice(0, close)}<Tencil />${source.slice(close)}`;
631
632
  return addImport(edited, `import { Tencil } from ${style.quote}tencil/react${style.quote}${style.semi}`);
632
633
  }
634
+ /**
635
+ * `export default nextConfig` → `export default withTencil(nextConfig)`, plus
636
+ * the import. Wraps whatever is exported, including another plugin's wrapper.
637
+ */
638
+ function addWithTencil(source) {
639
+ if (/["']tencil\/next["']/.test(source)) return source;
640
+ const style = detectStyle(source);
641
+ const exported = /^export\s+default\s+/m.exec(source);
642
+ if (!exported) return null;
643
+ const start = exported.index + exported[0].length;
644
+ const end = expressionEnd(source, start);
645
+ if (end === -1) return null;
646
+ const expression = source.slice(start, end).trimEnd();
647
+ if (!expression || /^(?:function|class|async)\b/.test(expression)) return null;
648
+ return addImport(`${source.slice(0, start)}withTencil(${expression})${source.slice(start + expression.length)}`, `import { withTencil } from ${style.quote}tencil/next${style.quote}${style.semi}`);
649
+ }
650
+ /** Where the expression starting at `start` ends: `;`, or a newline outside brackets. */
651
+ function expressionEnd(source, start) {
652
+ for (let i = start; i < source.length; i++) {
653
+ const char = source[i];
654
+ if (char === "\"" || char === "'" || char === "`") i = skipString(source, i);
655
+ else if (char === "(" || char === "[" || char === "{") {
656
+ i = matchBracket(source, i);
657
+ if (i === -1) return -1;
658
+ } else if (char === ";" || char === "\n") return i;
659
+ }
660
+ return source.length;
661
+ }
633
662
  /** Index of the bracket closing the one at `open`, skipping strings and comments. */
634
663
  function matchBracket(source, open) {
635
664
  const pairs = {
@@ -668,14 +697,6 @@ function skipString(source, start) {
668
697
  else if (source[i] === quote) return i;
669
698
  return source.length;
670
699
  }
671
- /** Projects set up while Tencil was called Fixhere (up to 0.2.0) import it under the old name. */
672
- function usesFixhere(source) {
673
- return /(['"])fixhere\/(?:react|vite)\1/.test(source);
674
- }
675
- /** Point a Fixhere integration at Tencil: `fixhere/react` → `tencil/react`, `<Fixhere />` → `<Tencil />`. */
676
- function renameFromFixhere(source) {
677
- return source.replace(/(['"])fixhere\/(react|vite)\1/g, "$1tencil/$2$1").replace(/\bFixhere\b/g, "Tencil").replace(/\bimport\s+fixhere\b/g, "import tencil").replace(/\bfixhere\(/g, "tencil(");
678
- }
679
700
  //#endregion
680
701
  //#region src/init/detect-framework.ts
681
702
  /** Inspect a project folder to decide how Tencil should be wired in. */
@@ -788,9 +809,6 @@ function installCommand(manager, spec) {
788
809
  ]];
789
810
  }
790
811
  }
791
- function uninstallCommand(manager, name) {
792
- return manager === "npm" ? ["npm", ["uninstall", name]] : [manager, ["remove", name]];
793
- }
794
812
  function variants(bases, extensions) {
795
813
  return bases.flatMap((base) => extensions.map((ext) => `${base}.${ext}`));
796
814
  }
@@ -850,23 +868,21 @@ function hunks(lines, context = 2) {
850
868
  //#endregion
851
869
  //#region src/init/run-init.ts
852
870
  const SCRIPT_TAG = "<script src=\"http://localhost:4747/tencil.js\" async><\/script>";
871
+ const NEXT_CONFIGS = [
872
+ "next.config.ts",
873
+ "next.config.mts",
874
+ "next.config.mjs",
875
+ "next.config.js"
876
+ ];
853
877
  /** Work out the edits without touching the disk. */
854
- async function planInit(root) {
878
+ async function planInit(root, options = {}) {
855
879
  const framework = await detectFramework(root);
856
880
  const edits = [];
857
881
  const manual = [];
858
882
  const edit = async (path, codemod, instruction) => {
859
883
  if (!path) return void manual.push(instruction);
860
884
  const before = await readFile(path, "utf8");
861
- if (usesFixhere(before)) {
862
- edits.push({
863
- path,
864
- before,
865
- after: renameFromFixhere(before)
866
- });
867
- return;
868
- }
869
- if (/(?:tencil|fixhere)\.js/.test(before)) {
885
+ if (/tencil\.js/.test(before)) {
870
886
  manual.push(`${relative(root, path)} loads tencil.js by hand. Replace that tag with \`<Tencil />\` from \`tencil/react\` so the bridge's port is picked up automatically.`);
871
887
  return;
872
888
  }
@@ -890,6 +906,19 @@ async function planInit(root) {
890
906
  break;
891
907
  case "unknown": manual.push(`${framework.reason} Load this in development only: ${SCRIPT_TAG}`);
892
908
  }
909
+ if (options.cloud && (framework.kind === "next-app" || framework.kind === "next-pages")) {
910
+ const config = NEXT_CONFIGS.map((name) => join(root, name)).find((path) => existsSync(path));
911
+ if (config) {
912
+ const before = await readFile(config, "utf8");
913
+ const after = addWithTencil(before);
914
+ if (after === null) manual.push(`Wrap the exported config in \`withTencil()\` from \`tencil/next\` (in ${relative(root, config)})`);
915
+ else if (after !== before) edits.push({
916
+ path: config,
917
+ before,
918
+ after
919
+ });
920
+ } else manual.push("Create next.config.ts that exports `withTencil({})` from `tencil/next`");
921
+ }
893
922
  return {
894
923
  framework,
895
924
  edits,
@@ -898,7 +927,7 @@ async function planInit(root) {
898
927
  }
899
928
  async function runInit(options) {
900
929
  const log = options.log ?? console.log;
901
- const plan = await planInit(options.root);
930
+ const plan = await planInit(options.root, { cloud: options.cloud });
902
931
  log(`\n ${pc.bold("Tencil")} ${pc.dim("·")} ${describe(plan.framework)}\n`);
903
932
  for (const edit of plan.edits) {
904
933
  log(` ${pc.bold(relative(options.root, edit.path))}`);
@@ -928,8 +957,8 @@ async function runInit(options) {
928
957
  for (const edit of plan.edits) await writeFile(edit.path, edit.after);
929
958
  if (!options.skipInstall && plan.framework.kind !== "unknown") {
930
959
  if (!await hasDependency(options.root, "tencil") || options.from) install(options, log);
931
- if (await hasDependency(options.root, "fixhere")) uninstall(options, "fixhere", log);
932
960
  }
961
+ if (options.cloud) return logCloudSteps(plan.framework, log);
933
962
  let autostart = false;
934
963
  if (options.daemon) {
935
964
  const result = await ensureDaemon(options.daemon, defaultDataDir());
@@ -945,6 +974,16 @@ async function runInit(options) {
945
974
  if (options.daemon && !autostart) log(pc.dim(" Start Tencil at login: npx tencil setup"));
946
975
  log("");
947
976
  }
977
+ /** What's left to do in Tencil Cloud and the host once the code is in place. */
978
+ function logCloudSteps(framework, log) {
979
+ const env = pc.cyan("TENCIL_CLOUD=<project key>");
980
+ log(` ${pc.green("✓")} The overlay loads from Tencil Cloud on preview builds that set ${env}.`);
981
+ log(` 1. Create a project at ${pc.cyan(DEFAULT_CLOUD_URL)} and copy its key.`);
982
+ log(` 2. Add ${env} to your host's ${pc.bold("Preview")} environment only (Vercel: Settings → Environment Variables).`);
983
+ log(" 3. Redeploy a preview. Production deployments never load the overlay.");
984
+ if (framework.kind === "next-app" || framework.kind === "next-pages") log(pc.dim(" Keep <Tencil /> in a server component: it reads TENCIL_CLOUD when the page renders."));
985
+ log("");
986
+ }
948
987
  /** Already a dependency (and no other package asked for with `--from`)? */
949
988
  async function hasDependency(root, name) {
950
989
  try {
@@ -954,16 +993,6 @@ async function hasDependency(root, name) {
954
993
  return false;
955
994
  }
956
995
  }
957
- function uninstall(options, name, log) {
958
- const [command, args] = uninstallCommand(detectPackageManager(options.root), name);
959
- log(` ${pc.dim(`$ ${command} ${args.join(" ")}`)}`);
960
- spawnSync(command, args, {
961
- cwd: options.root,
962
- stdio: "inherit",
963
- shell: process.platform === "win32",
964
- env: withoutNpmEnv()
965
- });
966
- }
967
996
  function install(options, log) {
968
997
  const [command, args] = installCommand(detectPackageManager(options.root), options.from ?? "tencil");
969
998
  log(` ${pc.dim(`$ ${command} ${args.join(" ")}`)}`);
@@ -983,64 +1012,6 @@ function describe(framework) {
983
1012
  }
984
1013
  }
985
1014
  //#endregion
986
- //#region src/service/migrate-from-fixhere.ts
987
- /** What Fixhere (Tencil's name up to 0.2.0) called its login service. */
988
- function fixhereServiceNames(port = DEFAULT_PORT) {
989
- const names = [{
990
- label: "dev.fixhere.daemon",
991
- unit: "fixhere.service",
992
- task: "Fixhere"
993
- }];
994
- if (port !== 4747) names.push({
995
- label: `dev.fixhere.daemon.${port}`,
996
- unit: `fixhere-${port}.service`,
997
- task: `Fixhere ${port}`
998
- });
999
- return names;
1000
- }
1001
- /** Files that move to Tencil's data folder: pins, pairing, settings. Not the runtime copy or logs. */
1002
- function carriesOver(path) {
1003
- const name = basename(path);
1004
- return !/^runtime(-\d+)?$/.test(name) && name !== "daemon.log";
1005
- }
1006
- /**
1007
- * Move a Fixhere install over to Tencil, once: copy its data folder, remove its
1008
- * login service and stop its daemon, which would otherwise hold the port.
1009
- */
1010
- async function migrateFromFixhere(port, dataDir, log) {
1011
- const steps = [];
1012
- const oldDir = join(dirname(dataDir), "fixhere");
1013
- if (existsSync(oldDir) && !existsSync(dataDir)) {
1014
- cpSync(oldDir, dataDir, {
1015
- recursive: true,
1016
- filter: carriesOver
1017
- });
1018
- steps.push("pins and pairing");
1019
- }
1020
- for (const names of fixhereServiceNames(port)) {
1021
- if (servicePort(readServiceDefinition(names)) !== port) continue;
1022
- removeService(names);
1023
- steps.push("login service");
1024
- }
1025
- if (await stopFixhereDaemon(port)) steps.push("daemon");
1026
- if (steps.length) log(`\n ${pc.green("✓")} Moved Fixhere over to Tencil ${pc.dim(`(${[...new Set(steps)].join(", ")})`)}`);
1027
- }
1028
- /** A Fixhere daemon on `port` answers /health as "fixhere"; stop it so Tencil can listen. */
1029
- async function stopFixhereDaemon(port) {
1030
- const health = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1500) }).then((response) => response.json()).catch(() => void 0);
1031
- if (health?.name !== "fixhere" || !health.pid) return false;
1032
- try {
1033
- process.kill(health.pid, "SIGTERM");
1034
- } catch {
1035
- return false;
1036
- }
1037
- for (let attempt = 0; attempt < 50; attempt++) {
1038
- await new Promise((resolve) => setTimeout(resolve, 100));
1039
- if (!await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(500) }).catch(() => void 0)) return true;
1040
- }
1041
- return true;
1042
- }
1043
- //#endregion
1044
1015
  //#region src/cli/commands/connect.ts
1045
1016
  async function connect(input, t3Url) {
1046
1017
  const store = new CredentialStore();
@@ -1327,18 +1298,12 @@ ${pc.dim("Setup and init options")}
1327
1298
  --dry-run Show the changes without writing them
1328
1299
  --skip-install Don't install the tencil package
1329
1300
  --skip-pair Don't pair with T3 Code
1301
+ --cloud init: set up for Tencil Cloud previews (no daemon on this machine)
1330
1302
  --from <spec> Package to install instead of "tencil" (e.g. a local path)
1331
1303
 
1332
1304
  -h, --help Show help
1333
1305
  -v, --version Show version
1334
1306
  `;
1335
- /** Commands that start or install the daemon. */
1336
- const SETS_UP = [
1337
- "setup",
1338
- "start",
1339
- "init",
1340
- "service"
1341
- ];
1342
1307
  async function main() {
1343
1308
  const { values, positionals } = parseArgs({
1344
1309
  allowPositionals: true,
@@ -1366,6 +1331,7 @@ async function main() {
1366
1331
  "dry-run": { type: "boolean" },
1367
1332
  "skip-install": { type: "boolean" },
1368
1333
  "skip-pair": { type: "boolean" },
1334
+ cloud: { type: "boolean" },
1369
1335
  from: { type: "string" },
1370
1336
  help: {
1371
1337
  type: "boolean",
@@ -1393,7 +1359,6 @@ async function main() {
1393
1359
  port,
1394
1360
  args: forwardedFlags(values)
1395
1361
  };
1396
- if (command === void 0 || SETS_UP.includes(command)) await migrateFromFixhere(port, defaultDataDir(), console.log);
1397
1362
  switch (command) {
1398
1363
  case void 0: return quickstart(daemonCommand, {
1399
1364
  root: resolve(values.root ?? process.cwd()),
@@ -1430,8 +1395,9 @@ async function main() {
1430
1395
  skipPair: values["skip-pair"],
1431
1396
  from: values.from,
1432
1397
  port,
1433
- daemon: daemonCommand,
1434
- t3Url
1398
+ daemon: values.cloud ? void 0 : daemonCommand,
1399
+ t3Url,
1400
+ cloud: values.cloud
1435
1401
  });
1436
1402
  default:
1437
1403
  console.error(`Unknown command "${command}"\n${HELP}`);
@@ -0,0 +1,14 @@
1
+ import "./index-B0phpEz9.mjs";
2
+ //#region src/integrations/cloud.d.ts
3
+ interface TencilCloudOptions {
4
+ /** Project key from the Tencil Cloud dashboard. Defaults to TENCIL_CLOUD. */
5
+ project?: string;
6
+ /** `owner/name` on GitHub. Defaults to the host's git env vars. */
7
+ repo?: string;
8
+ branch?: string;
9
+ sha?: string;
10
+ /** Tencil Cloud itself; only for testing against a local one. Defaults to TENCIL_CLOUD_URL. */
11
+ url?: string;
12
+ }
13
+ //#endregion
14
+ export { TencilCloudOptions as t };
@@ -0,0 +1,104 @@
1
+ //#region src/integrations/cloud.ts
2
+ /** Where Tencil Cloud serves the overlay and its bridge. */
3
+ const DEFAULT_CLOUD_URL = "https://cloud.tencil.dev";
4
+ const PROJECT_KEY = /^[A-Za-z0-9_-]{8,64}$/;
5
+ const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
6
+ const SHA = /^[0-9a-f]{7,64}$/i;
7
+ /**
8
+ * Whether this build loads the overlay from Tencil Cloud. Only when a project key
9
+ * is set, and never for a production deployment: the overlay lets reviewers make
10
+ * an agent change the code, so it belongs on previews only. Repo, branch and
11
+ * commit come from the host (Vercel, Netlify, Cloudflare Pages, GitHub Actions),
12
+ * so the cloud knows which code the page was built from.
13
+ */
14
+ function resolveCloudBuild(env, options = {}) {
15
+ const projectKey = options.project ?? env.TENCIL_CLOUD;
16
+ if (!projectKey) return { kind: "off" };
17
+ if (!PROJECT_KEY.test(projectKey)) return {
18
+ kind: "refused",
19
+ reason: "TENCIL_CLOUD is not a Tencil Cloud project key."
20
+ };
21
+ const production = productionDeployment(env);
22
+ if (production) return {
23
+ kind: "refused",
24
+ reason: `${production}: the overlay only loads on previews.`
25
+ };
26
+ const repo = options.repo ?? env.TENCIL_CLOUD_REPO ?? hostRepo(env);
27
+ const branch = options.branch ?? env.TENCIL_CLOUD_BRANCH ?? hostBranch(env);
28
+ const sha = options.sha ?? env.TENCIL_CLOUD_SHA ?? hostSha(env);
29
+ const missing = [
30
+ !repo && "repository",
31
+ !branch && "branch",
32
+ !sha && "commit"
33
+ ].filter(Boolean);
34
+ if (missing.length) return {
35
+ kind: "refused",
36
+ reason: `No ${missing.join(", ")} found for this build. Set TENCIL_CLOUD_REPO, TENCIL_CLOUD_BRANCH and TENCIL_CLOUD_SHA.`
37
+ };
38
+ if (!REPO.test(repo)) return {
39
+ kind: "refused",
40
+ reason: `"${repo}" is not a GitHub repository (owner/name).`
41
+ };
42
+ if (!SHA.test(sha)) return {
43
+ kind: "refused",
44
+ reason: `"${sha}" is not a commit hash.`
45
+ };
46
+ const url = (options.url ?? env.TENCIL_CLOUD_URL ?? "https://cloud.tencil.dev").replace(/\/+$/, "");
47
+ if (!/^https?:\/\//.test(url)) return {
48
+ kind: "refused",
49
+ reason: `TENCIL_CLOUD_URL "${url}" is not an http(s) URL.`
50
+ };
51
+ return {
52
+ kind: "on",
53
+ url,
54
+ build: {
55
+ projectKey,
56
+ repo,
57
+ branch,
58
+ sha: sha.toLowerCase()
59
+ }
60
+ };
61
+ }
62
+ /** The host's name for a production deployment, if this is one. */
63
+ function productionDeployment(env) {
64
+ if (env.VERCEL_ENV === "production") return "VERCEL_ENV is production";
65
+ if (env.NETLIFY && env.CONTEXT === "production") return "Netlify CONTEXT is production";
66
+ if (env.TENCIL_CLOUD_ENV === "production") return "TENCIL_CLOUD_ENV is production";
67
+ }
68
+ function hostRepo(env) {
69
+ if (env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG) return `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}`;
70
+ if (env.GITHUB_REPOSITORY) return env.GITHUB_REPOSITORY;
71
+ return (env.REPOSITORY_URL?.match(/github\.com[/:]([^/]+\/[^/]+?)(?:\.git)?$/))?.[1];
72
+ }
73
+ function hostBranch(env) {
74
+ return env.VERCEL_GIT_COMMIT_REF ?? env.CF_PAGES_BRANCH ?? (env.NETLIFY ? env.HEAD : void 0) ?? env.GITHUB_HEAD_REF ?? env.GITHUB_REF_NAME;
75
+ }
76
+ function hostSha(env) {
77
+ return env.VERCEL_GIT_COMMIT_SHA ?? env.CF_PAGES_COMMIT_SHA ?? (env.NETLIFY ? env.COMMIT_REF : void 0) ?? env.GITHUB_SHA;
78
+ }
79
+ /** A JSON string literal that is also safe inside an inline `<script>`. */
80
+ function scriptString(value) {
81
+ return JSON.stringify(value).replace(/</g, "\\u003c");
82
+ }
83
+ /**
84
+ * Browser code that loads the overlay from Tencil Cloud. The script tag carries
85
+ * the build, which the overlay passes on when it connects.
86
+ */
87
+ function cloudLoader({ url, build }) {
88
+ return `;(() => {
89
+ if (typeof document === "undefined") return;
90
+ const src = ${scriptString(`${url}/tencil.js`)};
91
+ if (document.querySelector('script[src="' + src + '"]')) return;
92
+ const script = document.createElement("script");
93
+ script.src = src;
94
+ script.async = true;
95
+ script.dataset.bridge = ${scriptString(url)};
96
+ script.dataset.tencilProject = ${scriptString(build.projectKey)};
97
+ script.dataset.tencilRepo = ${scriptString(build.repo)};
98
+ script.dataset.tencilBranch = ${scriptString(build.branch)};
99
+ script.dataset.tencilSha = ${scriptString(build.sha)};
100
+ document.head.appendChild(script);
101
+ })();`;
102
+ }
103
+ //#endregion
104
+ export { cloudLoader as n, resolveCloudBuild as r, DEFAULT_CLOUD_URL as t };