From 1e38f6bfd323214007a31f788e6968b9ed675db9 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:09:55 -0600 Subject: [PATCH 01/48] Add first and last name to My details --- README.md | 2 +- core/src/profile.test.ts | 64 +++++++++++++++++++++++++++++++++++++++- core/src/profile.ts | 2 ++ 3 files changed, 66 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1ad958e..37baadf 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Stage 1 is the dashboard. Stage 2 adds saving a job from the page you are on, pl - **Formhand log.** On an application, record the application site type and how filling went. You enter it by hand. - **Contacts** (`#/contacts`) with a log of reaching out, replies and referrals. The popup and the application page ask "anyone here?" and let you record that you checked and nobody was there. - **Deadlines** (`#/deadlines`): open tasks, next-action dates and quiet applications on one list, dated rows first. -- **My details** (`#/details`): 12 profile fields (name, email, phone, address, links) and your canonical answers, each with a copy button. Copying uses a click only, and nothing is typed into a page. +- **My details** (`#/details`): 14 profile fields (name, first and last name, email, phone, address, links) and your canonical answers, each with a copy button. Copying uses a click only, and nothing is typed into a page. - **Application detail** with a status history. Entries can be backdated, and a mistaken status can be undone without deleting history. - **Resume and cover-letter records.** You attach a file to record which one you sent. Countersign stores the file name and a SHA-256 hash, not the file. - **Canonical answers** (for example work authorisation or salary range), each with its history of earlier values. diff --git a/core/src/profile.test.ts b/core/src/profile.test.ts index 270d467..f75d43b 100644 --- a/core/src/profile.test.ts +++ b/core/src/profile.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { profileValues, setProfileFieldOps } from './profile'; +import { PROFILE_FIELDS, profileValues, setProfileFieldOps } from './profile'; import { emptySnapshot } from './schema'; import type { Deps, ProfileField, Snapshot } from './types'; @@ -219,7 +219,69 @@ describe('setProfileFieldOps', () => { }); }); +describe('PROFILE_FIELDS', () => { + it('has fourteen fields in order', () => { + expect(PROFILE_FIELDS.map((f) => f.key)).toEqual([ + 'full_name', + 'first_name', + 'last_name', + 'email', + 'phone', + 'address_line1', + 'address_line2', + 'city', + 'region', + 'postal_code', + 'country', + 'linkedin', + 'github', + 'website', + ]); + }); + + it('saves last name with its label', () => { + expect( + setProfileFieldOps(emptySnapshot(), 'last_name', 'Example', deps()), + ).toEqual([ + { + kind: 'put', + store: 'profileFields', + record: { + id: 'new1', + createdAt: NOW, + key: 'last_name', + label: 'Last name', + value: 'Example', + }, + }, + ]); + }); +}); + describe('profileValues', () => { + it('reads first and last name', () => { + const data = withFields( + { + id: 'p1', + createdAt: OLD, + key: 'first_name', + label: 'First name', + value: 'Sam', + }, + { + id: 'p2', + createdAt: OLD, + key: 'last_name', + label: 'Last name', + value: 'Example', + }, + ); + expect(profileValues(data)).toEqual({ + first_name: 'Sam', + last_name: 'Example', + }); + }); + it('reads one value per known key', () => { const data = withFields( { diff --git a/core/src/profile.ts b/core/src/profile.ts index f92a3d7..93326e1 100644 --- a/core/src/profile.ts +++ b/core/src/profile.ts @@ -3,6 +3,8 @@ import type { Deps, Id, Snapshot } from './types'; export const PROFILE_FIELDS = [ { key: 'full_name', label: 'Full name' }, + { key: 'first_name', label: 'First name' }, + { key: 'last_name', label: 'Last name' }, { key: 'email', label: 'Email' }, { key: 'phone', label: 'Phone' }, { key: 'address_line1', label: 'Address line 1' }, From 4787270a0e8102068c6a3a25c5ee9aad31f2eabd Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:13:52 -0600 Subject: [PATCH 02/48] Add fill scan types and validation --- core/src/fill/types.ts | 124 +++++++++++ core/src/fill/validate.test.ts | 372 +++++++++++++++++++++++++++++++++ core/src/fill/validate.ts | 151 +++++++++++++ 3 files changed, 647 insertions(+) create mode 100644 core/src/fill/types.ts create mode 100644 core/src/fill/validate.test.ts create mode 100644 core/src/fill/validate.ts diff --git a/core/src/fill/types.ts b/core/src/fill/types.ts new file mode 100644 index 0000000..f96fcd7 --- /dev/null +++ b/core/src/fill/types.ts @@ -0,0 +1,124 @@ +import type { ProfileKey } from '../profile'; +import type { AnswerValue, CanonicalAnswer } from '../types'; + +export const MAX_FIELDS = 200; +export const MAX_OPTIONS = 50; +export const MAX_LABEL = 300; +export const MAX_VALUE = 500; +export const MAX_FRAMES = 5; +export const MAX_FRAME_SRC = 2_000; +export const MAX_AUTOCOMPLETE = 40; + +export const CONTROL_KINDS = [ + 'text', + 'textarea', + 'date', + 'select', + 'choice_group', + 'file', + 'custom', +] as const; +export type ControlKind = (typeof CONTROL_KINDS)[number]; + +export interface ScannedField { + /** The field's number in the page script's list for this scan. */ + ref: number; + control: ControlKind; + /** '' when none was found. */ + label: string; + /** Last token, lower case; '' when absent. */ + autocomplete: string; + required: boolean; + /** Text, textarea, date: the value. Select: the chosen option's text, '' on a placeholder. Others: ''. */ + value: string; + /** Select (placeholders left out) and choice_group; [] otherwise. */ + options: string[]; + /** Choice_group: indexes into options; [] otherwise. */ + checked: number[]; + /** A checkbox group or a multi-select. */ + multiple: boolean; + /** The page had more than MAX_OPTIONS options. */ + optionsTruncated: boolean; +} + +export interface FormScan { + fields: ScannedField[]; + frames: string[]; + truncated: boolean; +} + +export type FillWrite = + | { ref: number; kind: 'value'; value: string } + | { ref: number; kind: 'option'; index: number }; + +export const WRITE_OUTCOMES = [ + 'written', + 'gone', + 'not_empty', + 'failed', +] as const; +export type WriteOutcome = (typeof WRITE_OUTCOMES)[number]; + +export interface WriteReport { + ref: number; + outcome: WriteOutcome; +} + +export interface ApplyResult { + outcomes: WriteReport[]; + scan: FormScan; +} + +export type FillTarget = + { kind: 'profile'; key: ProfileKey } | { kind: 'answer'; key: string }; + +export type RowStatus = 'will_fill' | 'matches' | 'differs' | 'not_filled'; + +export type NotFilledReason = + | 'no_value' + | 'custom_control' + | 'unsupported_control' + | 'never_auto' + | 'ambiguous' + | 'negated' + | 'other_country' + | 'file' + | 'not_recognised' + | 'changed'; + +export interface PlanRow { + ref: number; + label: string; + control: ControlKind; + required: boolean; + /** Absent on file and not_recognised rows. */ + target?: FillTarget; + status: RowStatus; + /** Set exactly when status is 'not_filled'. */ + reason?: NotFilledReason; + /** What the form holds now, as text. */ + formValue: string; + /** The owner's value as text; '' when there is none or it must not be offered. */ + ownValue: string; + /** Set exactly when status is 'will_fill'. */ + write?: FillWrite; + /** Answer targets that have a value. */ + answerValue?: AnswerValue; +} + +export interface FrameAdvice { + site: 'greenhouse' | 'ashby'; + src: string; +} + +export interface FillPlan { + rows: PlanRow[]; + writes: FillWrite[]; + unrecognisedOptional: number; + frames: FrameAdvice[]; +} + +export interface PlanInput { + profile: Partial>; + answers: readonly CanonicalAnswer[]; +} diff --git a/core/src/fill/validate.test.ts b/core/src/fill/validate.test.ts new file mode 100644 index 0000000..b2e87f8 --- /dev/null +++ b/core/src/fill/validate.test.ts @@ -0,0 +1,372 @@ +import { describe, expect, it } from 'vitest'; +import type { FormScan, ScannedField } from './types'; +import { toApplyResult, toFormScan } from './validate'; + +function field(over: Record = {}): Record { + return { + ref: 0, + control: 'text', + label: 'First name', + autocomplete: 'given-name', + required: true, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + ...over, + }; +} + +function scanOf( + fields: unknown[], + extra: Record = {}, +): Record { + return { fields, frames: [], truncated: false, ...extra }; +} + +describe('toFormScan', () => { + it('passes a well-formed scan through', () => { + const fields: ScannedField[] = [ + { + ref: 0, + control: 'text', + label: 'Name', + autocomplete: 'name', + required: true, + value: 'Ada Example', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 1, + control: 'textarea', + label: 'Why us', + autocomplete: '', + required: false, + value: 'Because', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 2, + control: 'date', + label: 'Start date', + autocomplete: '', + required: false, + value: '2026-12-01', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 3, + control: 'select', + label: 'Country', + autocomplete: 'country', + required: false, + value: 'Canada', + options: ['Canada', 'Mexico'], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 4, + control: 'choice_group', + label: 'Authorised', + autocomplete: '', + required: true, + value: '', + options: ['Yes', 'No'], + checked: [0], + multiple: false, + optionsTruncated: false, + }, + { + ref: 5, + control: 'file', + label: 'Resume', + autocomplete: '', + required: true, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 6, + control: 'custom', + label: 'Skills', + autocomplete: '', + required: false, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + ]; + const scan: FormScan = { + fields, + frames: ['https://jobs.example.com/a'], + truncated: false, + }; + expect(toFormScan(structuredClone(scan))).toEqual(scan); + }); + + it('rejects non-objects', () => { + expect(toFormScan(undefined)).toBeUndefined(); + expect(toFormScan('x')).toBeUndefined(); + expect(toFormScan([1])).toBeUndefined(); + expect(toFormScan(new Date())).toBeUndefined(); + expect(toFormScan({ fields: 'no' })).toBeUndefined(); + const swapped = Object.create({ x: 1 }) as Record; + swapped.fields = []; + expect(toFormScan(swapped)).toBeUndefined(); + }); + + it('caps a hostile scan', () => { + const many = Array.from({ length: 5000 }, (_, i) => field({ ref: i })); + const big = toFormScan(scanOf(many)); + expect(big?.fields).toHaveLength(200); + expect(big?.truncated).toBe(true); + + const one = toFormScan( + scanOf([ + field({ + label: 'a'.repeat(10_000), + value: 'b'.repeat(600), + }), + ]), + ); + expect(one?.fields[0]?.label).toHaveLength(300); + expect(one?.fields[0]?.value).toHaveLength(500); + + const opts = Array.from({ length: 80 }, (_, i) => `o${String(i)}`); + const sel = toFormScan( + scanOf([field({ control: 'select', options: opts })]), + ); + expect(sel?.fields[0]?.options).toHaveLength(50); + expect(sel?.fields[0]?.optionsTruncated).toBe(true); + }); + + it('caps autocomplete and each option, after trimming', () => { + const scan = toFormScan( + scanOf([ + field({ + control: 'select', + autocomplete: ` ${'X'.repeat(100)} `, + options: [` ${'y'.repeat(400)} `, ' Yes '], + }), + ]), + ); + expect(scan?.fields[0]?.autocomplete).toBe('x'.repeat(40)); + expect(scan?.fields[0]?.options).toEqual(['y'.repeat(300), 'Yes']); + }); + + it('trusts truncation flags only when exactly true', () => { + const scan = toFormScan( + scanOf([field({ control: 'select', optionsTruncated: true })], { + truncated: true, + }), + ); + expect(scan?.truncated).toBe(true); + expect(scan?.fields[0]?.optionsTruncated).toBe(true); + const no = toFormScan( + scanOf([field({ control: 'select', optionsTruncated: 'true' })], { + truncated: 1, + }), + ); + expect(no?.truncated).toBe(false); + expect(no?.fields[0]?.optionsTruncated).toBe(false); + }); + + it('drops bad fields', () => { + const scan = toFormScan( + scanOf([ + field({ ref: -1 }), + field({ ref: 1.5 }), + field({ ref: '2' }), + field({ ref: 3 }), + field({ ref: 3, label: 'dup' }), + field({ ref: 4, control: 'password' }), + null, + field({ ref: 5 }), + ]), + ); + expect(scan?.fields.map((f) => f.ref)).toEqual([3, 5]); + expect(scan?.fields[0]?.label).toBe('First name'); + }); + + it('coerces types', () => { + const scan = toFormScan( + scanOf([ + field({ label: 42, required: 'yes', multiple: 1 }), + field({ + ref: 1, + control: 'choice_group', + options: ['Yes', 7, 'No'], + checked: [0, 9, 'x'], + multiple: true, + }), + field({ ref: 2, control: 'choice_group', options: ['A', 'B'] }), + ]), + ); + expect(scan?.fields[0]?.label).toBe(''); + expect(scan?.fields[0]?.required).toBe(false); + expect(scan?.fields[0]?.multiple).toBe(false); + expect(scan?.fields[1]?.options).toEqual(['Yes', 'No']); + expect(scan?.fields[1]?.checked).toEqual([0]); + expect(scan?.fields[1]?.multiple).toBe(true); + expect(scan?.fields[2]?.checked).toEqual([]); + }); + + it('treats a missing or non-array frames, options and checked as empty', () => { + const scan = toFormScan({ + fields: [ + field({ control: 'choice_group', options: 'Yes', checked: 'x' }), + ], + frames: 'https://a.example.com', + }); + expect(scan?.frames).toEqual([]); + expect(scan?.fields[0]?.options).toEqual([]); + expect(scan?.fields[0]?.checked).toEqual([]); + }); + + it('empties values a control does not use', () => { + const scan = toFormScan( + scanOf([ + field({ ref: 0, control: 'file', value: 'C:\\x.pdf' }), + field({ ref: 1, control: 'custom', value: 'x', options: ['a'] }), + field({ + ref: 2, + control: 'text', + value: 'kept', + options: ['a'], + checked: [0], + multiple: true, + }), + field({ + ref: 3, + control: 'select', + value: 'a', + options: ['a', 'b'], + checked: [0], + multiple: true, + }), + ]), + ); + expect(scan?.fields[0]?.value).toBe(''); + expect(scan?.fields[1]?.value).toBe(''); + expect(scan?.fields[1]?.options).toEqual([]); + expect(scan?.fields[2]).toMatchObject({ + value: 'kept', + options: [], + checked: [], + multiple: false, + }); + expect(scan?.fields[3]).toMatchObject({ + value: 'a', + options: ['a', 'b'], + checked: [], + multiple: true, + }); + }); + + it('keeps only https frames', () => { + const one = toFormScan( + scanOf([], { + frames: ['https://jobs.ashbyhq.com/a', 'javascript:alert(1)', 7], + }), + ); + expect(one?.frames).toEqual(['https://jobs.ashbyhq.com/a']); + + const six = toFormScan( + scanOf([], { + frames: Array.from( + { length: 6 }, + (_, i) => `https://e.example.com/${String(i)}`, + ), + }), + ); + expect(six?.frames).toHaveLength(5); + + const long = toFormScan( + scanOf([], { frames: [`https://e.example.com/${'a'.repeat(3000)}`] }), + ); + expect(long?.frames[0]).toHaveLength(2000); + }); + + it('ignores unknown keys', () => { + const raw: unknown = JSON.parse( + '{"fields":[],"frames":[],"extra":1,"__proto__":{"x":1}}', + ); + expect(toFormScan(raw)).toEqual({ + fields: [], + frames: [], + truncated: false, + }); + }); +}); + +describe('toApplyResult', () => { + const scan = scanOf([field()]); + + it('passes a good result', () => { + const result = toApplyResult({ + outcomes: [ + { ref: 0, outcome: 'written' }, + { ref: 1, outcome: 'not_empty' }, + ], + scan, + }); + expect(result?.outcomes).toEqual([ + { ref: 0, outcome: 'written' }, + { ref: 1, outcome: 'not_empty' }, + ]); + expect(result?.scan.fields).toHaveLength(1); + }); + + it('turns an unknown outcome into failed', () => { + const result = toApplyResult({ + outcomes: [ + { ref: 0, outcome: 'exploded' }, + { ref: 1, outcome: 7 }, + ], + scan, + }); + expect(result?.outcomes).toEqual([ + { ref: 0, outcome: 'failed' }, + { ref: 1, outcome: 'failed' }, + ]); + }); + + it('rejects a missing scan or bad shape', () => { + expect(toApplyResult({ outcomes: [] })).toBeUndefined(); + expect(toApplyResult({ outcomes: [], scan: 'x' })).toBeUndefined(); + expect(toApplyResult({ outcomes: 'no', scan })).toBeUndefined(); + expect(toApplyResult(null)).toBeUndefined(); + }); + + it('drops entries without an integer ref and caps at 200', () => { + const outcomes: unknown[] = [ + { ref: 'a', outcome: 'written' }, + { ref: 1.5, outcome: 'written' }, + null, + ...Array.from({ length: 300 }, (_, i) => ({ + ref: i, + outcome: 'written', + })), + ]; + const result = toApplyResult({ outcomes, scan }); + expect(result?.outcomes).toHaveLength(200); + expect(result?.outcomes[0]?.ref).toBe(0); + }); +}); diff --git a/core/src/fill/validate.ts b/core/src/fill/validate.ts new file mode 100644 index 0000000..407e4de --- /dev/null +++ b/core/src/fill/validate.ts @@ -0,0 +1,151 @@ +import { + CONTROL_KINDS, + MAX_AUTOCOMPLETE, + MAX_FIELDS, + MAX_FRAME_SRC, + MAX_FRAMES, + MAX_LABEL, + MAX_OPTIONS, + MAX_VALUE, + WRITE_OUTCOMES, + type ApplyResult, + type ControlKind, + type FormScan, + type ScannedField, + type WriteOutcome, + type WriteReport, +} from './types'; + +// Everything here arrives from a script that ran inside a web page. It is +// capped or dropped, never thrown on. + +function isPlainObject(value: unknown): value is Record { + if (typeof value !== 'object' || value === null || Array.isArray(value)) + return false; + const proto: unknown = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function text(value: unknown, max: number): string { + return typeof value === 'string' ? value.trim().slice(0, max) : ''; +} + +function controlOf(value: unknown): ControlKind | undefined { + return CONTROL_KINDS.find((kind) => kind === value); +} + +const VALUE_CONTROLS: readonly ControlKind[] = [ + 'text', + 'textarea', + 'date', + 'select', +]; +const OPTION_CONTROLS: readonly ControlKind[] = ['select', 'choice_group']; + +function toOptions(raw: unknown): { options: string[]; cut: boolean } { + const options: string[] = []; + if (!Array.isArray(raw)) return { options, cut: false }; + for (const entry of raw as unknown[]) { + if (typeof entry !== 'string') continue; + if (options.length === MAX_OPTIONS) return { options, cut: true }; + options.push(text(entry, MAX_LABEL)); + } + return { options, cut: false }; +} + +function toChecked(raw: unknown, optionCount: number): number[] { + if (!Array.isArray(raw)) return []; + const checked: number[] = []; + for (const entry of raw as unknown[]) { + if ( + typeof entry === 'number' && + Number.isInteger(entry) && + entry >= 0 && + entry < optionCount && + !checked.includes(entry) + ) + checked.push(entry); + } + return checked; +} + +function toField(raw: unknown): ScannedField | undefined { + if (!isPlainObject(raw)) return undefined; + const ref = raw.ref; + if (typeof ref !== 'number' || !Number.isInteger(ref) || ref < 0) + return undefined; + const control = controlOf(raw.control); + if (control === undefined) return undefined; + const usesOptions = OPTION_CONTROLS.includes(control); + const { options, cut } = usesOptions + ? toOptions(raw.options) + : { options: [], cut: false }; + return { + ref, + control, + label: text(raw.label, MAX_LABEL), + autocomplete: text(raw.autocomplete, MAX_AUTOCOMPLETE).toLowerCase(), + required: raw.required === true, + value: VALUE_CONTROLS.includes(control) ? text(raw.value, MAX_VALUE) : '', + options, + checked: + control === 'choice_group' ? toChecked(raw.checked, options.length) : [], + multiple: usesOptions && raw.multiple === true, + optionsTruncated: usesOptions && (cut || raw.optionsTruncated === true), + }; +} + +function toFrames(raw: unknown): string[] { + if (!Array.isArray(raw)) return []; + const frames: string[] = []; + for (const entry of raw as unknown[]) { + if (frames.length === MAX_FRAMES) break; + if (typeof entry === 'string' && entry.startsWith('https://')) + frames.push(entry.slice(0, MAX_FRAME_SRC)); + } + return frames; +} + +export function toFormScan(raw: unknown): FormScan | undefined { + if (!isPlainObject(raw) || !Array.isArray(raw.fields)) return undefined; + const fields: ScannedField[] = []; + const seen = new Set(); + let cut = false; + for (const entry of raw.fields as unknown[]) { + const field = toField(entry); + if (field === undefined || seen.has(field.ref)) continue; + if (fields.length === MAX_FIELDS) { + cut = true; + break; + } + seen.add(field.ref); + fields.push(field); + } + return { + fields, + frames: toFrames(raw.frames), + truncated: cut || raw.truncated === true, + }; +} + +function outcomeOf(value: unknown): WriteOutcome { + return WRITE_OUTCOMES.find((outcome) => outcome === value) ?? 'failed'; +} + +export function toApplyResult(raw: unknown): ApplyResult | undefined { + if (!isPlainObject(raw) || !Array.isArray(raw.outcomes)) return undefined; + const scan = toFormScan(raw.scan); + if (scan === undefined) return undefined; + const outcomes: WriteReport[] = []; + for (const entry of raw.outcomes as unknown[]) { + if (outcomes.length === MAX_FIELDS) break; + if ( + !isPlainObject(entry) || + typeof entry.ref !== 'number' || + !Number.isInteger(entry.ref) + ) + continue; + outcomes.push({ ref: entry.ref, outcome: outcomeOf(entry.outcome) }); + } + return { outcomes, scan }; +} From 2976255579828d60c82e1aba75fcd48d3d367dc3 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:16:57 -0600 Subject: [PATCH 03/48] Tighten fill scan validation --- core/src/fill/validate.test.ts | 52 ++++++++++++++++++++++++++++++++++ core/src/fill/validate.ts | 15 +++++++--- 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/core/src/fill/validate.test.ts b/core/src/fill/validate.test.ts index b2e87f8..43964ff 100644 --- a/core/src/fill/validate.test.ts +++ b/core/src/fill/validate.test.ts @@ -228,6 +228,58 @@ describe('toFormScan', () => { expect(scan?.fields[2]?.checked).toEqual([]); }); + it('marks the options untrusted when a non-string option was dropped', () => { + const scan = toFormScan( + scanOf([ + field({ ref: 0, control: 'select', options: ['Yes', 7, 'No'] }), + field({ ref: 1, control: 'select', options: ['Yes', 'No'] }), + field({ ref: 2, control: 'choice_group', options: [null, 'No'] }), + ]), + ); + expect(scan?.fields[0]).toMatchObject({ + options: ['Yes', 'No'], + optionsTruncated: true, + }); + expect(scan?.fields[1]?.optionsTruncated).toBe(false); + expect(scan?.fields[2]).toMatchObject({ + options: ['No'], + optionsTruncated: true, + }); + }); + + it('drops a ref that is not a safe integer', () => { + const scan = toFormScan(scanOf([field({ ref: 1e300 }), field({ ref: 2 })])); + expect(scan?.fields.map((f) => f.ref)).toEqual([2]); + const result = toApplyResult({ + outcomes: [ + { ref: 1e300, outcome: 'written' }, + { ref: 2, outcome: 'written' }, + ], + scan: scanOf([]), + }); + expect(result?.outcomes).toEqual([{ ref: 2, outcome: 'written' }]); + }); + + it('keeps optionsTruncated false on a control without options', () => { + const scan = toFormScan( + scanOf([field({ control: 'text', optionsTruncated: true })]), + ); + expect(scan?.fields[0]?.optionsTruncated).toBe(false); + }); + + it('drops duplicate and out-of-range checked indexes', () => { + const scan = toFormScan( + scanOf([ + field({ + control: 'choice_group', + options: ['A', 'B'], + checked: [1, 1, -1, 0], + }), + ]), + ); + expect(scan?.fields[0]?.checked).toEqual([1, 0]); + }); + it('treats a missing or non-array frames, options and checked as empty', () => { const scan = toFormScan({ fields: [ diff --git a/core/src/fill/validate.ts b/core/src/fill/validate.ts index 407e4de..a9096a2 100644 --- a/core/src/fill/validate.ts +++ b/core/src/fill/validate.ts @@ -42,15 +42,21 @@ const VALUE_CONTROLS: readonly ControlKind[] = [ ]; const OPTION_CONTROLS: readonly ControlKind[] = ['select', 'choice_group']; +// `cut` is true when the list is not trustworthy as a whole: it was cut at +// the cap, or a non-string entry was dropped (which shifts later indexes). function toOptions(raw: unknown): { options: string[]; cut: boolean } { const options: string[] = []; if (!Array.isArray(raw)) return { options, cut: false }; + let dropped = false; for (const entry of raw as unknown[]) { - if (typeof entry !== 'string') continue; + if (typeof entry !== 'string') { + dropped = true; + continue; + } if (options.length === MAX_OPTIONS) return { options, cut: true }; options.push(text(entry, MAX_LABEL)); } - return { options, cut: false }; + return { options, cut: dropped }; } function toChecked(raw: unknown, optionCount: number): number[] { @@ -72,7 +78,7 @@ function toChecked(raw: unknown, optionCount: number): number[] { function toField(raw: unknown): ScannedField | undefined { if (!isPlainObject(raw)) return undefined; const ref = raw.ref; - if (typeof ref !== 'number' || !Number.isInteger(ref) || ref < 0) + if (typeof ref !== 'number' || !Number.isSafeInteger(ref) || ref < 0) return undefined; const control = controlOf(raw.control); if (control === undefined) return undefined; @@ -142,7 +148,8 @@ export function toApplyResult(raw: unknown): ApplyResult | undefined { if ( !isPlainObject(entry) || typeof entry.ref !== 'number' || - !Number.isInteger(entry.ref) + !Number.isSafeInteger(entry.ref) || + entry.ref < 0 ) continue; outcomes.push({ ref: entry.ref, outcome: outcomeOf(entry.outcome) }); From b519712fce4376fdfecf75f09dfbfd72bf4a1e78 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:19:11 -0600 Subject: [PATCH 04/48] Add label normalising for the fill matcher --- core/src/fill/normalize.test.ts | 104 ++++++++++++++++++++++++++++++++ core/src/fill/normalize.ts | 40 ++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 core/src/fill/normalize.test.ts create mode 100644 core/src/fill/normalize.ts diff --git a/core/src/fill/normalize.test.ts b/core/src/fill/normalize.test.ts new file mode 100644 index 0000000..c9db3c5 --- /dev/null +++ b/core/src/fill/normalize.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'vitest'; +import { + containsPhrase, + hasNegation, + isPlaceholderOption, + normalizeLabel, +} from './normalize'; + +describe('normalizeLabel', () => { + it('lower-cases and drops required markers and stars', () => { + expect(normalizeLabel('First Name *')).toBe('first name'); + expect(normalizeLabel('E-mail (required)')).toBe('e mail'); + expect(normalizeLabel('Phone ✱')).toBe('phone'); + }); + + it('drops optional markers regardless of case', () => { + expect(normalizeLabel('State/Province (Optional)')).toBe('state province'); + }); + + it('turns punctuation into spaces and trims', () => { + expect(normalizeLabel(' LinkedIn URL: ')).toBe('linkedin url'); + expect(normalizeLabel('U.S.')).toBe('u s'); + }); + + it('returns an empty string for empty input', () => { + expect(normalizeLabel('')).toBe(''); + }); +}); + +describe('containsPhrase', () => { + it('matches a phrase of whole words inside the text', () => { + expect( + containsPhrase( + 'are you legally authorized to work in the united states', + 'authorized to work', + ), + ).toBe(true); + }); + + it('does not match a phrase that is only part of a word', () => { + expect( + containsPhrase('i am unauthorized to work', 'authorized to work'), + ).toBe(false); + }); + + it('matches a single whole word', () => { + expect(containsPhrase('salary', 'salary')).toBe(true); + }); + + it('does not match a word that only starts with the phrase', () => { + expect(containsPhrase('salaryman', 'salary')).toBe(false); + }); + + it('returns false for an empty phrase', () => { + expect(containsPhrase('salary', '')).toBe(false); + }); +}); + +describe('hasNegation', () => { + it.each([ + 'Are you not authorized', + "Don't you need sponsorship?", + 'Don’t you', + 'without sponsorship', + 'no longer eligible', + 'cannot work', + 'unless sponsored', + ])('is true for %j', (raw) => { + expect(hasNegation(raw)).toBe(true); + }); + + it.each(['Are you authorized to work?', 'Notice period', 'Notes', 'Nothing'])( + 'is false for %j', + (raw) => { + expect(hasNegation(raw)).toBe(false); + }, + ); +}); + +describe('isPlaceholderOption', () => { + it('treats an empty value as a placeholder at any index', () => { + expect(isPlaceholderOption('Choose one', '', 0)).toBe(true); + expect(isPlaceholderOption('No', '', 2)).toBe(true); + }); + + it('treats a leading select, choose, please or pick option as a placeholder', () => { + expect(isPlaceholderOption('Select...', 'Select...', 0)).toBe(true); + expect(isPlaceholderOption('Please select', 'p', 0)).toBe(true); + expect(isPlaceholderOption('Pick one', 'p', 0)).toBe(true); + }); + + it('treats a first option with no letters or digits as a placeholder', () => { + expect(isPlaceholderOption('--', 'x', 0)).toBe(true); + expect(isPlaceholderOption('--', 'x', 1)).toBe(false); + }); + + it('keeps a real option that is not first', () => { + expect(isPlaceholderOption('Select Committee', 's', 1)).toBe(false); + }); + + it('keeps a real first option', () => { + expect(isPlaceholderOption('Yes', 'yes', 0)).toBe(false); + }); +}); diff --git a/core/src/fill/normalize.ts b/core/src/fill/normalize.ts new file mode 100644 index 0000000..1fefd4d --- /dev/null +++ b/core/src/fill/normalize.ts @@ -0,0 +1,40 @@ +const NEGATION_WORDS = + /(? Date: Fri, 20 Nov 2026 10:22:06 -0600 Subject: [PATCH 05/48] Add the country table for work questions --- core/src/fill/countries.test.ts | 214 ++++++++++++++++++++++ core/src/fill/countries.ts | 307 ++++++++++++++++++++++++++++++++ 2 files changed, 521 insertions(+) create mode 100644 core/src/fill/countries.test.ts create mode 100644 core/src/fill/countries.ts diff --git a/core/src/fill/countries.test.ts b/core/src/fill/countries.test.ts new file mode 100644 index 0000000..8dc6b76 --- /dev/null +++ b/core/src/fill/countries.test.ts @@ -0,0 +1,214 @@ +import { describe, expect, it } from 'vitest'; +import { + COUNTRY_NAMES, + COUNTRY_TABLE, + REGION_TABLE, + countryOf, + placesNamed, +} from './countries'; +import { normalizeLabel } from './normalize'; + +const PREFIX = 'are you authorized to work in '; + +describe('COUNTRY_NAMES', () => { + it('covers the UN members', () => { + expect(COUNTRY_NAMES.length).toBeGreaterThanOrEqual(200); + expect(new Set(COUNTRY_NAMES).size).toBe(COUNTRY_NAMES.length); + for (const name of [ + 'estonia', + 'papua new guinea', + 'south sudan', + 'timor leste', + 'eswatini', + 'north macedonia', + 'kiribati', + 'canada', + 'india', + 'germany', + ]) { + expect(COUNTRY_NAMES).toContain(name); + } + }); + + it('stores every name and alias in normalised form', () => { + for (const row of [...COUNTRY_TABLE, ...REGION_TABLE]) { + for (const name of row) { + expect(name).toBe(normalizeLabel(name)); + expect(name).not.toBe(''); + } + } + }); + + it('never repeats a name or alias across the whole table', () => { + const all = [...COUNTRY_TABLE, ...REGION_TABLE].flat(); + expect(new Set(all).size).toBe(all.length); + }); +}); + +describe('countryOf', () => { + it('reads common spellings of the United States', () => { + for (const text of [ + 'United States', + 'USA', + 'U.S.', + 'us', + ' United States of America ', + ]) { + expect(countryOf(text)).toBe('united states'); + } + }); + + it('reads the United Kingdom', () => { + expect(countryOf('UK')).toBe('united kingdom'); + }); + + it('needs the whole string to be a place', () => { + expect(countryOf('Texas, USA')).toBeUndefined(); + expect(countryOf('')).toBeUndefined(); + expect(countryOf('EU')).toBeUndefined(); + expect(countryOf('Narnia')).toBeUndefined(); + }); + + it.each([ + ['usa', 'united states'], + ['u s a', 'united states'], + ['america', 'united states'], + ['england', 'united kingdom'], + ['scotland', 'united kingdom'], + ['wales', 'united kingdom'], + ['northern ireland', 'united kingdom'], + ['great britain', 'united kingdom'], + ['britain', 'united kingdom'], + ['u k', 'united kingdom'], + ['uae', 'united arab emirates'], + ['korea', 'south korea'], + ['republic of korea', 'south korea'], + ['russian federation', 'russia'], + ['czech republic', 'czechia'], + ['holland', 'netherlands'], + ['the netherlands', 'netherlands'], + ['cote d ivoire', 'ivory coast'], + ['côte d ivoire', 'ivory coast'], + ['turkiye', 'turkey'], + ['türkiye', 'turkey'], + ['burma', 'myanmar'], + ['the gambia', 'gambia'], + ['the bahamas', 'bahamas'], + ['cabo verde', 'cape verde'], + ['east timor', 'timor leste'], + ['swaziland', 'eswatini'], + ['macedonia', 'north macedonia'], + ['bosnia', 'bosnia and herzegovina'], + ['st lucia', 'saint lucia'], + ['holy see', 'vatican city'], + ['macao', 'macau'], + ['viet nam', 'vietnam'], + ['dr congo', 'democratic republic of the congo'], + ['dprk', 'north korea'], + ['hong kong', 'hong kong'], + ['kosovo', 'kosovo'], + ['taiwan', 'taiwan'], + ['palestine', 'palestine'], + ['puerto rico', 'puerto rico'], + ['vatican city', 'vatican city'], + ])('reads %s as %s', (text, expected) => { + expect(countryOf(text)).toBe(expected); + }); + + it.each(REGION_TABLE.flat())( + 'does not read the region %s as a country', + (name) => { + expect(countryOf(name)).toBeUndefined(); + }, + ); +}); + +describe('placesNamed', () => { + it('finds a country', () => { + expect(placesNamed(PREFIX + 'the united states')).toEqual([ + 'united states', + ]); + expect(placesNamed(PREFIX + 'estonia')).toEqual(['estonia']); + }); + + it('consumes what it matched', () => { + expect(placesNamed(PREFIX + 'papua new guinea')).toEqual([ + 'papua new guinea', + ]); + expect(placesNamed(PREFIX + 'nigeria')).toEqual(['nigeria']); + expect(placesNamed(PREFIX + 'dominican republic')).toEqual([ + 'dominican republic', + ]); + expect(placesNamed(PREFIX + 'south sudan')).toEqual(['south sudan']); + expect(placesNamed(PREFIX + 'equatorial guinea')).toEqual([ + 'equatorial guinea', + ]); + expect(placesNamed(PREFIX + 'northern ireland')).toEqual([ + 'united kingdom', + ]); + }); + + it('returns several places in order of first appearance, once each', () => { + expect(placesNamed(PREFIX + 'the us or canada')).toEqual([ + 'united states', + 'canada', + ]); + expect(placesNamed('canada or the us or canada')).toEqual([ + 'canada', + 'united states', + ]); + expect(placesNamed('usa or the united states')).toEqual(['united states']); + }); + + it('finds regions', () => { + expect(placesNamed(PREFIX + 'the eu')).toEqual(['european union']); + expect(placesNamed(PREFIX + 'the e u')).toEqual(['european union']); + expect(placesNamed(PREFIX + 'the european economic area')).toEqual(['eea']); + expect(placesNamed(PREFIX + 'europe')).toEqual(['europe']); + expect(placesNamed(PREFIX + 'the schengen area')).toEqual(['schengen']); + expect(placesNamed(PREFIX + 'emea')).toEqual(['emea']); + expect(placesNamed(PREFIX + 'latin america')).toEqual(['latin america']); + expect(placesNamed(PREFIX + 'north america')).toEqual(['north america']); + }); + + it('reads continents and regions as themselves, not as a country', () => { + for (const [text, expected] of [ + ['south america', 'south america'], + ['central america', 'central america'], + ['the americas', 'americas'], + ['asia', 'asia'], + ['africa', 'africa'], + ['the middle east', 'middle east'], + ['oceania', 'oceania'], + ['the caribbean', 'caribbean'], + ['asia pacific', 'apac'], + ['apac', 'apac'], + ] as const) { + expect(placesNamed(PREFIX + text)).toEqual([expected]); + } + }); + + it('keeps a country apart from a region that shares a word', () => { + expect(placesNamed(PREFIX + 'south africa')).toEqual(['south africa']); + expect(placesNamed(PREFIX + 'north korea')).toEqual(['north korea']); + expect(placesNamed(PREFIX + 'korea')).toEqual(['south korea']); + expect(placesNamed(PREFIX + 'north america or the us')).toEqual([ + 'north america', + 'united states', + ]); + }); + + it('names nothing for a generic question', () => { + expect(placesNamed(PREFIX + 'this country')).toEqual([]); + expect(placesNamed('')).toEqual([]); + }); + + it('accepts a known false alarm in the safe direction', () => { + expect(placesNamed('tell us about yourself')).toEqual(['united states']); + }); + + it('matches whole words only', () => { + expect(placesNamed('do you use indiana software')).toEqual([]); + expect(placesNamed('a business')).toEqual([]); + }); +}); diff --git a/core/src/fill/countries.ts b/core/src/fill/countries.ts new file mode 100644 index 0000000..c8edb65 --- /dev/null +++ b/core/src/fill/countries.ts @@ -0,0 +1,307 @@ +import { normalizeLabel } from './normalize'; + +// One row per place: the canonical name first, then its aliases. Every entry is +// stored the way normalizeLabel writes it. The table exists so a question about +// another place is never answered with the owner's own country, so recognising +// one place too many is the safe direction. +export const COUNTRY_TABLE: readonly (readonly string[])[] = [ + ['afghanistan'], + ['albania'], + ['algeria'], + ['andorra'], + ['angola'], + ['antigua and barbuda'], + ['argentina'], + ['armenia'], + ['australia'], + ['austria'], + ['azerbaijan'], + ['bahamas', 'the bahamas'], + ['bahrain'], + ['bangladesh'], + ['barbados'], + ['belarus'], + ['belgium'], + ['belize'], + ['benin'], + ['bhutan'], + ['bolivia'], + ['bosnia and herzegovina', 'bosnia'], + ['botswana'], + ['brazil'], + ['brunei', 'brunei darussalam'], + ['bulgaria'], + ['burkina faso'], + ['burundi'], + ['cambodia'], + ['cameroon'], + ['canada'], + ['cape verde', 'cabo verde'], + ['central african republic'], + ['chad'], + ['chile'], + ['china'], + ['colombia'], + ['comoros'], + ['congo', 'republic of the congo'], + ['costa rica'], + ['croatia'], + ['cuba'], + ['cyprus'], + ['czechia', 'czech republic'], + ['democratic republic of the congo', 'dr congo'], + ['denmark'], + ['djibouti'], + ['dominica'], + ['dominican republic'], + ['ecuador'], + ['egypt'], + ['el salvador'], + ['equatorial guinea'], + ['eritrea'], + ['estonia'], + ['eswatini', 'swaziland'], + ['ethiopia'], + ['fiji'], + ['finland'], + ['france'], + ['gabon'], + ['gambia', 'the gambia'], + ['georgia'], + ['germany'], + ['ghana'], + ['greece'], + ['grenada'], + ['guatemala'], + ['guinea'], + ['guinea bissau'], + ['guyana'], + ['haiti'], + ['honduras'], + ['hungary'], + ['iceland'], + ['india'], + ['indonesia'], + ['iran'], + ['iraq'], + ['ireland'], + ['israel'], + ['italy'], + ['ivory coast', 'cote d ivoire', 'côte d ivoire'], + ['jamaica'], + ['japan'], + ['jordan'], + ['kazakhstan'], + ['kenya'], + ['kiribati'], + ['kuwait'], + ['kyrgyzstan'], + ['laos'], + ['latvia'], + ['lebanon'], + ['lesotho'], + ['liberia'], + ['libya'], + ['liechtenstein'], + ['lithuania'], + ['luxembourg'], + ['madagascar'], + ['malawi'], + ['malaysia'], + ['maldives'], + ['mali'], + ['malta'], + ['marshall islands'], + ['mauritania'], + ['mauritius'], + ['mexico'], + ['micronesia', 'federated states of micronesia'], + ['moldova'], + ['monaco'], + ['mongolia'], + ['montenegro'], + ['morocco'], + ['mozambique'], + ['myanmar', 'burma'], + ['namibia'], + ['nauru'], + ['nepal'], + ['netherlands', 'the netherlands', 'holland'], + ['new zealand'], + ['nicaragua'], + ['niger'], + ['nigeria'], + ['north korea', 'dprk', 'democratic people s republic of korea'], + ['north macedonia', 'macedonia'], + ['norway'], + ['oman'], + ['pakistan'], + ['palau'], + ['panama'], + ['papua new guinea'], + ['paraguay'], + ['peru'], + ['philippines'], + ['poland'], + ['portugal'], + ['qatar'], + ['romania'], + ['russia', 'russian federation'], + ['rwanda'], + ['saint kitts and nevis'], + ['saint lucia', 'st lucia'], + ['saint vincent and the grenadines'], + ['samoa'], + ['san marino'], + ['sao tome and principe'], + ['saudi arabia'], + ['senegal'], + ['serbia'], + ['seychelles'], + ['sierra leone'], + ['singapore'], + ['slovakia'], + ['slovenia'], + ['solomon islands'], + ['somalia'], + ['south africa'], + ['south korea', 'korea', 'republic of korea'], + ['south sudan'], + ['spain'], + ['sri lanka'], + ['sudan'], + ['suriname'], + ['sweden'], + ['switzerland'], + ['syria'], + ['tajikistan'], + ['tanzania'], + ['thailand'], + ['timor leste', 'east timor'], + ['togo'], + ['tonga'], + ['trinidad and tobago'], + ['tunisia'], + ['turkey', 'turkiye', 'türkiye'], + ['turkmenistan'], + ['tuvalu'], + ['uganda'], + ['ukraine'], + ['united arab emirates', 'uae'], + [ + 'united kingdom', + 'uk', + 'u k', + 'great britain', + 'britain', + 'england', + 'scotland', + 'wales', + 'northern ireland', + ], + [ + 'united states', + 'usa', + 'u s a', + 'us', + 'u s', + 'united states of america', + 'america', + ], + ['uruguay'], + ['uzbekistan'], + ['vanuatu'], + ['venezuela'], + ['vietnam', 'viet nam'], + ['yemen'], + ['zambia'], + ['zimbabwe'], + // Not UN members, but places a question can name. + ['kosovo'], + ['taiwan'], + ['hong kong'], + ['macau', 'macao'], + ['palestine', 'state of palestine'], + ['puerto rico'], + ['vatican city', 'vatican', 'holy see'], +]; + +// Regions are named by questions but are never a My details country. +export const REGION_TABLE: readonly (readonly string[])[] = [ + ['european union', 'eu', 'e u'], + ['europe'], + ['eea', 'european economic area'], + ['schengen'], + ['emea'], + ['apac', 'asia pacific'], + ['latin america'], + ['north america'], + ['south america'], + ['central america'], + ['americas', 'the americas'], + ['asia'], + ['africa'], + ['middle east'], + ['oceania'], + ['caribbean'], +]; + +/** Canonical country names, lower case. Regions are not included. */ +export const COUNTRY_NAMES: readonly string[] = COUNTRY_TABLE.map( + (row) => row[0]!, +); + +const COUNTRY_BY_ALIAS = new Map(); +for (const row of COUNTRY_TABLE) { + for (const alias of row) COUNTRY_BY_ALIAS.set(alias, row[0]!); +} + +interface Matcher { + readonly words: readonly string[]; + readonly length: number; + readonly canonical: string; +} + +// Longest first (more words, then more characters) so a shorter alias cannot +// match inside a longer one, such as "guinea" inside "papua new guinea". +const MATCHERS: readonly Matcher[] = [...COUNTRY_TABLE, ...REGION_TABLE] + .flatMap((row) => + row.map((alias) => ({ + words: alias.split(' '), + length: alias.length, + canonical: row[0]!, + })), + ) + .sort((a, b) => b.words.length - a.words.length || b.length - a.length); + +/** Reads a My details value as a country. The whole text must be one name. */ +export function countryOf(text: string): string | undefined { + return COUNTRY_BY_ALIAS.get(normalizeLabel(text)); +} + +/** + * Every country and region a normalised question names, each once, in the + * order it first appears. Matches whole words and uses each word once. + */ +export function placesNamed(normalizedQuestion: string): string[] { + if (normalizedQuestion === '') return []; + const words = normalizedQuestion.split(' '); + const used = new Array(words.length).fill(false); + const firstSeen = new Map(); + for (const matcher of MATCHERS) { + const size = matcher.words.length; + for (let start = 0; start + size <= words.length; start++) { + if (!matcher.words.every((word, i) => words[start + i] === word)) + continue; + if (used.slice(start, start + size).some(Boolean)) continue; + used.fill(true, start, start + size); + const seen = firstSeen.get(matcher.canonical); + if (seen === undefined || start < seen) { + firstSeen.set(matcher.canonical, start); + } + } + } + return [...firstSeen.entries()] + .sort((a, b) => a[1] - b[1]) + .map(([name]) => name); +} From ce0fd6f224caa68c6eb86e09d74744cdabf468ee Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:23:38 -0600 Subject: [PATCH 06/48] Tighten placeholder and negation checks --- core/src/fill/normalize.test.ts | 24 ++++++++++++++++++++++++ core/src/fill/normalize.ts | 10 +++++----- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/core/src/fill/normalize.test.ts b/core/src/fill/normalize.test.ts index c9db3c5..a93b6bc 100644 --- a/core/src/fill/normalize.test.ts +++ b/core/src/fill/normalize.test.ts @@ -25,6 +25,18 @@ describe('normalizeLabel', () => { it('returns an empty string for empty input', () => { expect(normalizeLabel('')).toBe(''); }); + + it('keeps words apart when a required marker sits between them', () => { + expect(normalizeLabel('Name(required)here')).toBe('name here'); + }); + + it('collapses repeated spaces inside a label', () => { + expect(normalizeLabel('FIRST NAME')).toBe('first name'); + }); + + it('drops a leading optional marker', () => { + expect(normalizeLabel('(Optional) City')).toBe('city'); + }); }); describe('containsPhrase', () => { @@ -61,8 +73,14 @@ describe('hasNegation', () => { 'Are you not authorized', "Don't you need sponsorship?", 'Don’t you', + 'Donʼt you', + 'Don‘t you', + 'Don`t you', 'without sponsorship', 'no longer eligible', + 'no\nlonger eligible', + 'no longer eligible', + 'no longer eligible', 'cannot work', 'unless sponsored', ])('is true for %j', (raw) => { @@ -94,6 +112,12 @@ describe('isPlaceholderOption', () => { expect(isPlaceholderOption('--', 'x', 1)).toBe(false); }); + it('does not treat a word that only starts with a placeholder word as one', () => { + expect(isPlaceholderOption('Pickup', 'p', 0)).toBe(false); + expect(isPlaceholderOption('Selection', 's', 0)).toBe(false); + expect(isPlaceholderOption('Chooser', 'c', 0)).toBe(false); + }); + it('keeps a real option that is not first', () => { expect(isPlaceholderOption('Select Committee', 's', 1)).toBe(false); }); diff --git a/core/src/fill/normalize.ts b/core/src/fill/normalize.ts index 1fefd4d..c208db3 100644 --- a/core/src/fill/normalize.ts +++ b/core/src/fill/normalize.ts @@ -1,16 +1,16 @@ const NEGATION_WORDS = - /(? Date: Fri, 20 Nov 2026 10:25:19 -0600 Subject: [PATCH 07/48] Add value comparison for the fill plan --- core/src/fill/compare.test.ts | 51 ++++++++++++++++++++++++++++++++++ core/src/fill/compare.ts | 52 +++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 core/src/fill/compare.test.ts create mode 100644 core/src/fill/compare.ts diff --git a/core/src/fill/compare.test.ts b/core/src/fill/compare.test.ts new file mode 100644 index 0000000..ac7b35f --- /dev/null +++ b/core/src/fill/compare.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest'; +import { sameLink, samePhone, sameProfileValue, sameText } from './compare'; + +describe('sameText', () => { + it('ignores surrounding spaces and case', () => { + expect(sameText(' Sam ', 'sam')).toBe(true); + }); + + it('treats different words as different', () => { + expect(sameText('Sam', 'Samuel')).toBe(false); + }); +}); + +describe('samePhone', () => { + it.each([ + ['+1 (555) 010-0142', '555 010 0142', true], + ['555-010-0142', '5550100142', true], + ['555-010-0142', '555-010-0143', false], + ['0142', '10142', false], + ['5550100142', '99995550100142', false], + ['', '', false], + ['abc', 'def', false], + ])('samePhone(%j, %j) is %s', (a, b, expected) => { + expect(samePhone(a, b)).toBe(expected); + }); +}); + +describe('sameLink', () => { + it.each([ + ['https://www.example.com/in/sam/', 'example.com/in/sam', true], + ['HTTP://Example.com', 'example.com', true], + ['example.com/a', 'example.com/b', false], + ['https://example.com//', 'example.com', true], + ])('sameLink(%j, %j) is %s', (a, b, expected) => { + expect(sameLink(a, b)).toBe(expected); + }); +}); + +describe('sameProfileValue', () => { + it.each([ + ['phone', '+1 555 010 0142', '5550100142', true], + ['website', 'https://example.com/', 'example.com', true], + ['city', 'Springfield ', 'springfield', true], + ['email', 'a@example.com', 'b@example.com', false], + ] as const)( + 'sameProfileValue(%j, %j, %j) is %s', + (key, formValue, own, expected) => { + expect(sameProfileValue(key, formValue, own)).toBe(expected); + }, + ); +}); diff --git a/core/src/fill/compare.ts b/core/src/fill/compare.ts new file mode 100644 index 0000000..ba64d11 --- /dev/null +++ b/core/src/fill/compare.ts @@ -0,0 +1,52 @@ +import type { ProfileKey } from '../profile'; + +/** Trimmed, case-insensitive equality. */ +export function sameText(a: string, b: string): boolean { + return a.trim().toLowerCase() === b.trim().toLowerCase(); +} + +/** + * Equal digit strings match, as does a shorter number (at least 7 digits) + * that is the tail of a longer one with 1 to 3 extra leading digits. + */ +export function samePhone(a: string, b: string): boolean { + const digitsA = a.replace(/\D/g, ''); + const digitsB = b.replace(/\D/g, ''); + if (digitsA === digitsB) { + return digitsA !== ''; + } + const [short, long] = + digitsA.length <= digitsB.length ? [digitsA, digitsB] : [digitsB, digitsA]; + const extra = long.length - short.length; + return short.length >= 7 && long.endsWith(short) && extra >= 1 && extra <= 3; +} + +function normalizeLink(value: string): string { + let link = value.trim().toLowerCase(); + link = link.replace(/^https?:\/\//, ''); + link = link.replace(/^www\./, ''); + return link.replace(/\/+$/, ''); +} + +/** Compares URLs or domains, ignoring scheme, leading www. and trailing slashes. */ +export function sameLink(a: string, b: string): boolean { + return normalizeLink(a) === normalizeLink(b); +} + +/** Picks the comparison rule for a saved profile key. */ +export function sameProfileValue( + key: ProfileKey, + formValue: string, + own: string, +): boolean { + switch (key) { + case 'phone': + return samePhone(formValue, own); + case 'linkedin': + case 'github': + case 'website': + return sameLink(formValue, own); + default: + return sameText(formValue, own); + } +} From c198f0998cf1ad7c3cd8773b1bfc70b6413b41f6 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:27:46 -0600 Subject: [PATCH 08/48] Recognise more spellings of country names --- core/src/fill/countries.test.ts | 105 +++++++++++++++++++++++++++++++- core/src/fill/countries.ts | 91 ++++++++++++++++++++++----- 2 files changed, 177 insertions(+), 19 deletions(-) diff --git a/core/src/fill/countries.test.ts b/core/src/fill/countries.test.ts index 8dc6b76..0b9542e 100644 --- a/core/src/fill/countries.test.ts +++ b/core/src/fill/countries.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest'; import { COUNTRY_NAMES, COUNTRY_TABLE, + EXPANDED_COUNTRY_TABLE, + EXPANDED_REGION_TABLE, REGION_TABLE, countryOf, placesNamed, @@ -31,7 +33,12 @@ describe('COUNTRY_NAMES', () => { }); it('stores every name and alias in normalised form', () => { - for (const row of [...COUNTRY_TABLE, ...REGION_TABLE]) { + for (const row of [ + ...COUNTRY_TABLE, + ...REGION_TABLE, + ...EXPANDED_COUNTRY_TABLE, + ...EXPANDED_REGION_TABLE, + ]) { for (const name of row) { expect(name).toBe(normalizeLabel(name)); expect(name).not.toBe(''); @@ -39,10 +46,25 @@ describe('COUNTRY_NAMES', () => { } }); - it('never repeats a name or alias across the whole table', () => { - const all = [...COUNTRY_TABLE, ...REGION_TABLE].flat(); + it('never repeats a name or alias across the whole table, derived forms included', () => { + const all = [...EXPANDED_COUNTRY_TABLE, ...EXPANDED_REGION_TABLE].flat(); expect(new Set(all).size).toBe(all.length); }); + + it('derives the and-less form of every name and alias with "and"', () => { + const base = new Set([...COUNTRY_TABLE, ...REGION_TABLE].flat()); + const expanded = new Set( + [...EXPANDED_COUNTRY_TABLE, ...EXPANDED_REGION_TABLE].flat(), + ); + for (const name of base) { + if (!name.split(' ').includes('and')) continue; + const derived = name + .split(' ') + .filter((word) => word !== 'and') + .join(' '); + expect(expanded.has(derived)).toBe(true); + } + }); }); describe('countryOf', () => { @@ -211,4 +233,81 @@ describe('placesNamed', () => { expect(placesNamed('do you use indiana software')).toEqual([]); expect(placesNamed('a business')).toEqual([]); }); + + it.each([ + ['guinea bissau', 'guinea bissau'], + ['democratic republic of the congo', 'democratic republic of the congo'], + ['united states of america', 'united states'], + ['republic of korea', 'south korea'], + ['dr congo', 'democratic republic of the congo'], + ['democratic republic of congo', 'democratic republic of the congo'], + ['korea democratic people s republic of', 'north korea'], + ['korea republic of', 'south korea'], + ['congo democratic republic of the', 'democratic republic of the congo'], + ['congo republic of the', 'congo'], + ])('names only one place in %s', (text, expected) => { + expect(placesNamed(text)).toEqual([expected]); + }); + + it('reads a european country as Europe, and the union as the union', () => { + expect(placesNamed(PREFIX + 'a european country')).toEqual(['europe']); + expect(placesNamed(PREFIX + 'the european union')).toEqual([ + 'european union', + ]); + }); +}); + +describe('spellings without "and" and other added aliases', () => { + it.each([ + ['trinidad tobago', 'trinidad and tobago'], + ['antigua barbuda', 'antigua and barbuda'], + ['saint kitts nevis', 'saint kitts and nevis'], + ['saint vincent the grenadines', 'saint vincent and the grenadines'], + ['sao tome principe', 'sao tome and principe'], + ['bosnia herzegovina', 'bosnia and herzegovina'], + ['st kitts and nevis', 'saint kitts and nevis'], + ['st kitts nevis', 'saint kitts and nevis'], + ['st lucia', 'saint lucia'], + ['st vincent and the grenadines', 'saint vincent and the grenadines'], + ['st vincent the grenadines', 'saint vincent and the grenadines'], + ['u a e', 'united arab emirates'], + ['drc', 'democratic republic of the congo'], + ['d r c', 'democratic republic of the congo'], + ['democratic republic of congo', 'democratic republic of the congo'], + ['dr congo', 'democratic republic of the congo'], + ['congo kinshasa', 'democratic republic of the congo'], + ['congo brazzaville', 'congo'], + ['kyrgyz republic', 'kyrgyzstan'], + ['slovak republic', 'slovakia'], + ['lao pdr', 'laos'], + ['lao people s democratic republic', 'laos'], + ['syrian arab republic', 'syria'], + ['são tomé and príncipe', 'sao tome and principe'], + ['korea democratic people s republic of', 'north korea'], + ['korea republic of', 'south korea'], + ['congo democratic republic of the', 'democratic republic of the congo'], + ['congo republic of the', 'congo'], + ['brunei darussalam', 'brunei'], + ['federated states of micronesia', 'micronesia'], + ['state of palestine', 'palestine'], + ['vatican', 'vatican city'], + ['republic of the congo', 'congo'], + ['democratic people s republic of korea', 'north korea'], + ])('reads %s as %s in both lookups', (text, expected) => { + expect(countryOf(text)).toBe(expected); + expect(placesNamed(PREFIX + text)).toEqual([expected]); + }); + + it('reads european as a region only', () => { + expect(countryOf('European')).toBeUndefined(); + }); + + it('ignores a leading "the" when reading a country', () => { + expect(countryOf('The United States')).toBe('united states'); + expect(countryOf('the UK')).toBe('united kingdom'); + expect(countryOf('The Netherlands')).toBe('netherlands'); + expect(countryOf('The Gambia')).toBe('gambia'); + expect(countryOf('the')).toBeUndefined(); + expect(countryOf('The European Union')).toBeUndefined(); + }); }); diff --git a/core/src/fill/countries.ts b/core/src/fill/countries.ts index c8edb65..011e424 100644 --- a/core/src/fill/countries.ts +++ b/core/src/fill/countries.ts @@ -43,13 +43,26 @@ export const COUNTRY_TABLE: readonly (readonly string[])[] = [ ['china'], ['colombia'], ['comoros'], - ['congo', 'republic of the congo'], + [ + 'congo', + 'republic of the congo', + 'congo brazzaville', + 'congo republic of the', + ], ['costa rica'], ['croatia'], ['cuba'], ['cyprus'], ['czechia', 'czech republic'], - ['democratic republic of the congo', 'dr congo'], + [ + 'democratic republic of the congo', + 'dr congo', + 'drc', + 'd r c', + 'democratic republic of congo', + 'congo kinshasa', + 'congo democratic republic of the', + ], ['denmark'], ['djibouti'], ['dominica'], @@ -95,8 +108,8 @@ export const COUNTRY_TABLE: readonly (readonly string[])[] = [ ['kenya'], ['kiribati'], ['kuwait'], - ['kyrgyzstan'], - ['laos'], + ['kyrgyzstan', 'kyrgyz republic'], + ['laos', 'lao pdr', 'lao people s democratic republic'], ['latvia'], ['lebanon'], ['lesotho'], @@ -131,7 +144,12 @@ export const COUNTRY_TABLE: readonly (readonly string[])[] = [ ['nicaragua'], ['niger'], ['nigeria'], - ['north korea', 'dprk', 'democratic people s republic of korea'], + [ + 'north korea', + 'dprk', + 'democratic people s republic of korea', + 'korea democratic people s republic of', + ], ['north macedonia', 'macedonia'], ['norway'], ['oman'], @@ -148,24 +166,24 @@ export const COUNTRY_TABLE: readonly (readonly string[])[] = [ ['romania'], ['russia', 'russian federation'], ['rwanda'], - ['saint kitts and nevis'], + ['saint kitts and nevis', 'st kitts and nevis'], ['saint lucia', 'st lucia'], - ['saint vincent and the grenadines'], + ['saint vincent and the grenadines', 'st vincent and the grenadines'], ['samoa'], ['san marino'], - ['sao tome and principe'], + ['sao tome and principe', 'são tomé and príncipe'], ['saudi arabia'], ['senegal'], ['serbia'], ['seychelles'], ['sierra leone'], ['singapore'], - ['slovakia'], + ['slovakia', 'slovak republic'], ['slovenia'], ['solomon islands'], ['somalia'], ['south africa'], - ['south korea', 'korea', 'republic of korea'], + ['south korea', 'korea', 'republic of korea', 'korea republic of'], ['south sudan'], ['spain'], ['sri lanka'], @@ -173,7 +191,7 @@ export const COUNTRY_TABLE: readonly (readonly string[])[] = [ ['suriname'], ['sweden'], ['switzerland'], - ['syria'], + ['syria', 'syrian arab republic'], ['tajikistan'], ['tanzania'], ['thailand'], @@ -187,7 +205,7 @@ export const COUNTRY_TABLE: readonly (readonly string[])[] = [ ['tuvalu'], ['uganda'], ['ukraine'], - ['united arab emirates', 'uae'], + ['united arab emirates', 'uae', 'u a e'], [ 'united kingdom', 'uk', @@ -229,7 +247,7 @@ export const COUNTRY_TABLE: readonly (readonly string[])[] = [ // Regions are named by questions but are never a My details country. export const REGION_TABLE: readonly (readonly string[])[] = [ ['european union', 'eu', 'e u'], - ['europe'], + ['europe', 'european'], ['eea', 'european economic area'], ['schengen'], ['emea'], @@ -251,8 +269,43 @@ export const COUNTRY_NAMES: readonly string[] = COUNTRY_TABLE.map( (row) => row[0]!, ); +// normalizeLabel turns "&" into a space, so "Trinidad & Tobago" arrives as +// "trinidad tobago". Registers the "and"-less form of every name that has one, +// skipping a form that is already taken by another entry. +function withAndlessForms( + tables: readonly (readonly (readonly string[])[])[], +): (readonly string[])[][] { + const taken = new Set(tables.flat(2)); + return tables.map((table) => + table.map((row) => { + const expanded = [...row]; + for (const name of row) { + const words = name.split(' '); + if (!words.includes('and')) continue; + const derived = words.filter((word) => word !== 'and').join(' '); + if (derived === '' || taken.has(derived)) continue; + taken.add(derived); + expanded.push(derived); + } + return expanded; + }), + ); +} + +const [expandedCountries, expandedRegions] = withAndlessForms([ + COUNTRY_TABLE, + REGION_TABLE, +]); + +/** COUNTRY_TABLE with the derived "and"-less spellings added to each row. */ +export const EXPANDED_COUNTRY_TABLE: readonly (readonly string[])[] = + expandedCountries!; +/** REGION_TABLE with the derived "and"-less spellings added to each row. */ +export const EXPANDED_REGION_TABLE: readonly (readonly string[])[] = + expandedRegions!; + const COUNTRY_BY_ALIAS = new Map(); -for (const row of COUNTRY_TABLE) { +for (const row of EXPANDED_COUNTRY_TABLE) { for (const alias of row) COUNTRY_BY_ALIAS.set(alias, row[0]!); } @@ -264,7 +317,10 @@ interface Matcher { // Longest first (more words, then more characters) so a shorter alias cannot // match inside a longer one, such as "guinea" inside "papua new guinea". -const MATCHERS: readonly Matcher[] = [...COUNTRY_TABLE, ...REGION_TABLE] +const MATCHERS: readonly Matcher[] = [ + ...EXPANDED_COUNTRY_TABLE, + ...EXPANDED_REGION_TABLE, +] .flatMap((row) => row.map((alias) => ({ words: alias.split(' '), @@ -276,7 +332,10 @@ const MATCHERS: readonly Matcher[] = [...COUNTRY_TABLE, ...REGION_TABLE] /** Reads a My details value as a country. The whole text must be one name. */ export function countryOf(text: string): string | undefined { - return COUNTRY_BY_ALIAS.get(normalizeLabel(text)); + const name = normalizeLabel(text); + const direct = COUNTRY_BY_ALIAS.get(name); + if (direct !== undefined || !name.startsWith('the ')) return direct; + return COUNTRY_BY_ALIAS.get(name.slice(4)); } /** From 3e742570e08ccb332bc17663a56a3bbe025cbb20 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:30:01 -0600 Subject: [PATCH 09/48] Add the fill recognition tables --- core/src/fill/recognise.test.ts | 141 ++++++++++++++++++++++++++++++++ core/src/fill/recognise.ts | 35 ++++++++ core/src/fill/tables.ts | 98 ++++++++++++++++++++++ 3 files changed, 274 insertions(+) create mode 100644 core/src/fill/recognise.test.ts create mode 100644 core/src/fill/recognise.ts create mode 100644 core/src/fill/tables.ts diff --git a/core/src/fill/recognise.test.ts b/core/src/fill/recognise.test.ts new file mode 100644 index 0000000..716b69d --- /dev/null +++ b/core/src/fill/recognise.test.ts @@ -0,0 +1,141 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_ANSWERS } from '../answers'; +import { PROFILE_FIELDS, type ProfileKey } from '../profile'; +import { normalizeLabel } from './normalize'; +import { recogniseAnswers, recogniseProfile } from './recognise'; +import { DEFAULT_TABLES } from './tables'; + +const profile = (label: string, autocomplete = '') => + recogniseProfile({ label, autocomplete }, DEFAULT_TABLES); +const answers = (label: string) => recogniseAnswers({ label }, DEFAULT_TABLES); + +describe('DEFAULT_TABLES', () => { + it('has exactly the 14 profile keys', () => { + expect([...DEFAULT_TABLES.profilePhrases.keys()].sort()).toEqual( + PROFILE_FIELDS.map((f) => f.key).sort(), + ); + }); + + it('lists the answer keys in the order of DEFAULT_ANSWERS', () => { + expect([...DEFAULT_TABLES.answerPhrases.keys()]).toEqual( + DEFAULT_ANSWERS.map((a) => a.key), + ); + }); + + it('stores every phrase in normalised form', () => { + const all = [ + ...[...DEFAULT_TABLES.profilePhrases.values()].flat(), + ...[...DEFAULT_TABLES.answerPhrases.values()].flat(), + ]; + expect(all.length).toBeGreaterThan(0); + for (const phrase of all) expect(normalizeLabel(phrase)).toBe(phrase); + }); + + it('has no phrase under two profile keys', () => { + const all = [...DEFAULT_TABLES.profilePhrases.values()].flat(); + expect(new Set(all).size).toBe(all.length); + }); + + it('maps each autocomplete token to one key', () => { + const keys = [...DEFAULT_TABLES.profileAutocomplete.keys()]; + expect(new Set(keys).size).toBe(keys.length); + }); +}); + +describe('recogniseProfile', () => { + it.each<[ProfileKey, string, string, ProfileKey | undefined]>([ + ['full_name', 'Full name', 'Company name', undefined], + ['first_name', 'First Name *', 'First name of referee', undefined], + ['last_name', 'Surname', 'Maiden surname', undefined], + ['email', 'Email address', 'Reference email', undefined], + ['phone', 'Mobile number', 'Emergency phone', undefined], + ['address_line1', 'Street address', 'Email address', 'email'], + ['address_line2', 'Address line 2', 'Address line 3', undefined], + ['city', 'City', 'City of birth', undefined], + ['region', 'State or province', 'State of mind', undefined], + ['postal_code', 'ZIP code', 'Area code', undefined], + ['country', 'Country', 'Country of birth', undefined], + ['linkedin', 'LinkedIn URL', 'LinkedIn headline', undefined], + ['github', 'GitHub profile', 'GitHub stars', undefined], + ['website', 'Portfolio URL', 'Website feedback', undefined], + ])('%s has a match and a near miss', (key, match, nearMiss, nearResult) => { + expect(profile(match)).toBe(key); + expect(profile(nearMiss)).toBe(nearResult); + }); + + it('lets autocomplete beat the label', () => { + expect(profile('Reference email', 'email')).toBe('email'); + expect(profile('Email', 'family-name')).toBe('last_name'); + expect(profile('Email', 'off')).toBe('email'); + }); + + it('gives undefined for an empty label with no known token', () => { + expect(profile('')).toBeUndefined(); + expect(profile('', 'organization')).toBeUndefined(); + }); + + it.each<[string, ProfileKey]>([ + ['name', 'full_name'], + ['given-name', 'first_name'], + ['family-name', 'last_name'], + ['email', 'email'], + ['tel', 'phone'], + ['tel-national', 'phone'], + ['address-line1', 'address_line1'], + ['address-line2', 'address_line2'], + ['address-level2', 'city'], + ['address-level1', 'region'], + ['postal-code', 'postal_code'], + ['country-name', 'country'], + ])('maps the autocomplete token %s to %s', (token, key) => { + expect(profile('', token)).toBe(key); + }); + + it('does not recognise prototype names', () => { + for (const token of ['constructor', '__proto__', 'toString']) { + expect(profile('', token)).toBeUndefined(); + } + for (const label of ['constructor', 'hasOwnProperty']) { + expect(profile(label)).toBeUndefined(); + expect(answers(label)).toEqual([]); + } + }); +}); + +describe('recogniseAnswers', () => { + it.each<[string, string[]]>([ + [ + 'Are you legally authorized to work in the United States?', + ['work_authorization'], + ], + [ + 'Will you now or in the future require sponsorship for employment visa status?', + ['sponsorship'], + ], + ['Are you willing to relocate?', ['relocation']], + ['When can you start?', ['earliest_start_date']], + ['Reason for leaving your last role', ['reason_for_leaving']], + ['Desired salary', ['salary_range']], + ])('matches %s', (question, expected) => { + expect(answers(question)).toEqual(expected); + }); + + it('returns both answers of a two-answer question, in table order', () => { + expect( + answers('Are you authorized to work without visa sponsorship?'), + ).toEqual(['work_authorization', 'sponsorship']); + expect( + answers('Visa sponsorship: are you authorized to work here?'), + ).toEqual(['work_authorization', 'sponsorship']); + }); + + it('returns each key once when several phrases match', () => { + expect( + answers('Authorized to work? Eligible to work? Right to work?'), + ).toEqual(['work_authorization']); + }); + + it('returns nothing when no phrase matches', () => { + expect(answers('Why do you want to work here?')).toEqual([]); + }); +}); diff --git a/core/src/fill/recognise.ts b/core/src/fill/recognise.ts new file mode 100644 index 0000000..9eafd9f --- /dev/null +++ b/core/src/fill/recognise.ts @@ -0,0 +1,35 @@ +import type { ProfileKey } from '../profile'; +import { containsPhrase, normalizeLabel } from './normalize'; +import type { RecognitionTables } from './tables'; +import type { ScannedField } from './types'; + +/** + * The profile key a field means, or undefined. A known autocomplete token + * decides; an unknown token is ignored and the label must equal a phrase. + */ +export function recogniseProfile( + field: Pick, + tables: RecognitionTables, +): ProfileKey | undefined { + const byToken = tables.profileAutocomplete.get(field.autocomplete); + if (byToken !== undefined) return byToken; + const label = normalizeLabel(field.label); + if (label === '') return undefined; + for (const [key, phrases] of tables.profilePhrases) { + if (phrases.includes(label)) return key; + } + return undefined; +} + +/** Every answer key whose phrase the label contains as whole words, once each, in table order. */ +export function recogniseAnswers( + field: Pick, + tables: RecognitionTables, +): string[] { + const label = normalizeLabel(field.label); + const keys: string[] = []; + for (const [key, phrases] of tables.answerPhrases) { + if (phrases.some((phrase) => containsPhrase(label, phrase))) keys.push(key); + } + return keys; +} diff --git a/core/src/fill/tables.ts b/core/src/fill/tables.ts new file mode 100644 index 0000000..8912226 --- /dev/null +++ b/core/src/fill/tables.ts @@ -0,0 +1,98 @@ +import type { ProfileKey } from '../profile'; + +export interface RecognitionTables { + profileAutocomplete: ReadonlyMap; + profilePhrases: ReadonlyMap; + /** Answer key to phrases, in the order of DEFAULT_ANSWERS. */ + answerPhrases: ReadonlyMap; +} + +/** Phrases are stored in the form normalizeLabel produces. */ +export const DEFAULT_TABLES: RecognitionTables = { + profileAutocomplete: new Map([ + ['name', 'full_name'], + ['given-name', 'first_name'], + ['family-name', 'last_name'], + ['email', 'email'], + ['tel', 'phone'], + ['tel-national', 'phone'], + ['address-line1', 'address_line1'], + ['address-line2', 'address_line2'], + ['address-level2', 'city'], + ['address-level1', 'region'], + ['postal-code', 'postal_code'], + ['country-name', 'country'], + ]), + profilePhrases: new Map([ + ['full_name', ['name', 'full name', 'your name', 'legal name']], + ['first_name', ['first name', 'given name']], + ['last_name', ['last name', 'surname', 'family name']], + ['email', ['email', 'email address', 'e mail']], + [ + 'phone', + ['phone', 'phone number', 'mobile', 'mobile number', 'telephone'], + ], + ['address_line1', ['address', 'street address', 'address line 1']], + ['address_line2', ['address line 2']], + ['city', ['city']], + ['region', ['state', 'province', 'region', 'state or province']], + ['postal_code', ['zip', 'zip code', 'postal code', 'postcode']], + ['country', ['country']], + ['linkedin', ['linkedin', 'linkedin url', 'linkedin profile']], + ['github', ['github', 'github url', 'github profile']], + [ + 'website', + [ + 'website', + 'personal website', + 'portfolio', + 'portfolio url', + 'other website', + 'other website url', + ], + ], + ]), + answerPhrases: new Map([ + [ + 'work_authorization', + [ + 'authorized to work', + 'authorised to work', + 'eligible to work', + 'legally authorized', + 'legally authorised', + 'right to work', + ], + ], + [ + 'sponsorship', + [ + 'require sponsorship', + 'need sponsorship', + 'visa sponsorship', + 'sponsorship for employment', + 'immigration sponsorship', + ], + ], + ['salary_range', ['salary', 'compensation', 'expected pay', 'desired pay']], + [ + 'earliest_start_date', + [ + 'start date', + 'available to start', + 'when can you start', + 'earliest start', + ], + ], + [ + 'relocation', + [ + 'willing to relocate', + 'open to relocating', + 'open to relocation', + 'able to relocate', + ], + ], + ['reason_for_leaving', ['reason for leaving', 'why are you leaving']], + ]), +}; From 4534d615717a0b7602132f24f2ff6d4e45887e62 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:31:48 -0600 Subject: [PATCH 10/48] Add site type and frame advice for fills --- core/src/fill/site.test.ts | 81 ++++++++++++++++++++++++++++++++++++++ core/src/fill/site.ts | 76 +++++++++++++++++++++++++++++++++++ 2 files changed, 157 insertions(+) create mode 100644 core/src/fill/site.test.ts create mode 100644 core/src/fill/site.ts diff --git a/core/src/fill/site.test.ts b/core/src/fill/site.test.ts new file mode 100644 index 0000000..279a95a --- /dev/null +++ b/core/src/fill/site.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest'; +import { FRAME_HOSTS, frameAdvice, siteTypeForUrl } from './site'; + +describe('FRAME_HOSTS', () => { + it('maps the Greenhouse and Ashby embed hosts', () => { + expect(FRAME_HOSTS.size).toBe(3); + expect(FRAME_HOSTS.get('job-boards.greenhouse.io')).toBe('greenhouse'); + expect(FRAME_HOSTS.get('boards.greenhouse.io')).toBe('greenhouse'); + expect(FRAME_HOSTS.get('jobs.ashbyhq.com')).toBe('ashby'); + }); +}); + +describe('siteTypeForUrl', () => { + it.each([ + ['https://job-boards.greenhouse.io/exampleco/jobs/1', 'greenhouse'], + ['https://jobs.lever.co/exampleco/abc/apply', 'lever'], + ['https://jobs.ashbyhq.com/exampleco/abc/application', 'ashby'], + ['https://exampleco.wd5.myworkdayjobs.com/x', 'workday'], + ['https://www.linkedin.com/jobs/view/1', 'linkedin'], + ['https://uk.indeed.com/viewjob', 'indeed'], + ['https://example.com/careers', 'other'], + ['https://evil-greenhouse.io/', 'other'], + ['https://greenhouse.io.example.com/', 'other'], + ['not a url', 'other'], + ['', 'other'], + ['about:addons', 'other'], + ['ftp://jobs.lever.co/x', 'other'], + ['HTTPS://JOBS.LEVER.CO/x', 'lever'], + ['https://lever.co/', 'lever'], + ])('siteTypeForUrl(%j) is %s', (url, expected) => { + expect(siteTypeForUrl(url)).toBe(expected); + }); +}); + +describe('frameAdvice', () => { + it('returns one greenhouse entry with the original src', () => { + const src = + 'https://job-boards.greenhouse.io/embed/job_app?for=exampleco&token=1'; + expect(frameAdvice(['https://example.com/video', src])).toEqual([ + { site: 'greenhouse', src }, + ]); + }); + + it('returns an ashby entry for an Ashby frame', () => { + const src = 'https://jobs.ashbyhq.com/exampleco'; + expect(frameAdvice([src])).toEqual([{ site: 'ashby', src }]); + }); + + it('keeps only the first frame for a site', () => { + const first = 'https://boards.greenhouse.io/embed/a'; + const second = 'https://job-boards.greenhouse.io/embed/b'; + expect(frameAdvice([first, second])).toEqual([ + { site: 'greenhouse', src: first }, + ]); + }); + + it('puts greenhouse before ashby whatever the order', () => { + const ashby = 'https://jobs.ashbyhq.com/exampleco'; + const greenhouse = 'https://boards.greenhouse.io/embed/a'; + expect(frameAdvice([ashby, greenhouse])).toEqual([ + { site: 'greenhouse', src: greenhouse }, + { site: 'ashby', src: ashby }, + ]); + }); + + it('ignores frames that do not parse', () => { + expect(frameAdvice(['nonsense'])).toEqual([]); + }); + + it('ignores a look-alike host', () => { + expect(frameAdvice(['https://jobs.ashbyhq.com.example.com/x'])).toEqual([]); + }); + + it('ignores non-https frames', () => { + expect(frameAdvice(['http://jobs.ashbyhq.com/exampleco'])).toEqual([]); + }); + + it('returns an empty list for no frames', () => { + expect(frameAdvice([])).toEqual([]); + }); +}); diff --git a/core/src/fill/site.ts b/core/src/fill/site.ts new file mode 100644 index 0000000..c4fdd6f --- /dev/null +++ b/core/src/fill/site.ts @@ -0,0 +1,76 @@ +import type { SiteType } from '../formhand'; +import type { FrameAdvice } from './types'; + +// core/ declares no URL global (lib ES2023, types []), so declare the subset used here. +interface UrlLike { + protocol: string; + hostname: string; +} +declare const URL: { new (url: string): UrlLike }; + +export const FRAME_HOSTS: ReadonlyMap = new Map< + string, + 'greenhouse' | 'ashby' +>([ + ['job-boards.greenhouse.io', 'greenhouse'], + ['boards.greenhouse.io', 'greenhouse'], + ['jobs.ashbyhq.com', 'ashby'], +]); + +const SITE_SUFFIXES: ReadonlyArray = [ + ['greenhouse.io', 'greenhouse'], + ['lever.co', 'lever'], + ['ashbyhq.com', 'ashby'], + ['myworkdayjobs.com', 'workday'], + ['workday.com', 'workday'], + ['linkedin.com', 'linkedin'], + ['indeed.com', 'indeed'], +]; + +function parseUrl(input: string): UrlLike | undefined { + try { + return new URL(input); + } catch { + return undefined; + } +} + +export function siteTypeForUrl(url: string): SiteType { + const parsed = parseUrl(url); + if ( + !parsed || + (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') + ) { + return 'other'; + } + const host = parsed.hostname.toLowerCase(); + for (const [suffix, site] of SITE_SUFFIXES) { + if (host === suffix || host.endsWith('.' + suffix)) { + return site; + } + } + return 'other'; +} + +export function frameAdvice(frames: readonly string[]): FrameAdvice[] { + const taken = new Map<'greenhouse' | 'ashby', string>(); + for (const src of frames) { + const parsed = parseUrl(src); + if (!parsed || parsed.protocol !== 'https:') { + continue; + } + const site = FRAME_HOSTS.get(parsed.hostname.toLowerCase()); + if (site === undefined || taken.has(site)) { + continue; + } + taken.set(site, src); + } + const advice: FrameAdvice[] = []; + for (const site of ['greenhouse', 'ashby'] as const) { + const src = taken.get(site); + if (src !== undefined) { + advice.push({ site, src }); + } + } + return advice; +} From b865e612486597bba3d6d614043d31e118955426 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:33:15 -0600 Subject: [PATCH 11/48] Pin the fill recognition tables in tests --- core/src/fill/recognise.test.ts | 100 +++++++++++++++++++++++++++++++- 1 file changed, 97 insertions(+), 3 deletions(-) diff --git a/core/src/fill/recognise.test.ts b/core/src/fill/recognise.test.ts index 716b69d..d1b38a5 100644 --- a/core/src/fill/recognise.test.ts +++ b/core/src/fill/recognise.test.ts @@ -36,9 +36,103 @@ describe('DEFAULT_TABLES', () => { expect(new Set(all).size).toBe(all.length); }); - it('maps each autocomplete token to one key', () => { - const keys = [...DEFAULT_TABLES.profileAutocomplete.keys()]; - expect(new Set(keys).size).toBe(keys.length); + it('pins the autocomplete table to the design', () => { + expect(DEFAULT_TABLES.profileAutocomplete.size).toBe(12); + expect([...DEFAULT_TABLES.profileAutocomplete]).toEqual([ + ['name', 'full_name'], + ['given-name', 'first_name'], + ['family-name', 'last_name'], + ['email', 'email'], + ['tel', 'phone'], + ['tel-national', 'phone'], + ['address-line1', 'address_line1'], + ['address-line2', 'address_line2'], + ['address-level2', 'city'], + ['address-level1', 'region'], + ['postal-code', 'postal_code'], + ['country-name', 'country'], + ]); + }); + + it('pins the profile label phrases to the design', () => { + expect([...DEFAULT_TABLES.profilePhrases]).toEqual([ + ['full_name', ['name', 'full name', 'your name', 'legal name']], + ['first_name', ['first name', 'given name']], + ['last_name', ['last name', 'surname', 'family name']], + ['email', ['email', 'email address', 'e mail']], + [ + 'phone', + ['phone', 'phone number', 'mobile', 'mobile number', 'telephone'], + ], + ['address_line1', ['address', 'street address', 'address line 1']], + ['address_line2', ['address line 2']], + ['city', ['city']], + ['region', ['state', 'province', 'region', 'state or province']], + ['postal_code', ['zip', 'zip code', 'postal code', 'postcode']], + ['country', ['country']], + ['linkedin', ['linkedin', 'linkedin url', 'linkedin profile']], + ['github', ['github', 'github url', 'github profile']], + [ + 'website', + [ + 'website', + 'personal website', + 'portfolio', + 'portfolio url', + 'other website', + 'other website url', + ], + ], + ]); + }); + + it('pins the answer phrases to the design', () => { + expect([...DEFAULT_TABLES.answerPhrases]).toEqual([ + [ + 'work_authorization', + [ + 'authorized to work', + 'authorised to work', + 'eligible to work', + 'legally authorized', + 'legally authorised', + 'right to work', + ], + ], + [ + 'sponsorship', + [ + 'require sponsorship', + 'need sponsorship', + 'visa sponsorship', + 'sponsorship for employment', + 'immigration sponsorship', + ], + ], + [ + 'salary_range', + ['salary', 'compensation', 'expected pay', 'desired pay'], + ], + [ + 'earliest_start_date', + [ + 'start date', + 'available to start', + 'when can you start', + 'earliest start', + ], + ], + [ + 'relocation', + [ + 'willing to relocate', + 'open to relocating', + 'open to relocation', + 'able to relocate', + ], + ], + ['reason_for_leaving', ['reason for leaving', 'why are you leaving']], + ]); }); }); From 1a0d2260a40e623f70f4a36dbf82eed68a882ffd Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:35:14 -0600 Subject: [PATCH 12/48] Add control fit for the fill plan --- core/src/fill/fit.test.ts | 299 ++++++++++++++++++++++++++++++++++++++ core/src/fill/fit.ts | 105 +++++++++++++ 2 files changed, 404 insertions(+) create mode 100644 core/src/fill/fit.test.ts create mode 100644 core/src/fill/fit.ts diff --git a/core/src/fill/fit.test.ts b/core/src/fill/fit.test.ts new file mode 100644 index 0000000..81671c2 --- /dev/null +++ b/core/src/fill/fit.test.ts @@ -0,0 +1,299 @@ +import { describe, expect, it } from 'vitest'; +import { fitField, type OwnKind } from './fit'; +import type { ScannedField } from './types'; + +function field(overrides: Partial = {}): ScannedField { + return { + ref: 3, + control: 'text', + label: '', + autocomplete: '', + required: false, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + ...overrides, + }; +} + +const UNSUPPORTED = { fit: 'none', reason: 'unsupported_control' }; + +function select(options: string[], overrides: Partial = {}) { + return field({ control: 'select', options, ...overrides }); +} + +function group(options: string[], overrides: Partial = {}) { + return field({ control: 'choice_group', options, ...overrides }); +} + +describe('fitField: text', () => { + it.each(['text', 'textarea'] as const)('writes into %s', (control) => { + expect(fitField(field({ control }), 'text', 'Acme')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'value', value: 'Acme' }, + }); + }); + + it.each([field({ control: 'date' }), select(['Acme']), group(['Acme'])])( + 'does not fit $control', + (f) => { + expect(fitField(f, 'text', 'Acme')).toEqual(UNSUPPORTED); + }, + ); +}); + +describe('fitField: place', () => { + it('writes a value into a text control', () => { + expect(fitField(field(), 'place', 'Canada')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'value', value: 'Canada' }, + }); + }); + + it('picks the matching option in a select', () => { + expect( + fitField(select(['Canada', 'United States']), 'place', 'united states'), + ).toEqual({ fit: 'write', write: { ref: 3, kind: 'option', index: 1 } }); + }); + + it('is unsupported with no equal option', () => { + expect(fitField(select(['Canada', 'Mexico']), 'place', 'France')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported with two equal options', () => { + expect(fitField(select(['Canada', ' canada ']), 'place', 'Canada')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported for a multi-select', () => { + expect( + fitField(select(['Canada'], { multiple: true }), 'place', 'Canada'), + ).toEqual(UNSUPPORTED); + }); + + it('is unsupported for a choice group', () => { + expect(fitField(group(['Canada']), 'place', 'Canada')).toEqual(UNSUPPORTED); + }); +}); + +describe('fitField: yes_no', () => { + it('picks No in a Yes/No select', () => { + expect(fitField(select(['Yes', 'No']), 'yes_no', 'No')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'option', index: 1 }, + }); + }); + + it('picks Yes in a No/Yes select', () => { + expect(fitField(select(['No', 'Yes']), 'yes_no', 'Yes')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'option', index: 1 }, + }); + }); + + it('matches option text case-insensitively', () => { + expect(fitField(select(['yes', 'NO']), 'yes_no', 'No')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'option', index: 1 }, + }); + }); + + it('is unsupported with a third option', () => { + expect(fitField(select(['Yes', 'No', 'Maybe']), 'yes_no', 'Yes')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported with two Yes options', () => { + expect(fitField(select(['Yes', 'Yes']), 'yes_no', 'Yes')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported for a multi-select', () => { + expect( + fitField(select(['Yes', 'No'], { multiple: true }), 'yes_no', 'Yes'), + ).toEqual(UNSUPPORTED); + }); + + it('writes into a radio group', () => { + expect(fitField(group(['Yes', 'No']), 'yes_no', 'Yes')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'option', index: 0 }, + }); + }); + + it('writes into an empty checkbox pair', () => { + expect( + fitField(group(['Yes', 'No'], { multiple: true }), 'yes_no', 'No'), + ).toEqual({ fit: 'write', write: { ref: 3, kind: 'option', index: 1 } }); + }); + + it('holds when one checkbox is checked', () => { + expect( + fitField( + group(['Yes', 'No'], { multiple: true, checked: [0] }), + 'yes_no', + 'No', + ), + ).toEqual({ fit: 'holds', formValue: 'Yes' }); + }); + + it('holds with both checkboxes checked', () => { + expect( + fitField( + group(['Yes', 'No'], { multiple: true, checked: [0, 1] }), + 'yes_no', + 'No', + ), + ).toEqual({ fit: 'holds', formValue: 'Yes, No' }); + }); + + it('holds a radio group that arrives with several checked', () => { + expect( + fitField(group(['Yes', 'No'], { checked: [0, 1] }), 'yes_no', 'No'), + ).toEqual({ fit: 'holds', formValue: 'Yes, No' }); + }); + + it('is unsupported for a text control', () => { + expect(fitField(field(), 'yes_no', 'Yes')).toEqual(UNSUPPORTED); + }); +}); + +describe('fitField: choice', () => { + it('picks the matching option', () => { + expect( + fitField( + select(['Yes', 'No', 'Depends on location']), + 'choice', + 'Depends on location', + ), + ).toEqual({ fit: 'write', write: { ref: 3, kind: 'option', index: 2 } }); + }); + + it('is unsupported with no equal option', () => { + expect(fitField(select(['Yes', 'No']), 'choice', 'Maybe')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported when two options equal own', () => { + expect( + fitField(select(['Other', 'other', 'Mine']), 'choice', 'Other'), + ).toEqual(UNSUPPORTED); + }); + + it('writes into a checkbox group with one matching option', () => { + expect( + fitField(group(['Red', 'Blue'], { multiple: true }), 'choice', 'Blue'), + ).toEqual({ fit: 'write', write: { ref: 3, kind: 'option', index: 1 } }); + }); + + it('is unsupported for a multi-select', () => { + expect( + fitField(select(['Red'], { multiple: true }), 'choice', 'Red'), + ).toEqual(UNSUPPORTED); + }); + + it('is unsupported for a text control', () => { + expect(fitField(field(), 'choice', 'Red')).toEqual(UNSUPPORTED); + }); +}); + +describe('fitField: date', () => { + it('writes into a date control', () => { + expect(fitField(field({ control: 'date' }), 'date', '2026-12-01')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'value', value: '2026-12-01' }, + }); + }); + + it('is unsupported for a text control', () => { + expect(fitField(field(), 'date', '2026-12-01')).toEqual(UNSUPPORTED); + }); +}); + +describe('fitField: custom and file', () => { + it.each(['text', 'place', 'yes_no', 'choice', 'date'] as OwnKind[])( + 'reports custom_control for %s', + (kind) => { + expect(fitField(field({ control: 'custom' }), kind, 'x')).toEqual({ + fit: 'none', + reason: 'custom_control', + }); + }, + ); + + it.each(['text', 'place', 'yes_no', 'choice', 'date'] as OwnKind[])( + 'reports unsupported_control for a file with %s', + (kind) => { + expect(fitField(field({ control: 'file' }), kind, 'x')).toEqual( + UNSUPPORTED, + ); + }, + ); +}); + +describe('fitField: holds', () => { + it('holds a text value', () => { + expect(fitField(field({ value: 'x' }), 'text', 'Acme')).toEqual({ + fit: 'holds', + formValue: 'x', + }); + }); + + it('holds a select value', () => { + expect( + fitField(select(['Yes', 'No'], { value: 'Yes' }), 'yes_no', 'No'), + ).toEqual({ fit: 'holds', formValue: 'Yes' }); + }); + + it('holds a select value even when no option equals own', () => { + expect( + fitField(select(['Red', 'Blue'], { value: 'Red' }), 'choice', 'Green'), + ).toEqual({ fit: 'holds', formValue: 'Red' }); + }); + + it('holds a date value', () => { + expect( + fitField( + field({ control: 'date', value: '2026-01-01' }), + 'date', + '2026-12-01', + ), + ).toEqual({ fit: 'holds', formValue: '2026-01-01' }); + }); +}); + +describe('fitField: truncated option lists', () => { + it('never picks from a truncated list', () => { + expect( + fitField( + select(['Canada', 'United States'], { optionsTruncated: true }), + 'place', + 'Canada', + ), + ).toEqual(UNSUPPORTED); + }); + + it('checks truncation before what the control holds', () => { + expect( + fitField( + select(['Canada'], { optionsTruncated: true, value: 'Canada' }), + 'place', + 'Canada', + ), + ).toEqual(UNSUPPORTED); + }); + + it('is unsupported for a truncated group', () => { + expect( + fitField(group(['Red'], { optionsTruncated: true }), 'choice', 'Red'), + ).toEqual(UNSUPPORTED); + }); +}); diff --git a/core/src/fill/fit.ts b/core/src/fill/fit.ts new file mode 100644 index 0000000..cf979d1 --- /dev/null +++ b/core/src/fill/fit.ts @@ -0,0 +1,105 @@ +import { sameText } from './compare'; +import type { FillWrite, ScannedField } from './types'; + +export type OwnKind = 'text' | 'place' | 'yes_no' | 'choice' | 'date'; + +export type FitResult = + | { fit: 'write'; write: FillWrite } + | { fit: 'holds'; formValue: string } + | { fit: 'none'; reason: 'custom_control' | 'unsupported_control' }; + +const UNSUPPORTED: FitResult = { fit: 'none', reason: 'unsupported_control' }; + +function isYesNo(options: string[]): boolean { + if (options.length !== 2) return false; + const [a, b] = options as [string, string]; + return ( + (sameText(a, 'Yes') && sameText(b, 'No')) || + (sameText(a, 'No') && sameText(b, 'Yes')) + ); +} + +function controlFits(field: ScannedField, kind: OwnKind): boolean { + const isSelect = field.control === 'select'; + const isGroup = field.control === 'choice_group'; + switch (kind) { + case 'text': + return field.control === 'text' || field.control === 'textarea'; + case 'place': + return ( + field.control === 'text' || + field.control === 'textarea' || + (isSelect && !field.multiple) + ); + case 'yes_no': + return ( + ((isSelect && !field.multiple) || isGroup) && isYesNo(field.options) + ); + case 'choice': + return (isSelect && !field.multiple) || isGroup; + case 'date': + return field.control === 'date'; + default: { + const unreachable: never = kind; + return unreachable; + } + } +} + +/** + * Decides whether one saved value can be written into one scanned control. + * Any doubt comes out as "holds" or "none", never as "write". + */ +export function fitField( + field: ScannedField, + kind: OwnKind, + own: string, +): FitResult { + // 1. Controls the filler never touches. + if (field.control === 'custom') { + return { fit: 'none', reason: 'custom_control' }; + } + if (field.control === 'file') return UNSUPPORTED; + + // 2. Does the control fit the kind. + if (!controlFits(field, kind)) return UNSUPPORTED; + + const isList = field.control === 'select' || field.control === 'choice_group'; + + // 3. A truncated option list cannot be trusted. + if (isList && field.optionsTruncated) return UNSUPPORTED; + + // 4. Never replace what is already there. + if (field.control === 'choice_group') { + if (field.checked.length > 0) { + const formValue = field.checked + .map((i) => field.options[i] ?? '') + .join(', '); + return { fit: 'holds', formValue }; + } + } else if (field.value !== '') { + return { fit: 'holds', formValue: field.value }; + } + + // 5. Pick the one matching option. + if (isList) { + let found = -1; + for (let i = 0; i < field.options.length; i++) { + if (sameText(field.options[i] ?? '', own)) { + if (found !== -1) return UNSUPPORTED; + found = i; + } + } + if (found === -1) return UNSUPPORTED; + return { + fit: 'write', + write: { ref: field.ref, kind: 'option', index: found }, + }; + } + + // 6. Plain value write. + return { + fit: 'write', + write: { ref: field.ref, kind: 'value', value: own }, + }; +} From ab0a1a28108fcdc07f72d3b5f5c0c319f13fc45c Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:46:38 -0600 Subject: [PATCH 13/48] Add the fill plan --- core/src/fill/plan.test.ts | 663 +++++++++++++++++++++++++++++++++++++ core/src/fill/plan.ts | 355 ++++++++++++++++++++ 2 files changed, 1018 insertions(+) create mode 100644 core/src/fill/plan.test.ts create mode 100644 core/src/fill/plan.ts diff --git a/core/src/fill/plan.test.ts b/core/src/fill/plan.test.ts new file mode 100644 index 0000000..5c1ccb3 --- /dev/null +++ b/core/src/fill/plan.test.ts @@ -0,0 +1,663 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_ANSWERS, formatAnswer } from '../answers'; +import type { ProfileKey } from '../profile'; +import type { AnswerValue, CanonicalAnswer } from '../types'; +import { buildPlan } from './plan'; +import { DEFAULT_TABLES, type RecognitionTables } from './tables'; +import type { FormScan, PlanInput, ScannedField } from './types'; + +let nextRef = 0; + +function field(overrides: Partial = {}): ScannedField { + nextRef += 1; + return { + ref: nextRef, + control: 'text', + label: '', + autocomplete: '', + required: false, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + ...overrides, + }; +} + +function scanOf(fields: ScannedField[], frames: string[] = []): FormScan { + return { fields, frames, truncated: false }; +} + +function answer(key: string, value: unknown): CanonicalAnswer { + const def = DEFAULT_ANSWERS.find((d) => d.key === key); + return { + id: `id-${key}`, + createdAt: '2026-11-20T00:00:00.000Z', + key, + label: def?.label ?? key, + type: def?.type, + value: value as AnswerValue, + }; +} + +const SALARY: AnswerValue = { + type: 'money_range', + min: 100000, + max: 120000, + currency: 'USD', + period: 'year', +}; + +const SAM_PROFILE: Record = { + full_name: 'Sam Example', + first_name: 'Sam', + last_name: 'Example', + email: 'sam@example.com', + phone: '555-010-0142', + address_line1: '12 Example Street', + address_line2: 'Unit 4', + city: 'Springfield', + region: 'Example State', + postal_code: '00000', + country: 'United States', + linkedin: 'https://example.com/in/sam', + github: 'https://example.com/sam', + website: 'https://example.com', +}; + +const SAM_ANSWERS: CanonicalAnswer[] = [ + answer('work_authorization', { type: 'yes_no', value: true }), + answer('sponsorship', { type: 'yes_no', value: false }), + answer('salary_range', SALARY), + answer('earliest_start_date', { type: 'date', value: '2026-12-01' }), + answer('relocation', { type: 'choice', value: 'Depends on location' }), + answer('reason_for_leaving', { + type: 'text', + value: 'Looking for a new challenge', + }), +]; + +const sam: PlanInput = { profile: { ...SAM_PROFILE }, answers: SAM_ANSWERS }; + +function withProfile(changes: Partial>): PlanInput { + return { profile: { ...SAM_PROFILE, ...changes }, answers: SAM_ANSWERS }; +} + +function withAnswers(answers: CanonicalAnswer[]): PlanInput { + return { profile: { ...SAM_PROFILE }, answers }; +} + +function yesNoSelect(label: string, overrides: Partial = {}) { + return field({ + control: 'select', + label, + options: ['Yes', 'No'], + ...overrides, + }); +} + +function expectNoBadWrites(plan: ReturnType): void { + for (const w of plan.writes) { + if (w.kind === 'value') { + expect(w.value).not.toBe('undefined'); + expect(w.value).not.toContain('[object'); + } + } +} + +const AUTH = 'Are you legally authorized to work'; + +describe('buildPlan: profile fields', () => { + it('fills an empty contact block', () => { + const fields = ['First name', 'Last name', 'Email', 'Phone'].map((label) => + field({ label }), + ); + const plan = buildPlan(scanOf(fields), sam); + expect(plan.rows.map((r) => r.status)).toEqual([ + 'will_fill', + 'will_fill', + 'will_fill', + 'will_fill', + ]); + expect(plan.writes).toEqual([ + { ref: fields[0]!.ref, kind: 'value', value: 'Sam' }, + { ref: fields[1]!.ref, kind: 'value', value: 'Example' }, + { ref: fields[2]!.ref, kind: 'value', value: 'sam@example.com' }, + { ref: fields[3]!.ref, kind: 'value', value: '555-010-0142' }, + ]); + }); + + it('matches, case and format aside', () => { + const email = field({ label: 'Email', value: 'SAM@example.com' }); + const phone = field({ label: 'Phone', value: '+1 555 010 0142' }); + const plan = buildPlan(scanOf([email, phone]), sam); + expect(plan.rows.map((r) => r.status)).toEqual(['matches', 'matches']); + expect(plan.writes).toEqual([]); + }); + + it('never replaces a value', () => { + const email = field({ label: 'Email', value: 'other@example.com' }); + const plan = buildPlan(scanOf([email]), sam); + expect(plan.rows[0]).toMatchObject({ + status: 'differs', + formValue: 'other@example.com', + ownValue: 'sam@example.com', + }); + expect(plan.rows[0]!.write).toBeUndefined(); + expect(plan.writes).toEqual([]); + }); + + it('reports no value when the profile lacks the key', () => { + const input = withProfile({ first_name: ' ' }); + const plan = buildPlan(scanOf([field({ label: 'First name' })]), input); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'no_value', + ownValue: '', + }); + const missing: PlanInput = { profile: {}, answers: [] }; + const again = buildPlan(scanOf([field({ label: 'First name' })]), missing); + expect(again.rows[0]!.reason).toBe('no_value'); + }); + + it('marks duplicated profile fields ambiguous and keeps the owner value', () => { + const fields = [ + field({ label: 'Name' }), + field({ label: 'Email' }), + field({ label: 'Name' }), + field({ label: 'Email' }), + ]; + const plan = buildPlan(scanOf(fields), sam); + expect(plan.rows.map((r) => r.reason)).toEqual([ + 'ambiguous', + 'ambiguous', + 'ambiguous', + 'ambiguous', + ]); + expect(plan.rows.map((r) => r.ownValue)).toEqual([ + 'Sam Example', + 'sam@example.com', + 'Sam Example', + 'sam@example.com', + ]); + expect(plan.writes).toEqual([]); + }); + + it('puts a country into a select and a text field', () => { + const select = field({ + control: 'select', + label: 'Country', + options: ['Canada', 'United States'], + }); + const plan = buildPlan(scanOf([select]), sam); + expect(plan.rows[0]).toMatchObject({ + status: 'will_fill', + write: { ref: select.ref, kind: 'option', index: 1 }, + }); + }); + + it('files are never filled and have no target', () => { + const plan = buildPlan( + scanOf([field({ control: 'file', label: 'Resume' })]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'file', + }); + expect(plan.rows[0]!.target).toBeUndefined(); + }); +}); + +describe('buildPlan: answers', () => { + it('fills each answer into its control', () => { + const auth = yesNoSelect(`${AUTH} in the United States?`); + const relocate = field({ + control: 'select', + label: 'Are you willing to relocate?', + options: ['Yes', 'No', 'Depends on location'], + }); + const start = field({ control: 'date', label: 'Earliest start date' }); + const reason = field({ control: 'textarea', label: 'Reason for leaving' }); + const plan = buildPlan(scanOf([auth, relocate, start, reason]), sam); + expect(plan.writes).toEqual([ + { ref: auth.ref, kind: 'option', index: 0 }, + { ref: relocate.ref, kind: 'option', index: 2 }, + { ref: start.ref, kind: 'value', value: '2026-12-01' }, + { ref: reason.ref, kind: 'value', value: 'Looking for a new challenge' }, + ]); + expect(plan.rows[0]!.answerValue).toEqual({ type: 'yes_no', value: true }); + }); + + it('never writes the salary', () => { + const plan = buildPlan(scanOf([field({ label: 'Desired salary' })]), sam); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'never_auto', + ownValue: formatAnswer(SALARY), + }); + expect(plan.rows[0]!.ownValue).not.toBe(''); + expect(plan.writes).toEqual([]); + }); + + it('does not answer a negated question', () => { + const plan = buildPlan( + scanOf([ + yesNoSelect('Are you not authorized to work in the United States?'), + ]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'negated', + ownValue: '', + }); + expect(plan.rows[0]!.answerValue).toBeUndefined(); + }); + + it('marks a question that matches two answers ambiguous', () => { + const plan = buildPlan( + scanOf([ + yesNoSelect('Are you authorized to work without visa sponsorship?'), + ]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + reason: 'ambiguous', + ownValue: '', + target: { kind: 'answer', key: 'work_authorization' }, + }); + }); + + it('marks duplicated answers ambiguous', () => { + const plan = buildPlan( + scanOf([ + yesNoSelect('Are you authorized to work in the U.S.?'), + yesNoSelect('Is your authorized to work status current?'), + ]), + sam, + ); + expect(plan.rows.map((r) => r.reason)).toEqual(['ambiguous', 'ambiguous']); + expect(plan.rows.map((r) => r.ownValue)).toEqual(['', '']); + expect(plan.writes).toEqual([]); + }); + + it('a question matching two answers counts for neither in the duplicate pass', () => { + const plan = buildPlan( + scanOf([ + yesNoSelect('Are you authorized to work without visa sponsorship?'), + yesNoSelect(`${AUTH}?`), + ]), + sam, + ); + expect(plan.rows.map((r) => r.reason)).toEqual(['ambiguous', undefined]); + expect(plan.rows[1]!.status).toBe('will_fill'); + }); + + it.each([ + ['Canada', sam], + ['Canada', { profile: {}, answers: SAM_ANSWERS }], + ['Canada', withProfile({ country: 'Narnia' })], + ['the EU', sam], + ['Estonia', sam], + ])('treats %s as another country', (place, input) => { + const plan = buildPlan( + scanOf([yesNoSelect(`${AUTH} in ${place}?`)]), + input, + ); + expect(plan.rows[0]).toMatchObject({ + reason: 'other_country', + ownValue: '', + }); + expect(plan.rows[0]!.answerValue).toBeUndefined(); + expect(plan.writes).toEqual([]); + }); + + it("fills for the owner's own country, by any spelling", () => { + const plan = buildPlan( + scanOf([yesNoSelect(`${AUTH} in the U.S.?`)]), + withProfile({ country: 'USA' }), + ); + expect(plan.rows[0]!.status).toBe('will_fill'); + }); + + it('fills when no country is named', () => { + const plan = buildPlan(scanOf([yesNoSelect(`${AUTH}?`)]), sam); + expect(plan.rows[0]!.status).toBe('will_fill'); + }); + + it('does not write into a custom control', () => { + const plan = buildPlan( + scanOf([field({ control: 'custom', label: `${AUTH}?` })]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + reason: 'custom_control', + ownValue: 'Yes', + }); + }); + + it('reports an unsupported control', () => { + const plan = buildPlan( + scanOf([field({ control: 'text', label: 'Earliest start date' })]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + reason: 'unsupported_control', + ownValue: '2026-12-01', + }); + }); + + it('compares a held answer to the owner', () => { + const same = field({ + control: 'select', + label: `${AUTH}?`, + options: ['Yes', 'No'], + value: 'yes', + }); + const other = field({ + control: 'select', + label: 'Do you need visa sponsorship?', + options: ['Yes', 'No'], + value: 'Yes', + }); + const plan = buildPlan(scanOf([same, other]), sam); + expect(plan.rows.map((r) => r.status)).toEqual(['matches', 'differs']); + expect(plan.writes).toEqual([]); + }); +}); + +describe('buildPlan: unrecognised, frames, tables', () => { + it('flags a required unknown field and counts optional ones', () => { + const plan = buildPlan( + scanOf([ + field({ label: 'Favourite colour', required: true }), + field({ label: 'Pet name' }), + field({ label: 'Shoe size' }), + ]), + sam, + ); + expect(plan.rows).toHaveLength(1); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'not_recognised', + }); + expect(plan.rows[0]!.target).toBeUndefined(); + expect(plan.unrecognisedOptional).toBe(2); + }); + + it('lists a frame and no rows for a scan without fields', () => { + const plan = buildPlan( + scanOf([], ['https://boards.greenhouse.io/embed/job_app?for=example']), + sam, + ); + expect(plan.rows).toEqual([]); + expect(plan.frames).toHaveLength(1); + expect(plan.frames[0]!.site).toBe('greenhouse'); + }); + + it('takes the recognition tables as an argument', () => { + const label = 'Do you hold a valid work permit?'; + const scan = scanOf([yesNoSelect(label)]); + expect(buildPlan(scan, sam).rows).toEqual([]); + const tables: RecognitionTables = { + ...DEFAULT_TABLES, + answerPhrases: new Map([ + ...DEFAULT_TABLES.answerPhrases, + ['work_authorization', ['work permit']], + ]), + }; + const plan = buildPlan(scan, sam, tables); + expect(plan.rows[0]).toMatchObject({ + status: 'will_fill', + target: { kind: 'answer', key: 'work_authorization' }, + }); + }); +}); + +describe('buildPlan: odd answer records', () => { + const auth = () => yesNoSelect(`${AUTH}?`); + + it.each<[string, CanonicalAnswer[]]>([ + [ + 'a record with no key', + [{ id: 'x', createdAt: 'now', value: { type: 'yes_no', value: true } }], + ], + [ + 'the wrong value type', + [answer('work_authorization', { type: 'text', value: 'yes' })], + ], + ['a string for a value', [answer('work_authorization', 'Yes')]], + ['a null value', [answer('work_authorization', null)]], + [ + 'a first record without a value', + [ + answer('work_authorization', undefined), + answer('work_authorization', { type: 'yes_no', value: true }), + ], + ], + [ + 'a non-boolean yes/no', + [answer('work_authorization', { type: 'yes_no', value: 'true' })], + ], + ['a null record', [null as never]], + ])('gives no value for %s', (_name, answers) => { + const plan = buildPlan(scanOf([auth()]), withAnswers(answers)); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'no_value', + ownValue: '', + }); + expect(plan.rows[0]!.answerValue).toBeUndefined(); + expect(plan.writes).toEqual([]); + expectNoBadWrites(plan); + }); + + it('never writes a malformed date or a blank text answer', () => { + const fields = [ + field({ control: 'date', label: 'Earliest start date' }), + field({ control: 'textarea', label: 'Reason for leaving' }), + ]; + const plan = buildPlan( + scanOf(fields), + withAnswers([ + answer('earliest_start_date', { type: 'date', value: '12/01/2026' }), + answer('reason_for_leaving', { type: 'text', value: ' ' }), + ]), + ); + expect(plan.rows.map((r) => r.reason)).toEqual(['no_value', 'no_value']); + expect(plan.writes).toEqual([]); + }); + + it('a missing profile object value is no value, not "undefined"', () => { + const odd = { profile: { email: 5 as never }, answers: [] }; + const plan = buildPlan(scanOf([field({ label: 'Email' })]), odd); + expect(plan.rows[0]!.reason).toBe('no_value'); + expectNoBadWrites(plan); + }); +}); + +describe('buildPlan: rule order and guards', () => { + it.each([ + [ + 'a negated question', + 'Are you not authorized to work in the United States?', + 'negated', + ], + ['a question naming Canada', `${AUTH} in Canada?`, 'other_country'], + ])('rule 6 comes before the custom control rule: %s', (_n, label, reason) => { + const plan = buildPlan(scanOf([field({ control: 'custom', label })]), sam); + expect(plan.rows[0]).toMatchObject({ reason, ownValue: '' }); + expect(plan.rows[0]).not.toHaveProperty('answerValue'); + }); + + it('applies the place check to sponsorship', () => { + const canada = yesNoSelect('Do you need visa sponsorship in Canada?'); + const us = yesNoSelect( + 'Do you need visa sponsorship in the United States?', + ); + const plan = buildPlan(scanOf([canada]), sam); + expect(plan.rows[0]).toMatchObject({ + reason: 'other_country', + ownValue: '', + }); + expect(plan.rows[0]).not.toHaveProperty('answerValue'); + expect(buildPlan(scanOf([us]), sam).rows[0]!.status).toBe('will_fill'); + }); + + it('marks a profile key matched by a custom control and a text field ambiguous', () => { + const plan = buildPlan( + scanOf([ + field({ label: 'Email' }), + field({ control: 'custom', label: 'Email' }), + ]), + sam, + ); + expect(plan.rows.map((r) => r.reason)).toEqual(['ambiguous', 'ambiguous']); + }); + + it('gives a file field labelled Email the file row, with no write', () => { + const plan = buildPlan( + scanOf([field({ control: 'file', label: 'Email' })]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'file', + }); + expect(plan.rows[0]!.target).toBeUndefined(); + expect(plan.rows[0]!.write).toBeUndefined(); + expect(plan.writes).toEqual([]); + }); + + it('does not count a file field as a duplicate', () => { + const text = field({ label: 'Email' }); + const plan = buildPlan( + scanOf([field({ control: 'file', label: 'Email' }), text]), + sam, + ); + expect(plan.rows[1]!.status).toBe('will_fill'); + expect(plan.writes).toEqual([ + { ref: text.ref, kind: 'value', value: 'sam@example.com' }, + ]); + }); + + it('trims the owner values it offers and writes', () => { + const name = field({ label: 'First name' }); + const reason = field({ control: 'textarea', label: 'Reason for leaving' }); + const input: PlanInput = { + profile: { first_name: ' Sam ' }, + answers: [ + answer('reason_for_leaving', { type: 'text', value: ' Moving on ' }), + ], + }; + const plan = buildPlan(scanOf([name, reason]), input); + expect(plan.rows.map((r) => r.ownValue)).toEqual(['Sam', 'Moving on']); + expect(plan.writes).toEqual([ + { ref: name.ref, kind: 'value', value: 'Sam' }, + { ref: reason.ref, kind: 'value', value: 'Moving on' }, + ]); + }); + + it('joins the checked options of a group in checked order', () => { + const group = field({ + control: 'choice_group', + label: 'Are you not willing to relocate?', + options: ['Red', 'Green', 'Blue'], + checked: [2, 0], + multiple: true, + }); + const plan = buildPlan(scanOf([group]), sam); + expect(plan.rows[0]!.formValue).toBe('Blue, Red'); + }); +}); + +describe('buildPlan: invariants', () => { + it('holds over a large mixed scan', () => { + // Every profile and answer key is used by one field, except the Name pair. + const fields: ScannedField[] = [ + field({ label: 'First name' }), // will_fill (profile) + field({ label: 'Email', value: 'other@example.com' }), // differs + field({ label: 'Phone', value: '555-010-0142' }), // matches + field({ label: 'Name' }), // ambiguous (the deliberate pair) + field({ label: 'Name' }), + field({ control: 'file', label: 'Resume' }), // file + field({ label: 'Favourite colour', required: true }), // not_recognised + field({ label: 'Pet name' }), // optional, counted + field({ control: 'custom', label: 'City' }), // custom_control + field({ label: 'GitHub' }), // no_value (profile lacks it) + field({ + control: 'select', + label: 'Country', + options: ['Canada', 'United States'], + }), // will_fill (profile, option) + field({ label: 'Desired salary' }), // never_auto + yesNoSelect(`${AUTH}?`), // will_fill (answer) + yesNoSelect('Do you need visa sponsorship in Canada?'), // other_country + field({ + control: 'select', + label: 'Are you not willing to relocate?', + options: ['Yes', 'No', 'Depends on location'], + }), // negated + yesNoSelect('Authorized to work, and need visa sponsorship?'), // two answers + field({ label: 'Earliest start date' }), // unsupported_control + field({ control: 'textarea', label: 'Reason for leaving' }), // will_fill (answer) + field({ label: 'LinkedIn', value: 'https://example.com/in/sam' }), // matches + ]; + const noGithub: Partial> = { ...SAM_PROFILE }; + delete noGithub.github; + const plan = buildPlan(scanOf(fields), { + profile: noGithub, + answers: SAM_ANSWERS, + }); + const willFill = plan.rows.filter((r) => r.status === 'will_fill'); + + // The scan must keep covering every outcome. + const seen = new Set( + plan.rows.map((r) => { + const kind = r.target?.kind ?? 'none'; + return r.status === 'not_filled' + ? `not_filled:${r.reason}` + : `${r.status}:${kind}`; + }), + ); + for (const expected of [ + 'will_fill:profile', + 'will_fill:answer', + 'matches:profile', + 'differs:profile', + 'not_filled:negated', + 'not_filled:other_country', + 'not_filled:no_value', + 'not_filled:custom_control', + 'not_filled:unsupported_control', + 'not_filled:ambiguous', + 'not_filled:never_auto', + 'not_filled:file', + 'not_filled:not_recognised', + ]) { + expect(seen).toContain(expected); + } + for (const row of willFill) expect(row.write?.ref).toBe(row.ref); + expect( + plan.rows.filter((r) => r.reason === 'ambiguous').length, + ).toBeGreaterThanOrEqual(3); + + for (const row of plan.rows) { + expect(row.reason !== undefined).toBe(row.status === 'not_filled'); + expect(row.write !== undefined).toBe(row.status === 'will_fill'); + expect(row.answerValue !== undefined).toBe( + row.target?.kind === 'answer' && row.ownValue !== '', + ); + } + for (const row of willFill) expect(row.formValue).toBe(''); + expect(plan.writes).toEqual(willFill.map((r) => r.write)); + expect(new Set(plan.writes.map((w) => w.ref)).size).toBe( + plan.writes.length, + ); + expect(willFill.length).toBeGreaterThan(3); + expect(plan.unrecognisedOptional).toBe(1); + expectNoBadWrites(plan); + }); +}); diff --git a/core/src/fill/plan.ts b/core/src/fill/plan.ts new file mode 100644 index 0000000..e1b24c9 --- /dev/null +++ b/core/src/fill/plan.ts @@ -0,0 +1,355 @@ +import { DEFAULT_ANSWERS, formatAnswer } from '../answers'; +import { isLocalDate } from '../dates'; +import type { ProfileKey } from '../profile'; +import type { AnswerType, AnswerValue } from '../types'; +import { sameProfileValue, sameText } from './compare'; +import { countryOf, placesNamed } from './countries'; +import { fitField, type FitResult, type OwnKind } from './fit'; +import { hasNegation, normalizeLabel } from './normalize'; +import { recogniseAnswers, recogniseProfile } from './recognise'; +import { frameAdvice } from './site'; +import { DEFAULT_TABLES, type RecognitionTables } from './tables'; +import type { + FillPlan, + FillTarget, + FormScan, + NotFilledReason, + PlanInput, + PlanRow, + ScannedField, +} from './types'; + +/** What a field means, found once per field. */ +type Recognised = + | { kind: 'profile'; key: ProfileKey } + | { kind: 'answer'; key: string } + | { kind: 'two_answers'; keys: string[] } + | { kind: 'nothing' }; + +/** A saved answer that is safe to offer: its display text and a clean copy of the value. */ +interface OwnAnswer { + value: AnswerValue; + text: string; +} + +const ANSWER_TYPES = new Map( + DEFAULT_ANSWERS.map((a) => [a.key, a.type]), +); + +// ---- Rule 2: recognise a field ------------------------------------------ + +function recognise(field: ScannedField, tables: RecognitionTables): Recognised { + const profileKey = recogniseProfile(field, tables); + if (profileKey !== undefined) return { kind: 'profile', key: profileKey }; + const keys = recogniseAnswers(field, tables); + const [first] = keys; + if (first === undefined) return { kind: 'nothing' }; + return keys.length === 1 + ? { kind: 'answer', key: first } + : { kind: 'two_answers', keys }; +} + +// ---- Rule 5: first pass, count the keys --------------------------------- + +function duplicateKeys(recognised: readonly Recognised[]): Set { + const counts = new Map(); + for (const r of recognised) { + const id = countKey(r); + if (id !== undefined) counts.set(id, (counts.get(id) ?? 0) + 1); + } + const duplicated = new Set(); + for (const [id, count] of counts) if (count >= 2) duplicated.add(id); + return duplicated; +} + +function countKey(r: Recognised): string | undefined { + if (r.kind === 'profile') return `profile:${r.key}`; + if (r.kind === 'answer') return `answer:${r.key}`; + return undefined; +} + +// ---- Rule 8: the owner's value ------------------------------------------ + +function profileValue(input: PlanInput, key: ProfileKey): string { + const raw: unknown = input.profile[key]; + return typeof raw === 'string' ? raw.trim() : ''; +} + +function nonEmptyString(raw: unknown): string | undefined { + if (typeof raw !== 'string') return undefined; + const trimmed = raw.trim(); + return trimmed === '' ? undefined : trimmed; +} + +/** Checks the stored value against the type the key must have; rebuilds a clean copy. */ +function cleanAnswer(raw: unknown, type: AnswerType): OwnAnswer | undefined { + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) { + return undefined; + } + const stored = raw as { type?: unknown; value?: unknown }; + if (stored.type !== type) return undefined; + switch (type) { + case 'yes_no': { + if (typeof stored.value !== 'boolean') return undefined; + return { + value: { type: 'yes_no', value: stored.value }, + text: stored.value ? 'Yes' : 'No', + }; + } + case 'choice': + case 'text': { + const text = nonEmptyString(stored.value); + if (text === undefined) return undefined; + return { value: { type, value: text }, text }; + } + case 'date': { + const day = stored.value; + if (typeof day !== 'string' || !isLocalDate(day)) return undefined; + return { value: { type: 'date', value: day }, text: day }; + } + case 'money_range': { + const text = formatAnswer(raw as AnswerValue); + return text === '' ? undefined : { value: raw as AnswerValue, text }; + } + default: + return undefined; + } +} + +function ownAnswer(input: PlanInput, key: string): OwnAnswer | undefined { + const type = ANSWER_TYPES.get(key); + if (type === undefined) return undefined; + const record: unknown = input.answers.find( + (a: unknown) => + typeof a === 'object' && + a !== null && + (a as { key?: unknown }).key === key, + ); + if (record === undefined) return undefined; + return cleanAnswer((record as { value?: unknown }).value, type); +} + +function answerKind(own: OwnAnswer): OwnKind | undefined { + switch (own.value.type) { + case 'yes_no': + case 'choice': + case 'date': + case 'text': + return own.value.type; + default: + return undefined; + } +} + +// ---- Rule 6: the place check -------------------------------------------- + +/** True when the question names a place that is not the owner's country. */ +function namesOtherPlace(label: string, input: PlanInput): boolean { + const named = placesNamed(normalizeLabel(label)); + if (named.length === 0) return false; + const country = + typeof input.profile.country === 'string' + ? countryOf(input.profile.country) + : undefined; + return country === undefined || !named.every((place) => place === country); +} + +// ---- Rows --------------------------------------------------------------- + +/** What the form holds now, as text. */ +function formValueOf(field: ScannedField): string { + switch (field.control) { + case 'text': + case 'textarea': + case 'date': + case 'select': + return field.value; + case 'choice_group': + return field.checked + .map((i) => field.options[i]) + .filter((o): o is string => o !== undefined) + .join(', '); + default: + return ''; + } +} + +function baseRow(field: ScannedField, target?: FillTarget): PlanRow { + const row: PlanRow = { + ref: field.ref, + label: field.label, + control: field.control, + required: field.required, + status: 'not_filled', + formValue: formValueOf(field), + ownValue: '', + }; + if (target !== undefined) row.target = target; + return row; +} + +function notFilled( + field: ScannedField, + reason: NotFilledReason, + target?: FillTarget, + own?: OwnAnswer | string, +): PlanRow { + const row = baseRow(field, target); + row.reason = reason; + if (own !== undefined) setOwn(row, own); + return row; +} + +/** Sets ownValue, and answerValue only for an answer target with a value (never for a profile one). */ +function setOwn(row: PlanRow, own: OwnAnswer | string): void { + if (typeof own === 'string') { + row.ownValue = own; + return; + } + row.ownValue = own.text; + if (row.target?.kind === 'answer') row.answerValue = own.value; +} + +/** Rule 9: the row for a fit result. */ +function fitRow( + field: ScannedField, + target: FillTarget, + fit: FitResult, + own: OwnAnswer | string, + same: (formValue: string, ownText: string) => boolean, +): PlanRow { + const ownText = typeof own === 'string' ? own : own.text; + if (fit.fit === 'none') return notFilled(field, fit.reason, target, own); + const row = baseRow(field, target); + setOwn(row, own); + if (fit.fit === 'holds') { + row.formValue = fit.formValue; + row.status = same(fit.formValue, ownText) ? 'matches' : 'differs'; + return row; + } + row.status = 'will_fill'; + row.write = fit.write; + return row; +} + +function profileRow( + field: ScannedField, + key: ProfileKey, + duplicated: boolean, + input: PlanInput, +): PlanRow { + const target: FillTarget = { kind: 'profile', key }; + const own = profileValue(input, key); + // 5. Duplicates keep the owner's value for the copy button. + if (duplicated) return notFilled(field, 'ambiguous', target, own); + // 7. Custom control. + if (field.control === 'custom') { + return notFilled(field, 'custom_control', target, own); + } + // 8. No value. + if (own === '') return notFilled(field, 'no_value', target); + // 9. Fit. + const kind: OwnKind = + key === 'country' || key === 'region' ? 'place' : 'text'; + return fitRow(field, target, fitField(field, kind, own), own, (form, mine) => + sameProfileValue(key, form, mine), + ); +} + +function answerRow( + field: ScannedField, + key: string, + duplicated: boolean, + input: PlanInput, +): PlanRow { + const target: FillTarget = { kind: 'answer', key }; + // 5. Duplicates offer nothing. + if (duplicated) return notFilled(field, 'ambiguous', target); + // 6. Answers only. + if (hasNegation(field.label)) return notFilled(field, 'negated', target); + const own = ownAnswer(input, key); + if (key === 'salary_range') { + return notFilled(field, 'never_auto', target, own); + } + if ( + (key === 'work_authorization' || key === 'sponsorship') && + namesOtherPlace(field.label, input) + ) { + return notFilled(field, 'other_country', target); + } + // 7. Custom control. + if (field.control === 'custom') { + return notFilled(field, 'custom_control', target, own); + } + // 8. No value. + const kind = own === undefined ? undefined : answerKind(own); + if (own === undefined || kind === undefined) { + return notFilled(field, 'no_value', target); + } + // 9. Fit. + return fitRow(field, target, fitField(field, kind, own.text), own, sameText); +} + +/** Rules 1, 3 and 4, then the profile or answer rules. Undefined means no row. */ +function planField( + field: ScannedField, + recognised: Recognised, + duplicates: ReadonlySet, + input: PlanInput, +): PlanRow | undefined { + // 1. Files. + if (field.control === 'file') return notFilled(field, 'file'); + const duplicated = duplicates.has(countKey(recognised) ?? ''); + switch (recognised.kind) { + case 'nothing': + // 3. Optional unknown fields get no row; the caller counts them. + return field.required ? notFilled(field, 'not_recognised') : undefined; + case 'two_answers': + // 4. One question, two answers. + return notFilled(field, 'ambiguous', { + kind: 'answer', + key: recognised.keys[0] ?? '', + }); + case 'profile': + return profileRow(field, recognised.key, duplicated, input); + case 'answer': + return answerRow(field, recognised.key, duplicated, input); + } +} + +/** + * Decides what the extension would write into a form. Pure: it reads the + * scan, the owner's details and answers, and returns one row per recognised + * field plus the writes. It never replaces a value and never writes when in doubt. + */ +export function buildPlan( + scan: FormScan, + input: PlanInput, + tables: RecognitionTables = DEFAULT_TABLES, +): FillPlan { + const recognised = scan.fields.map((f) => + f.control === 'file' + ? ({ kind: 'nothing' } as const) + : recognise(f, tables), + ); + const duplicates = duplicateKeys(recognised); + const plan: FillPlan = { + rows: [], + writes: [], + unrecognisedOptional: 0, + frames: frameAdvice(scan.frames), + }; + scan.fields.forEach((field, i) => { + const r = recognised[i] ?? ({ kind: 'nothing' } as const); + const row = planField(field, r, duplicates, input); + if (row === undefined) { + plan.unrecognisedOptional += 1; + return; + } + plan.rows.push(row); + if (row.status === 'will_fill' && row.write !== undefined) { + plan.writes.push(row.write); + } + }); + return plan; +} From d47af6362eaffd94dc7e827e317cfaca404e7373 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:48:47 -0600 Subject: [PATCH 14/48] Add the fill result for later recording --- core/src/fill/result.test.ts | 284 +++++++++++++++++++++++++++++++++++ core/src/fill/result.ts | 66 ++++++++ 2 files changed, 350 insertions(+) create mode 100644 core/src/fill/result.test.ts create mode 100644 core/src/fill/result.ts diff --git a/core/src/fill/result.test.ts b/core/src/fill/result.test.ts new file mode 100644 index 0000000..07d5975 --- /dev/null +++ b/core/src/fill/result.test.ts @@ -0,0 +1,284 @@ +import { describe, expect, it } from 'vitest'; +import { buildFillResult } from './result'; +import type { FillPlan, PlanRow, WriteReport } from './types'; + +const AT = '2026-11-20T09:00:00.000Z'; + +function plan(rows: PlanRow[]): FillPlan { + return { rows, writes: [], unrecognisedOptional: 0, frames: [] }; +} + +function willFill(ref: number, label = `Field ${ref}`): PlanRow { + return { + ref, + label, + control: 'text', + required: false, + target: { kind: 'profile', key: 'first_name' }, + status: 'will_fill', + formValue: '', + ownValue: 'Alex', + write: { ref, kind: 'value', value: 'Alex' }, + }; +} + +function differs(ref: number, label = `Field ${ref}`): PlanRow { + return { + ref, + label, + control: 'text', + required: false, + target: { kind: 'profile', key: 'email' }, + status: 'differs', + formValue: 'old@example.com', + ownValue: 'new@example.com', + }; +} + +function matches(ref: number, label = `Field ${ref}`): PlanRow { + return { + ref, + label, + control: 'text', + required: false, + target: { kind: 'profile', key: 'city' }, + status: 'matches', + formValue: 'Springfield', + ownValue: 'Springfield', + }; +} + +function notFilled( + ref: number, + reason: PlanRow['reason'], + label = `Field ${ref}`, +): PlanRow { + return { + ref, + label, + control: 'file', + required: false, + status: 'not_filled', + reason, + formValue: '', + ownValue: '', + }; +} + +function answerRow(ref: number): PlanRow { + return { + ref, + label: 'Are you authorised to work in the United States?', + control: 'choice_group', + required: true, + target: { kind: 'answer', key: 'work_auth_us' }, + status: 'will_fill', + formValue: '', + ownValue: 'Yes', + write: { ref, kind: 'option', index: 0 }, + answerValue: { type: 'yes_no', value: true }, + }; +} + +describe('buildFillResult', () => { + it('canonicalises the address', () => { + const tabUrl = 'https://example.com/jobs/1?utm_source=x#apply'; + const empty = plan([]); + + expect( + buildFillResult({ tabUrl, at: AT, plan: empty, outcomes: [] }).url, + ).toBe('https://example.com/jobs/1'); + expect( + buildFillResult({ + tabUrl, + relCanonical: 'https://example.com/jobs/one', + at: AT, + plan: empty, + outcomes: [], + }).url, + ).toBe('https://example.com/jobs/one'); + }); + + it('sets the site type', () => { + const result = buildFillResult({ + tabUrl: 'https://jobs.lever.co/example-co/abc123', + at: AT, + plan: plan([]), + outcomes: [], + }); + + expect(result.siteType).toBe('lever'); + }); + + it('carries outcomes', () => { + const outcomes: WriteReport[] = [ + { ref: 1, outcome: 'written' }, + { ref: 2, outcome: 'gone' }, + ]; + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1), willFill(2), differs(3)]), + outcomes, + }).rows; + + expect(rows[0]).toStrictEqual({ + label: 'Field 1', + target: { kind: 'profile', key: 'first_name' }, + status: 'will_fill', + outcome: 'written', + }); + expect(rows[1]?.outcome).toBe('gone'); + expect(rows[2]).not.toHaveProperty('outcome'); + }); + + it('a will_fill row with no report is failed', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1)]), + outcomes: [], + }).rows; + + expect(rows[0]?.outcome).toBe('failed'); + }); + + it('an answer row carries what item 3 needs', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([answerRow(5)]), + outcomes: [{ ref: 5, outcome: 'written' }], + }).rows; + + expect(rows[0]).toStrictEqual({ + label: 'Are you authorised to work in the United States?', + target: { kind: 'answer', key: 'work_auth_us' }, + status: 'will_fill', + answerValue: { type: 'yes_no', value: true }, + outcome: 'written', + }); + }); + + it('the first report for a ref wins', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1)]), + outcomes: [ + { ref: 1, outcome: 'written' }, + { ref: 1, outcome: 'failed' }, + ], + }).rows; + + expect(rows[0]?.outcome).toBe('written'); + }); + + it('a report for a ref no row has is ignored', () => { + const withStray = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1)]), + outcomes: [{ ref: 99, outcome: 'written' }], + }); + const without = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1)]), + outcomes: [], + }); + + expect(withStray).toStrictEqual(without); + expect(withStray.rows).toHaveLength(1); + }); + + it('a report for a differs row does not give it an outcome', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([differs(2)]), + outcomes: [{ ref: 2, outcome: 'written' }], + }).rows; + + expect(rows[0]).not.toHaveProperty('outcome'); + }); + + it('an empty plan gives no rows but keeps url, siteType and at', () => { + const result = buildFillResult({ + tabUrl: 'https://jobs.lever.co/example-co/abc123?utm_medium=x', + at: AT, + plan: plan([]), + outcomes: [{ ref: 1, outcome: 'written' }], + }); + + expect(result).toStrictEqual({ + url: 'https://jobs.lever.co/example-co/abc123', + siteType: 'lever', + at: AT, + rows: [], + }); + }); + + it('keeps plan row order for mixed statuses', () => { + const planRows = [ + willFill(1, 'First name'), + notFilled(2, 'no_value', 'Middle name'), + differs(3, 'Email'), + matches(4, 'City'), + answerRow(5), + ]; + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan(planRows), + outcomes: [], + }).rows; + + expect(rows.map((row) => row.label)).toStrictEqual( + planRows.map((row) => row.label), + ); + expect(rows.map((row) => row.status)).toStrictEqual([ + 'will_fill', + 'not_filled', + 'differs', + 'matches', + 'will_fill', + ]); + }); + + it('a row without target or reason gets no such keys', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([notFilled(7, 'file', 'Resume')]), + outcomes: [], + }).rows; + + expect(rows[0]).toStrictEqual({ + label: 'Resume', + status: 'not_filled', + reason: 'file', + }); + }); + + it('does not change its arguments', () => { + const input = { + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1), answerRow(5), differs(3)]), + outcomes: [ + { ref: 1, outcome: 'written' }, + { ref: 5, outcome: 'gone' }, + ] as WriteReport[], + }; + const snapshot: unknown = JSON.parse( + JSON.stringify({ plan: input.plan, outcomes: input.outcomes }), + ); + + buildFillResult(input); + + expect({ plan: input.plan, outcomes: input.outcomes }).toStrictEqual( + snapshot, + ); + }); +}); diff --git a/core/src/fill/result.ts b/core/src/fill/result.ts new file mode 100644 index 0000000..be3d45a --- /dev/null +++ b/core/src/fill/result.ts @@ -0,0 +1,66 @@ +import type { SiteType } from '../formhand'; +import { canonicalizeUrl } from '../url'; +import type { AnswerValue, IsoInstant } from '../types'; +import { siteTypeForUrl } from './site'; +import type { + FillPlan, + FillTarget, + NotFilledReason, + RowStatus, + WriteOutcome, + WriteReport, +} from './types'; + +export interface FillResultRow { + label: string; + target?: FillTarget; + status: RowStatus; + reason?: NotFilledReason; + outcome?: WriteOutcome; + answerValue?: AnswerValue; +} + +export interface FillResult { + url: string; + siteType: SiteType; + at: IsoInstant; + rows: FillResultRow[]; +} + +/** + * Turns a fill plan and the page's write reports into the record kept for a + * later feature. The first report for a ref wins; reports for unknown refs are + * ignored. Only will_fill rows get an outcome. Never changes its arguments. + */ +export function buildFillResult(args: { + tabUrl: string; + relCanonical?: string; + at: IsoInstant; + plan: FillPlan; + outcomes: readonly WriteReport[]; +}): FillResult { + const reported = new Map(); + for (const report of args.outcomes) { + if (!reported.has(report.ref)) { + reported.set(report.ref, report.outcome); + } + } + + const rows = args.plan.rows.map((row): FillResultRow => { + const result: FillResultRow = { label: row.label, status: row.status }; + if (row.target !== undefined) result.target = row.target; + if (row.reason !== undefined) result.reason = row.reason; + if (row.status === 'will_fill') { + result.outcome = reported.get(row.ref) ?? 'failed'; + } + if (row.answerValue !== undefined) result.answerValue = row.answerValue; + return result; + }); + + return { + url: canonicalizeUrl(args.tabUrl, args.relCanonical), + siteType: siteTypeForUrl(args.tabUrl), + at: args.at, + rows, + }; +} From daa966ee198c081124c97926ab3fe8d7adf53c00 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:16:21 -0600 Subject: [PATCH 15/48] Let the fill injector inject and guard its apply call --- eslint.config.js | 32 ++++++++++++++--- guard/source-rules.test.ts | 72 ++++++++++++++++++++++++++++++-------- 2 files changed, 84 insertions(+), 20 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 94d89fd..02aedfa 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -65,14 +65,16 @@ const navigationSyntax = [ `AssignmentExpression[left.property.name='href'][left.object.property.name='location'][left.object.object.name=${GLOBAL_OBJECTS}]`, `AssignmentExpression[left.property.value='href'][left.object.property.name='location'][left.object.object.name=${GLOBAL_OBJECTS}]`, ].map((selector) => ({ selector, message: NAVIGATION_MESSAGE })); -// Reading tabs and injecting scripts are confined to two shell files. -const TABS_MESSAGE = 'Use tabs only in open-dashboard.ts or capture/inject.ts.'; +// Reading tabs and injecting scripts are confined to three shell files. +const TABS_MESSAGE = + 'Use tabs only in open-dashboard.ts, capture/inject.ts or fill/inject.ts.'; const tabsSyntax = [ "MemberExpression[property.name='tabs']", "MemberExpression[property.value='tabs']", "Property[key.name='tabs']", ].map((selector) => ({ selector, message: TABS_MESSAGE })); -const SCRIPTING_MESSAGE = 'Inject only through shell/capture/inject.ts.'; +const SCRIPTING_MESSAGE = + 'Inject only through shell/capture/inject.ts or shell/fill/inject.ts.'; const scriptingSyntax = [ "MemberExpression[property.name='scripting']", "MemberExpression[property.value='scripting']", @@ -102,6 +104,21 @@ export default defineConfig( rules: { 'no-restricted-globals': ['error', ...networkGlobals], 'no-restricted-properties': ['error', ...networkProperties], + // The apply call writes into the user's page, so only the controller + // (and the injector's own test) may import it. + 'no-restricted-imports': [ + 'error', + { + patterns: [ + { + regex: '(^|/)fill/inject$|^\\./inject$', + importNames: ['applyToPage', 'browserFillApi'], + message: + 'Only shell/fill/controller.ts may import the fill apply call.', + }, + ], + }, + ], 'no-restricted-syntax': [ 'error', ...networkSyntax, @@ -156,9 +173,9 @@ export default defineConfig( ], }, }, - // capture/inject.ts may use both tabs and scripting. + // The two injectors may use both tabs and scripting. { - files: ['shell/capture/inject.ts'], + files: ['shell/capture/inject.ts', 'shell/fill/inject.ts'], rules: { 'no-restricted-syntax': [ 'error', @@ -168,6 +185,11 @@ export default defineConfig( ], }, }, + // The controller and the injector's test may import the apply call. + { + files: ['shell/fill/controller.ts', 'shell/fill/inject.test.ts'], + rules: { 'no-restricted-imports': 'off' }, + }, // core/ is framework-free: no framework, storage or browser access. { files: ['core/**'], diff --git a/guard/source-rules.test.ts b/guard/source-rules.test.ts index 22bb473..fcb4db2 100644 --- a/guard/source-rules.test.ts +++ b/guard/source-rules.test.ts @@ -254,10 +254,12 @@ describe('download guard', { timeout: 60_000 }, () => { describe('navigation and injection guard', { timeout: 60_000 }, () => { const navMessage = 'Countersign never navigates away or opens windows.'; const tabsMessage = - 'Use tabs only in open-dashboard.ts or capture/inject.ts.'; - const scriptingMessage = 'Inject only through shell/capture/inject.ts.'; + 'Use tabs only in open-dashboard.ts, capture/inject.ts or fill/inject.ts.'; + const scriptingMessage = + 'Inject only through shell/capture/inject.ts or shell/fill/inject.ts.'; const dashboard = 'shell/open-dashboard.ts'; const inject = 'shell/capture/inject.ts'; + const fillInject = 'shell/fill/inject.ts'; const save = "browser.downloads.download({ url: 'blob:x' });"; // Probe paths such as shell/ui/x.tsx and shell/capture/inject.ts do not exist // on disk, so type-aware parsing would fail. Switch type information off; @@ -321,27 +323,38 @@ describe('navigation and injection guard', { timeout: 60_000 }, () => { const found = await syntaxMessages(code, 'shell/ui/x.tsx'); expect(found.some((m) => m.message === tabsMessage)).toBe(true); }); - it.each([dashboard, inject])('allows tabs access in %s', async (file) => { - const found = await syntaxMessages('browser.tabs.query({});', file); - expect(found.some((m) => m.message === tabsMessage)).toBe(false); - }); + it.each([dashboard, inject, fillInject])( + 'allows tabs access in %s', + async (file) => { + const found = await syntaxMessages('browser.tabs.query({});', file); + expect(found.some((m) => m.message === tabsMessage)).toBe(false); + }, + ); it.each([ 'browser.scripting.executeScript({});', "browser['scripting'].executeScript({});", 'const { scripting } = browser;', ])('rejects scripting access %s outside inject.ts', async (code) => { - for (const file of ['shell/ui/x.tsx', dashboard]) { + for (const file of [ + 'shell/ui/x.tsx', + dashboard, + 'shell/fill/controller.ts', + 'shell/fill/page/scan.ts', + ]) { const found = await syntaxMessages(code, file); expect(found.some((m) => m.message === scriptingMessage)).toBe(true); } }); - it('allows scripting access in inject.ts', async () => { - const found = await syntaxMessages( - 'browser.scripting.executeScript({});', - inject, - ); - expect(found.some((m) => m.message === scriptingMessage)).toBe(false); - }); + it.each([inject, fillInject])( + 'allows scripting access in %s', + async (file) => { + const found = await syntaxMessages( + 'browser.scripting.executeScript({});', + file, + ); + expect(found.some((m) => m.message === scriptingMessage)).toBe(false); + }, + ); it('rejects tabs access in the download wrapper', async () => { const found = await syntaxMessages( 'browser.tabs.query({});', @@ -349,7 +362,7 @@ describe('navigation and injection guard', { timeout: 60_000 }, () => { ); expect(found.some((m) => m.message === tabsMessage)).toBe(true); }); - it.each([dashboard, inject])( + it.each([dashboard, inject, fillInject])( 'keeps the download, network and navigation rules in %s', async (file) => { for (const [code, message] of [ @@ -372,6 +385,35 @@ describe('navigation and injection guard', { timeout: 60_000 }, () => { ); expect(found.some((m) => m.message === navMessage)).toBe(true); }); + it.each([ + [ + "import { applyToPage } from '../fill/inject';", + 'shell/ui/FillSection.tsx', + ], + ["import { applyToPage } from './inject';", 'shell/fill/other.ts'], + ["import { browserFillApi } from '../fill/inject';", 'shell/ui/Popup.tsx'], + ["import * as inject from '../fill/inject';", 'shell/ui/x.tsx'], + ["export { applyToPage } from './inject';", 'shell/fill/index.ts'], + ])('rejects the apply import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.ruleId === 'no-restricted-imports')).toBe(true); + }); + it.each([ + ["import { applyToPage } from './inject';", 'shell/fill/controller.ts'], + ["import { applyToPage } from './inject';", 'shell/fill/inject.test.ts'], + ["import type { ScanOutcome } from '../fill/inject';", 'shell/ui/x.tsx'], + ["import { scanPage } from './inject';", 'shell/fill/other.ts'], + ])('allows the import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.ruleId === 'no-restricted-imports')).toBe(false); + }); + it('still rejects shell imports in core/', async () => { + const found = await syntaxMessages( + "import { x } from '../../shell/fill/inject';", + 'core/src/status.ts', + ); + expect(found.some((m) => m.ruleId === 'no-restricted-imports')).toBe(true); + }); const styleMessage = 'No inline styles: the CSP blocks them. Use a class.'; it.each(['shell/ui/x.tsx', 'entrypoints/popup/x.tsx'])( 'rejects a style prop in %s', From 028e4f36f320b5b5733142b75a4bf0d3330281e1 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:18:38 -0600 Subject: [PATCH 16/48] Guard what the fill page script may do --- eslint.config.js | 103 ++++++++++++++++++++++++++++++++ guard/source-rules.test.ts | 119 +++++++++++++++++++++++++++++++++++++ 2 files changed, 222 insertions(+) diff --git a/eslint.config.js b/eslint.config.js index 02aedfa..7cb442f 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -86,6 +86,72 @@ const STYLE_MESSAGE = 'No inline styles: the CSP blocks them. Use a class.'; const styleSyntax = [ { selector: "JSXAttribute[name.name='style']", message: STYLE_MESSAGE }, ]; +// The fill page script runs inside the user's page. It reads fields and sets +// their values, nothing else. Each part below is a named list so that +// shell/fill/page/events.ts can drop exactly the dispatch and constructor +// selectors it needs to change. +const FILL_PAGE_MESSAGE = + 'The fill page script only reads fields and sets their values.'; +/** @param {string[]} names */ +const callNames = (names) => `/^(${names.join('|')})$/`; +/** @param {string[]} names */ +const callSelectors = (names) => [ + `CallExpression[callee.property.name=${callNames(names)}]`, + `CallExpression[callee.property.value=${callNames(names)}]`, +]; +/** @param {string[]} names */ +const memberSelectors = (names) => [ + `MemberExpression[property.name=${callNames(names)}]`, + `MemberExpression[property.value=${callNames(names)}]`, +]; +/** @param {string[]} selectors */ +const asFillSyntax = (selectors) => + selectors.map((selector) => ({ selector, message: FILL_PAGE_MESSAGE })); +const fillCallSyntax = asFillSyntax( + callSelectors([ + 'submit', + 'requestSubmit', + 'click', + 'focus', + 'scrollIntoView', + 'createEvent', + 'execCommand', + ]), +); +const fillDispatchSyntax = asFillSyntax(callSelectors(['dispatchEvent'])); +/** @param {string} pattern */ +const eventCtorSelectors = (pattern) => [ + `NewExpression[callee.name=${pattern}]`, + `NewExpression[callee.property.name=${pattern}]`, + `NewExpression[callee.property.value=${pattern}]`, +]; +const fillEventCtorSyntax = asFillSyntax(eventCtorSelectors('/Event$/')); +// Same as above but a bare Event is allowed: the name must have a prefix. +const fillPlainEventCtorSyntax = asFillSyntax(eventCtorSelectors('/.+Event$/')); +const fillDomSyntax = asFillSyntax( + memberSelectors([ + 'createElement', + 'setAttribute', + 'removeAttribute', + 'toggleAttribute', + 'dataset', + 'innerHTML', + 'outerHTML', + 'insertAdjacentHTML', + 'append', + 'appendChild', + ]), +); +const fillLeakSyntax = asFillSyntax([ + `Identifier[name=${callNames(['console', 'localStorage', 'sessionStorage', 'postMessage'])}]`, + ...memberSelectors([ + 'console', + 'localStorage', + 'sessionStorage', + 'postMessage', + 'cookie', + ]), +]); export default defineConfig( { @@ -190,6 +256,43 @@ export default defineConfig( files: ['shell/fill/controller.ts', 'shell/fill/inject.test.ts'], rules: { 'no-restricted-imports': 'off' }, }, + // The fill page script may only read fields and set their values. + { + files: ['shell/fill/page/**', 'entrypoints/fill.ts'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ...fillCallSyntax, + ...fillDispatchSyntax, + ...fillEventCtorSyntax, + ...fillDomSyntax, + ...fillLeakSyntax, + ], + }, + }, + // events.ts alone may dispatch an event, and only a plain Event. + { + files: ['shell/fill/page/events.ts'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ...fillCallSyntax, + ...fillPlainEventCtorSyntax, + ...fillDomSyntax, + ...fillLeakSyntax, + ], + }, + }, // core/ is framework-free: no framework, storage or browser access. { files: ['core/**'], diff --git a/guard/source-rules.test.ts b/guard/source-rules.test.ts index fcb4db2..f41c2f3 100644 --- a/guard/source-rules.test.ts +++ b/guard/source-rules.test.ts @@ -442,6 +442,125 @@ describe('navigation and injection guard', { timeout: 60_000 }, () => { }); }); +describe('fill page guard', { timeout: 60_000 }, () => { + const fillMessage = + 'The fill page script only reads fields and sets their values.'; + const pageFiles = ['shell/fill/page/x.ts', 'entrypoints/fill.ts']; + const eventsFile = 'shell/fill/page/events.ts'; + // Probe paths do not exist on disk, so switch type information off. + const syntaxLint = new ESLint({ + cwd: resolve(import.meta.dirname, '..'), + overrideConfig: tseslint.configs.disableTypeChecked, + }); + async function syntaxMessages(code: string, filePath: string) { + const [result] = await syntaxLint.lintText(code, { filePath }); + const found = result?.messages ?? []; + expect(found.filter((m) => m.fatal)).toEqual([]); + return found; + } + + const rejected = [ + 'form.submit();', + 'form.requestSubmit();', + 'el.click();', + "el['click']();", + 'el.focus();', + 'el.dispatchEvent(e);', + 'el.scrollIntoView();', + "document.createEvent('Event');", + "document.execCommand('insertText');", + "new Event('input');", + "new KeyboardEvent('keydown');", + "new MouseEvent('click');", + "new window.PointerEvent('pointerdown');", + "new CustomEvent('x');", + "document.createElement('div');", + "el.setAttribute('a', 'b');", + "el.removeAttribute('a');", + "el.dataset.x = '1';", + "el.innerHTML = '';", + 'el.outerHTML;', + "el.insertAdjacentHTML('beforeend', '');", + 'el.append(x);', + 'el.appendChild(x);', + 'console.log(1);', + "localStorage.setItem('a', 'b');", + 'window.sessionStorage;', + "postMessage('x');", + "window.postMessage('x', '*');", + 'document.cookie;', + ]; + describe.each(pageFiles)('in %s', (file) => { + it.each(rejected)('rejects %s in the page script', async (code) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.message === fillMessage)).toBe(true); + }); + it.each([ + "el.value = 'x';", + 'const v = el.checked;', + "setter.call(el, 'x');", + "el.querySelectorAll('input');", + 'const submitted = 1;', + ])('allows %s', async (code) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.message === fillMessage)).toBe(false); + }); + }); + + it('events.ts may dispatch a plain Event', async () => { + const found = await syntaxMessages( + "el.dispatchEvent(new Event('input', { bubbles: true }));", + eventsFile, + ); + expect(found.some((m) => m.message === fillMessage)).toBe(false); + }); + it.each([ + "new KeyboardEvent('keydown');", + "new InputEvent('input');", + "new window.InputEvent('input');", + 'el.click();', + 'form.submit();', + 'console.log(1);', + ])('events.ts may do nothing else: rejects %s', async (code) => { + const found = await syntaxMessages(code, eventsFile); + expect(found.some((m) => m.message === fillMessage)).toBe(true); + }); + it.each([...pageFiles, eventsFile])( + 'keeps the shared rules in %s', + async (file) => { + for (const [code, message] of [ + [ + "navigator.sendBeacon('https://example.com');", + 'This extension makes no network requests.', + ], + [ + 'location.reload();', + 'Countersign never navigates away or opens windows.', + ], + [ + 'browser.tabs.query({});', + 'Use tabs only in open-dashboard.ts, capture/inject.ts or fill/inject.ts.', + ], + [ + 'browser.scripting.executeScript({});', + 'Inject only through shell/capture/inject.ts or shell/fill/inject.ts.', + ], + [ + "browser.downloads.download({ url: 'blob:x' });", + 'Save files only through shell/files/download.ts.', + ], + ] as const) { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.message === message)).toBe(true); + } + }, + ); + it('does not reach other files', async () => { + const found = await syntaxMessages('el.click();', 'shell/ui/x.tsx'); + expect(found.some((m) => m.message === fillMessage)).toBe(false); + }); +}); + describe( 'core/ restrictions still bite alongside the network rules', { timeout: 60_000 }, From 6dabfa961c837869455335a03a1bd3ee8034841d Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:20:29 -0600 Subject: [PATCH 17/48] Guard dynamic imports of the fill apply call --- eslint.config.js | 18 +++++++++++++++++- guard/source-rules.test.ts | 16 ++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/eslint.config.js b/eslint.config.js index 7cb442f..3c19920 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -86,6 +86,15 @@ const STYLE_MESSAGE = 'No inline styles: the CSP blocks them. Use a class.'; const styleSyntax = [ { selector: "JSXAttribute[name.name='style']", message: STYLE_MESSAGE }, ]; +// no-restricted-imports cannot see import(), so a dynamic import of the fill +// apply call is caught here. It applies to every file, controller.ts included. +const applyImportSyntax = [ + { + selector: + 'ImportExpression[source.value=/(^|\\/)fill\\/inject(\\.[jt]s)?$|^\\.\\/inject(\\.[jt]s)?$/]', + message: 'Only shell/fill/controller.ts may import the fill apply call.', + }, +]; // The fill page script runs inside the user's page. It reads fields and sets // their values, nothing else. Each part below is a named list so that // shell/fill/page/events.ts can drop exactly the dispatch and constructor @@ -177,7 +186,7 @@ export default defineConfig( { patterns: [ { - regex: '(^|/)fill/inject$|^\\./inject$', + regex: '(^|/)fill/inject(\\.[jt]s)?$|^\\./inject(\\.[jt]s)?$', importNames: ['applyToPage', 'browserFillApi'], message: 'Only shell/fill/controller.ts may import the fill apply call.', @@ -190,6 +199,7 @@ export default defineConfig( ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, ...tabsSyntax, ...scriptingSyntax, ], @@ -205,6 +215,7 @@ export default defineConfig( ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, ...tabsSyntax, ...scriptingSyntax, ...styleSyntax, @@ -221,6 +232,7 @@ export default defineConfig( 'error', ...networkSyntax, ...navigationSyntax, + ...applyImportSyntax, ...tabsSyntax, ...scriptingSyntax, ], @@ -235,6 +247,7 @@ export default defineConfig( ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, ...scriptingSyntax, ], }, @@ -248,6 +261,7 @@ export default defineConfig( ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, ], }, }, @@ -265,6 +279,7 @@ export default defineConfig( ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, ...tabsSyntax, ...scriptingSyntax, ...fillCallSyntax, @@ -284,6 +299,7 @@ export default defineConfig( ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, ...tabsSyntax, ...scriptingSyntax, ...fillCallSyntax, diff --git a/guard/source-rules.test.ts b/guard/source-rules.test.ts index f41c2f3..e62e6c8 100644 --- a/guard/source-rules.test.ts +++ b/guard/source-rules.test.ts @@ -394,10 +394,26 @@ describe('navigation and injection guard', { timeout: 60_000 }, () => { ["import { browserFillApi } from '../fill/inject';", 'shell/ui/Popup.tsx'], ["import * as inject from '../fill/inject';", 'shell/ui/x.tsx'], ["export { applyToPage } from './inject';", 'shell/fill/index.ts'], + ["export * from './inject';", 'shell/fill/index.ts'], + ["import { applyToPage } from '../fill/inject.js';", 'shell/ui/x.tsx'], ])('rejects the apply import %s in %s', async (code, file) => { const found = await syntaxMessages(code, file); expect(found.some((m) => m.ruleId === 'no-restricted-imports')).toBe(true); }); + it.each([ + ["const m = await import('./inject');", 'shell/fill/other.ts'], + ["const m = await import('./inject');", 'shell/fill/controller.ts'], + ["const m = await import('../fill/inject');", 'shell/ui/x.tsx'], + ])('rejects the dynamic import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect( + found.some( + (m) => + m.message === + 'Only shell/fill/controller.ts may import the fill apply call.', + ), + ).toBe(true); + }); it.each([ ["import { applyToPage } from './inject';", 'shell/fill/controller.ts'], ["import { applyToPage } from './inject';", 'shell/fill/inject.test.ts'], From 2399725eea2b038ddd6cc7368e4e6d4259bc5c50 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:21:58 -0600 Subject: [PATCH 18/48] Add the fill events helper --- shell/fill/page-events.test.ts | 45 ++++++++++++++++++++++++++++++++++ shell/fill/page/events.ts | 5 ++++ 2 files changed, 50 insertions(+) create mode 100644 shell/fill/page-events.test.ts create mode 100644 shell/fill/page/events.ts diff --git a/shell/fill/page-events.test.ts b/shell/fill/page-events.test.ts new file mode 100644 index 0000000..632c688 --- /dev/null +++ b/shell/fill/page-events.test.ts @@ -0,0 +1,45 @@ +// @vitest-environment happy-dom +import { Window } from 'happy-dom'; +import { describe, expect, it } from 'vitest'; +import { notifyChanged } from './page/events'; + +const WATCHED = [ + 'input', + 'change', + 'keydown', + 'keyup', + 'click', + 'focus', + 'blur', + 'submit', +]; + +function build(): { document: Document; input: Element } { + const window = new Window({ url: 'https://example.com/apply' }); + window.document.write('
'); + const document = window.document as unknown as Document; + const input = document.querySelector('input'); + if (!input) throw new Error('fixture has no input'); + return { document, input }; +} + +describe('notifyChanged', () => { + it('dispatches exactly input then change', () => { + const { document, input } = build(); + const events: Event[] = []; + // Capture listeners see focus and blur, which do not bubble. + for (const type of WATCHED) { + document.addEventListener(type, (event) => events.push(event), { + capture: true, + }); + } + + notifyChanged(input); + + expect(events.map((event) => event.type)).toEqual(['input', 'change']); + for (const event of events) { + expect(event.bubbles).toBe(true); + expect(event.target).toBe(input); + } + }); +}); diff --git a/shell/fill/page/events.ts b/shell/fill/page/events.ts new file mode 100644 index 0000000..33b70d2 --- /dev/null +++ b/shell/fill/page/events.ts @@ -0,0 +1,5 @@ +// Tells the page that a field's value was set by the extension. +export function notifyChanged(el: Element): void { + el.dispatchEvent(new Event('input', { bubbles: true })); + el.dispatchEvent(new Event('change', { bubbles: true })); +} From 8dc8435d68a2430f44a55db47a7feb4157ac53c9 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:24:04 -0600 Subject: [PATCH 19/48] Tighten the fill page script guard --- eslint.config.js | 37 +++++++++++++++++---------- guard/source-rules.test.ts | 52 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 13 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 3c19920..8b5d1e6 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -117,17 +117,21 @@ const memberSelectors = (names) => [ const asFillSyntax = (selectors) => selectors.map((selector) => ({ selector, message: FILL_PAGE_MESSAGE })); const fillCallSyntax = asFillSyntax( - callSelectors([ + callSelectors(['createEvent', 'execCommand']), +); +// Plain member access is banned, not just calls, so el.focus.call(el), +// Reflect.apply(el.focus, ...) and const f = el.scrollIntoView are caught too. +const fillActionSyntax = asFillSyntax( + memberSelectors([ 'submit', 'requestSubmit', 'click', 'focus', + 'blur', 'scrollIntoView', - 'createEvent', - 'execCommand', ]), ); -const fillDispatchSyntax = asFillSyntax(callSelectors(['dispatchEvent'])); +const fillDispatchSyntax = asFillSyntax(memberSelectors(['dispatchEvent'])); /** @param {string} pattern */ const eventCtorSelectors = (pattern) => [ `NewExpression[callee.name=${pattern}]`, @@ -135,8 +139,16 @@ const eventCtorSelectors = (pattern) => [ `NewExpression[callee.property.value=${pattern}]`, ]; const fillEventCtorSyntax = asFillSyntax(eventCtorSelectors('/Event$/')); -// Same as above but a bare Event is allowed: the name must have a prefix. -const fillPlainEventCtorSyntax = asFillSyntax(eventCtorSelectors('/.+Event$/')); +// events.ts: every name longer than Event stays banned, and a plain Event is +// banned unless its first argument is the literal 'input' or 'change'. +const notInputOrChange = + ":not([arguments.0.type='Literal'][arguments.0.value=/^(input|change)$/])"; +const fillPlainEventCtorSyntax = asFillSyntax([ + ...eventCtorSelectors('/.+Event$/'), + `NewExpression[callee.name='Event']${notInputOrChange}`, + `NewExpression[callee.property.name='Event']${notInputOrChange}`, + `NewExpression[callee.property.value='Event']${notInputOrChange}`, +]); const fillDomSyntax = asFillSyntax( memberSelectors([ 'createElement', @@ -153,13 +165,10 @@ const fillDomSyntax = asFillSyntax( ); const fillLeakSyntax = asFillSyntax([ `Identifier[name=${callNames(['console', 'localStorage', 'sessionStorage', 'postMessage'])}]`, - ...memberSelectors([ - 'console', - 'localStorage', - 'sessionStorage', - 'postMessage', - 'cookie', - ]), + // The Identifier selector already catches these by name, so a computed + // string is the only member form left to add. + `MemberExpression[property.value=${callNames(['console', 'localStorage', 'sessionStorage', 'postMessage'])}]`, + ...memberSelectors(['cookie']), ]); export default defineConfig( @@ -283,6 +292,7 @@ export default defineConfig( ...tabsSyntax, ...scriptingSyntax, ...fillCallSyntax, + ...fillActionSyntax, ...fillDispatchSyntax, ...fillEventCtorSyntax, ...fillDomSyntax, @@ -303,6 +313,7 @@ export default defineConfig( ...tabsSyntax, ...scriptingSyntax, ...fillCallSyntax, + ...fillActionSyntax, ...fillPlainEventCtorSyntax, ...fillDomSyntax, ...fillLeakSyntax, diff --git a/guard/source-rules.test.ts b/guard/source-rules.test.ts index e62e6c8..61a045a 100644 --- a/guard/source-rules.test.ts +++ b/guard/source-rules.test.ts @@ -505,6 +505,35 @@ describe('fill page guard', { timeout: 60_000 }, () => { "postMessage('x');", "window.postMessage('x', '*');", 'document.cookie;', + "el['dispatchEvent'](e);", + "new window['MouseEvent']('x');", + "el['innerHTML'] = '';", + "document['cookie'];", + "window['postMessage']('x');", + "window['console'];", + "window['localStorage'];", + "window['sessionStorage'];", + 'el.focus.call(el);', + 'const f = el.scrollIntoView;', + 'Reflect.apply(el.focus, el, []);', + 'el.blur();', + "el['focus']();", + "el['blur']();", + "el['scrollIntoView']();", + "el['submit']();", + "el['requestSubmit']();", + "document['createEvent']('Event');", + "document['execCommand']('insertText');", + "document['createElement']('div');", + "el['setAttribute']('a', 'b');", + "el['removeAttribute']('a');", + "el['toggleAttribute']('a');", + 'el.toggleAttribute(a);', + "el['dataset'];", + "el['outerHTML'];", + "el['insertAdjacentHTML']('beforeend', '');", + "el['append'](x);", + "el['appendChild'](x);", ]; describe.each(pageFiles)('in %s', (file) => { it.each(rejected)('rejects %s in the page script', async (code) => { @@ -530,6 +559,29 @@ describe('fill page guard', { timeout: 60_000 }, () => { ); expect(found.some((m) => m.message === fillMessage)).toBe(false); }); + it.each([ + "el.dispatchEvent(new Event('change', { bubbles: true }));", + "new Event('input');", + "el['dispatchEvent'](new Event('input'));", + "el.dispatchEvent(new window.Event('change'));", + ])('events.ts allows %s', async (code) => { + const found = await syntaxMessages(code, eventsFile); + expect(found.some((m) => m.message === fillMessage)).toBe(false); + }); + it.each([ + "new window['InputEvent']('x');", + "new Event('focus');", + 'new Event(type);', + 'new Event();', + "new window.Event('focus');", + "new window['Event']('focus');", + 'el.focus();', + 'el.blur();', + "document['createEvent']('Event');", + ])('events.ts also rejects %s', async (code) => { + const found = await syntaxMessages(code, eventsFile); + expect(found.some((m) => m.message === fillMessage)).toBe(true); + }); it.each([ "new KeyboardEvent('keydown');", "new InputEvent('input');", From b60664c999cbac6753094b995285a39afa5bb52f Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:26:13 -0600 Subject: [PATCH 20/48] Add label resolution for the fill scan --- shell/fill/page-label.test.ts | 151 +++++++++++++++++++++++++++++++++ shell/fill/page/label.ts | 155 ++++++++++++++++++++++++++++++++++ 2 files changed, 306 insertions(+) create mode 100644 shell/fill/page-label.test.ts create mode 100644 shell/fill/page/label.ts diff --git a/shell/fill/page-label.test.ts b/shell/fill/page-label.test.ts new file mode 100644 index 0000000..d825874 --- /dev/null +++ b/shell/fill/page-label.test.ts @@ -0,0 +1,151 @@ +// @vitest-environment happy-dom +import { Window } from 'happy-dom'; +import { describe, expect, it } from 'vitest'; +import { fieldLabel, groupLabel } from './page/label'; + +function load(body: string): Document { + const window = new Window({ url: 'https://example.com/apply' }); + window.document.write(`${body}`); + return window.document as unknown as Document; +} + +const isField = (): boolean => true; + +describe('fieldLabel', () => { + it('aria-labelledby wins over a label for', () => { + const doc = load( + 'Full name', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Full name'); + }); + + it('joins two labelledby ids with a space', () => { + const doc = load( + 'Example RoboticsPhone', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe( + 'Example Robotics Phone', + ); + }); + + it('label for', () => { + const doc = load(''); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Full name'); + }); + + it('wrapping label', () => { + const doc = load(''); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Full name'); + }); + + it("a wrapping label leaves out a nested select's options", () => { + const doc = load( + '', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Country'); + }); + + it('aria-label when there is no label element', () => { + const doc = load(''); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Phone'); + }); + + it('nearest container, Lever shape', () => { + const doc = load( + '
  • Phone
  • ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Phone'); + }); + + it('does not climb past a container with another field', () => { + const doc = load( + '

    Contact

      ' + + '
    • Phone
    • ' + + '
    • Email
    • ' + + '
    ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Phone'); + expect(fieldLabel(doc.getElementById('b')!, isField)).toBe('Email'); + }); + + it('a placeholder is not a label', () => { + const doc = load( + '
    ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe(''); + }); + + it('caps at 300 characters', () => { + const doc = load(``); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('a'.repeat(300)); + }); + + it('trims again when the cut ends on a space', () => { + const doc = load(``); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('a'.repeat(299)); + }); + + it('collapses whitespace and newlines', () => { + const doc = load(''); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe( + 'Full name here', + ); + }); + + it('does not use a label for an element without an id', () => { + const doc = load('
    '); + expect(fieldLabel(doc.querySelector('input')!, isField)).toBe(''); + }); + + it('respects isCandidate when deciding what a container holds', () => { + const doc = load( + '
    Phone
    ', + ); + const notHidden = (o: Element): boolean => + o.getAttribute('type') !== 'hidden'; + expect(fieldLabel(doc.getElementById('a')!, notHidden)).toBe('Phone'); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe(''); + }); +}); + +describe('groupLabel', () => { + it('uses the legend of a fieldset', () => { + const doc = load( + '
    Work authorisation
    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Work authorisation'); + }); + + it('uses aria-labelledby on a radiogroup', () => { + const doc = load( + 'Do you need sponsorship?
    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Do you need sponsorship?'); + }); + + it('uses the question text of a container without the members labels', () => { + const doc = load( + '

    Do you need sponsorship?

    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Do you need sponsorship?'); + }); + + it('leaves out labels that point at a member by id', () => { + const doc = load( + '

    Pick one

    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Pick one'); + }); + + it('does not use a fieldset that holds another field', () => { + const doc = load( + '
    Everything

    Pick one

    ', + ); + const members = [doc.querySelector('input[type=checkbox]')!]; + expect(groupLabel(members, isField)).toBe('Pick one'); + }); +}); diff --git a/shell/fill/page/label.ts b/shell/fill/page/label.ts new file mode 100644 index 0000000..c2dd55c --- /dev/null +++ b/shell/fill/page/label.ts @@ -0,0 +1,155 @@ +import { MAX_LABEL } from '../../../core/src/fill/types'; + +// Finds the question text for a field or a group of fields. Reads the DOM only. + +const SKIPPED = new Set([ + 'input', + 'select', + 'textarea', + 'button', + 'option', + 'script', + 'style', +]); +const FIELDS = 'input, select, textarea'; +const GROUP_ANCESTOR = 'fieldset, [role="group"], [role="radiogroup"]'; + +function tidy(raw: string): string { + return raw.replace(/\s+/g, ' ').trim().slice(0, MAX_LABEL).trim(); +} + +function collect( + node: Node, + left: ReadonlySet, + parts: string[], +): void { + for (const child of Array.from(node.childNodes)) { + if (child.nodeType === 3) { + parts.push(child.textContent ?? ''); + } else if (child.nodeType === 1) { + const el = child as Element; + if (!SKIPPED.has(el.localName) && !left.has(el)) { + collect(el, left, parts); + } + } + } +} + +function textOf(node: Node, left: ReadonlySet = new Set()): string { + const parts: string[] = []; + collect(node, left, parts); + return tidy(parts.join(' ')); +} + +function labelledBy(el: Element): string { + const ids = (el.getAttribute('aria-labelledby') ?? '') + .split(/\s+/) + .filter((id) => id !== ''); + const texts: string[] = []; + for (const id of ids) { + const target = el.ownerDocument.getElementById(id); + if (target) texts.push(textOf(target)); + } + return tidy(texts.filter((t) => t !== '').join(' ')); +} + +function labelsFor(el: Element): Element[] { + const id = el.getAttribute('id') ?? ''; + if (id === '') return []; + return Array.from(el.ownerDocument.querySelectorAll('label')).filter( + (label) => label.getAttribute('for') === id, + ); +} + +function isRoot(el: Element): boolean { + return el.localName === 'form' || el.localName === 'body'; +} + +function holdsOther( + container: Element, + allowed: readonly Element[], + isCandidate: (other: Element) => boolean, +): boolean { + return Array.from(container.querySelectorAll(FIELDS)).some( + (other) => !allowed.includes(other) && isCandidate(other), + ); +} + +// Climbs from the field's parent. Only empty containers are passed over; the +// first one with text wins; one that holds another candidate ends the search. +function containerText( + start: Element | null, + members: readonly Element[], + isCandidate: (other: Element) => boolean, + left: ReadonlySet, +): string { + for (let cur = start; cur && !isRoot(cur); cur = cur.parentElement) { + if (holdsOther(cur, members, isCandidate)) return ''; + if (left.has(cur) || !members.every((m) => cur.contains(m))) continue; + const text = textOf(cur, left); + if (text !== '') return text; + } + return ''; +} + +export function fieldLabel( + el: Element, + isCandidate: (other: Element) => boolean, +): string { + const named = labelledBy(el); + if (named !== '') return named; + + for (const label of labelsFor(el)) { + const text = textOf(label); + if (text !== '') return text; + } + + const wrapping = el.closest('label'); + if (wrapping) { + const text = textOf(wrapping); + if (text !== '') return text; + } + + const aria = tidy(el.getAttribute('aria-label') ?? ''); + if (aria !== '') return aria; + + return containerText(el.parentElement, [el], isCandidate, new Set()); +} + +export function groupLabel( + members: readonly Element[], + isCandidate: (other: Element) => boolean, +): string { + const first = members[0]; + if (!first) return ''; + + for ( + let cur = first.parentElement; + cur && !isRoot(cur); + cur = cur.parentElement + ) { + if (!cur.matches(GROUP_ANCESTOR)) continue; + if (!members.every((m) => cur.contains(m))) continue; + if (holdsOther(cur, members, isCandidate)) continue; + const named = labelledBy(cur); + if (named !== '') return named; + const aria = tidy(cur.getAttribute('aria-label') ?? ''); + if (aria !== '') return aria; + if (cur.localName === 'fieldset') { + const legend = Array.from(cur.children).find( + (child) => child.localName === 'legend', + ); + const text = legend ? textOf(legend) : ''; + if (text !== '') return text; + } + break; + } + + const left = new Set(); + for (const member of members) { + const wrapping = member.closest('label'); + if (wrapping) left.add(wrapping); + for (const label of labelsFor(member)) left.add(label); + } + return containerText(first.parentElement, members, isCandidate, left); +} From 2eb810a7338a8bce36200445631bf18ed1533ee9 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:29:03 -0600 Subject: [PATCH 21/48] Add the fill page scan --- shell/fill/fixtures/autocomplete-only.html | 41 +++ shell/fill/fixtures/greenhouse-like.html | 75 ++++ shell/fill/fixtures/lever-like.html | 77 +++++ shell/fill/fixtures/prefilled.html | 42 +++ shell/fill/page-scan.test.ts | 376 +++++++++++++++++++++ shell/fill/page/scan.ts | 287 ++++++++++++++++ 6 files changed, 898 insertions(+) create mode 100644 shell/fill/fixtures/autocomplete-only.html create mode 100644 shell/fill/fixtures/greenhouse-like.html create mode 100644 shell/fill/fixtures/lever-like.html create mode 100644 shell/fill/fixtures/prefilled.html create mode 100644 shell/fill/page-scan.test.ts create mode 100644 shell/fill/page/scan.ts diff --git a/shell/fill/fixtures/autocomplete-only.html b/shell/fill/fixtures/autocomplete-only.html new file mode 100644 index 0000000..3eafe5b --- /dev/null +++ b/shell/fill/fixtures/autocomplete-only.html @@ -0,0 +1,41 @@ + + + + + Example Robotics - Quick contact + + +
    + + + + + + + + + + + + + + +
    + + diff --git a/shell/fill/fixtures/greenhouse-like.html b/shell/fill/fixtures/greenhouse-like.html new file mode 100644 index 0000000..5912176 --- /dev/null +++ b/shell/fill/fixtures/greenhouse-like.html @@ -0,0 +1,75 @@ + + + + + Example Robotics - Careers + + + +

    Robotics Engineer, Example Robotics

    +
    + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + + +
    +
    + + + +
    + +
    + + diff --git a/shell/fill/fixtures/lever-like.html b/shell/fill/fixtures/lever-like.html new file mode 100644 index 0000000..25ac6ce --- /dev/null +++ b/shell/fill/fixtures/lever-like.html @@ -0,0 +1,77 @@ + + + + + Example Robotics - Apply for Robotics Engineer + + +

    Apply for Robotics Engineer at Example Robotics

    +
    + +
      +
    • + +
    • +
    • + +
    • +
    • +
      Phone
      + +
    • +
    • +
      Current location
      + +
    • +
    • +
      LinkedIn URL
      + +
    • +
    • +
      Resume/CV
      + +
    • +
    • +
      + Are you legally authorized to work in the United States? +
      + +
    • +
    • +
      + Will you now or in the future require visa sponsorship? +
      +
        +
      • + +
      • +
      • + +
      • +
      +
    • +
    • +
      Additional information
      + +
    • +
    + +
    + + diff --git a/shell/fill/fixtures/prefilled.html b/shell/fill/fixtures/prefilled.html new file mode 100644 index 0000000..3e0457d --- /dev/null +++ b/shell/fill/fixtures/prefilled.html @@ -0,0 +1,42 @@ + + + + + Example Robotics - Update your application + + +
    + +
    + + +
    +
    + + +
    +
    + + +
    +
    + Are you over 18? + + +
    +
    + + +
    +
    + + +
    + +
    + + diff --git a/shell/fill/page-scan.test.ts b/shell/fill/page-scan.test.ts new file mode 100644 index 0000000..18c8fba --- /dev/null +++ b/shell/fill/page-scan.test.ts @@ -0,0 +1,376 @@ +// @vitest-environment happy-dom +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { Window } from 'happy-dom'; +import { describe, expect, it } from 'vitest'; +import { toFormScan } from '../../core/src/fill/validate'; +import { scanForm } from './page/scan'; + +function parse(html: string): Document { + const window = new Window({ url: 'https://example.com/jobs/1' }); + window.document.write(html); + return window.document as unknown as Document; +} + +function load(name: string): Document { + return parse( + readFileSync(join(import.meta.dirname, 'fixtures', name), 'utf8'), + ); +} + +const FIXTURES = [ + 'lever-like.html', + 'greenhouse-like.html', + 'autocomplete-only.html', + 'prefilled.html', +]; + +describe('scanForm: lever-like', () => { + const { scan } = scanForm(load('lever-like.html')); + + it('finds nine fields with the right controls', () => { + expect(scan.fields.map((f) => f.control)).toEqual([ + 'text', + 'text', + 'text', + 'custom', + 'text', + 'file', + 'select', + 'choice_group', + 'textarea', + ]); + expect(scan.frames).toEqual([]); + expect(scan.truncated).toBe(false); + }); + + it('reads the labels', () => { + expect(scan.fields.map((f) => f.label)).toEqual([ + 'Full name', + 'Email', + 'Phone', + 'Current location', + 'LinkedIn URL', + 'Resume/CV', + 'Are you legally authorized to work in the United States?', + 'Will you now or in the future require visa sponsorship?', + 'Additional information', + ]); + }); + + it('marks Full name required and nothing else', () => { + expect(scan.fields.map((f) => f.required)).toEqual([ + true, + false, + false, + false, + false, + false, + false, + false, + false, + ]); + }); + + it('reports the select without its placeholder', () => { + const select = scan.fields[6]; + expect(select?.options).toEqual(['Yes', 'No']); + expect(select?.value).toBe(''); + expect(select?.multiple).toBe(false); + }); + + it('reports the checkbox group', () => { + const group = scan.fields[7]; + expect(group?.options).toEqual(['Yes', 'No']); + expect(group?.checked).toEqual([]); + expect(group?.multiple).toBe(true); + }); + + it('never reads the hidden input', () => { + expect(JSON.stringify(scan)).not.toContain('hidden-token-7731'); + }); +}); + +describe('scanForm: greenhouse-like', () => { + const { scan } = scanForm(load('greenhouse-like.html')); + + it('finds nine fields', () => { + expect(scan.fields).toHaveLength(9); + expect(scan.fields.slice(0, 3).map((f) => f.autocomplete)).toEqual([ + 'given-name', + 'family-name', + 'email', + ]); + }); + + it('reads First Name as required', () => { + const first = scan.fields[0]; + expect(['First Name *', 'First Name']).toContain(first?.label); + expect(first?.required).toBe(true); + }); + + it('reports the comboboxes as custom with no value', () => { + const custom = scan.fields.filter((f) => f.control === 'custom'); + expect(custom).toHaveLength(2); + expect(custom.every((f) => f.value === '')).toBe(true); + expect(scan.fields[7]?.control).toBe('custom'); + expect(scan.fields[8]?.control).toBe('custom'); + }); + + it('skips the aria-hidden helpers and keeps the clipped file input', () => { + expect(scan.fields.filter((f) => f.control === 'file')).toHaveLength(1); + expect(scan.fields[4]?.control).toBe('file'); + expect(scan.fields).toHaveLength(9); + }); +}); + +describe('scanForm: autocomplete-only', () => { + const { scan } = scanForm(load('autocomplete-only.html')); + + it('finds nine unlabelled fields', () => { + expect(scan.fields).toHaveLength(9); + expect(scan.fields.every((f) => f.label === '')).toBe(true); + expect(scan.fields.map((f) => f.autocomplete)).toEqual([ + 'name', + 'email', + 'tel', + 'address-line1', + 'address-level2', + 'address-level1', + 'postal-code', + 'country-name', + 'given-name', + ]); + }); + + it('skips card, one-time code and password inputs', () => { + const tokens = scan.fields.map((f) => f.autocomplete); + expect(tokens).not.toContain('cc-number'); + expect(tokens).not.toContain('one-time-code'); + expect(tokens).not.toContain('current-password'); + }); +}); + +describe('scanForm: prefilled', () => { + const { scan } = scanForm(load('prefilled.html')); + + it('reads the values', () => { + expect(scan.fields).toHaveLength(4); + expect(scan.fields[0]?.value).toBe('someone@example.com'); + expect(scan.fields[1]?.value).toBe('555-0100'); + expect(scan.fields[2]?.control).toBe('select'); + expect(scan.fields[2]?.value).toBe('Yes'); + }); + + it('reads the radio group', () => { + const group = scan.fields[3]; + expect(group?.control).toBe('choice_group'); + expect(group?.options).toEqual(['Yes', 'No']); + expect(group?.checked).toEqual([1]); + expect(group?.multiple).toBe(false); + }); + + it('leaves out the read-only and disabled inputs', () => { + const text = JSON.stringify(scan); + expect(text).not.toContain('REF-1'); + expect(text).not.toContain('locked'); + }); +}); + +describe('scanForm: elements line up', () => { + it.each(FIXTURES)('%s', (name) => { + const { scan, elements } = scanForm(load(name)); + expect(elements).toHaveLength(scan.fields.length); + scan.fields.forEach((field, i) => { + expect(field.ref).toBe(i); + expect(elements[i]?.control).toBe(field.control); + if (field.control === 'select' || field.control === 'choice_group') { + expect(elements[i]?.options).toHaveLength(field.options.length); + } + }); + }); + + it('keeps a select placeholder out of both lists', () => { + const { scan, elements } = scanForm(load('lever-like.html')); + expect(scan.fields[6]?.options).toEqual(['Yes', 'No']); + expect( + elements[6]?.options.map((o) => (o as HTMLOptionElement).text), + ).toEqual(['Yes', 'No']); + }); + + it('puts the first group member in el', () => { + const { elements } = scanForm(load('prefilled.html')); + expect((elements[3]?.el as HTMLInputElement).value).toBe('yes'); + }); +}); + +describe('scanForm: hidden fields', () => { + it('skips fields hidden by an ancestor', () => { + const doc = parse(`
    + + +
    +
    +
    + +
    `); + expect(scanForm(doc).scan.fields.map((f) => f.label)).toEqual(['Six']); + }); + + it('keeps a file input that is hidden by display', () => { + const doc = parse( + '
    ', + ); + const { scan } = scanForm(doc); + expect(scan.fields).toHaveLength(1); + expect(scan.fields[0]?.control).toBe('file'); + }); +}); + +describe('scanForm: candidates and control', () => { + it('uses an allow list of input types', () => { + const doc = parse(`
    + + + + + + + + + +
    `); + const { scan } = scanForm(doc); + expect(scan.fields.map((f) => f.label)).toEqual([ + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + ]); + expect(scan.fields[3]?.control).toBe('date'); + }); + + it('treats aria-haspopup, aria-autocomplete and role as custom', () => { + const doc = parse(`
    + + + + + +
    `); + expect(scanForm(doc).scan.fields.map((f) => f.control)).toEqual([ + 'custom', + 'text', + 'text', + 'custom', + 'custom', + ]); + }); + + it('skips a field in a disabled fieldset', () => { + const doc = parse( + '
    ', + ); + expect(scanForm(doc).scan.fields.map((f) => f.label)).toEqual(['b']); + }); + + it('skips new-password and cc- autocomplete, keeps the rest', () => { + const doc = parse(`
    + + + + +
    `); + const { scan } = scanForm(doc); + expect(scan.fields.map((f) => f.label)).toEqual(['d']); + expect(scan.fields[0]?.autocomplete).toBe('off'); + }); + + it('reads aria-required and trims values', () => { + const doc = parse( + '
    ', + ); + const { scan } = scanForm(doc); + expect(scan.fields[0]?.required).toBe(true); + expect(scan.fields[0]?.value).toBe('hi'); + expect(scan.fields[1]?.value).toBe(''); + }); + + it('reads a multi-select and a checked group of one', () => { + const doc = parse(`
    + + +
    `); + const { scan } = scanForm(doc); + expect(scan.fields[0]?.multiple).toBe(true); + expect(scan.fields[1]?.control).toBe('choice_group'); + expect(scan.fields[1]?.options).toEqual(['Agree']); + expect(scan.fields[1]?.checked).toEqual([0]); + }); + + it('falls back to the value attribute for an option label', () => { + const doc = parse( + '
    ', + ); + expect(scanForm(doc).scan.fields[0]?.options).toEqual(['alpha', 'beta']); + }); + + it('gives a select with only a placeholder chosen an empty value', () => { + const doc = parse( + '
    ', + ); + expect(scanForm(doc).scan.fields[0]?.value).toBe(''); + }); +}); + +describe('scanForm: caps', () => { + it('stops at 200 fields', () => { + const inputs = Array.from( + { length: 250 }, + (_, i) => ``, + ).join(''); + const { scan, elements } = scanForm(parse(`
    ${inputs}
    `)); + expect(scan.fields).toHaveLength(200); + expect(elements).toHaveLength(200); + expect(scan.truncated).toBe(true); + }); + + it('is not truncated at exactly 200 fields', () => { + const inputs = Array.from( + { length: 200 }, + (_, i) => ``, + ).join(''); + expect(scanForm(parse(`
    ${inputs}
    `)).scan.truncated).toBe( + false, + ); + }); + + it('cuts a select at 50 options in both lists', () => { + const options = Array.from( + { length: 80 }, + (_, i) => ``, + ).join(''); + const { scan, elements } = scanForm( + parse(`
    `), + ); + expect(scan.fields[0]?.options).toHaveLength(50); + expect(elements[0]?.options).toHaveLength(50); + expect(scan.fields[0]?.optionsTruncated).toBe(true); + }); + + it('cuts long values at 500 characters', () => { + const doc = parse( + `
    `, + ); + expect(scanForm(doc).scan.fields[0]?.value).toHaveLength(500); + }); +}); + +describe('scanForm: validation', () => { + it.each(FIXTURES)('%s passes toFormScan unchanged', (name) => { + const { scan } = scanForm(load(name)); + expect(toFormScan(scan)).toEqual(scan); + }); +}); diff --git a/shell/fill/page/scan.ts b/shell/fill/page/scan.ts new file mode 100644 index 0000000..b061c8f --- /dev/null +++ b/shell/fill/page/scan.ts @@ -0,0 +1,287 @@ +import { isPlaceholderOption } from '../../../core/src/fill/normalize'; +import { + MAX_AUTOCOMPLETE, + MAX_FIELDS, + MAX_OPTIONS, + MAX_VALUE, + type ControlKind, + type FormScan, + type ScannedField, +} from '../../../core/src/fill/types'; +import { fieldLabel, groupLabel } from './label'; + +export interface FieldElements { + control: ControlKind; + /** The element, or the first member of a group. */ + el: Element; + /** The