Repository navigation
Expand file tree
/
Copy pathrecipe-parser.js
More file actions
239 lines (201 loc) · 5.57 KB
/
Copy pathrecipe-parser.js
File metadata and controls
239 lines (201 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Client-side mirror of recipe_importer.py, used only when the app runs
// without a backend (file:// mode). Keep the two in sync: both read the
// same JSON-LD Recipe shape and fall back to the same heading keywords.
export function extractRecipeFromHtml(doc, sourceUrl, uuid = () => cryptoRandomUUID()) {
const jsonLdScripts = Array.from(
doc.querySelectorAll('script[type="application/ld+json"]')
);
const candidateRecipes = jsonLdScripts
.flatMap((script) => parseJsonLd(script.textContent))
.flatMap(flattenJsonLdNodes)
.filter((entry) => isRecipeNode(entry));
const recipeNode = candidateRecipes[0];
if (!recipeNode) {
return extractRecipeFromVisibleHtml(doc, sourceUrl, uuid);
}
const instructions = normalizeInstructions(recipeNode.recipeInstructions);
const ingredients = normalizeStringList(recipeNode.recipeIngredient);
const description = normalizeText(recipeNode.description);
const title = normalizeText(recipeNode.name) || inferTitleFromUrl(sourceUrl);
const image = normalizeImage(recipeNode.image);
const servings = extractServings(recipeNode.recipeYield);
return {
id: uuid(),
title,
sourceUrl,
description,
ingredients,
instructions,
method: instructions.join(" "),
image,
servings,
importedAt: new Date().toISOString(),
};
}
export function extractRecipeFromVisibleHtml(doc, sourceUrl, uuid = () => cryptoRandomUUID()) {
const title =
normalizeText(doc.querySelector("h1")?.textContent) || inferTitleFromUrl(sourceUrl);
const ingredients = gatherListAfterHeading(doc, ["ingredients"]);
const instructions = gatherListAfterHeading(doc, [
"instructions",
"method",
"directions",
"preparation",
]);
const description = normalizeText(
doc.querySelector('meta[name="description"]')?.getAttribute("content")
);
return {
id: uuid(),
title,
sourceUrl,
description,
ingredients,
instructions,
method: instructions.join(" "),
image: "",
servings: null,
importedAt: new Date().toISOString(),
};
}
export function gatherListAfterHeading(doc, keywords) {
const headings = Array.from(doc.querySelectorAll("h1, h2, h3, h4, strong, b"));
const match = headings.find((heading) => {
const text = normalizeText(heading.textContent).toLowerCase();
return keywords.some((keyword) => text === keyword || text.includes(keyword));
});
if (!match) {
return [];
}
let sibling = match.nextElementSibling;
while (sibling) {
if (["UL", "OL"].includes(sibling.tagName)) {
return Array.from(sibling.querySelectorAll("li"))
.map((item) => normalizeText(item.textContent))
.filter(Boolean);
}
if (sibling.tagName === "P") {
const lines = sibling.textContent
.split(/\n|\. /)
.map((line) => normalizeText(line))
.filter(Boolean);
if (lines.length) {
return lines;
}
}
sibling = sibling.nextElementSibling;
}
return [];
}
export function parseJsonLd(text) {
if (!text) {
return [];
}
try {
const parsed = JSON.parse(text);
return Array.isArray(parsed) ? parsed : [parsed];
} catch (error) {
return [];
}
}
export function flattenJsonLdNodes(node) {
if (!node) {
return [];
}
const graph = Array.isArray(node["@graph"]) ? node["@graph"] : [];
return [node, ...graph];
}
export function isRecipeNode(node) {
const type = node["@type"];
if (Array.isArray(type)) {
return type.includes("Recipe");
}
return type === "Recipe";
}
export function normalizeInstructions(input) {
if (!input) {
return [];
}
if (Array.isArray(input)) {
return input
.flatMap((entry) => {
if (typeof entry === "string") {
return [entry];
}
if (entry?.text) {
return [entry.text];
}
if (Array.isArray(entry?.itemListElement)) {
return entry.itemListElement.map((item) => item.text || "");
}
return [];
})
.map((entry) => normalizeText(entry))
.filter(Boolean);
}
if (typeof input === "string") {
return input
.split(/\n+/)
.map((entry) => normalizeText(entry))
.filter(Boolean);
}
return [];
}
export function normalizeStringList(input) {
if (!input) {
return [];
}
return (Array.isArray(input) ? input : [input])
.map((entry) => normalizeText(String(entry)))
.filter(Boolean);
}
export function normalizeImage(image) {
if (!image) {
return "";
}
if (typeof image === "string") {
return image;
}
if (Array.isArray(image)) {
return typeof image[0] === "string" ? image[0] : image[0]?.url || "";
}
return image.url || "";
}
// recipeYield can be "4", "4 servings", or a list of those; pull the first number out.
export function extractServings(raw) {
if (raw === null || raw === undefined) {
return null;
}
const values = Array.isArray(raw) ? raw : [raw];
for (const value of values) {
const match = String(value).match(/\d+/);
if (match) {
return Number(match[0]);
}
}
return null;
}
export function normalizeText(value) {
return String(value || "")
.replace(/\s+/g, " ")
.replace(/\u00a0/g, " ")
.trim();
}
export function inferTitleFromUrl(url) {
try {
const path = new URL(url).pathname
.split("/")
.filter(Boolean)
.pop();
return path
? path
.replace(/[-_]/g, " ")
.replace(/\b\w/g, (letter) => letter.toUpperCase())
: "Imported Recipe";
} catch (error) {
return "Imported Recipe";
}
}
function cryptoRandomUUID() {
return crypto.randomUUID();
}