@lincolness/ponte 0.0.0-stage → 0.1.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.
@@ -0,0 +1,88 @@
1
+ // Área de transferência e "abrir pasta", em macOS, Windows e Linux.
2
+
3
+ import { execFile, spawn } from "node:child_process";
4
+ import { promises as fs } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+
8
+ function run(cmd: string, args: string[], input?: string): Promise<string> {
9
+ return new Promise((resolve, reject) => {
10
+ const child = spawn(cmd, args, { windowsHide: true });
11
+ let out = "";
12
+ let err = "";
13
+ child.stdout.setEncoding("utf8");
14
+ child.stdout.on("data", (d) => (out += d));
15
+ child.stderr.on("data", (d) => (err += d));
16
+ child.on("error", reject);
17
+ child.on("close", (code) => (code === 0 ? resolve(out) : reject(new Error(err || `${cmd} saiu com ${code}`))));
18
+ if (input !== undefined) child.stdin.end(input, "utf8");
19
+ else child.stdin.end();
20
+ });
21
+ }
22
+
23
+ const PS = ["-NoProfile", "-NonInteractive", "-Command"];
24
+
25
+ function psQuote(s: string): string {
26
+ return `'${s.replace(/'/g, "''")}'`;
27
+ }
28
+
29
+ export async function copyText(text: string): Promise<void> {
30
+ switch (process.platform) {
31
+ case "darwin":
32
+ await run("pbcopy", [], text);
33
+ return;
34
+ case "win32": {
35
+ // via arquivo temporário: evita problemas de codificação do stdin do PowerShell 5
36
+ const tmp = path.join(os.tmpdir(), `ponte-${process.pid}-${Date.now()}.txt`);
37
+ await fs.writeFile(tmp, text, "utf8");
38
+ try {
39
+ await run("powershell", [...PS, `Get-Content -Raw -Encoding UTF8 -LiteralPath ${psQuote(tmp)} | Set-Clipboard`]);
40
+ } finally {
41
+ await fs.rm(tmp, { force: true });
42
+ }
43
+ return;
44
+ }
45
+ default:
46
+ try {
47
+ await run("wl-copy", [], text);
48
+ } catch {
49
+ await run("xclip", ["-selection", "clipboard"], text);
50
+ }
51
+ }
52
+ }
53
+
54
+ export async function readClipboard(): Promise<string> {
55
+ switch (process.platform) {
56
+ case "darwin":
57
+ return run("pbpaste", []);
58
+ case "win32":
59
+ return run("powershell", [...PS, "[Console]::OutputEncoding=[Text.Encoding]::UTF8; Get-Clipboard -Raw"]);
60
+ default:
61
+ try {
62
+ return await run("wl-paste", ["--no-newline"]);
63
+ } catch {
64
+ return run("xclip", ["-selection", "clipboard", "-o"]);
65
+ }
66
+ }
67
+ }
68
+
69
+ /** Copia os arquivos (não o texto) para colar como anexo com Ctrl+V / Cmd+V. */
70
+ export async function copyFiles(absPaths: string[]): Promise<void> {
71
+ switch (process.platform) {
72
+ case "win32":
73
+ await run("powershell", [...PS, `Set-Clipboard -LiteralPath ${absPaths.map(psQuote).join(",")}`]);
74
+ return;
75
+ case "darwin": {
76
+ const list = absPaths.map((p) => `POSIX file ${JSON.stringify(p)}`).join(", ");
77
+ await run("osascript", ["-e", `set the clipboard to {${list}}`]);
78
+ return;
79
+ }
80
+ default:
81
+ throw new Error("copiar arquivos para a área de transferência não é suportado neste sistema");
82
+ }
83
+ }
84
+
85
+ export function openFolder(absDir: string): void {
86
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
87
+ execFile(cmd, [absDir], { windowsHide: true }, () => {});
88
+ }
package/src/files.ts ADDED
@@ -0,0 +1,297 @@
1
+ // Listagem de arquivos do repositório, filtros (glob estilo .gitignore) e leitura de texto.
2
+ // Sem dependência do pi, para poder ser testado com `node --test`.
3
+
4
+ import { execFile } from "node:child_process";
5
+ import { promises as fs } from "node:fs";
6
+ import path from "node:path";
7
+
8
+ export interface PonteConfig {
9
+ /** Padrões extras a excluir (mesma sintaxe do .gitignore, sem negação). */
10
+ exclude: string[];
11
+ /** Se preenchido, só entram arquivos que casem com algum destes padrões. */
12
+ include: string[];
13
+ /** Arquivos maiores que isso ficam de fora do pacote (KB). */
14
+ maxFileKB: number;
15
+ /** Divide o pacote em partes de até este tamanho (KB). 0 = arquivo único. */
16
+ maxPartKB: number;
17
+ /** Pasta de saída, relativa à raiz do repositório. */
18
+ outDir: string;
19
+ /** Extensão dos arquivos gerados (txt é aceito em qualquer upload). */
20
+ ext: string;
21
+ }
22
+
23
+ export const DEFAULT_CONFIG: PonteConfig = {
24
+ exclude: [],
25
+ include: [],
26
+ maxFileKB: 256,
27
+ maxPartKB: 0,
28
+ outDir: ".pi/ponte",
29
+ ext: "txt",
30
+ };
31
+
32
+ export const CONFIG_FILE = ".pi/ponte.json";
33
+
34
+ /**
35
+ * Pastas de build e dependências. Só se aplicam quando a pasta não é um repositório git;
36
+ * num repositório git o .gitignore já cuida disso, e o que estiver versionado entra.
37
+ */
38
+ export const BUILD_EXCLUDES = [
39
+ "node_modules/",
40
+ ".venv/",
41
+ "venv/",
42
+ "env/",
43
+ "__pycache__/",
44
+ ".mypy_cache/",
45
+ ".pytest_cache/",
46
+ ".ruff_cache/",
47
+ ".ipynb_checkpoints/",
48
+ ".tox/",
49
+ "dist/",
50
+ "build/",
51
+ "target/",
52
+ "bin/",
53
+ "obj/",
54
+ ".next/",
55
+ ".nuxt/",
56
+ "coverage/",
57
+ ".idea/",
58
+ ".vs/",
59
+ ".gradle/",
60
+ ];
61
+
62
+ /** Sempre excluídos: metadados, lixo gerado, lockfiles e segredos (nada disso deve ir para o chat). */
63
+ export const DEFAULT_EXCLUDES = [
64
+ ".git/",
65
+ ".pi/",
66
+ ".claude/",
67
+ "*.pyc",
68
+ "*.class",
69
+ "*.min.js",
70
+ "*.min.css",
71
+ "*.map",
72
+ ".DS_Store",
73
+ "Thumbs.db",
74
+ // lockfiles: enormes e inúteis para o modelo
75
+ "package-lock.json",
76
+ "yarn.lock",
77
+ "pnpm-lock.yaml",
78
+ "bun.lockb",
79
+ "uv.lock",
80
+ "poetry.lock",
81
+ "Pipfile.lock",
82
+ "Cargo.lock",
83
+ "Gemfile.lock",
84
+ "composer.lock",
85
+ "packages.lock.json",
86
+ // segredos
87
+ ".env",
88
+ ".env.*",
89
+ "*.pem",
90
+ "*.key",
91
+ "*.pfx",
92
+ "*.p12",
93
+ "id_rsa*",
94
+ "id_ed25519*",
95
+ ".npmrc",
96
+ ".pypirc",
97
+ ".netrc",
98
+ "secrets.*",
99
+ "*.secret*",
100
+ ];
101
+
102
+ /** Arquivos que casam com os padrões de segredo, mas que são exemplos seguros. */
103
+ const ALWAYS_ALLOW = [/(^|\/)\.env\.(example|sample|template)$/];
104
+
105
+ export async function loadConfig(root: string): Promise<PonteConfig> {
106
+ try {
107
+ const raw = await fs.readFile(path.join(root, CONFIG_FILE), "utf8");
108
+ const parsed = JSON.parse(raw) as Partial<PonteConfig>;
109
+ return { ...DEFAULT_CONFIG, ...parsed };
110
+ } catch {
111
+ return { ...DEFAULT_CONFIG };
112
+ }
113
+ }
114
+
115
+ /** Ordem por código de caractere: estável entre sistemas e mantém cada pasta contígua. */
116
+ export function byPath(a: string, b: string): number {
117
+ return a < b ? -1 : a > b ? 1 : 0;
118
+ }
119
+
120
+ export function toPosix(p: string): string {
121
+ return p.replace(/\\/g, "/");
122
+ }
123
+
124
+ export function globToRegExp(glob: string): RegExp {
125
+ let re = "";
126
+ for (let i = 0; i < glob.length; i++) {
127
+ const c = glob[i];
128
+ if (c === "*") {
129
+ if (glob[i + 1] === "*") {
130
+ // "**/" casa zero ou mais diretórios; "**" sozinho casa qualquer coisa
131
+ if (glob[i + 2] === "/") {
132
+ re += "(?:.*/)?";
133
+ i += 2;
134
+ } else {
135
+ re += ".*";
136
+ i += 1;
137
+ }
138
+ } else {
139
+ re += "[^/]*";
140
+ }
141
+ } else if (c === "?") {
142
+ re += "[^/]";
143
+ } else if ("\\^$+.()|{}[]".includes(c)) {
144
+ re += "\\" + c;
145
+ } else {
146
+ re += c;
147
+ }
148
+ }
149
+ return new RegExp("^" + re + "$");
150
+ }
151
+
152
+ interface CompiledPattern {
153
+ re: RegExp;
154
+ anchored: boolean;
155
+ dirOnly: boolean;
156
+ }
157
+
158
+ function compile(pattern: string): CompiledPattern | null {
159
+ let p = toPosix(pattern.trim());
160
+ if (!p || p.startsWith("#") || p.startsWith("!")) return null;
161
+ const dirOnly = p.endsWith("/");
162
+ if (dirOnly) p = p.replace(/\/+$/, "");
163
+ if (p.startsWith("./")) p = p.slice(2);
164
+ const anchored = p.includes("/");
165
+ if (p.startsWith("/")) p = p.slice(1);
166
+ if (!p) return null;
167
+ return { re: globToRegExp(p), anchored, dirOnly };
168
+ }
169
+
170
+ export type Matcher = (rel: string, isDir?: boolean) => boolean;
171
+
172
+ /**
173
+ * Semântica próxima do .gitignore:
174
+ * - padrão sem "/" casa com qualquer componente do caminho ("node_modules", "*.py");
175
+ * - padrão com "/" é ancorado na raiz ("src/legacy", "docs/*.md");
176
+ * - "/" no fim só casa diretórios;
177
+ * - casar um diretório inclui tudo que está dentro dele.
178
+ */
179
+ export function makeMatcher(patterns: string[]): Matcher {
180
+ const compiled = patterns.map(compile).filter((c): c is CompiledPattern => c !== null);
181
+ return (rel: string, isDir = false) => {
182
+ const parts = toPosix(rel).split("/").filter(Boolean);
183
+ for (const c of compiled) {
184
+ for (let i = 0; i < parts.length; i++) {
185
+ const segIsDir = i < parts.length - 1 || isDir;
186
+ if (c.dirOnly && !segIsDir) continue;
187
+ const subject = c.anchored ? parts.slice(0, i + 1).join("/") : parts[i];
188
+ if (c.re.test(subject)) return true;
189
+ }
190
+ }
191
+ return false;
192
+ };
193
+ }
194
+
195
+ function run(cmd: string, args: string[], cwd: string): Promise<string> {
196
+ return new Promise((resolve, reject) => {
197
+ execFile(cmd, args, { cwd, maxBuffer: 256 * 1024 * 1024, windowsHide: true }, (err, stdout) => {
198
+ if (err) reject(err);
199
+ else resolve(stdout);
200
+ });
201
+ });
202
+ }
203
+
204
+ async function gitFiles(root: string): Promise<string[] | null> {
205
+ try {
206
+ const out = await run("git", ["ls-files", "-co", "--exclude-standard", "-z"], root);
207
+ return out.split("\0").filter(Boolean).map(toPosix);
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+
213
+ async function readGitignore(root: string): Promise<string[]> {
214
+ try {
215
+ return (await fs.readFile(path.join(root, ".gitignore"), "utf8")).split(/\r?\n/);
216
+ } catch {
217
+ return [];
218
+ }
219
+ }
220
+
221
+ async function walk(root: string, ignored: Matcher): Promise<string[]> {
222
+ const out: string[] = [];
223
+ async function visit(relDir: string) {
224
+ let entries;
225
+ try {
226
+ entries = await fs.readdir(path.join(root, relDir), { withFileTypes: true });
227
+ } catch {
228
+ return;
229
+ }
230
+ for (const e of entries) {
231
+ const rel = relDir ? `${relDir}/${e.name}` : e.name;
232
+ if (e.isDirectory()) {
233
+ if (!ignored(rel, true)) await visit(rel);
234
+ } else if (e.isFile()) {
235
+ if (!ignored(rel) || ALWAYS_ALLOW.some((re) => re.test(rel))) out.push(rel);
236
+ }
237
+ }
238
+ }
239
+ await visit("");
240
+ return out;
241
+ }
242
+
243
+ export interface ListOptions {
244
+ /** Filtros pedidos na hora (ex.: `/ponte pack src tests/*.py`). */
245
+ only?: string[];
246
+ }
247
+
248
+ export async function listFiles(root: string, cfg: PonteConfig, opts: ListOptions = {}): Promise<string[]> {
249
+ const outDir = toPosix(cfg.outDir).replace(/^\.\//, "").replace(/\/+$/, "");
250
+ const baseExcludes = [...DEFAULT_EXCLUDES, ...cfg.exclude, `/${outDir}/`];
251
+ let files = await gitFiles(root);
252
+ let ignored: Matcher;
253
+ if (files) {
254
+ ignored = makeMatcher(baseExcludes);
255
+ } else {
256
+ ignored = makeMatcher([...baseExcludes, ...BUILD_EXCLUDES, ...(await readGitignore(root))]);
257
+ files = await walk(root, ignored);
258
+ }
259
+ const include = [...cfg.include, ...(opts.only ?? [])];
260
+ const included = include.length ? makeMatcher(include) : null;
261
+ const result = files.filter((f) => {
262
+ if (ALWAYS_ALLOW.some((re) => re.test(f))) return included ? included(f) : true;
263
+ if (ignored(f)) return false;
264
+ return included ? included(f) : true;
265
+ });
266
+ return [...new Set(result)].sort(byPath);
267
+ }
268
+
269
+ export type TextRead =
270
+ | { ok: true; text: string; eol: "\n" | "\r\n"; bom: boolean }
271
+ | { ok: false; reason: string };
272
+
273
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); // ignoreBOM: mantém o BOM no texto para sabermos que existia
274
+
275
+ /** Lê um arquivo como UTF-8, devolvendo o texto com quebras de linha normalizadas para \n. */
276
+ export async function readText(abs: string, maxBytes = Infinity): Promise<TextRead> {
277
+ let buf: Buffer;
278
+ try {
279
+ const st = await fs.stat(abs);
280
+ if (!st.isFile()) return { ok: false, reason: "não é arquivo" };
281
+ if (st.size > maxBytes) return { ok: false, reason: `grande demais (${Math.round(st.size / 1024)} KB)` };
282
+ buf = await fs.readFile(abs);
283
+ } catch {
284
+ return { ok: false, reason: "não encontrado" };
285
+ }
286
+ if (buf.subarray(0, 8000).includes(0)) return { ok: false, reason: "binário" };
287
+ let text: string;
288
+ try {
289
+ text = decoder.decode(buf);
290
+ } catch {
291
+ return { ok: false, reason: "não está em UTF-8" };
292
+ }
293
+ const bom = text.charCodeAt(0) === 0xfeff;
294
+ if (bom) text = text.slice(1);
295
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
296
+ return { ok: true, text: text.replace(/\r\n/g, "\n"), eol, bom };
297
+ }