11import fs from 'fs' ;
22import path from 'path' ;
3- import { json } from 'stream/consumers ' ;
3+ import { fileURLToPath } from 'url ' ;
44
5- export default ( inputUrl ) => {
6- if ( ! inputUrl ) {
7- return '请输入 URL' ;
8- }
9- if ( / \. ( e d u | v p n ) ( \/ | \. | $ ) / . test ( inputUrl ) ) {
10- return '请勿提交机构代理的 URL' ;
11- }
12- if ( / \. c n k i \. / . test ( inputUrl ) ) {
13- return '该 url 已通过 CNKI.js 适配。' ;
5+ // 兼容 ES Module 环境下的 __dirname
6+ const __filename = fileURLToPath ( import . meta. url ) ;
7+ const __dirname = path . dirname ( __filename ) ;
8+
9+ export default function validate ( inputUrl ) {
10+ if ( ! inputUrl ) {
11+ return '请输入 URL' ;
12+ }
13+ if ( / \. ( e d u | v p n ) ( \/ | \. | $ ) / . test ( inputUrl ) ) {
14+ return '请勿提交机构代理的 URL' ;
15+ }
16+ if ( / \. c n k i \. / . test ( inputUrl ) ) {
17+ return '该 url 已通过 CNKI.js 适配。' ;
18+ }
19+
20+ const rootDir = path . resolve ( __dirname , '../../..' ) ;
21+ let files ;
22+ try {
23+ files = fs . readdirSync ( rootDir ) . filter ( f => f . endsWith ( '.js' ) ) ;
24+ } catch ( e ) {
25+ return '读取仓库文件失败' ;
26+ }
27+
28+ for ( const file of files ) {
29+ const filePath = path . join ( rootDir , file ) ;
30+ let content ;
31+ try {
32+ content = fs . readFileSync ( filePath , 'utf8' ) ;
33+ } catch {
34+ continue ;
1435 }
36+ const metaMatch = content . match ( / ^ \{ [ \s \S ] * ?\} / ) ;
37+ if ( ! metaMatch ) continue ;
1538
16- const rootDir = path . resolve ( __dirname , '../../..' ) ;
17- const files = fs . readdirSync ( rootDir ) . filter ( f => f . endsWith ( '.js' ) ) ;
18- let matched = false ;
39+ let meta ;
40+ try {
41+ meta = JSON . parse ( metaMatch [ 0 ] ) ;
42+ } catch {
43+ continue ;
44+ }
45+ if ( ! meta ?. target || ! meta ?. label ) continue ;
1946
20- for ( const file of files ) {
21- const filePath = path . join ( rootDir , file ) ;
22- const content = fs . readFileSync ( filePath , 'utf8' ) ;
23- const meta = content . match ( / ^ \{ [ \s \S ] * ?\} / ) ;
24- if ( meta ) {
25- try {
26- const json = JSON . parse ( meta ) ;
27- if ( json . target && new RegExp ( json . target ) . test ( inputUrl ) ) {
28- return `该 url 已通过 ${ json . label } .js 适配。` ;
29- }
30- } catch ( e ) {
31- console . error ( `Error parsing JSON in ${ file } :` , e ) ;
32- continue ;
33- }
34- }
47+ let re ;
48+ try {
49+ re = new RegExp ( meta . target ) ;
50+ } catch {
51+ continue ;
3552 }
36- return 'success' ;
53+ if ( re . test ( inputUrl ) ) {
54+ return `该 url 已通过 ${ meta . label } .js 适配。` ;
55+ }
56+ }
57+
58+ return 'success' ;
3759}
0 commit comments