promptlike 0.2.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,91 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getConfigPath = getConfigPath;
37
+ exports.readConfig = readConfig;
38
+ exports.writeConfig = writeConfig;
39
+ exports.clearConfig = clearConfig;
40
+ exports.isTokenExpiringSoon = isTokenExpiringSoon;
41
+ const fs = __importStar(require("fs"));
42
+ const os = __importStar(require("os"));
43
+ const path = __importStar(require("path"));
44
+ const CONFIG_DIR = path.join(os.homedir(), '.config', 'promptlike');
45
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
46
+ /** Config dosyasının tam yolu — debug çıktılarında göstermek için. */
47
+ function getConfigPath() {
48
+ return CONFIG_FILE;
49
+ }
50
+ /**
51
+ * Config'i diskten oku. Yoksa null döner — login gerekli demektir.
52
+ * Bozuk JSON varsa null döner ve dosyayı silmiyoruz; kullanıcı `ple logout`
53
+ * çağırsın diye log'ı sessiz tutuyoruz.
54
+ */
55
+ function readConfig() {
56
+ try {
57
+ if (!fs.existsSync(CONFIG_FILE))
58
+ return null;
59
+ const raw = fs.readFileSync(CONFIG_FILE, 'utf-8');
60
+ const parsed = JSON.parse(raw);
61
+ if (!parsed.access_token || !parsed.refresh_token)
62
+ return null;
63
+ return parsed;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /**
70
+ * Config'i diske yaz. Klasör yoksa oluştur, dosya izinlerini 0600 yap
71
+ * (sadece kullanıcı okuyabilir — token sızıntısı önlemi).
72
+ */
73
+ function writeConfig(config) {
74
+ if (!fs.existsSync(CONFIG_DIR)) {
75
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
76
+ }
77
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), {
78
+ mode: 0o600,
79
+ });
80
+ }
81
+ /** `ple logout` için: config dosyasını ve klasörünü sil. */
82
+ function clearConfig() {
83
+ if (fs.existsSync(CONFIG_FILE)) {
84
+ fs.unlinkSync(CONFIG_FILE);
85
+ }
86
+ }
87
+ /** Token'ın 60 saniye içinde sona erecek olup olmadığını kontrol et. */
88
+ function isTokenExpiringSoon(config) {
89
+ const now = Math.floor(Date.now() / 1000);
90
+ return config.expires_at - now < 60;
91
+ }
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ /**
3
+ * CLI configuration constants.
4
+ *
5
+ * The CLI talks to the PromptLikeEngineer **web API** (not Supabase directly),
6
+ * so it needs only a base URL — a public, non-secret value. Advanced users and
7
+ * self-hosters can point the CLI at another deployment via `PROMPTLIKE_API_URL`.
8
+ *
9
+ * Resolution order:
10
+ * 1. `PROMPTLIKE_API_URL` env var (override).
11
+ * 2. `BAKED_API_URL` below — the public production URL.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.WEB_APP_URL = exports.CLI_VERSION = exports.CLI_NAME = exports.API_BASE_URL = void 0;
15
+ const BAKED_API_URL = 'https://promptlikeengineer.com';
16
+ function resolveEnv(key, fallback) {
17
+ const value = process.env[key];
18
+ if (typeof value === 'string' && value.trim().length > 0) {
19
+ return value.trim();
20
+ }
21
+ return fallback;
22
+ }
23
+ /** Base URL of the web API the CLI calls (no trailing slash). */
24
+ exports.API_BASE_URL = resolveEnv('PROMPTLIKE_API_URL', BAKED_API_URL).replace(/\/+$/, '');
25
+ exports.CLI_NAME = 'ple';
26
+ exports.CLI_VERSION = '0.2.0';
27
+ /** Web app URL — shown to the user when their prompt list is empty. */
28
+ exports.WEB_APP_URL = 'https://promptlikeengineer.com';
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.c = void 0;
7
+ exports.timeAgo = timeAgo;
8
+ exports.shortId = shortId;
9
+ exports.truncate = truncate;
10
+ exports.joinPromptParts = joinPromptParts;
11
+ const chalk_1 = __importDefault(require("chalk"));
12
+ /**
13
+ * Tutarlı renk paleti — komutlar arasında aynı vurguları kullanmak için.
14
+ * chalk 4.x CommonJS uyumlu (5.x ESM only — kullanmıyoruz).
15
+ */
16
+ exports.c = {
17
+ title: chalk_1.default.bold.cyan,
18
+ label: chalk_1.default.dim,
19
+ success: chalk_1.default.green,
20
+ error: chalk_1.default.red,
21
+ warn: chalk_1.default.yellow,
22
+ accent: chalk_1.default.magenta,
23
+ muted: chalk_1.default.gray,
24
+ code: chalk_1.default.white.bgBlackBright,
25
+ };
26
+ /** Human-readable time delta — "now", "3h ago", "2d ago". */
27
+ function timeAgo(isoString) {
28
+ const then = new Date(isoString).getTime();
29
+ const now = Date.now();
30
+ const diff = Math.max(0, now - then);
31
+ const sec = Math.floor(diff / 1000);
32
+ if (sec < 60)
33
+ return 'now';
34
+ const min = Math.floor(sec / 60);
35
+ if (min < 60)
36
+ return `${min}m ago`;
37
+ const hr = Math.floor(min / 60);
38
+ if (hr < 24)
39
+ return `${hr}h ago`;
40
+ const day = Math.floor(hr / 24);
41
+ if (day < 7)
42
+ return `${day}d ago`;
43
+ const week = Math.floor(day / 7);
44
+ if (week < 5)
45
+ return `${week}w ago`;
46
+ const month = Math.floor(day / 30);
47
+ if (month < 12)
48
+ return `${month}mo ago`;
49
+ return `${Math.floor(day / 365)}y ago`;
50
+ }
51
+ /** ID'nin ilk 8 karakteri — listede yer kaplamasın diye. */
52
+ function shortId(id) {
53
+ return id.slice(0, 8);
54
+ }
55
+ /** Bir string'i maks N karakterde kes (sondaki "…"i dahil). */
56
+ function truncate(str, max) {
57
+ if (str.length <= max)
58
+ return str;
59
+ return str.slice(0, max - 1) + '…';
60
+ }
61
+ /** Üç parçalı içeriği (role/description/context) tek metne birleştir. */
62
+ function joinPromptParts(parts) {
63
+ // Eski kayıtlarda content tek alanda — onu önce dene
64
+ if (parts.content && parts.content.trim())
65
+ return parts.content;
66
+ const segments = [parts.role_text, parts.description_text, parts.context_text]
67
+ .map((s) => (s || '').trim())
68
+ .filter(Boolean);
69
+ return segments.join('\n\n---\n\n');
70
+ }
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ /**
3
+ * Loop Engineering API calls — variant generation + winner save.
4
+ *
5
+ * Kept separate from `api-client.ts` on purpose: these endpoints are
6
+ * Pro-gated and have their own 403 semantics ("upgrade to Pro"), which we
7
+ * translate here into clear, user-facing messages. Auth still rides on the
8
+ * same bearer token stored by `ple login` (callers run `ensureAuthed()`
9
+ * first, so the token is fresh).
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.requestVariants = requestVariants;
13
+ exports.saveWinner = saveWinner;
14
+ const constants_1 = require("./constants");
15
+ const config_1 = require("./config");
16
+ const NOT_LOGGED_IN = 'Not logged in. Run `ple login` first.';
17
+ const SESSION_EXPIRED = 'Session expired. Log in again: `ple login`';
18
+ /** The Pro upsell suffix — appended to every 403 from the loop endpoints. */
19
+ function proMessage(serverError) {
20
+ const base = serverError?.trim() || 'Loop requires Pro';
21
+ return `${base} — upgrade at ${constants_1.API_BASE_URL}/pricing`;
22
+ }
23
+ /**
24
+ * Minimal bearer POST used by the two loop calls. Mirrors the error mapping
25
+ * of `api-client.ts` (network / 401 / 403 / 429 / error body) without the
26
+ * refresh-retry machinery — `ensureAuthed()` has already refreshed the token.
27
+ */
28
+ async function bearerPost(path, body) {
29
+ const config = (0, config_1.readConfig)();
30
+ if (!config)
31
+ throw new Error(NOT_LOGGED_IN);
32
+ let res;
33
+ try {
34
+ res = await fetch(constants_1.API_BASE_URL + path, {
35
+ method: 'POST',
36
+ headers: {
37
+ 'Content-Type': 'application/json',
38
+ Authorization: `Bearer ${config.access_token}`,
39
+ },
40
+ body: JSON.stringify(body),
41
+ });
42
+ }
43
+ catch (err) {
44
+ throw new Error(`Cannot reach ${constants_1.API_BASE_URL}. Check your connection. (${err instanceof Error ? err.message : String(err)})`);
45
+ }
46
+ if (res.status === 401)
47
+ throw new Error(SESSION_EXPIRED);
48
+ let parsed = {};
49
+ try {
50
+ parsed = (await res.json());
51
+ }
52
+ catch {
53
+ // Non-JSON body — fall through to the generic messages below.
54
+ }
55
+ // Pro gate → 403; tükenen AI token bütçesi → 402 (ApiErrors.insufficientTokens).
56
+ if (res.status === 403)
57
+ throw new Error(proMessage(parsed.error));
58
+ if (res.status === 402) {
59
+ const base = parsed.error?.trim() || 'You are out of AI tokens';
60
+ throw new Error(`${base} — top up or wait for your monthly reset: ${constants_1.API_BASE_URL}/settings`);
61
+ }
62
+ if (res.status === 429) {
63
+ const retryAfter = res.headers.get('retry-after');
64
+ throw new Error(`Rate limited. Try again${retryAfter ? ` in ${retryAfter}s` : ' in a moment'}.`);
65
+ }
66
+ if (!res.ok) {
67
+ throw new Error(parsed.error || `Request failed (${res.status}).`);
68
+ }
69
+ return parsed;
70
+ }
71
+ /**
72
+ * POST /api/prompts/{id}/variants — ask the server to generate 2-3 AI
73
+ * variants of the prompt's current version.
74
+ */
75
+ async function requestVariants(promptId, opts = {}) {
76
+ const body = {
77
+ // Her tur ayrı bilinçli üretim: nonce, aynı dakikadaki idempotency
78
+ // çakışmasını (bedava üretim + sahte critical alarm) önler.
79
+ attempt: crypto.randomUUID(),
80
+ };
81
+ if (opts.count !== undefined)
82
+ body.count = opts.count;
83
+ if (opts.focus !== undefined && opts.focus.trim() !== '')
84
+ body.focus = opts.focus.trim();
85
+ const res = await bearerPost(`/api/prompts/${promptId}/variants`, body);
86
+ return { variants: res.variants ?? [], tokensUsed: res.tokensUsed ?? 0 };
87
+ }
88
+ /**
89
+ * Save the winning variant as a new version of the prompt via the existing
90
+ * save endpoint (update path — no `isNew`). Section mapping: the variant's
91
+ * `role`/`instruction`/`context` land in the prompt's three-part structure
92
+ * as role / description / context respectively.
93
+ */
94
+ async function saveWinner(promptId, variant, changelog) {
95
+ return bearerPost('/api/prompts', {
96
+ id: promptId,
97
+ roleText: variant.role || '',
98
+ descriptionText: variant.instruction || '',
99
+ contextText: variant.context || '',
100
+ changelog,
101
+ source: 'cli',
102
+ });
103
+ }
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ /**
3
+ * Loop Engineering terminal UX — variant rendering, interactive selection,
4
+ * and the `--exec` variant test-runner.
5
+ *
6
+ * Shared by `ple improve` (single round) and `ple loop` (multi-round).
7
+ * All interactive I/O lives here so the command modules stay testable
8
+ * (tests mock `selectVariant` / `confirmContinue` and keep the rest real).
9
+ */
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.estimateTokens = estimateTokens;
45
+ exports.variantText = variantText;
46
+ exports.renderVariant = renderVariant;
47
+ exports.renderVariants = renderVariants;
48
+ exports.selectVariant = selectVariant;
49
+ exports.confirmContinue = confirmContinue;
50
+ exports.runExec = runExec;
51
+ exports.printExecResult = printExecResult;
52
+ const readline = __importStar(require("readline"));
53
+ const child_process_1 = require("child_process");
54
+ const format_1 = require("./format");
55
+ /** Rough token estimate — chars/4 is the usual English heuristic. */
56
+ function estimateTokens(text) {
57
+ return Math.ceil(text.length / 4);
58
+ }
59
+ /** Join a variant's three sections into the full prompt text. */
60
+ function variantText(variant) {
61
+ return (0, format_1.joinPromptParts)({
62
+ role_text: variant.role,
63
+ description_text: variant.instruction,
64
+ context_text: variant.context,
65
+ });
66
+ }
67
+ const STRATEGY_LABELS = {
68
+ concise: 'CONCISE',
69
+ structured: 'STRUCTURED',
70
+ cot: 'CHAIN-OF-THOUGHT',
71
+ };
72
+ const PREVIEW_MAX = 160;
73
+ function printSectionPreview(label, text) {
74
+ if (!text || !text.trim())
75
+ return;
76
+ console.log(` ${format_1.c.label(label)} ${(0, format_1.truncate)(text.trim().replace(/\s+/g, ' '), PREVIEW_MAX)}`);
77
+ }
78
+ /**
79
+ * Render one numbered variant card: strategy header, rationale, shortened
80
+ * section previews and a size comparison against the current version.
81
+ */
82
+ function renderVariant(variant, index, baselineText) {
83
+ const full = variantText(variant);
84
+ const chars = full.length;
85
+ const tokens = estimateTokens(full);
86
+ const delta = chars - baselineText.length;
87
+ const deltaLabel = baselineText.length > 0
88
+ ? ` (${delta >= 0 ? '+' : ''}${delta} chars vs current)`
89
+ : '';
90
+ console.log();
91
+ console.log(`${format_1.c.title(`[${index}]`)} ${format_1.c.accent(STRATEGY_LABELS[variant.strategy] ?? variant.strategy.toUpperCase())} ${format_1.c.muted(`· ${chars} chars · ~${tokens} tokens${deltaLabel}`)}`);
92
+ if (variant.rationale?.trim()) {
93
+ console.log(` ${format_1.c.warn('why:')} ${variant.rationale.trim()}`);
94
+ }
95
+ printSectionPreview('role: ', variant.role);
96
+ printSectionPreview('instruction:', variant.instruction);
97
+ printSectionPreview('context: ', variant.context);
98
+ }
99
+ /** Render every variant (used when there's no per-variant exec output). */
100
+ function renderVariants(variants, baselineText) {
101
+ variants.forEach((v, i) => renderVariant(v, i + 1, baselineText));
102
+ }
103
+ /** Ask a single readline question; resolves null on Ctrl-C / closed stdin. */
104
+ function ask(question) {
105
+ return new Promise((resolve) => {
106
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
107
+ let settled = false;
108
+ const settle = (value) => {
109
+ if (settled)
110
+ return;
111
+ settled = true;
112
+ rl.close();
113
+ resolve(value);
114
+ };
115
+ rl.on('SIGINT', () => {
116
+ console.error(''); // move past the ^C
117
+ settle(null);
118
+ });
119
+ rl.on('close', () => settle(null));
120
+ rl.question(question, (answer) => settle(answer));
121
+ });
122
+ }
123
+ /**
124
+ * Interactive winner selection. Returns 1..max, or 0 for cancel
125
+ * (explicit `0`, empty Ctrl-C, or closed stdin — all safe exits).
126
+ */
127
+ async function selectVariant(max) {
128
+ // Not a TTY (piped stdin) — never hang waiting for a human.
129
+ if (!process.stdin.isTTY) {
130
+ console.error(format_1.c.warn('No interactive terminal — cannot pick a variant. Nothing saved.'));
131
+ return 0;
132
+ }
133
+ for (;;) {
134
+ const answer = await ask(format_1.c.label(`Pick a winner [1-${max}], 0 to cancel: `));
135
+ if (answer === null)
136
+ return 0;
137
+ const n = Number.parseInt(answer.trim(), 10);
138
+ if (!Number.isNaN(n) && n >= 0 && n <= max)
139
+ return n;
140
+ console.error(format_1.c.warn(`Please enter a number between 0 and ${max}.`));
141
+ }
142
+ }
143
+ /** "Continue to next round? (y/n)" — defaults to no on anything unclear. */
144
+ async function confirmContinue() {
145
+ if (!process.stdin.isTTY)
146
+ return false;
147
+ const answer = await ask(format_1.c.label('Continue to next round? (y/n) '));
148
+ return answer !== null && /^y(es)?$/i.test(answer.trim());
149
+ }
150
+ /**
151
+ * Run the user's command against one variant. The prompt text is delivered
152
+ * as the `PLE_PROMPT` env var AND on stdin; a literal `{}` in the command is
153
+ * replaced with the (single-quoted) prompt text. `shell: true` is deliberate:
154
+ * this is the user's own command on their own machine (à la `find -exec` /
155
+ * `xargs`), not remote input.
156
+ */
157
+ async function runExec(command, promptText, opts = {}) {
158
+ const timeoutMs = opts.timeoutMs ?? 60000;
159
+ const maxLines = opts.maxLines ?? 20;
160
+ // POSIX single-quote escaping for the {} placeholder.
161
+ const quoted = `'${promptText.replace(/'/g, `'\\''`)}'`;
162
+ const finalCommand = command.includes('{}') ? command.split('{}').join(quoted) : command;
163
+ return new Promise((resolve) => {
164
+ const child = (0, child_process_1.spawn)(finalCommand, {
165
+ shell: true,
166
+ env: { ...process.env, PLE_PROMPT: promptText },
167
+ stdio: ['pipe', 'pipe', 'pipe'],
168
+ });
169
+ let stdout = '';
170
+ let stderr = '';
171
+ let timedOut = false;
172
+ const timer = setTimeout(() => {
173
+ timedOut = true;
174
+ child.kill('SIGKILL');
175
+ }, timeoutMs);
176
+ child.stdout.on('data', (chunk) => {
177
+ stdout += chunk.toString();
178
+ });
179
+ child.stderr.on('data', (chunk) => {
180
+ stderr += chunk.toString();
181
+ });
182
+ // Commands that never read stdin close the pipe — ignore the EPIPE.
183
+ child.stdin.on('error', () => { });
184
+ child.stdin.write(promptText);
185
+ child.stdin.end();
186
+ child.on('error', (err) => {
187
+ clearTimeout(timer);
188
+ resolve({
189
+ lines: [`(failed to run: ${err.message})`],
190
+ truncated: false,
191
+ exitCode: null,
192
+ timedOut: false,
193
+ });
194
+ });
195
+ child.on('close', (code) => {
196
+ clearTimeout(timer);
197
+ const raw = stdout.trim() !== '' ? stdout : stderr;
198
+ const allLines = raw.replace(/\n+$/, '').split('\n');
199
+ const truncated = allLines.length > maxLines;
200
+ resolve({
201
+ lines: allLines.slice(0, maxLines),
202
+ truncated,
203
+ exitCode: code,
204
+ timedOut,
205
+ });
206
+ });
207
+ });
208
+ }
209
+ /** Print an exec result under its variant card. */
210
+ function printExecResult(result) {
211
+ if (result.timedOut) {
212
+ console.log(` ${format_1.c.error('exec timed out (60s)')}`);
213
+ return;
214
+ }
215
+ const status = result.exitCode === 0 ? format_1.c.success('exit 0') : format_1.c.error(`exit ${result.exitCode ?? '?'}`);
216
+ console.log(` ${format_1.c.label('── exec output')} ${status} ${format_1.c.label('──')}`);
217
+ for (const line of result.lines) {
218
+ console.log(` ${format_1.c.muted('│')} ${line}`);
219
+ }
220
+ if (result.truncated) {
221
+ console.log(` ${format_1.c.muted('│ … output truncated')}`);
222
+ }
223
+ }
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolvePromptByName = resolvePromptByName;
4
+ exports.fetchPromptContent = fetchPromptContent;
5
+ const format_1 = require("./format");
6
+ const api_client_1 = require("./api-client");
7
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+ const SHORT_ID_RE = /^[0-9a-f]{8,}$/i;
9
+ /**
10
+ * Resolve a user-supplied `<name>` argument to a single prompt.
11
+ * - Full UUID → direct detail lookup.
12
+ * - 8+ hex-char short-id prefix → match a page of the user's prompts client-side.
13
+ * - Otherwise → title/description search (server-side, escaped), preferring
14
+ * title matches.
15
+ * - One match → return it. Multiple → print the candidates and return null.
16
+ *
17
+ * Throws on auth/network errors (the command wrapper catches them).
18
+ */
19
+ async function resolvePromptByName(name) {
20
+ const trimmed = name.trim();
21
+ if (!trimmed) {
22
+ throw new Error('Cannot resolve an empty name.');
23
+ }
24
+ // 1) Full UUID → detail endpoint.
25
+ if (UUID_RE.test(trimmed)) {
26
+ const found = await (0, api_client_1.getPromptById)(trimmed);
27
+ if (found)
28
+ return found;
29
+ // Not found by id — fall through to a title search.
30
+ }
31
+ // 2) Short-id prefix (hex, 8+ chars, not a full UUID) → match a page.
32
+ if (!UUID_RE.test(trimmed) && SHORT_ID_RE.test(trimmed)) {
33
+ const page = await (0, api_client_1.listPrompts)({ limit: 100 });
34
+ const lower = trimmed.toLowerCase();
35
+ const matches = page.filter((p) => p.id.toLowerCase().startsWith(lower));
36
+ if (matches.length === 1)
37
+ return matches[0];
38
+ if (matches.length > 1) {
39
+ printAmbiguous(trimmed, matches);
40
+ return null;
41
+ }
42
+ // No id match — fall through to a title search.
43
+ }
44
+ // 3) Title / description search.
45
+ const results = await (0, api_client_1.listPrompts)({ search: trimmed, limit: 100 });
46
+ const lower = trimmed.toLowerCase();
47
+ const titleMatches = results.filter((p) => p.title.toLowerCase().includes(lower));
48
+ const pool = titleMatches.length > 0 ? titleMatches : results;
49
+ if (pool.length === 0) {
50
+ console.error(format_1.c.error(`No prompt matched '${trimmed}'.`));
51
+ return null;
52
+ }
53
+ if (pool.length === 1)
54
+ return pool[0];
55
+ // Disambiguate on an exact (case-insensitive) title match if unique.
56
+ const exact = pool.filter((p) => p.title.toLowerCase() === lower);
57
+ if (exact.length === 1)
58
+ return exact[0];
59
+ printAmbiguous(trimmed, pool);
60
+ return null;
61
+ }
62
+ function printAmbiguous(query, rows) {
63
+ console.error(format_1.c.warn(`'${query}' matched multiple prompts. Use a more specific name or short id:`));
64
+ for (const r of rows.slice(0, 10)) {
65
+ console.error(` ${format_1.c.muted((0, format_1.shortId)(r.id))} ${r.title}`);
66
+ }
67
+ }
68
+ /**
69
+ * Extract the resolved prompt's current-version content. The content is already
70
+ * present on the resolved item (list/detail return it inline), so this is a
71
+ * plain accessor — no extra request.
72
+ */
73
+ function fetchPromptContent(prompt) {
74
+ return prompt.current_version ?? null;
75
+ }
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ /**
3
+ * Prompt değişkenleri (`{{ad}}`) — CLI yerel kopyası.
4
+ *
5
+ * Web tarafındaki `src/lib/prompt-variables.ts` ile BİREBİR aynı mantık. CLI
6
+ * ayrı bir npm paketi olduğu için web'den import edemiyor; bu yüzden küçük,
7
+ * bağımlılıksız util burada tekrarlanıyor. Birini değiştirirken diğerini de
8
+ * güncelle (ya da ileride shared/ altına taşıyıp sync-types ile senkronla).
9
+ *
10
+ * Syntax: `{{ad}}`, içeride whitespace tolere, Unicode adlar (Türkçe dahil).
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.extractVariables = extractVariables;
14
+ exports.fillVariables = fillVariables;
15
+ const VARIABLE_PATTERN = /\{\{\s*([\p{L}\p{N}_.-]+)\s*\}\}/gu;
16
+ /** Metindeki benzersiz değişken adları, ilk görülme sırasıyla. */
17
+ function extractVariables(text) {
18
+ if (!text)
19
+ return [];
20
+ const seen = new Set();
21
+ const result = [];
22
+ for (const match of text.matchAll(VARIABLE_PATTERN)) {
23
+ const name = match[1];
24
+ if (!seen.has(name)) {
25
+ seen.add(name);
26
+ result.push(name);
27
+ }
28
+ }
29
+ return result;
30
+ }
31
+ /**
32
+ * `{{ad}}` yer tutucularını doldurur. Bulunmayan/boş değer çıktıda `{{ad}}`
33
+ * olarak kalır (sessizce silinmez).
34
+ */
35
+ function fillVariables(text, values) {
36
+ if (!text)
37
+ return '';
38
+ return text.replace(VARIABLE_PATTERN, (whole, name) => {
39
+ const value = values[name];
40
+ return value !== undefined && value !== '' ? value : whole;
41
+ });
42
+ }