promptlike 0.6.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,70 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.0 — 2026-10-17
4
+
5
+ - **New: `ple repo`.** Create and manage repos from the terminal.
6
+ `ple repo create <name> [--private|--public] [-d <text>]` (private unless you
7
+ say `--public`), `ple repo list` (visibility, your role, prompt count),
8
+ `ple repo show <repo>`, `ple repo visibility <repo> private|public` (owner
9
+ only; making a repo public asks first, `--yes` in scripts). `<repo>` is a name,
10
+ slug, id or the 8-character id that `ple repo list` prints. All four take
11
+ `--json` (stable shape, see the README). There is no delete command: deleting a
12
+ repo cannot be undone, so it stays on the web. The server enforces the plan's
13
+ repo limit (Free: 1), the name rules, slug uniqueness and owner-only visibility;
14
+ the CLI only checks first so mistakes fail faster.
15
+ - **New: `ple list --project <repo>`** (the README listed it as missing). The short
16
+ repo id from `ple repo list` now also works for every `--project` option.
17
+ - **`ple --help` is grouped** (Prompts, Repos, Account, Import / export / sync,
18
+ Insights & settings) with examples and the exit codes. Every old command and
19
+ option still works unchanged.
20
+ - **Exit codes are consistent:** 0 success; 1 you can fix it (bad input, not
21
+ signed in, not found, not allowed, plan limit, conflict); 2 try again later (no
22
+ network, timeout, rate limit, server error). Before, every failure exited 1.
23
+ A script that tested for exactly `1` should test for non-zero.
24
+ - **Security: the API URL must be https.** `PROMPTLIKE_API_URL` now has to be https
25
+ (plain http only for localhost / 127.0.0.1 / [::1]), without a username, password,
26
+ query or fragment. A bad value stops the command before any request, so the
27
+ token and your password can never be sent to an insecure or mistyped address.
28
+ - **Security: no redirects.** The CLI no longer follows HTTP redirects (a redirect
29
+ could replay your login or token at another address); it stops with a message.
30
+ - **Security: session and local files.** The session file is written atomically,
31
+ `0600` in a `0700` folder; a looser existing file or folder is tightened. A
32
+ symbolic link at `config.json`, a prompt file, a history file or an export target
33
+ is never written through (the link is replaced or the export refused); a link at
34
+ `config.json` is not trusted as a session. `ple logout` now also removes a corrupt
35
+ or unreadable session file instead of reporting "Not logged in" and leaving it.
36
+ Settings, the suggestion cache and `~/.promptlike` files get the same treatment.
37
+ - **Security: `ple export`** refuses to write through a symbolic link (even with
38
+ `--force`) and treats a dangling link as existing; skill files must stay inside the
39
+ chosen folder.
40
+ - **Security: server text on your terminal.** Titles, descriptions and repo names
41
+ from the server (including shared repos) have terminal escape sequences and
42
+ control characters removed before they are printed; `ple show` does the same for
43
+ the body. `ple get` and `ple copy` still output the prompt byte for byte.
44
+ - **Security: responses are checked.** A sign-in response without proper tokens is
45
+ rejected before anything is written to disk; repo rows from the server are
46
+ validated and fall back to the most restrictive reading (private, viewer). A
47
+ `Retry-After` header is only echoed when it is a plain number.
48
+ - No environment variable can hold the token: the only place a session lives is
49
+ `config.json`. Tokens are never printed or put on a command line.
50
+ - **Docs:** README documents `ple repo`, the `--json` shapes, exit codes and the
51
+ security behavior above.
52
+
53
+ ## 0.7.0 — 2026-10-15
54
+
55
+ - **Local version history (no account needed):** `ple save` now keeps an
56
+ append-only history under `~/.promptlike/history/<name>/` (`v0001.md`, …). A
57
+ save adds a version only when the prompt text changed. Signed out, `ple log`,
58
+ `ple diff [a] [b]` and `ple rollback <name> <version>` work on it instead of
59
+ saying "local prompts keep no versions". Rollback adds the old text as a new
60
+ version ("Restored vX as a new version. Nothing was deleted."); the CLI never
61
+ overwrites or deletes a version and there is no limit. These commands make no
62
+ network requests (covered by a test). Signed in, the three commands are
63
+ unchanged and still use the account history. `ple sync` uploads each prompt's
64
+ current text only; the local history is not uploaded.
65
+ - **Docs:** README describes the local history; the claim that the local store
66
+ keeps no versions is removed.
67
+
3
68
  ## 0.6.3 — 2026-10-13
