promptlike 0.7.0 → 0.9.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.
@@ -46,7 +46,7 @@ async function showCommand(name, options = {}) {
46
46
  !version.description_text &&
47
47
  !version.context_text) {
48
48
  console.log();
49
- console.log(version.content);
49
+ console.log((0, format_1.safeText)(version.content, true));
50
50
  console.log();
51
51
  return;
52
52
  }
@@ -54,17 +54,17 @@ async function showCommand(name, options = {}) {
54
54
  if (version.role_text?.trim()) {
55
55
  console.log();
56
56
  console.log(format_1.c.accent('── ROLE ──'));
57
- console.log(version.role_text.trim());
57
+ console.log((0, format_1.safeText)(version.role_text.trim(), true));
58
58
  }
59
59
  if (version.description_text?.trim()) {
60
60
  console.log();
61
61
  console.log(format_1.c.accent('── DESCRIPTION ──'));
62
- console.log(version.description_text.trim());
62
+ console.log((0, format_1.safeText)(version.description_text.trim(), true));
63
63
  }
64
64
  if (version.context_text?.trim()) {
65
65
  console.log();
66
66
  console.log(format_1.c.accent('── CONTEXT ──'));
67
- console.log(version.context_text.trim());
67
+ console.log((0, format_1.safeText)(version.context_text.trim(), true));
68
68
  }
69
69
  console.log();
70
70
  }
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ /**
3
+ * `ple tag <name> <version> <label>` — point a deployment label (`production`, `staging`, …)
4
+ * at one version of a prompt. Moving a label keeps an audit trail (who/when/from → to); the version
5
+ * history itself never changes.
6
+ *
7
+ * ple tag "code review" 3 production # label v3 as production (moves it if it was elsewhere)
8
+ * ple tag "code review" --list # labels + recent moves
9
+ * ple tag "code review" --remove staging
10
+ *
11
+ * Then read it back with `ple get "code review" --label production`.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.LABEL_RE = void 0;
15
+ exports.normalizeLabel = normalizeLabel;
16
+ exports.tagCommand = tagCommand;
17
+ const api_client_1 = require("../lib/api-client");
18
+ const format_1 = require("../lib/format");
19
+ const local_1 = require("./local");
20
+ const history_1 = require("./history");
21
+ /** Same rule as the server (a-z 0-9 . _ - ; 1-32 chars, starts alphanumeric). */
22
+ exports.LABEL_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
23
+ function normalizeLabel(raw) {
24
+ const label = raw.trim().toLowerCase();
25
+ if (!exports.LABEL_RE.test(label)) {
26
+ throw new Error(`Invalid label '${raw}'. Use a-z, 0-9, '.', '_' or '-' (max 32 chars).`);
27
+ }
28
+ return label;
29
+ }
30
+ async function tagCommand(name, version, label, options = {}) {
31
+ if ((0, local_1.isSignedOut)()) {
32
+ throw new Error("Deployment labels need an account (they live on the server). Run 'ple login' first.");
33
+ }
34
+ const prompt = await (0, history_1.resolveForHistory)(name, options.project);
35
+ if (!prompt) {
36
+ process.exitCode = 1;
37
+ return;
38
+ }
39
+ if (options.list || (!version && !label && !options.remove)) {
40
+ const { labels, events } = await (0, api_client_1.listPromptLabels)(prompt.id);
41
+ if (labels.length === 0) {
42
+ console.log(format_1.c.muted(`No labels on '${prompt.title}'. Set one: ple tag "${prompt.title}" <version> production`));
43
+ }
44
+ for (const l of labels) {
45
+ console.log(`${l.label.padEnd(14)} → v${l.version_number} ${format_1.c.muted(new Date(l.set_at).toLocaleString())}`);
46
+ }
47
+ if (events.length > 0) {
48
+ console.log(format_1.c.muted('\nRecent moves:'));
49
+ for (const e of events.slice(0, 10)) {
50
+ const move = e.to_version_number == null
51
+ ? `removed from v${e.from_version_number ?? '?'}`
52
+ : e.from_version_number == null
53
+ ? `set to v${e.to_version_number}`
54
+ : `v${e.from_version_number} → v${e.to_version_number}`;
55
+ console.log(format_1.c.muted(` ${e.label}: ${move} (${new Date(e.created_at).toLocaleString()})`));
56
+ }
57
+ }
58
+ return;
59
+ }
60
+ if (options.remove) {
61
+ const target = normalizeLabel(options.remove);
62
+ const res = await (0, api_client_1.clearPromptLabel)(prompt.id, target);
63
+ console.log(res.changed
64
+ ? format_1.c.success(`✓ Removed label '${target}'`) + format_1.c.muted(` (was v${res.previous_version_number ?? '?'})`)
65
+ : format_1.c.muted(`Label '${target}' was not set — nothing to do.`));
66
+ return;
67
+ }
68
+ if (!version || !label) {
69
+ throw new Error('Usage: ple tag <name> <version> <label> (or --list / --remove <label>)');
70
+ }
71
+ const wanted = normalizeLabel(label);
72
+ const history = await (0, api_client_1.getPromptHistory)(prompt.id);
73
+ const target = (0, history_1.findVersion)(history.versions, version);
74
+ if (!target)
75
+ throw (0, history_1.versionNotFound)(version, history.versions);
76
+ const res = await (0, api_client_1.setPromptLabel)(prompt.id, wanted, target.id);
77
+ if (res.changed === false) {
78
+ console.log(format_1.c.muted(`'${wanted}' already points at v${target.version_number} — nothing to do.`));
79
+ return;
80
+ }
81
+ const moved = res.previous_version_number != null ? ` (moved from v${res.previous_version_number})` : '';
82
+ console.log(format_1.c.success(`✓ ${wanted} → v${target.version_number}`) + format_1.c.muted(`${moved} — ${history.title}`));
83
+ if (res.previous_version_number != null) {
84
+ console.log(format_1.c.muted(`Move it back with: ple tag "${history.title}" ${res.previous_version_number} ${wanted}`));
85
+ }
86
+ }
package/dist/help.js ADDED
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ /**
3
+ * Grouped `ple --help`. commander lists commands in registration order with no
4
+ * headings; with ~20 commands that is a wall of text. This prints the same
5
+ * commands under task-based headings. A test (program.test.ts) fails when a
6
+ * command is registered but missing from GROUPS, so the help cannot drift.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.COMMAND_GROUPS = void 0;
10
+ exports.formatRootHelp = formatRootHelp;
11
+ const commander_1 = require("commander");
12
+ exports.COMMAND_GROUPS = [
13
+ { title: 'Prompts', commands: ['save', 'get', 'show', 'copy', 'list', 'search', 'log', 'diff', 'rollback', 'tag', 'improve', 'loop'] },
14
+ { title: 'Repos', commands: ['repo'] },
15
+ { title: 'Account', commands: ['login', 'logout'] },
16
+ { title: 'Import / export / sync', commands: ['import', 'export', 'sync'] },
17
+ { title: 'Insights & settings', commands: ['stats', 'suggest', 'config'] },
18
+ ];
19
+ const EXAMPLES = [
20
+ 'ple save "code review" -m "Review this diff: {{diff}}" # no account needed',
21
+ 'ple get "code review" --var diff="$(git diff)" | claude',
22
+ 'ple repo create "team-prompts" # private by default',
23
+ 'ple login && ple sync --dry-run',
24
+ ];
25
+ const EXIT_CODES = [
26
+ '0 success',
27
+ '1 fix it yourself: bad input, not signed in, not found, not allowed, plan limit',
28
+ '2 try again later: no network, timeout, rate limit, server error',
29
+ ];
30
+ function formatRootHelp(cmd, helper) {
31
+ // configureHelp() is inherited by subcommands; only the root gets the grouped layout.
32
+ if (cmd.parent)
33
+ return commander_1.Help.prototype.formatHelp.call(helper, cmd, helper);
34
+ const lines = [];
35
+ lines.push(`Usage: ${helper.commandUsage(cmd)}`, '');
36
+ lines.push(helper.commandDescription(cmd), '');
37
+ const subs = helper.visibleCommands(cmd);
38
+ const byName = new Map(subs.map((s) => [s.name(), s]));
39
+ const width = Math.max(...subs.map((s) => helper.subcommandTerm(s).length)) + 2;
40
+ const seen = new Set();
41
+ const render = (title, names) => {
42
+ const rows = names.map((n) => byName.get(n)).filter((s) => s !== undefined);
43
+ if (rows.length === 0)
44
+ return;
45
+ lines.push(`${title}:`);
46
+ for (const s of rows) {
47
+ seen.add(s.name());
48
+ lines.push(` ${helper.subcommandTerm(s).padEnd(width)}${helper.subcommandDescription(s)}`);
49
+ }
50
+ lines.push('');
51
+ };
52
+ for (const g of exports.COMMAND_GROUPS)
53
+ render(g.title, g.commands);
54
+ // A command nobody grouped still shows up (and fails the test) instead of vanishing.
55
+ render('Other', subs.map((s) => s.name()).filter((n) => !seen.has(n) && n !== 'help'));
56
+ lines.push('Options:');
57
+ for (const o of helper.visibleOptions(cmd)) {
58
+ lines.push(` ${helper.optionTerm(o).padEnd(width)}${helper.optionDescription(o)}`);
59
+ }
60
+ lines.push('');
61
+ lines.push('Examples:', ...EXAMPLES.map((e) => ` ${e}`), '');
62
+ lines.push('Exit codes:', ...EXIT_CODES.map((e) => ` ${e}`), '');
63
+ lines.push('Run `ple <command> --help` for a command, or `ple repo --help` for the repo commands.');
64
+ return lines.join('\n') + '\n';
65
+ }
package/dist/index.js CHANGED
@@ -1,176 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
  /**
4
- * promptlike CLI entry point.
5
- *
6
- * Registers the commands and runs `commander`. Each command's real logic lives
7
- * under `src/commands/` — this file only does argument parsing + the global
8
- * error wrapper.
4
+ * promptlike CLI entry point — builds the command table (src/program.ts) and runs it.
9
5
  */
