promptlike 0.9.0 → 0.10.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/CHANGELOG.md +94 -0
- package/README.md +241 -27
- package/dist/commands/config.js +13 -0
- package/dist/commands/copy.js +10 -3
- package/dist/commands/get.js +11 -2
- package/dist/commands/import.js +30 -128
- package/dist/commands/importCheck.js +304 -0
- package/dist/commands/importGithub.js +171 -0
- package/dist/commands/list.js +83 -17
- package/dist/commands/local.js +31 -9
- package/dist/commands/login.js +6 -5
- package/dist/commands/search.js +73 -7
- package/dist/commands/show.js +11 -3
- package/dist/commands/sync.js +57 -13
- package/dist/index.js +7 -0
- package/dist/lib/errors.js +4 -0
- package/dist/lib/format.js +28 -0
- package/dist/lib/frontmatter.js +86 -4
- package/dist/lib/github.js +208 -0
- package/dist/lib/githubCache.js +118 -0
- package/dist/lib/githubHttp.js +197 -0
- package/dist/lib/githubImport.js +238 -0
- package/dist/lib/githubSelect.js +148 -0
- package/dist/lib/githubSnapshot.js +67 -0
- package/dist/lib/githubSpec.js +78 -0
- package/dist/lib/importOrigins.js +36 -0
- package/dist/lib/importShared.js +179 -0
- package/dist/lib/licenses.js +243 -0
- package/dist/lib/localStore.js +49 -0
- package/dist/lib/loopApi.js +63 -11
- package/dist/lib/promptResolver.js +22 -9
- package/dist/lib/promptSource.js +123 -0
- package/dist/lib/rank.js +30 -13
- package/dist/lib/settings.js +24 -3
- package/dist/lib/tagFilter.js +40 -0
- package/dist/lib/updateCheck.js +296 -0
- package/dist/lib/upstreamCheck.js +71 -0
- package/dist/program.js +26 -7
- package/package.json +1 -1
package/dist/commands/sync.js
CHANGED
|
@@ -10,6 +10,16 @@
|
|
|
10
10
|
* One-way (local → account) on purpose. Pulling the account library down would
|
|
11
11
|
* need conflict rules the local store cannot express (the local history is
|
|
12
12
|
* a private, append-only log, not a mergeable one) and a half-correct merge silently losing an edit is worse than no pull.
|
|
13
|
+
*
|
|
14
|
+
* Re-running is safe: every prompt travels with the sha256 of its text, and the
|
|
15
|
+
* server skips text that is already in the account. A prompt edited since is a
|
|
16
|
+
* different text, so it is uploaded as a NEW prompt — sync copies, it never updates.
|
|
17
|
+
* A prompt that came from GitHub also carries where from (see lib/githubImport.ts),
|
|
18
|
+
* so `ple import --check` can follow it in the account.
|
|
19
|
+
*
|
|
20
|
+
* `--project <repo>` uploads into that repo (name, slug, id or short id — the same
|
|
21
|
+
* resolution as `ple import`); without it the prompts land in the default repo, or
|
|
22
|
+
* in the user's only repo when the plan cannot create another one.
|
|
13
23
|
*/
|
|
14
24
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
15
25
|
if (k2 === undefined) k2 = k;
|
|
@@ -50,11 +60,37 @@ const store = __importStar(require("../lib/localStore"));
|
|
|
50
60
|
const history = __importStar(require("../lib/localHistory"));
|
|
51
61
|
const api_client_1 = require("../lib/api-client");
|
|
52
62
|
const format_1 = require("../lib/format");
|
|
63
|
+
const githubImport_1 = require("../lib/githubImport");
|
|
53
64
|
const libraryCache_1 = require("../lib/libraryCache");
|
|
65
|
+
const promptResolver_1 = require("../lib/promptResolver");
|
|
66
|
+
const scanners_1 = require("../lib/scanners");
|
|
54
67
|
/** The import endpoint caps one request at 50 records. */
|
|
55
68
|
const BATCH = 50;
|
|
69
|
+
/** The `--project` value as it would be typed again: quoted when a shell would split or expand it. */
|
|
70
|
+
function typed(value) {
|
|
71
|
+
const v = (0, format_1.safeText)(value);
|
|
72
|
+
return /^[\w.@:/+-]+$/.test(v) ? v : `"${v.replace(/(["\\$`])/g, '\\$1')}"`;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Every prompt carries where it is from, so the server can tell what it already
|
|
76
|
+
* has: the sha256 of the text, and — for a GitHub import — the source and license.
|
|
77
|
+
*/
|
|
78
|
+
function toImportable(p) {
|
|
79
|
+
const sha256 = (0, scanners_1.hashBody)(p.body);
|
|
80
|
+
return {
|
|
81
|
+
title: p.title,
|
|
82
|
+
description: p.description,
|
|
83
|
+
content: p.body,
|
|
84
|
+
tags: p.tags,
|
|
85
|
+
origin: p.upstream
|
|
86
|
+
? (0, githubImport_1.originFromUpstream)(p.upstream, sha256)
|
|
87
|
+
: { tool: 'other', kind: 'prompt', path: `local:${p.slug}`, sha256 },
|
|
88
|
+
};
|
|
89
|
+
}
|
|
56
90
|
async function syncCommand(options = {}) {
|
|
57
91
|
const local = store.list().filter((p) => p.body.trim());
|
|
92
|
+
/** What to run again: the same repo, not the default one. */
|
|
93
|
+
const again = `ple sync${options.project ? ` --project ${typed(options.project)}` : ''}`;
|
|
58
94
|
if (local.length === 0) {
|
|
59
95
|
console.log(format_1.c.muted('Nothing to sync — the local store is empty.'));
|
|
60
96
|
console.log(format_1.c.muted(' ple save "code review" -m "Review this diff: {{diff}}"'));
|
|
@@ -64,17 +100,18 @@ async function syncCommand(options = {}) {
|
|
|
64
100
|
console.log(format_1.c.label(`${local.length} local prompt${local.length === 1 ? '' : 's'} would be uploaded:`));
|
|
65
101
|
for (const p of local)
|
|
66
102
|
console.log(format_1.c.muted(` ${p.slug} ${p.title}`));
|
|
67
|
-
|
|
103
|
+
// Offline on purpose: the repo is looked up (and a wrong name rejected) when you upload.
|
|
104
|
+
if (options.project)
|
|
105
|
+
console.log(format_1.c.muted(`→ repo ${(0, format_1.safeText)(options.project)} (checked when you upload)`));
|
|
106
|
+
console.log(format_1.c.muted(`\nRun \`${again}\` without --dry-run to upload.`));
|
|
68
107
|
return;
|
|
69
108
|
}
|
|
70
109
|
await (0, api_client_1.ensureAuthed)();
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
content: p.body,
|
|
75
|
-
tags: p.tags,
|
|
76
|
-
}));
|
|
110
|
+
// A wrong repo name stops here, before anything is uploaded.
|
|
111
|
+
const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
|
|
112
|
+
const payload = local.map(toImportable);
|
|
77
113
|
let imported = 0;
|
|
114
|
+
let skippedDuplicate = 0;
|
|
78
115
|
let failed = 0;
|
|
79
116
|
let skippedInvalid = 0;
|
|
80
117
|
let truncatedByQuota = 0;
|
|
@@ -86,8 +123,13 @@ async function syncCommand(options = {}) {
|
|
|
86
123
|
let abortMessage = null;
|
|
87
124
|
for (let i = 0; i < payload.length; i += BATCH) {
|
|
88
125
|
try {
|
|
89
|
-
const res = await (0, api_client_1.importPrompts)(payload.slice(i, i + BATCH)
|
|
126
|
+
const res = await (0, api_client_1.importPrompts)(payload.slice(i, i + BATCH), {
|
|
127
|
+
source: 'cli',
|
|
128
|
+
projectId,
|
|
129
|
+
fallbackToExistingProject: !projectId,
|
|
130
|
+
});
|
|
90
131
|
imported += res.imported;
|
|
132
|
+
skippedDuplicate += res.skippedDuplicate;
|
|
91
133
|
failed += res.failed;
|
|
92
134
|
skippedInvalid += res.skippedInvalid;
|
|
93
135
|
truncatedByQuota += res.truncatedByQuota;
|
|
@@ -107,6 +149,8 @@ async function syncCommand(options = {}) {
|
|
|
107
149
|
(0, libraryCache_1.startBackgroundRefresh)({ force: true });
|
|
108
150
|
const tagNote = serverCarriesTags && tagsApplied > 0 ? ` (+${tagsApplied} tag link${tagsApplied === 1 ? '' : 's'})` : '';
|
|
109
151
|
console.log(format_1.c.success(`✓ Uploaded ${imported} prompt${imported === 1 ? '' : 's'}${tagNote}`));
|
|
152
|
+
if (skippedDuplicate > 0)
|
|
153
|
+
console.log(format_1.c.muted(` ${skippedDuplicate} already in your account — skipped`));
|
|
110
154
|
// Each shortfall gets its own line with its own fix — "12 of 20 synced"
|
|
111
155
|
// with no reason is the kind of message that sends people to support.
|
|
112
156
|
if (abortMessage) {
|
|
@@ -114,13 +158,13 @@ async function syncCommand(options = {}) {
|
|
|
114
158
|
}
|
|
115
159
|
if (truncatedByQuota > 0) {
|
|
116
160
|
console.log(format_1.c.warn(`⚠ ${truncatedByQuota} not uploaded — plan prompt limit reached.`));
|
|
117
|
-
console.log(format_1.c.muted(
|
|
161
|
+
console.log(format_1.c.muted(` Upgrade for unlimited prompts, then run \`${again}\` again.`));
|
|
118
162
|
}
|
|
119
163
|
if (skippedInvalid > 0) {
|
|
120
164
|
console.log(format_1.c.warn(`⚠ ${skippedInvalid} skipped — missing a title or body.`));
|
|
121
165
|
}
|
|
122
166
|
if (failed > 0) {
|
|
123
|
-
console.log(format_1.c.warn(`⚠ ${failed} failed to import. Re-run \`
|
|
167
|
+
console.log(format_1.c.warn(`⚠ ${failed} failed to import. Re-run \`${again}\` to retry those.`));
|
|
124
168
|
}
|
|
125
169
|
// Tags travel since the server started answering with `tagsApplied`. An
|
|
126
170
|
// older deployment ignores the field silently — that is the one case where
|
|
@@ -128,9 +172,9 @@ async function syncCommand(options = {}) {
|
|
|
128
172
|
if (!serverCarriesTags && local.some((p) => p.tags.length > 0)) {
|
|
129
173
|
console.log(format_1.c.muted('Note: tags stayed local — this server does not carry them yet.'));
|
|
130
174
|
}
|
|
131
|
-
// Local files are NOT deleted: sync copies, it does not move.
|
|
132
|
-
//
|
|
175
|
+
// Local files are NOT deleted: sync copies, it does not move. Say what a
|
|
176
|
+
// re-run does, so nobody has to find out.
|
|
133
177
|
console.log(format_1.c.muted(`\nLocal files kept in ${store.promptsDir()} (sync copies, it does not move).`));
|
|
134
|
-
console.log(format_1.c.muted('Re-running
|
|
178
|
+
console.log(format_1.c.muted('Re-running is safe: text that is already in your account is skipped. A prompt you edited since is uploaded as a new prompt.'));
|
|
135
179
|
console.log(format_1.c.muted(`Only the current text of each prompt is uploaded; the local version history stays in ${history.historyRoot()}.`));
|
|
136
180
|
}
|
package/dist/index.js
CHANGED
|
@@ -5,8 +5,15 @@
|
|
|
5
5
|
*/
|
|
6
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
7
|
const program_1 = require("./program");
|
|
8
|
+
const updateCheck_1 = require("./lib/updateCheck");
|
|
8
9
|
(0, program_1.buildProgram)()
|
|
9
10
|
.parseAsync(process.argv)
|
|
11
|
+
.then(() => {
|
|
12
|
+
// Once per run, after the command succeeded: at most one stderr line a day about a newer version, and a
|
|
13
|
+
// detached background lookup when one is due. Never waits for the network, never throws, silent in
|
|
14
|
+
// pipes, CI and when switched off (see lib/updateCheck.ts).
|
|
15
|
+
(0, updateCheck_1.afterCommand)();
|
|
16
|
+
})
|
|
10
17
|
.catch((err) => {
|
|
11
18
|
// Commands handle their own errors; this only catches a bug in the wiring itself.
|
|
12
19
|
console.error(`✗ ${err instanceof Error ? err.message : String(err)}`);
|
package/dist/lib/errors.js
CHANGED
|
@@ -8,9 +8,13 @@ exports.exitCodeFor = exitCodeFor;
|
|
|
8
8
|
* 2 not your fault / try again: no network, timeout, rate limit, server error (5xx)
|
|
9
9
|
*/
|
|
10
10
|
const api_client_1 = require("./api-client");
|
|
11
|
+
const github_1 = require("./github");
|
|
11
12
|
function exitCodeFor(err) {
|
|
12
13
|
if (err instanceof api_client_1.NetworkError || err instanceof api_client_1.RequestTimeoutError)
|
|
13
14
|
return 2;
|
|
15
|
+
// GitHub: no network, timeout, rate limit, 5xx → try again; not found, empty, too large → fix the input.
|
|
16
|
+
if (err instanceof github_1.GithubError)
|
|
17
|
+
return err.retryable ? 2 : 1;
|
|
14
18
|
if (err instanceof api_client_1.ApiError && (err.status >= 500 || err.status === 429))
|
|
15
19
|
return 2;
|
|
16
20
|
return 1;
|
package/dist/lib/format.js
CHANGED
|
@@ -7,6 +7,7 @@ exports.c = void 0;
|
|
|
7
7
|
exports.timeAgo = timeAgo;
|
|
8
8
|
exports.shortId = shortId;
|
|
9
9
|
exports.truncate = truncate;
|
|
10
|
+
exports.formatTags = formatTags;
|
|
10
11
|
exports.joinPromptParts = joinPromptParts;
|
|
11
12
|
exports.safeText = safeText;
|
|
12
13
|
const chalk_1 = __importDefault(require("chalk"));
|
|
@@ -59,6 +60,33 @@ function truncate(str, max) {
|
|
|
59
60
|
return str;
|
|
60
61
|
return str.slice(0, max - 1) + '…';
|
|
61
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* Tag names for one table cell: every name cleaned with {@link safeText} (tag names come from
|
|
65
|
+
* the server, and from other people in shared repos, and are not cleaned by the API client),
|
|
66
|
+
* joined with ", " and kept within `max` characters. Whole tags are kept where they fit and the
|
|
67
|
+
* rest is counted ("debug, review +2"); a first tag too long for the cell is truncated.
|
|
68
|
+
*/
|
|
69
|
+
function formatTags(names, max = 24) {
|
|
70
|
+
const clean = names.map((n) => safeText(n).trim()).filter(Boolean);
|
|
71
|
+
if (clean.length === 0)
|
|
72
|
+
return '';
|
|
73
|
+
const all = clean.join(', ');
|
|
74
|
+
if (all.length <= max)
|
|
75
|
+
return all;
|
|
76
|
+
const shown = [];
|
|
77
|
+
for (let i = 0; i < clean.length; i++) {
|
|
78
|
+
const candidate = [...shown, clean[i]].join(', ');
|
|
79
|
+
const rest = clean.length - (i + 1);
|
|
80
|
+
if ((rest > 0 ? `${candidate} +${rest}` : candidate).length > max)
|
|
81
|
+
break;
|
|
82
|
+
shown.push(clean[i]);
|
|
83
|
+
}
|
|
84
|
+
if (shown.length === 0) {
|
|
85
|
+
const suffix = clean.length > 1 ? ` +${clean.length - 1}` : '';
|
|
86
|
+
return truncate(clean[0], Math.max(1, max - suffix.length)) + suffix;
|
|
87
|
+
}
|
|
88
|
+
return `${shown.join(', ')} +${clean.length - shown.length}`;
|
|
89
|
+
}
|
|
62
90
|
/** Üç parçalı içeriği (role/description/context) tek metne birleştir.
|
|
63
91
|
* Yapısal parçalardan yeniden kurar ve BOŞ bölümleri atlar → yalnız-description
|
|
64
92
|
* bir prompt'ta başıboş `---` ayraçları çıkmaz (E2E bulgusu F2). Stored `content`
|
package/dist/lib/frontmatter.js
CHANGED
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Minimal YAML-frontmatter reader for agent files (commands, SKILL.md,
|
|
4
4
|
* `.prompt.md`). Not a YAML parser — agent frontmatter is flat `key: value`
|
|
5
|
-
* lines plus the occasional list (`tags: [a, b]` or `- item` lines),
|
|
6
|
-
*
|
|
5
|
+
* lines plus the occasional list (`tags: [a, b]` or `- item` lines), a block
|
|
6
|
+
* scalar (`description: >` / `|`) and a one-level map (`metadata:` + indented
|
|
7
|
+
* `author: x`), and a full YAML dependency is off-limits for this CLI
|
|
8
|
+
* (commander + chalk only).
|
|
7
9
|
*
|
|
8
10
|
* Anything it cannot understand stays a raw string; nothing throws.
|
|
9
11
|
*/
|
|
@@ -16,6 +18,43 @@ function unquote(v) {
|
|
|
16
18
|
}
|
|
17
19
|
return t;
|
|
18
20
|
}
|
|
21
|
+
/** `>`, `>-`, `|`, `|-` (also the `+` and indentation-digit variants). */
|
|
22
|
+
const BLOCK_SCALAR = /^([>|])[0-9+-]{0,2}$/;
|
|
23
|
+
const indentOf = (line) => line.length - line.trimStart().length;
|
|
24
|
+
/**
|
|
25
|
+
* Lines after `from` that belong to a block scalar: blank, or indented deeper
|
|
26
|
+
* than the key that opened it. Returns them and the index of the first line
|
|
27
|
+
* that does not belong.
|
|
28
|
+
*/
|
|
29
|
+
function collectBlock(lines, from, keyIndent) {
|
|
30
|
+
let next = from;
|
|
31
|
+
while (next < lines.length && (lines[next].trim() === '' || indentOf(lines[next]) > keyIndent))
|
|
32
|
+
next++;
|
|
33
|
+
return { raw: lines.slice(from, next), next };
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Block scalar text: the common indentation is dropped. `|` keeps the line
|
|
37
|
+
* breaks, `>` folds lines into single spaces (a blank line stays a line
|
|
38
|
+
* break). The result is trimmed.
|
|
39
|
+
*/
|
|
40
|
+
function blockText(raw, folded) {
|
|
41
|
+
const filled = raw.filter((l) => l.trim() !== '');
|
|
42
|
+
const strip = filled.length > 0 ? Math.min(...filled.map(indentOf)) : 0;
|
|
43
|
+
const lines = raw.map((l) => (l.trim() === '' ? '' : l.slice(strip).trimEnd()));
|
|
44
|
+
if (!folded)
|
|
45
|
+
return lines.join('\n').trim();
|
|
46
|
+
let out = '';
|
|
47
|
+
let gap = 0;
|
|
48
|
+
for (const l of lines) {
|
|
49
|
+
if (l === '') {
|
|
50
|
+
gap++;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
out = out === '' ? l : gap > 0 ? `${out}${'\n'.repeat(gap)}${l}` : `${out} ${l}`;
|
|
54
|
+
gap = 0;
|
|
55
|
+
}
|
|
56
|
+
return out.trim();
|
|
57
|
+
}
|
|
19
58
|
function parseFrontmatter(raw) {
|
|
20
59
|
const text = raw.replace(/^/, '').replace(/\r\n/g, '\n');
|
|
21
60
|
const empty = { fields: {}, lists: {}, body: text };
|
|
@@ -29,29 +68,72 @@ function parseFrontmatter(raw) {
|
|
|
29
68
|
const body = afterClose.replace(/^[^\n]*\n?/, ''); // rest of the closing line
|
|
30
69
|
const fields = {};
|
|
31
70
|
const lists = {};
|
|
71
|
+
const lines = header.split('\n');
|
|
32
72
|
let currentListKey = null;
|
|
33
|
-
|
|
73
|
+
// A `key:` with no value opens either a list (`- item`) or a one-level map
|
|
74
|
+
// (` child: value`); whichever child comes first decides.
|
|
75
|
+
let mapParent = null;
|
|
76
|
+
let mapIndent = -1;
|
|
77
|
+
for (let i = 0; i < lines.length; i++) {
|
|
78
|
+
const line = lines[i];
|
|
34
79
|
const item = line.match(/^\s+-\s+(.*)$/) ?? line.match(/^-\s+(.*)$/);
|
|
35
80
|
if (item && currentListKey) {
|
|
36
81
|
lists[currentListKey].push(unquote(item[1]));
|
|
37
82
|
fields[currentListKey] = lists[currentListKey].join(', ');
|
|
83
|
+
mapParent = null; // it is a list
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (mapParent !== null && line.trim() !== '' && /^[ \t]/.test(line)) {
|
|
87
|
+
const child = line.match(/^([ \t]+)([A-Za-z0-9_-]+):[ \t]*(.*)$/);
|
|
88
|
+
if (child) {
|
|
89
|
+
const indent = child[1].length;
|
|
90
|
+
if (mapIndent === -1)
|
|
91
|
+
mapIndent = indent;
|
|
92
|
+
// Only the first level: deeper structure is skipped, not guessed at.
|
|
93
|
+
if (indent === mapIndent) {
|
|
94
|
+
const name = `${mapParent}_${child[2].toLowerCase()}`;
|
|
95
|
+
delete fields[mapParent];
|
|
96
|
+
delete lists[mapParent];
|
|
97
|
+
currentListKey = null;
|
|
98
|
+
const value = child[3].trim();
|
|
99
|
+
const block = value.match(BLOCK_SCALAR);
|
|
100
|
+
if (block) {
|
|
101
|
+
const b = collectBlock(lines, i + 1, indent);
|
|
102
|
+
fields[name] = blockText(b.raw, block[1] === '>');
|
|
103
|
+
i = b.next - 1;
|
|
104
|
+
}
|
|
105
|
+
else if (value !== '') {
|
|
106
|
+
fields[name] = unquote(value);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
38
110
|
continue;
|
|
39
111
|
}
|
|
40
112
|
const kv = line.match(/^([A-Za-z0-9_-]+):[ \t]*(.*)$/);
|
|
41
113
|
if (!kv) {
|
|
42
114
|
currentListKey = null;
|
|
115
|
+
mapParent = null;
|
|
43
116
|
continue;
|
|
44
117
|
}
|
|
45
118
|
const key = kv[1].toLowerCase();
|
|
46
119
|
const value = kv[2].trim();
|
|
120
|
+
mapParent = null;
|
|
121
|
+
mapIndent = -1;
|
|
47
122
|
if (value === '') {
|
|
48
123
|
currentListKey = key;
|
|
124
|
+
mapParent = key;
|
|
49
125
|
lists[key] = [];
|
|
50
126
|
fields[key] = '';
|
|
51
127
|
continue;
|
|
52
128
|
}
|
|
53
129
|
currentListKey = null;
|
|
54
|
-
|
|
130
|
+
const block = value.match(BLOCK_SCALAR);
|
|
131
|
+
if (block) {
|
|
132
|
+
const b = collectBlock(lines, i + 1, 0);
|
|
133
|
+
fields[key] = blockText(b.raw, block[1] === '>');
|
|
134
|
+
i = b.next - 1;
|
|
135
|
+
}
|
|
136
|
+
else if (value.startsWith('[') && value.endsWith(']')) {
|
|
55
137
|
lists[key] = value
|
|
56
138
|
.slice(1, -1)
|
|
57
139
|
.split(',')
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Read-only GitHub client for `ple import github:…` — PUBLIC repositories only,
|
|
4
|
+
* no token. Four calls, an import costs at most three of the counted ones
|
|
5
|
+
* (repo, commit, tree) plus raw downloads; the Contents API is never used:
|
|
6
|
+
*
|
|
7
|
+
* getRepo repo → {fullName, defaultBranch, license}
|
|
8
|
+
* resolveCommit ref → 40-hex commit
|
|
9
|
+
* getTree commit → every file (refuses a truncated list)
|
|
10
|
+
* fetchRaw file at a commit → text (≤ 64 KB, no binary)
|
|
11
|
+
*
|
|
12
|
+
* Every URL is built from validated parts with each path segment encoded. The
|
|
13
|
+
* HTTP rules (hosts, headers, redirects, errors) live in ./githubHttp.ts, the
|
|
14
|
+
* on-disk cache in ./githubCache.ts.
|
|
15
|
+
*/
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.TOO_LARGE_REPO = exports.REPO_RE = exports.OWNER_RE = exports.GithubError = exports.GITHUB_RAW = exports.GITHUB_API = exports.CACHE_TTL_MS = void 0;
|
|
18
|
+
exports.blobUrl = blobUrl;
|
|
19
|
+
exports.resetGithubRunState = resetGithubRunState;
|
|
20
|
+
exports.getRepo = getRepo;
|
|
21
|
+
exports.resolveCommit = resolveCommit;
|
|
22
|
+
exports.getTree = getTree;
|
|
23
|
+
exports.fetchRaw = fetchRaw;
|
|
24
|
+
exports.rememberRaw = rememberRaw;
|
|
25
|
+
const githubCache_1 = require("./githubCache");
|
|
26
|
+
Object.defineProperty(exports, "CACHE_TTL_MS", { enumerable: true, get: function () { return githubCache_1.CACHE_TTL_MS; } });
|
|
27
|
+
const githubHttp_1 = require("./githubHttp");
|
|
28
|
+
Object.defineProperty(exports, "GITHUB_API", { enumerable: true, get: function () { return githubHttp_1.GITHUB_API; } });
|
|
29
|
+
Object.defineProperty(exports, "GITHUB_RAW", { enumerable: true, get: function () { return githubHttp_1.GITHUB_RAW; } });
|
|
30
|
+
Object.defineProperty(exports, "GithubError", { enumerable: true, get: function () { return githubHttp_1.GithubError; } });
|
|
31
|
+
const format_1 = require("./format");
|
|
32
|
+
const secretGuard_1 = require("./secretGuard");
|
|
33
|
+
const MAX_TREE_BYTES = 8 * 1024 * 1024;
|
|
34
|
+
const MAX_JSON_BYTES = 1024 * 1024;
|
|
35
|
+
exports.OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
|
|
36
|
+
exports.REPO_RE = /^[A-Za-z0-9._-]{1,100}$/;
|
|
37
|
+
const SHA_RE = /^[0-9a-f]{40}$/;
|
|
38
|
+
exports.TOO_LARGE_REPO = 'This repository is too large to list in one request; try a smaller repository or open an issue.';
|
|
39
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
40
|
+
function assertRepo(owner, repo) {
|
|
41
|
+
if (!exports.OWNER_RE.test(owner) || !exports.REPO_RE.test(repo) || repo === '.' || repo === '..') {
|
|
42
|
+
throw new githubHttp_1.GithubError('Use github:<owner>/<repo>[/path][@ref], e.g. github:anthropics/skills/skills/pdf');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const encodePath = (p) => p.split('/').map(encodeURIComponent).join('/');
|
|
46
|
+
/** Permalink to a file at a commit on github.com (every path segment encoded). */
|
|
47
|
+
function blobUrl(repo, commit, filePath) {
|
|
48
|
+
return `https://github.com/${repo}/blob/${commit}/${encodePath(filePath)}`;
|
|
49
|
+
}
|
|
50
|
+
/** A path from a tree: no empty, `.` or `..` segment (it is only ever placed into a URL). */
|
|
51
|
+
function assertSafePath(p) {
|
|
52
|
+
if (!p || p.split('/').some((s) => s === '' || s === '.' || s === '..')) {
|
|
53
|
+
throw new githubHttp_1.GithubError(`Not a file path GitHub can serve: ${(0, format_1.safeText)(p)}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Tests only: forget the once-per-run state (rate-limit warning, cache pruning). */
|
|
57
|
+
function resetGithubRunState() {
|
|
58
|
+
(0, githubHttp_1.resetHttpState)();
|
|
59
|
+
(0, githubCache_1.resetCacheState)();
|
|
60
|
+
}
|
|
61
|
+
const repoKey = (owner, repo) => `${owner}/${repo}`.toLowerCase();
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
// Public calls
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
const isRepoInfo = (d) => isObject(d) &&
|
|
66
|
+
typeof d.fullName === 'string' &&
|
|
67
|
+
typeof d.defaultBranch === 'string' &&
|
|
68
|
+
(d.licenseSpdx === null || typeof d.licenseSpdx === 'string');
|
|
69
|
+
/** GET /repos/{owner}/{repo} */
|
|
70
|
+
async function getRepo(owner, repo) {
|
|
71
|
+
assertRepo(owner, repo);
|
|
72
|
+
const key = `repo:${repoKey(owner, repo)}`;
|
|
73
|
+
const hit = (0, githubCache_1.cacheGet)(key, githubCache_1.CACHE_TTL_MS, isRepoInfo);
|
|
74
|
+
if (hit)
|
|
75
|
+
return hit;
|
|
76
|
+
const label = `github.com/${owner}/${repo}`;
|
|
77
|
+
const body = (0, githubHttp_1.parseJson)(await (0, githubHttp_1.request)({
|
|
78
|
+
url: `${githubHttp_1.GITHUB_API}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`,
|
|
79
|
+
accept: 'application/vnd.github+json',
|
|
80
|
+
api: true,
|
|
81
|
+
maxBytes: MAX_JSON_BYTES,
|
|
82
|
+
what: `repo info for ${label}`,
|
|
83
|
+
missing: { statuses: [404], message: `Not found: ${label}. Only public repositories can be imported.` },
|
|
84
|
+
tooLarge: new githubHttp_1.GithubError(`GitHub sent too much data for ${label}.`),
|
|
85
|
+
}), `repo info for ${label}`);
|
|
86
|
+
if (!isObject(body) || typeof body.full_name !== 'string' || typeof body.default_branch !== 'string' || !body.default_branch) {
|
|
87
|
+
throw new githubHttp_1.GithubError(`GitHub sent an unexpected answer for repo info for ${label}.`);
|
|
88
|
+
}
|
|
89
|
+
// The canonical name is used to build every later URL: it must look like owner/repo, nothing else.
|
|
90
|
+
const [fullOwner, fullRepo, ...extra] = body.full_name.split('/');
|
|
91
|
+
if (extra.length > 0 || !exports.OWNER_RE.test(fullOwner) || !exports.REPO_RE.test(fullRepo ?? '')) {
|
|
92
|
+
throw new githubHttp_1.GithubError(`GitHub sent an unexpected answer for repo info for ${label}.`);
|
|
93
|
+
}
|
|
94
|
+
const license = isObject(body.license) && typeof body.license.spdx_id === 'string' ? body.license.spdx_id : null;
|
|
95
|
+
const info = { fullName: body.full_name, defaultBranch: body.default_branch, licenseSpdx: license };
|
|
96
|
+
(0, githubCache_1.cachePut)(key, info);
|
|
97
|
+
return info;
|
|
98
|
+
}
|
|
99
|
+
const isRefAnswer = (d) => typeof d === 'string' && SHA_RE.test(d);
|
|
100
|
+
/** GET /repos/{owner}/{repo}/commits/{ref} with the `sha` media type → the 40-hex commit id. */
|
|
101
|
+
async function resolveCommit(owner, repo, ref) {
|
|
102
|
+
assertRepo(owner, repo);
|
|
103
|
+
const key = `ref:${repoKey(owner, repo)}@${ref}`;
|
|
104
|
+
const hit = (0, githubCache_1.cacheGet)(key, githubCache_1.CACHE_TTL_MS, isRefAnswer);
|
|
105
|
+
if (hit)
|
|
106
|
+
return hit;
|
|
107
|
+
const label = `github.com/${owner}/${repo}`;
|
|
108
|
+
const text = (await (0, githubHttp_1.request)({
|
|
109
|
+
url: `${githubHttp_1.GITHUB_API}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits/${encodeURIComponent(ref)}`,
|
|
110
|
+
accept: 'application/vnd.github.sha',
|
|
111
|
+
api: true,
|
|
112
|
+
maxBytes: 1024,
|
|
113
|
+
what: `the commit for '${ref}' in ${label}`,
|
|
114
|
+
// GitHub answers 422 for a ref it cannot resolve, 404 for some spellings of the same.
|
|
115
|
+
missing: { statuses: [404, 422], message: `Cannot find '${(0, format_1.safeText)(ref)}' in ${label} (branch, tag or commit).` },
|
|
116
|
+
tooLarge: new githubHttp_1.GithubError(`GitHub sent an unexpected answer for the commit of '${(0, format_1.safeText)(ref)}'.`),
|
|
117
|
+
}))
|
|
118
|
+
.toString('utf8')
|
|
119
|
+
.trim();
|
|
120
|
+
if (!SHA_RE.test(text)) {
|
|
121
|
+
throw new githubHttp_1.GithubError(`GitHub sent an unexpected answer for the commit of '${(0, format_1.safeText)(ref)}'.`);
|
|
122
|
+
}
|
|
123
|
+
(0, githubCache_1.cachePut)(key, text);
|
|
124
|
+
return text;
|
|
125
|
+
}
|
|
126
|
+
const isTree = (d) => isObject(d) &&
|
|
127
|
+
Array.isArray(d.entries) &&
|
|
128
|
+
d.entries.every((e) => isObject(e) && typeof e.path === 'string' && typeof e.sha === 'string');
|
|
129
|
+
/** GET /repos/{owner}/{repo}/git/trees/{sha}?recursive=1 — every file of the commit. */
|
|
130
|
+
async function getTree(owner, repo, sha) {
|
|
131
|
+
assertRepo(owner, repo);
|
|
132
|
+
if (!SHA_RE.test(sha))
|
|
133
|
+
throw new githubHttp_1.GithubError('Not a commit id.');
|
|
134
|
+
const key = `tree:${repoKey(owner, repo)}@${sha}`;
|
|
135
|
+
const hit = (0, githubCache_1.cacheGet)(key, null, isTree);
|
|
136
|
+
if (hit)
|
|
137
|
+
return hit;
|
|
138
|
+
const label = `github.com/${owner}/${repo}`;
|
|
139
|
+
const body = (0, githubHttp_1.parseJson)(await (0, githubHttp_1.request)({
|
|
140
|
+
url: `${githubHttp_1.GITHUB_API}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/git/trees/${sha}?recursive=1`,
|
|
141
|
+
accept: 'application/vnd.github+json',
|
|
142
|
+
api: true,
|
|
143
|
+
maxBytes: MAX_TREE_BYTES,
|
|
144
|
+
what: `the file list of ${label}`,
|
|
145
|
+
missing: { statuses: [404], message: `Not found: ${label}. Only public repositories can be imported.` },
|
|
146
|
+
tooLarge: new githubHttp_1.GithubError(exports.TOO_LARGE_REPO),
|
|
147
|
+
}), `the file list of ${label}`);
|
|
148
|
+
if (!isObject(body) || !Array.isArray(body.tree)) {
|
|
149
|
+
throw new githubHttp_1.GithubError(`GitHub sent an unexpected answer for the file list of ${label}.`);
|
|
150
|
+
}
|
|
151
|
+
// The recursive listing stops at 100,000 entries / 7 MB; a partial list would silently hide files.
|
|
152
|
+
if (body.truncated === true)
|
|
153
|
+
throw new githubHttp_1.GithubError(exports.TOO_LARGE_REPO);
|
|
154
|
+
const entries = [];
|
|
155
|
+
for (const e of body.tree) {
|
|
156
|
+
if (!isObject(e) || e.type !== 'blob' || typeof e.path !== 'string' || typeof e.sha !== 'string')
|
|
157
|
+
continue;
|
|
158
|
+
entries.push({
|
|
159
|
+
path: e.path,
|
|
160
|
+
type: 'blob',
|
|
161
|
+
sha: e.sha,
|
|
162
|
+
...(typeof e.size === 'number' ? { size: e.size } : {}),
|
|
163
|
+
...(typeof e.mode === 'string' ? { mode: e.mode } : {}),
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
const tree = { entries, truncated: false };
|
|
167
|
+
(0, githubCache_1.cachePut)(key, tree);
|
|
168
|
+
return tree;
|
|
169
|
+
}
|
|
170
|
+
const isText = (d) => typeof d === 'string';
|
|
171
|
+
const rawKey = (owner, repo, sha, filePath) => `raw:${repoKey(owner, repo)}@${sha}:${filePath}`;
|
|
172
|
+
/**
|
|
173
|
+
* One file at a commit, as text. At most MAX_SCAN_FILE_BYTES is ever downloaded
|
|
174
|
+
* (the limit applies while streaming, not only after), and a file with a NUL
|
|
175
|
+
* byte is refused as binary. `cache: false` skips WRITING the cache — callers
|
|
176
|
+
* use it for files they might still refuse (license, secret) and call
|
|
177
|
+
* {@link rememberRaw} once the file is accepted.
|
|
178
|
+
*/
|
|
179
|
+
async function fetchRaw(owner, repo, sha, filePath, opts = {}) {
|
|
180
|
+
assertRepo(owner, repo);
|
|
181
|
+
if (!SHA_RE.test(sha))
|
|
182
|
+
throw new githubHttp_1.GithubError('Not a commit id.');
|
|
183
|
+
assertSafePath(filePath);
|
|
184
|
+
const key = rawKey(owner, repo, sha, filePath);
|
|
185
|
+
const hit = (0, githubCache_1.cacheGet)(key, null, isText);
|
|
186
|
+
if (hit !== null)
|
|
187
|
+
return hit;
|
|
188
|
+
const shown = (0, format_1.safeText)(filePath);
|
|
189
|
+
const limit = secretGuard_1.MAX_SCAN_FILE_BYTES / 1024;
|
|
190
|
+
const buf = await (0, githubHttp_1.request)({
|
|
191
|
+
url: `${githubHttp_1.GITHUB_RAW}/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${sha}/${encodePath(filePath)}`,
|
|
192
|
+
accept: 'text/plain',
|
|
193
|
+
api: false,
|
|
194
|
+
maxBytes: secretGuard_1.MAX_SCAN_FILE_BYTES,
|
|
195
|
+
what: shown,
|
|
196
|
+
tooLarge: new githubHttp_1.GithubError(`${shown} is larger than ${limit} KB`, { kind: 'too_large' }),
|
|
197
|
+
});
|
|
198
|
+
if (buf.includes(0))
|
|
199
|
+
throw new githubHttp_1.GithubError(`${shown} is not a text file`, { kind: 'binary' });
|
|
200
|
+
const text = buf.toString('utf8');
|
|
201
|
+
if (opts.cache !== false)
|
|
202
|
+
(0, githubCache_1.cachePut)(key, text);
|
|
203
|
+
return text;
|
|
204
|
+
}
|
|
205
|
+
/** Keep a file fetched with `cache: false` — call it only for files that were accepted. */
|
|
206
|
+
function rememberRaw(owner, repo, sha, filePath, text) {
|
|
207
|
+
(0, githubCache_1.cachePut)(rawKey(owner, repo, sha, filePath), text);
|
|
208
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Politeness cache for GitHub answers, under `<localRoot>/cache/github/`:
|
|
4
|
+
* what a `--dry-run` fetched must not be fetched again by the real import.
|
|
5
|
+
*
|
|
6
|
+
* Trees and files are keyed by commit SHA — immutable, so kept; repo info and
|
|
7
|
+
* ref → commit lookups go stale and live 10 minutes. File names are the sha256
|
|
8
|
+
* of the key (never user input); reads and writes go through fsSafe (0600/0700,
|
|
9
|
+
* atomic, never through a symlink). A corrupt or foreign file is ignored, a
|
|
10
|
+
* failed write is ignored; the folder keeps the newest {@link MAX_CACHE_FILES}.
|
|
11
|
+
*/
|
|
12
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
13
|
+
if (k2 === undefined) k2 = k;
|
|
14
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
15
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
16
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
17
|
+
}
|
|
18
|
+
Object.defineProperty(o, k2, desc);
|
|
19
|
+
}) : (function(o, m, k, k2) {
|
|
20
|
+
if (k2 === undefined) k2 = k;
|
|
21
|
+
o[k2] = m[k];
|
|
22
|
+
}));
|
|
23
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
24
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
25
|
+
}) : function(o, v) {
|
|
26
|
+
o["default"] = v;
|
|
27
|
+
});
|
|
28
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
29
|
+
var ownKeys = function(o) {
|
|
30
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
31
|
+
var ar = [];
|
|
32
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
33
|
+
return ar;
|
|
34
|
+
};
|
|
35
|
+
return ownKeys(o);
|
|
36
|
+
};
|
|
37
|
+
return function (mod) {
|
|
38
|
+
if (mod && mod.__esModule) return mod;
|
|
39
|
+
var result = {};
|
|
40
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
41
|
+
__setModuleDefault(result, mod);
|
|
42
|
+
return result;
|
|
43
|
+
};
|
|
44
|
+
})();
|
|
45
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
46
|
+
exports.CACHE_TTL_MS = void 0;
|
|
47
|
+
exports.cacheGet = cacheGet;
|
|
48
|
+
exports.resetCacheState = resetCacheState;
|
|
49
|
+
exports.cachePut = cachePut;
|
|
50
|
+
const crypto = __importStar(require("crypto"));
|
|
51
|
+
const fs = __importStar(require("fs"));
|
|
52
|
+
const path = __importStar(require("path"));
|
|
53
|
+
const fsSafe_1 = require("./fsSafe");
|
|
54
|
+
const localStore_1 = require("./localStore");
|
|
55
|
+
/** Repo info and ref → commit answers go stale; trees and files by SHA do not. */
|
|
56
|
+
exports.CACHE_TTL_MS = 10 * 60 * 1000;
|
|
57
|
+
const MAX_CACHE_FILES = 400;
|
|
58
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
59
|
+
function cacheDir() {
|
|
60
|
+
return path.join((0, localStore_1.localRoot)(), 'cache', 'github');
|
|
61
|
+
}
|
|
62
|
+
/** File names are a hash of the key — never user input. */
|
|
63
|
+
function cacheFile(key) {
|
|
64
|
+
return path.join(cacheDir(), `${crypto.createHash('sha256').update(key).digest('hex')}.json`);
|
|
65
|
+
}
|
|
66
|
+
/** Cached value, or null when missing, corrupt, of another shape, or older than `maxAgeMs` (null = keep forever). */
|
|
67
|
+
function cacheGet(key, maxAgeMs, valid) {
|
|
68
|
+
const raw = (0, fsSafe_1.readPrivateFile)(cacheFile(key));
|
|
69
|
+
if (raw === null)
|
|
70
|
+
return null;
|
|
71
|
+
try {
|
|
72
|
+
const entry = JSON.parse(raw);
|
|
73
|
+
if (!isObject(entry) || entry.v !== 1 || entry.key !== key || typeof entry.savedAt !== 'number')
|
|
74
|
+
return null;
|
|
75
|
+
const age = Date.now() - entry.savedAt;
|
|
76
|
+
if (maxAgeMs !== null && (age < 0 || age > maxAgeMs))
|
|
77
|
+
return null;
|
|
78
|
+
return valid(entry.data) ? entry.data : null;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
let pruned = false;
|
|
85
|
+
/** Tests only: forget the once-per-run state. */
|
|
86
|
+
function resetCacheState() {
|
|
87
|
+
pruned = false;
|
|
88
|
+
}
|
|
89
|
+
/** Once per run: keep the newest MAX_CACHE_FILES files, drop the rest. */
|
|
90
|
+
function pruneCache() {
|
|
91
|
+
if (pruned)
|
|
92
|
+
return;
|
|
93
|
+
pruned = true;
|
|
94
|
+
try {
|
|
95
|
+
const dir = cacheDir();
|
|
96
|
+
const files = fs
|
|
97
|
+
.readdirSync(dir)
|
|
98
|
+
.filter((f) => /^[0-9a-f]{64}\.json$/.test(f))
|
|
99
|
+
.map((f) => ({ f, t: fs.statSync(path.join(dir, f)).mtimeMs }))
|
|
100
|
+
.sort((a, b) => b.t - a.t);
|
|
101
|
+
for (const old of files.slice(MAX_CACHE_FILES))
|
|
102
|
+
fs.unlinkSync(path.join(dir, old.f));
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
/* best effort */
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Best effort: a read-only disk just means the next run asks GitHub again. */
|
|
109
|
+
function cachePut(key, data) {
|
|
110
|
+
try {
|
|
111
|
+
const entry = { v: 1, key, savedAt: Date.now(), data };
|
|
112
|
+
(0, fsSafe_1.writePrivateFile)(cacheFile(key), JSON.stringify(entry));
|
|
113
|
+
pruneCache();
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
/* best effort */
|
|
117
|
+
}
|
|
118
|
+
}
|