fwdloop 0.21.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/fwdloop +85 -34
- package/package.json +4 -3
- package/src/ask.js +20 -4
- package/src/audit-fold.js +5 -1
- package/src/authoring.js +36 -6
- package/src/canrun.js +5 -0
- package/src/checked.js +32 -4
- package/src/cited-record.js +138 -0
- package/src/cited-source.js +49 -0
- package/src/citedcheck.js +321 -0
- package/src/citedwords.js +197 -0
- package/src/closers.js +37 -198
- package/src/csv.js +69 -12
- package/src/ctx-tools.js +2 -14
- package/src/declaration.js +143 -5
- package/src/diary.js +2 -2
- package/src/docx.js +16 -2
- package/src/draft-steps.js +1 -1
- package/src/drafter.js +322 -33
- package/src/flow.js +33 -7
- package/src/flowmodel.js +21 -0
- package/src/input-facts.js +20 -3
- package/src/model-step.js +38 -21
- package/src/pageask.js +136 -0
- package/src/pagebits.js +107 -0
- package/src/pagedropwords.js +171 -0
- package/src/pagedry.js +120 -0
- package/src/pagefetch.js +164 -0
- package/src/pagelook.js +155 -0
- package/src/pagemap.js +55 -0
- package/src/pageplace.js +103 -0
- package/src/pagerules.js +318 -0
- package/src/panel/author.js +43 -21
- package/src/panel/authorcard.js +20 -3
- package/src/panel/authorflows.js +21 -15
- package/src/panel/authorstart.js +2 -4
- package/src/panel/authortrigger.js +14 -4
- package/src/panel/data.js +102 -6
- package/src/panel/index.html +321 -12
- package/src/panel/result.js +301 -0
- package/src/panel/server.js +27 -3
- package/src/primitives.js +2 -3
- package/src/provider.js +5 -2
- package/src/redact.js +17 -0
- package/src/runner.js +102 -14
- package/src/schedule.js +3 -3
- package/src/setup.js +16 -1
- package/src/sheet-record.js +57 -0
- package/src/sheetblock.js +170 -0
- package/src/sheetchecks.js +206 -0
- package/src/sheetclaims.js +78 -0
- package/src/sheetfind.js +50 -0
- package/src/sheetlook.js +157 -0
- package/src/sheetoffer.js +125 -0
- package/src/sheetrun.js +105 -0
- package/src/signed-text.js +11 -1
- package/src/thinking.js +1 -1
- package/src/try-checks.js +12 -0
- package/src/types.js +4 -11
- package/types/ask.d.ts +2 -1
- package/types/authoring.d.ts +19 -2
- package/types/checked.d.ts +19 -3
- package/types/cited-record.d.ts +21 -0
- package/types/cited-source.d.ts +18 -0
- package/types/citedcheck.d.ts +95 -0
- package/types/citedwords.d.ts +97 -0
- package/types/closers.d.ts +37 -10
- package/types/csv.d.ts +25 -4
- package/types/ctx-tools.d.ts +0 -1
- package/types/declaration.d.ts +20 -1
- package/types/docx.d.ts +14 -0
- package/types/drafter.d.ts +264 -8
- package/types/flow.d.ts +21 -0
- package/types/flowmodel.d.ts +15 -0
- package/types/input-facts.d.ts +12 -2
- package/types/model-step.d.ts +40 -19
- package/types/pageask.d.ts +75 -0
- package/types/pagebits.d.ts +32 -0
- package/types/pagedropwords.d.ts +40 -0
- package/types/pagedry.d.ts +38 -0
- package/types/pagefetch.d.ts +86 -0
- package/types/pagelook.d.ts +75 -0
- package/types/pagemap.d.ts +31 -0
- package/types/pageplace.d.ts +22 -0
- package/types/pagerules.d.ts +86 -0
- package/types/panel/authorcard.d.ts +4 -1
- package/types/panel/authorflows.d.ts +2 -0
- package/types/panel/data.d.ts +26 -0
- package/types/panel/result.d.ts +156 -0
- package/types/provider.d.ts +3 -1
- package/types/redact.d.ts +1 -0
- package/types/runner.d.ts +162 -9
- package/types/schedule.d.ts +0 -11
- package/types/setup.d.ts +13 -0
- package/types/sheet-record.d.ts +24 -0
- package/types/sheetblock.d.ts +116 -0
- package/types/sheetchecks.d.ts +70 -0
- package/types/sheetclaims.d.ts +26 -0
- package/types/sheetfind.d.ts +46 -0
- package/types/sheetlook.d.ts +120 -0
- package/types/sheetoffer.d.ts +25 -0
- package/types/sheetrun.d.ts +35 -0
- package/types/thinking.d.ts +1 -1
- package/types/types.d.ts +27 -14
package/src/pagedry.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/pagedry.js@c550dc8 (c61d227 + dryReadPhrases) (adapted: the REAL checker here is fwdloop's run-time `checkCited`, src/citedcheck.js, fed the fact exactly as it would be signed, `factsOfLook`).
|
|
2
|
+
// "CAN IT READ" (F241). After the page rules, a $0 dry read asks of each kept money fact whether the run-time checker can read a price on the page's own
|
|
3
|
+
// result lines. For every result line it checks an HONEST claim (quote = that line, value = the line's amount) with `checkCited`, the one reader the run
|
|
4
|
+
// itself uses - no copy of its logic here. A fact that reads no result line is dropped as `reads-no-result` and shows under Not checked.
|
|
5
|
+
// Throws away: nothing silently (the drop is returned). Third outcomes: a checker that stops (a fault) counts as "did not read" for that line.
|
|
6
|
+
// No limits, no counts, no pass bar: only "can it read". No I/O, no clock, no model. The caller is src/pagelook.js `lookAtPage`.
|
|
7
|
+
|
|
8
|
+
import { checkCited, factsOfLook } from './citedcheck.js';
|
|
9
|
+
import { linesOf } from './pagerules.js';
|
|
10
|
+
|
|
11
|
+
/** @typedef {import('./pagerules.js').KeptFact} KeptFact @typedef {import('./pagerules.js').Dropped} Dropped */
|
|
12
|
+
|
|
13
|
+
/** a number as the page writes it, thousands commas allowed: \d[\d,]*(?:\.\d+)? (written out as literals - this repo bans dynamic patterns in src/) */
|
|
14
|
+
const AFTER_LABEL = /^\s*(?:[$€£]\s*)?(\d[\d,]*(?:\.\d+)?)/;
|
|
15
|
+
const BEFORE_UNIT = /(\d[\d,]*(?:\.\d+)?)\s*$/;
|
|
16
|
+
/** the name every dry-read claim is made under (the checker only needs one name; the fact's own is not read) */
|
|
17
|
+
const CLAIM = 'price';
|
|
18
|
+
const SOURCE = 'page';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The result lines of a kept money fact: with a label, every page line where a kept label is followed by a number (one sign between allowed);
|
|
22
|
+
* with no label (U1 moved it to a unit, e.g. "€533 total"), every line where a number is followed by a kept unit.
|
|
23
|
+
* @param {string} text @param {KeptFact} k @returns {{quote: string, value: string}[]}
|
|
24
|
+
*/
|
|
25
|
+
export function moneyResultLines(text, k) {
|
|
26
|
+
const raw = text.split('\n');
|
|
27
|
+
const squashed = linesOf(text);
|
|
28
|
+
/** @type {{quote: string, value: string}[]} */
|
|
29
|
+
const out = [];
|
|
30
|
+
squashed.forEach((ln, i) => {
|
|
31
|
+
/** @type {string|undefined} */
|
|
32
|
+
let amount;
|
|
33
|
+
if (k.words.length) {
|
|
34
|
+
for (const w of k.words) {
|
|
35
|
+
for (let at = ln.indexOf(w); at !== -1 && amount === undefined; at = ln.indexOf(w, at + w.length)) amount = AFTER_LABEL.exec(ln.slice(at + w.length))?.[1];
|
|
36
|
+
if (amount !== undefined) break;
|
|
37
|
+
}
|
|
38
|
+
} else {
|
|
39
|
+
for (const u of k.unit ?? []) {
|
|
40
|
+
for (let at = ln.indexOf(u); at !== -1 && amount === undefined; at = ln.indexOf(u, at + u.length)) amount = BEFORE_UNIT.exec(ln.slice(0, at))?.[1];
|
|
41
|
+
if (amount !== undefined) break;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (amount !== undefined) out.push({ quote: raw[i].trim(), value: amount.replace(/,/g, '') });
|
|
45
|
+
});
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The fact as the drafter would sign it (same function: `factsOfLook`), under the one claim name, with no number rule: only "can it read".
|
|
51
|
+
* @param {KeptFact} k @returns {Record<string, any>}
|
|
52
|
+
*/
|
|
53
|
+
const signedOf = (k) => factsOfLook({ name: CLAIM, shape: k.shape, words: k.words, ...(k.unit ? { unit: k.unit } : {}), ...(k.currency ? { currency: k.currency } : {}) })[0];
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Dry-read every kept money fact; drop (as `reads-no-result`) the ones whose forms read no result line. Other facts pass through untouched.
|
|
57
|
+
* @param {string} text the frozen page text @param {KeptFact[]} facts what the page rules kept
|
|
58
|
+
* @returns {Promise<{facts: KeptFact[], dropped: Dropped[], reads: Record<string, number>, results: Record<string, number>}>}
|
|
59
|
+
* `reads` / `results` = result lines the checker read / lines found, per fact name (for tests and reports; no verdict derives from the numbers)
|
|
60
|
+
*/
|
|
61
|
+
export async function dryReadMoney(text, facts) {
|
|
62
|
+
/** @type {KeptFact[]} */
|
|
63
|
+
const kept = [];
|
|
64
|
+
/** @type {Dropped[]} */
|
|
65
|
+
const dropped = [];
|
|
66
|
+
/** @type {Record<string, number>} */
|
|
67
|
+
const reads = {};
|
|
68
|
+
/** @type {Record<string, number>} */
|
|
69
|
+
const results = {};
|
|
70
|
+
for (const k of facts) {
|
|
71
|
+
if (k.shape !== 'money') { kept.push(k); continue; }
|
|
72
|
+
const part = { source: SOURCE, facts: [signedOf(k)] };
|
|
73
|
+
const lines = moneyResultLines(text, k);
|
|
74
|
+
let n = 0;
|
|
75
|
+
for (const r of lines) {
|
|
76
|
+
const g = await checkCited({ part, text, results: [{ quote: r.quote, values: { [CLAIM]: r.value } }] });
|
|
77
|
+
if (g.verdict === 'green') n += 1;
|
|
78
|
+
}
|
|
79
|
+
reads[k.name] = n;
|
|
80
|
+
results[k.name] = lines.length;
|
|
81
|
+
if (n > 0) { kept.push(k); continue; }
|
|
82
|
+
dropped.push({ line: k.line, ...(k.forRule === undefined ? {} : { rule: k.forRule }), fact: k.name, reason: 'reads-no-result' });
|
|
83
|
+
}
|
|
84
|
+
return { facts: kept, dropped, reads, results };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The same "can it read" for PHRASE facts (bareloop c550dc8; our failure: m10-walk-flights-3, "Rome" was on the page only in "Track prices from Madrid to
|
|
89
|
+
* Rome" switches, in none of the 18 result lines, so no result could ever say it). A kept phrase fact is read against the page's RESULT LINES = the lines
|
|
90
|
+
* the job's kept money facts read (`moneyResultLines`), each checked as an honest claim by the run's own `checkCited` (quote = that line; a phrase has no
|
|
91
|
+
* value to write). A phrase that reads no result line is dropped whole as `phrase-no-result` and shows under Not checked. With no kept money fact the
|
|
92
|
+
* result lines are unknown, so phrase facts pass through untouched (nothing is guessed about what a result is).
|
|
93
|
+
* Throws away: nothing silently (the drop is returned). Third outcomes: a checker that stops counts as "did not read" for that line.
|
|
94
|
+
* @param {string} text the frozen page text @param {KeptFact[]} facts what the money dry read kept
|
|
95
|
+
* @returns {Promise<{facts: KeptFact[], dropped: Dropped[], reads: Record<string, number>}>} `reads` = result lines that said the phrase, per fact name
|
|
96
|
+
*/
|
|
97
|
+
export async function dryReadPhrases(text, facts) {
|
|
98
|
+
/** @type {Set<string>} */
|
|
99
|
+
const quotes = new Set();
|
|
100
|
+
for (const k of facts) if (k.shape === 'money') for (const r of moneyResultLines(text, k)) quotes.add(r.quote);
|
|
101
|
+
/** @type {KeptFact[]} */
|
|
102
|
+
const kept = [];
|
|
103
|
+
/** @type {Dropped[]} */
|
|
104
|
+
const dropped = [];
|
|
105
|
+
/** @type {Record<string, number>} */
|
|
106
|
+
const reads = {};
|
|
107
|
+
for (const k of facts) {
|
|
108
|
+
if (k.shape !== 'phrase' || quotes.size === 0 || !k.words.length) { kept.push(k); continue; }
|
|
109
|
+
const part = { source: SOURCE, facts: factsOfLook({ name: CLAIM, shape: 'phrase', words: [k.words[0]] }) };
|
|
110
|
+
let n = 0;
|
|
111
|
+
for (const quote of quotes) {
|
|
112
|
+
const g = await checkCited({ part, text, results: [{ quote, values: {} }] });
|
|
113
|
+
if (g.verdict === 'green') n += 1;
|
|
114
|
+
}
|
|
115
|
+
reads[k.name] = n;
|
|
116
|
+
if (n > 0) { kept.push(k); continue; }
|
|
117
|
+
dropped.push({ line: k.line, ...(k.forRule === undefined ? {} : { rule: k.forRule }), fact: k.name, other: k.words[0], reason: 'phrase-no-result' });
|
|
118
|
+
}
|
|
119
|
+
return { facts: kept, dropped, reads };
|
|
120
|
+
}
|
package/src/pagefetch.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/pagefetch.js@56dc096 (adapted: secret check uses src/redact.js)
|
|
2
|
+
// URL inputs (PART 1c, docs/product/ITEM33-BUILD.md "4. URL inputs" + live fix L1, PRD item 33 RF21/RF22): an Inputs line may be a web
|
|
3
|
+
// address the person pastes (a results page). bareloop fetches it with barebrowse, READ ONLY, headless and incognito, as published:
|
|
4
|
+
//
|
|
5
|
+
// page = await connect({ incognito: true, blockPrivateNetwork: true })
|
|
6
|
+
// await page.goto(url); await page.waitForNetworkIdle({ idle, timeout }); await page.snapshot({ mode: 'act' })
|
|
7
|
+
//
|
|
8
|
+
// L1: one-shot `browse()` snapshots at load, before the page's own scripts fill a results list (the same URL gave 77,951 / 8,801 / 719
|
|
9
|
+
// chars). So we wait for the network to go quiet (bounded) before the snapshot. Generic: no site selector. The snapshot mode is the one
|
|
10
|
+
// proven in step 0 ('read' and 'full' returned almost nothing from a results page). The text that comes back is the input. An empty
|
|
11
|
+
// fetch is a plain-words stop, never a silent empty input. Nothing here touches a model.
|
|
12
|
+
import { readFileSync } from 'node:fs';
|
|
13
|
+
import { dirname, join } from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { redactSecrets } from './redact.js';
|
|
16
|
+
|
|
17
|
+
/** the session options (incognito: no auth ever enters; blockPrivateNetwork: SSRF guard); ONE frozen object so a test can pin them */
|
|
18
|
+
export const CONNECT_OPTIONS = Object.freeze({ incognito: true, blockPrivateNetwork: true });
|
|
19
|
+
/** the snapshot options step 0 proved */
|
|
20
|
+
export const SNAPSHOT_OPTIONS = Object.freeze({ mode: 'act' });
|
|
21
|
+
/** the page's network must be quiet this long (ms) before we read it: long enough to span the gap between a page's first load and the
|
|
22
|
+
* script requests that fill the results, short enough not to stretch a plain page */
|
|
23
|
+
export const NETWORK_IDLE_MS = 1500;
|
|
24
|
+
/** the most we wait for the network to go quiet (ms); a page that never settles (polling, streaming) is read as it stands after this */
|
|
25
|
+
export const NETWORK_IDLE_TIMEOUT_MS = 20_000;
|
|
26
|
+
/** the most we wait for the page to load at all (ms) */
|
|
27
|
+
export const GOTO_TIMEOUT_MS = 30_000;
|
|
28
|
+
/** a page that comes back with fewer characters than this (after trimming) is treated as "nothing came back" */
|
|
29
|
+
export const MIN_PAGE_CHARS = 200;
|
|
30
|
+
/** the page text left after the site's own header, menus and footer are taken out must hold at least this many characters, or the page is
|
|
31
|
+
* "only site chrome" (L2: a 719-character fetch of a site's header and sign-in passed the 200-character floor) */
|
|
32
|
+
export const MIN_CONTENT_CHARS = 100;
|
|
33
|
+
/** the page reader's landmark roles for a site's own chrome (the ARIA names of header, menu and footer); everything under one is not the page's content */
|
|
34
|
+
const CHROME_ROLES = new Set(['banner', 'navigation', 'contentinfo']);
|
|
35
|
+
/** our own deadline around one whole fetch (a hung browser leaves no trace; this is the only thing that fires on the absence of an answer) */
|
|
36
|
+
export const PAGE_FETCH_TIMEOUT_MS = 90_000;
|
|
37
|
+
|
|
38
|
+
/** @param {unknown} v @returns {boolean} an http(s) address (the one spelling of "this Inputs value is a web address") */
|
|
39
|
+
export function isWebUrl(v) {
|
|
40
|
+
return typeof v === 'string' && /^https?:\/\//i.test(v.trim());
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** M10 am3: the web pages a signed job names, role -> address (`source <role> = page:<address>`). The ONE reader of which roles are pages and what their signed address is.
|
|
44
|
+
* @param {{sources?: Array<{role: string, kind?: string, path: string}>}} arbiter @returns {Record<string, string>} */
|
|
45
|
+
export function pageAddressesOf(arbiter) {
|
|
46
|
+
return Object.fromEntries((arbiter?.sources ?? []).filter((s) => s.kind === 'page').map((s) => [s.role, s.path]));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** M10 am3: why a run may not name another address for a page input (the signed address is the job's; a different one is a changed job). @param {string} role @param {string} signed */
|
|
50
|
+
export function pageAddressRefusal(role, signed) {
|
|
51
|
+
return `the input "${role}" is a web page signed as ${signed}; a run cannot name a different address (a changed address is a changed job, a new workflow). Nothing started.`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* How much of a fetched page is the page's own content: the snapshot's header lines (url, size note, hint) and every part of the tree
|
|
56
|
+
* under a banner / navigation / contentinfo landmark are taken out, the page reader's bracketed tags are removed, and what is left is
|
|
57
|
+
* counted. Generic - no site names, only the ARIA landmark roles. Text that is not a snapshot tree (a plain file) has no landmark, so it
|
|
58
|
+
* counts whole.
|
|
59
|
+
* @param {string} text @returns {number}
|
|
60
|
+
*/
|
|
61
|
+
export function pageContentChars(text) {
|
|
62
|
+
const lines = String(text ?? '').split('\n');
|
|
63
|
+
let skipIndent = -1;
|
|
64
|
+
let n = 0;
|
|
65
|
+
let head = true;
|
|
66
|
+
for (const raw of lines) {
|
|
67
|
+
if (head && (/^url: /.test(raw) || /^[\d,]+ chars → /.test(raw) || /^hint: /.test(raw))) continue;
|
|
68
|
+
head = false;
|
|
69
|
+
const m = /^(\s*)- ([A-Za-z_]+)\b/.exec(raw);
|
|
70
|
+
const indent = m ? m[1].length : raw.length - raw.trimStart().length;
|
|
71
|
+
if (skipIndent >= 0) {
|
|
72
|
+
if (raw.trim() === '' || indent > skipIndent) continue;
|
|
73
|
+
skipIndent = -1;
|
|
74
|
+
}
|
|
75
|
+
if (m && CHROME_ROLES.has(m[2])) { skipIndent = indent; continue; }
|
|
76
|
+
n += raw.replace(/\[[A-Za-z]+=[^\]\s]*\]/g, ' ').replace(/^\s*-\s*/, '').replace(/\s+/g, ' ').trim().length;
|
|
77
|
+
}
|
|
78
|
+
return n;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @typedef {{goto: (url: string, timeout?: number) => Promise<void>, waitForNetworkIdle: (o?: {idle?: number, timeout?: number}) => Promise<void>,
|
|
83
|
+
* snapshot: (o?: {mode?: string}) => Promise<string>, close: () => Promise<void>}} FetchPage the part of barebrowse's page handle the fetch uses
|
|
84
|
+
*/
|
|
85
|
+
|
|
86
|
+
/** the oldest barebrowse that honours CONNECT_OPTIONS (incognito, blockPrivateNetwork); an older one would drop both guards without a word */
|
|
87
|
+
export const MIN_BAREBROWSE = [0, 21, 0];
|
|
88
|
+
|
|
89
|
+
/** @param {string} v @returns {boolean} true when `v` (x.y.z) is at least MIN_BAREBROWSE */
|
|
90
|
+
export function barebrowseNewEnough(v) {
|
|
91
|
+
const p = String(v).split('.').map((n) => parseInt(n, 10));
|
|
92
|
+
for (let i = 0; i < 3; i += 1) {
|
|
93
|
+
const a = Number.isFinite(p[i]) ? p[i] : 0;
|
|
94
|
+
if (a !== MIN_BAREBROWSE[i]) return a > MIN_BAREBROWSE[i];
|
|
95
|
+
}
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** barebrowse is an optional peer: loaded here, on first use, and refused by name when missing or too old. */
|
|
100
|
+
async function loadConnect() {
|
|
101
|
+
try {
|
|
102
|
+
const mod = /** @type {any} */ (await import('barebrowse'));
|
|
103
|
+
const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.resolve('barebrowse'))), '..', 'package.json'), 'utf8'));
|
|
104
|
+
if (!barebrowseNewEnough(pkg.version)) return { ok: /** @type {const} */ (false), error: `the page reader (barebrowse ${pkg.version}) is too old: a web page needs 0.21.0 or newer, which keeps the browser private and off the local network` };
|
|
105
|
+
return { ok: /** @type {const} */ (true), connect: /** @type {(opts: Record<string, any>) => Promise<FetchPage>} */ (mod.connect) };
|
|
106
|
+
} catch (e) { return { ok: /** @type {const} */ (false), error: `the page reader (barebrowse) could not be loaded: ${/** @type {Error} */ (e).message}` }; }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Fetch one page's text. `connect` is injected (a test never reaches the network); the default is barebrowse's own `connect`.
|
|
111
|
+
* @param {string} url
|
|
112
|
+
* @param {{connect?: (opts: Record<string, any>) => Promise<FetchPage>, timeoutMs?: number, idleMs?: number, idleTimeoutMs?: number, closeWaitMs?: number}} [o]
|
|
113
|
+
* @returns {Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>} `error` is plain words, without a spend line
|
|
114
|
+
*/
|
|
115
|
+
export async function fetchPageText(url, { connect, timeoutMs = PAGE_FETCH_TIMEOUT_MS, idleMs = NETWORK_IDLE_MS, idleTimeoutMs = NETWORK_IDLE_TIMEOUT_MS, closeWaitMs = 3000 } = {}) {
|
|
116
|
+
let u;
|
|
117
|
+
try { u = new URL(url.trim()); } catch { return { ok: false, error: `${url} is not a web address fwdloop can read` }; }
|
|
118
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') return { ok: false, error: `${url} is not an http or https address` };
|
|
119
|
+
if (redactSecrets(u.href) !== u.href) return { ok: false, error: 'the web address carries a known secret shape - secrets never enter a job' };
|
|
120
|
+
if (u.username !== '' || u.password !== '') return { ok: false, error: 'a web address with a user name or password in it is refused - fwdloop reads a page with no credentials at all' };
|
|
121
|
+
/** @type {(opts: Record<string, any>) => Promise<FetchPage>} */
|
|
122
|
+
let open;
|
|
123
|
+
if (connect) open = connect;
|
|
124
|
+
else {
|
|
125
|
+
const loaded = await loadConnect();
|
|
126
|
+
if (!loaded.ok) return loaded;
|
|
127
|
+
open = loaded.connect;
|
|
128
|
+
}
|
|
129
|
+
/** @type {NodeJS.Timeout|undefined} */
|
|
130
|
+
let timer;
|
|
131
|
+
/** @type {Promise<FetchPage>|undefined} */
|
|
132
|
+
let opening;
|
|
133
|
+
try {
|
|
134
|
+
opening = open({ ...CONNECT_OPTIONS });
|
|
135
|
+
const page = opening;
|
|
136
|
+
const text = await Promise.race([
|
|
137
|
+
(async () => {
|
|
138
|
+
const p = await page;
|
|
139
|
+
await p.goto(u.href, GOTO_TIMEOUT_MS);
|
|
140
|
+
// bounded: a page that never goes quiet (polling, streaming) is read as it stands (bareloop); the size and chrome floors below then decide
|
|
141
|
+
try { await p.waitForNetworkIdle({ idle: idleMs, timeout: idleTimeoutMs }); } catch { /* read what is there */ }
|
|
142
|
+
return p.snapshot({ ...SNAPSHOT_OPTIONS });
|
|
143
|
+
})(),
|
|
144
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`no answer inside ${Math.round(timeoutMs / 1000)} seconds`)), timeoutMs); }),
|
|
145
|
+
]);
|
|
146
|
+
if (typeof text !== 'string') return { ok: false, error: `${u.href} did not come back as text` };
|
|
147
|
+
if (/\[BOT CHALLENGE DETECTED\]/.test(text)) return { ok: false, error: `${u.href} asked for a human check (a bot challenge), so the page could not be read` };
|
|
148
|
+
const size = text.trim().length;
|
|
149
|
+
if (size < MIN_PAGE_CHARS) return { ok: false, error: `${u.href} came back with ${size === 0 ? 'no text' : `only ${size} characters of text`} (less than ${MIN_PAGE_CHARS}) - the page did not load, or holds nothing to read` };
|
|
150
|
+
if (pageContentChars(text) < MIN_CONTENT_CHARS) return { ok: false, error: `${u.href} came back with only the site's own header and menus - the page did not load its content, so there is nothing to read` };
|
|
151
|
+
return { ok: true, text, url: u.href };
|
|
152
|
+
} catch (e) {
|
|
153
|
+
return { ok: false, error: `${u.href} could not be read: ${/** @type {Error} */ (e)?.message ?? String(e)}` };
|
|
154
|
+
} finally {
|
|
155
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
156
|
+
// always close the browser, also when the deadline fired while it was still starting or loading
|
|
157
|
+
if (opening) {
|
|
158
|
+
/** @type {NodeJS.Timeout|undefined} */
|
|
159
|
+
let w;
|
|
160
|
+
await Promise.race([opening.then((p) => p.close()).catch(() => {}), new Promise((r) => { w = setTimeout(r, closeWaitMs); })]);
|
|
161
|
+
if (w !== undefined) clearTimeout(w);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
package/src/pagelook.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// M10 item 3 ("the source's own words"): the page-word look for ONE page input. One AI call names the page's own words for each job rule
|
|
2
|
+
// (bareloop's prompt, src/pagemap.js); code keeps only words the saved page proves (bareloop's rules, src/pagerules.js) plus one rule of ours:
|
|
3
|
+
// a label that reads no value is dropped. The AI never grades; every drop is written once, from the one table (src/pagedropwords.js).
|
|
4
|
+
//
|
|
5
|
+
// Throws away: nothing silently. A word, fact or rule that a rule removes comes back in `dropped` with its reason code and as a Not-checked line.
|
|
6
|
+
// Third outcomes: an unreadable answer twice (stop, MAP_UNREADABLE), a cut-off answer (unreadable), a failed call (stop, its reason).
|
|
7
|
+
// The model call itself is the caller's (`callModel`): the drafter meters every round through it.
|
|
8
|
+
|
|
9
|
+
import { mapPrompt, parseMapAnswer, MAP_UNREADABLE } from './pagemap.js';
|
|
10
|
+
import { applyPageRules } from './pagerules.js';
|
|
11
|
+
import { dryReadMoney, dryReadPhrases } from './pagedry.js';
|
|
12
|
+
import { dropRows, dropLine } from './pagedropwords.js';
|
|
13
|
+
import { lineRules, squash } from './pagebits.js';
|
|
14
|
+
import { placePhrases } from './pageplace.js';
|
|
15
|
+
import { ruleWords } from './pageask.js';
|
|
16
|
+
|
|
17
|
+
/** Our rule (signed item 3): a kept money / number / time label must have a value of its kind written right AFTER it on some page line. */
|
|
18
|
+
const READ = {
|
|
19
|
+
money: /^\s*[$€£]?\s*\d[\d,]*(?:\.\d+)?/,
|
|
20
|
+
number: /^\s*\d[\d,]*(?:\.\d+)?/,
|
|
21
|
+
time: /^\s*\d{1,2}:\d{2}[\s\u202f\u00a0]?[AaPp][Mm]/, // h:mm AM/PM, as bareloop's own time reader (src/pagerules.js READ)
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** @param {string[]} lines squashed page lines @param {string} label @param {'money'|'number'|'time'} shape @returns {boolean} */
|
|
25
|
+
function readsValue(lines, label, shape) {
|
|
26
|
+
const p = squash(label).trim();
|
|
27
|
+
if (p === '') return false;
|
|
28
|
+
for (const ln of lines) for (let i = ln.indexOf(p); i !== -1; i = ln.indexOf(p, i + p.length)) if (READ[shape].test(ln.slice(i + p.length))) return true;
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @param {unknown} v @returns {unknown} the list with a repeated entry once (first kept); anything else as it came */
|
|
33
|
+
const once = (v) => (Array.isArray(v) ? [...new Set(v)] : v);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A unit, currency or label listed twice in one list is one entry: removed before the rules run, so no rule can compare a word with itself.
|
|
37
|
+
* @param {any} mapping @returns {any}
|
|
38
|
+
*/
|
|
39
|
+
export function dedupeMap(mapping) {
|
|
40
|
+
if (!mapping || !Array.isArray(mapping.facts)) return mapping;
|
|
41
|
+
return { ...mapping, facts: mapping.facts.map((f) => (f && typeof f === 'object' ? { ...f, ...(f.words === undefined ? {} : { words: once(f.words) }), ...(f.unit === undefined ? {} : { unit: once(f.unit) }), ...(f.currency === undefined ? {} : { currency: once(f.currency) }) } : f)) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The rules over one saved page: bareloop's (found-on-page, N2, R1, U1/R1L, S1, ...), then ours (no-value).
|
|
46
|
+
* @param {string} text the frozen page text @param {import('./pagerules.js').PageMap} mapping @param {{n: number, text?: string, rule?: string, rules?: string[]}[]} jobLines
|
|
47
|
+
* @returns {{facts: import('./pagerules.js').KeptFact[], dropped: import('./pagerules.js').Dropped[]}}
|
|
48
|
+
*/
|
|
49
|
+
export function applyPageWords(text, mapping, jobLines) {
|
|
50
|
+
const r = applyPageRules(text, dedupeMap(mapping), jobLines);
|
|
51
|
+
const lines = text.split('\n').map(squash);
|
|
52
|
+
const dropped = [...r.dropped];
|
|
53
|
+
/** @type {any[]} */
|
|
54
|
+
const facts = [];
|
|
55
|
+
// the kept facts say 'phrase' for a place too; the AI's own map says which were places
|
|
56
|
+
const placeNames = new Set((Array.isArray(mapping?.facts) ? mapping.facts : []).filter((m) => m?.shape === 'place').map((m) => String(m.name)));
|
|
57
|
+
for (const f of r.facts) {
|
|
58
|
+
const shape = f.shape;
|
|
59
|
+
if (shape === 'phrase' && f.words.length > 0 && placeNames.has(f.name)) {
|
|
60
|
+
// M10 am7 item 2 (R2, R2a, R2b): a PLACE word grows to its role word; the phrases are all to be in a result's quote (R2c, src/citedcheck.js factsOfLook)
|
|
61
|
+
facts.push({ ...f, phrases: placePhrases(text, f.words).phrases });
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (!(shape === 'money' || shape === 'number' || shape === 'time') || f.words.length === 0) { facts.push(f); continue; }
|
|
65
|
+
const at = { line: f.line, ...(f.forRule === undefined ? {} : { rule: f.forRule }), fact: f.name };
|
|
66
|
+
const keep = [];
|
|
67
|
+
for (const w of f.words) {
|
|
68
|
+
if (readsValue(lines, w, shape)) keep.push(w);
|
|
69
|
+
else dropped.push({ ...at, word: w, reason: 'no-value' });
|
|
70
|
+
}
|
|
71
|
+
if (keep.length === 0) { dropped.push({ ...at, reason: 'no-label' }); continue; }
|
|
72
|
+
facts.push({ ...f, words: keep });
|
|
73
|
+
}
|
|
74
|
+
return { facts, dropped };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** @param {import('./pagerules.js').Dropped[]} dropped @param {{n: number}[]} jobLines @returns {string[]} one plain line per fact that lost something, in the person's own words */
|
|
78
|
+
export const notCheckedLines = (dropped, jobLines) => dropRows(dropped).map((row) => dropLine(row, jobLines, lineRules));
|
|
79
|
+
|
|
80
|
+
// borrowed-from: bareloop src/inputlook.js@6b5dc74 (lookFactOf, rewritten to a plain function; the `example` field is not used here)
|
|
81
|
+
/**
|
|
82
|
+
* A kept fact as the look carries it: the page words under the name the later pieces read (a phrase holds `phrase`, any other `labels`/`label`).
|
|
83
|
+
* @param {import('./pagerules.js').KeptFact} k @param {string} source @returns {any}
|
|
84
|
+
*/
|
|
85
|
+
export function lookFactOf(k, source) {
|
|
86
|
+
/** @type {any} */
|
|
87
|
+
const out = { line: k.line, name: k.name, shape: k.shape, source, words: [...k.words] };
|
|
88
|
+
if (k.shape === 'phrase') out.phrase = k.words[0];
|
|
89
|
+
if (Array.isArray(/** @type {any} */ (k).phrases)) out.phrases = [.../** @type {any} */ (k).phrases];
|
|
90
|
+
else { out.labels = [...k.words]; if (k.words.length) out.label = k.words[0]; }
|
|
91
|
+
if (k.unit) out.unit = [...k.unit];
|
|
92
|
+
if (k.currency) out.currency = [...k.currency];
|
|
93
|
+
if (k.forRule !== undefined) out.forRule = k.forRule;
|
|
94
|
+
if (k.reading) out.reading = { ...k.reading };
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Look at ONE page input: the map call (once; once more if the answer is unreadable), then the rules.
|
|
100
|
+
* `callModel(content, attempt)` (attempt 1 or 2) makes and meters ONE model round and returns `{text}`, `{text, cutOff: true}` (the round hit its output cap) or `{error}`.
|
|
101
|
+
* @param {{label: string, text: string, jobLines: {n: number, text: string, rule?: string, rules?: string[]}[], callModel: (content: string, attempt: number) => Promise<{text?: string, cutOff?: boolean, error?: string}>}} o
|
|
102
|
+
* @returns {Promise<{ok: true, look: {facts: any[], dropped: any[]}, notChecked: string[], mapping: any, attempts: number}|{ok: false, reason: string, attempts: number}>}
|
|
103
|
+
*/
|
|
104
|
+
export async function lookAtPage({
|
|
105
|
+
label, text, jobLines, callModel,
|
|
106
|
+
}) {
|
|
107
|
+
const content = mapPrompt({ jobLines, label, text });
|
|
108
|
+
let attempts = 0;
|
|
109
|
+
for (;;) {
|
|
110
|
+
attempts += 1;
|
|
111
|
+
const r = await callModel(content, attempts);
|
|
112
|
+
if (r.error !== undefined) return { ok: false, reason: `the call about the page failed: ${r.error}`, attempts };
|
|
113
|
+
const parsed = r.cutOff === true ? { ok: false } : parseMapAnswer(r.text);
|
|
114
|
+
if (parsed.ok) {
|
|
115
|
+
const { mapping } = /** @type {any} */ (parsed);
|
|
116
|
+
const words = applyPageWords(text, mapping, jobLines);
|
|
117
|
+
// F241 "can it read": a money fact whose forms read no result line, by the run's own checker (src/pagedry.js), is Not checked, never signed
|
|
118
|
+
const read = await dryReadMoney(text, words.facts);
|
|
119
|
+
// a phrase fact is read against the same result lines (only when the job keeps a money fact; bareloop c550dc8)
|
|
120
|
+
const phr = await dryReadPhrases(text, read.facts);
|
|
121
|
+
const kept = { facts: phr.facts, dropped: [...words.dropped, ...read.dropped, ...phr.dropped] };
|
|
122
|
+
const dropped = kept.dropped.map((d) => ({ ...d, source: label }));
|
|
123
|
+
return {
|
|
124
|
+
ok: true, look: { facts: kept.facts.map((f) => lookFactOf(f, label)), dropped }, notChecked: notCheckedLines(kept.dropped, jobLines), mapping, attempts,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
if (attempts >= 2) return { ok: false, reason: MAP_UNREADABLE, attempts };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* What the drafter is told about a page it cannot read for itself: the words code checked against the saved page (kept), and every drop, so it never
|
|
133
|
+
* claims a check the page cannot give (bareloop's withDropNotes, told to the drafter as plain lines).
|
|
134
|
+
* @param {{label: string, address: string, chars: number, look: {facts: any[]}, notChecked: string[]}} o @returns {string[]}
|
|
135
|
+
*/
|
|
136
|
+
export function pageInfoLines({
|
|
137
|
+
label, address, chars, look, notChecked,
|
|
138
|
+
}) {
|
|
139
|
+
const q = (/** @type {string} */ w) => `"${w}"`;
|
|
140
|
+
const say = (/** @type {any} */ f) => {
|
|
141
|
+
const head = `${f.name}${f.forRule === undefined ? '' : ` (rule ${f.forRule})`}`;
|
|
142
|
+
// M10 am7 item 2: a place is told as the phrases it must be checked with (R2c: every one is a fact of its own)
|
|
143
|
+
if (Array.isArray(f.phrases)) return `${head}: place phrases (every one must be its own phrase fact) ${f.phrases.map(q).join(', ')}`;
|
|
144
|
+
const forms = [...(f.unit ?? []).map((/** @type {string} */ u) => `unit ${q(u)}`), ...(f.currency ?? []).map((/** @type {string} */ c) => `currency ${q(c)}`)];
|
|
145
|
+
const read = f.reading ? `, limit read from your words: ${ruleWords({ shape: f.shape, unit: f.unit, currency: f.currency, rule: f.reading })}` : '';
|
|
146
|
+
return `${head}: ${f.shape === 'phrase' ? 'phrase ' : f.words.length ? 'labels ' : ''}${f.words.map(q).join(', ') || '(read by its unit)'}${forms.length ? `, ${forms.join(', ')}` : ''}${read}`;
|
|
147
|
+
};
|
|
148
|
+
return [
|
|
149
|
+
`- ${label}: a web page (${address}), saved at drafting, ${chars} characters. Code checked the page's own words for the job's rules and kept only words the saved page proves.`,
|
|
150
|
+
...(look.facts.length ? [` Kept, line ${[...new Set(look.facts.map((/** @type {any} */ f) => f.line))].join(', ')}: ${look.facts.map(say).join('; ')}`] : [' Kept: nothing.']),
|
|
151
|
+
...(notChecked.length
|
|
152
|
+
? [' Code could not make these a check, so they are Not checked; never claim them as checked:', ...notChecked.map((l) => ` - ${l}`)]
|
|
153
|
+
: []),
|
|
154
|
+
];
|
|
155
|
+
}
|
package/src/pagemap.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/pagemap.js@54fa5ca (MAP_SHAPES, MAP_SYSTEM, mapPrompt, parseMapAnswer, MAP_UNREADABLE)
|
|
2
|
+
// Not copied: runPageMap (bareloop's spend and transport plumbing; fwdloop meters through the drafter's own provider call, see src/pagelook.js),
|
|
3
|
+
// and the ask half (DROP_IT, askableFromLook, ...), which is the next piece.
|
|
4
|
+
import { lineRules } from './pagebits.js';
|
|
5
|
+
import { validReading } from './pagerules.js';
|
|
6
|
+
export const MAP_SHAPES = Object.freeze(['place', 'money', 'time', 'phrase']);
|
|
7
|
+
|
|
8
|
+
export const MAP_SYSTEM = 'You map a person\'s job to the exact words of ONE saved web page. You never grade and never invent words: every string you return must be copied from the page text, character for character.';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* What the AI is told, for ONE page input. Ported from the POC prompt: the job, the `~` rules, "a result is one item", the answer form
|
|
12
|
+
* and the shape meanings.
|
|
13
|
+
* @param {{jobLines: {n: number, text: string, rule?: string, rules?: string[]}[], label: string, text: string}} o
|
|
14
|
+
* @returns {string}
|
|
15
|
+
*/
|
|
16
|
+
export function mapPrompt({ jobLines, label, text }) {
|
|
17
|
+
const job = jobLines.map((l) => `LINE ${l.n}: ${l.text}${lineRules(l).map((r, i) => `\n~ rule ${i + 1}: ${r}`).join('')}`).join('\n');
|
|
18
|
+
return `THE JOB (each ~ rule applies to the line above it):\n${job}\n\n`
|
|
19
|
+
+ 'A "result" is one item the page lists (one flight, one stay, one row). For each job line and for each rule, say which fact(s) every result must carry, and give the PAGE\'S OWN WORDS for it.\n\n'
|
|
20
|
+
+ 'Return ONLY a JSON object, no prose, no code fence:\n'
|
|
21
|
+
+ '{"facts":[{"name":"<letters and spaces only>","from":"<line N | line N rule M>","shape":"place|money|time|phrase","words":["<page words>", ...],"currency":["<symbol>"],"unit":["<words after the amount>"],"reading":<optional, see below>}]}\n\n'
|
|
22
|
+
+ 'shape meanings:\n'
|
|
23
|
+
+ '- place: words = ways the page writes the place (a city, an airport name), copied from the page.\n'
|
|
24
|
+
+ '- money: words = the label(s) written right BEFORE the amount, copied from the page. currency / unit = how the page writes the currency ("$") and/or the words after the amount ("US dollars"); give every spelling the page uses, as lists.\n'
|
|
25
|
+
+ '- time: words = the label(s) written right BEFORE the time that is the one the rule is about, copied from the page.\n'
|
|
26
|
+
+ '- phrase: words = fixed words a result\'s text must contain, copied from the page.\n'
|
|
27
|
+
+ 'Several words in one list are alternatives for the same fact. Put the best one first.\n'
|
|
28
|
+
+ 'reading (optional, only on a time or money fact): when a ~ rule is a limit on that fact that the page cannot hold in words (for example "not a red-eye" is a limit on the departure time), give your own best reading of the rule as that limit: {"op":"between","lo":<bound>,"hi":<bound>} or {"op":"lt|lte|gt|gte","value":<bound>}. A time bound is a "HH:MM" string on a 24-hour clock; a money bound is a number. Leave reading out when a page word already carries the rule.\n\n'
|
|
29
|
+
+ `PAGE TEXT (the input "${label}"):\n${text}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Read the AI's answer: ONE JSON object of the answer form, and nothing else. No repair (hamr's ruling): text that is not JSON, JSON of
|
|
34
|
+
* another form, or a fact whose shape or lists are not of the form is a malformed answer.
|
|
35
|
+
* @param {unknown} text @returns {{ok: true, mapping: import('./pagerules.js').PageMap}|{ok: false}}
|
|
36
|
+
*/
|
|
37
|
+
export function parseMapAnswer(text) {
|
|
38
|
+
/** @type {any} */
|
|
39
|
+
let m;
|
|
40
|
+
try { m = JSON.parse(String(text ?? '').trim()); } catch { return { ok: false }; }
|
|
41
|
+
const strs = (/** @type {unknown} */ v) => Array.isArray(v) && v.every((x) => typeof x === 'string');
|
|
42
|
+
if (m === null || typeof m !== 'object' || Array.isArray(m) || !Array.isArray(m.facts)) return { ok: false };
|
|
43
|
+
for (const f of m.facts) {
|
|
44
|
+
if (f === null || typeof f !== 'object' || Array.isArray(f)) return { ok: false };
|
|
45
|
+
if (typeof f.name !== 'string' || !MAP_SHAPES.includes(f.shape) || !strs(f.words)) return { ok: false };
|
|
46
|
+
if (f.from !== undefined && typeof f.from !== 'string') return { ok: false };
|
|
47
|
+
for (const k of ['currency', 'unit']) if (f[k] !== undefined && !strs(f[k])) return { ok: false };
|
|
48
|
+
// PRD v1.107 Part 5b: a `reading` is a limit of the signed-rule shape on a time or money fact; any other is a malformed answer (no repair)
|
|
49
|
+
if (f.reading !== undefined && !validReading(f.shape, f.reading)) return { ok: false };
|
|
50
|
+
}
|
|
51
|
+
return { ok: true, mapping: m };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** the plain-word stop when the answer was not readable twice (no Resume: a draft is not a run) */
|
|
55
|
+
export const MAP_UNREADABLE = 'The AI\'s answer about the page was not readable twice. Nothing was signed.';
|
package/src/pageplace.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// borrowed-from: bareloop (its scratch folder) idea-a-v2/rules.mjs@ef815eb (bareloop HEAD when copied; that file is untracked there, sha256 1057f690ee79fe3c58d51624255477894d76f4a7222683c5cdd1d8531ef1b64f)
|
|
2
|
+
// Copy of its growOnce, growLeft and the R2 / R2a / R2b block for a place word; R2c (every kept phrase is a fact of its own, all must be in the quote) is
|
|
3
|
+
// `factsOfLook` in src/citedcheck.js. M10 amendment 7 item 2 (docs/wiki/the-module-ladder.md): a place word grows LEFT to take in its role word
|
|
4
|
+
// ("Leaves Amsterdam Airport Schiphol", "arrives at Heathrow Airport"), so a result that leaves Heathrow and arrives at Amsterdam does not say them.
|
|
5
|
+
// Proof: FINDINGS F72 (R2 caught the flipped route 114/114, honest 57/57; the same phrases without growth let it pass 114/114).
|
|
6
|
+
//
|
|
7
|
+
// Pure: no I/O, no model. Throws away: a place word the longest phrase contains (R2a), a place word that shares fewer than 90% of the longest phrase's
|
|
8
|
+
// page lines (R2b); both come back in `trace` with the reason, never silently. Third outcome: growth that stops (line start, under 90%, tree markup) is
|
|
9
|
+
// said in `notes` and the word stays as it was.
|
|
10
|
+
|
|
11
|
+
import { squash } from './pagebits.js';
|
|
12
|
+
|
|
13
|
+
/** a word with tree markup in it is not a role word: growth stops there */
|
|
14
|
+
const MARKUP = /["[\]=]/;
|
|
15
|
+
/** R2 / R2b: at least this share */
|
|
16
|
+
const SHARE = 0.9;
|
|
17
|
+
/** R2: up to this many words to the left */
|
|
18
|
+
const MAX_GROW = 2;
|
|
19
|
+
|
|
20
|
+
/** @param {string} text @returns {string[]} the page's lines, white space squashed */
|
|
21
|
+
const linesOf = (text) => text.split('\n').map(squash);
|
|
22
|
+
|
|
23
|
+
/** @param {string[]} lines @param {string} phrase @returns {{li: number, at: number}[]} every occurrence, non-overlapping per line */
|
|
24
|
+
function occ(lines, phrase) {
|
|
25
|
+
/** @type {{li: number, at: number}[]} */
|
|
26
|
+
const out = [];
|
|
27
|
+
const p = squash(phrase).trim();
|
|
28
|
+
if (!p) return out;
|
|
29
|
+
lines.forEach((ln, li) => { for (let i = ln.indexOf(p); i !== -1; i = ln.indexOf(p, i + p.length)) out.push({ li, at: i }); });
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
/** @param {string[]} lines @param {string} phrase @returns {Set<number>} the page lines the phrase is in */
|
|
33
|
+
const lineSet = (lines, phrase) => new Set(occ(lines, phrase).map((o) => o.li));
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* R2, one step: the phrase with the word before it, when that word is the same in at least 90% of its occurrences and holds no markup. Otherwise null.
|
|
37
|
+
* @param {string[]} lines @param {string} phrase @param {string[]} notes @param {string} tag @returns {string|null}
|
|
38
|
+
*/
|
|
39
|
+
function growOnce(lines, phrase, notes, tag) {
|
|
40
|
+
const os = occ(lines, phrase);
|
|
41
|
+
if (os.length === 0) return null;
|
|
42
|
+
/** @type {Map<string|null, number>} */
|
|
43
|
+
const votes = new Map();
|
|
44
|
+
for (const o of os) {
|
|
45
|
+
const before = lines[o.li].slice(0, o.at);
|
|
46
|
+
/** @type {string|null} */
|
|
47
|
+
let w = null;
|
|
48
|
+
if (before.length > 0 && !/\s$/.test(before)) w = before.slice(before.lastIndexOf(' ') + 1); // the phrase starts mid-token: the fragment is the "word"
|
|
49
|
+
else { const t = before.trimEnd(); if (t) w = t.slice(t.lastIndexOf(' ') + 1); }
|
|
50
|
+
votes.set(w, (votes.get(w) ?? 0) + 1);
|
|
51
|
+
}
|
|
52
|
+
const [word, n] = [...votes].sort((a, b) => b[1] - a[1])[0];
|
|
53
|
+
if (word === null) { notes.push(`${tag}: growth stops, the word before it is the start of a line`); return null; }
|
|
54
|
+
if (n / os.length < SHARE) { notes.push(`${tag}: growth stops, ${JSON.stringify(word)} comes before it ${n} of ${os.length} times, under 90%`); return null; }
|
|
55
|
+
if (MARKUP.test(word)) { notes.push(`${tag}: growth stops at markup in ${JSON.stringify(word)}`); return null; }
|
|
56
|
+
return `${word} ${phrase}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* R2: a phrase extended left by up to 2 words.
|
|
61
|
+
* @param {string[]} lines @param {string} phrase @param {string[]} notes @param {string} tag @returns {{grown: string, steps: string[]}}
|
|
62
|
+
*/
|
|
63
|
+
export function growLeft(lines, phrase, notes, tag) {
|
|
64
|
+
let p = phrase;
|
|
65
|
+
/** @type {string[]} */
|
|
66
|
+
const steps = [];
|
|
67
|
+
for (let i = 0; i < MAX_GROW; i += 1) { const g = growOnce(lines, p, notes, tag); if (!g) break; p = g; steps.push(p); }
|
|
68
|
+
return { grown: p, steps };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The phrases a place fact is signed with: each kept place word grown (R2), a phrase another kept phrase contains dropped (R2a), a phrase that shares
|
|
73
|
+
* under 90% of the longest phrase's page lines dropped (R2b). `grow: false` skips R2 only (the control of F72: the same phrases, no growth).
|
|
74
|
+
* @param {string} text the saved page @param {string[]} words the kept words of ONE place fact, each already on the page
|
|
75
|
+
* @param {{grow?: boolean}} [o]
|
|
76
|
+
* @returns {{phrases: string[], notes: string[], trace: string[]}} `phrases` are all to be in a result's quote (R2c)
|
|
77
|
+
*/
|
|
78
|
+
export function placePhrases(text, words, { grow = true } = {}) {
|
|
79
|
+
const lines = linesOf(text);
|
|
80
|
+
/** @type {string[]} */
|
|
81
|
+
const notes = [];
|
|
82
|
+
/** @type {string[]} */
|
|
83
|
+
const trace = [];
|
|
84
|
+
let kept = [...new Set(words.map((w) => (grow ? growLeft(lines, w, notes, `R2 "${w}"`).grown : w)))];
|
|
85
|
+
kept = kept.filter((a) => {
|
|
86
|
+
const c = kept.find((b) => b !== a && b.includes(a));
|
|
87
|
+
if (c) { trace.push(`R2a drop ${JSON.stringify(a)} in ${JSON.stringify(c)}`); return false; }
|
|
88
|
+
return true;
|
|
89
|
+
});
|
|
90
|
+
if (kept.length > 1) {
|
|
91
|
+
const longest = [...kept].sort((a, b) => b.length - a.length)[0];
|
|
92
|
+
const L = lineSet(lines, longest);
|
|
93
|
+
kept = kept.filter((a) => {
|
|
94
|
+
if (a === longest) return true;
|
|
95
|
+
const A = lineSet(lines, a);
|
|
96
|
+
const share = [...L].filter((x) => A.has(x)).length / L.size;
|
|
97
|
+
if (share >= SHARE) return true;
|
|
98
|
+
trace.push(`R2b drop ${JSON.stringify(a)} ${(share * 100).toFixed(0)}%`);
|
|
99
|
+
return false;
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
return { phrases: kept, notes, trace };
|
|
103
|
+
}
|