scrapo 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.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # scrapo
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Convert any GitHub repository into a single AI-ready text file, right from your terminal. No install required — just `npx` it.
4
+
5
+ ```bash
6
+ npx scrapo
7
+ ```
8
+
9
+ You'll be asked for:
10
+ 1. **A GitHub repository URL** (public or private)
11
+ 2. **An optional Personal Access Token** — skip with Enter, or provide one to raise the GitHub API rate limit from 60 to 5,000 requests/hour (and to access private repos)
12
+ 3. **Which branch** to convert (defaults to the repository's default branch)
13
+
14
+ Scrapo then fetches the repo, filters out binaries/lockfiles/build output/dependency folders automatically, and saves a single `{repo-name}.txt` file in your current directory — ready to paste into ChatGPT, Claude, Gemini, or any other LLM.
15
+
16
+ ## Why
17
+
18
+ Premium AI models offer a "paste a GitHub URL, get the whole codebase as context" feature — usually locked behind a paid tier. Scrapo replicates that for free, both as a [web app](https://scrapogithubtool.vercel.app/) and now as this CLI for terminal-first workflows (CI pipelines, scripts, or just preferring not to open a browser).
19
+
20
+ ## What gets filtered out automatically
21
+
22
+ - Dependency folders: `node_modules`, `vendor`, `.venv`, `venv`
23
+ - Build/cache output: `dist`, `build`, `.next`, `out`, `.cache`, `__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache`
24
+ - Binary/media files: images, fonts, audio/video, archives
25
+ - ML/data files: `.joblib`, `.pkl`, `.pt`, `.onnx`, `.sqlite`, `.parquet`, etc.
26
+ - Lockfiles and minified files: `package-lock.json`, `yarn.lock`, `.min.js`, `.min.css`
27
+
28
+ Same filtering rules as the [Scrapo web app](https://github.com/trivedikavya/Repotext), so output is consistent between both.
29
+
30
+ ## Requirements
31
+
32
+ Node.js 18 or higher.
33
+
34
+ ## License
35
+
36
+ Apache-2.0
package/bin/scrapo.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../dist/index.js';
package/dist/github.js ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * GitHub API client for the Scrapo CLI - a trimmed-down port of the web
3
+ * app's `src/lib/github.ts`. Deliberately duplicated here rather than
4
+ * shared via a workspace package for now: this only uses Web-standard APIs
5
+ * (`fetch`, `AbortController`, `atob`, `TextDecoder`) that are native in
6
+ * Node.js 18+, so the logic ports over almost unchanged. If the CLI gains
7
+ * real traction and the two copies drift, that's the point to extract a
8
+ * shared package - not before.
9
+ */
10
+ export function parseGithubUrl(url) {
11
+ const match = url.match(/github\.com\/([^/]+)\/([^/\s?#]+)/);
12
+ if (!match)
13
+ return null;
14
+ const owner = match[1];
15
+ const repo = match[2].replace(/\.git$/, '');
16
+ return { owner, repo };
17
+ }
18
+ const TREE_TIMEOUT_MS = 20_000;
19
+ const FILE_TIMEOUT_MS = 15_000;
20
+ let lastRateLimitInfo = null;
21
+ export function getLastRateLimitInfo() {
22
+ return lastRateLimitInfo;
23
+ }
24
+ function buildHeaders(token) {
25
+ const headers = { Accept: 'application/vnd.github+json' };
26
+ if (token)
27
+ headers.Authorization = `Bearer ${token}`;
28
+ return headers;
29
+ }
30
+ function updateRateLimitInfo(response) {
31
+ const limit = response.headers.get('x-ratelimit-limit');
32
+ const remaining = response.headers.get('x-ratelimit-remaining');
33
+ const reset = response.headers.get('x-ratelimit-reset');
34
+ if (limit !== null && remaining !== null && reset !== null) {
35
+ lastRateLimitInfo = { limit: Number(limit), remaining: Number(remaining), reset: Number(reset) };
36
+ }
37
+ }
38
+ async function fetchWithTimeout(url, options, timeoutMs, signal) {
39
+ if (signal?.aborted)
40
+ throw new DOMException('The operation was aborted.', 'AbortError');
41
+ const controller = new AbortController();
42
+ let timedOut = false;
43
+ const timeoutId = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
44
+ const onExternalAbort = () => controller.abort();
45
+ signal?.addEventListener('abort', onExternalAbort, { once: true });
46
+ try {
47
+ return await fetch(url, { ...options, signal: controller.signal });
48
+ }
49
+ catch (error) {
50
+ if (timedOut)
51
+ throw new Error('The GitHub API took too long to respond. Please try again.', { cause: error });
52
+ throw error;
53
+ }
54
+ finally {
55
+ clearTimeout(timeoutId);
56
+ signal?.removeEventListener('abort', onExternalAbort);
57
+ }
58
+ }
59
+ export class GithubRateLimitError extends Error {
60
+ }
61
+ function isRateLimitResponse(response) {
62
+ return response.status === 403 && response.headers.get('x-ratelimit-remaining') === '0';
63
+ }
64
+ function buildErrorMessage(response, errorData, hasToken) {
65
+ if (response.status === 401)
66
+ return 'Invalid or expired GitHub token.';
67
+ if (response.status === 403) {
68
+ if (response.headers.get('x-ratelimit-remaining') === '0') {
69
+ return hasToken
70
+ ? 'GitHub API rate limit exceeded. Please try again later.'
71
+ : 'GitHub API rate limit exceeded. Re-run with --token (or enter a token when prompted) for 5,000 requests/hour instead of 60.';
72
+ }
73
+ return 'Access forbidden. Your token may not have permission to read this repository.';
74
+ }
75
+ if (response.status === 404) {
76
+ return hasToken
77
+ ? 'Repository not found. Double-check the URL and that your token has access to it.'
78
+ : 'Repository not found. If it is private, provide a Personal Access Token.';
79
+ }
80
+ return errorData.message || response.statusText || `Request failed with status ${response.status}.`;
81
+ }
82
+ export async function getRepoMeta(owner, repo, token, signal) {
83
+ try {
84
+ const response = await fetchWithTimeout(`https://api.github.com/repos/${owner}/${repo}`, { headers: buildHeaders(token) }, TREE_TIMEOUT_MS, signal);
85
+ if (!response.ok)
86
+ return null;
87
+ const data = (await response.json());
88
+ return { defaultBranch: data.default_branch, isEmpty: data.size === 0 };
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ }
94
+ export async function fetchFileTree(owner, repo, token, signal, ref = 'HEAD') {
95
+ const headers = buildHeaders(token);
96
+ const requestTree = (r) => fetchWithTimeout(`https://api.github.com/repos/${owner}/${repo}/git/trees/${r}?recursive=1`, { headers }, TREE_TIMEOUT_MS, signal);
97
+ let response = await requestTree(ref);
98
+ if (!response.ok && response.status === 404) {
99
+ const meta = await getRepoMeta(owner, repo, token, signal);
100
+ if (meta?.isEmpty)
101
+ throw new Error('This repository appears to be empty (no commits yet).');
102
+ if (ref === 'HEAD' && meta?.defaultBranch) {
103
+ response = await requestTree(meta.defaultBranch);
104
+ }
105
+ else if (ref !== 'HEAD') {
106
+ throw new Error(`Branch "${ref}" was not found in this repository.`);
107
+ }
108
+ }
109
+ updateRateLimitInfo(response);
110
+ if (!response.ok) {
111
+ const errorData = (await response.json().catch(() => ({})));
112
+ const message = buildErrorMessage(response, errorData, !!token);
113
+ throw isRateLimitResponse(response) ? new GithubRateLimitError(message) : new Error(message);
114
+ }
115
+ const data = (await response.json());
116
+ const tree = data.tree || [];
117
+ return tree.filter(file => file.type === 'blob' && shouldIncludeFile(file));
118
+ }
119
+ export async function fetchBranches(owner, repo, token, signal) {
120
+ const response = await fetchWithTimeout(`https://api.github.com/repos/${owner}/${repo}/branches?per_page=100`, { headers: buildHeaders(token) }, TREE_TIMEOUT_MS, signal);
121
+ updateRateLimitInfo(response);
122
+ if (!response.ok) {
123
+ const errorData = (await response.json().catch(() => ({})));
124
+ const message = buildErrorMessage(response, errorData, !!token);
125
+ throw isRateLimitResponse(response) ? new GithubRateLimitError(message) : new Error(message);
126
+ }
127
+ const data = (await response.json());
128
+ return data.map(b => ({ name: b.name }));
129
+ }
130
+ // Same exclusion rules as the web app - keeps CLI and web output consistent.
131
+ const SKIP_EXT = /\.(png|jpg|jpeg|gif|ico|svg|webp|bmp|tiff|woff|woff2|ttf|eot|mp4|mp3|wav|avi|pdf|zip|gz|tar|7z|lock|min\.js|min\.css|pyc|class|o|exe|dll|so|joblib|pkl|pt|pth|h5|onnx|sqlite|sqlite3|db|parquet|bin|dat)$/i;
132
+ const SKIP_DIRS = [
133
+ 'node_modules', 'dist', 'build', '.git', 'coverage', '__pycache__', '.next',
134
+ 'out', '.cache', 'vendor', '.venv', 'venv', '.pytest_cache', '.mypy_cache', '.ruff_cache',
135
+ ];
136
+ export function shouldIncludeFile(file) {
137
+ if (SKIP_EXT.test(file.path))
138
+ return false;
139
+ return !file.path.split('/').some(segment => SKIP_DIRS.includes(segment));
140
+ }
141
+ export async function fetchFileContent(owner, repo, path, token, signal) {
142
+ const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`;
143
+ try {
144
+ const response = await fetchWithTimeout(url, { headers: buildHeaders(token) }, FILE_TIMEOUT_MS, signal);
145
+ if (!response.ok)
146
+ return null;
147
+ const data = (await response.json());
148
+ if (!data.content)
149
+ return null;
150
+ return decodeBase64Utf8(data.content);
151
+ }
152
+ catch (error) {
153
+ if (signal?.aborted)
154
+ throw error;
155
+ return null;
156
+ }
157
+ }
158
+ export function decodeBase64Utf8(base64) {
159
+ const cleanBase64 = base64.replace(/\n/g, '');
160
+ const binaryString = atob(cleanBase64);
161
+ const bytes = new Uint8Array(binaryString.length);
162
+ for (let i = 0; i < binaryString.length; i++)
163
+ bytes[i] = binaryString.charCodeAt(i);
164
+ return new TextDecoder('utf-8').decode(bytes);
165
+ }
package/dist/index.js ADDED
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ import { intro, outro, text, password, select, spinner, cancel, isCancel, log } from '@clack/prompts';
3
+ import { writeFile } from 'node:fs/promises';
4
+ import { resolve } from 'node:path';
5
+ import { parseGithubUrl, fetchFileTree, fetchFileContent, fetchBranches, getRepoMeta, getLastRateLimitInfo, GithubRateLimitError, } from './github.js';
6
+ /** Exits cleanly if the user cancelled a prompt (Ctrl+C / Esc). */
7
+ function bailIfCancelled(value) {
8
+ if (isCancel(value)) {
9
+ cancel('Operation cancelled.');
10
+ process.exit(0);
11
+ }
12
+ }
13
+ async function main() {
14
+ intro('scrapo — convert a GitHub repo into an AI-ready text file');
15
+ const urlInput = await text({
16
+ message: 'GitHub repository URL:',
17
+ placeholder: 'https://github.com/owner/repo',
18
+ validate: (value) => {
19
+ if (!value)
20
+ return 'A URL is required.';
21
+ if (!parseGithubUrl(value))
22
+ return "That doesn't look like a valid GitHub repository URL.";
23
+ },
24
+ });
25
+ bailIfCancelled(urlInput);
26
+ const repoInfo = parseGithubUrl(urlInput);
27
+ if (!repoInfo) {
28
+ log.error('Invalid GitHub URL.');
29
+ process.exit(1);
30
+ }
31
+ const tokenInput = await password({
32
+ message: 'GitHub Personal Access Token (optional, raises rate limit 60 -> 5,000/hour - Enter to skip):',
33
+ });
34
+ bailIfCancelled(tokenInput);
35
+ const token = tokenInput.trim() ? tokenInput.trim() : undefined;
36
+ // ── Branch discovery ──────────────────────────────────────────────────
37
+ const branchSpin = spinner();
38
+ branchSpin.start('Looking up branches...');
39
+ let branches = [];
40
+ let defaultBranch;
41
+ try {
42
+ const [branchList, meta] = await Promise.all([
43
+ fetchBranches(repoInfo.owner, repoInfo.repo, token),
44
+ getRepoMeta(repoInfo.owner, repoInfo.repo, token),
45
+ ]);
46
+ branches = branchList;
47
+ defaultBranch = meta?.defaultBranch;
48
+ branchSpin.stop(`Found ${branches.length} branch${branches.length === 1 ? '' : 'es'}.`);
49
+ }
50
+ catch {
51
+ branchSpin.stop("Couldn't list branches - continuing with the repository's default branch.");
52
+ }
53
+ let selectedBranch = defaultBranch ?? 'HEAD';
54
+ if (branches.length > 0) {
55
+ const preselected = defaultBranch && branches.some(b => b.name === defaultBranch) ? defaultBranch : branches[0].name;
56
+ const branchChoice = await select({
57
+ message: 'Which branch?',
58
+ options: branches.map(b => ({
59
+ value: b.name,
60
+ label: b.name === defaultBranch ? `${b.name} (default)` : b.name,
61
+ })),
62
+ initialValue: preselected,
63
+ });
64
+ bailIfCancelled(branchChoice);
65
+ selectedBranch = branchChoice;
66
+ }
67
+ // ── Fetch + build output ──────────────────────────────────────────────
68
+ const fetchSpin = spinner();
69
+ fetchSpin.start('Fetching file tree...');
70
+ let files;
71
+ try {
72
+ files = await fetchFileTree(repoInfo.owner, repoInfo.repo, token, undefined, selectedBranch);
73
+ }
74
+ catch (err) {
75
+ fetchSpin.stop('Failed to fetch repository.');
76
+ if (err instanceof GithubRateLimitError) {
77
+ log.error(err.message);
78
+ }
79
+ else {
80
+ log.error(err instanceof Error ? err.message : 'Unknown error.');
81
+ }
82
+ process.exit(1);
83
+ }
84
+ if (files.length === 0) {
85
+ fetchSpin.stop('No matching files found.');
86
+ log.warn('Every file in this repository was excluded by the smart filtering rules (binaries, lockfiles, build output, etc.) - nothing to save.');
87
+ process.exit(0);
88
+ }
89
+ let combinedText = `${repoInfo.repo}\n`;
90
+ for (let i = 0; i < files.length; i++) {
91
+ const file = files[i];
92
+ fetchSpin.message(`${i + 1}/${files.length} — ${file.path}`);
93
+ const content = await fetchFileContent(repoInfo.owner, repoInfo.repo, file.path, token);
94
+ if (content !== null) {
95
+ combinedText += `\n${file.path}\n`;
96
+ combinedText += content.split('\n').map(l => ' ' + l).join('\n') + '\n';
97
+ }
98
+ }
99
+ fetchSpin.stop(`Fetched ${files.length} files.`);
100
+ const rateLimit = getLastRateLimitInfo();
101
+ if (rateLimit && rateLimit.remaining <= 5) {
102
+ log.warn(`Heads up: only ${rateLimit.remaining}/${rateLimit.limit} GitHub API requests remaining this hour.`);
103
+ }
104
+ const outputPath = resolve(process.cwd(), `${repoInfo.repo}.txt`);
105
+ await writeFile(outputPath, combinedText, 'utf-8');
106
+ outro(`Saved to ${outputPath}`);
107
+ }
108
+ main().catch((err) => {
109
+ log.error(err instanceof Error ? err.message : 'Unexpected error.');
110
+ process.exit(1);
111
+ });
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "scrapo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Convert any GitHub repository into a single AI-ready text file, right from your terminal.",
5
+ "type": "module",
6
+ "bin": {
7
+ "scrapo": "./bin/scrapo.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "dist"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "license": "Apache-2.0",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/trivedikavya/Repotext.git",
20
+ "directory": "cli"
21
+ },
22
+ "keywords": [
23
+ "github",
24
+ "cli",
25
+ "ai",
26
+ "llm",
27
+ "repo-to-text",
28
+ "context"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.json",
32
+ "dev": "tsx src/index.ts"
33
+ },
34
+ "dependencies": {
35
+ "@clack/prompts": "^1.9.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^24.12.3",
39
+ "tsx": "^4.23.15",
40
+ "typescript": "~6.0.2"
41
+ }
42
+ }