@phnx-labs/artifacts-cli 0.4.7 → 0.6.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 (128) hide show
  1. package/CHANGELOG.md +135 -1
  2. package/README.md +161 -10
  3. package/dist/cli.d.ts +1 -6
  4. package/dist/cli.js +100 -88
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/auth.d.ts +5 -0
  7. package/dist/commands/auth.js +112 -0
  8. package/dist/commands/auth.js.map +1 -0
  9. package/dist/commands/favorite.d.ts +9 -0
  10. package/dist/commands/favorite.js +59 -0
  11. package/dist/commands/favorite.js.map +1 -0
  12. package/dist/commands/share.d.ts +297 -14
  13. package/dist/commands/share.js +1351 -71
  14. package/dist/commands/share.js.map +1 -1
  15. package/dist/lib/browser-detect.d.ts +28 -0
  16. package/dist/lib/browser-detect.js +126 -0
  17. package/dist/lib/browser-detect.js.map +1 -0
  18. package/dist/lib/components.d.ts +23 -0
  19. package/dist/lib/components.js +44 -0
  20. package/dist/lib/components.js.map +1 -0
  21. package/dist/lib/config.d.ts +17 -0
  22. package/dist/lib/config.js +8 -0
  23. package/dist/lib/config.js.map +1 -1
  24. package/dist/lib/embedded-html.d.ts +1 -1
  25. package/dist/lib/embedded-html.js +14 -0
  26. package/dist/lib/embedded-html.js.map +1 -1
  27. package/dist/lib/excerpt.d.ts +48 -0
  28. package/dist/lib/excerpt.js +167 -0
  29. package/dist/lib/excerpt.js.map +1 -0
  30. package/dist/lib/explorer.d.ts +37 -0
  31. package/dist/lib/explorer.js +166 -0
  32. package/dist/lib/explorer.js.map +1 -0
  33. package/dist/lib/favorites.d.ts +73 -0
  34. package/dist/lib/favorites.js +180 -0
  35. package/dist/lib/favorites.js.map +1 -0
  36. package/dist/lib/format.d.ts +2 -0
  37. package/dist/lib/format.js +14 -0
  38. package/dist/lib/format.js.map +1 -0
  39. package/dist/lib/github.d.ts +14 -0
  40. package/dist/lib/github.js +36 -0
  41. package/dist/lib/github.js.map +1 -0
  42. package/dist/lib/header-actions.d.ts +44 -0
  43. package/dist/lib/header-actions.js +181 -0
  44. package/dist/lib/header-actions.js.map +1 -0
  45. package/dist/lib/identity/client.d.ts +49 -0
  46. package/dist/lib/identity/client.js +97 -0
  47. package/dist/lib/identity/client.js.map +1 -0
  48. package/dist/lib/identity/index.d.ts +60 -0
  49. package/dist/lib/identity/index.js +69 -0
  50. package/dist/lib/identity/index.js.map +1 -0
  51. package/dist/lib/link-previews.d.ts +67 -0
  52. package/dist/lib/link-previews.js +427 -0
  53. package/dist/lib/link-previews.js.map +1 -0
  54. package/dist/lib/links.d.ts +2 -0
  55. package/dist/lib/links.js +21 -2
  56. package/dist/lib/links.js.map +1 -1
  57. package/dist/lib/math.d.ts +31 -0
  58. package/dist/lib/math.js +122 -0
  59. package/dist/lib/math.js.map +1 -0
  60. package/dist/lib/metadata-menu.d.ts +15 -0
  61. package/dist/lib/metadata-menu.js +23 -0
  62. package/dist/lib/metadata-menu.js.map +1 -1
  63. package/dist/lib/open.d.ts +6 -0
  64. package/dist/lib/open.js +54 -0
  65. package/dist/lib/open.js.map +1 -0
  66. package/dist/lib/render.d.ts +5 -0
  67. package/dist/lib/render.js +166 -35
  68. package/dist/lib/render.js.map +1 -1
  69. package/dist/lib/revisions.d.ts +17 -0
  70. package/dist/lib/revisions.js +6 -1
  71. package/dist/lib/revisions.js.map +1 -1
  72. package/dist/lib/share/analytics.d.ts +13 -0
  73. package/dist/lib/share/analytics.js +46 -0
  74. package/dist/lib/share/analytics.js.map +1 -0
  75. package/dist/lib/share/backend.d.ts +105 -0
  76. package/dist/lib/share/backend.js +161 -0
  77. package/dist/lib/share/backend.js.map +1 -0
  78. package/dist/lib/share/capture.d.ts +31 -0
  79. package/dist/lib/share/capture.js +175 -0
  80. package/dist/lib/share/capture.js.map +1 -0
  81. package/dist/lib/share/config.d.ts +82 -0
  82. package/dist/lib/share/config.js +181 -0
  83. package/dist/lib/share/config.js.map +1 -0
  84. package/dist/lib/share/delete.d.ts +122 -0
  85. package/dist/lib/share/delete.js +174 -0
  86. package/dist/lib/share/delete.js.map +1 -0
  87. package/dist/lib/share/html.d.ts +22 -0
  88. package/dist/lib/share/html.js +89 -0
  89. package/dist/lib/share/html.js.map +1 -0
  90. package/dist/lib/share/http-error.d.ts +52 -0
  91. package/dist/lib/share/http-error.js +66 -0
  92. package/dist/lib/share/http-error.js.map +1 -0
  93. package/dist/lib/share/og.d.ts +25 -0
  94. package/dist/lib/share/og.js +85 -0
  95. package/dist/lib/share/og.js.map +1 -0
  96. package/dist/lib/share/provision.d.ts +99 -0
  97. package/dist/lib/share/provision.js +271 -0
  98. package/dist/lib/share/provision.js.map +1 -0
  99. package/dist/lib/share/publish.d.ts +393 -0
  100. package/dist/lib/share/publish.js +829 -0
  101. package/dist/lib/share/publish.js.map +1 -0
  102. package/dist/lib/share/qr.d.ts +36 -0
  103. package/dist/lib/share/qr.js +102 -0
  104. package/dist/lib/share/qr.js.map +1 -0
  105. package/dist/lib/share/storage-policy.d.ts +9 -0
  106. package/dist/lib/share/storage-policy.js +43 -0
  107. package/dist/lib/share/storage-policy.js.map +1 -0
  108. package/dist/lib/share/visibility.d.ts +92 -0
  109. package/dist/lib/share/visibility.js +108 -0
  110. package/dist/lib/share/visibility.js.map +1 -0
  111. package/dist/lib/share/worker-template.d.ts +29 -0
  112. package/dist/lib/share/worker-template.js +2154 -0
  113. package/dist/lib/share/worker-template.js.map +1 -0
  114. package/dist/lib/status-list.d.ts +49 -0
  115. package/dist/lib/status-list.js +153 -0
  116. package/dist/lib/status-list.js.map +1 -0
  117. package/dist/lib/validate.js +128 -9
  118. package/dist/lib/validate.js.map +1 -1
  119. package/package.json +12 -3
  120. package/dist/lib/share-provision.d.ts +0 -31
  121. package/dist/lib/share-provision.js +0 -83
  122. package/dist/lib/share-provision.js.map +0 -1
  123. package/dist/lib/share-worker.d.ts +0 -1
  124. package/dist/lib/share-worker.js +0 -66
  125. package/dist/lib/share-worker.js.map +0 -1
  126. package/dist/lib/share.d.ts +0 -39
  127. package/dist/lib/share.js +0 -159
  128. package/dist/lib/share.js.map +0 -1
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Favorites and the local artifact listing.
3
+ *
4
+ * The revision store (`revisions.ts`) already knows every rendered artifact:
5
+ * one directory per source under {@link historyRoot}, keyed by the SHA-256 of
6
+ * its canonical path, with a strict-integrity `manifest.json`. Favorites ride
7
+ * BESIDE that store in a single `favorites.json` at the same root rather than
8
+ * inside each manifest — a manifest is rewritten only inside the locked
9
+ * serialize→render→write transaction, and a favorite toggle must never touch
10
+ * (or be blocked by) that pipeline.
11
+ *
12
+ * Same env override as the revision store (`ARTIFACTS_HISTORY_DIR`), so a test
13
+ * or a scratch HOME relocates both together. Reads are lock-free (writes are
14
+ * atomic renames); writes take a lock on the store root so a served page and a
15
+ * CLI toggle never lose each other's update.
16
+ */
17
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from 'node:fs';
18
+ import { closeSync, fsyncSync, openSync, writeFileSync } from 'node:fs';
19
+ import { randomBytes } from 'node:crypto';
20
+ import { basename, dirname, join } from 'node:path';
21
+ import { lock } from 'proper-lockfile';
22
+ import { artifactTarget, historyRoot } from './revisions.js';
23
+ const FAVORITES_SCHEMA = 'artifacts.favorites.v1';
24
+ const FAVORITES_FILE = 'favorites.json';
25
+ const FILE_MODE = 0o600;
26
+ const ID_RE = /^[0-9a-f]{64}$/;
27
+ export function favoritesPath() {
28
+ return join(historyRoot(), FAVORITES_FILE);
29
+ }
30
+ /**
31
+ * Read the favorites file. Absent means "no favorites yet"; present but
32
+ * unparseable or wrong-shaped is fatal — never silently reset a user's marks
33
+ * behind a transient read glitch (same rule as the revision manifest).
34
+ */
35
+ export function readFavorites(file = favoritesPath()) {
36
+ if (!existsSync(file))
37
+ return {};
38
+ let parsed;
39
+ try {
40
+ parsed = JSON.parse(readFileSync(file, 'utf8'));
41
+ }
42
+ catch (error) {
43
+ throw new Error(`Corrupt favorites file at ${file}: ${error.message}`);
44
+ }
45
+ const v = parsed;
46
+ if (!v || v.schema !== FAVORITES_SCHEMA || typeof v.favorites !== 'object' || v.favorites === null) {
47
+ throw new Error(`Corrupt favorites file at ${file}: unexpected shape`);
48
+ }
49
+ return v.favorites;
50
+ }
51
+ function atomicWrite(target, data, mode) {
52
+ const tmp = join(dirname(target), `.${basename(target)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
53
+ const fd = openSync(tmp, 'wx', mode);
54
+ try {
55
+ writeFileSync(fd, data);
56
+ fsyncSync(fd);
57
+ }
58
+ finally {
59
+ closeSync(fd);
60
+ }
61
+ renameSync(tmp, target);
62
+ }
63
+ /**
64
+ * Set, clear, or flip the favorite flag for an artifact (a source path or a
65
+ * bare 64-hex id). The current-state read for a flip happens INSIDE the lock
66
+ * on the store root — reading before acquiring it would let two concurrent
67
+ * toggles both compute the same next state and collapse into one.
68
+ * Returns the resulting state.
69
+ */
70
+ export async function setFavorite(sourceOrId, favorite, extra = {}) {
71
+ const { id, sourcePath } = artifactTarget(sourceOrId);
72
+ const root = historyRoot();
73
+ mkdirSync(root, { recursive: true, mode: 0o700 });
74
+ const release = await lock(root, {
75
+ realpath: false,
76
+ // A concurrent toggle (a served page and a CLI invocation racing) waits
77
+ // briefly instead of failing outright.
78
+ retries: { retries: 20, factor: 1.4, minTimeout: 25, maxTimeout: 500 },
79
+ });
80
+ try {
81
+ const file = favoritesPath();
82
+ const favorites = readFavorites(file);
83
+ const next = favorite === 'toggle' ? !favorites[id] : favorite;
84
+ if (next) {
85
+ const prior = favorites[id];
86
+ favorites[id] = {
87
+ sourcePath: extra.sourcePath ?? sourcePath ?? prior?.sourcePath,
88
+ title: extra.title ?? prior?.title,
89
+ favoritedAt: prior?.favoritedAt ?? new Date().toISOString(),
90
+ };
91
+ }
92
+ else {
93
+ delete favorites[id];
94
+ }
95
+ atomicWrite(file, JSON.stringify({ schema: FAVORITES_SCHEMA, favorites }, null, 2) + '\n', FILE_MODE);
96
+ return { id, favorite: next };
97
+ }
98
+ finally {
99
+ await release();
100
+ }
101
+ }
102
+ /** Flip the favorite flag (atomically, under the store lock); returns the resulting state. */
103
+ export async function toggleFavorite(sourceOrId, extra = {}) {
104
+ return setFavorite(sourceOrId, 'toggle', extra);
105
+ }
106
+ export function isFavorite(sourceOrId) {
107
+ const { id } = artifactTarget(sourceOrId);
108
+ return Boolean(readFavorites()[id]);
109
+ }
110
+ /** Frontmatter `title:` of a Markdown source, when the file still exists. */
111
+ function sourceTitle(sourcePath) {
112
+ try {
113
+ const raw = readFileSync(sourcePath, 'utf8');
114
+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(raw);
115
+ const line = frontmatter && /^title:\s*(.+)$/m.exec(frontmatter[1]);
116
+ const title = line?.[1]?.trim().replace(/^["']|["']$/g, '').trim();
117
+ if (title)
118
+ return title;
119
+ }
120
+ catch {
121
+ // Source moved or unreadable — the basename is the fallback below.
122
+ }
123
+ return '';
124
+ }
125
+ /**
126
+ * Enumerate every artifact the local store knows: the union of the revision
127
+ * manifests and the favorites file (a favorite can outlive — or predate — a
128
+ * manifest). A manifest that fails to parse is SKIPPED rather than fatal: a
129
+ * listing must degrade gracefully, unlike the integrity gate a targeted
130
+ * `history` read applies. Sorted most-recently-updated first.
131
+ */
132
+ export function listArtifacts() {
133
+ const root = historyRoot();
134
+ const favorites = readFavorites();
135
+ const byId = new Map();
136
+ if (existsSync(root)) {
137
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
138
+ if (!entry.isDirectory() || !ID_RE.test(entry.name))
139
+ continue;
140
+ const manifestFile = join(root, entry.name, 'manifest.json');
141
+ if (!existsSync(manifestFile))
142
+ continue;
143
+ let manifest;
144
+ try {
145
+ manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
146
+ }
147
+ catch {
148
+ continue;
149
+ }
150
+ const revisions = Array.isArray(manifest.revisions) ? manifest.revisions : [];
151
+ const first = revisions[0];
152
+ const last = revisions.at(-1);
153
+ const sourcePath = typeof manifest.sourcePath === 'string' ? manifest.sourcePath : '';
154
+ byId.set(entry.name, {
155
+ id: entry.name,
156
+ sourcePath,
157
+ title: favorites[entry.name]?.title || sourceTitle(sourcePath) || basename(sourcePath),
158
+ createdAt: first?.createdAt ?? '',
159
+ updatedAt: last?.createdAt ?? '',
160
+ revisionCount: revisions.length,
161
+ favorite: Boolean(favorites[entry.name]),
162
+ });
163
+ }
164
+ }
165
+ for (const [id, entry] of Object.entries(favorites)) {
166
+ if (byId.has(id) || !ID_RE.test(id))
167
+ continue;
168
+ byId.set(id, {
169
+ id,
170
+ sourcePath: entry.sourcePath ?? '',
171
+ title: entry.title || (entry.sourcePath ? basename(entry.sourcePath) : ''),
172
+ createdAt: '',
173
+ updatedAt: '',
174
+ revisionCount: 0,
175
+ favorite: true,
176
+ });
177
+ }
178
+ return [...byId.values()].sort((a, b) => (b.updatedAt || b.createdAt).localeCompare(a.updatedAt || a.createdAt));
179
+ }
180
+ //# sourceMappingURL=favorites.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"favorites.js","sourceRoot":"","sources":["../../src/lib/favorites.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACvF,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAe7D,MAAM,gBAAgB,GAAG,wBAAwB,CAAC;AAClD,MAAM,cAAc,GAAG,gBAAgB,CAAC;AACxC,MAA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CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;AACnH,CAAC"}
@@ -0,0 +1,2 @@
1
+ /** Human-readable bytes, e.g. `1.2 KB`, `640 B`. */
2
+ export declare function formatBytes(n: number): string;
@@ -0,0 +1,14 @@
1
+ /** Human-readable bytes, e.g. `1.2 KB`, `640 B`. */
2
+ export function formatBytes(n) {
3
+ if (n < 1024)
4
+ return `${n} B`;
5
+ const units = ['KB', 'MB', 'GB', 'TB'];
6
+ let size = n / 1024;
7
+ let unit = 0;
8
+ while (size >= 1024 && unit < units.length - 1) {
9
+ size /= 1024;
10
+ unit++;
11
+ }
12
+ return `${size < 10 ? size.toFixed(1) : Math.round(size)} ${units[unit]}`;
13
+ }
14
+ //# sourceMappingURL=format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.js","sourceRoot":"","sources":["../../src/lib/format.ts"],"names":[],"mappings":"AAAA,oDAAoD;AACpD,MAAM,UAAU,WAAW,CAAC,CAAS;IACnC,IAAI,CAAC,GAAG,IAAI;QAAE,OAAO,GAAG,CAAC,IAAI,CAAC;IAC9B,MAAM,KAAK,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,IAAI,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC;IACpB,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,OAAO,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC/C,IAAI,IAAI,IAAI,CAAC;QACb,IAAI,EAAE,CAAC;IACT,CAAC;IACD,OAAO,GAAG,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;AAC5E,CAAC"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The publisher's GitHub username — the URL namespace a BYO (bring-your-own
3
+ * Cloudflare) share publishes under. The managed endpoint namespaces on the
4
+ * Phoenix handle instead and never calls this.
5
+ */
6
+ /** Explicit override, so a machine with no `gh` and no git config can still publish. */
7
+ export declare const GITHUB_USER_ENV = "ARTIFACTS_GITHUB_USER";
8
+ /**
9
+ * Resolve the GitHub username: the explicit env override, then the signed-in
10
+ * `gh` account, then `git config --global github.user`. `null` when none of the
11
+ * three answer — the caller turns that into an actionable error rather than
12
+ * inventing a namespace.
13
+ */
14
+ export declare function resolveGitHubUsername(): Promise<string | null>;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The publisher's GitHub username — the URL namespace a BYO (bring-your-own
3
+ * Cloudflare) share publishes under. The managed endpoint namespaces on the
4
+ * Phoenix handle instead and never calls this.
5
+ */
6
+ import { execFile } from 'node:child_process';
7
+ import { promisify } from 'node:util';
8
+ const execFileAsync = promisify(execFile);
9
+ /** Explicit override, so a machine with no `gh` and no git config can still publish. */
10
+ export const GITHUB_USER_ENV = 'ARTIFACTS_GITHUB_USER';
11
+ async function tryCommand(file, args) {
12
+ try {
13
+ const { stdout } = await execFileAsync(file, args, { encoding: 'utf8', timeout: 10_000 });
14
+ const value = stdout.trim();
15
+ return value || null;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ /**
22
+ * Resolve the GitHub username: the explicit env override, then the signed-in
23
+ * `gh` account, then `git config --global github.user`. `null` when none of the
24
+ * three answer — the caller turns that into an actionable error rather than
25
+ * inventing a namespace.
26
+ */
27
+ export async function resolveGitHubUsername() {
28
+ const fromEnv = process.env[GITHUB_USER_ENV]?.trim();
29
+ if (fromEnv)
30
+ return fromEnv;
31
+ const fromGh = await tryCommand('gh', ['api', 'user', '-q', '.login']);
32
+ if (fromGh)
33
+ return fromGh;
34
+ return tryCommand('git', ['config', '--global', 'github.user']);
35
+ }
36
+ //# sourceMappingURL=github.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github.js","sourceRoot":"","sources":["../../src/lib/github.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAE1C,wFAAwF;AACxF,MAAM,CAAC,MAAM,eAAe,GAAG,uBAAuB,CAAC;AAEvD,KAAK,UAAU,UAAU,CAAC,IAAY,EAAE,IAAc;IACpD,IAAI,CAAC;QACH,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,aAAa,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;QAC1F,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;QAC5B,OAAO,KAAK,IAAI,IAAI,CAAC;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB;IACzC,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC;IACrD,IAAI,OAAO;QAAE,OAAO,OAAO,CAAC;IAC5B,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC;IACvE,IAAI,MAAM;QAAE,OAAO,MAAM,CAAC;IAC1B,OAAO,UAAU,CAAC,KAAK,EAAE,CAAC,QAAQ,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC;AAClE,CAAC"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The document-header action buttons: Share and Favorite.
3
+ *
4
+ * One markup builder, one style block, one script. The renderer emits the
5
+ * slot between {@link HEADER_ACTIONS_START}/{@link HEADER_ACTIONS_END} markers
6
+ * with the buttons in their DEFAULT (unfavorited) state, so the render
7
+ * fingerprint never flips on a favorite toggle; the decorate step (which runs
8
+ * after fingerprinting) rewrites the slot with the favorite state actually
9
+ * recorded in the store.
10
+ *
11
+ * Click behavior is decided at runtime by where the page is being viewed:
12
+ * - served by `artifacts render --open` (loopback http): POST back to the
13
+ * local server, which performs the owner-only share / favorite toggle for
14
+ * real and reports the result;
15
+ * - a plain file:// page: the copy-command idiom — the button copies the
16
+ * exact CLI command (`artifacts share <id> --visibility me`,
17
+ * `artifacts favorite <id>`) to run in a terminal;
18
+ * - a hosted page (the managed share host, or any non-loopback origin): the
19
+ * artifact is already published, so Share degrades to copying the page's
20
+ * own URL rather than offering to re-share; Favorite still copies the
21
+ * command (only meaningful on the author's machine, harmless elsewhere).
22
+ *
23
+ * The copied commands address the artifact by its store ID, never by path —
24
+ * reader-facing HTML must not carry local absolute paths (the revision store
25
+ * has a standing test for that invariant), and `artifacts share` accepts an id
26
+ * exactly like `artifacts history` does.
27
+ */
28
+ export declare const HEADER_ACTIONS_START = "<!--artifact-actions-start-->";
29
+ export declare const HEADER_ACTIONS_END = "<!--artifact-actions-end-->";
30
+ export interface HeaderActions {
31
+ /** The artifact's store identity (SHA-256 of its canonical source path). */
32
+ artifactId: string;
33
+ /** Render-time favorite state; the decorate step replaces it with the store's. */
34
+ favorited: boolean;
35
+ }
36
+ export declare function shareCommand(actions: HeaderActions): string;
37
+ export declare function favoriteCommand(actions: HeaderActions): string;
38
+ export declare function headerActions(actions: HeaderActions): string;
39
+ /** The slot the renderer emits; `decorateHeaderActions` rewrites its content. */
40
+ export declare function headerActionsSlot(actions: HeaderActions): string;
41
+ /** Replace a rendered document's action slot with fresh state. No markers → unchanged. */
42
+ export declare function decorateHeaderActions(html: string, actions: HeaderActions): string;
43
+ export declare const HEADER_ACTIONS_CSS = "\n.header-actions{display:inline-flex;align-items:center;gap:6px;flex:0 0 auto}\n.header-action{display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 12px;border:1px solid var(--line);border-radius:999px;background:var(--surface);color:var(--muted);font:500 12px/1 var(--font-mono);cursor:pointer}\n.header-action:hover{color:var(--accent);border-color:var(--accent)}\n.header-action:focus-visible{outline:2px solid var(--accent);outline-offset:2px}\n.header-action:disabled{opacity:.6;cursor:default}\n.header-action svg{width:13px;height:13px;flex:0 0 auto}\n.favorite-action{padding:0 10px;border-color:color-mix(in srgb,var(--accent) 45%,var(--line));color:var(--accent)}\n.favorite-action.is-favorite{background:color-mix(in srgb,var(--accent) 16%,var(--surface));border-color:var(--accent)}\n.favorite-action.is-favorite svg{fill:currentColor}\n.header-action-feedback{color:var(--muted);font:11.5px/1.4 var(--font-mono);max-width:300px;overflow-wrap:anywhere}\n.header-action-feedback:empty{display:none}\n@media print{.header-actions{display:none}}\n";
44
+ export declare const HEADER_ACTIONS_SCRIPT = "<script>\n(() => {\n const root = document.querySelector('[data-header-actions]');\n if (!root) return;\n const shareButton = root.querySelector('.share-action');\n const favoriteButton = root.querySelector('.favorite-action');\n const status = root.querySelector('.header-action-feedback');\n let timer;\n const say = (message) => {\n status.textContent = message;\n clearTimeout(timer);\n timer = setTimeout(() => { if (status.textContent === message) status.textContent = ''; }, 8000);\n };\n const copy = async (text) => {\n try {\n if (!navigator.clipboard || !navigator.clipboard.writeText) throw new Error('unavailable');\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n const area = document.createElement('textarea');\n area.value = text;\n area.style.position = 'fixed'; area.style.opacity = '0';\n document.body.appendChild(area);\n area.focus(); area.select();\n let ok = false;\n try { ok = document.execCommand('copy'); } catch {}\n area.remove();\n return ok;\n }\n };\n // Where is this page being viewed? The loopback dev server (artifacts render\n // --open) answers POSTs for real actions; any other http(s) origin is an\n // already-published page; file:// has no server at all.\n const hostname = location.hostname;\n const web = location.protocol === 'http:' || location.protocol === 'https:';\n const loopback = web && (hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]' || hostname === '::1');\n const hosted = web && !loopback;\n const copyCommand = async (command, what) => {\n const ok = await copy(command);\n say(ok ? what + ' command copied \u2014 run it in your terminal' : 'Could not copy. ' + what + ' command: ' + command);\n };\n const paintFavorite = (on) => {\n favoriteButton.classList.toggle('is-favorite', on);\n favoriteButton.setAttribute('aria-pressed', String(on));\n const label = on ? 'Remove from favorites' : 'Add to favorites';\n favoriteButton.setAttribute('aria-label', label);\n favoriteButton.setAttribute('title', on ? 'Remove from favorites' : 'Favorite this artifact');\n };\n if (hosted) {\n // Already published: re-sharing makes no sense here, so Share becomes a\n // plain copy-link of this page's URL.\n shareButton.querySelector('.share-action-label').textContent = 'Copy link';\n shareButton.setAttribute('aria-label', 'Copy link to this page');\n shareButton.setAttribute('title', 'Copy the link to this page');\n shareButton.addEventListener('click', async () => {\n const ok = await copy(location.href);\n say(ok ? 'Link copied' : 'Could not copy the link \u2014 copy it from the address bar');\n });\n } else if (loopback) {\n shareButton.addEventListener('click', async () => {\n shareButton.disabled = true;\n say('Sharing owner-only\u2026');\n try {\n const response = await fetch('/artifacts/share', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });\n if (!response.ok) throw new Error(await response.text());\n const result = await response.json();\n const copied = await copy(result.url);\n say(copied ? 'Shared owner-only \u2014 link copied' : 'Shared owner-only: ' + result.url);\n } catch (error) {\n await copyCommand(shareButton.dataset.shareCommand, 'Share');\n } finally {\n shareButton.disabled = false;\n }\n });\n } else {\n shareButton.addEventListener('click', () => copyCommand(shareButton.dataset.shareCommand, 'Share'));\n }\n if (loopback) {\n favoriteButton.addEventListener('click', async () => {\n favoriteButton.disabled = true;\n try {\n const response = await fetch('/artifacts/favorite', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ title: document.title }),\n });\n if (!response.ok) throw new Error(await response.text());\n const result = await response.json();\n paintFavorite(Boolean(result.favorite));\n say(result.favorite ? 'Favorited' : 'Removed from favorites');\n } catch {\n await copyCommand(favoriteButton.dataset.favoriteCommand, 'Favorite');\n } finally {\n favoriteButton.disabled = false;\n }\n });\n } else {\n favoriteButton.addEventListener('click', () => copyCommand(favoriteButton.dataset.favoriteCommand, 'Favorite'));\n }\n})();\n</script>";
@@ -0,0 +1,181 @@
1
+ /**
2
+ * The document-header action buttons: Share and Favorite.
3
+ *
4
+ * One markup builder, one style block, one script. The renderer emits the
5
+ * slot between {@link HEADER_ACTIONS_START}/{@link HEADER_ACTIONS_END} markers
6
+ * with the buttons in their DEFAULT (unfavorited) state, so the render
7
+ * fingerprint never flips on a favorite toggle; the decorate step (which runs
8
+ * after fingerprinting) rewrites the slot with the favorite state actually
9
+ * recorded in the store.
10
+ *
11
+ * Click behavior is decided at runtime by where the page is being viewed:
12
+ * - served by `artifacts render --open` (loopback http): POST back to the
13
+ * local server, which performs the owner-only share / favorite toggle for
14
+ * real and reports the result;
15
+ * - a plain file:// page: the copy-command idiom — the button copies the
16
+ * exact CLI command (`artifacts share <id> --visibility me`,
17
+ * `artifacts favorite <id>`) to run in a terminal;
18
+ * - a hosted page (the managed share host, or any non-loopback origin): the
19
+ * artifact is already published, so Share degrades to copying the page's
20
+ * own URL rather than offering to re-share; Favorite still copies the
21
+ * command (only meaningful on the author's machine, harmless elsewhere).
22
+ *
23
+ * The copied commands address the artifact by its store ID, never by path —
24
+ * reader-facing HTML must not carry local absolute paths (the revision store
25
+ * has a standing test for that invariant), and `artifacts share` accepts an id
26
+ * exactly like `artifacts history` does.
27
+ */
28
+ import { escapeHtml } from './html.js';
29
+ export const HEADER_ACTIONS_START = '<!--artifact-actions-start-->';
30
+ export const HEADER_ACTIONS_END = '<!--artifact-actions-end-->';
31
+ export function shareCommand(actions) {
32
+ // The id is a fixed-shape [0-9a-f]{64} digest — safe unquoted.
33
+ return `artifacts share ${actions.artifactId} --visibility me`;
34
+ }
35
+ export function favoriteCommand(actions) {
36
+ return `artifacts favorite ${actions.artifactId}`;
37
+ }
38
+ const STAR_PATH = 'M12 2.6l2.9 6.28 6.9.68-5.19 4.6 1.44 6.8L12 17.77l-6.05 3.19 1.44-6.8-5.19-4.6 6.9-.68z';
39
+ const SHARE_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 15V3.5"/><path d="M7.5 7.5L12 3l4.5 4.5"/><path d="M4.5 13.5v5a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-5"/></svg>';
40
+ export function headerActions(actions) {
41
+ const share = shareCommand(actions);
42
+ const favorite = favoriteCommand(actions);
43
+ const on = actions.favorited;
44
+ return (`<span class="header-actions" data-header-actions>` +
45
+ `<button type="button" class="header-action share-action" data-share-command="${escapeHtml(share)}" ` +
46
+ `aria-label="Share owner-only (only you can open the link)" title="Share owner-only — only you can open the link. Copies the share command; shares directly when served by artifacts render --open.">` +
47
+ `${SHARE_ICON}<span class="share-action-label">Share</span></button>` +
48
+ `<button type="button" class="header-action favorite-action${on ? ' is-favorite' : ''}" data-favorite-command="${escapeHtml(favorite)}" ` +
49
+ `aria-pressed="${on}" aria-label="${on ? 'Remove from favorites' : 'Add to favorites'}" title="${on ? 'Remove from favorites' : 'Favorite this artifact'}">` +
50
+ `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="${STAR_PATH}"/></svg></button>` +
51
+ `<span class="header-action-feedback" role="status" aria-live="polite"></span>` +
52
+ `</span>`);
53
+ }
54
+ /** The slot the renderer emits; `decorateHeaderActions` rewrites its content. */
55
+ export function headerActionsSlot(actions) {
56
+ return `${HEADER_ACTIONS_START}${headerActions(actions)}${HEADER_ACTIONS_END}`;
57
+ }
58
+ /** Replace a rendered document's action slot with fresh state. No markers → unchanged. */
59
+ export function decorateHeaderActions(html, actions) {
60
+ const start = html.indexOf(HEADER_ACTIONS_START);
61
+ const end = html.indexOf(HEADER_ACTIONS_END, start);
62
+ if (start < 0 || end < 0)
63
+ return html;
64
+ return html.slice(0, start) + headerActionsSlot(actions) + html.slice(end + HEADER_ACTIONS_END.length);
65
+ }
66
+ export const HEADER_ACTIONS_CSS = `
67
+ .header-actions{display:inline-flex;align-items:center;gap:6px;flex:0 0 auto}
68
+ .header-action{display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 12px;border:1px solid var(--line);border-radius:999px;background:var(--surface);color:var(--muted);font:500 12px/1 var(--font-mono);cursor:pointer}
69
+ .header-action:hover{color:var(--accent);border-color:var(--accent)}
70
+ .header-action:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
71
+ .header-action:disabled{opacity:.6;cursor:default}
72
+ .header-action svg{width:13px;height:13px;flex:0 0 auto}
73
+ .favorite-action{padding:0 10px;border-color:color-mix(in srgb,var(--accent) 45%,var(--line));color:var(--accent)}
74
+ .favorite-action.is-favorite{background:color-mix(in srgb,var(--accent) 16%,var(--surface));border-color:var(--accent)}
75
+ .favorite-action.is-favorite svg{fill:currentColor}
76
+ .header-action-feedback{color:var(--muted);font:11.5px/1.4 var(--font-mono);max-width:300px;overflow-wrap:anywhere}
77
+ .header-action-feedback:empty{display:none}
78
+ @media print{.header-actions{display:none}}
79
+ `;
80
+ export const HEADER_ACTIONS_SCRIPT = `<script>
81
+ (() => {
82
+ const root = document.querySelector('[data-header-actions]');
83
+ if (!root) return;
84
+ const shareButton = root.querySelector('.share-action');
85
+ const favoriteButton = root.querySelector('.favorite-action');
86
+ const status = root.querySelector('.header-action-feedback');
87
+ let timer;
88
+ const say = (message) => {
89
+ status.textContent = message;
90
+ clearTimeout(timer);
91
+ timer = setTimeout(() => { if (status.textContent === message) status.textContent = ''; }, 8000);
92
+ };
93
+ const copy = async (text) => {
94
+ try {
95
+ if (!navigator.clipboard || !navigator.clipboard.writeText) throw new Error('unavailable');
96
+ await navigator.clipboard.writeText(text);
97
+ return true;
98
+ } catch {
99
+ const area = document.createElement('textarea');
100
+ area.value = text;
101
+ area.style.position = 'fixed'; area.style.opacity = '0';
102
+ document.body.appendChild(area);
103
+ area.focus(); area.select();
104
+ let ok = false;
105
+ try { ok = document.execCommand('copy'); } catch {}
106
+ area.remove();
107
+ return ok;
108
+ }
109
+ };
110
+ // Where is this page being viewed? The loopback dev server (artifacts render
111
+ // --open) answers POSTs for real actions; any other http(s) origin is an
112
+ // already-published page; file:// has no server at all.
113
+ const hostname = location.hostname;
114
+ const web = location.protocol === 'http:' || location.protocol === 'https:';
115
+ const loopback = web && (hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]' || hostname === '::1');
116
+ const hosted = web && !loopback;
117
+ const copyCommand = async (command, what) => {
118
+ const ok = await copy(command);
119
+ say(ok ? what + ' command copied — run it in your terminal' : 'Could not copy. ' + what + ' command: ' + command);
120
+ };
121
+ const paintFavorite = (on) => {
122
+ favoriteButton.classList.toggle('is-favorite', on);
123
+ favoriteButton.setAttribute('aria-pressed', String(on));
124
+ const label = on ? 'Remove from favorites' : 'Add to favorites';
125
+ favoriteButton.setAttribute('aria-label', label);
126
+ favoriteButton.setAttribute('title', on ? 'Remove from favorites' : 'Favorite this artifact');
127
+ };
128
+ if (hosted) {
129
+ // Already published: re-sharing makes no sense here, so Share becomes a
130
+ // plain copy-link of this page's URL.
131
+ shareButton.querySelector('.share-action-label').textContent = 'Copy link';
132
+ shareButton.setAttribute('aria-label', 'Copy link to this page');
133
+ shareButton.setAttribute('title', 'Copy the link to this page');
134
+ shareButton.addEventListener('click', async () => {
135
+ const ok = await copy(location.href);
136
+ say(ok ? 'Link copied' : 'Could not copy the link — copy it from the address bar');
137
+ });
138
+ } else if (loopback) {
139
+ shareButton.addEventListener('click', async () => {
140
+ shareButton.disabled = true;
141
+ say('Sharing owner-only…');
142
+ try {
143
+ const response = await fetch('/artifacts/share', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
144
+ if (!response.ok) throw new Error(await response.text());
145
+ const result = await response.json();
146
+ const copied = await copy(result.url);
147
+ say(copied ? 'Shared owner-only — link copied' : 'Shared owner-only: ' + result.url);
148
+ } catch (error) {
149
+ await copyCommand(shareButton.dataset.shareCommand, 'Share');
150
+ } finally {
151
+ shareButton.disabled = false;
152
+ }
153
+ });
154
+ } else {
155
+ shareButton.addEventListener('click', () => copyCommand(shareButton.dataset.shareCommand, 'Share'));
156
+ }
157
+ if (loopback) {
158
+ favoriteButton.addEventListener('click', async () => {
159
+ favoriteButton.disabled = true;
160
+ try {
161
+ const response = await fetch('/artifacts/favorite', {
162
+ method: 'POST',
163
+ headers: { 'content-type': 'application/json' },
164
+ body: JSON.stringify({ title: document.title }),
165
+ });
166
+ if (!response.ok) throw new Error(await response.text());
167
+ const result = await response.json();
168
+ paintFavorite(Boolean(result.favorite));
169
+ say(result.favorite ? 'Favorited' : 'Removed from favorites');
170
+ } catch {
171
+ await copyCommand(favoriteButton.dataset.favoriteCommand, 'Favorite');
172
+ } finally {
173
+ favoriteButton.disabled = false;
174
+ }
175
+ });
176
+ } else {
177
+ favoriteButton.addEventListener('click', () => copyCommand(favoriteButton.dataset.favoriteCommand, 'Favorite'));
178
+ }
179
+ })();
180
+ </script>`;
181
+ //# sourceMappingURL=header-actions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"header-actions.js","sourceRoot":"","sources":["../../src/lib/header-actions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,MAAM,CAAC,MAAM,oBAAoB,GAAG,+BAA+B,CAAC;AACpE,MAAM,CAAC,MAAM,kBAAkB,GAAG,6BAA6B,CAAC;AAShE,MAAM,UAAU,YAAY,CAAC,OAAsB;IACjD,+DAA+D;IAC/D,OAAO,mBAAmB,OAA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CAAC;IACpD,IAAI,KAAK,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,iBAAiB,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;AACzG,CAAC;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;CAajC,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAoG3B,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The ONE place artifacts-cli talks to its account backend (Phoenix ID).
3
+ *
4
+ * One base URL, one token reader, one HTTP funnel, one error type. Commands
5
+ * import from `./index.js` and nothing else builds a Phoenix URL or reads the
6
+ * session file itself.
7
+ */
8
+ /**
9
+ * Where the account backend lives. Config, never a literal at a call site.
10
+ *
11
+ * The default is Phoenix ID's branded custom domain. The managed share Worker
12
+ * verifies its bearers against this same base, so the two must not drift.
13
+ */
14
+ export declare const DEFAULT_PHOENIX_ID_BASE = "https://id.byphoenix.com";
15
+ export declare const PHOENIX_ID_BASE: string;
16
+ /** Our own session file. artifacts-cli never reads another product's credentials. */
17
+ export declare function sessionFilePath(): string;
18
+ export interface PhoenixSession {
19
+ access_token: string;
20
+ email?: string;
21
+ userId?: string;
22
+ /**
23
+ * Hosted OAuth profile image (https URL), when Phoenix ID exposes one. Wins
24
+ * over the email-Gravatar fallback in share attribution. Optional forever —
25
+ * a missing value just means the Gravatar/initials fallback.
26
+ */
27
+ avatarUrl?: string;
28
+ /** Unix ms; absent means the server did not scope the token's lifetime. */
29
+ expires_at?: number;
30
+ }
31
+ export declare function readSession(): PhoenixSession | null;
32
+ export declare function writeSession(session: PhoenixSession): void;
33
+ export declare function clearSession(): void;
34
+ /** An error carrying the server's status and message, so callers can branch on it. */
35
+ export declare class PhoenixApiError extends Error {
36
+ readonly status: number;
37
+ constructor(message: string, status: number);
38
+ }
39
+ interface RequestOptions {
40
+ body?: unknown;
41
+ /** Send the stored session token. Default true; the device-flow start does not. */
42
+ auth?: boolean;
43
+ /** Use this token instead of the stored one (mid-login, before the write). */
44
+ token?: string;
45
+ timeoutMs?: number;
46
+ }
47
+ /** The single HTTP funnel. Every request to the account backend goes through here. */
48
+ export declare function phoenixRequest<T>(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', route: string, opts?: RequestOptions): Promise<T>;
49
+ export {};