promptlike 0.8.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +270 -28
  3. package/dist/commands/config.js +13 -0
  4. package/dist/commands/copy.js +22 -7
  5. package/dist/commands/get.js +17 -3
  6. package/dist/commands/import.js +30 -128
  7. package/dist/commands/importCheck.js +304 -0
  8. package/dist/commands/importGithub.js +171 -0
  9. package/dist/commands/list.js +83 -17
  10. package/dist/commands/local.js +35 -12
  11. package/dist/commands/login.js +6 -5
  12. package/dist/commands/search.js +73 -7
  13. package/dist/commands/show.js +11 -3
  14. package/dist/commands/sync.js +57 -13
  15. package/dist/commands/tag.js +86 -0
  16. package/dist/help.js +1 -1
  17. package/dist/index.js +7 -0
  18. package/dist/lib/api-client.js +39 -0
  19. package/dist/lib/errors.js +4 -0
  20. package/dist/lib/format.js +28 -0
  21. package/dist/lib/frontmatter.js +86 -4
  22. package/dist/lib/github.js +208 -0
  23. package/dist/lib/githubCache.js +118 -0
  24. package/dist/lib/githubHttp.js +197 -0
  25. package/dist/lib/githubImport.js +238 -0
  26. package/dist/lib/githubSelect.js +148 -0
  27. package/dist/lib/githubSnapshot.js +67 -0
  28. package/dist/lib/githubSpec.js +78 -0
  29. package/dist/lib/importOrigins.js +36 -0
  30. package/dist/lib/importShared.js +179 -0
  31. package/dist/lib/licenses.js +243 -0
  32. package/dist/lib/localStore.js +52 -10
  33. package/dist/lib/loopApi.js +63 -11
  34. package/dist/lib/promptResolver.js +22 -9
  35. package/dist/lib/promptSource.js +123 -0
  36. package/dist/lib/promptTemplate.js +189 -0
  37. package/dist/lib/promptVariables.js +7 -40
  38. package/dist/lib/rank.js +30 -13
  39. package/dist/lib/settings.js +24 -3
  40. package/dist/lib/tagFilter.js +40 -0
  41. package/dist/lib/updateCheck.js +296 -0
  42. package/dist/lib/upstreamCheck.js +71 -0
  43. package/dist/program.js +41 -10
  44. package/package.json +1 -1
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ /**
3
+ * What `ple import --scan` and `ple import github:…` have in common: parsing a
4
+ * pick ("1,3-5", "all"), asking, a free local slug, and uploading a batch to
5
+ * the account with the same plan-limit and partial-failure reporting.
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.BATCH = void 0;
42
+ exports.parseSelection = parseSelection;
43
+ exports.formatSize = formatSize;
44
+ exports.defaultAsk = defaultAsk;
45
+ exports.freeSlug = freeSlug;
46
+ exports.chooseRows = chooseRows;
47
+ exports.uploadPrompts = uploadPrompts;
48
+ const readline = __importStar(require("readline"));
49
+ const api_client_1 = require("./api-client");
50
+ const constants_1 = require("./constants");
51
+ const format_1 = require("./format");
52
+ const store = __importStar(require("./localStore"));
53
+ /** The import endpoint caps one request at 50 records. */
54
+ exports.BATCH = 50;
55
+ /**
56
+ * Parse a pick like `1,3-5`, `all`, or empty (cancel). Returns 0-based
57
+ * indices, `null` for cancel; throws on anything out of range or malformed.
58
+ */
59
+ function parseSelection(input, count) {
60
+ const v = input.trim().toLowerCase();
61
+ if (v === '' || v === 'q' || v === 'n' || v === 'none')
62
+ return null;
63
+ if (v === 'a' || v === 'all' || v === '*')
64
+ return Array.from({ length: count }, (_, i) => i);
65
+ const picked = new Set();
66
+ for (const part of v.split(/[\s,]+/).filter(Boolean)) {
67
+ const range = part.match(/^(\d+)-(\d+)$/);
68
+ const single = part.match(/^(\d+)$/);
69
+ if (range) {
70
+ const a = Number(range[1]);
71
+ const b = Number(range[2]);
72
+ if (a < 1 || b > count || a > b)
73
+ throw new Error(`'${part}' is out of range (1-${count}).`);
74
+ for (let i = a; i <= b; i++)
75
+ picked.add(i - 1);
76
+ }
77
+ else if (single) {
78
+ const n = Number(single[1]);
79
+ if (n < 1 || n > count)
80
+ throw new Error(`'${part}' is out of range (1-${count}).`);
81
+ picked.add(n - 1);
82
+ }
83
+ else {
84
+ throw new Error(`Could not read '${part}'. Use numbers like 1,3-5 or 'all'.`);
85
+ }
86
+ }
87
+ return [...picked].sort((x, y) => x - y);
88
+ }
89
+ function formatSize(bytes) {
90
+ return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
91
+ }
92
+ function defaultAsk(question) {
93
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
94
+ return new Promise((resolve) => {
95
+ rl.question(question, (answer) => {
96
+ rl.close();
97
+ resolve(answer);
98
+ });
99
+ });
100
+ }
101
+ /** Local slug that does not overwrite a different existing prompt. */
102
+ function freeSlug(title) {
103
+ const base = store.slugify(title.replace(/[/\\:]+/g, '-'));
104
+ let slug = base;
105
+ for (let n = 2; store.exists(slug); n++)
106
+ slug = `${base}-${n}`;
107
+ return slug;
108
+ }
109
+ /**
110
+ * Which of `rows` to import: all with `--all`, a pick on a terminal, nothing
111
+ * (with a hint) otherwise. Returns null when nothing was chosen.
112
+ */
113
+ async function chooseRows(rows, all, deps) {
114
+ if (all)
115
+ return rows;
116
+ const interactive = deps.isTTY ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
117
+ if (!interactive) {
118
+ console.log(format_1.c.muted(`\nNot a terminal — re-run with --all to import these ${rows.length}, or --dry-run to only look.`));
119
+ return null;
120
+ }
121
+ const answer = await (deps.ask ?? defaultAsk)(`\nImport which? [all | 1,3-5 | Enter to cancel]: `);
122
+ const picked = parseSelection(answer, rows.length);
123
+ if (!picked || picked.length === 0) {
124
+ console.log(format_1.c.muted('Cancelled — nothing imported.'));
125
+ return null;
126
+ }
127
+ return picked.map((i) => rows[i]);
128
+ }
129
+ /**
130
+ * Upload to the signed-in account in batches of {@link BATCH}: say the plan
131
+ * limit BEFORE uploading, then report what landed, what was a duplicate, what
132
+ * hit the limit and what failed. `retryCommand` is what to run again.
133
+ */
134
+ async function uploadPrompts(payload, opts) {
135
+ const headroom = await (0, api_client_1.getAccountHeadroom)();
136
+ if (headroom.promptsRemaining !== null && payload.length > headroom.promptsRemaining) {
137
+ console.log(format_1.c.warn(`Your plan has room for ${headroom.promptsRemaining} more prompt${headroom.promptsRemaining === 1 ? '' : 's'}; ` +
138
+ `the first ${headroom.promptsRemaining} of ${payload.length} will be imported.`));
139
+ }
140
+ let imported = 0;
141
+ let skippedDuplicate = 0;
142
+ let truncatedByQuota = 0;
143
+ let failed = 0;
144
+ let abortMessage = null;
145
+ for (let i = 0; i < payload.length; i += exports.BATCH) {
146
+ try {
147
+ const res = await (0, api_client_1.importPrompts)(payload.slice(i, i + exports.BATCH), {
148
+ source: 'import',
149
+ projectId: opts.projectId,
150
+ fallbackToExistingProject: !opts.projectId,
151
+ });
152
+ imported += res.imported;
153
+ skippedDuplicate += res.skippedDuplicate;
154
+ truncatedByQuota += res.truncatedByQuota;
155
+ failed += res.failed + res.skippedInvalid;
156
+ }
157
+ catch (err) {
158
+ abortMessage = err instanceof Error ? err.message : String(err);
159
+ truncatedByQuota += payload.length - i;
160
+ break;
161
+ }
162
+ }
163
+ console.log(format_1.c.success(`✓ Imported ${imported} prompt${imported === 1 ? '' : 's'} into your account`));
164
+ if (skippedDuplicate > 0)
165
+ console.log(format_1.c.muted(` ${skippedDuplicate} already there — skipped`));
166
+ if (abortMessage)
167
+ console.log(format_1.c.warn(`⚠ Stopped early: ${abortMessage}`));
168
+ if (truncatedByQuota > 0) {
169
+ console.log(format_1.c.warn(`⚠ ${truncatedByQuota} not imported — plan prompt limit reached.`));
170
+ // Deneme vaadi YOK: deneme web'de bayrakla (NEXT_PUBLIC_PRO_TRIAL_DAYS) açılır
171
+ // kapanır; CLI bayrağı bilemez, kapalıyken "14-day trial" yanlış söz olurdu.
172
+ console.log(format_1.c.muted(` Upgrade to Pro to bring the rest: ${constants_1.WEB_APP_URL}/pricing`));
173
+ console.log(format_1.c.muted(` Then run \`${opts.retryCommand}\` again — what already came in is skipped.`));
174
+ }
175
+ if (failed > 0)
176
+ console.log(format_1.c.warn(`⚠ ${failed} failed. Re-run \`${opts.retryCommand}\` to retry those.`));
177
+ if (imported > 0)
178
+ console.log(format_1.c.muted(`Open them at ${constants_1.WEB_APP_URL}/dashboard or \`ple list\`.`));
179
+ }
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ /**
3
+ * License gate for `ple import github:…`: a file is copied only when it has an
4
+ * open license. Nobody can import something the author did not allow copying.
5
+ *
6
+ * Which license applies to a file — the CLOSEST declaration wins:
7
+ * (a) the file's own `license:` frontmatter line (an SPDX id or a common name);
8
+ * a value that points at a file ("see LICENSE.txt") continues with (b);
9
+ * (b) the nearest LICENSE / LICENCE / COPYING file — in the file's folder, then
10
+ * each parent up to the repo root. A closer file that is not recognized
11
+ * BLOCKS; it never falls back to the repo-wide license;
12
+ * (c) only when no license file exists on the way up: the license GitHub
13
+ * reports for the repo.
14
+ * Anything not on the allowed list (all rights reserved, NonCommercial,
15
+ * NoDerivatives, custom or source-available terms, no license at all) blocks.
16
+ *
17
+ * Pure except for `LicenseEnv.readText`, which the caller supplies.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.SHARE_ALIKE_NOTE = exports.ALLOWED_SPDX = void 0;
21
+ exports.normalizeLicenseName = normalizeLicenseName;
22
+ exports.pointsToLicenseFile = pointsToLicenseFile;
23
+ exports.detectLicenseText = detectLicenseText;
24
+ exports.extractCopyright = extractCopyright;
25
+ exports.indexLicenseFiles = indexLicenseFiles;
26
+ exports.closestLicenseFile = closestLicenseFile;
27
+ exports.checkLicense = checkLicense;
28
+ const github_1 = require("./github");
29
+ /** Open licenses a prompt may be copied under. */
30
+ exports.ALLOWED_SPDX = [
31
+ 'MIT',
32
+ 'MIT-0',
33
+ 'Apache-2.0',
34
+ 'BSD-2-Clause',
35
+ 'BSD-3-Clause',
36
+ 'ISC',
37
+ '0BSD',
38
+ 'Unlicense',
39
+ 'CC0-1.0',
40
+ 'CC-BY-4.0',
41
+ 'CC-BY-SA-4.0',
42
+ ];
43
+ exports.SHARE_ALIKE_NOTE = 'CC BY-SA: if you change it and make it public, keep the same license';
44
+ // ---------------------------------------------------------------------------
45
+ // Names → SPDX
46
+ // ---------------------------------------------------------------------------
47
+ const ALIASES = {
48
+ mit: 'MIT',
49
+ 'mit-license': 'MIT',
50
+ 'the-mit-license': 'MIT',
51
+ 'mit-0': 'MIT-0',
52
+ 'mit-no-attribution': 'MIT-0',
53
+ 'apache-2.0': 'Apache-2.0',
54
+ 'apache-2': 'Apache-2.0',
55
+ apache2: 'Apache-2.0',
56
+ 'apache-license-2.0': 'Apache-2.0',
57
+ 'apache-license-version-2.0': 'Apache-2.0',
58
+ 'apache-license-v2.0': 'Apache-2.0',
59
+ 'apache-license-v2': 'Apache-2.0',
60
+ 'apache-v2.0': 'Apache-2.0',
61
+ 'apache-v2': 'Apache-2.0',
62
+ 'bsd-2-clause': 'BSD-2-Clause',
63
+ 'bsd-2': 'BSD-2-Clause',
64
+ 'bsd-2-clause-license': 'BSD-2-Clause',
65
+ 'simplified-bsd': 'BSD-2-Clause',
66
+ 'bsd-3-clause': 'BSD-3-Clause',
67
+ 'bsd-3': 'BSD-3-Clause',
68
+ 'bsd-3-clause-license': 'BSD-3-Clause',
69
+ 'new-bsd': 'BSD-3-Clause',
70
+ 'modified-bsd': 'BSD-3-Clause',
71
+ isc: 'ISC',
72
+ 'isc-license': 'ISC',
73
+ '0bsd': '0BSD',
74
+ unlicense: 'Unlicense',
75
+ 'the-unlicense': 'Unlicense',
76
+ cc0: 'CC0-1.0',
77
+ 'cc0-1.0': 'CC0-1.0',
78
+ 'cc0-1.0-universal': 'CC0-1.0',
79
+ 'cc-0': 'CC0-1.0',
80
+ 'cc-by-4.0': 'CC-BY-4.0',
81
+ 'cc-by-4.0-international': 'CC-BY-4.0',
82
+ 'creative-commons-attribution-4.0': 'CC-BY-4.0',
83
+ 'creative-commons-attribution-4.0-international': 'CC-BY-4.0',
84
+ 'cc-by-sa-4.0': 'CC-BY-SA-4.0',
85
+ 'cc-by-sa-4.0-international': 'CC-BY-SA-4.0',
86
+ 'creative-commons-attribution-sharealike-4.0': 'CC-BY-SA-4.0',
87
+ 'creative-commons-attribution-sharealike-4.0-international': 'CC-BY-SA-4.0',
88
+ };
89
+ /**
90
+ * A license name as people write it in frontmatter → its SPDX id. Case does
91
+ * not matter; "MIT License", "Apache 2.0", "CC BY 4.0", "CC0" all work. A
92
+ * plain id this module does not know ("GPL-3.0") is passed through so it can
93
+ * be reported — it is simply not on the allowed list. Anything else → null.
94
+ */
95
+ function normalizeLicenseName(value) {
96
+ const trimmed = value.trim();
97
+ const key = trimmed
98
+ .toLowerCase()
99
+ .replace(/["'`()]/g, '')
100
+ .replace(/[^a-z0-9.]+/g, '-')
101
+ .replace(/^-+|-+$/g, '');
102
+ if (ALIASES[key])
103
+ return ALIASES[key];
104
+ const exact = exports.ALLOWED_SPDX.find((id) => id.toLowerCase() === trimmed.toLowerCase());
105
+ if (exact)
106
+ return exact;
107
+ return /^[A-Za-z0-9][A-Za-z0-9.+-]{0,63}$/.test(trimmed) ? trimmed : null;
108
+ }
109
+ /** "See LICENSE.txt", "Complete terms in LICENSE" — the value names a file instead of a license. */
110
+ function pointsToLicenseFile(value) {
111
+ return /\b(?:licen[sc]e|copying)\b/i.test(value);
112
+ }
113
+ // ---------------------------------------------------------------------------
114
+ // License text → SPDX
115
+ // ---------------------------------------------------------------------------
116
+ /** Terms that turn a permissive-looking text into something that is not open. */
117
+ const RESTRICTIONS = /commons clause|non-?commercial|no[- ]?derivatives?|noderivs|advertising materials mentioning features/;
118
+ /**
119
+ * Recognizes a license by its characteristic sentences (whitespace and case
120
+ * do not matter). Unknown text → null, which blocks.
121
+ */
122
+ function detectLicenseText(text) {
123
+ const t = text.replace(/\s+/g, ' ').toLowerCase();
124
+ const has = (s) => t.includes(s);
125
+ if (has('cc0 1.0 universal'))
126
+ return 'CC0-1.0';
127
+ if (has('attribution-sharealike 4.0 international'))
128
+ return 'CC-BY-SA-4.0';
129
+ if (has('attribution 4.0 international') && !/sharealike|non-?commercial|no ?derivatives?|noderivs/.test(t))
130
+ return 'CC-BY-4.0';
131
+ if (/creative commons/.test(t) || RESTRICTIONS.test(t))
132
+ return null;
133
+ if (has('this is free and unencumbered software released into the public domain'))
134
+ return 'Unlicense';
135
+ if (has('apache license') && has('version 2.0'))
136
+ return 'Apache-2.0';
137
+ if (has('mit no attribution'))
138
+ return 'MIT-0';
139
+ if (has('permission is hereby granted, free of charge'))
140
+ return 'MIT';
141
+ if (has('redistribution and use in source and binary forms')) {
142
+ return has('neither the name') ? 'BSD-3-Clause' : 'BSD-2-Clause';
143
+ }
144
+ if (has('permission to use, copy, modify, and/or distribute this software for any purpose with or without fee')) {
145
+ return has('provided that the above copyright notice') ? 'ISC' : '0BSD';
146
+ }
147
+ return null;
148
+ }
149
+ /**
150
+ * Copyright notice line: "Copyright (c) 2025 Name", "Copyright 2025 Name",
151
+ * "© 2025 Name". Placeholders from license templates ("Copyright [yyyy] [name
152
+ * of copyright owner]") and legal prose that happens to start the same way
153
+ * ("copyright license to reproduce …", Apache's "(c) You must retain …") are
154
+ * not notices.
155
+ */
156
+ const NOTICE = /^\s*(?:copyright\s*(?:\(c\)|©)|copyright\s+(?:19|20)\d{2}|©|\(c\)\s*(?:19|20)\d{2})/i;
157
+ const PLACEHOLDER = /\[(?:yyyy|year)\]|\[name of copyright owner\]|<year>|<(?:copyright )?holders?>|\{(?:yyyy|year)\}/i;
158
+ function extractCopyright(text) {
159
+ for (const line of text.split(/\r?\n/)) {
160
+ if (NOTICE.test(line) && !PLACEHOLDER.test(line))
161
+ return line.trim().slice(0, 200);
162
+ }
163
+ return undefined;
164
+ }
165
+ // ---------------------------------------------------------------------------
166
+ // Which license file belongs to a file
167
+ // ---------------------------------------------------------------------------
168
+ const LICENSE_FILE = /^(LICENSE|LICENCE|COPYING)(\.(md|txt))?$/i;
169
+ /** Lower is better: plain LICENSE first, then .md, .txt, then LICENCE, COPYING. */
170
+ function fileRank(name) {
171
+ const base = name.toUpperCase();
172
+ const kind = base.startsWith('LICENSE') ? 0 : base.startsWith('LICENCE') ? 3 : 6;
173
+ return kind + (base.endsWith('.MD') ? 1 : base.endsWith('.TXT') ? 2 : 0);
174
+ }
175
+ const dirOf = (p) => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '');
176
+ const baseOf = (p) => p.slice(p.lastIndexOf('/') + 1);
177
+ /** folder → its license files (best first), for every folder that has one. */
178
+ function indexLicenseFiles(paths) {
179
+ const index = new Map();
180
+ for (const p of paths) {
181
+ if (!LICENSE_FILE.test(baseOf(p)))
182
+ continue;
183
+ const dir = dirOf(p);
184
+ index.set(dir, [...(index.get(dir) ?? []), p]);
185
+ }
186
+ for (const [dir, files] of index) {
187
+ index.set(dir, files.sort((a, b) => fileRank(baseOf(a)) - fileRank(baseOf(b)) || (a < b ? -1 : a > b ? 1 : 0)));
188
+ }
189
+ return index;
190
+ }
191
+ /** The license file in the file's folder, else the nearest parent's. */
192
+ function closestLicenseFile(index, filePath) {
193
+ let dir = dirOf(filePath);
194
+ for (;;) {
195
+ const hit = index.get(dir)?.[0];
196
+ if (hit)
197
+ return hit;
198
+ if (dir === '')
199
+ return null;
200
+ dir = dirOf(dir);
201
+ }
202
+ }
203
+ // ---------------------------------------------------------------------------
204
+ // The gate
205
+ // ---------------------------------------------------------------------------
206
+ function verdict(spdx, source, extra = {}) {
207
+ return {
208
+ spdx,
209
+ source,
210
+ allowed: spdx !== null && exports.ALLOWED_SPDX.includes(spdx),
211
+ shareAlike: spdx === 'CC-BY-SA-4.0',
212
+ ...extra,
213
+ };
214
+ }
215
+ /** Which license applies to `filePath`, and may it be copied? `declared` is the file's own `license:` value. */
216
+ async function checkLicense(env, filePath, declared) {
217
+ // (a) the file says it itself
218
+ if (declared && declared.trim()) {
219
+ const spdx = normalizeLicenseName(declared);
220
+ const namesFile = pointsToLicenseFile(declared);
221
+ // A known license name wins even though it says "License" ("MIT License");
222
+ // a bare file name ("LICENSE.txt") looks like an id but names a file → (b).
223
+ if (spdx && (exports.ALLOWED_SPDX.includes(spdx) || !namesFile))
224
+ return verdict(spdx, 'frontmatter');
225
+ // "Proprietary", "Custom" …: a declaration we cannot read as an open license blocks.
226
+ if (!namesFile)
227
+ return verdict(null, 'frontmatter');
228
+ }
229
+ // (b) the nearest license file — a closer one that is not recognized blocks
230
+ const licensePath = closestLicenseFile(env.licenseFiles, filePath);
231
+ if (licensePath) {
232
+ const text = await env.readText(licensePath);
233
+ const copyright = text === null ? undefined : extractCopyright(text);
234
+ return verdict(text === null ? null : detectLicenseText(text), 'file', {
235
+ licenseUrl: (0, github_1.blobUrl)(env.repo, env.commit, licensePath),
236
+ ...(copyright ? { copyright } : {}),
237
+ });
238
+ }
239
+ // (c) no license file anywhere on the way up: what GitHub says about the repo
240
+ if (!env.repoLicense)
241
+ return verdict(null, 'none');
242
+ return verdict(env.repoLicense === 'NOASSERTION' ? null : normalizeLicenseName(env.repoLicense), 'repo');
243
+ }
@@ -23,6 +23,10 @@
23
23
  * updated: 2026-08-10T12:00:00.000Z
24
24
  * ---
25
25
  * <prompt body>
26
+ *
27
+ * A prompt that came from a public GitHub repo (`ple import github:…`) also
28
+ * carries `upstream_*` lines (repo, commit, blob, path, license …) so
29
+ * `ple import --check` can tell what changed there; they are written only then.
26
30
  */
27
31
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
28
32
  if (k2 === undefined) k2 = k;
@@ -76,6 +80,21 @@ const fs = __importStar(require("fs"));
76
80
  const os = __importStar(require("os"));
77
81
  const path = __importStar(require("path"));
78
82
  const fsSafe_1 = require("./fsSafe");
83
+ const promptTemplate_1 = require("./promptTemplate");
84
+ /** Frontmatter key ↔ `Upstream` property. Order = file order. */
85
+ const UPSTREAM_KEYS = [
86
+ ['repo', 'upstream_repo'],
87
+ ['ref', 'upstream_ref'],
88
+ ['commit', 'upstream_commit'],
89
+ ['blob', 'upstream_blob'],
90
+ ['path', 'upstream_path'],
91
+ ['license', 'upstream_license'],
92
+ ['licenseUrl', 'upstream_license_url'],
93
+ ['copyright', 'upstream_copyright'],
94
+ ['tool', 'upstream_tool'],
95
+ ['kind', 'upstream_kind'],
96
+ ['url', 'upstream_url'],
97
+ ];
79
98
  /** Root of the local store. Overridable for tests and for people who relocate it. */
80
99
  function localRoot() {
81
100
  const override = process.env.PROMPTLIKE_HOME;
@@ -118,6 +137,12 @@ function serialize(p) {
118
137
  field('tags', p.tags.map(escapeValue).filter(Boolean).join(', ')),
119
138
  field('created', p.created),
120
139
  field('updated', p.updated),
140
+ ...(p.upstream
141
+ ? UPSTREAM_KEYS.flatMap(([prop, key]) => {
142
+ const v = p.upstream?.[prop];
143
+ return v ? [field(key, escapeValue(v))] : [];
144
+ })
145
+ : []),
121
146
  '---',
122
147
  '',
123
148
  ];
@@ -158,6 +183,25 @@ function parse(slug, raw) {
158
183
  .split(',')
159
184
  .map((t) => t.trim())
160
185
  .filter(Boolean);
186
+ // Without the four ids `--check` works from, the lines are not provenance.
187
+ const up = {};
188
+ for (const [prop, key] of UPSTREAM_KEYS)
189
+ up[prop] = field(key);
190
+ const upstream = up.repo && up.ref && up.commit && up.blob && up.path
191
+ ? {
192
+ repo: up.repo,
193
+ ref: up.ref,
194
+ commit: up.commit,
195
+ blob: up.blob,
196
+ path: up.path,
197
+ license: up.license,
198
+ ...(up.licenseUrl ? { licenseUrl: up.licenseUrl } : {}),
199
+ ...(up.copyright ? { copyright: up.copyright } : {}),
200
+ tool: up.tool,
201
+ kind: up.kind,
202
+ url: up.url,
203
+ }
204
+ : undefined;
161
205
  return {
162
206
  slug,
163
207
  title: field('title') || slug,
@@ -166,6 +210,7 @@ function parse(slug, raw) {
166
210
  body: body.trim(),
167
211
  created: field('created'),
168
212
  updated: field('updated'),
213
+ ...(upstream ? { upstream } : {}),
169
214
  };
170
215
  }
171
216
  function ensureDir() {
@@ -196,6 +241,11 @@ function save(p) {
196
241
  created: p.created || previous?.created || now,
197
242
  updated: now,
198
243
  };
244
+ // Same idea for where it came from: `ple save --force` or a rollback must not
245
+ // cut a GitHub import loose from its source.
246
+ const upstream = p.upstream ?? previous?.upstream;
247
+ if (upstream)
248
+ record.upstream = upstream;
199
249
  // Atomic + 0600; a symlink at the target is replaced, never written through.
200
250
  (0, fsSafe_1.writePrivateFile)(filePath(record.slug), serialize(record));
201
251
  return record;
@@ -265,14 +315,6 @@ function search(query) {
265
315
  }
266
316
  /** Fill `{{variables}}`; report the ones left unfilled rather than shipping them. */
267
317
  function fillVariables(body, values) {
268
- const missing = new Set();
269
- const text = body.replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (match, key) => {
270
- const value = values[key];
271
- if (value === undefined) {
272
- missing.add(key);
273
- return match;
274
- }
275
- return value;
276
- });
277
- return { text, missing: [...missing] };
318
+ const text = (0, promptTemplate_1.fillVariables)(body, values);
319
+ return { text, missing: (0, promptTemplate_1.extractVariables)(text) };
278
320
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  /**
3
- * Loop Engineering API calls — variant generation + winner save.
3
+ * Loop Engineering API calls — variant generation + winner save — and the two
4
+ * generic bearer helpers other commands reuse (`bearerGet`, `saveVersion`).
4
5
  *
5
6
  * Kept separate from `api-client.ts` on purpose: these endpoints are
6
7
  * Pro-gated and have their own 403 semantics ("upgrade to Pro"), which we
@@ -9,8 +10,10 @@
9
10
  * first, so the token is fresh).
10
11
  */
11
12
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.SAVE_TIMEOUT_MS = exports.VARIANTS_TIMEOUT_MS = void 0;
13
+ exports.VersionLimitError = exports.GET_TIMEOUT_MS = exports.SAVE_TIMEOUT_MS = exports.VARIANTS_TIMEOUT_MS = void 0;
14
+ exports.bearerGet = bearerGet;
13
15
  exports.requestVariants = requestVariants;
16
+ exports.saveVersion = saveVersion;
14
17
  exports.saveWinner = saveWinner;
15
18
  const constants_1 = require("./constants");
16
19
  const config_1 = require("./config");
@@ -20,6 +23,8 @@ const config_1 = require("./config");
20
23
  */
21
24
  exports.VARIANTS_TIMEOUT_MS = 120000;
22
25
  exports.SAVE_TIMEOUT_MS = 30000;
26
+ /** Hafif okumalar (api-client.ts READ_TIMEOUT_MS ile aynı). */
27
+ exports.GET_TIMEOUT_MS = 15000;
23
28
  const NOT_LOGGED_IN = 'Not logged in. Run `ple login` first.';
24
29
  const SESSION_EXPIRED = 'Session expired. Log in again: `ple login`';
25
30
  /** The Pro upsell suffix — appended to every 403 from the loop endpoints. */
@@ -43,12 +48,15 @@ function timeoutError(timeoutMs) {
43
48
  return new Error(`No response from ${constants_1.API_BASE_URL} within ${Math.round(timeoutMs / 1000)}s. ` +
44
49
  'The server may still be working on it; wait a moment, then try again.');
45
50
  }
51
+ const proForbidden = (serverError) => new Error(proMessage(serverError));
46
52
  /**
47
- * Minimal bearer POST used by the two loop calls. Mirrors the error mapping
48
- * of `api-client.ts` (network / 401 / 403 / 429 / error body) without the
49
- * refresh-retry machinery — `ensureAuthed()` has already refreshed the token.
53
+ * Minimal bearer request used by the loop calls and the generic helpers below.
54
+ * Mirrors the error mapping of `api-client.ts` (network / 401 / 403 / 429 /
55
+ * error body) without the refresh-retry machinery — `ensureAuthed()` has
56
+ * already refreshed the token. Redirects are never followed: the bearer token
57
+ * must not be replayed at a Location the server chose.
50
58
  */
51
- async function bearerPost(path, body, timeoutMs) {
59
+ async function bearerRequest(method, path, body, timeoutMs, forbidden) {
52
60
  const config = (0, config_1.readConfig)();
53
61
  if (!config)
54
62
  throw new Error(NOT_LOGGED_IN);
@@ -56,14 +64,15 @@ async function bearerPost(path, body, timeoutMs) {
56
64
  let res;
57
65
  try {
58
66
  res = await fetch(constants_1.API_BASE_URL + path, {
59
- method: 'POST',
67
+ method,
60
68
  headers: {
61
- 'Content-Type': 'application/json',
69
+ ...(method === 'POST' ? { 'Content-Type': 'application/json' } : {}),
62
70
  Authorization: `Bearer ${config.access_token}`,
63
71
  },
64
- body: JSON.stringify(body),
72
+ body: method === 'POST' ? JSON.stringify(body) : undefined,
65
73
  // Süre başlıkla sınırlı değil: gövde okuması da aynı sinyalle kesilir.
66
74
  signal,
75
+ redirect: 'manual',
67
76
  });
68
77
  }
69
78
  catch (err) {
@@ -71,6 +80,10 @@ async function bearerPost(path, body, timeoutMs) {
71
80
  throw timeoutError(timeoutMs);
72
81
  throw new Error(`Cannot reach ${constants_1.API_BASE_URL}. Check your connection. (${err instanceof Error ? err.message : String(err)})`);
73
82
  }
83
+ if (res.status >= 300 && res.status < 400) {
84
+ throw new Error(`The server answered with a redirect (HTTP ${res.status}); the CLI does not follow redirects. ` +
85
+ `Check PROMPTLIKE_API_URL (currently ${constants_1.API_BASE_URL}).`);
86
+ }
74
87
  if (res.status === 401)
75
88
  throw new Error(SESSION_EXPIRED);
76
89
  let parsed = {};
@@ -83,9 +96,9 @@ async function bearerPost(path, body, timeoutMs) {
83
96
  throw timeoutError(timeoutMs);
84
97
  // Non-JSON body — fall through to the generic messages below.
85
98
  }
86
- // Pro gate → 403; tükenen AI token bütçesi → 402 (ApiErrors.insufficientTokens).
99
+ // Pro gate / plan limit → 403 (endpoint-specific); tükenen AI token bütçesi → 402 (ApiErrors.insufficientTokens).
87
100
  if (res.status === 403)
88
- throw new Error(proMessage(parsed.error));
101
+ throw forbidden(parsed.error, parsed);
89
102
  if (res.status === 402) {
90
103
  // Satış anı, hata anı değil: MicroBoost adıyla ve fiyatıyla anılır.
91
104
  const base = parsed.error?.trim() || "You've used this month's AI tokens";
@@ -100,6 +113,15 @@ async function bearerPost(path, body, timeoutMs) {
100
113
  }
101
114
  return parsed;
102
115
  }
116
+ const bearerPost = (path, body, timeoutMs) => bearerRequest('POST', path, body, timeoutMs, proForbidden);
117
+ /**
118
+ * GET an API path with the stored bearer token and parse the JSON body.
119
+ * Same error mapping and timeout rules as the loop calls (callers run
120
+ * `ensureAuthed()` first).
121
+ */
122
+ function bearerGet(path, timeoutMs = exports.GET_TIMEOUT_MS) {
123
+ return bearerRequest('GET', path, undefined, timeoutMs, (serverError) => new Error(serverError?.trim() || 'Not allowed.'));
124
+ }
103
125
  /**
104
126
  * POST /api/prompts/{id}/variants — ask the server to generate 2-3 AI
105
127
  * variants of the prompt's current version.
@@ -117,6 +139,35 @@ async function requestVariants(promptId, opts = {}) {
117
139
  const res = await bearerPost(`/api/prompts/${promptId}/variants`, body, exports.VARIANTS_TIMEOUT_MS);
118
140
  return { variants: res.variants ?? [], tokensUsed: res.tokensUsed ?? 0 };
119
141
  }
142
+ /** The plan's per-prompt version limit (Free) was hit — 403 with an upgrade link. */
143
+ class VersionLimitError extends Error {
144
+ constructor(message) {
145
+ super(message);
146
+ this.name = 'VersionLimitError';
147
+ }
148
+ }
149
+ exports.VersionLimitError = VersionLimitError;
150
+ const versionForbidden = (serverError, body) => typeof body.upgradeUrl === 'string'
151
+ ? new VersionLimitError(`${serverError?.trim() || 'Version limit reached on this plan.'} — upgrade at ${constants_1.API_BASE_URL}/pricing`)
152
+ : new Error(serverError?.trim() || 'You are not allowed to save a new version of this prompt.');
153
+ /**
154
+ * Add a new version to an existing prompt through the save endpoint (update
155
+ * path — no `isNew`). Nothing is overwritten and no label moves: the server
156
+ * appends the version and the prompt's labels keep pointing where they did.
157
+ * `description` also updates the prompt-level description; leave it out to
158
+ * keep it.
159
+ */
160
+ async function saveVersion(promptId, parts, changelog, source = 'cli', extra = {}) {
161
+ return bearerRequest('POST', '/api/prompts', {
162
+ id: promptId,
163
+ roleText: parts.roleText,
164
+ descriptionText: parts.descriptionText,
165
+ contextText: parts.contextText,
166
+ changelog,
167
+ source,
168
+ ...(extra.description !== undefined ? { description: extra.description } : {}),
169
+ }, exports.SAVE_TIMEOUT_MS, versionForbidden);
170
+ }
120
171
  /**
121
172
  * Save the winning variant as a new version of the prompt via the existing
122
173
  * save endpoint (update path — no `isNew`). Section mapping: the variant's
@@ -124,6 +175,7 @@ async function requestVariants(promptId, opts = {}) {
124
175
  * as role / description / context respectively.
125
176
  */
126
177
  async function saveWinner(promptId, variant, changelog) {
178
+ // 403 stays the Pro-gate message here: loop callers never meet the version limit's wording.
127
179
  return bearerPost('/api/prompts', {
128
180
  id: promptId,
129
181
  roleText: variant.role || '',