@archastro/astroshot 0.2.0 → 0.2.2

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,346 @@
1
+ /**
2
+ * Read-only access to the Astroshots macOS app's real preferences.
3
+ *
4
+ * Two traps make the obvious implementations wrong:
5
+ *
6
+ * 1. Whole-domain plist → JSON conversion can never work. The domain contains
7
+ * AppKit's `NSOSPLastRootDirectory` open-panel bookmark (CFData), and JSON
8
+ * has no representation for it, so `plutil -convert json` aborts with
9
+ * "Invalid object in plist for JSON format" on effectively every real user's
10
+ * machine. Extract one key at a time instead.
11
+ * 2. `~/Library/Preferences/<domain>.plist` is a lazily flushed cache of
12
+ * cfprefsd state, so reading the file can report yesterday's configuration.
13
+ * Go through cfprefsd (`defaults export`) first and treat the file as a
14
+ * fallback only.
15
+ *
16
+ * Nothing here writes: `astroshot doctor` must not mutate app state.
17
+ */
18
+ import fs from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+ import { spawnSync } from "node:child_process";
22
+
23
+ export const ASTROSHOTS_DOMAIN = "ai.archastro.Astroshots";
24
+
25
+ const MISSING_KEY_PATTERN =
26
+ /No value at that key path|invalid key path|Invalid object in plist/i;
27
+
28
+ // Resolve Apple's tools by absolute path. They always live in /usr/bin, and a
29
+ // minimal or empty PATH must never be mistaken for "this user has no watch
30
+ // roots" — that is the exact false negative doctor exists to eliminate.
31
+ const DEFAULTS_BIN = "/usr/bin/defaults";
32
+ const PLUTIL_BIN = "/usr/bin/plutil";
33
+
34
+ /** Whether the tools this module shells out to are actually present. */
35
+ export function preferenceToolsAvailable({ platform = process.platform } = {}) {
36
+ if (platform !== "darwin") return { available: false, missing: [] };
37
+ const missing = [DEFAULTS_BIN, PLUTIL_BIN].filter(
38
+ (binary) => !fs.existsSync(binary),
39
+ );
40
+ return { available: missing.length === 0, missing };
41
+ }
42
+
43
+ /**
44
+ * Snapshot the preference domain as an XML plist.
45
+ *
46
+ * `defaults export` goes through cfprefsd, so it observes what the app itself
47
+ * sees. The on-disk plist is only used when cfprefsd is unavailable.
48
+ */
49
+ export function readPreferenceDomain(
50
+ domain = ASTROSHOTS_DOMAIN,
51
+ { home = os.homedir(), platform = process.platform } = {},
52
+ ) {
53
+ if (platform !== "darwin") {
54
+ return { available: false, source: null, reason: "not-macos" };
55
+ }
56
+
57
+ const exported = spawnSync(DEFAULTS_BIN, ["export", domain, "-"], {
58
+ maxBuffer: 16 * 1024 * 1024,
59
+ });
60
+ if (!exported.error && exported.status === 0 && exported.stdout?.length) {
61
+ return { available: true, source: "cfprefsd", plist: exported.stdout };
62
+ }
63
+
64
+ const plistPath = path.join(
65
+ home,
66
+ "Library",
67
+ "Preferences",
68
+ `${domain}.plist`,
69
+ );
70
+ try {
71
+ const bytes = fs.readFileSync(plistPath);
72
+ return {
73
+ available: true,
74
+ source: "plist-file",
75
+ plist: bytes,
76
+ plistPath,
77
+ staleRisk: true,
78
+ };
79
+ } catch {
80
+ // `defaults` failing to launch is a tool failure, not evidence that the
81
+ // domain is absent.
82
+ if (exported.error) {
83
+ return {
84
+ available: false,
85
+ source: null,
86
+ reason: "tool-unavailable",
87
+ error: exported.error.message,
88
+ };
89
+ }
90
+ return {
91
+ available: false,
92
+ source: null,
93
+ reason:
94
+ exported.status === 1 && !exported.stdout?.length
95
+ ? "domain-not-found"
96
+ : "unreadable",
97
+ };
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Extract a single preference key from a plist snapshot.
103
+ *
104
+ * Three outcomes, deliberately distinct:
105
+ * - `{ present: true, raw }` the key exists
106
+ * - `{ present: false }` the key is genuinely absent
107
+ * - `{ present: false, failed: true }` the tool could not answer
108
+ *
109
+ * A missing key exits non-zero with the same "Invalid object" wording as a real
110
+ * failure, so absence is matched explicitly. Everything else — `plutil`
111
+ * missing, a spawn error, or an unrecognized non-zero exit — is a tool failure.
112
+ * Collapsing the third case into absence would make a correctly configured user
113
+ * read as "setup never completed".
114
+ */
115
+ export function extractPreferenceKey(plist, key, format = "raw") {
116
+ const result = spawnSync(
117
+ PLUTIL_BIN,
118
+ ["-extract", key, format, "-o", "-", "-"],
119
+ { input: plist, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 },
120
+ );
121
+ if (result.error) {
122
+ return { present: false, failed: true, error: result.error.message };
123
+ }
124
+ if (result.status !== 0) {
125
+ if (MISSING_KEY_PATTERN.test(result.stderr ?? "")) {
126
+ return { present: false };
127
+ }
128
+ return {
129
+ present: false,
130
+ failed: true,
131
+ error: (result.stderr ?? "").trim() || `plutil exited ${result.status}`,
132
+ };
133
+ }
134
+ return { present: true, raw: result.stdout };
135
+ }
136
+
137
+ function extractStringArray(plist, key) {
138
+ const extracted = extractPreferenceKey(plist, key, "json");
139
+ if (!extracted.present) {
140
+ return { present: false, failed: extracted.failed, error: extracted.error };
141
+ }
142
+ try {
143
+ const parsed = JSON.parse(extracted.raw);
144
+ if (!Array.isArray(parsed)) return { present: false };
145
+ return {
146
+ present: true,
147
+ value: parsed.filter((entry) => typeof entry === "string"),
148
+ };
149
+ } catch (error) {
150
+ // The key exists but did not decode: unreadable, not absent.
151
+ return {
152
+ present: false,
153
+ failed: true,
154
+ error: error instanceof Error ? error.message : String(error),
155
+ };
156
+ }
157
+ }
158
+
159
+ function extractString(plist, key) {
160
+ const extracted = extractPreferenceKey(plist, key, "raw");
161
+ if (!extracted.present) {
162
+ return { present: false, failed: extracted.failed, error: extracted.error };
163
+ }
164
+ const value = extracted.raw.replace(/\n$/, "");
165
+ return { present: true, value };
166
+ }
167
+
168
+ function extractBoolean(plist, key) {
169
+ const extracted = extractString(plist, key);
170
+ if (!extracted.present) {
171
+ return { present: false, failed: extracted.failed };
172
+ }
173
+ return { present: true, value: /^(true|1|yes)$/i.test(extracted.value) };
174
+ }
175
+
176
+ /**
177
+ * Mirror of `Preferences.normalizeWatchRootPaths` in the Swift app: expand
178
+ * tildes, standardize, resolve symlinks, drop duplicates, and drop roots
179
+ * already covered recursively by an earlier root.
180
+ */
181
+ export function normalizeWatchRootPaths(paths, { home = os.homedir() } = {}) {
182
+ const result = [];
183
+ for (const rawPath of paths) {
184
+ if (typeof rawPath !== "string" || rawPath.length === 0) continue;
185
+ const candidate = normalizePath(rawPath, { home });
186
+ if (result.some((root) => pathIsInside(root, candidate))) continue;
187
+ for (let index = result.length - 1; index >= 0; index -= 1) {
188
+ if (pathIsInside(candidate, result[index])) result.splice(index, 1);
189
+ }
190
+ result.push(candidate);
191
+ }
192
+ return result;
193
+ }
194
+
195
+ /** Expand `~`, make absolute, and resolve symlinks as far as the path exists. */
196
+ export function normalizePath(rawPath, { home = os.homedir() } = {}) {
197
+ let expanded = rawPath;
198
+ if (expanded === "~") expanded = home;
199
+ else if (expanded.startsWith("~/")) expanded = path.join(home, expanded.slice(2));
200
+ const absolute = path.resolve(expanded);
201
+ try {
202
+ return fs.realpathSync.native(absolute);
203
+ } catch {
204
+ // Resolve the deepest existing ancestor so a missing leaf still normalizes.
205
+ const parts = absolute.split(path.sep);
206
+ for (let depth = parts.length - 1; depth > 1; depth -= 1) {
207
+ const ancestor = parts.slice(0, depth).join(path.sep);
208
+ try {
209
+ const real = fs.realpathSync.native(ancestor);
210
+ return path.join(real, ...parts.slice(depth));
211
+ } catch {
212
+ continue;
213
+ }
214
+ }
215
+ return absolute;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Containment on path-component boundaries, so `/Users/x/proj-two` is not
221
+ * treated as living inside `/Users/x/proj`.
222
+ */
223
+ export function pathIsInside(root, candidate) {
224
+ if (root === candidate) return true;
225
+ const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
226
+ return candidate.startsWith(prefix);
227
+ }
228
+
229
+ /**
230
+ * The app's live watch configuration.
231
+ *
232
+ * `watchRoots` (string array) is authoritative; the legacy singular
233
+ * `watchRoot` is still honored when `watchRoots` was never written so upgrades
234
+ * keep the folder the user already chose.
235
+ */
236
+ export function readWatchConfiguration({
237
+ domain = ASTROSHOTS_DOMAIN,
238
+ home = os.homedir(),
239
+ platform = process.platform,
240
+ // Seam for tests: lets a suite supply a plist snapshot (including a corrupt
241
+ // one) without breaking the host's /usr/bin.
242
+ readDomain = readPreferenceDomain,
243
+ } = {}) {
244
+ const snapshot = readDomain(domain, { home, platform });
245
+ if (!snapshot.available) {
246
+ return {
247
+ available: false,
248
+ reason: snapshot.reason,
249
+ source: null,
250
+ roots: [],
251
+ hasCompletedFirstRunSetup: false,
252
+ usedLegacyKey: false,
253
+ };
254
+ }
255
+
256
+ const modern = extractStringArray(snapshot.plist, "watchRoots");
257
+ const legacy = modern.present
258
+ ? { present: false }
259
+ : extractString(snapshot.plist, "watchRoot");
260
+ const firstRun = extractBoolean(snapshot.plist, "hasCompletedFirstRunSetup");
261
+
262
+ // If the extraction tool could not answer, we know nothing about this user's
263
+ // setup. Reporting "no watch roots" here would tell a correctly configured
264
+ // user to redo first-run setup, so surface the unreadable state instead.
265
+ const failure = [modern, legacy, firstRun].find((result) => result.failed);
266
+ if (failure) {
267
+ return {
268
+ available: false,
269
+ reason: "tool-unavailable",
270
+ error: failure.error,
271
+ source: snapshot.source,
272
+ roots: [],
273
+ hasCompletedFirstRunSetup: false,
274
+ usedLegacyKey: false,
275
+ };
276
+ }
277
+
278
+ const stored = modern.present
279
+ ? modern.value
280
+ : legacy.present && legacy.value
281
+ ? [legacy.value]
282
+ : [];
283
+
284
+ return {
285
+ available: true,
286
+ source: snapshot.source,
287
+ staleRisk: Boolean(snapshot.staleRisk),
288
+ plistPath: snapshot.plistPath,
289
+ roots: normalizeWatchRootPaths(stored, { home }),
290
+ storedRoots: stored,
291
+ usedLegacyKey: !modern.present && legacy.present,
292
+ hasCompletedFirstRunSetup: firstRun.present ? firstRun.value : false,
293
+ hasConfiguredWatchRoots: modern.present || legacy.present,
294
+ };
295
+ }
296
+
297
+ /**
298
+ * Classify a project directory against the app's watch roots.
299
+ *
300
+ * Each outcome needs a different remediation, so they stay distinct instead of
301
+ * collapsing into "not watched":
302
+ * - `setup-incomplete` first-run folder setup never finished
303
+ * - `outside-roots` setup finished, but this project is not covered
304
+ * - `inside-root` covered by `matchedRoot`
305
+ * - `unknown` the configuration could not be read at all — never
306
+ * claim anything about the user's setup here
307
+ * - `unsupported` not macOS
308
+ */
309
+ export function evaluateWatchCoverage(
310
+ projectPath,
311
+ configuration,
312
+ { home = os.homedir() } = {},
313
+ ) {
314
+ if (!configuration.available) {
315
+ return {
316
+ state: configuration.reason === "not-macos" ? "unsupported" : "unknown",
317
+ reason: configuration.reason,
318
+ error: configuration.error,
319
+ roots: [],
320
+ };
321
+ }
322
+ const normalizedProject = normalizePath(projectPath, { home });
323
+ const matchedRoot =
324
+ configuration.roots.find((root) => pathIsInside(root, normalizedProject)) ??
325
+ null;
326
+ if (matchedRoot) {
327
+ return {
328
+ state: "inside-root",
329
+ matchedRoot,
330
+ projectPath: normalizedProject,
331
+ roots: configuration.roots,
332
+ };
333
+ }
334
+ if (!configuration.hasCompletedFirstRunSetup || configuration.roots.length === 0) {
335
+ return {
336
+ state: "setup-incomplete",
337
+ projectPath: normalizedProject,
338
+ roots: configuration.roots,
339
+ };
340
+ }
341
+ return {
342
+ state: "outside-roots",
343
+ projectPath: normalizedProject,
344
+ roots: configuration.roots,
345
+ };
346
+ }
@@ -0,0 +1,42 @@
1
+ {
2
+ "version": 1,
3
+ "generated_by": "npm run build:demo-fixtures --workspace @archastro/astroshot",
4
+ "viewport": "720x450",
5
+ "shots": [
6
+ {
7
+ "asset": "welcome.png",
8
+ "slug": "welcome",
9
+ "title": "Watch path works",
10
+ "description": "astroshot demo wrote this still into .astroshot/ with zero prerequisites."
11
+ },
12
+ {
13
+ "asset": "next-steps.png",
14
+ "slug": "next-steps",
15
+ "title": "Next steps",
16
+ "description": "The commands that capture real React, Ink, PTY, and movie states."
17
+ },
18
+ {
19
+ "asset": "journey.png",
20
+ "video": "journey.webm",
21
+ "slug": "journey",
22
+ "title": "Journey movie",
23
+ "description": "A poster PNG plus sibling WebM proves movie playback, duration, and chapters.",
24
+ "duration_ms": 4240,
25
+ "source": "frames",
26
+ "chapters": [
27
+ {
28
+ "slug": "recording",
29
+ "t_ms": 0
30
+ },
31
+ {
32
+ "slug": "poster",
33
+ "t_ms": 2685
34
+ },
35
+ {
36
+ "slug": "streaming",
37
+ "t_ms": 3180
38
+ }
39
+ ]
40
+ }
41
+ ]
42
+ }
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@archastro/astroshot",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "One CLI for deterministic React, terminal, and movie UI captures",
5
5
  "keywords": [
6
6
  "react",
@@ -47,6 +47,7 @@
47
47
  },
48
48
  "files": [
49
49
  "bin",
50
+ "fixtures",
50
51
  "react.d.ts",
51
52
  "react.js",
52
53
  "ink.d.ts",
@@ -59,7 +60,8 @@
59
60
  ],
60
61
  "scripts": {
61
62
  "pretest": "npm run build --workspace @archastro/react-shot && npm run build --workspace @archastro/tui-shot && npm run build --workspace @archastro/movie-harness",
62
- "test": "node --test test/*.test.mjs"
63
+ "test": "node --test test/*.test.mjs",
64
+ "build:demo-fixtures": "node scripts/build-demo-fixtures.mjs"
63
65
  },
64
66
  "engines": {
65
67
  "node": ">=22.14.0"
@@ -70,8 +72,9 @@
70
72
  "registry": "https://registry.npmjs.org/"
71
73
  },
72
74
  "dependencies": {
73
- "@archastro/movie-harness": "0.2.0",
74
- "@archastro/react-shot": "0.2.0",
75
- "@archastro/tui-shot": "0.2.0"
75
+ "@archastro/astroshot-review": "0.2.2",
76
+ "@archastro/movie-harness": "0.2.2",
77
+ "@archastro/react-shot": "0.2.2",
78
+ "@archastro/tui-shot": "0.2.2"
76
79
  }
77
80
  }