4
69
 
5
70
  - **Package metadata:** `repository` and `bugs` now point to the public plugin repository
package/README.md CHANGED
@@ -37,11 +37,13 @@ ple sync # one-way, local → account; local files are kept
37
37
  1. [Install](#install)
38
38
  2. [Quick start](#quick-start)
39
39
  3. [Commands](#commands)
40
- 4. [Configuration](#configuration)
41
- 5. [How it works](#how-it-works)
42
- 6. [Troubleshooting](#troubleshooting)
43
- 7. [Feedback](#feedback)
44
- 8. [License](#license)
40
+ 4. [Exit codes](#exit-codes)
41
+ 5. [Security notes](#security-notes)
42
+ 6. [Configuration](#configuration)
43
+ 7. [How it works](#how-it-works)
44
+ 8. [Troubleshooting](#troubleshooting)
45
+ 9. [Feedback](#feedback)
46
+ 10. [License](#license)
45
47
 
46
48
  ---
47
49
 
@@ -94,9 +96,10 @@ $ ple save "code review" -m "Review this diff: {{diff}}" -t review
94
96
  $ pbpaste | ple save "bug triage" # or pipe it in
95
97
  ```
96
98
 
97
- Saving over an existing prompt needs `--force`, because the local store keeps
98
- no version history. Tags and the description you do not repeat are carried
99
- over rather than wiped.
99
+ Saving over an existing prompt needs `--force`. Tags and the description you do
100
+ not repeat are carried over rather than wiped. Every save that changes the text
101
+ also adds a version to a local, append-only history (see
102
+ [Local version history](#local-version-history-signed-out)).
100
103
 
101
104
  ### `ple sync [--dry-run]`
102
105
 
@@ -125,7 +128,7 @@ Password: ********
125
128
  Removes the local session file. The session itself expires naturally on its
126
129
  own clock — this just clears the local copy.
127
130
 
128
- ### `ple list [--tag <name>] [--limit <n>]`
131
+ ### `ple list [--tag <name>] [--limit <n>] [--project <repo>]`
129
132
 
130
133
  Lists every prompt your account has access to. The server scopes results to
131
134
  you automatically.
@@ -139,8 +142,58 @@ ID TITLE UPDATED
139
142
 
140
143
  $ ple list --tag debug # filter by tag (server-side)
141
144
  $ ple list --limit 50 # default 30, max 100
145
+ $ ple list --project my-prompts # only one repo (name, slug or id)
142
146
  ```
143
147
 
148
+ ### `ple repo` — create and manage repos
149
+
150
+ A repo is a collection of prompts in your account. Needs an account
151
+ (`ple login`); signed out, the commands say so.
152
+
153
+ ```bash
154
+ $ ple repo create "team-prompts" --description "Shared review prompts"
155
+ ✓ Created private repo 'team-prompts' (team-prompts, 1a2b3c4d)
156
+ Private: only you and people you invite can see it.
157
+ Next: ple import --scan --project 1a2b3c4d (or ple sync, then move prompts on the web)
158
+
159
+ $ ple repo list
160
+ ID NAME VISIBILITY ROLE PROMPTS UPDATED
161
+ ──────── ────────────────────────────── ────────── ────── ─────── ──────────
162
+ 1a2b3c4d team-prompts private owner 0 now
163
+ 9f8e7d6c Open prompts public owner 12 3d ago
164
+
165
+ $ ple repo show team-prompts
166
+ $ ple repo visibility team-prompts public # asks first; --yes in scripts
167
+ ✓ 'team-prompts' is now public.
168
+ ```
169
+
170
+ | Command | What it does |
171
+ |---|---|
172
+ | `ple repo create <name> [--private\|--public] [-d <text>] [--json]` | Creates a repo. **Private unless you pass `--public`.** Name: 1–100 characters, plain text, at least one letter or digit (it becomes the URL slug). Description: up to 500 characters. |
173
+ | `ple repo list [--json]` | Every repo you own or belong to: visibility, your role, prompt count. |
174
+ | `ple repo show <repo> [--json]` | One repo. `<repo>` = name, slug, id, or the 8-character id from `ple repo list`. |
175
+ | `ple repo visibility <repo> private\|public [--yes] [--json]` | Owner only. Going public asks for confirmation (a script must pass `--yes`); going private never asks. |
176
+
177
+ The server enforces the rules, not just the CLI: you must be signed in, Free
178
+ includes 1 repo (hitting the limit says so and links the pricing page), names and URL slugs must be valid and unique among your repos
179
+ (a clash says "pick a different name"), and only the owner can change a repo's
180
+ visibility. Private repos are available on every plan. A repo you do not own or
181
+ belong to is reported as "not found". There is **no delete command**: deleting
182
+ a repo cannot be undone, so it is only possible on the web.
183
+
184
+ `--json` prints one stable object and nothing else:
185
+
186
+ ```json
187
+ { "ok": true, "repo": { "id": "…", "name": "team-prompts", "slug": "team-prompts",
188
+ "description": null, "visibility": "private", "role": "owner",
189
+ "prompt_count": 0, "member_count": 1,
190
+ "created_at": "2026-10-17T09:00:00Z", "updated_at": "2026-10-17T09:00:00Z" } }
191
+ ```
192
+
193
+ `list` prints `{ "repos": [ … ] }` with the same repo objects; `show` prints
194
+ `{ "repo": { … } }`; `visibility` prints `{ "ok": true, "changed": true|false, "repo": { … } }`.
195
+ Keys are only ever added, never renamed or removed, within 0.x minor releases.
196
+
144
197
  ### `ple copy <name>`
145
198
 
146
199
  Looks up a prompt by title substring (case-insensitive) or short ID, joins
@@ -309,6 +362,36 @@ ple rollback "code review" v2 # asks first; --yes for scripts
309
362
  Rollback is non-destructive: the old version is copied forward as a new one,
310
363
  nothing is deleted — so a rollback can itself be undone.
311
364
 
365
+ #### Local version history (signed out)
366
+
367
+ Without an account the same three commands work on a history kept on your
368
+ machine, in `~/.promptlike/history/<name>/v0001.md`, `v0002.md`, … (the same
369
+ Markdown format as your prompts, so you can read, grep and commit it).
370
+
371
+ ```bash
372
+ ple save "code review" -m "Review this diff: {{diff}}" # v1
373
+ ple save "code review" -m "Review this diff, be strict" --force # v2
374
+ ple log "code review" # newest first, * = current
375
+ ple diff "code review" # previous ↔ current (same unified format)
376
+ ple diff "code review" 1 2 # any two: 1, v1 or #1
377
+ ple rollback "code review" v1 # asks first; --yes for scripts
378
+ # ✓ Restored v1 as a new version. Nothing was deleted.
379
+ ```
380
+
381
+ - A save adds a version only when the prompt text changed. Title, description
382
+ and tags are stored with each version, but only a change to the text creates one.
383
+ - Append-only: version files are never overwritten or deleted by the CLI and
384
+ there is no limit on how many are kept. A rollback adds a new version, so it
385
+ can be undone with another rollback. Rollback restores the text; the current
386
+ title, description and tags stay.
387
+ - A prompt that existed before you updated has no history yet; the first
388
+ `ple save --force` over it records the text that was on disk as v1 first.
389
+ A file you edited by hand is recorded the same way before a rollback.
390
+ - No network access: these commands only read and write files under
391
+ `~/.promptlike` (`PROMPTLIKE_HOME` moves it). `--project` is ignored signed out.
392
+ - `ple sync` uploads the current text of each prompt. The version history is
393
+ not uploaded and stays local.
394
+
312
395
  ### `ple stats [--range 7|30|365] [--json]`
313
396
 
314
397
  How your library is actually used — the same numbers as the web Insights
@@ -368,6 +451,38 @@ sub-command.
368
451
 
369
452
  ---
370
453
 
454
+ ## Exit codes
455
+
456
+ | Code | Meaning | Examples |
457
+ |---|---|---|
458
+ | `0` | Success | |
459
+ | `1` | You can fix it | bad input, not signed in, not found, not allowed, plan limit, name already used |
460
+ | `2` | Try again later | no network, timeout, rate limited, server error (5xx) |
461
+
462
+ Scripts should treat any non-zero code as failure; `2` is the one worth retrying.
463
+
464
+ ## Security notes
465
+
466
+ - **Where your session lives:** `~/.config/promptlike/config.json`, mode `0600`
467
+ inside a `0700` folder (a looser existing file or folder is tightened). It is
468
+ written atomically and never through a symbolic link. There is no environment
469
+ variable for the token, the token is never printed or passed on a command line,
470
+ and `ple logout` deletes the file (also when it is corrupt).
471
+ - **HTTPS only.** `PROMPTLIKE_API_URL` must be https (plain http only for
472
+ `localhost`, `127.0.0.1`, `[::1]`), without credentials, query or fragment. An
473
+ invalid value stops the command before anything is sent. Redirects are never
474
+ followed. Requests time out (15 s reads, 30 s writes) and are never retried
475
+ automatically.
476
+ - **Files:** `ple export` refuses to overwrite without `--force` and never writes
477
+ through a symbolic link; local prompts, history and cache are `0600`.
478
+ - **Terminal safety:** titles and descriptions that come from the server have
479
+ escape sequences and control characters removed before they are printed.
480
+ - **No shell:** `ple copy` runs the clipboard tool directly and sends the text on
481
+ its standard input. The one deliberate exception is `ple loop --exec`, which runs
482
+ *your own* command through your shell (see the note there).
483
+
484
+ ---
485
+
371
486
  ## Configuration
372
487
 
373
488
  | Path | Purpose | Permissions |
@@ -395,7 +510,8 @@ you to run `ple login`.
395
510
  ### Optional environment variables
396
511
 
397
512
  The CLI ships with the production API URL baked in. You can point it at a
398
- different deployment (e.g. a local dev server) for testing:
513
+ different deployment (e.g. a local dev server) for testing. The URL must be
514
+ https, except for `localhost` / `127.0.0.1` / `[::1]`:
399
515
 
400
516
  ```bash
401
517
  export PROMPTLIKE_API_URL="http://localhost:3000"
@@ -410,6 +526,8 @@ to configure.
410
526
  | `PLE_SUGGEST=off` | `ple suggest --hook` stays silent |
411
527
  | `PLE_SURFACE`, `PLE_VIA` | How `copy/get/show` report a use (e.g. `hook`, `suggestion`) |
412
528
  | `PROMPTLIKE_HOME` | Local store location (default `~/.promptlike`) |
529
+ | `PROMPTLIKE_CONFIG_DIR` | Session / settings / cache folder (default `~/.config/promptlike`) |
530
+ | `PROMPTLIKE_API_URL` | API address (https only, see above) |
413
531
 
414
532
  ---
415
533
 
@@ -430,6 +548,7 @@ to configure.
430
548
  │ POST /api/auth/cli/login │
431
549
  │ GET /api/prompts?tag&search&limit │
432
550
  │ GET /api/prompts/{id} │
551
+ │ GET/POST /api/projects (repos) │
433
552
  │ rate limiting · validation · RLS │
434
553
  └──────────────────────────────────────┘
435
554
  ```
@@ -460,6 +579,11 @@ to configure.
460
579
  | `'X' matched multiple prompts.` | Substring matched several rows | Use a more specific name or the short ID |
461
580
  | `Rate limited. Try again in Ns.` | Too many requests in a short window | Wait the suggested seconds and retry |
462
581
  | `Cannot reach <url>. Check your connection.` | Network / wrong `PROMPTLIKE_API_URL` | Check connectivity or unset the override |
582
+ | `PROMPTLIKE_API_URL must use https …` | The override is plain http (or not a URL) | Use an https address, or unset it; http works only for localhost |
583
+ | `Your plan's repo limit is reached …` | Free includes 1 repo | Use your existing repo (`ple repo list`) or upgrade |
584
+ | `You already have a repo with that name …` | The name's URL slug is taken | Pick a different name |
585
+ | `Only the owner can change a repo's visibility` | You are an admin/editor/viewer there | Ask the owner |
586
+ | `Making '…' public needs confirmation` | Non-interactive run | Re-run with `--yes` |
463
587
 
464
588
  ---
465
589
 
@@ -469,7 +593,7 @@ What this CLI does **not** do yet:
469
593
 
470
594
  - Delete prompts (`ple save` creates and updates; deleting is done on the web)
471
595
  - `ple search` over version body (`content`); needs a server-side full-text index
472
- - `--project <name>` filter on `ple list`
596
+ - Delete a repo (`ple repo` creates, lists, shows and changes visibility; deleting is done on the web)
473
597
  - Interactive picker (think `fzf`-style)
474
598
  - Configurable color theme
475
599
 
@@ -11,11 +11,15 @@ exports.diffCommand = diffCommand;
11
11
  const api_client_1 = require("../lib/api-client");
12
12
  const format_1 = require("../lib/format");
13
13
  const diff_1 = require("../lib/diff");
14
+ const localHistory_1 = require("./localHistory");
15
+ const local_1 = require("./local");
14
16
  const history_1 = require("./history");
15
17
  function label(title, v) {
16
18
  return `${title} v${v.version_number} (${(0, history_1.semverOf)(v)})`;
17
19
  }
18
20
  async function diffCommand(name, a, b, options = {}) {
21
+ if ((0, local_1.isSignedOut)())
22
+ return (0, localHistory_1.localDiff)(name, a, b, options);
19
23
  const prompt = await (0, history_1.resolveForHistory)(name, options.project);
20
24
  if (!prompt) {
21
25
  process.exitCode = 1;
@@ -41,6 +41,7 @@ const local_1 = require("./local");
41
41
  const store = __importStar(require("../lib/localStore"));
42
42
  const promptResolver_1 = require("../lib/promptResolver");
43
43
  const format_1 = require("../lib/format");
44
+ const fsSafe_1 = require("../lib/fsSafe");
44
45
  const agentExport_1 = require("../lib/agentExport");
45
46
  /** Hard cap for a repo export — 10 pages × 100. */
46
47
  const MAX_PAGES = 10;
@@ -80,9 +81,19 @@ async function collectRemoteRepo(projectId) {
80
81
  return out;
81
82
  }
82
83
  function ensureWritable(target, force) {
83
- if (fs.existsSync(target) && !force) {
84
+ // lstat-based: a dangling symlink counts as "exists" (existsSync said no and
85
+ // the write then created the link's target), and a link is never written through.
86
+ if ((0, fsSafe_1.pathExists)(target) && !force) {
84
87
  throw new Error(`${target} already exists. Re-run with --force to overwrite.`);
85
88
  }
89
+ (0, fsSafe_1.assertNotSymlink)(target);
90
+ }
91
+ /** Every file of an export must land inside the chosen folder (no `..`, no absolute paths). */
92
+ function assertInside(parent, target) {
93
+ const rel = path.relative(parent, target);
94
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
95
+ throw new Error(`Refusing to write outside ${parent}: ${target}`);
96
+ }
86
97
  }
87
98
  function writeSkill(skill, options) {
88
99
  const parent = path.resolve(options.out ?? '.');
@@ -97,6 +108,8 @@ function writeSkill(skill, options) {
97
108
  ensureWritable(folder, options.force);
98
109
  for (const f of skill.files) {
99
110
  const target = path.join(parent, ...f.path.split('/'));
111
+ assertInside(parent, target);
112
+ (0, fsSafe_1.assertNotSymlink)(target);
100
113
  fs.mkdirSync(path.dirname(target), { recursive: true });
101
114
  fs.writeFileSync(target, f.content, 'utf-8');
102
115
  }
@@ -3,7 +3,6 @@
3
3
  * Shared helpers for `ple log`, `ple diff`, `ple rollback` (W1-4).
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.HISTORY_NEEDS_ACCOUNT = void 0;
7
6
  exports.semverOf = semverOf;
8
7
  exports.sortNewestFirst = sortNewestFirst;
9
8
  exports.findVersion = findVersion;
@@ -12,8 +11,6 @@ exports.resolveForHistory = resolveForHistory;
12
11
  exports.versionNotFound = versionNotFound;
13
12
  const api_client_1 = require("../lib/api-client");
14
13
  const promptResolver_1 = require("../lib/promptResolver");
15
- const local_1 = require("./local");
16
- exports.HISTORY_NEEDS_ACCOUNT = 'Version history lives in your account — local prompts keep no versions. Run `ple login`, then `ple sync`.';
17
14
  /** "1.2.3" from the semver columns, else release_tag, else "v<n>". */
18
15
  function semverOf(v) {
19
16
  if (v.major_version != null && v.minor_version != null && v.patch_version != null) {
@@ -48,10 +45,6 @@ function currentVersion(history) {
48
45
  }
49
46
  /** Signed-in guard + name/--project resolution. Returns null when unresolved (message already printed). */
50
47
  async function resolveForHistory(name, project) {
51
- if ((0, local_1.isSignedOut)()) {
52
- (0, local_1.noteIgnoredProject)(project);
53
- throw new Error(exports.HISTORY_NEEDS_ACCOUNT);
54
- }
55
48
  await (0, api_client_1.ensureAuthed)();
56
49
  const projectId = project ? await (0, promptResolver_1.resolveProjectId)(project) : undefined;
57
50
  const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.listCommand = listCommand;
4
4
  const api_client_1 = require("../lib/api-client");
5
5
  const local_1 = require("./local");
6
+ const promptResolver_1 = require("../lib/promptResolver");
6
7
  const constants_1 = require("../lib/constants");
7
8
  const format_1 = require("../lib/format");
8
9
  const libraryCache_1 = require("../lib/libraryCache");
@@ -17,11 +18,13 @@ async function listCommand(options) {
17
18
  const limit = Math.max(1, Math.min(100, parseInt(options.limit ?? '30', 10) || 30));
18
19
  // Signed out → the local store. The install has to be useful on its own.
19
20
  if ((0, local_1.isSignedOut)()) {
21
+ (0, local_1.noteIgnoredProject)(options.project);
20
22
  (0, local_1.localList)({ tag: options.tag, limit });
21
23
  return;
22
24
  }
23
25
  await (0, api_client_1.ensureAuthed)();
24
- const prompts = await (0, api_client_1.listPrompts)({ tag: options.tag, limit });
26
+ const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
27
+ const prompts = await (0, api_client_1.listPrompts)({ tag: options.tag, limit, projectId });
25
28
  // Keep the suggestion cache (W1-5) in step with the account — detached,
26
29
  // at most once a minute, never slows this command down.
27
30
  (0, libraryCache_1.startBackgroundRefresh)();
@@ -30,7 +33,7 @@ async function listCommand(options) {
30
33
  console.log(format_1.c.muted(`No prompts matched tag '${options.tag}'.`));
31
34
  }
32
35
  else {
33
- console.log(format_1.c.muted(`No prompts yet. Create one at ${constants_1.WEB_APP_URL}`));
36
+ console.log(format_1.c.muted(options.project ? `No prompts in '${options.project}' yet.` : `No prompts yet. Create one at ${constants_1.WEB_APP_URL}`));
34
37
  }
35
38
  return;
36
39
  }
@@ -42,6 +42,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
42
42
  exports.isSignedOut = isSignedOut;
43
43
  exports.noteIgnoredProject = noteIgnoredProject;
44
44
  exports.emptyHint = emptyHint;
45
+ exports.resolveOrExplain = resolveOrExplain;
45
46
  exports.localList = localList;
46
47
  exports.localShow = localShow;
47
48
  exports.localGet = localGet;
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ /**
3
+ * Signed-out `ple log` / `ple diff` / `ple rollback` — over the local,
4
+ * append-only history (lib/localHistory.ts). No network, ever.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.localLog = localLog;
41
+ exports.localDiff = localDiff;
42
+ exports.localRollback = localRollback;
43
+ const readline = __importStar(require("readline"));
44
+ const store = __importStar(require("../lib/localStore"));
45
+ const history = __importStar(require("../lib/localHistory"));
46
+ const format_1 = require("../lib/format");
47
+ const diff_1 = require("../lib/diff");
48
+ const local_1 = require("./local");
49
+ function versionNotFound(ref, versions) {
50
+ const known = [...versions].reverse().slice(0, 8).map((v) => `v${v.version}`).join(', ');
51
+ return new Error(`No version '${ref}'. Known: ${known || 'none'}${versions.length > 8 ? ', …' : ''} — see \`ple log\`.`);
52
+ }
53
+ /** Tell the user when the file on disk was edited outside `ple` (not in history yet). */
54
+ function noteUnrecorded(p, latest) {
55
+ if (latest && latest.body.trim() !== p.body.trim()) {
56
+ console.error(format_1.c.muted(`(The file on disk differs from v${latest.version} — it was edited outside ple. ` +
57
+ `Run \`ple save "${p.slug}" --force\` or a rollback to record it.)`));
58
+ }
59
+ }
60
+ function localLog(name, options) {
61
+ (0, local_1.noteIgnoredProject)(options.project);
62
+ const p = (0, local_1.resolveOrExplain)(name);
63
+ if (!p)
64
+ return;
65
+ const all = history.listVersions(p.slug);
66
+ const limit = Math.max(1, Math.min(Number.parseInt(options.limit ?? '20', 10) || 20, 100));
67
+ const shown = [...all].reverse().slice(0, limit);
68
+ const currentNo = all.length > 0 ? all[all.length - 1].version : null;
69
+ if (options.json) {
70
+ console.log(JSON.stringify(shown.map((v) => ({
71
+ version: v.version,
72
+ created_at: v.saved,
73
+ note: v.note || null,
74
+ current: v.version === currentNo,
75
+ })), null, 2));
76
+ return;
77
+ }
78
+ console.log(format_1.c.title(p.title) + format_1.c.muted(` ${all.length} version${all.length === 1 ? '' : 's'} (local)`));
79
+ if (shown.length === 0) {
80
+ console.log(format_1.c.muted(' No versions yet — the next `ple save` records one.'));
81
+ return;
82
+ }
83
+ for (const v of shown) {
84
+ const mark = v.version === currentNo ? format_1.c.success('*') : ' ';
85
+ console.log(`${mark} ${format_1.c.accent(`v${v.version}`.padEnd(5))} ${format_1.c.muted((0, format_1.timeAgo)(v.saved).padEnd(8))} ` +
86
+ (0, format_1.truncate)(v.note.replace(/\s+/g, ' '), 60));
87
+ }
88
+ if (all.length > shown.length) {
89
+ console.log(format_1.c.muted(` … ${all.length - shown.length} older (use --limit)`));
90
+ }
91
+ noteUnrecorded(p, all.length > 0 ? all[all.length - 1] : null);
92
+ console.log(format_1.c.muted(`\nCompare: ple diff "${p.slug}" <a> <b> · Restore: ple rollback "${p.slug}" <version>`));
93
+ }
94
+ function localDiff(name, a, b, options) {
95
+ (0, local_1.noteIgnoredProject)(options.project);
96
+ const p = (0, local_1.resolveOrExplain)(name);
97
+ if (!p)
98
+ return;
99
+ const versions = history.listVersions(p.slug);
100
+ const current = versions[versions.length - 1];
101
+ if (!current)
102
+ throw new Error(`'${p.title}' has no versions yet — the next \`ple save\` records one.`);
103
+ let from;
104
+ let to;
105
+ const need = (ref) => history.findVersion(versions, ref) ?? (() => { throw versionNotFound(ref, versions); })();
106
+ if (a && b) {
107
+ from = need(a);
108
+ to = need(b);
109
+ }
110
+ else if (a) {
111
+ from = need(a);
112
+ to = current;
113
+ }
114
+ else {
115
+ to = current;
116
+ const older = versions[versions.length - 2];
117
+ if (!older) {
118
+ console.log(format_1.c.muted(`'${p.title}' has a single version — nothing to compare yet.`));
119
+ return;
120
+ }
121
+ from = older;
122
+ }
123
+ const useColor = options.color !== false && format_1.c.success.level > 0;
124
+ const lines = (0, diff_1.unifiedDiff)(from.body, to.body, {
125
+ fromLabel: `${p.title} v${from.version}`,
126
+ toLabel: `${p.title} v${to.version}`,
127
+ colors: useColor ? { header: format_1.c.title, hunk: format_1.c.accent, add: format_1.c.success, del: format_1.c.error } : undefined,
128
+ });
129
+ if (lines.length === 0) {
130
+ console.log(format_1.c.muted(`v${from.version} and v${to.version} have identical content.`));
131
+ return;
132
+ }
133
+ for (const line of lines)
134
+ console.log(line);
135
+ }
136
+ function defaultConfirm(question) {
137
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
138
+ return new Promise((resolve) => {
139
+ rl.question(question, (answer) => {
140
+ rl.close();
141
+ resolve(/^y(es)?$/i.test(answer.trim()));
142
+ });
143
+ });
144
+ }
145
+ async function localRollback(name, ref, options, deps = {}) {
146
+ (0, local_1.noteIgnoredProject)(options.project);
147
+ const p = (0, local_1.resolveOrExplain)(name);
148
+ if (!p)
149
+ return;
150
+ // Anything edited outside ple is recorded first, so a rollback can never
151
+ // hide the text it replaces.
152
+ history.recordIfChanged(p.slug, { title: p.title, description: p.description, tags: p.tags, body: p.body }, { onDisk: null, note: 'Edited outside ple' });
153
+ const versions = history.listVersions(p.slug);
154
+ const target = history.findVersion(versions, ref);
155
+ if (!target)
156
+ throw versionNotFound(ref, versions);
157
+ const current = versions[versions.length - 1];
158
+ if (current && current.body.trim() === target.body.trim()) {
159
+ console.log(format_1.c.muted(`v${target.version} is already the current content — nothing to do.`));
160
+ return;
161
+ }
162
+ if (!options.yes) {
163
+ const interactive = deps.isTTY ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
164
+ if (!interactive) {
165
+ throw new Error('Refusing to roll back without confirmation. Re-run with --yes.');
166
+ }
167
+ const ok = await (deps.confirm ?? defaultConfirm)(`Restore '${p.title}' to v${target.version}? This adds a new version; nothing is deleted. [y/N] `);
168
+ if (!ok) {
169
+ console.log(format_1.c.muted('Cancelled.'));
170
+ return;
171
+ }
172
+ }
173
+ // Body is restored; the title, description and tags you have now are kept.
174
+ const saved = store.save({ slug: p.slug, title: p.title, description: p.description, tags: p.tags, body: target.body });
175
+ const created = history.recordIfChanged(p.slug, { title: saved.title, description: saved.description, tags: saved.tags, body: saved.body }, { onDisk: null, note: `Restored from v${target.version}` });
176
+ console.log(format_1.c.success(`✓ Restored v${target.version} as a new version. Nothing was deleted.`) + format_1.c.muted(` — ${p.title}`));
177
+ if (created)
178
+ console.log(format_1.c.muted(` now at v${created.version}`));
179
+ console.log(format_1.c.muted(`Undo with: ple rollback "${p.slug}" v${current.version}`));
180
+ }
@@ -9,8 +9,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.logCommand = logCommand;
10
10
  const api_client_1 = require("../lib/api-client");
11
11
  const format_1 = require("../lib/format");
12
+ const localHistory_1 = require("./localHistory");
13
+ const local_1 = require("./local");
12
14
  const history_1 = require("./history");
13
15
  async function logCommand(name, options = {}) {
16
+ if ((0, local_1.isSignedOut)())
17
+ return (0, localHistory_1.localLog)(name, options);
14
18
  const prompt = await (0, history_1.resolveForHistory)(name, options.project);
15
19
  if (!prompt) {
16
20
  process.exitCode = 1;
@@ -4,15 +4,20 @@ exports.logoutCommand = logoutCommand;
4
4
  const config_1 = require("../lib/config");
5
5
  const format_1 = require("../lib/format");
6
6
  /**
7
- * `ple logout` — delete the local config file. No server call is made (the
7
+ * `ple logout` — delete the local session file. No server call is made (the
8
8
  * session expires naturally); this only clears local state.
9
+ *
10
+ * A corrupt or unreadable session file is deleted too: logout is the documented
11
+ * fix for that state, so it must not answer "Not logged in" and leave the file.
9
12
  */
10
13
  async function logoutCommand() {
11
- const existing = (0, config_1.readConfig)();
12
- if (!existing) {
14
+ if ((0, config_1.configStatus)() === 'absent') {
13
15
  console.log(format_1.c.muted('Not logged in.'));
14
16
  return;
15
17
  }
18
+ const existing = (0, config_1.readConfig)();
16
19
  (0, config_1.clearConfig)();
17
- console.log(format_1.c.success(`✓ Logged out (${existing.email}).`));
20
+ console.log(existing
21
+ ? format_1.c.success(`✓ Logged out (${existing.email}).`)
22
+ : format_1.c.success('✓ Removed the unreadable session file. You are logged out.'));
18
23
  }