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.
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ /**
3
+ * `ple import github:owner/repo[/path][@ref]` — what the argument may look like.
4
+ *
5
+ * github:owner/repo github:owner/repo/sub/path …@ref (split at the LAST '@')
6
+ * https://github.com/o/r …/tree/<ref>/<path> …/blob/<ref>/<path>
7
+ *
8
+ * In the URL form the ref is ONE segment (that is how github.com writes it): a
9
+ * branch name containing '/' needs the `github:…@ref` form (or %2F in the URL).
10
+ * Every part is validated before it can reach a URL; anything else is refused
11
+ * with {@link SPEC_HELP}.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.SPEC_HELP = void 0;
15
+ exports.parseGithubSpec = parseGithubSpec;
16
+ const github_1 = require("./github");
17
+ exports.SPEC_HELP = 'Use github:<owner>/<repo>[/path][@ref], e.g. github:anthropics/skills/skills/pdf';
18
+ const MAX_SPEC_PATH = 512;
19
+ const MAX_REF = 200;
20
+ const BAD_SEGMENT_CHARS = /[\u0000-\u001f\u007f-\u009f\\]/;
21
+ const REF_RE = /^[A-Za-z0-9._/-]+$/;
22
+ const bad = () => {
23
+ throw new Error(exports.SPEC_HELP);
24
+ };
25
+ function validRef(ref) {
26
+ if (!ref || ref.length > MAX_REF || !REF_RE.test(ref) || ref.includes('..') || ref.includes('//') || ref.startsWith('/') || ref.endsWith('/')) {
27
+ return bad();
28
+ }
29
+ return ref;
30
+ }
31
+ function validParts(owner, repoRaw, pathSegments) {
32
+ const repo = repoRaw.replace(/\.git$/, '');
33
+ if (!github_1.OWNER_RE.test(owner) || !github_1.REPO_RE.test(repo) || repo === '.' || repo === '..')
34
+ return bad();
35
+ for (const s of pathSegments) {
36
+ if (s === '' || s === '.' || s === '..' || s.includes('/') || BAD_SEGMENT_CHARS.test(s))
37
+ return bad();
38
+ }
39
+ const path = pathSegments.join('/');
40
+ if (path.length > MAX_SPEC_PATH)
41
+ return bad();
42
+ return { owner, repo, path };
43
+ }
44
+ function parseGithubSpec(input) {
45
+ const raw = input.trim();
46
+ const url = raw.match(/^https:\/\/github\.com\/([^?#]*)/i);
47
+ if (url) {
48
+ let segs;
49
+ try {
50
+ segs = url[1].replace(/\/+$/, '').split('/').map(decodeURIComponent);
51
+ }
52
+ catch {
53
+ return bad();
54
+ }
55
+ if (segs.length < 2)
56
+ return bad();
57
+ const [owner, repo, kind, ref, ...rest] = segs;
58
+ if (segs.length === 2)
59
+ return { ...validParts(owner, repo, []), ref: null };
60
+ if ((kind !== 'tree' && kind !== 'blob') || ref === undefined)
61
+ return bad();
62
+ return { ...validParts(owner, repo, rest), ref: validRef(ref) };
63
+ }
64
+ const short = raw.match(/^github:(.+)$/i);
65
+ if (!short)
66
+ return bad();
67
+ let body = short[1];
68
+ let ref = null;
69
+ const at = body.lastIndexOf('@');
70
+ if (at !== -1) {
71
+ ref = validRef(body.slice(at + 1));
72
+ body = body.slice(0, at);
73
+ }
74
+ const [owner, repo, ...rest] = body.replace(/\/+$/, '').split('/');
75
+ if (repo === undefined)
76
+ return bad();
77
+ return { ...validParts(owner, repo, rest), ref };
78
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ /**
3
+ * What the account remembers about where its prompts came from:
4
+ * GET /api/prompts/import?include=origins → the sha256 of everything imported
5
+ * (`knownHashes`) and, from servers that know the parameter, one row per
6
+ * imported prompt with its provenance (`origins`). Older servers ignore the
7
+ * parameter and answer with `knownHashes` only; `origins` is then null.
8
+ *
9
+ * Rides on the loop module's bearer GET (api-client.ts is not touched);
10
+ * callers run `ensureAuthed()` first.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.fetchImportOrigins = fetchImportOrigins;
14
+ const loopApi_1 = require("./loopApi");
15
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
16
+ function toRow(raw) {
17
+ if (!isRecord(raw) || typeof raw.promptId !== 'string' || typeof raw.sha256 !== 'string')
18
+ return null;
19
+ let meta = null;
20
+ if (isRecord(raw.meta)) {
21
+ meta = {};
22
+ for (const [k, v] of Object.entries(raw.meta)) {
23
+ if (typeof v === 'string')
24
+ meta[k] = v;
25
+ }
26
+ }
27
+ return { promptId: raw.promptId, sha256: raw.sha256, path: typeof raw.path === 'string' ? raw.path : null, meta };
28
+ }
29
+ async function fetchImportOrigins() {
30
+ const res = await (0, loopApi_1.bearerGet)('/api/prompts/import?include=origins');
31
+ const hashes = Array.isArray(res.knownHashes) ? res.knownHashes.filter((h) => typeof h === 'string') : [];
32
+ const origins = Array.isArray(res.origins)
33
+ ? res.origins.map(toRow).filter((r) => r !== null)
34
+ : null;
35
+ return { knownHashes: new Set(hashes), origins };
36
+ }
@@ -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;
@@ -77,6 +81,20 @@ const os = __importStar(require("os"));
77
81
  const path = __importStar(require("path"));
78
82
  const fsSafe_1 = require("./fsSafe");
79
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
+ ];
80
98
  /** Root of the local store. Overridable for tests and for people who relocate it. */
81
99
  function localRoot() {
82
100
  const override = process.env.PROMPTLIKE_HOME;
@@ -119,6 +137,12 @@ function serialize(p) {
119
137
  field('tags', p.tags.map(escapeValue).filter(Boolean).join(', ')),
120
138
  field('created', p.created),
121
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
+ : []),
122
146
  '---',
123
147
  '',
124
148
  ];
@@ -159,6 +183,25 @@ function parse(slug, raw) {
159
183
  .split(',')
160
184
  .map((t) => t.trim())
161
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;
162
205
  return {
163
206
  slug,
164
207
  title: field('title') || slug,
@@ -167,6 +210,7 @@ function parse(slug, raw) {
167
210
  body: body.trim(),
168
211
  created: field('created'),
169
212
  updated: field('updated'),
213
+ ...(upstream ? { upstream } : {}),
170
214
  };
171
215
  }
172
216
  function ensureDir() {
@@ -197,6 +241,11 @@ function save(p) {
197
241
  created: p.created || previous?.created || now,
198
242
  updated: now,
199
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;
200
249
  // Atomic + 0600; a symlink at the target is replaced, never written through.
201
250
  (0, fsSafe_1.writePrivateFile)(filePath(record.slug), serialize(record));
202
251
  return record;