@acepaste/ingress 0.9.6 → 0.9.21

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 (74) hide show
  1. package/dist/src/adapters.d.ts +9 -0
  2. package/dist/src/adapters.js +76 -6
  3. package/dist/src/agent-hooks.d.ts +112 -0
  4. package/dist/src/agent-hooks.js +533 -0
  5. package/dist/src/approvers.d.ts +16 -0
  6. package/dist/src/approvers.js +50 -0
  7. package/dist/src/audio.d.ts +70 -0
  8. package/dist/src/audio.js +224 -0
  9. package/dist/src/audit-changes.d.ts +46 -0
  10. package/dist/src/audit-changes.js +110 -0
  11. package/dist/src/audit-local.d.ts +57 -0
  12. package/dist/src/audit-local.js +231 -0
  13. package/dist/src/audit-parsers.d.ts +1 -1
  14. package/dist/src/audit.js +48 -0
  15. package/dist/src/broker.d.ts +92 -1
  16. package/dist/src/broker.js +222 -3
  17. package/dist/src/calendar.d.ts +36 -0
  18. package/dist/src/calendar.js +227 -0
  19. package/dist/src/captions.d.ts +44 -0
  20. package/dist/src/captions.js +209 -0
  21. package/dist/src/changes.d.ts +105 -0
  22. package/dist/src/changes.js +174 -0
  23. package/dist/src/character.js +15 -1
  24. package/dist/src/classifier-model.d.ts +53 -0
  25. package/dist/src/classifier-model.js +3 -0
  26. package/dist/src/classifier.d.ts +41 -0
  27. package/dist/src/classifier.js +213 -0
  28. package/dist/src/cli.js +501 -1
  29. package/dist/src/egress.d.ts +71 -0
  30. package/dist/src/egress.js +242 -0
  31. package/dist/src/email.d.ts +42 -0
  32. package/dist/src/email.js +424 -0
  33. package/dist/src/engine.d.ts +35 -12
  34. package/dist/src/engine.js +88 -37
  35. package/dist/src/image-meta.d.ts +33 -0
  36. package/dist/src/image-meta.js +433 -0
  37. package/dist/src/image.d.ts +104 -0
  38. package/dist/src/image.js +347 -0
  39. package/dist/src/index.d.ts +50 -5
  40. package/dist/src/index.js +28 -3
  41. package/dist/src/localguard.d.ts +33 -0
  42. package/dist/src/localguard.js +61 -0
  43. package/dist/src/meaning.d.ts +2 -0
  44. package/dist/src/meaning.js +77 -22
  45. package/dist/src/messages.d.ts +79 -0
  46. package/dist/src/messages.js +431 -0
  47. package/dist/src/nearby.d.ts +52 -0
  48. package/dist/src/nearby.js +186 -0
  49. package/dist/src/netpolicy.js +50 -19
  50. package/dist/src/provenance.d.ts +56 -0
  51. package/dist/src/provenance.js +114 -0
  52. package/dist/src/qr.d.ts +25 -0
  53. package/dist/src/qr.js +113 -0
  54. package/dist/src/safeguards.d.ts +61 -0
  55. package/dist/src/safeguards.js +199 -0
  56. package/dist/src/served.d.ts +20 -0
  57. package/dist/src/served.js +53 -0
  58. package/dist/src/shell-commands.d.ts +39 -0
  59. package/dist/src/shell-commands.js +291 -0
  60. package/dist/src/shortcuts.d.ts +45 -0
  61. package/dist/src/shortcuts.js +220 -0
  62. package/dist/src/stream.d.ts +88 -0
  63. package/dist/src/stream.js +119 -0
  64. package/dist/src/terminal.d.ts +29 -0
  65. package/dist/src/terminal.js +313 -0
  66. package/dist/src/tooldefs.d.ts +84 -0
  67. package/dist/src/tooldefs.js +122 -0
  68. package/dist/src/types.d.ts +50 -6
  69. package/dist/src/types.js +15 -2
  70. package/dist/src/visibility.d.ts +23 -3
  71. package/dist/src/visibility.js +285 -78
  72. package/native/ingress-presence.swift +48 -0
  73. package/native/ingress-vision.swift +417 -0
  74. package/package.json +3 -1
@@ -14,10 +14,30 @@ import { type RGBA } from "./color.js";
14
14
  export interface HiddenRule {
15
15
  selector: string;
16
16
  reason: TextSegment["visibility"];
17
+ /** other classes the element must also have (`.a.b` is keyed on b and requires a) */
18
+ all?: string[];
19
+ /** classes the element must not have (`:not(.show)`) */
20
+ not?: string[];
21
+ /** tag the element must be (`div.note`) */
22
+ tag?: string;
17
23
  }