10
6
  Object.defineProperty(exports, "__esModule", { value: true });
11
- const commander_1 = require("commander");
12
- const constants_1 = require("./lib/constants");
13
- const format_1 = require("./lib/format");
14
- const login_1 = require("./commands/login");
15
- const logout_1 = require("./commands/logout");
16
- const list_1 = require("./commands/list");
17
- const copy_1 = require("./commands/copy");
18
- const show_1 = require("./commands/show");
19
- const search_1 = require("./commands/search");
20
- const get_1 = require("./commands/get");
21
- const improve_1 = require("./commands/improve");
22
- const loop_1 = require("./commands/loop");
23
- const save_1 = require("./commands/save");
24
- const sync_1 = require("./commands/sync");
25
- const export_1 = require("./commands/export");
26
- const stats_1 = require("./commands/stats");
27
- const import_1 = require("./commands/import");
28
- const log_1 = require("./commands/log");
29
- const diff_1 = require("./commands/diff");
30
- const rollback_1 = require("./commands/rollback");
31
- const suggest_1 = require("./commands/suggest");
32
- const config_1 = require("./commands/config");
33
- /** A single global try/catch — consistent error output for every command. */
34
- function runWithErrorHandler(fn) {
35
- return async (...args) => {
36
- try {
37
- await fn(...args);
38
- }
39
- catch (err) {
40
- const message = err instanceof Error ? err.message : String(err);
41
- console.error(format_1.c.error(`✗ ${message}`));
42
- process.exit(process.exitCode || 1);
43
- }
44
- };
45
- }
46
- const program = new commander_1.Command();
47
- program
48
- .name(constants_1.CLI_NAME)
49
- .description('Terminal access to your PromptLikeEngineer prompt library')
50
- .version(constants_1.CLI_VERSION);
51
- program
52
- .command('save <title>')
53
- .description('Save a prompt locally — no account needed')
54
- .option('-m, --message <text>', 'Prompt body (or pipe it via stdin)')
55
- .option('-d, --description <text>', 'Short description')
56
- .option('-t, --tag <name>', 'Tag (repeatable)', save_1.collectTag, [])
57
- .option('-f, --force', 'Overwrite an existing local prompt')
58
- .action(runWithErrorHandler(save_1.saveCommand));
59
- program
60
- .command('sync')
61
- .description('Upload your local prompts to your account (one-way, explicit)')
62
- .option('--dry-run', 'List what would be uploaded, change nothing')
63
- .action(runWithErrorHandler(sync_1.syncCommand));
64
- program
65
- .command('login')
66
- .description('Sign in with email + password; store the session under ~/.config/promptlike/')
67
- .action(runWithErrorHandler(login_1.loginCommand));
68
- program
69
- .command('logout')
70
- .description('Delete the local session file')
71
- .action(runWithErrorHandler(logout_1.logoutCommand));
72
- program
73
- .command('list')
74
- .description('List your prompts')
75
- .option('-t, --tag <name>', 'Filter by a specific tag')
76
- .option('-l, --limit <n>', 'Max number of rows (default 30)', '30')
77
- .action(runWithErrorHandler(list_1.listCommand));
78
- program
79
- .command('copy <name>')
80
- .description('Copy a prompt to the clipboard (by title or short id)')
81
- .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
82
- .action(runWithErrorHandler(copy_1.copyCommand));
83
- program
84
- .command('show <name>')
85
- .description('Show a prompt in the terminal')
86
- .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
87
- .action(runWithErrorHandler(show_1.showCommand));
88
- program
89
- .command('get <name>')
90
- .description("Print a prompt raw to stdout; fill {{variables}} (agent/pipe friendly)")
91
- .option('-v, --var <keyval>', 'Fill a variable — key=value (repeatable)', get_1.collectVar, {})
92
- .option('-c, --copy', 'Also copy the output to the clipboard')
93
- .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
94
- .action(runWithErrorHandler(get_1.getCommand));
95
- program
96
- .command('improve <name>')
97
- .option('-p, --pick <n>', 'Non-interactive: auto-pick variant N (1..3), 0 to cancel — for scripts/agents')
98
- .description('Generate AI variants of a prompt, pick a winner, save it as a new version (Pro)')
99
- .option('-f, --focus <hint>', "Steer the variants (e.g. 'shorter', 'more explicit output format')")
100
- .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
101
- .action(runWithErrorHandler(improve_1.improveCommand));
102
- program
103
- .command('loop <name>')
104
- .description('Multi-round improve — optionally test each variant with your own agent command (Pro)')
105
- .option('-e, --exec <cmd>', 'Test each variant: prompt passed via PLE_PROMPT env + stdin; {} placeholder substituted')
106
- .option('-r, --rounds <n>', 'Number of improvement rounds', '1')
107
- .option('-f, --focus <hint>', 'Steer the variants')
108
- .option('-p, --pick <n>', 'Non-interactive: auto-pick variant N each round + auto-continue — for scripts/agents')
109
- .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
110
- .action(runWithErrorHandler(loop_1.loopCommand));
111
- program
112
- .command('export [name]')
113
- .description('Export a prompt (or a whole repo with --project) as an AGENTS.md section or an Agent Skill (SKILL.md)')
114
- .requiredOption('--format <format>', 'agents-md | skill')
115
- .option('--project <repo>', 'Repo to export (no name) or to scope the name to')
116
- .option('-o, --out <path>', 'agents-md: file to write (default stdout) · skill: parent folder (default .)')
117
- .option('--zip', 'skill: write <name>.zip (upload in Claude) instead of a folder')
118
- .option('-f, --force', 'Overwrite an existing file or folder')
119
- .action(runWithErrorHandler(export_1.exportCommand));
120
- program
121
- .command('search <keyword>')
122
- .description('Search titles and descriptions (signed out: also local prompt bodies and tags)')
123
- .action(runWithErrorHandler(search_1.searchCommand));
124
- program
125
- .command('stats')
126
- .description('How your library is used — uses by surface, most used, gathering dust')
127
- .option('-r, --range <days>', 'Window: 7, 30 or 365 (Free: 7)', '7')
128
- .option('--json', 'Print the raw summary as JSON')
129
- .action(runWithErrorHandler(stats_1.statsCommand));
130
- program
131
- .command('import')
132
- .description('Bring in prompts you already have: .claude/commands, SKILL.md, .cursor/commands, ~/.codex/prompts')
133
- .option('--scan', 'Scan this repo and your home folder for agent prompt files')
134
- .option('--dry-run', 'Only show what was found, import nothing')
135
- .option('-a, --all', 'Import everything new without asking')
136
- .option('--project <repo>', 'Import into this repo (signed in)')
137
- .action(runWithErrorHandler((opts) => (0, import_1.importCommand)(opts)));
138
- program
139
- .command('log <name>')
140
- .description('Version history of a prompt (* = current). Signed out: the local history')
141
- .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
142
- .option('-l, --limit <n>', 'Max versions to show (default 20)', '20')
143
- .option('--json', 'Print as JSON')
144
- .action(runWithErrorHandler(log_1.logCommand));
145
- program
146
- .command('diff <name> [a] [b]')
147
- .description('Diff two versions (default: previous ↔ current). Refs: 3, v3 or 1.0.2')
148
- .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
149
- .option('--no-color', 'Plain output (automatic when piped)')
150
- .action(runWithErrorHandler((name, a, b, opts) => (0, diff_1.diffCommand)(name, a, b, opts)));
151
- program
152
- .command('suggest [text...]')
153
- .description('Which saved prompt fits this task? Local match — the text never leaves your machine')
154
- .option('--json', 'Print matches as JSON')
155
- .option('-l, --limit <n>', 'Max matches (default 3)', '3')
156
- .option('--hook', 'Claude Code UserPromptSubmit mode: read hook JSON on stdin, print a short hint or nothing')
157
- .option('--refresh-cache', 'Refresh the local library cache from your account and exit')
158
- .action(runWithErrorHandler((text, opts) => (0, suggest_1.suggestCommand)(text ?? [], opts)));
159
- const configCmd = program
160
- .command('config')
161
- .description('CLI preferences (suggest on|off)');
162
- configCmd
163
- .command('get [key]')
164
- .description('Show a setting (or all)')
165
- .action(runWithErrorHandler(config_1.configGetCommand));
166
- configCmd
167
- .command('set <key> <value>')
168
- .description('Change a setting, e.g. `ple config set suggest off`')
169
- .action(runWithErrorHandler(config_1.configSetCommand));
170
- program
171
- .command('rollback <name> <version>')
172
- .description('Restore an old version as a new one — nothing is deleted (signed out: local history)')
173
- .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
174
- .option('-y, --yes', 'Skip the confirmation prompt')
175
- .action(runWithErrorHandler((name, version, opts) => (0, rollback_1.rollbackCommand)(name, version, opts)));
176
- program.parseAsync(process.argv);
7
+ const program_1 = require("./program");
8
+ (0, program_1.buildProgram)()
9
+ .parseAsync(process.argv)
10
+ .catch((err) => {
11
+ // Commands handle their own errors; this only catches a bug in the wiring itself.
12
+ console.error(`✗ ${err instanceof Error ? err.message : String(err)}`);
13
+ process.exit(1);
14
+ });
@@ -27,13 +27,22 @@ exports.importPrompts = importPrompts;
27
27
  exports.getImportedHashes = getImportedHashes;
