-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.go
More file actions
270 lines (235 loc) · 7.11 KB
/
Copy pathschema.go
File metadata and controls
270 lines (235 loc) · 7.11 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package defuddle
import (
"encoding/json"
"fmt"
"log/slog"
"regexp"
"strings"
"github.com/PuerkitoBio/goquery"
)
// Pre-compiled regex patterns for JSON-LD content cleaning.
var (
htmlCommentRe = regexp.MustCompile(`<!--[\s\S]*?-->`)
jsCommentRe = regexp.MustCompile(`/\*[\s\S]*?\*/|^\s*//.*$`)
cdataRe = regexp.MustCompile(`^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$`)
commentMarkerRe = regexp.MustCompile(`^\s*(\*/|/\*)\s*|\s*(\*/|/\*)\s*$`)
)
// extractSchemaOrgData extracts and processes schema.org structured data using JSON-LD processor
// JavaScript original code:
//
// private _extractSchemaOrgData(document: Document) {
// const schemaItems = [];
// const scripts = document.querySelectorAll('script[type="application/ld+json"]');
//
// scripts.forEach(script => {
// try {
// const jsonData = JSON.parse(script.textContent);
// if (jsonData['@graph']) {
// schemaItems.push(...jsonData['@graph']);
// } else {
// schemaItems.push(jsonData);
// }
// } catch (e) {
// console.warn('Failed to parse schema.org data:', e);
// }
// });
//
// return schemaItems;
// }
func (d *Defuddle) extractSchemaOrgData() any {
var allSchemaItems []any
if d.debugger.IsEnabled() {
d.debugger.StartTimer("schema_extraction")
}
d.doc.Find(`script[type="application/ld+json"]`).Each(func(i int, script *goquery.Selection) {
allSchemaItems = append(allSchemaItems, d.schemaItemsFromScript(script, i)...)
})
if d.debugger.IsEnabled() {
d.debugger.EndTimer("schema_extraction")
d.debugger.AddProcessingStep("schema_org_extraction",
fmt.Sprintf("Extracted %d schema.org items", len(allSchemaItems)),
len(allSchemaItems), "")
}
if d.debug {
slog.Debug("Schema.org data extraction completed",
"total_items", len(allSchemaItems),
"unique_types", d.countSchemaTypes(allSchemaItems))
}
return allSchemaItems
}
// schemaItemsFromScript parses one ld+json <script> into schema.org items,
// returning nil when the script is empty or unparseable.
func (d *Defuddle) schemaItemsFromScript(script *goquery.Selection, i int) []any {
jsonContent := strings.TrimSpace(script.Text())
if jsonContent == "" {
return nil
}
// Clean and validate JSON-LD content
cleanedContent := d.cleanJSONLDContent(jsonContent)
if cleanedContent == "" {
if d.debug {
slog.Debug("Empty JSON-LD content after cleaning", "index", i)
}
return nil
}
// Parse JSON — matching TS which uses JSON.parse() directly
var rawData any
if err := json.Unmarshal([]byte(cleanedContent), &rawData); err != nil {
if d.debug {
slog.Debug("Failed to parse schema.org JSON-LD",
"error", err,
"index", i,
"content_preview", cleanedContent[:min(len(cleanedContent), 100)])
}
return nil
}
// Extract items from parsed data
return d.extractSchemaItems(rawData)
}
// cleanJSONLDContent cleans and normalizes JSON-LD content
// JavaScript original code:
//
// // Remove comments, CDATA, and other non-JSON content
func (d *Defuddle) cleanJSONLDContent(content string) string {
// Remove HTML comments
content = htmlCommentRe.ReplaceAllString(content, "")
// Remove JavaScript-style comments
content = jsCommentRe.ReplaceAllString(content, "")
// Handle CDATA sections
if matches := cdataRe.FindStringSubmatch(content); len(matches) > 1 {
content = matches[1]
}
// Remove comment markers that might be left
content = commentMarkerRe.ReplaceAllString(content, "")
// Remove leading/trailing whitespace
content = strings.TrimSpace(content)
// Basic JSON validation - check if it starts and ends correctly
isValidJSON := (strings.HasPrefix(content, "{") && strings.HasSuffix(content, "}")) ||
(strings.HasPrefix(content, "[") && strings.HasSuffix(content, "]"))
if content != "" && !isValidJSON {
if d.debug {
slog.Debug("Invalid JSON-LD format detected", "content_preview", content[:min(len(content), 50)])
}
return ""
}
return content
}
// extractSchemaItems extracts individual schema items from parsed JSON-LD data
// JavaScript original code:
//
// // Handle both single items and @graph arrays
func (d *Defuddle) extractSchemaItems(data any) []any {
var items []any
switch typedData := data.(type) {
case map[string]any:
// Check for @graph property (common in schema.org JSON-LD)
if graph, exists := typedData["@graph"]; exists {
if graphArray, ok := graph.([]any); ok {
items = append(items, graphArray...)
} else {
items = append(items, graph)
}
} else {
// Single item
items = append(items, typedData)
}
case []any:
// Array of items (from JSON-LD expansion)
items = append(items, typedData...)
default:
// Single item of unknown type
items = append(items, data)
}
// Filter and validate schema items
var validItems []any
for _, item := range items {
if d.isValidSchemaItem(item) {
validItems = append(validItems, item)
}
}
return validItems
}
// isValidSchemaItem validates if an item is a valid schema.org item
// JavaScript original code:
//
// // Check for @type or other schema.org indicators
func (d *Defuddle) isValidSchemaItem(item any) bool {
itemMap, ok := item.(map[string]any)
if !ok {
return false
}
// Check for @type or type property (required for schema.org items)
var itemType any
var exists bool
if itemType, exists = itemMap["@type"]; !exists {
itemType, exists = itemMap["type"]
}
if exists {
switch typedValue := itemType.(type) {
case string:
return typedValue != ""
case []any:
return len(typedValue) > 0
}
}
// Check for schema.org URL in @id
if itemID, exists := itemMap["@id"]; exists {
if idStr, ok := itemID.(string); ok {
return strings.Contains(idStr, "schema.org") ||
strings.Contains(idStr, "http") // Any URL-like identifier
}
}
// Check if it has common schema.org properties
commonProps := []string{"name", "description", "url", "image", "author", "publisher"}
propCount := 0
for _, prop := range commonProps {
if _, exists := itemMap[prop]; exists {
propCount++
}
}
// Consider valid if it has multiple common properties
return propCount >= 2
}
// countSchemaTypes counts unique schema types for debugging
// JavaScript original code:
//
// // Helper for debugging and logging
func (d *Defuddle) countSchemaTypes(items []any) int {
typeSet := make(map[string]bool)
for _, item := range items {
for _, t := range schemaItemTypes(item) {
typeSet[t] = true
}
}
return len(typeSet)
}
// schemaItemTypes returns the JSON-LD type values of a schema item: read from
// @type or (post-JSON-LD-processing) type, each of which may be a single string
// or an array of strings. Returns nil when item is not a typed object.
func schemaItemTypes(item any) []string {
itemMap, ok := item.(map[string]any)
if !ok {
return nil
}
// Check both @type and type (after JSON-LD processing)
itemType, exists := itemMap["@type"]
if !exists {
itemType, exists = itemMap["type"]
}
if !exists {
return nil
}
switch typedValue := itemType.(type) {
case string:
return []string{typedValue}
case []any:
var types []string
for _, t := range typedValue {
if typeStr, ok := t.(string); ok {
types = append(types, typeStr)
}
}
return types
}
return nil
}