18
- /** Classify a style declaration string. Returns the hiding reason or null. */
19
- export declare function classifyStyle(style: string): TextSegment["visibility"] | null;
20
- export declare function rulesFromCss(cssIn: string): HiddenRule[];
24
+ /** Custom properties (`--name`) and every value a stylesheet or inline style gives them. */
25
+ export type CssVars = Map<string, Set<string>>;
26
+ /**
27
+ * Split a declaration block into property -> value (lower case, whitespace removed, `!important` dropped).
28
+ * The last declaration of a property wins, as in the cascade. Semicolons inside parentheses or quotes
29
+ * (a data: URL) do not split.
30
+ */
31
+ export declare function parseDeclarations(style: string): Map<string, string>;
32
+ /** Collect custom property definitions from CSS text (rule bodies or one inline style). */
33
+ export declare function collectCssVars(css: string, into?: CssVars): CssVars;
34
+ /**
35
+ * Classify a declaration block. Returns the hiding reason or null. Properties are matched by their exact
36
+ * names (so `-webkit-tap-highlight-color:transparent`, `background-color:rgba(0,0,0,0)` and
37
+ * `fill-opacity:0` hide nothing), and var() references are resolved against `vars` before judging.
38
+ */
39
+ export declare function classifyStyle(style: string, vars?: CssVars): TextSegment["visibility"] | null;
40
+ export declare function rulesFromCss(cssIn: string, extraVars?: CssVars): HiddenRule[];
21
41
  export interface ColorRule {
22
42
  selector: string;
23
43
  fg?: RGBA | null;
@@ -16,94 +16,284 @@ import { colorsFromStyle, contrastRatio, blend, parseColor, INVISIBLE_CONTRAST }
16
16
  const HIDDEN_CONTAINER_TAGS = new Set(["noscript", "template"]);
17
17
  /** not rendered as page copy at all; skipped (scripts are collected separately) */
18
18
  const SKIPPED_TAGS = new Set(["script", "style", "head", "meta", "link", "base"]);
19
- const A11Y_CLASS_HINTS = /\b(sr-only|visually-hidden|screen-reader-only|visuallyhidden|a11y-hidden|screen-reader-text|visually-hidden-focusable)\b/i;
20
- const HIDDEN_CLASS_HINTS = /\b(hidden|offscreen|clip|is-hidden|d-none|invisible)\b/i;
21
- /** Classify a style declaration string. Returns the hiding reason or null. */
22
- export function classifyStyle(style) {
23
- const s = style.toLowerCase().replace(/\s+/g, "");
24
- if (/display:none/.test(s) || /visibility:(hidden|collapse)/.test(s))
25
- return "css_hidden";
26
- if (/content-visibility:hidden/.test(s))
27
- return "css_hidden";
28
- const op = s.match(/opacity:(0?\.\d+|0|1)(?![\d.])/);
29
- if (op && Number(op[1]) < 0.1)
30
- return "tiny_or_transparent";
31
- const fs = s.match(/font-size:(\d*\.?\d+)(px|pt|em|rem|%)?/);
32
- if (fs && Number(fs[1]) <= (fs[2] === "em" || fs[2] === "rem" ? 0.1 : fs[2] === "%" ? 10 : 1))
33
- return "tiny_or_transparent";
34
- if (/color:transparent/.test(s) || /color:rgba\([^)]*,0\)/.test(s) || /color:#[0-9a-f]{6}00\b/.test(s))
35
- return "tiny_or_transparent";
36
- if (/transform:[^;]*scale(x|y|3d)?\(0(\.0+)?[,)]/.test(s) || /transform:[^;]*scale(x|y)?\(0\.0\d/.test(s))
37
- return "tiny_or_transparent";
38
- if (/filter:[^;]*opacity\(0(\.0\d*)?\)/.test(s))
39
- return "tiny_or_transparent";
40
- if (/(^|;)scale:0(\.0\d*)?(\s|;|$)/.test(s))
41
- return "tiny_or_transparent";
42
- if (/(^|;)translate:-?\d{3,}(px|em|rem|vw|vh|%)/.test(s))
43
- return "offscreen";
44
- if (/(^|;)inset:[^;]*-\d{3,}(px|em|rem|vw|vh|%)/.test(s))
45
- return "offscreen";
46
- if (/(^|;)font:[^;]*(^|\s|:)0(px|pt|em|rem|%)?\/|(^|;)font:0(px)?(\s|\/|;|$)/.test(s))
47
- return "tiny_or_transparent";
48
- // a custom property driving display/visibility/opacity/transform cannot be resolved statically; treat as hidden (hidden text is never delivered, so the cost of being wrong is low)
49
- if (/(display|visibility|opacity|transform|clip-path|font-size|scale|translate):var\(/.test(s))
50
- return "css_hidden";
51
- if (/transform:[^;]*translate(x|y|3d)?\(-?\d{3,}(px|em|rem|vw|vh)/.test(s))
52
- return "offscreen";
53
- // same-colour text is judged by contrast in the cascade (color.ts), not by comparing two strings here
54
- if (/-webkit-text-fill-color:transparent/.test(s))
55
- return "tiny_or_transparent";
56
- if (/(left|top|right|bottom|margin-left|margin-top|text-indent):-\d{3,}(px|em|rem|%|vw|vh)/.test(s))
57
- return "offscreen";
58
- if (/text-indent:(1\d\d|[2-9]\d\d|\d{4,})%/.test(s) || /text-indent:\d{4,}px/.test(s))
59
- return "offscreen";
60
- if (/position:(absolute|fixed)/.test(s) && /(left|top):\d{4,}(px|vw|vh)/.test(s))
61
- return "offscreen";
62
- if (/clip:rect\(0(px)?,0(px)?,0(px)?,0(px)?\)/.test(s) || /clip:rect\(1px,1px,1px,1px\)/.test(s))
63
- return "offscreen";
64
- if (/clip-path:(inset\(([4-9]\d|100)%|circle\(0|polygon\(0(px|%)?\s*0)/.test(s))
19
+ /**
20
+ * Class names that hide an element by convention, matched as whole class names. Matching inside names read
21
+ * `overflow-hidden`, `overflow-x-clip` and `bg-clip-text` as "hidden" and "clip", and hid the main column of
22
+ * every page that clips its overflow.
23
+ */
24
+ const A11Y_CLASSES = new Set(["sr-only", "visually-hidden", "screen-reader-only", "visuallyhidden", "a11y-hidden", "screen-reader-text", "visually-hidden-focusable"]);
25
+ const HIDDEN_CLASSES = new Set(["hidden", "offscreen", "is-hidden", "d-none", "invisible", "u-hidden", "hide", "is-invisible"]);
26
+ /** utility-framework variants: `md:block` shows at a width, `dark:block` in a theme, `not-sr-only` undoes sr-only */
27
+ const SHOWS_AT_A_WIDTH_OR_THEME = /^(?:sm|md|lg|xl|2xl|dark|light|print|max-(?:sm|md|lg|xl|2xl)|min-\[[^\]]+\]|supports-\[[^\]]+\]):(?:block|flex|grid|inline|inline-block|inline-flex|inline-grid|table|table-cell|contents|flow-root|list-item|visible|not-sr-only)$/;
28
+ const HIDES_ON_DESKTOP = /^(?:sm|md|lg|xl|2xl):(?:hidden|invisible|sr-only)$/;
29
+ /** How an element's class names hide it, if they do. A person at a desktop width in either theme is the reference. */
30
+ function classHides(cls) {
31
+ const tokens = cls.toLowerCase().split(/\s+/).filter(Boolean);
32
+ if (!tokens.length)
33
+ return null;
34
+ const shownSomewhere = tokens.some((t) => SHOWS_AT_A_WIDTH_OR_THEME.test(t));
35
+ if (tokens.some((t) => A11Y_CLASSES.has(t)) && !tokens.includes("not-sr-only") && !shownSomewhere)
36
+ return { vis: "css_hidden", a11y: true };
37
+ // `hidden lg:block` is a desktop sidebar: hidden on a phone, shown to the reader we model
38
+ if (tokens.some((t) => HIDDEN_CLASSES.has(t)) && !shownSomewhere)
39
+ return { vis: "css_hidden", a11y: false };
40
+ // `lg:hidden` is the phone menu: not shown at desktop width
41
+ if (tokens.some((t) => HIDES_ON_DESKTOP.test(t)))
42
+ return { vis: "css_hidden", a11y: false };
43
+ return null;
44
+ }
45
+ /**
46
+ * Split a declaration block into property -> value (lower case, whitespace removed, `!important` dropped).
47
+ * The last declaration of a property wins, as in the cascade. Semicolons inside parentheses or quotes
48
+ * (a data: URL) do not split.
49
+ */
50
+ export function parseDeclarations(style) {
51
+ const out = new Map();
52
+ let depth = 0, quote = "", start = 0;
53
+ const flush = (end) => {
54
+ const d = style.slice(start, end);
55
+ const i = d.indexOf(":");
56
+ if (i > 0) {
57
+ const prop = d.slice(0, i).trim().toLowerCase();
58
+ const value = d.slice(i + 1).toLowerCase().replace(/\s+/g, "").replace(/!important$/, "");
59
+ if (prop && value) {
60
+ out.delete(prop);
61
+ out.set(prop, value);
62
+ }
63
+ }
64
+ start = end + 1;
65
+ };
66
+ for (let i = 0; i < style.length; i++) {
67
+ const c = style[i];
68
+ if (quote) {
69
+ if (c === quote && style[i - 1] !== "\\")
70
+ quote = "";
71
+ continue;
72
+ }
73
+ if (c === '"' || c === "'")
74
+ quote = c;
75
+ else if (c === "(")
76
+ depth++;
77
+ else if (c === ")")
78
+ depth = Math.max(0, depth - 1);
79
+ else if (c === ";" && depth === 0)
80
+ flush(i);
81
+ }
82
+ flush(style.length);
83
+ return out;
84
+ }
85
+ /** Collect custom property definitions from CSS text (rule bodies or one inline style). */
86
+ export function collectCssVars(css, into = new Map()) {
87
+ for (const m of css.matchAll(/(--[\w-]+)\s*:\s*([^;{}]+)/g)) {
88
+ const v = m[2].toLowerCase().replace(/\s+/g, "").replace(/!important$/, "");
89
+ if (!v)
90
+ continue;
91
+ const set = into.get(m[1].toLowerCase()) ?? new Set();
92
+ if (set.size < 12)
93
+ set.add(v);
94
+ into.set(m[1].toLowerCase(), set);
95
+ }
96
+ return into;
97
+ }
98
+ /**
99
+ * Every value a declaration could take once its var() references are resolved: each known definition of
100
+ * the variable, and the fallback. A variable nobody defines statically resolves to nothing: its value is
101
+ * unknown, and unknown is not hidden. (Tailwind 4 sets every text size as `font-size:var(--text-sm)`;
102
+ * reading that as "hidden" marked whole sites as hidden text.)
103
+ */
104
+ function candidates(value, vars, depth = 0) {
105
+ const m = value.match(/var\((--[\w-]+)(?:,([^()]*(?:\([^()]*\)[^()]*)*))?\)/);
106
+ if (!m || depth > 4)
107
+ return [value];
108
+ const defs = [...(vars?.get(m[1]) ?? [])];
109
+ if (m[2] !== undefined && m[2] !== "")
110
+ defs.push(m[2]);
111
+ const out = [];
112
+ for (const d of defs.slice(0, 12))
113
+ out.push(...candidates(value.replace(m[0], d), vars, depth + 1));
114
+ return out.slice(0, 24);
115
+ }
116
+ const ZERO_ALPHA_COLOR = /^(?:transparent|rgba?\([^)]*[,/]0(?:\.0+)?%?\)|hsla?\([^)]*[,/]0(?:\.0+)?%?\)|#[0-9a-f]{6}00|#[0-9a-f]{3}0)$/;
117
+ const num = (v) => { const m = v.match(/^(-?\d*\.?\d+)(px|pt|em|rem|%|vw|vh)?$/); return m ? { n: Number(m[1]), unit: m[2] ?? "" } : undefined; };
118
+ /** One property with one concrete value: does it hide the element's text? */
119
+ function hidesByProperty(prop, v) {
120
+ switch (prop) {
121
+ case "display": return v === "none" ? "css_hidden" : null;
122
+ case "visibility": return v === "hidden" || v === "collapse" ? "css_hidden" : null;
123
+ case "content-visibility": return v === "hidden" ? "css_hidden" : null;
124
+ case "opacity": {
125
+ const x = num(v);
126
+ return x && (x.unit === "%" ? x.n < 10 : x.unit === "" && x.n < 0.1) ? "tiny_or_transparent" : null;
127
+ }
128
+ case "font-size": {
129
+ const x = num(v);
130
+ return x && x.n <= (x.unit === "em" || x.unit === "rem" ? 0.1 : x.unit === "%" ? 10 : 1) ? "tiny_or_transparent" : null;
131
+ }
132
+ case "color":
133
+ case "-webkit-text-fill-color": return ZERO_ALPHA_COLOR.test(v) ? "tiny_or_transparent" : null;
134
+ case "transform":
135
+ case "-webkit-transform":
136
+ if (/scale(x|y|3d)?\(0(\.0+)?[,)]/.test(v) || /scale(x|y)?\(0\.0\d/.test(v))
137
+ return "tiny_or_transparent";
138
+ return /translate(x|y|3d)?\(-?\d{3,}(px|em|rem|vw|vh)/.test(v) ? "offscreen" : null;
139
+ case "filter": return /opacity\(0(\.0\d*)?%?\)/.test(v) ? "tiny_or_transparent" : null;
140
+ case "scale": return /^0(\.0\d*)?($|[^\d.])/.test(v) ? "tiny_or_transparent" : null;
141
+ case "translate": return /^-?\d{3,}(px|em|rem|vw|vh|%)/.test(v) ? "offscreen" : null;
142
+ case "inset": return /-\d{3,}(px|em|rem|vw|vh|%)/.test(v) ? "offscreen" : null;
143
+ case "font": return /(^|[^\d.])0(px|pt|em|rem|%)?\//.test(v) || /^0(px)?(\/|$)/.test(v) ? "tiny_or_transparent" : null;
144
+ case "left":
145
+ case "top":
146
+ case "right":
147
+ case "bottom":
148
+ case "margin-left":
149
+ case "margin-top":
150
+ return /^-\d{3,}(px|em|rem|%|vw|vh)/.test(v) ? "offscreen" : null;
151
+ case "text-indent": return /^-\d{3,}(px|em|rem|%|vw|vh)/.test(v) || /^(1\d\d|[2-9]\d\d|\d{4,})%/.test(v) || /^\d{4,}px/.test(v) ? "offscreen" : null;
152
+ case "clip": return /^rect\(0(px)?,?0(px)?,?0(px)?,?0(px)?\)/.test(v) || /^rect\(1px,?1px,?1px,?1px\)/.test(v) ? "offscreen" : null;
153
+ case "clip-path": return /^(inset\(([4-9]\d|100)%|circle\(0|polygon\(0(px|%)?0)/.test(v) ? "offscreen" : null;
154
+ default: return null;
155
+ }
156
+ }
157
+ /**
158
+ * Classify a declaration block. Returns the hiding reason or null. Properties are matched by their exact
159
+ * names (so `-webkit-tap-highlight-color:transparent`, `background-color:rgba(0,0,0,0)` and
160
+ * `fill-opacity:0` hide nothing), and var() references are resolved against `vars` before judging.
161
+ */
162
+ export function classifyStyle(style, vars) {
163
+ const d = parseDeclarations(style);
164
+ // variables this very block defines apply to it too (style="--o:0;opacity:var(--o)")
165
+ let scope = vars;
166
+ for (const [p, v] of d)
167
+ if (p.startsWith("--")) {
168
+ scope = scope === vars ? new Map(vars ?? []) : scope;
169
+ const s = new Set(scope.get(p) ?? []);
170
+ s.add(v);
171
+ scope.set(p, s);
172
+ }
173
+ for (const [prop, value] of d) {
174
+ if (prop.startsWith("--"))
175
+ continue;
176
+ for (const v of value.includes("var(") ? candidates(value, scope) : [value]) {
177
+ const r = hidesByProperty(prop, v);
178
+ if (r)
179
+ return r;
180
+ }
181
+ }
182
+ // combinations
183
+ const get = (p) => d.get(p) ?? "";
184
+ const zero = (p) => /^0(px)?$/.test(get(p));
185
+ const clips = get("overflow") === "hidden" || get("overflow-x") === "hidden" || get("overflow-y") === "hidden";
186
+ if (clips && (zero("width") || zero("height") || zero("max-height") || zero("max-width")))
65
187
  return "offscreen";
66
- if (/(width|height|max-height|max-width):0(px)?;.*overflow:hidden/.test(s) || /overflow:hidden;.*(width|height|max-height|max-width):0(px)?(;|$)/.test(s))
188
+ if (clips && (get("width") === "1px" || get("height") === "1px") && get("position") === "absolute")
67
189
  return "offscreen";
68
- if (/(width|height):1px;.*overflow:hidden/.test(s) && /position:absolute/.test(s))
190
+ if (/^(absolute|fixed)$/.test(get("position")) && (/^\d{4,}(px|vw|vh)/.test(get("left")) || /^\d{4,}(px|vw|vh)/.test(get("top"))))
69
191
  return "offscreen";
70
192
  return null;
71
193
  }
72
- export function rulesFromCss(cssIn) {
194
+ /** Split a selector list on commas that are not inside parentheses or brackets (`:is(.a, .b)` is one selector). */
195
+ function splitSelectors(list) {
196
+ const out = [];
197
+ let depth = 0, start = 0;
198
+ for (let i = 0; i < list.length; i++) {
199
+ const c = list[i];
200
+ if (c === "(" || c === "[")
201
+ depth++;
202
+ else if (c === ")" || c === "]")
203
+ depth = Math.max(0, depth - 1);
204
+ else if (c === "," && depth === 0) {
205
+ out.push(list.slice(start, i));
206
+ start = i + 1;
207
+ }
208
+ }
209
+ out.push(list.slice(start));
210
+ return out.map((s) => s.trim()).filter(Boolean);
211
+ }
212
+ /** an ancestor that names a theme, a state or a script-set class: the rule applies in one mode of the page, not always */
213
+ const CONDITIONAL_ANCESTOR = /(^|[.#\[="'_-])(dark|light|theme|mode|print|no-?js|js|open|opened|closed|active|inactive|collapsed|expanded|loading|loaded|ready|is-|has-)/i;
214
+ /**
215
+ * Turn one selector into a rule the static pass can apply, or nothing when the selector does not describe
216
+ * what a reader at a desktop sees by default:
217
+ * - a pseudo-element (`::-webkit-scrollbar`, `::before`) styles another box, not the element's text.
218
+ * `.scroll::-webkit-scrollbar{display:none}` hides a scrollbar; read as hiding `.scroll`, it hid every
219
+ * table on a documentation page.
220
+ * - a state (`:hover`, `:checked`, `[data-state=closed]`, `[hidden]`) holds only sometimes. The `hidden`
221
+ * attribute itself is handled where elements are read.
222
+ * - an ancestor that names a theme or a state makes the rule one mode of the page.
223
+ * `:not(.class)` on the element is kept and checked (`.collapse:not(.show)`).
224
+ */
225
+ function ruleFromSelector(sel, reason) {
226
+ if (/^[.#]?[\w-]+$/.test(sel))
227
+ return { selector: sel, reason };
228
+ const parts = sel.replace(/\s*([>+~])\s*/g, " $1 ").split(/\s+/).filter((p) => p && !/^[>+~]$/.test(p));
229
+ const last = parts.pop() ?? "";
230
+ if (/::|:(before|after|first-line|first-letter|placeholder|marker|selection|backdrop|file-selector-button)\b/i.test(last))
231
+ return null;
232
+ if (last.includes("\\"))
233
+ return null; // an escaped name (`.lg\:hidden`): a variant class, read from the class list instead
234
+ const nots = [...last.matchAll(/:not\(\.([\w-]+)\)/g)].map((m) => m[1]);
235
+ const bare = last.replace(/:not\(\.[\w-]+\)/g, "");
236
+ if (/[:\[()*]/.test(bare))
237
+ return null; // any other pseudo-class or attribute test: a state
238
+ if (parts.some((a) => /[:\[\\]/.test(a) || CONDITIONAL_ANCESTOR.test(a)))
239
+ return null;
240
+ const classes = (bare.match(/\.[\w-]+/g) ?? []).map((c) => c.slice(1));
241
+ const id = bare.match(/#([\w-]+)/)?.[1];
242
+ const tag = bare.match(/^[a-z][\w-]*/i)?.[0]?.toLowerCase();
243
+ if (id)
244
+ return { selector: `#${id}`, reason, all: classes, not: nots, tag };
245
+ if (classes.length)
246
+ return { selector: `.${classes[classes.length - 1]}`, reason, all: classes.slice(0, -1), not: nots, tag };
247
+ if (tag && parts.length)
248
+ return null; // `nav ul`: a tag under an ancestor over-matches every such tag on the page
249
+ return tag ? { selector: tag, reason, not: nots } : null;
250
+ }
251
+ export function rulesFromCss(cssIn, extraVars) {
73
252
  const rules = [];
74
- // flatten @media / @supports wrappers: "@media x { a{..} }" -> "a{..}"; drop keyframes and comments
75
- const css = cssIn
76
- .replace(/\/\*[\s\S]*?\*\//g, "")
253
+ // media blocks that do not describe a desktop screen are dropped; the rest of the @-wrappers are flattened:
254
+ // "@media x { a{..} }" -> "a{..}". Keyframes and comments are dropped.
255
+ const css = dropAlternateMedia(cssIn.replace(/\/\*[\s\S]*?\*\//g, ""))
77
256
  .replace(/@keyframes[^{]*\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}/g, "")
78
257
  .replace(/@(media|supports|layer|container)[^{]*\{/g, "");
258
+ // custom properties defined anywhere in this stylesheet, so var() references can be resolved before judging
259
+ const vars = collectCssVars(css, new Map(extraVars ?? []));
79
260
  const re = /([^{}]+)\{([^{}]*)\}/g;
80
261
  let m;
81
262
  let count = 0;
82
263
  while ((m = re.exec(css)) && count++ < 20000) {
83
- const reason = classifyStyle(m[2]);
264
+ const reason = classifyStyle(m[2], vars);
84
265
  if (!reason)
85
266
  continue;
86
- for (const sel of m[1].split(",")) {
87
- const t = sel.trim();
88
- if (/^[.#]?[\w-]+$/.test(t)) {
89
- rules.push({ selector: t, reason });
90
- continue;
91
- }
92
- // compound/descendant selectors: key on the last simple class or id; over-matching only raises suspicion
93
- const last = t.split(/[\s>+~]+/).pop() ?? "";
94
- const simple = last.match(/[.#][\w-]+/g);
95
- if (simple)
96
- rules.push({ selector: simple[simple.length - 1], reason });
267
+ for (const sel of splitSelectors(m[1])) {
268
+ const r = ruleFromSelector(sel, reason);
269
+ if (r)
270
+ rules.push(r);
97
271
  }
98
272
  }
99
273
  return rules;
100
274
  }
101
- /** Remove @media blocks that do not describe the default screen rendering (dark mode, print), brace-matched. */
275
+ /** widths below this are phones and small tablets: `@media (max-width: 767px)` does not describe a desktop screen */
276
+ const DESKTOP_MIN_PX = 1024;
277
+ function isAlternateMedia(query) {
278
+ const q = query.toLowerCase();
279
+ if (/prefers-color-scheme\s*:\s*dark|\bprint\b|forced-colors|prefers-contrast|prefers-reduced-(motion|transparency)|\(\s*hover\s*:\s*none\s*\)|\(\s*pointer\s*:\s*coarse\s*\)|orientation\s*:\s*portrait/.test(q))
280
+ return true;
281
+ // a width cap below desktop: `max-width: 767px`, `width <= 40rem`, `width < 640px`
282
+ for (const m of q.matchAll(/(?:max-width\s*:|width\s*<=?)\s*(\d*\.?\d+)(px|em|rem)/g)) {
283
+ const px = Number(m[1]) * (m[2] === "px" ? 1 : 16);
284
+ if (px < DESKTOP_MIN_PX)
285
+ return true;
286
+ }
287
+ return false;
288
+ }
289
+ /** Remove @media blocks that do not describe the default desktop screen (dark mode, print, phone widths), brace-matched. */
102
290
  function dropAlternateMedia(css) {
103
291
  let out = "", i = 0;
104
- const re = /@media[^{]*(prefers-color-scheme\s*:\s*dark|print|forced-colors|prefers-contrast)[^{]*\{/gi;
292
+ const re = /@media([^{]*)\{/gi;
105
293
  let m;
106
294
  while ((m = re.exec(css))) {
295
+ if (!isAlternateMedia(m[1]))
296
+ continue;
107
297
  out += css.slice(i, m.index);
108
298
  let depth = 1, j = m.index + m[0].length;
109
299
  while (j < css.length && depth > 0) {
@@ -153,10 +343,15 @@ function attr(el, name) {
153
343
  return el.attrs.find((a) => a.name === name)?.value;
154
344
  }
155
345
  function matchesRule(el, rule) {
156
- if (rule.selector.startsWith(".")) {
157
- const cls = attr(el, "class") ?? "";
158
- return cls.split(/\s+/).includes(rule.selector.slice(1));
159
- }
346
+ const classes = (attr(el, "class") ?? "").split(/\s+/);
347
+ if (rule.tag && rule.selector !== rule.tag && el.tagName !== rule.tag)
348
+ return false;
349
+ if (rule.all?.some((c) => !classes.includes(c)))
350
+ return false;
351
+ if (rule.not?.some((c) => classes.includes(c)))
352
+ return false;
353
+ if (rule.selector.startsWith("."))
354
+ return classes.includes(rule.selector.slice(1));
160
355
  if (rule.selector.startsWith("#"))
161
356
  return attr(el, "id") === rule.selector.slice(1);
162
357
  return el.tagName === rule.selector;
@@ -195,6 +390,9 @@ export function analyzeHtml(html, externalRules = [], externalColorRules = []) {
195
390
  const lowContrast = new Map();
196
391
  const lowContrastRatio = new Map();
197
392
  let maxDepth = 0;
393
+ /** custom properties defined in the page's own <style> blocks and style attributes */
394
+ const cssVars = new Map();
395
+ const styleBlocks = [];
198
396
  // pass 1: <style> rules and stylesheet links (iterative)
199
397
  {
200
398
  const stack = [doc];
@@ -203,15 +401,23 @@ export function analyzeHtml(html, externalRules = [], externalColorRules = []) {
203
401
  if (defaultTreeAdapter.isElementNode(n)) {
204
402
  if (n.tagName === "style") {
205
403
  const css = n.childNodes.map((c) => (defaultTreeAdapter.isTextNode(c) ? c.value : "")).join("");
206
- styleRules.push(...rulesFromCss(css));
404
+ styleBlocks.push(css);
405
+ collectCssVars(css, cssVars);
207
406
  colorRules.push(...colorRulesFromCss(css));
208
407
  }
408
+ // a custom property set in a style attribute can drive a rule elsewhere (style="--o:0" with opacity:var(--o))
409
+ const inline = attr(n, "style");
410
+ if (inline && inline.includes("--"))
411
+ collectCssVars(inline, cssVars);
209
412
  if (n.tagName === "link" && /\bstylesheet\b/.test((attr(n, "rel") ?? "").toLowerCase()) && attr(n, "href"))
210
413
  stylesheetLinks.push(attr(n, "href"));
211
414
  }
212
415
  for (const c of children(n))
213
416
  stack.push(c);
214
417
  }
418
+ // rules are classified once every variable the page defines is known, wherever it was defined
419
+ for (const css of styleBlocks)
420
+ styleRules.push(...rulesFromCss(css, cssVars));
215
421
  }
216
422
  // pass 2: segments and scripts (iterative, document order)
217
423
  let scriptIndex = 0;
@@ -360,20 +566,20 @@ export function analyzeHtml(html, externalRules = [], externalColorRules = []) {
360
566
  vis = "css_hidden";
361
567
  const style = attr(el, "style");
362
568
  if (style)
363
- vis = classifyStyle(style) ?? vis;
569
+ vis = classifyStyle(style, cssVars) ?? vis;
364
570
  if (vis === "visible")
365
571
  for (const r of styleRules)
366
572
  if (matchesRule(el, r)) {
367
573
  vis = r.reason;
368
574
  break;
369
575
  }
370
- const cls = attr(el, "class") ?? "";
371
- if (vis === "visible" && A11Y_CLASS_HINTS.test(cls)) {
372
- vis = "css_hidden";
373
- a11y = true;
576
+ if (vis === "visible") {
577
+ const h = classHides(attr(el, "class") ?? "");
578
+ if (h) {
579
+ vis = h.vis;
580
+ a11y = a11y || h.a11y;
581
+ }
374
582
  }
375
- if (vis === "visible" && HIDDEN_CLASS_HINTS.test(cls))
376
- vis = "css_hidden";
377
583
  }
378
584
  const kids = el.childNodes;
379
585
  for (let i = kids.length - 1; i >= 0; i--) {
@@ -390,6 +596,7 @@ export function analyzeHtml(html, externalRules = [], externalColorRules = []) {
390
596
  attribute: "visibility.attribute_only",
391
597
  comment: "visibility.html_comment",
392
598
  tiny_or_transparent: "visibility.tiny_or_transparent",
599
+ concealed: "visibility.css_hidden", // not produced by the HTML pass; here so the map is total
393
600
  };
394
601
  for (const s of segments) {
395
602
  if (s.visibility === "visible")
@@ -0,0 +1,48 @@
1
+ // ingress-presence: is a person at this machine, right now?
2
+ //
3
+ // An approval dialog can be clicked by anything that controls the pointer. This asks the operating system to
4
+ // confirm a person: Touch ID, an unlocked Apple Watch, or the login password, checked by macOS itself
5
+ // (LocalAuthentication). The answer is the system's, not this program's.
6
+ //
7
+ // ingress-presence --check can this machine ask? prints JSON
8
+ // ingress-presence [--biometry-only] <reason> ask; exit 0 only if the person was confirmed
9
+ //
10
+ // Build: swiftc -O -swift-version 5 ingress-presence.swift -o ingress-presence (macOS 12 or later)
11
+
12
+ import Foundation
13
+ import LocalAuthentication
14
+
15
+ func emit(_ d: [String: Any], _ code: Int32) -> Never {
16
+ if let data = try? JSONSerialization.data(withJSONObject: d, options: [.sortedKeys]) { FileHandle.standardOutput.write(data); FileHandle.standardOutput.write("\n".data(using: .utf8)!) }
17
+ exit(code)
18
+ }
19
+
20
+ var args = Array(CommandLine.arguments.dropFirst())
21
+ let biometryOnly = args.contains("--biometry-only")
22
+ args.removeAll { $0 == "--biometry-only" }
23
+ let policy: LAPolicy = biometryOnly ? .deviceOwnerAuthenticationWithBiometrics : .deviceOwnerAuthentication
24
+ let ctx = LAContext()
25
+ var why: NSError?
26
+ let can = ctx.canEvaluatePolicy(policy, error: &why)
27
+ let kind: String = { switch ctx.biometryType { case .touchID: return "touch-id"; case .faceID: return "face-id"; default: return "none" } }()
28
+
29
+ if args.first == "--check" {
30
+ emit(["available": can, "biometry": kind, "biometryOnly": biometryOnly, "reason": why?.localizedDescription ?? ""], 0)
31
+ }
32
+ guard let reason = args.first, !reason.isEmpty else {
33
+ FileHandle.standardError.write("usage: ingress-presence --check | ingress-presence [--biometry-only] <reason>\n".data(using: .utf8)!)
34
+ exit(2)
35
+ }
36
+ guard can else { emit(["ok": false, "error": why?.localizedDescription ?? "this machine cannot confirm a person"], 1) }
37
+
38
+ ctx.localizedCancelTitle = "Deny"
39
+ let done = DispatchSemaphore(value: 0)
40
+ var ok = false
41
+ var failure = ""
42
+ ctx.evaluatePolicy(policy, localizedReason: String(reason.prefix(300))) { success, error in
43
+ ok = success
44
+ failure = error?.localizedDescription ?? ""
45
+ done.signal()
46
+ }
47
+ if done.wait(timeout: .now() + 120) == .timedOut { ctx.invalidate(); emit(["ok": false, "error": "nobody answered in two minutes"], 1) }
48
+ emit(ok ? ["ok": true, "biometry": kind] : ["ok": false, "error": failure], ok ? 0 : 1)