28
28
  exports.getAccountHeadroom = getAccountHeadroom;
29
29
  exports.listProjects = listProjects;
30
+ exports.toRepoDetail = toRepoDetail;
31
+ exports.listProjectsDetailed = listProjectsDetailed;
32
+ exports.createProject = createProject;
33
+ exports.setProjectVisibility = setProjectVisibility;
30
34
  exports.getPromptById = getPromptById;
31
35
  exports.getPromptHistory = getPromptHistory;
32
36
  exports.rollbackPrompt = rollbackPrompt;
37
+ exports.listPromptLabels = listPromptLabels;
38
+ exports.setPromptLabel = setPromptLabel;
39
+ exports.clearPromptLabel = clearPromptLabel;
40
+ exports.getLabeledVersion = getLabeledVersion;
33
41
  exports.buildUseEventBody = buildUseEventBody;
34
42
  exports.recordPromptUse = recordPromptUse;
35
43
  exports.getUsageInsights = getUsageInsights;
36
44
  const constants_1 = require("./constants");
45
+ const format_1 = require("./format");
37
46
  const config_1 = require("./config");
38
47
  const NOT_LOGGED_IN = 'Not logged in. Run `ple login` first.';
39
48
  const SESSION_EXPIRED = 'Session expired. Log in again: `ple login`';
