summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
Diffstat (limited to 'scripts')
-rwxr-xr-xscripts/icloud-note.mjs76
-rw-r--r--scripts/lib/note-helpers.mjs88
2 files changed, 139 insertions, 25 deletions
diff --git a/scripts/icloud-note.mjs b/scripts/icloud-note.mjs
index 30c3b83..aa42e95 100755
--- a/scripts/icloud-note.mjs
+++ b/scripts/icloud-note.mjs
@@ -10,14 +10,21 @@ import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
+import {
+ formatNoteText,
+ isAppleAuthUrl,
+ looksLoggedOut,
+ requireCreateContent,
+ resolveConfigPaths,
+} from "./lib/note-helpers.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_DIR =
- process.env.ICLOUD_NOTES_CONFIG ||
- path.join(os.homedir(), ".config", "icloud-notes");
-const PROFILE_DIR = path.join(CONFIG_DIR, "browser-profile");
-const STATE_PATH = path.join(CONFIG_DIR, "storage-state.json");
+const paths = resolveConfigPaths(process.env, os.homedir());
+const CONFIG_DIR = paths.configDir;
+const PROFILE_DIR = paths.profileDir;
+const STATE_PATH = paths.statePath;
const NOTES_URL = "https://www.icloud.com/notes/";
+const DRY_RUN = process.env.ICLOUD_NOTES_DRY_RUN === "1";
function die(msg, code = 1) {
console.error(msg);
@@ -113,26 +120,23 @@ async function withLoginBrowser(fn) {
async function pageLooksLoggedOut(page) {
const url = page.url();
- if (/idmsa\.apple\.com|appleid\.apple\.com/i.test(url)) return true;
- return page.evaluate(() => {
+ if (isAppleAuthUrl(url)) return true;
+ const signals = await page.evaluate(() => {
const t = (document.body?.innerText || "").slice(0, 4000);
- if (/Sign in to iCloud/i.test(t)) return true;
- if (
+ const hasPasswordField = Boolean(
document.querySelector(
'input[type="password"], #password_text_field, #account_name_text_field',
- )
- ) {
- return true;
- }
- // Prominent Sign In control without Notes app loaded
- const signIn = [...document.querySelectorAll("a,button,div[role='button']")].some(
+ ),
+ );
+ const hasSignInControl = [...document.querySelectorAll("a,button,div[role='button']")].some(
(el) => /^sign in$/i.test((el.textContent || "").trim()),
);
- const hasNotes = Boolean(
+ const hasNotesApp = Boolean(
document.querySelector("iframe")?.contentWindow?.NotesApp?.dataManager,
);
- return signIn && !hasNotes;
- }).catch(() => false);
+ return { bodyText: t, hasPasswordField, hasSignInControl, hasNotesApp };
+ }).catch(() => ({}));
+ return looksLoggedOut({ url, ...signals });
}
async function waitForNotesApp(page, { timeoutMs = 120_000, allowLoginWait = false } = {}) {
@@ -170,8 +174,7 @@ async function waitForNotesApp(page, { timeoutMs = 120_000, allowLoginWait = fal
}
async function createViaNotesApp(page, title, body) {
- const fullText = [title, body].filter((s) => s != null && String(s).length)
- .join("\n\n");
+ const fullText = formatNoteText(title, body);
return page.evaluate(async (text) => {
const iframe = document.querySelector("iframe");
@@ -260,7 +263,7 @@ async function createViaUiFallback(page, title, body) {
throw new Error("UI fallback: could not find New Note control");
}
- const text = [title, body].filter(Boolean).join("\n\n");
+ const text = formatNoteText(title, body);
const editable = page
.frameLocator("iframe")
.locator('[contenteditable="true"], [role="textbox"]')
@@ -272,6 +275,13 @@ async function createViaUiFallback(page, title, body) {
}
async function cmdStatus() {
+ if (DRY_RUN) {
+ if (!fs.existsSync(STATE_PATH) && !fs.existsSync(path.join(PROFILE_DIR, "Default"))) {
+ die("not ready: No saved session. Run: icloud-note login");
+ }
+ console.log("ok: dry-run status (would check Notes headless)");
+ return;
+ }
try {
await withHeadlessNotes(async (page) => {
await waitForNotesApp(page, { timeoutMs: 20_000 });
@@ -283,6 +293,9 @@ async function cmdStatus() {
}
async function cmdLogin() {
+ if (DRY_RUN) {
+ die("login dry-run: would open a visible browser (refusing)");
+ }
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
die("login needs a graphical session (DISPLAY or WAYLAND_DISPLAY).");
}
@@ -321,10 +334,23 @@ function readBody(opts) {
}
async function cmdCreate(opts) {
- const title = opts.values.title || "";
- const body = readBody(opts).replace(/\s+$/, "");
- if (!title && !body) {
- die("Provide --title and/or --body / --body-file / stdin");
+ let title;
+ let body;
+ try {
+ ({ title, body } = requireCreateContent(
+ opts.values.title || "",
+ readBody(opts),
+ ));
+ } catch (err) {
+ die(err.message);
+ }
+
+ if (DRY_RUN) {
+ const text = formatNoteText(title, body);
+ console.log(
+ `dry-run: would create note title=${JSON.stringify(title)} chars=${text.length}`,
+ );
+ return;
}
await withHeadlessNotes(async (page) => {
diff --git a/scripts/lib/note-helpers.mjs b/scripts/lib/note-helpers.mjs
new file mode 100644
index 0000000..5dd43a0
--- /dev/null
+++ b/scripts/lib/note-helpers.mjs
@@ -0,0 +1,88 @@
+/**
+ * Pure helpers for icloud-note (unit-tested; no Playwright).
+ */
+
+/** Join title + body the way Apple Notes expects (first line = title). */
+export function formatNoteText(title, body) {
+ const t = title == null ? "" : String(title);
+ const b = body == null ? "" : String(body);
+ return [t, b].filter((s) => s.length > 0).join("\n\n");
+}
+
+/** True when a URL is clearly an Apple auth/sign-in page. */
+export function isAppleAuthUrl(url) {
+ return /idmsa\.apple\.com|appleid\.apple\.com/i.test(String(url || ""));
+}
+
+/**
+ * Heuristic "logged out" detection from page signals (mirrors pageLooksLoggedOut).
+ * @param {{ url?: string, bodyText?: string, hasPasswordField?: boolean, hasSignInControl?: boolean, hasNotesApp?: boolean }} s
+ */
+export function looksLoggedOut(s = {}) {
+ if (isAppleAuthUrl(s.url)) return true;
+ const t = String(s.bodyText || "").slice(0, 4000);
+ if (/Sign in to iCloud/i.test(t)) return true;
+ if (s.hasPasswordField) return true;
+ if (s.hasSignInControl && !s.hasNotesApp) return true;
+ return false;
+}
+
+/** Resolve XDG-style config paths (overridable via env for tests). */
+export function resolveConfigPaths(env = process.env, homedir = "") {
+ const home =
+ homedir ||
+ env.HOME ||
+ env.USERPROFILE ||
+ "/tmp";
+ const configDir =
+ env.ICLOUD_NOTES_CONFIG || `${home}/.config/icloud-notes`;
+ return {
+ configDir,
+ profileDir: `${configDir}/browser-profile`,
+ statePath: `${configDir}/storage-state.json`,
+ };
+}
+
+/**
+ * Parse create CLI flags (subset of node:util parseArgs shape).
+ * @returns {{ title: string, bodyFile?: string, body?: string, positionals: string[] }}
+ */
+export function parseCreateArgv(argv) {
+ const out = { title: "", body: undefined, bodyFile: undefined, positionals: [] };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === "--title") {
+ out.title = String(argv[++i] ?? "");
+ } else if (a === "--body") {
+ out.body = String(argv[++i] ?? "");
+ } else if (a === "--body-file") {
+ out.bodyFile = String(argv[++i] ?? "");
+ } else if (a.startsWith("-")) {
+ throw new Error(`Unknown option: ${a}`);
+ } else {
+ out.positionals.push(a);
+ }
+ }
+ if (!out.title && out.positionals[0]) {
+ out.title = out.positionals[0];
+ }
+ return out;
+}
+
+/** Validate create has something to send. */
+export function requireCreateContent(title, body) {
+ const t = title == null ? "" : String(title);
+ const b = body == null ? "" : String(body).replace(/\s+$/, "");
+ if (!t && !b) {
+ throw new Error("Provide --title and/or --body / --body-file / stdin");
+ }
+ return { title: t, body: b };
+}
+
+/** Conventional Commits 1.0.0 subject line (first line of message). */
+export function isConventionalCommitSubject(subject) {
+ const line = String(subject || "").trim();
+ return /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-zA-Z0-9._/-]+\))?!?: .+/.test(
+ line,
+ );
+}