njsparser 0.1.0 → 0.2.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.
@@ -1,33 +1,36 @@
1
- import { make_tree } from '../utils.js';
1
+ /**
2
+ * Next data extraction from __NEXT_DATA__ script
3
+ */
4
+
5
+ import { makeTree } from '../utils.js';
2
6
 
3
7
  /**
4
- * Returns the dict content of the `<script id='__NEXT_DATA__'>`, if it exists.
5
- * @param {any} value
6
- * @returns {object | null}
8
+ * Extract and parse __NEXT_DATA__ script content
9
+ * @param {string} html - HTML string
10
+ * @param {DOMParser} DOMParser - DOMParser instance
11
+ * @returns {Object|null} Parsed JSON data or null
7
12
  */
8
- export const get_next_data = (value) => {
9
- const $ = make_tree(value);
10
- const nextdata = $("#__NEXT_DATA__");
11
-
12
- if (nextdata.length > 0) {
13
- if (nextdata.length !== 1) {
14
- console.warn(`invalid nextdata length ${nextdata.length}`);
15
- }
16
- try {
17
- return JSON.parse(nextdata.html().trim());
18
- } catch (e) {
19
- console.error("Failed to parse __NEXT_DATA__ json", e);
20
- return null;
21
- }
22
- }
13
+ export function getNextData(html, DOMParser) {
14
+ const doc = makeTree(html, DOMParser);
15
+ const script = doc.querySelector('script#__NEXT_DATA__');
16
+
17
+ if (!script || !script.textContent) {
18
+ return null;
19
+ }
20
+
21
+ try {
22
+ return JSON.parse(script.textContent.trim());
23
+ } catch (e) {
23
24
  return null;
24
- };
25
+ }
26
+ }
25
27
 
26
28
  /**
27
- * Tells if the given page contains a `<script id='__NEXT_DATA__'>`.
28
- * @param {any} value
29
- * @returns {boolean}
29
+ * Check if HTML contains __NEXT_DATA__ script
30
+ * @param {string} html - HTML string
31
+ * @param {DOMParser} DOMParser - DOMParser instance
32
+ * @returns {boolean} True if __NEXT_DATA__ exists
30
33
  */
31
- export const has_next_data = (value) => {
32
- return get_next_data(value) !== null;
33
- };
34
+ export function hasNextData(html, DOMParser) {
35
+ return getNextData(html, DOMParser) !== null;
36
+ }