@recapi/client 0.18.0 → 0.33.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/README.md +396 -40
- package/index.d.ts +18 -1
- package/package.json +1 -1
- package/src/cards.js +253 -0
- package/src/client.js +445 -19
- package/src/index.js +3 -1
- package/src/magento.js +183 -149
- package/src/page.js +418 -0
- package/src/row.js +145 -79
- package/src/shopify.js +190 -179
- package/src/shops.js +197 -0
- package/src/woocommerce.js +157 -186
package/src/page.js
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a product page tells search engines about its product, read as
|
|
3
|
+
* recapi's server reads it (server/internal/pageproduct; the shared pages
|
|
4
|
+
* are spec/page_product_vectors.json): schema.org Product in JSON-LD, then
|
|
5
|
+
* microdata, then Open Graph when it calls the page a product. Only what a browser sends:
|
|
6
|
+
* the name, category and the page's own address, never a picture or price,
|
|
7
|
+
* which recapi takes from nobody's browser.
|
|
8
|
+
*
|
|
9
|
+
* @module page
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** The items API's title cap, in UTF-8 bytes. */
|
|
13
|
+
const MAX_NAME = 512;
|
|
14
|
+
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The page's JSON-LD blocks, meta tags and the properties of its first
|
|
18
|
+
* microdata Product, as the browser parsed them.
|
|
19
|
+
*
|
|
20
|
+
* @param {Document} doc
|
|
21
|
+
* @returns {{ scripts: string[], metas: Array<[string, string]>, micro: Array<[string, string]> | null }}
|
|
22
|
+
*/
|
|
23
|
+
export function pageOf(doc) {
|
|
24
|
+
const scripts = [];
|
|
25
|
+
for (const s of doc.querySelectorAll('script')) {
|
|
26
|
+
if ((s.getAttribute('type') ?? '').toLowerCase() === 'application/ld+json') scripts.push(s.textContent ?? '');
|
|
27
|
+
}
|
|
28
|
+
const metas = [];
|
|
29
|
+
for (const m of doc.querySelectorAll('meta')) metas.push([m.getAttribute('property') || m.getAttribute('name') || '', m.getAttribute('content') ?? '']);
|
|
30
|
+
let micro = null;
|
|
31
|
+
const scope = [...doc.querySelectorAll('[itemscope]')].find((e) => /schema\.org\/Product(Group)?$/.test(e.getAttribute('itemtype') ?? ''));
|
|
32
|
+
if (scope) {
|
|
33
|
+
micro = [];
|
|
34
|
+
for (const e of scope.querySelectorAll('[itemprop]')) {
|
|
35
|
+
// The product's own properties only: a review's or a brand's name sits in a scope of its own.
|
|
36
|
+
let up = e.parentElement;
|
|
37
|
+
while (up && up !== scope && up.getAttribute('itemscope') === null) up = up.parentElement;
|
|
38
|
+
if (up !== scope) continue;
|
|
39
|
+
const value = e.getAttribute('content') ?? e.getAttribute('href') ?? e.getAttribute('src') ?? e.textContent ?? '';
|
|
40
|
+
for (const prop of (e.getAttribute('itemprop') ?? '').split(/\s+/)) micro.push([prop, value]);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return { scripts, metas, micro };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The page's product, or null when it carries no product markup. JSON-LD
|
|
48
|
+
* wins field by field, then microdata, then Open Graph. `url` is on the host of `at`
|
|
49
|
+
* (the page's address), else the page's own address without its query: a
|
|
50
|
+
* visitor's click and campaign ids ride there, and a site whose product
|
|
51
|
+
* address needs a query names it in its markup.
|
|
52
|
+
*
|
|
53
|
+
* @param {{ scripts: string[], metas: Array<[string, string]>, micro?: Array<[string, string]> | null }} page
|
|
54
|
+
* @param {string} at
|
|
55
|
+
* @returns {{ name: string, url: string, category: string } | null}
|
|
56
|
+
*/
|
|
57
|
+
export function readProduct(page, at) {
|
|
58
|
+
const p = read(page, at);
|
|
59
|
+
return p && { name: p.name, url: p.url, category: p.category };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The id of the page's product for a site that sends none of its own, or ''
|
|
64
|
+
* when the page carries no product markup: the address the markup names on
|
|
65
|
+
* the page's host, else the page's own, by `addressId`. Never the page's
|
|
66
|
+
* `sku`: most pages print none, and two rules in one shop would split its
|
|
67
|
+
* products.
|
|
68
|
+
*
|
|
69
|
+
* @param {{ scripts: string[], metas: Array<[string, string]>, micro?: Array<[string, string]> | null }} page
|
|
70
|
+
* @param {string} at
|
|
71
|
+
* @returns {string}
|
|
72
|
+
*/
|
|
73
|
+
export function pageProductId(page, at) {
|
|
74
|
+
const p = read(page, at);
|
|
75
|
+
return p ? addressId(p.own || at) : '';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The shape of an id the API makes (internal/ids: rec_ and hex), the only one
|
|
80
|
+
* read from an address: any other value is the site's own. Internal, shared
|
|
81
|
+
* with client.js, cards.js and shops.js; index.js doesn't export it.
|
|
82
|
+
*/
|
|
83
|
+
export const REC_ID = /^rec_[0-9a-f]+$/;
|
|
84
|
+
|
|
85
|
+
/** The API's id cap, in UTF-8 bytes. */
|
|
86
|
+
const MAX_ID = 256;
|
|
87
|
+
|
|
88
|
+
// What ad networks and mail tools add to a link to name the visitor or the
|
|
89
|
+
// campaign, never the product: the server's clickIDs (api/products_seen.go).
|
|
90
|
+
const CLICK_IDS = new Set(['gclid', 'gbraid', 'wbraid', 'dclid', 'fbclid', 'msclkid', 'ttclid', 'twclid', 'li_fat_id', 'yclid', 'igshid', 'srsltid', 'mc_cid', 'mc_eid', '_hsenc', '_hsmi', '_ga', '_gl']);
|
|
91
|
+
|
|
92
|
+
// What shop software adds to a product's address for one visitor: a session
|
|
93
|
+
// kept in the link when cookies are off, the currency or language switch
|
|
94
|
+
// (PrestaShop's SubmitCurrency, Shopware 5's __shop, xt:Commerce's XTCsid,
|
|
95
|
+
// Magento's ___store, Shopify's search trail _pos/_sid/_ss). Kept, one
|
|
96
|
+
// product would get one id per currency, or per visitor. Not `_locale`: a
|
|
97
|
+
// shop on the sample keeps its product's path in it.
|
|
98
|
+
const SWITCHES = new Set(['phpsessid', 'sid', 'sessionid', 'session_id', 'jsessionid', 'force_sid', 'xtcsid', 'oscsid', 'modsid', 'zenid', 'scoreid', 'stoken',
|
|
99
|
+
'submitcurrency', 'id_currency', 'currency', 'cur', '__currency', 'aelia_cs_currency',
|
|
100
|
+
'id_lang', 'lang', 'language', '__shop', '__redirect', '___store', '___from_store',
|
|
101
|
+
'_pos', '_sid', '_ss', '_psq', '_fid', '_v']);
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A product id from its address (spec/page_product_vectors.json): path and
|
|
105
|
+
* query without scheme, host or fragment, percent-decoded where that keeps
|
|
106
|
+
* it readable, one trailing slash dropped, click and campaign ids and a
|
|
107
|
+
* visitor's session, currency and language switch dropped from the query
|
|
108
|
+
* and the site's own kept (a product addressed by
|
|
109
|
+
* `?product_id=40`). Over 256 bytes, a prefix and a hash of the whole: the
|
|
110
|
+
* same address always gives the same id. '' when `raw` is no http(s) address.
|
|
111
|
+
*
|
|
112
|
+
* @param {string} raw
|
|
113
|
+
* @returns {string}
|
|
114
|
+
*/
|
|
115
|
+
export function addressId(raw) {
|
|
116
|
+
let u;
|
|
117
|
+
try {
|
|
118
|
+
u = new URL(raw);
|
|
119
|
+
} catch {
|
|
120
|
+
return '';
|
|
121
|
+
}
|
|
122
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:') return '';
|
|
123
|
+
const query = u.search.slice(1).split('&').filter((pair) => {
|
|
124
|
+
if (pair === '') return false;
|
|
125
|
+
const [name, ...rest] = pair.split('=');
|
|
126
|
+
// A card's own `?rec=rec_…` credits the click, then leaves the address
|
|
127
|
+
// (client.js landed()): kept, the product would have a second id for the
|
|
128
|
+
// view that carries the credit. The site's own `?rec=1` stays.
|
|
129
|
+
if (name === 'rec' && REC_ID.test(rest.join('='))) return false;
|
|
130
|
+
let key = name;
|
|
131
|
+
try {
|
|
132
|
+
key = decodeURIComponent(key.replace(/\+/g, ' '));
|
|
133
|
+
} catch {}
|
|
134
|
+
key = key.toLowerCase();
|
|
135
|
+
return !CLICK_IDS.has(key) && !SWITCHES.has(key) && !key.startsWith('utm_');
|
|
136
|
+
}).join('&');
|
|
137
|
+
const path = u.pathname.length > 1 && u.pathname.endsWith('/') ? u.pathname.slice(0, -1) : u.pathname;
|
|
138
|
+
let id = query ? `${path}?${query}` : path;
|
|
139
|
+
try {
|
|
140
|
+
// decodeURI leaves reserved characters (/ ? & = #) encoded, so the
|
|
141
|
+
// decoded id still reads back to one address.
|
|
142
|
+
const decoded = decodeURI(id);
|
|
143
|
+
if (!/[\u0000-\u001f\u007f]/.test(decoded)) id = decoded;
|
|
144
|
+
} catch {}
|
|
145
|
+
return fit(id);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Over the cap: the longest prefix cut on a character that leaves room for
|
|
149
|
+
// '~' and the FNV-1a 64 hash of the whole id's UTF-8, in 16 hex digits.
|
|
150
|
+
function fit(id) {
|
|
151
|
+
const bytes = new TextEncoder().encode(id);
|
|
152
|
+
if (bytes.length <= MAX_ID) return id;
|
|
153
|
+
let sum = 0xcbf29ce484222325n;
|
|
154
|
+
for (const b of bytes) sum = BigInt.asUintN(64, (sum ^ BigInt(b)) * 0x100000001b3n);
|
|
155
|
+
return `${cut(id, MAX_ID - 17)}~${sum.toString(16).padStart(16, '0')}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function read({ scripts, metas, micro = null }, at) {
|
|
159
|
+
let p = null;
|
|
160
|
+
const docs = [];
|
|
161
|
+
let node = null;
|
|
162
|
+
for (const text of scripts) {
|
|
163
|
+
try {
|
|
164
|
+
docs.push(JSON.parse(text));
|
|
165
|
+
} catch {
|
|
166
|
+
// Themes often print one broken block beside good ones.
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
node ??= findProduct(docs.at(-1), 0);
|
|
170
|
+
}
|
|
171
|
+
if (node) {
|
|
172
|
+
// Shoper splits one product over many blocks sharing its @id.
|
|
173
|
+
if (typeof node['@id'] === 'string' && node['@id']) for (const doc of docs) sameId(doc, node['@id'], node, 0);
|
|
174
|
+
const url = typeof node.url === 'string' ? onHost(node.url, at) : '';
|
|
175
|
+
p = { name: typeof node.name === 'string' ? clean(node.name) : '', url, own: url, category: category(node.category) };
|
|
176
|
+
}
|
|
177
|
+
if (micro) {
|
|
178
|
+
const prop = (k) => micro.find(([name]) => name === k)?.[1] ?? '';
|
|
179
|
+
p ??= { name: '', url: '', own: '', category: '' };
|
|
180
|
+
p.name ||= clean(prop('name'));
|
|
181
|
+
p.url ||= onHost(prop('url'), at);
|
|
182
|
+
p.own ||= p.url;
|
|
183
|
+
p.category ||= clean(prop('category'));
|
|
184
|
+
}
|
|
185
|
+
const og = {};
|
|
186
|
+
for (const [k, v] of metas) {
|
|
187
|
+
const key = k.toLowerCase();
|
|
188
|
+
if (key && !Object.hasOwn(og, key)) og[key] = v;
|
|
189
|
+
}
|
|
190
|
+
const type = (og['og:type'] ?? '').toLowerCase();
|
|
191
|
+
if (!p && (type === 'product' || type === 'og:product' || og['product:price:amount'] || og['og:price:amount'])) p = { name: '', url: '', own: '', category: '' };
|
|
192
|
+
if (!p) return null;
|
|
193
|
+
const site = clean(og['og:site_name'] ?? '');
|
|
194
|
+
// A " | Site" tail goes only when it names the page's own site.
|
|
195
|
+
const tail = [' | ', ' - ', ' – ', ' — '].map((sep) => sep + site).find((t) => site && clean(og['og:title'] ?? '').endsWith(t) && clean(og['og:title']).length > t.length);
|
|
196
|
+
p.name ||= tail ? clean(og['og:title']).slice(0, -tail.length) : clean(og['og:title'] ?? '');
|
|
197
|
+
p.category ||= clean(og['product:category'] ?? '');
|
|
198
|
+
p.own ||= onHost(og['og:url'] ?? '', at);
|
|
199
|
+
p.url ||= p.own || onHost(bare(at), at);
|
|
200
|
+
return p;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// One node, an array, a @graph wrapper (Yoast, Rank Math), a page whose
|
|
204
|
+
// mainEntity is the product.
|
|
205
|
+
function findProduct(v, depth) {
|
|
206
|
+
if (depth > 4 || v === null || typeof v !== 'object') return null;
|
|
207
|
+
if (Array.isArray(v)) {
|
|
208
|
+
for (const e of v) {
|
|
209
|
+
const p = findProduct(e, depth + 1);
|
|
210
|
+
if (p) return p;
|
|
211
|
+
}
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
const types = Array.isArray(v['@type']) ? v['@type'] : [v['@type']];
|
|
215
|
+
if (types.some((t) => typeof t === 'string' && ['Product', 'ProductGroup'].includes(t.slice(Math.max(t.lastIndexOf('/'), t.lastIndexOf(':')) + 1)))) return v;
|
|
216
|
+
return findProduct(v['@graph'], depth + 1) ?? findProduct(v.mainEntity, depth + 1);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Fills node's missing fields from every node of v with its id.
|
|
220
|
+
function sameId(v, id, node, depth) {
|
|
221
|
+
if (depth > 4 || v === null || typeof v !== 'object') return;
|
|
222
|
+
if (Array.isArray(v)) {
|
|
223
|
+
for (const e of v) sameId(e, id, node, depth + 1);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
if (v['@id'] === id) for (const k of Object.keys(v)) if (!Object.hasOwn(node, k)) node[k] = v[k];
|
|
227
|
+
sameId(v['@graph'], id, node, depth + 1);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function category(v) {
|
|
231
|
+
if (typeof v === 'string') return clean(v);
|
|
232
|
+
if (Array.isArray(v)) {
|
|
233
|
+
const first = v.find((e) => typeof e === 'string' && e.trim() !== '');
|
|
234
|
+
if (first) return clean(first);
|
|
235
|
+
}
|
|
236
|
+
return '';
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// The entities some themes leave in JSON-LD unescaped, spaces collapsed, at
|
|
240
|
+
// most 512 bytes cut on a character.
|
|
241
|
+
function clean(s) {
|
|
242
|
+
const text = s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
|
|
243
|
+
if (e[0] !== '#') return ENTITIES[e.toLowerCase()] ?? m;
|
|
244
|
+
const code = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
|
245
|
+
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m;
|
|
246
|
+
}).split(/\s+/).filter(Boolean).join(' ');
|
|
247
|
+
return cut(text, MAX_NAME);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// At most `max` bytes of UTF-8, cut on a character.
|
|
251
|
+
function cut(text, max) {
|
|
252
|
+
let out = '';
|
|
253
|
+
let bytes = 0;
|
|
254
|
+
for (const ch of text) {
|
|
255
|
+
const n = ch.codePointAt(0) < 0x80 ? 1 : ch.codePointAt(0) < 0x800 ? 2 : ch.codePointAt(0) < 0x10000 ? 3 : 4;
|
|
256
|
+
if (bytes + n > max) break;
|
|
257
|
+
out += ch;
|
|
258
|
+
bytes += n;
|
|
259
|
+
}
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The page's http(s) address with no query or fragment, else ''.
|
|
265
|
+
*
|
|
266
|
+
* @param {string} at
|
|
267
|
+
* @returns {string}
|
|
268
|
+
*/
|
|
269
|
+
export function bare(at) {
|
|
270
|
+
try {
|
|
271
|
+
const u = new URL(at);
|
|
272
|
+
return u.protocol === 'https:' || u.protocol === 'http:' ? u.origin + u.pathname : '';
|
|
273
|
+
} catch {
|
|
274
|
+
return '';
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// An http(s) address on the page's host, resolved against it, else ''.
|
|
279
|
+
function onHost(s, at) {
|
|
280
|
+
if (s.trim() === '') return '';
|
|
281
|
+
try {
|
|
282
|
+
const u = new URL(s.trim(), at);
|
|
283
|
+
return (u.protocol === 'https:' || u.protocol === 'http:') && u.hostname !== '' && u.hostname === new URL(at).hostname ? u.href : '';
|
|
284
|
+
} catch {
|
|
285
|
+
return '';
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* `again` on each return to the page by Back or Forward that the browser
|
|
291
|
+
* shows from memory (the back/forward cache): none of the page's script runs
|
|
292
|
+
* again, and one page change in five on a phone is such a return.
|
|
293
|
+
*
|
|
294
|
+
* @param {() => void} again
|
|
295
|
+
* @returns {() => void} stops listening
|
|
296
|
+
*/
|
|
297
|
+
export function onReturn(again) {
|
|
298
|
+
const win = globalThis.window;
|
|
299
|
+
const shown = (event) => {
|
|
300
|
+
if (event.persisted) again();
|
|
301
|
+
};
|
|
302
|
+
win?.addEventListener?.('pageshow', shown);
|
|
303
|
+
return () => win?.removeEventListener?.('pageshow', shown);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const NAVIGATED = 'recapi:navigate';
|
|
307
|
+
const PATCHED = Symbol.for('recapi.history');
|
|
308
|
+
// After a move without a reload, the page's product is read at these times
|
|
309
|
+
// (ms) until one differs from the last: a site builder swaps the markup after
|
|
310
|
+
// the address, at its own pace.
|
|
311
|
+
const AFTER_MOVE = [0, 300, 1000, 2500];
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Follows the page's product id (`pageProductId`) for calls that name none:
|
|
315
|
+
* `changed(id)` once the page is parsed ('' with no product), and again each
|
|
316
|
+
* time the id changes. A page with no product at first is read again at load
|
|
317
|
+
* and 2 s later (Square Online adds its markup by script). A site that moves
|
|
318
|
+
* between pages without reloading (Wix) is followed through pushState,
|
|
319
|
+
* replaceState and popstate; the same address twice is one page. Two copies
|
|
320
|
+
* of this library share one wrapper of `history`.
|
|
321
|
+
*
|
|
322
|
+
* `settled()`, if given, is called when a move's reads end on the same id:
|
|
323
|
+
* nothing changed, but the site may have drawn the page again.
|
|
324
|
+
* `returned(id)`, if given, is called when Back or Forward shows the page
|
|
325
|
+
* again from memory (`onReturn`), once its product is read.
|
|
326
|
+
*
|
|
327
|
+
* @param {(id: string) => void} changed
|
|
328
|
+
* @param {() => void} [settled]
|
|
329
|
+
* @param {(id: string) => void} [returned]
|
|
330
|
+
* @returns {() => void} stops following
|
|
331
|
+
*/
|
|
332
|
+
export function followProduct(changed, settled, returned) {
|
|
333
|
+
const win = globalThis.window;
|
|
334
|
+
const timers = new Set();
|
|
335
|
+
let id = null;
|
|
336
|
+
let move = 0;
|
|
337
|
+
let stopped = false;
|
|
338
|
+
const here = () => String(globalThis.location?.href ?? '').split('#')[0];
|
|
339
|
+
let address = here();
|
|
340
|
+
const readNow = () => {
|
|
341
|
+
try {
|
|
342
|
+
return pageProductId(pageOf(globalThis.document), String(globalThis.location?.href ?? ''));
|
|
343
|
+
} catch {
|
|
344
|
+
return '';
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
const later = (ms, fn) => {
|
|
348
|
+
const t = setTimeout(() => {
|
|
349
|
+
timers.delete(t);
|
|
350
|
+
if (!stopped) fn();
|
|
351
|
+
}, ms);
|
|
352
|
+
timers.add(t);
|
|
353
|
+
};
|
|
354
|
+
const take = (next) => {
|
|
355
|
+
if (next === id) return;
|
|
356
|
+
id = next;
|
|
357
|
+
changed(next);
|
|
358
|
+
};
|
|
359
|
+
const again = () => {
|
|
360
|
+
if (id === '' && move === 0) take(readNow());
|
|
361
|
+
};
|
|
362
|
+
const first = () => {
|
|
363
|
+
if (stopped) return;
|
|
364
|
+
take(readNow());
|
|
365
|
+
// Found at once, it stays: a later read of other markup would give the
|
|
366
|
+
// same product a second id.
|
|
367
|
+
if (id !== '') return;
|
|
368
|
+
if (globalThis.document.readyState === 'complete') later(2000, again);
|
|
369
|
+
else win?.addEventListener?.('load', () => {
|
|
370
|
+
again();
|
|
371
|
+
later(2000, again);
|
|
372
|
+
}, { once: true });
|
|
373
|
+
};
|
|
374
|
+
const moved = () => {
|
|
375
|
+
const now = here();
|
|
376
|
+
if (stopped || now === address) return;
|
|
377
|
+
address = now;
|
|
378
|
+
const before = id;
|
|
379
|
+
const mine = ++move;
|
|
380
|
+
const step = (k) => later(AFTER_MOVE[k] - (AFTER_MOVE[k - 1] ?? 0), () => {
|
|
381
|
+
if (mine !== move) return;
|
|
382
|
+
const next = readNow();
|
|
383
|
+
// The last page's markup, or none yet: the new one may still come.
|
|
384
|
+
if ((next === before || next === '') && k < AFTER_MOVE.length - 1) return step(k + 1);
|
|
385
|
+
if (next === id) settled?.();
|
|
386
|
+
else take(next);
|
|
387
|
+
});
|
|
388
|
+
step(0);
|
|
389
|
+
};
|
|
390
|
+
const history = globalThis.history;
|
|
391
|
+
if (win?.addEventListener && history && !history[PATCHED]) {
|
|
392
|
+
history[PATCHED] = true;
|
|
393
|
+
for (const name of ['pushState', 'replaceState']) {
|
|
394
|
+
const original = history[name];
|
|
395
|
+
if (typeof original !== 'function') continue;
|
|
396
|
+
history[name] = function (...args) {
|
|
397
|
+
const result = original.apply(this, args);
|
|
398
|
+
win.dispatchEvent(new Event(NAVIGATED));
|
|
399
|
+
return result;
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
win?.addEventListener?.(NAVIGATED, moved);
|
|
404
|
+
win?.addEventListener?.('popstate', moved);
|
|
405
|
+
const unreturn = returned ? onReturn(() => {
|
|
406
|
+
if (!stopped && id !== null) returned(id);
|
|
407
|
+
}) : () => {};
|
|
408
|
+
if (globalThis.document.readyState === 'loading') globalThis.document.addEventListener('DOMContentLoaded', first, { once: true });
|
|
409
|
+
else first();
|
|
410
|
+
return () => {
|
|
411
|
+
stopped = true;
|
|
412
|
+
for (const t of timers) clearTimeout(t);
|
|
413
|
+
timers.clear();
|
|
414
|
+
win?.removeEventListener?.(NAVIGATED, moved);
|
|
415
|
+
win?.removeEventListener?.('popstate', moved);
|
|
416
|
+
unreturn();
|
|
417
|
+
};
|
|
418
|
+
}
|