printer-doctor 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,128 @@
1
+ // Text reports. The first part is written for the person; the details at the end are for
2
+ // whoever helps them next. Job names, user names, serial numbers and hardware addresses are
3
+ // never included; printer names are, because people need them to find the printer.
4
+ import { diagnose, displayName, showHost } from "./diagnose.js";
5
+
6
+ const OS_NAME = { darwin: "Mac", win32: "Windows", linux: "Linux" };
7
+ const MARK = { problem: "[problem]", warning: "[warning]", note: "[note] ", ok: "[ok] " };
8
+ const HEAD = "Printer Doctor";
9
+
10
+ const CONNECTION = {
11
+ network: "on the network",
12
+ usb: "on a USB cable",
13
+ virtual: "saves a file instead of printing",
14
+ shared: "shared by another computer",
15
+ cable: "on a printer cable",
16
+ bluetooth: "on Bluetooth",
17
+ unknown: "connection not known",
18
+ };
19
+
20
+ // An address is shown as it is; a name only when it does not carry a hardware address.
21
+ const hostText = (host) => (/^[\d.]+$|:/.test(host) ? host : showHost(host) ? `"${showHost(host)}"` : "a network name (not shown)");
22
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
23
+ const took = (seconds) => (seconds >= 1 ? `${seconds} s` : "under a second");
24
+
25
+ function sendsTo(p) {
26
+ if (p.kind !== "network") return "";
27
+ if (p.host) return `, jobs go to ${hostText(p.host)}`;
28
+ if (p.match?.addresses?.length) return `, now at ${p.match.addresses[0]}`;
29
+ return "";
30
+ }
31
+
32
+ function queueLine(p) {
33
+ const bits = [];
34
+ if (p.isDefault) bits.push("default");
35
+ if (p.paused) bits.push("paused");
36
+ if (p.offlineFlag) bits.push("marked offline");
37
+ if (p.jobs?.length) bits.push(`${plural(p.jobs.length, "job")} waiting`);
38
+ return `- ${displayName(p)}${bits.length ? ` (${bits.join(", ")})` : ""}: ${CONNECTION[p.kind] || CONNECTION.unknown}${sendsTo(p)}`;
39
+ }
40
+
41
+ // ---------- find_printers ----------------------------------------------------------------------
42
+
43
+ export function renderList(f) {
44
+ const lines = [`${HEAD}: printers (${OS_NAME[f.platform] || f.platform}; took ${took(f.seconds)})`, ""];
45
+ const sys = f.system;
46
+ if (sys.system === "windows" && sys.available && sys.serviceRunning === false) {
47
+ lines.push("Windows' print service (the \"Print Spooler\") is not running, so this computer's printer list can't be read and nothing can print. Ask me to check the printer and I will explain how to start it.", "");
48
+ } else if (!sys.available) {
49
+ lines.push("This computer's print system is not running or not installed, so no printers are set up on it.", "");
50
+ } else {
51
+ const real = sys.printers.filter((p) => !p.virtual);
52
+ const virtual = sys.printers.filter((p) => p.virtual);
53
+ lines.push("Set up on this computer");
54
+ if (!real.length) lines.push("- no real printer");
55
+ for (const p of real) lines.push(queueLine(p));
56
+ for (const p of virtual) lines.push(queueLine(p));
57
+ lines.push("");
58
+ }
59
+ lines.push("Found on your network, not set up on this computer");
60
+ if (f.notSetUp.length) {
61
+ for (const a of f.notSetUp) lines.push(`- ${a.instance}${a.model && a.model.toLowerCase() !== a.instance.toLowerCase() ? ` (${a.model})` : ""}${a.addresses.length ? ` at ${a.addresses[0]}` : ""}`);
62
+ } else if (f.announcedCount) {
63
+ lines.push("- none: every printer I can see on the network is already set up here");
64
+ } else {
65
+ lines.push(`- none found${f.viaVpn ? ". A VPN is on, which can hide devices at home: if you expected a printer here, turn the VPN off and look again" : ""}`);
66
+ }
67
+ lines.push(
68
+ "",
69
+ "How I looked: this computer's own printer list, plus one question on your home network asking printers to announce themselves (the way AirPrint finds them). Printers on a guest network, older printers that don't announce themselves, and printers that are switched off will not show up.",
70
+ "To find out why one of them won't print, ask me to check it by name.",
71
+ );
72
+ return lines.join("\n");
73
+ }
74
+
75
+ // ---------- check_printer ----------------------------------------------------------------------
76
+
77
+ const STATE = { 3: "idle", 4: "printing", 5: "stopped" };
78
+
79
+ export function details(f) {
80
+ const when = new Date().toISOString().replace("T", " ").slice(0, 16) + " UTC";
81
+ const out = [`Details (${when}, ${OS_NAME[f.platform] || f.platform})`];
82
+ const sys = f.system || {};
83
+ out.push(` Print system on this computer: ${sys.system === "windows" ? "Windows spooler" : sys.system === "cups" ? "CUPS" : "none"}, ${sys.available ? (sys.serviceRunning === false ? "not running" : "running") : "not available"}; ${plural((sys.printers || []).length, "printer")} set up`);
84
+ const p = f.target;
85
+ if (p) {
86
+ const to = p.kind === "network" ? `network${p.scheme ? ` (${p.scheme}${p.port ? `, port ${p.port}` : ""})` : ""}${p.host ? ` to ${hostText(p.host)}` : p.instance ? ", found by its announced name" : ""}` : CONNECTION[p.kind] || p.kind;
87
+ out.push(` Printer: ${displayName(p)}${p.driver ? `; driver: ${p.driver}` : ""}; connection: ${to}`);
88
+ const words = (p.reasons || []).join(", ") || "none";
89
+ out.push(` Queue on this computer: ${p.paused ? "paused" : "not paused"}${p.offlineFlag ? ", marked offline" : ""}${p.accepting === false ? ", refusing jobs" : ""}, ${plural((p.jobs || []).length, "job")} waiting; status words: ${words}`);
90
+ }
91
+ const loc = f.location;
92
+ if (loc) {
93
+ const ports = loc.probes.map((x) => `${x.port} ${x.state}`).join(", ");
94
+ const where = loc.publicAddress
95
+ ? "the queue points at an address outside home networks (not contacted)"
96
+ : loc.address
97
+ ? `${loc.answered ? "answers" : "no answer"} at ${loc.address}${ports ? ` (ports: ${ports})` : ""}`
98
+ : "no address known for it";
99
+ out.push(` On the network: ${where}${loc.addressChanged ? `; the queue still points at ${loc.queueAddress || "a name that is not found"}` : ""}${loc.match ? `; announces itself as "${loc.match.instance}"` : "; not seen announcing itself"}${loc.sameNetwork === false ? "; not on this computer's own network" : ""}`);
100
+ }
101
+ const dev = f.device;
102
+ if (dev?.answered) {
103
+ out.push(` Printer's own status (asked over IPP${dev.secure ? " with TLS" : ""}, port ${dev.port}): ${STATE[dev.state] || "unknown"}; status words: ${(dev.reasons || []).join(", ") || "none"}; accepting jobs: ${dev.accepting === false ? "no" : "yes"}${dev.alert?.length ? `; message: ${dev.alert.join("; ")}` : ""}${dev.model ? `; says it is a ${dev.model}` : ""}`);
104
+ } else if (dev?.asked) {
105
+ out.push(` Printer's own status: could not be read (${dev.error})`);
106
+ }
107
+ const markers = (dev?.answered && dev.markers?.length ? dev.markers : p?.markers) || [];
108
+ if (markers.length) out.push(` Supplies: ${markers.map((m) => `${m.label} ${m.level === null ? "level not reported" : `${m.level}%`}`).join(", ")}`);
109
+ if (f.network) out.push(` Network: ${f.network.viaVpn ? `VPN on (${(f.network.vpnIfaces || []).join(", ")})` : "no VPN in the way"}; printers announcing themselves: ${(f.network.announced || []).length}`);
110
+ return out;
111
+ }
112
+
113
+ export function renderCheck(f) {
114
+ const d = diagnose(f);
115
+ const p = f.target;
116
+ const how = [OS_NAME[f.platform] || f.platform];
117
+ if (p) how.push(CONNECTION[p.kind] || CONNECTION.unknown);
118
+ const lines = [`${HEAD}: ${p ? `check of "${displayName(p)}"` : "printer check"} (${how.join(", ")}; took ${took(f.seconds)})`, "", `Verdict: ${d.verdict.title}`, "", "What I found"];
119
+ const order = { problem: 0, warning: 1, note: 2, ok: 3 };
120
+ for (const x of [...d.findings].sort((a, b) => order[a.level] - order[b.level])) lines.push(`${MARK[x.level]} ${x.text}`);
121
+ if (d.steps.length) {
122
+ lines.push("", d.verdict.code === "healthy" ? "If it still won't print" : "What to do");
123
+ d.steps.forEach((s, i) => lines.push(`${i + 1}. ${s}`));
124
+ }
125
+ lines.push("", ...details(f));
126
+ lines.push("", "How this was checked: this computer's own print system, one question on your home network asking printers to announce themselves, and (for a network printer) one question to the printer about its own state. Nothing was printed, cancelled or changed, and nothing outside your home network was contacted.");
127
+ return lines.join("\n");
128
+ }
package/src/lib/run.js ADDED
@@ -0,0 +1,52 @@
1
+ // Starts the few system programs this tool reads from. Each one is looked up at a fixed
2
+ // location (never through PATH or a shell) and always gets a fixed argument list, so nothing a
3
+ // caller types can turn into a command. Every run has a time limit.
4
+ import { execFile } from "node:child_process";
5
+ import fs from "node:fs";
6
+
7
+ const SYS32 = `${process.env.SystemRoot || "C:\\Windows"}\\System32\\`;
8
+
9
+ const PROGRAMS = {
10
+ netstat: { darwin: ["/usr/sbin/netstat"] },
11
+ route: { win32: [`${SYS32}ROUTE.EXE`] },
12
+ powershell: { win32: [`${SYS32}WindowsPowerShell\\v1.0\\powershell.exe`] },
13
+ };
14
+
15
+ const found = new Map();
16
+
17
+ export function programPath(name, platform = process.platform) {
18
+ const key = `${platform}:${name}`;
19
+ if (!found.has(key)) {
20
+ const list = PROGRAMS[name]?.[platform] || [];
21
+ found.set(key, list.find((p) => fs.existsSync(p)) || null);
22
+ }
23
+ return found.get(key);
24
+ }
25
+
26
+ /**
27
+ * Run a known program. Resolves (never rejects) with
28
+ * { ok, missing, code, stdout, stderr, timedOut }.
29
+ */
30
+ export function run(name, args, { timeoutMs = 15000 } = {}) {
31
+ const file = programPath(name);
32
+ if (!file) return Promise.resolve({ ok: false, missing: true, code: null, stdout: "", stderr: "", timedOut: false });
33
+ // English output where the system allows it, so the readers see the words they expect.
34
+ const env = process.platform === "win32" ? process.env : { ...process.env, LC_ALL: "C", LANG: "C" };
35
+ return new Promise((resolve) => {
36
+ execFile(
37
+ file,
38
+ args,
39
+ { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024, windowsHide: true, env, encoding: "utf8" },
40
+ (err, stdout, stderr) => {
41
+ resolve({
42
+ ok: !err,
43
+ missing: false,
44
+ code: err ? (typeof err.code === "number" ? err.code : null) : 0,
45
+ stdout: String(stdout || ""),
46
+ stderr: String(stderr || ""),
47
+ timedOut: Boolean(err && err.killed),
48
+ });
49
+ },
50
+ );
51
+ });
52
+ }
@@ -0,0 +1,27 @@
1
+ // Names and words that come from outside this program (a printer's model, its announced name, a
2
+ // queue's name) end up in a report that an AI assistant reads. They are kept short and on one
3
+ // line, so a device cannot smuggle a paragraph of "instructions" into the report through its name.
4
+
5
+ // Control characters, line and paragraph separators, zero-width and text-direction marks.
6
+ const INVISIBLE = /[\u0000-\u001f\u007f-\u009f\u00ad\u200b-\u200f\u2028-\u202f\u2060-\u206f\ufeff]/g;
7
+
8
+ /** One line of plain text, trimmed and cut to `max` characters. Never returns null. */
9
+ export function cleanText(value, max = 64) {
10
+ const s = String(value ?? "")
11
+ .replace(INVISIBLE, " ")
12
+ .replace(/\s+/g, " ")
13
+ .trim();
14
+ return s.length > max ? `${s.slice(0, max - 1).trimEnd()}\u2026` : s;
15
+ }
16
+
17
+ /** The same, or null when nothing is left. */
18
+ export const cleanOrNull = (value, max = 64) => cleanText(value, max) || null;
19
+
20
+ /** A status keyword as printers send it ("media-empty-error"), or null if it does not look like one. */
21
+ export const cleanKeyword = (value) => {
22
+ const s = String(value ?? "").toLowerCase();
23
+ return /^[a-z0-9][a-z0-9.-]{0,59}$/.test(s) ? s : null;
24
+ };
25
+
26
+ /** A list of status keywords: only well-formed ones, at most `max`. */
27
+ export const cleanKeywords = (values, max = 12) => (values || []).map(cleanKeyword).filter(Boolean).slice(0, max);
@@ -0,0 +1,166 @@
1
+ // Windows: what the print system (the "spooler") knows. One fixed PowerShell script reads it and
2
+ // prints JSON; nothing a person types is ever put into that script. The script only reads:
3
+ // service state, printers, their ports, and the jobs waiting. It never reads a document name or
4
+ // who printed it.
5
+ import { run } from "./run.js";
6
+ import { cleanText } from "./text.js";
7
+
8
+ // Single quotes only, so the script passes through the Windows command line untouched. The JSON
9
+ // is printed as base64 so printer names with accents survive any console code page.
10
+ export const WINDOWS_SCRIPT = [
11
+ "$ErrorActionPreference = 'Stop'",
12
+ "$o = @{ spooler = $null; printers = @(); ports = @(); jobs = @(); errors = @() }",
13
+ "try { $s = Get-CimInstance -ClassName Win32_Service -Filter 'Name=''Spooler'''; if ($s) { $o.spooler = @{ state = [string]$s.State; start = [string]$s.StartMode } } } catch { $o.errors += 'spooler' }",
14
+ "try { $o.printers = @(Get-CimInstance -ClassName Win32_Printer | ForEach-Object { @{ name = [string]$_.Name; driver = [string]$_.DriverName; port = [string]$_.PortName; offline = [bool]$_.WorkOffline; isDefault = [bool]$_.Default; shared = [bool]$_.Shared; network = [bool]$_.Network; state = [long]$_.PrinterState; error = [int]$_.DetectedErrorState; extended = [int]$_.ExtendedPrinterStatus; attributes = [long]$_.Attributes } }) } catch { $o.errors += 'printers' }",
15
+ "try { $o.ports = @(Get-CimInstance -ClassName Win32_TCPIPPrinterPort | ForEach-Object { @{ name = [string]$_.Name; address = [string]$_.HostAddress; number = [int]$_.PortNumber; protocol = [int]$_.Protocol } }) } catch { $o.errors += 'ports' }",
16
+ "try { $o.jobs = @(Get-CimInstance -ClassName Win32_PrintJob | ForEach-Object { $t = $null; if ($_.TimeSubmitted) { $t = $_.TimeSubmitted.ToUniversalTime().ToString('o') }; @{ printer = ([string]$_.Name -replace ',\\s*\\d+$', ''); mask = [long]$_.StatusMask; submitted = $t } }) } catch { $o.errors += 'jobs' }",
17
+ "[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($o | ConvertTo-Json -Depth 4 -Compress)))",
18
+ ].join("; ");
19
+
20
+ // PRINTER_STATUS_* bits of Win32_Printer.PrinterState, mapped to the same words printers use
21
+ // themselves (IPP "printer-state-reasons"), so one table of plain-word explanations covers both.
22
+ const STATE_BITS = [
23
+ [0x00000001, "paused"],
24
+ [0x00000002, "other-error"],
25
+ [0x00000008, "media-jam-error"],
26
+ [0x00000010, "media-empty-error"],
27
+ [0x00000020, "media-needed"],
28
+ [0x00000040, "media-jam-error"],
29
+ [0x00000080, "offline"],
30
+ [0x00000800, "output-area-full"],
31
+ [0x00001000, "offline"],
32
+ [0x00020000, "toner-low-warning"],
33
+ [0x00040000, "toner-empty-error"],
34
+ [0x00100000, "attention-needed"],
35
+ [0x00400000, "cover-open-error"],
36
+ ];
37
+
38
+ // Win32_Printer.DetectedErrorState (0 unknown, 1 other, 2 no error).
39
+ const ERROR_STATE = {
40
+ 3: "media-low-warning",
41
+ 4: "media-empty-error",
42
+ 5: "toner-low-warning",
43
+ 6: "toner-empty-error",
44
+ 7: "cover-open-error",
45
+ 8: "media-jam-error",
46
+ 9: "offline",
47
+ 10: "attention-needed",
48
+ 11: "output-area-full",
49
+ };
50
+
51
+ // Things that show up in the printer list but put nothing on paper.
52
+ const VIRTUAL =
53
+ /\bpdf\b|\bxps\b|onenote|one note|\bfax\b|document writer|image printer|image writer|snagit|evernote|send to |print to file|virtual|cutepdf|bullzip|dopdf|pdf24|foxit|nitro|adobe pdf|quicken|quickbooks/i;
54
+ const VIRTUAL_PORT = /^(PORTPROMPT:|nul:|SHRFAX:|FILE:|XPSPort:|TS\d+|CPW\d+:|BULLZIP|PDF|FOXIT|NVF\d+:)/i;
55
+ // A basic stand-in driver ("Generic / Text Only"). Microsoft's IPP Class Driver is the normal modern way and is not flagged.
56
+ const GENERIC_DRIVER = /^generic\b/i;
57
+
58
+ const JOB_ERROR = 0x2 | 0x20 | 0x40 | 0x200 | 0x400; // error, offline, paper out, blocked, needs a person
59
+ const JOB_PAUSED = 0x1;
60
+
61
+ /** The script's output (base64 of JSON, possibly with stray lines around it) -> object, or null. */
62
+ export function decodeWindowsOutput(stdout) {
63
+ const line = String(stdout || "")
64
+ .split(/\r?\n/)
65
+ .map((s) => s.trim())
66
+ .filter((s) => /^[A-Za-z0-9+/=]{16,}$/.test(s))
67
+ .pop();
68
+ if (!line) return null;
69
+ try {
70
+ return JSON.parse(Buffer.from(line, "base64").toString("utf8"));
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+
76
+ const list = (x) => (Array.isArray(x) ? x : x ? [x] : []);
77
+
78
+ function portKind(port, tcpPort, virtual) {
79
+ if (virtual) return "virtual";
80
+ if (tcpPort) return "network";
81
+ if (/^(USB|DOT4_)\d+/i.test(port)) return "usb";
82
+ if (/^WSD-/i.test(port) || /^(https?|ipps?):\/\//i.test(port) || /^IP_/i.test(port)) return "network";
83
+ if (/^\\\\/.test(port)) return "shared";
84
+ if (/^(LPT|COM)\d+:?$/i.test(port)) return "cable";
85
+ if (/^BTH/i.test(port)) return "bluetooth";
86
+ return "unknown";
87
+ }
88
+
89
+ /**
90
+ * Turns the script's JSON into the same shape the other systems produce:
91
+ * { available, serviceRunning, serviceDisabled, printers: [...], defaultName }.
92
+ */
93
+ export function readWindows(data, nowMs = Date.now()) {
94
+ if (!data || typeof data !== "object") return { system: "windows", available: false, printers: [], defaultName: null };
95
+ const errors = list(data.errors);
96
+ const spooler = data.spooler && typeof data.spooler === "object" ? data.spooler : null;
97
+ const serviceRunning = spooler ? /^running$/i.test(String(spooler.state)) : !errors.includes("printers");
98
+ const ports = new Map(list(data.ports).map((p) => [String(p.name), p]));
99
+ const jobsByPrinter = new Map();
100
+ for (const j of list(data.jobs)) {
101
+ const key = cleanText(j.printer, 80);
102
+ if (!jobsByPrinter.has(key)) jobsByPrinter.set(key, []);
103
+ const t = Date.parse(j.submitted || "");
104
+ const mask = Number(j.mask) || 0;
105
+ jobsByPrinter.get(key).push({
106
+ ageSec: Number.isFinite(t) ? Math.max(0, Math.round((nowMs - t) / 1000)) : null,
107
+ error: (mask & JOB_ERROR) !== 0,
108
+ paused: (mask & JOB_PAUSED) !== 0,
109
+ });
110
+ }
111
+ const printers = list(data.printers).map((p) => {
112
+ const name = cleanText(p.name, 80);
113
+ const driver = cleanText(p.driver, 80);
114
+ const port = String(p.port || "");
115
+ const tcp = ports.get(port) || null;
116
+ const attributes = Number(p.attributes) || 0;
117
+ const isFax = (attributes & 0x4000) !== 0;
118
+ const virtual = isFax || VIRTUAL_PORT.test(port) || VIRTUAL.test(name) || VIRTUAL.test(driver) || /writer port$/i.test(port);
119
+ let kind = portKind(port, tcp, virtual);
120
+ if (kind === "unknown" && /^\\\\/.test(name)) kind = "shared";
121
+ const state = Number(p.state) || 0;
122
+ const reasons = new Set();
123
+ for (const [bit, word] of STATE_BITS) if (state & bit) reasons.add(word);
124
+ if (ERROR_STATE[p.error]) reasons.add(ERROR_STATE[p.error]);
125
+ if (Number(p.extended) === 7) reasons.add("offline");
126
+ const paused = reasons.delete("paused") || Number(p.extended) === 8;
127
+ const offlineFlag = Boolean(p.offline) || (attributes & 0x400) !== 0;
128
+ return {
129
+ name,
130
+ isDefault: Boolean(p.isDefault),
131
+ kind,
132
+ virtual,
133
+ driver: driver || null,
134
+ genericDriver: GENERIC_DRIVER.test(driver),
135
+ // For a network port: where the computer sends print jobs.
136
+ host: tcp?.address ? String(tcp.address) : null,
137
+ port: tcp?.number ? Number(tcp.number) : null,
138
+ scheme: tcp ? (Number(tcp.protocol) === 2 ? "lpd" : "socket") : null,
139
+ path: null,
140
+ instance: null,
141
+ uuid: null,
142
+ paused,
143
+ offlineFlag,
144
+ accepting: true,
145
+ reasons: [...reasons],
146
+ jobs: jobsByPrinter.get(name) || [],
147
+ markers: [],
148
+ };
149
+ });
150
+ return {
151
+ system: "windows",
152
+ available: true,
153
+ serviceRunning,
154
+ serviceDisabled: spooler ? /^disabled$/i.test(String(spooler.start)) : false,
155
+ printers,
156
+ defaultName: printers.find((p) => p.isDefault)?.name || null,
157
+ partial: errors,
158
+ };
159
+ }
160
+
161
+ /** Reads the Windows print system. */
162
+ export async function getWindows() {
163
+ const r = await run("powershell", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_SCRIPT], { timeoutMs: 30000 });
164
+ if (r.missing) return { system: "windows", available: false, printers: [], defaultName: null };
165
+ return readWindows(decodeWindowsOutput(r.stdout));
166
+ }