@@ -206,8 +215,27 @@ function getAccessTokenOrThrow() {
206
215
  throw new Error(NOT_LOGGED_IN);
207
216
  return config.access_token;
208
217
  }
218
+ /**
219
+ * The auth endpoints are the one place where a malformed (or hostile) response
220
+ * would be written to disk as our session. Check the shape first; the message
221
+ * never echoes the body (it may contain tokens).
222
+ */
223
+ function assertAuthResponse(data) {
224
+ const d = data;
225
+ const ok = typeof d === 'object' &&
226
+ d !== null &&
227
+ typeof d.access_token === 'string' &&
228
+ d.access_token.length > 0 &&
229
+ typeof d.refresh_token === 'string' &&
230
+ d.refresh_token.length > 0 &&
231
+ (d.expires_at === undefined || (typeof d.expires_at === 'number' && Number.isFinite(d.expires_at)));
232
+ if (!ok) {
233
+ throw new ApiError('The server sent an unexpected sign-in response. Update the CLI (npm i -g promptlike) and try again.', 502);
234
+ }
235
+ }
209
236
  /** Persist a fresh auth payload to the local config file. */
210
237
  function persist(data) {
238
+ assertAuthResponse(data);
211
239
  const previous = (0, config_1.readConfig)();
212
240
  const config = {
213
241
  access_token: data.access_token,
@@ -244,12 +272,15 @@ async function refreshSession() {
244
272
  if (err instanceof NetworkError)
245
273
  throw new NetworkError(err.detail, exports.REFRESH_NETWORK_ADVICE);
246
274
  // 503 / 429 / 5xx / tanınmayan yanıt: geçici; yerel oturum korunur.
247
- throw new Error(refreshUnavailableMessage(err instanceof Error ? err.message : String(err)));
275
+ throw new ApiError(refreshUnavailableMessage(err instanceof Error ? err.message : String(err)), 503);
248
276
  }
249
277
  persist(data);
250
278
  }
251
279
  /** Core request helper. See module doc for behavior. */
252
280
  async function apiFetch(path, opts = {}) {
281
+ // An unusable PROMPTLIKE_API_URL is reported BEFORE a request (and a token) exists.
282
+ if (constants_1.API_BASE_URL_ERROR)
283
+ throw new Error(constants_1.API_BASE_URL_ERROR);
253
284
  const { method = 'GET', body, query, auth = true } = opts;
254
285
  const timeoutMs = opts.timeoutMs ?? (method === 'GET' ? exports.READ_TIMEOUT_MS : exports.WRITE_TIMEOUT_MS);
255
286
  const signal = AbortSignal.timeout(timeoutMs);
@@ -270,6 +301,9 @@ async function apiFetch(path, opts = {}) {
270
301
  body: body === undefined ? undefined : JSON.stringify(body),
271
302
  // Süre başlıkla sınırlı değil: gövde okuması da aynı sinyalle kesilir.
272
303
  signal,
304
+ // Never follow redirects automatically: a 307/308 would replay the POST body
305
+ // (email + password on login) at a Location the server chose.
306
+ redirect: 'manual',
273
307
  });
274
308
  }
