amazon-business-cli-kdp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -2
- package/machine/extractor/extract.js +508 -0
- package/machine/extractor/parse.js +336 -0
- package/machine/pipeline/README.md +14 -0
- package/machine/pipeline/apply.ts +242 -0
- package/machine/pipeline/autocomplete.ts +157 -0
- package/machine/pipeline/bsr.ts +185 -0
- package/machine/pipeline/capture-bestsellers.ts +252 -0
- package/machine/pipeline/capture-search.ts +103 -0
- package/machine/pipeline/category-words.txt +6124 -0
- package/machine/pipeline/classify.ts +127 -0
- package/machine/pipeline/common-words.txt +64001 -0
- package/machine/pipeline/cross.ts +241 -0
- package/machine/pipeline/cruce.ts +174 -0
- package/machine/pipeline/dedupe.ts +73 -0
- package/machine/pipeline/gates.ts +147 -0
- package/machine/pipeline/homogeneity.ts +116 -0
- package/machine/pipeline/http.ts +126 -0
- package/machine/pipeline/ngram.ts +190 -0
- package/machine/pipeline/paths.ts +26 -0
- package/machine/pipeline/phrases.ts +164 -0
- package/machine/pipeline/prefilter.ts +90 -0
- package/machine/pipeline/render.ts +127 -0
- package/machine/pipeline/run.ts +458 -0
- package/machine/pipeline/sweep.ts +153 -0
- package/machine/pipeline/total.ts +25 -0
- package/machine/pipeline/types.ts +63 -0
- package/machine/pipeline/units.ts +27 -0
- package/machine/pipeline/verify.ts +153 -0
- package/machine/storage/schema.sql +90 -0
- package/package.json +30 -4
- package/src/cli.ts +220 -0
- package/src/workspace.ts +199 -0
package/README.md
CHANGED
|
@@ -1,3 +1,103 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Amazon Business CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
CLI y motor independiente para investigación de mercado de Amazon KDP. El código ejecutable vive
|
|
4
|
+
debajo de `machine/`; la CLI resuelve rutas, configura el entorno y ejecuta su propio pipeline.
|
|
5
|
+
No necesita cargar los scripts de `Editorial-Program` para operar. Esa copia queda intacta
|
|
6
|
+
mientras probamos esta como la futura fuente de verdad.
|
|
7
|
+
|
|
8
|
+
El comando de terminal es `abck`; el paquete se llama `amazon-business-cli-kdp`.
|
|
9
|
+
|
|
10
|
+
La CLI y el motor son Bun/TypeScript. Requiere Bun y la dependencia `linkedom`.
|
|
11
|
+
|
|
12
|
+
## Desarrollo
|
|
13
|
+
|
|
14
|
+
Desde esta carpeta:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
bun install
|
|
18
|
+
bun run dev --help
|
|
19
|
+
bun test
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Instalación local reversible
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
bun link --global
|
|
26
|
+
abck --help
|
|
27
|
+
abck doctor
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
El link apunta a esta carpeta, así que los cambios al código se reflejan al volver a ejecutar
|
|
31
|
+
el comando; no hace falta reinstalar después de cada edición. Si cambia el paquete/bin, repetí
|
|
32
|
+
`bun link --global`. Para quitar la instalación:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
bun unlink --global
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Instalación desde npm
|
|
39
|
+
|
|
40
|
+
Cuando la versión esté publicada:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
bun add --global amazon-business-cli-kdp
|
|
44
|
+
abck --help
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Para actualizar solo el ejecutable, sin tocar los workspaces:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
bun update --global amazon-business-cli-kdp
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Paths
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
abck init /path/to/project
|
|
57
|
+
abck doctor --workspace /path/to/project
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
- `init` crea `<workspace>/.amazon-business/{config.json,data/}` y una base SQLite vacía
|
|
61
|
+
aislada para ese workspace. Crea también `data/amazon`, `data/autocomplete` y `data/corridas`.
|
|
62
|
+
- Cada workspace tiene su propia DB; **no se usa un directorio global compartido**.
|
|
63
|
+
- `--workspace`: raíz del proyecto donde trabaja el agente; `machine` exige que esté inicializado.
|
|
64
|
+
- No existe `--data-dir`: los datos pertenecen al workspace y no se pueden redirigir a una
|
|
65
|
+
carpeta global por accidente.
|
|
66
|
+
- `--tool-dir`: integración legacy opcional de E5; no contiene la DB principal del CLI.
|
|
67
|
+
- `--pipeline-dir`: override excepcional para comparar con otra instalación. Por defecto
|
|
68
|
+
apunta al motor dentro de esta carpeta.
|
|
69
|
+
- E5 está apagada por defecto. `--legacy-e5` es opt-in y usa `competitors` en `--tool-dir`,
|
|
70
|
+
fuera del workspace; no usarlo en una corrida que deba quedar aislada.
|
|
71
|
+
|
|
72
|
+
`init` es idempotente: conserva la DB y los artefactos si ya existen. Rechaza una base que no
|
|
73
|
+
reconoce en vez de sobrescribirla. `doctor` es de solo lectura.
|
|
74
|
+
|
|
75
|
+
## Comandos iniciales
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
abck machine run --plan 1 --seed 1 --workspace /path/to/project
|
|
79
|
+
abck machine verify --phrases-file seleccionadas.json \
|
|
80
|
+
--workspace /path/to/project
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Prueba offline de E2, sin red:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
abck machine phrases \
|
|
87
|
+
machine/pipeline/test/fixtures/captures/parenting-relationships-marriage.json \
|
|
88
|
+
--limit 4 --label smoke \
|
|
89
|
+
--workspace /path/to/project
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
La CLI propaga el exit code del motor. El pipeline E1–E4 está ahora dentro de esta carpeta y
|
|
93
|
+
la CLI lo ejecuta como proceso hijo. La siguiente iteración puede desacoplarlo del proceso
|
|
94
|
+
para fijar un contrato estable de JSON/eventos que terminal y OpenChamber consuman por igual.
|
|
95
|
+
|
|
96
|
+
## Dependencias que todavía estamos aislando
|
|
97
|
+
|
|
98
|
+
- E5 todavía invoca el comando `competitors` desde `--tool-dir`, pero solo con
|
|
99
|
+
`--legacy-e5`.
|
|
100
|
+
|
|
101
|
+
La DB y los artefactos ya son propios del workspace. No copié el histórico ni la herramienta
|
|
102
|
+
Chromium; si queremos que la CLI sea completamente autónoma, el siguiente corte es migrar el
|
|
103
|
+
dossier E5 y después trasladar reglas, decisiones y datos del laboratorio con trazabilidad.
|
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extraccion desde el DOM de Amazon. Solo lee lo que la pagina ya muestra.
|
|
3
|
+
* No pide datos a Amazon ni navega por su cuenta.
|
|
4
|
+
*/
|
|
5
|
+
(function () {
|
|
6
|
+
const P = window.KDPXParse;
|
|
7
|
+
|
|
8
|
+
const q = (sel, root) => (root || document).querySelector(sel);
|
|
9
|
+
const qa = (sel, root) => Array.from((root || document).querySelectorAll(sel));
|
|
10
|
+
const text = (el) => (el ? P.clean(el.innerText || el.textContent) : "");
|
|
11
|
+
const attr = (el, name) => (el ? P.clean(el.getAttribute(name) || "") : "");
|
|
12
|
+
|
|
13
|
+
function marketplace() {
|
|
14
|
+
const host = location.hostname.replace(/^www\./, "");
|
|
15
|
+
return host;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function pageKind() {
|
|
19
|
+
const p = location.pathname;
|
|
20
|
+
if (/^\/checkpoint\//.test(p) || /^\/ap\/signin/.test(p)) return "blocked";
|
|
21
|
+
if (/^\/(gp\/)?(bestsellers|zgbs)\//.test(p) || p.includes("/zgbs/")) return "bestsellers";
|
|
22
|
+
if (/\/(dp|gp\/product)\//.test(p)) return "product";
|
|
23
|
+
if (p === "/s" || p.startsWith("/s/")) return "search";
|
|
24
|
+
return "unknown";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function parsePageNumber() {
|
|
28
|
+
const m = location.search.match(/[?&]page=(\d+)/);
|
|
29
|
+
return m ? Number(m[1]) : 1;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function department() {
|
|
33
|
+
const sel = q("#searchDropdownBox option[selected]") || q("#searchDropdownBox");
|
|
34
|
+
const fromSelect = text(sel && sel.tagName === "OPTION" ? sel : q("#searchDropdownBox option:checked"));
|
|
35
|
+
if (fromSelect) return fromSelect.replace(/^Todos los departamentos$|^All Departments$/, "All");
|
|
36
|
+
const m = location.search.match(/[?&]i=([^&]+)/);
|
|
37
|
+
return m ? decodeURIComponent(m[1]) : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function sortOrder() {
|
|
41
|
+
const sel = q("#s-result-sort-select");
|
|
42
|
+
if (sel && sel.value) return sel.value;
|
|
43
|
+
const m = location.search.match(/[?&]s=([^&]+)/);
|
|
44
|
+
return m ? decodeURIComponent(m[1]) : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function baseMeta() {
|
|
48
|
+
const body = document.body ? document.body.innerText : "";
|
|
49
|
+
return {
|
|
50
|
+
marketplace: marketplace(),
|
|
51
|
+
currency: P.detectCurrency(body.slice(0, 20000)),
|
|
52
|
+
location: text(q("#glow-ingress-line2")) || null,
|
|
53
|
+
lang: document.documentElement.lang || null,
|
|
54
|
+
department: department(),
|
|
55
|
+
sort: sortOrder(),
|
|
56
|
+
page: parsePageNumber(),
|
|
57
|
+
url: location.href,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function firstPrice(root) {
|
|
62
|
+
const candidates = [
|
|
63
|
+
q("#corePriceDisplay_desktop_feature_div .a-price:not(.a-text-price) .a-offscreen", root),
|
|
64
|
+
q("#corePriceDisplay_desktop_feature_div .a-price .a-offscreen", root),
|
|
65
|
+
q("#price", root),
|
|
66
|
+
q(".a-price:not(.a-text-price) .a-offscreen", root),
|
|
67
|
+
q(".a-price .a-offscreen", root),
|
|
68
|
+
q("#priceblock_ourprice", root),
|
|
69
|
+
q("#priceblock_dealprice", root),
|
|
70
|
+
];
|
|
71
|
+
for (const el of candidates) {
|
|
72
|
+
const raw = text(el);
|
|
73
|
+
if (raw && /\d/.test(raw)) return { raw, el };
|
|
74
|
+
}
|
|
75
|
+
return { raw: "", el: null };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function firstRating(root) {
|
|
79
|
+
const el = q("[data-hook='rating-out-of-text']", root) || q("#acrPopover", root) || q(".a-icon-alt", root);
|
|
80
|
+
if (!el) return null;
|
|
81
|
+
return P.parseRating(text(el) || attr(el, "title") || attr(el, "aria-label"));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function firstReviews(root) {
|
|
85
|
+
const candidate =
|
|
86
|
+
q("#acrCustomerReviewText", root) ||
|
|
87
|
+
q("[data-hook='total-review-count']", root) ||
|
|
88
|
+
q("a[href*='#customerReviews'] span", root) ||
|
|
89
|
+
q(".s-underline-text", root);
|
|
90
|
+
if (!candidate) return null;
|
|
91
|
+
const count = P.parseReviewCount(text(candidate));
|
|
92
|
+
if (count != null) return count;
|
|
93
|
+
// Ultimo recurso: el primer texto con parentesis numerico.
|
|
94
|
+
const paren = qa("span, a", root).map(text).find((t) => /\(\s*[\d.,]+\s*[km]?\s*\)/i.test(t));
|
|
95
|
+
return paren ? P.parseReviewCount(paren) : null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function detailBullets() {
|
|
99
|
+
const selectors = [
|
|
100
|
+
"#detailBullets_feature_div li",
|
|
101
|
+
"#detailBulletsWrapper_feature_div li",
|
|
102
|
+
"#productDetails_detailBullets_sections1 tr",
|
|
103
|
+
"#productDetails_feature_div tr",
|
|
104
|
+
"#rpi-attribute-book_details-fiona-prelaunch tr",
|
|
105
|
+
];
|
|
106
|
+
const out = [];
|
|
107
|
+
for (const sel of selectors) for (const el of qa(sel)) {
|
|
108
|
+
const t = P.clean(el.innerText || el.textContent);
|
|
109
|
+
if (t) out.push(t);
|
|
110
|
+
}
|
|
111
|
+
return Array.from(new Set(out));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function labelValue(bullets, labels) {
|
|
115
|
+
for (const raw of bullets) {
|
|
116
|
+
const t = raw.replace(/\s*:\s*/g, ": ");
|
|
117
|
+
for (const label of labels) {
|
|
118
|
+
const re = new RegExp("^(?:" + label + ")\\s*:\\s*(.+)$", "i");
|
|
119
|
+
const m = t.match(re);
|
|
120
|
+
if (m) return P.clean(m[1]).replace(/^\s*:\s*/, "").trim();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function normalizeUrl(href) {
|
|
127
|
+
if (!href) return null;
|
|
128
|
+
try {
|
|
129
|
+
const u = new URL(href, location.origin);
|
|
130
|
+
const asin = (u.pathname.match(/\/(?:dp|gp\/product)\/([A-Z0-9]{10})/) || [])[1];
|
|
131
|
+
return asin ? `${location.origin}/dp/${asin}` : u.href;
|
|
132
|
+
} catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function asinFromUrl(href) {
|
|
138
|
+
if (!href) return null;
|
|
139
|
+
const m = String(href).match(/\/(?:dp|gp\/product)\/([A-Z0-9]{10})/);
|
|
140
|
+
return m ? m[1] : null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Texto de un shadow root abierto, sin estilos ni scripts. */
|
|
144
|
+
function shadowText(root) {
|
|
145
|
+
const parts = [];
|
|
146
|
+
const walk = (node) => {
|
|
147
|
+
for (const child of node.childNodes || []) {
|
|
148
|
+
if (child.nodeType === 3) parts.push(child.textContent);
|
|
149
|
+
else if (!/^(STYLE|SCRIPT|IMG|SVG)$/.test(child.nodeName)) walk(child);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
walk(root);
|
|
153
|
+
return P.clean(parts.join(" "));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Lee los datos que la extension gratuita PublishFlow dibuja sobre cada
|
|
158
|
+
* resultado: BSR general, categorias, paginas, fecha y ASIN.
|
|
159
|
+
* Es DOM ya visible en la pagina, no una llamada extra a Amazon.
|
|
160
|
+
*/
|
|
161
|
+
function publishFlowIndex() {
|
|
162
|
+
const map = new Map();
|
|
163
|
+
const boxes = document.querySelectorAll("pf-bsr-box");
|
|
164
|
+
for (const el of boxes) {
|
|
165
|
+
const asin = el.getAttribute("data-pf-asin") || el.closest("[data-asin]")?.getAttribute("data-asin");
|
|
166
|
+
if (!asin) continue;
|
|
167
|
+
const root = el.shadowRoot;
|
|
168
|
+
if (!root) continue;
|
|
169
|
+
const text = shadowText(root);
|
|
170
|
+
if (!text) continue;
|
|
171
|
+
|
|
172
|
+
const parsed = P.parsePublishFlowText(text);
|
|
173
|
+
const ranks = parsed.ranks;
|
|
174
|
+
const overall = ranks.find((r) => P.isOverallCategory(r.category)) || ranks[0] || null;
|
|
175
|
+
|
|
176
|
+
map.set(asin, {
|
|
177
|
+
bsrOverall: overall ? overall.rank : null,
|
|
178
|
+
bsrOverallCategory: overall ? overall.category : null,
|
|
179
|
+
bsr: ranks.map((r) => ({ ...r, isOverall: P.isOverallCategory(r.category) })),
|
|
180
|
+
pages: parsed.pages,
|
|
181
|
+
pubDate: parsed.pubDate,
|
|
182
|
+
price: parsed.price,
|
|
183
|
+
currency: parsed.currency,
|
|
184
|
+
format: parsed.format,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
return map;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Lee las tarjetas de CoAuthor (requiere cuenta gratis en ese perfil):
|
|
192
|
+
* ventas y regalias estimadas por dia, y BSR de la tarjeta.
|
|
193
|
+
*/
|
|
194
|
+
function coauthorIndex() {
|
|
195
|
+
const map = new Map();
|
|
196
|
+
const cards = document.querySelectorAll(".coauthor-mini, .coauthor-badge.coauthor-mini, .coauthor-mini-wrap");
|
|
197
|
+
for (const el of cards) {
|
|
198
|
+
const asin =
|
|
199
|
+
(el.querySelector(".coauthor-mini-asin-value")?.textContent || "").trim() ||
|
|
200
|
+
el.closest("[data-asin]")?.getAttribute("data-asin") ||
|
|
201
|
+
null;
|
|
202
|
+
if (!asin || asin.length < 6) continue;
|
|
203
|
+
const salesText = P.clean(el.querySelector(".coauthor-mini-sales")?.textContent || "");
|
|
204
|
+
const royaltyText = P.clean(el.querySelector(".coauthor-mini-royalty")?.textContent || "");
|
|
205
|
+
const bsrText = P.clean(el.querySelector(".coauthor-mini-bsr")?.textContent || "");
|
|
206
|
+
const sales = salesText ? P.parseRange(salesText + " Sales/Day", "Sales\\/Day") : null;
|
|
207
|
+
const royalty = royaltyText ? P.parseRange(royaltyText + " Royalty/Day", "Royalty\\/Day") : null;
|
|
208
|
+
const bsr = bsrText ? P.toNumber(bsrText.replace(/[^\d.,]/g, "")) : null;
|
|
209
|
+
map.set(asin, {
|
|
210
|
+
salesDayMin: sales ? sales.min : null,
|
|
211
|
+
salesDayMax: sales ? sales.max : null,
|
|
212
|
+
royaltyDayMin: royalty ? royalty.min : null,
|
|
213
|
+
royaltyDayMax: royalty ? royalty.max : null,
|
|
214
|
+
bsr: bsr == null ? null : Math.round(bsr),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
return map;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function extractSearch() {
|
|
221
|
+
const cards = qa("[data-component-type='s-search-result']");
|
|
222
|
+
const items = [];
|
|
223
|
+
cards.forEach((card, idx) => {
|
|
224
|
+
const asin = attr(card, "data-asin") || null;
|
|
225
|
+
if (!asin) return;
|
|
226
|
+
const fullText = P.clean(card.innerText);
|
|
227
|
+
const titleEl = q("h2 span", card) || q("h2", card) || q("[data-cy='title-recipe'] span", card);
|
|
228
|
+
const title = text(titleEl);
|
|
229
|
+
if (!title) return;
|
|
230
|
+
|
|
231
|
+
const link = q("a[href*='/dp/']", card);
|
|
232
|
+
const { raw: priceRaw } = firstPrice(card);
|
|
233
|
+
const price = P.parsePrice(priceRaw, fullText);
|
|
234
|
+
const sponsored =
|
|
235
|
+
P.isSponsored(fullText) || !!q("[data-component-type='sp-sponsored-result'], .s-sponsored-label-text", card);
|
|
236
|
+
const badge = text(q(".a-badge-label-inner, .a-badge-text", card)) || null;
|
|
237
|
+
|
|
238
|
+
// La linea del autor es la unica .a-row que empieza con "por"/"by".
|
|
239
|
+
const bylineText = qa(".a-row", card).map(text).find((t) => /^(por|by)\s+/i.test(t));
|
|
240
|
+
let author = bylineText
|
|
241
|
+
? bylineText
|
|
242
|
+
.replace(/^(por|by)\s+/i, "")
|
|
243
|
+
.split("|")[0]
|
|
244
|
+
.replace(/\s+(?:\d{1,2}\s+de\s+\w+|\w+\s+\d{1,2},?\s+\d{4}).*$/i, "")
|
|
245
|
+
.trim()
|
|
246
|
+
: "";
|
|
247
|
+
if (!author) {
|
|
248
|
+
const m = fullText.match(/(?:^|\s)(?:por|by)\s+([A-ZÁÉÍÓÚÑ][^|]{2,70}?)(?:\s+\d|\s*\|)/);
|
|
249
|
+
author = m ? m[1].trim() : "";
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
items.push({
|
|
253
|
+
asin,
|
|
254
|
+
position: idx + 1,
|
|
255
|
+
title,
|
|
256
|
+
author: author || null,
|
|
257
|
+
price: price.value,
|
|
258
|
+
priceRaw: price.raw || priceRaw || null,
|
|
259
|
+
currency: price.currency,
|
|
260
|
+
rating: firstRating(card),
|
|
261
|
+
reviews: firstReviews(card),
|
|
262
|
+
sponsored,
|
|
263
|
+
badge,
|
|
264
|
+
format:
|
|
265
|
+
qa(".a-row", card)
|
|
266
|
+
.map(text)
|
|
267
|
+
.filter((t) => /^(pasta dura|pasta blanda|tapa dura|tapa blanda|edici[oó]n kindle|kindle|audiolibro|hardcover|paperback|audiobook)$/i.test(t))
|
|
268
|
+
.map((t) => P.formatFromText(t))[0] || null,
|
|
269
|
+
ku: P.isKindleUnlimited(fullText),
|
|
270
|
+
url: normalizeUrl(link && link.href) || `${location.origin}/dp/${asin}`,
|
|
271
|
+
});
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
// Fusionar los datos de PublishFlow (si esta instalado) por ASIN.
|
|
275
|
+
const pf = publishFlowIndex();
|
|
276
|
+
for (const it of items) {
|
|
277
|
+
const extra = pf.get(it.asin);
|
|
278
|
+
if (!extra) continue;
|
|
279
|
+
it.bsrOverall = it.bsrOverall ?? extra.bsrOverall;
|
|
280
|
+
it.bsrOverallCategory = it.bsrOverallCategory ?? extra.bsrOverallCategory;
|
|
281
|
+
it.bsr = it.bsr ?? extra.bsr;
|
|
282
|
+
it.pages = it.pages ?? extra.pages;
|
|
283
|
+
it.pubDate = it.pubDate ?? extra.pubDate;
|
|
284
|
+
if (it.price == null && extra.price != null) {
|
|
285
|
+
it.price = extra.price;
|
|
286
|
+
it.currency = it.currency || extra.currency;
|
|
287
|
+
}
|
|
288
|
+
it.format = it.format || extra.format;
|
|
289
|
+
it.raw = { ...(it.raw || {}), publishflow: true };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Fusionar estimaciones de CoAuthor (si esta logueado en el perfil).
|
|
293
|
+
const ca = coauthorIndex();
|
|
294
|
+
for (const it of items) {
|
|
295
|
+
const extra = ca.get(it.asin);
|
|
296
|
+
if (!extra) continue;
|
|
297
|
+
it.bsrOverall = it.bsrOverall ?? extra.bsr;
|
|
298
|
+
it.salesDayMin = extra.salesDayMin;
|
|
299
|
+
it.salesDayMax = extra.salesDayMax;
|
|
300
|
+
it.royaltyDayMin = extra.royaltyDayMin;
|
|
301
|
+
it.royaltyDayMax = extra.royaltyDayMax;
|
|
302
|
+
it.estimateSource = "coauthor";
|
|
303
|
+
it.raw = { ...(it.raw || {}), coauthor: true };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const infoRaw = text(q("[data-component-type='s-result-info-bar']")) || "";
|
|
307
|
+
// Quedarse con la frase de resultados, antes del selector de orden.
|
|
308
|
+
const info = infoRaw.split(/Ordenar por|Sort by/i)[0];
|
|
309
|
+
const total = P.parseTotalResults(info);
|
|
310
|
+
|
|
311
|
+
return {
|
|
312
|
+
kind: "search",
|
|
313
|
+
items,
|
|
314
|
+
totalResultsText: total.text,
|
|
315
|
+
totalResults: total.total,
|
|
316
|
+
totalResultsIsOver: total.isOver,
|
|
317
|
+
keyword: new URLSearchParams(location.search).get("k") || null,
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function extractReviews() {
|
|
322
|
+
return qa("[data-hook='review']").slice(0, 10).map((el) => {
|
|
323
|
+
const titleRaw = text(q("[data-hook='review-title']", el));
|
|
324
|
+
const rating = P.parseRating(text(q(".a-icon-alt", el)));
|
|
325
|
+
const date = text(q("[data-hook='review-date']", el));
|
|
326
|
+
const verified = !!q("[data-hook='avp-badge']", el);
|
|
327
|
+
const body = text(q("[data-hook='review-body']", el)).slice(0, 1200);
|
|
328
|
+
return { title: titleRaw.slice(0, 160), rating, date, verified, body };
|
|
329
|
+
}).filter((r) => r.body);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function extractProduct() {
|
|
333
|
+
const asin =
|
|
334
|
+
asinFromUrl(location.href) ||
|
|
335
|
+
(q("#ASIN") && q("#ASIN").value) ||
|
|
336
|
+
null;
|
|
337
|
+
const title = text(q("#productTitle")) || null;
|
|
338
|
+
const bullets = detailBullets();
|
|
339
|
+
const joined = bullets.join(" | ");
|
|
340
|
+
const rankList = P.parseRankList(joined);
|
|
341
|
+
const { raw: priceRaw } = firstPrice(document);
|
|
342
|
+
const price = P.parsePrice(priceRaw, text(q("#corePriceDisplay_desktop_feature_div")) || text(q("#buybox")));
|
|
343
|
+
const formatRaw =
|
|
344
|
+
text(q("#tmmSwatches .swatchElement.selected .a-button-text")) ||
|
|
345
|
+
text(q("#tmmSwatches .selected")) ||
|
|
346
|
+
text(q("#productSubtitle")) ||
|
|
347
|
+
"";
|
|
348
|
+
const format = P.formatFromText(formatRaw) || P.formatFromText(title || "") || formatRaw || null;
|
|
349
|
+
|
|
350
|
+
const split = P.splitTitleSubtitle(title || "");
|
|
351
|
+
const subtitle = text(q("#productSubtitle")) || split.subtitle || null;
|
|
352
|
+
|
|
353
|
+
const description =
|
|
354
|
+
text(q("#bookDescription_feature_div")) ||
|
|
355
|
+
text(q("#productDescription")) ||
|
|
356
|
+
text(q("#bookDescription_feature_div .a-expander-content")) ||
|
|
357
|
+
null;
|
|
358
|
+
|
|
359
|
+
const coverEl = q("#landingImage") || q("#imgTagWrapperId img") || q("#main-image-container img");
|
|
360
|
+
const coverUrl = coverEl ? attr(coverEl, "data-old-hires") || attr(coverEl, "src") || null : null;
|
|
361
|
+
|
|
362
|
+
const reviewSamples = extractReviews();
|
|
363
|
+
const customersSay =
|
|
364
|
+
text(q("[data-hook='cr-insights-widget-summary']")) ||
|
|
365
|
+
text(q("#cr-product-insights-cards")) ||
|
|
366
|
+
text(q("[data-hook='cr-insights-widget']")) ||
|
|
367
|
+
null;
|
|
368
|
+
|
|
369
|
+
const series = bullets.find((b) => /^(Parte de|Book \d+ of|Series:)/i.test(b)) || null;
|
|
370
|
+
const aplus = !!q("#aplus");
|
|
371
|
+
const editorial = text(q("#editorialReviews_feature_div")).slice(0, 3000) || null;
|
|
372
|
+
|
|
373
|
+
const publisher = labelValue(bullets, ["Editorial", "Publisher", "Editado por", "Published by"]);
|
|
374
|
+
const pubDateRaw = labelValue(bullets, ["Fecha de publicación", "Publication date", "Fecha de publicaci[oó]n"]);
|
|
375
|
+
const pagesRaw = labelValue(bullets, ["Número de páginas", "Print length", "Páginas", "Pages"]);
|
|
376
|
+
const isbnRaw = labelValue(bullets, ["ISBN-13", "ISBN 13"]);
|
|
377
|
+
const overall = rankList.find((r) => P.isOverallCategory(r.category));
|
|
378
|
+
|
|
379
|
+
return {
|
|
380
|
+
kind: "product",
|
|
381
|
+
items: [
|
|
382
|
+
{
|
|
383
|
+
asin,
|
|
384
|
+
position: 1,
|
|
385
|
+
title,
|
|
386
|
+
author: text(q("#bylineInfo")).replace(/^(visitar|visit)\s+/i, "").replace(/^(la página del autor|author page)\s*/i, "") || null,
|
|
387
|
+
price: price.value,
|
|
388
|
+
priceRaw: price.raw || priceRaw || null,
|
|
389
|
+
currency: price.currency,
|
|
390
|
+
rating: firstRating(document),
|
|
391
|
+
reviews: firstReviews(document),
|
|
392
|
+
sponsored: false,
|
|
393
|
+
badge: null,
|
|
394
|
+
format,
|
|
395
|
+
publisher,
|
|
396
|
+
pubDate: P.parseDate(pubDateRaw || ""),
|
|
397
|
+
pages: P.parsePages(pagesRaw || ""),
|
|
398
|
+
isbn13: P.parseIsbn13(isbnRaw || "") || P.parseIsbn13(asin || ""),
|
|
399
|
+
bsrOverall: overall ? overall.rank : null,
|
|
400
|
+
bsrOverallCategory: overall ? overall.category : null,
|
|
401
|
+
bsr: rankList.map((r) => ({ ...r, isOverall: P.isOverallCategory(r.category) })),
|
|
402
|
+
ku: P.isKindleUnlimited(text(q("#buybox"))),
|
|
403
|
+
url: `${location.origin}/dp/${asin}`,
|
|
404
|
+
subtitle,
|
|
405
|
+
description: description ? description.slice(0, 8000) : null,
|
|
406
|
+
coverUrl,
|
|
407
|
+
reviewSamples,
|
|
408
|
+
dossier: {
|
|
409
|
+
customersSay: customersSay ? customersSay.slice(0, 1500) : null,
|
|
410
|
+
series,
|
|
411
|
+
aplus,
|
|
412
|
+
editorial,
|
|
413
|
+
},
|
|
414
|
+
raw: { bullets, reviewCount: reviewSamples.length },
|
|
415
|
+
},
|
|
416
|
+
],
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function extractBestsellers() {
|
|
421
|
+
const cells = qa("#gridItemRoot, [data-testid='grid'] > div, .zg-grid-general-faceout");
|
|
422
|
+
const items = [];
|
|
423
|
+
const seen = new Set();
|
|
424
|
+
cells.forEach((cell, idx) => {
|
|
425
|
+
const link = q("a[href*='/dp/']", cell);
|
|
426
|
+
const asin = asinFromUrl(link && link.href);
|
|
427
|
+
if (!asin || seen.has(asin)) return;
|
|
428
|
+
seen.add(asin);
|
|
429
|
+
const fullText = P.clean(cell.innerText);
|
|
430
|
+
const title =
|
|
431
|
+
text(q("._cDEzb_p13n-sc-css-line-clamp-3_g3dy1", cell)) ||
|
|
432
|
+
text(q(".p13n-sc-truncate-desktop-type2", cell)) ||
|
|
433
|
+
text(q("a span div", cell)) ||
|
|
434
|
+
text(link);
|
|
435
|
+
const rankRaw = text(q(".zg-bdg-text, .zg-badge-text", cell)) || fullText.slice(0, 12);
|
|
436
|
+
const { raw: priceRaw } = firstPrice(cell);
|
|
437
|
+
const price = P.parsePrice(priceRaw, fullText);
|
|
438
|
+
const ratingEl = q(".a-icon-alt", cell);
|
|
439
|
+
const reviewsEl = q("a[href*='#customerReviews'] .a-size-small, .a-size-small", cell);
|
|
440
|
+
const reviewsFallback =
|
|
441
|
+
(fullText.match(/\(\s*([\d.,]+\s*[km]?)\s*\)/i) || [])[1] ||
|
|
442
|
+
(fullText.match(/estrellas\s+([\d.,]+\s*[km]?)/i) || [])[1] ||
|
|
443
|
+
(fullText.match(/stars\s+([\d.,]+\s*[km]?)/i) || [])[1] ||
|
|
444
|
+
null;
|
|
445
|
+
|
|
446
|
+
items.push({
|
|
447
|
+
asin,
|
|
448
|
+
position: P.parseBestsellerRank(rankRaw) || idx + 1,
|
|
449
|
+
title,
|
|
450
|
+
author: null,
|
|
451
|
+
price: price.value,
|
|
452
|
+
priceRaw: price.raw || null,
|
|
453
|
+
currency: price.currency,
|
|
454
|
+
rating: P.parseRating(text(ratingEl)),
|
|
455
|
+
reviews: P.parseReviewCount(text(reviewsEl)) ?? P.parseReviewCount(reviewsFallback),
|
|
456
|
+
sponsored: false,
|
|
457
|
+
badge: null,
|
|
458
|
+
format: null,
|
|
459
|
+
url: `${location.origin}/dp/${asin}`,
|
|
460
|
+
raw: { text: fullText.slice(0, 500) },
|
|
461
|
+
});
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
return {
|
|
465
|
+
kind: "bestsellers",
|
|
466
|
+
items,
|
|
467
|
+
totalResultsText: null,
|
|
468
|
+
totalResults: items.length,
|
|
469
|
+
totalResultsIsOver: false,
|
|
470
|
+
keyword: null,
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function extractSuggestions() {
|
|
475
|
+
const box = q("#sac-autocomplete-results-container, .s-suggestions");
|
|
476
|
+
if (!box) return [];
|
|
477
|
+
const nodes = qa(".s-suggestion, .s-suggestion-container, [role='option']", box);
|
|
478
|
+
const phrases = [];
|
|
479
|
+
for (const n of nodes) {
|
|
480
|
+
const t = text(n).replace(/^[\u2191\u2193]/, "").trim();
|
|
481
|
+
if (t && !phrases.includes(t)) phrases.push(t);
|
|
482
|
+
}
|
|
483
|
+
return phrases;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function collect(kindOverride) {
|
|
487
|
+
const kind = kindOverride || pageKind();
|
|
488
|
+
const meta = baseMeta();
|
|
489
|
+
if (kind === "search") return { ...meta, ...extractSearch() };
|
|
490
|
+
if (kind === "product") return { ...meta, ...extractProduct() };
|
|
491
|
+
if (kind === "bestsellers") return { ...meta, ...extractBestsellers() };
|
|
492
|
+
return { ...meta, kind: "unknown", items: [] };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
window.KDPXExtract = {
|
|
496
|
+
hasPublishFlow: () => document.querySelectorAll("pf-bsr-box").length > 0,
|
|
497
|
+
publishFlowCount: () => document.querySelectorAll("pf-bsr-box[data-pf-asin]").length,
|
|
498
|
+
pageKind,
|
|
499
|
+
baseMeta,
|
|
500
|
+
extractSearch,
|
|
501
|
+
extractProduct,
|
|
502
|
+
extractBestsellers,
|
|
503
|
+
extractSuggestions,
|
|
504
|
+
collect,
|
|
505
|
+
countSearchCards: () => qa("[data-component-type='s-search-result']").length,
|
|
506
|
+
countBestsellerCells: () => qa("#gridItemRoot, [data-testid='grid'] > div, .zg-grid-general-faceout").length,
|
|
507
|
+
};
|
|
508
|
+
})();
|