275
309
  catch (err) {
@@ -277,6 +311,10 @@ async function apiFetch(path, opts = {}) {
277
311
  throw new RequestTimeoutError(timeoutMs, method);
278
312
  throw new NetworkError(err instanceof Error ? err.message : String(err));
279
313
  }
314
+ if (res.status >= 300 && res.status < 400) {
315
+ throw new ApiError(`The server answered with a redirect (HTTP ${res.status}); the CLI does not follow redirects. ` +
316
+ `Check PROMPTLIKE_API_URL (currently ${constants_1.API_BASE_URL}).`, res.status);
317
+ }
280
318
  // Reactive refresh: expired/invalid access token → refresh once, retry once.
281
319
  if (res.status === 401 && auth) {
282
320
  if (opts._retried)
@@ -286,7 +324,8 @@ async function apiFetch(path, opts = {}) {
286
324
  }
287
325
  if (res.status === 429) {
288
326
  const retryAfter = res.headers.get('retry-after');
289
- throw new Error(`Rate limited. Try again${retryAfter ? ` in ${retryAfter}s` : ' in a moment'}.`);
327
+ const wait = retryAfter && /^\d{1,6}$/.test(retryAfter.trim()) ? retryAfter.trim() : undefined;
328
+ throw new ApiError(`Rate limited. Try again${wait ? ` in ${wait}s` : ' in a moment'}.`, 429, 'RATE_LIMITED');
290
329
  }
291
330
  if (!res.ok) {
292
331
  throw await toError(res);
@@ -326,6 +365,20 @@ async function ensureAuthed() {
326
365
  await refreshSession();
327
366
  }
328
367
  }
368
+ /**
369
+ * Titles, descriptions and repo names come from the server (and, for shared
370
+ * repos, from other people). Strip terminal control sequences once, at the
371
+ * boundary, so no command can print an escape code by accident. Prompt BODIES
372
+ * are left alone here: `get`/`copy` must hand them over byte for byte.
373
+ */
374
+ function cleanPrompt(p) {
375
+ return {
376
+ ...p,
377
+ title: typeof p.title === 'string' ? (0, format_1.safeText)(p.title) : '',
378
+ description: typeof p.description === 'string' ? (0, format_1.safeText)(p.description) : p.description,
379
+ project_name: typeof p.project_name === 'string' ? (0, format_1.safeText)(p.project_name) : p.project_name,
380
+ };
381
+ }
329
382
  /** GET /api/prompts — list the user's prompts (optionally by tag / search / project). */
330
383
  async function listPrompts(params = {}) {
331
384
  const res = await apiFetch('/api/prompts', {
@@ -337,7 +390,7 @@ async function listPrompts(params = {}) {
337
390
  projectId: params.projectId,
338
391
  },
339
392
  });
340
- return res.prompts ?? [];
393
+ return (Array.isArray(res.prompts) ? res.prompts : []).map(cleanPrompt);
341
394
  }
342
395
  /**
343
396
  * POST /api/prompts/import — bulk-upload prompts into the account.
@@ -396,11 +449,66 @@ async function listProjects() {
396
449
  });
397
450
  return res.projects ?? [];
398
451
  }
452
+ const ROLES = ['owner', 'admin', 'editor', 'viewer'];
453
+ /**
454
+ * Validate one project row from the server instead of trusting its shape: a
455
+ * row without a string id/name is dropped, unknown visibility/role values fall
456
+ * back to the most restrictive reading ('private' / 'viewer').
457
+ */
458
+ function toRepoDetail(raw) {
459
+ if (typeof raw !== 'object' || raw === null)
460
+ return null;
461
+ const r = raw;
462
+ if (typeof r.id !== 'string' || !r.id || typeof r.name !== 'string')
463
+ return null;
464
+ const role = ROLES.includes(r.role) ? r.role : 'viewer';
465
+ return {
466
+ id: r.id,
467
+ name: (0, format_1.safeText)(r.name),
468
+ slug: typeof r.slug === 'string' ? (0, format_1.safeText)(r.slug) : null,
469
+ description: typeof r.description === 'string' ? (0, format_1.safeText)(r.description) : null,
470
+ visibility: r.visibility === 'public' ? 'public' : 'private',
471
+ role,
472
+ prompt_count: typeof r.prompt_count === 'number' ? r.prompt_count : 0,
473
+ member_count: typeof r.member_count === 'number' ? r.member_count : 0,
474
+ created_at: typeof r.created_at === 'string' ? r.created_at : null,
475
+ updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,
476
+ };
477
+ }
478
+ /** GET /api/projects — every repo you own or belong to, with visibility, role and counts. */
479
+ async function listProjectsDetailed() {
480
+ const res = await apiFetch('/api/projects', { query: { limit: 100 } });
481
+ return (Array.isArray(res.projects) ? res.projects : [])
482
+ .map(toRepoDetail)
483
+ .filter((p) => p !== null);
484
+ }
485
+ /** POST /api/projects — create a repo. The server enforces plan limit, name rules and slug uniqueness. */
486
+ async function createProject(input) {
487
+ const res = await apiFetch('/api/projects', {
488
+ method: 'POST',
489
+ body: {
490
+ name: input.name,
491
+ visibility: input.visibility,
492
+ ...(input.description ? { description: input.description } : {}),
493
+ },
494
+ });
495
+ const project = toRepoDetail(res.project);
496
+ if (!project)
497
+ throw new ApiError('The server created the repo but sent an unexpected response. Run `ple repo list` to check.', 502);
498
+ return { ...project, role: 'owner' };
499
+ }
500
+ /** PATCH /api/projects/{id} — change visibility (the server allows the owner only). */
501
+ async function setProjectVisibility(id, visibility) {
502
+ await apiFetch(`/api/projects/${encodeURIComponent(id)}`, {
503
+ method: 'PATCH',
504
+ body: { visibility },
505
+ });
506
+ }
399
507
  /** GET /api/prompts/{id} — full detail; returns null when not found (404). */
400
508
  async function getPromptById(id) {
401
509
  try {
402
510
  const res = await apiFetch(`/api/prompts/${id}`);
403
- return res.prompt ?? null;
511
+ return res.prompt ? cleanPrompt(res.prompt) : null;
404
512
  }
405
513
  catch (err) {
406
514
  if (err instanceof Error && /not found/i.test(err.message))
@@ -415,7 +523,7 @@ async function getPromptHistory(id) {
415
523
  throw new Error('Prompt not found.');
416
524
  return {
417
525
  id: res.prompt.id,
418
- title: res.prompt.title,
526
+ title: (0, format_1.safeText)(String(res.prompt.title ?? '')),
419
527
  current_version_id: res.prompt.current_version_id ?? null,
420
528
  versions: Array.isArray(res.prompt.versions) ? res.prompt.versions : [],
421
529
  };
@@ -430,6 +538,41 @@ async function rollbackPrompt(id, versionId) {
430
538
  body: { versionId },
431
539
  });
432
540
  }
541
+ /** GET /api/prompts/{id}/labels → current labels + the latest moves. */
542
+ async function listPromptLabels(id) {
543
+ const res = await apiFetch(`/api/prompts/${id}/labels`);
544
+ return { labels: res.labels ?? [], events: res.events ?? [] };
545
+ }
546
+ /** PUT /api/prompts/{id}/labels/{label} — point the label at a version (moving it leaves an audit event). */
547
+ async function setPromptLabel(id, label, versionId) {
548
+ return apiFetch(`/api/prompts/${id}/labels/${encodeURIComponent(label)}`, {
549
+ method: 'PUT',
550
+ body: { versionId },
551
+ });
552
+ }
553
+ /** DELETE /api/prompts/{id}/labels/{label}. */
554
+ async function clearPromptLabel(id, label) {
555
+ return apiFetch(`/api/prompts/${id}/labels/${encodeURIComponent(label)}`, { method: 'DELETE' });
556
+ }
557
+ /**
558
+ * GET /api/prompts/{id}?label=… → the version the label points at (content + number).
559
+ * Throws a readable error when the label does not exist.
560
+ */
561
+ async function getLabeledVersion(id, label) {
562
+ try {
563
+ const res = await apiFetch(`/api/prompts/${id}?label=${encodeURIComponent(label)}`);
564
+ const v = res.prompt?.labeled_version;
565
+ if (!v)
566
+ throw new Error(`Label '${label}' did not return a version.`);
567
+ return v;
568
+ }
569
+ catch (err) {
570
+ if (err instanceof ApiError && err.status === 404) {
571
+ throw new Error(`No label '${label}' on this prompt — see \`ple tag <name> --list\`.`);
572
+ }
573
+ throw err;
574
+ }
575
+ }
433
576
  /** Kullanım yüzeyleri — sunucudaki `USE_SURFACES` ile aynı küme (W1-1). */
434
577
  exports.USE_SURFACES = [
435
578
  'web', 'cli', 'mcp_tool', 'mcp_prompt', 'mcp_resource', 'extension', 'hook', 'repo', 'api', 'unknown',