-
Notifications
You must be signed in to change notification settings - Fork 0
/
hvml.js
398 lines (351 loc) · 13.4 KB
/
hvml.js
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
const fs = require( 'fs' );
const { extname } = require( 'path' );
const { exec } = require( 'child_process' );
const HVMLElement = require( './hvml-element' );
const Video = require( './video' );
const Series = require( './series' );
const Group = require( './group' );
const Validation = require( './util/validation' );
const { hasProperty } = require( './util/types.js' );
const Data = require( './util/data' );
let xml;
let canParseXml = false;
try {
xml = require( 'libxmljs' ); /* eslint-disable-line global-require */ /* eslint-disable-line import/no-extraneous-dependencies */
/* istanbul ignore next */
if ( hasProperty( xml, 'parseXmlString' ) ) {
canParseXml = true;
}
} catch ( error ) {
// eslint-disable-line no-empty
}
// const elements = {
// Series,
// Group,
// Video,
// };
class HVML extends HVMLElement {
constructor( path, config = {} ) {
super();
/*
fs.readFile(path[, options], callback)
- path <string> | <Buffer> | <URL> | <integer> filename or file descriptor
- options <Object> | <string>
- encoding <string> | <null> Default: null
- flag <string> See support of file system flags. Default: 'r'.
- callback <Function>
- err <Error>
- data <string> | <Buffer>
*/
const defaultConfig = {
"schemaPath": "rng/hvml.rng",
"schemaType": "rng",
"encoding": "utf8",
};
config = {
...defaultConfig,
...config,
};
this.namespaces = {
"html": "http://www.w3.org/1999/xhtml",
"hvml": "https://hypervideo.tech/hvml#",
"xlink": "http://www.w3.org/1999/xlink",
"css": "https://www.w3.org/TR/CSS/",
"rng": "http://relaxng.org/ns/structure/1.0",
};
this.fileExtensions = {
"xml": [
"xml",
"ovml",
"hvml",
// "rng",
],
"json": [
"json",
"jsonld",
],
};
this.prefixes = Object.keys( this.namespaces )
.reduce( ( accumulator, currentPrefix ) => {
accumulator[this.namespaces[currentPrefix]] = currentPrefix;
return accumulator;
}, {} );
this.schemaPath = config.schemaPath;
this.schemaType = config.schemaType;
if ( path ) {
const fileReady = ( new Promise( ( resolve, reject ) => {
fs.readFile( path, config.encoding, ( error, data ) => {
if ( error ) {
// throw new Error( error );
reject( error );
}
resolve( data );
} );
} ) );
const schemaReady = ( new Promise( ( resolve, reject ) => {
fs.readFile( this.schemaPath, 'utf8', ( error, data ) => {
if ( error ) {
reject( error );
}
resolve( data );
} );
} ) );
this.ready = Promise.all( [fileReady, schemaReady] ).then( ( data ) => {
const fileContents = data[0];
const extension = extname( path ).slice( 1 );
const isXml = ( this.fileExtensions.xml.indexOf( extension ) !== -1 );
const isJson = ( this.fileExtensions.json.indexOf( extension ) !== -1 );
if ( isXml ) {
if ( !canParseXml ) {
throw new Validation.OptionalDependencyNotInstalled( {
"className": "HVML",
"fieldName": "ready",
"dependency": "libxmljs",
} );
}
this.xml = xml.parseXmlString( fileContents );
this.json = null;
this.hvmlPath = path;
this.children = [];
// this.xsd = xml.parseXmlString( data[1] );
return this.xml;
}
if ( isJson ) {
this.xml = null;
this.json = JSON.parse( fileContents );
this.hvmlPath = path;
this.children = [];
// throw new Error( 'JSON Parsing not implemented yet' );
return this.json;
}
throw new Error( 'Unsupported file type' );
} );
} else {
// Instantiate with empty JSON data if no file path is specified
this.xml = null;
this.json = Data.getJsonBoilerplate();
this.hvmlPath = null;
this.children = [];
this.ready = Promise.resolve( this.json );
}
}
validate( xmllintPath = 'xmllint' ) {
// return this.xml.validate( this.xsd );
return ( new Promise( ( resolve, reject ) => {
exec( `${xmllintPath} --nowarning --noout --relaxng ${this.schemaPath} ${this.hvmlPath}`, ( error, stdout, stderr ) => { // eslint-disable-line
if ( error ) {
/* istanbul ignore next */
const xmllintNotFound = (
// Linux/macOS exit code 127 means command not found
( error.code === 127 )
// Windows may exit with code 1 instead of 127,
// which is the same code thrown by xmllint
// when it finds validation errors.
//
// So instead, test for the nonexistence of a pass/fail message.
// (Rather than testing against “command not found” strings which
// will be localized into different languages for different users.)
|| (
!/fails to validate/.test( error.message )
&& !/validates/.test( error.message )
)
);
if ( xmllintNotFound ) {
reject( new Validation.OptionalDependencyNotInstalled( {
"className": "HVML",
"fieldName": "validate",
"dependency": "xmllint",
} ) );
return;
}
let validationErrors = error.toString().trim().split( '\n' );
validationErrors.shift();
validationErrors.pop();
/* Array [
"./examples/redblue.ovml.xml:3: element ovml: Relax-NG validity error : Expecting element hvml, got ovml",
"./examples/redblue.ovml.xml fails to validate",
] */
validationErrors = validationErrors.map( ( currentValue ) => {
const validationErrorRegexPattern = `(?:(${this.hvmlPath}):(\\d+)):\\s+`
+ `(?:element .+):\\s+(Relax-NG validity error)\\s+:\\s+`
+ `(Expecting element (.+), got (.+))`;
const expectingGotRegex = new RegExp( validationErrorRegexPattern, 'gi' );
const expectingGot = expectingGotRegex.exec( currentValue );
if ( expectingGot ) {
return {
"message": expectingGot[0],
"file": expectingGot[1],
"line": expectingGot[2],
"type": expectingGot[3].replace( 'Relax-NG ', '' ).replace( ' error', '' ),
"error": expectingGot[4],
"expecting": expectingGot[5],
"got": expectingGot[6],
};
}
const wrongNamespaceRegexPattern = validationErrorRegexPattern.replace(
`(Expecting element (.+), got (.+))`,
`(Element (.+) has wrong namespace: expecting (.+))`,
);
const wrongNamespaceRegex = new RegExp( wrongNamespaceRegexPattern, 'gi' );
const wrongNamespace = wrongNamespaceRegex.exec( currentValue );
if ( wrongNamespace ) {
return {
"message": wrongNamespace[0],
"file": wrongNamespace[1],
"line": wrongNamespace[2],
"type": wrongNamespace[3].replace( 'Relax-NG ', '' ),
"error": wrongNamespace[4],
"element": wrongNamespace[5],
"expecting": wrongNamespace[6],
// "got": null,
};
}
const missingNamespaceRegexPattern = wrongNamespaceRegexPattern.replace(
`(Element (.+) has wrong namespace: expecting (.+))`,
`(Expecting a namespace for element (.+))`,
);
const missingNamespaceRegex = new RegExp( missingNamespaceRegexPattern, 'gi' );
const missingNamespace = missingNamespaceRegex.exec( currentValue );
if ( missingNamespace ) {
let namespace = missingNamespace[6];
/* istanbul ignore else: optional */
if ( !namespace && ( missingNamespace[5] === 'hvml' ) ) {
namespace = this.namespaces.hvml;
}
return {
"message": missingNamespace[0],
"file": missingNamespace[1],
"line": missingNamespace[2],
"type": missingNamespace[3].replace( 'Relax-NG ', '' ),
"error": missingNamespace[4],
"element": missingNamespace[5],
"expecting": namespace,
"got": null,
};
}
const unexpectedTextRegexPattern = missingNamespaceRegexPattern.replace(
`(Expecting a namespace for element (.+))`,
`(Did not expect text in element (.+) content)`,
);
const unexpectedTextRegex = new RegExp( unexpectedTextRegexPattern, 'gi' );
const unexpectedText = unexpectedTextRegex.exec( currentValue );
if ( unexpectedText ) {
return {
"message": unexpectedText[0],
"file": unexpectedText[1],
"line": unexpectedText[2],
"type": unexpectedText[3].replace( 'Relax-NG ', '' ),
"error": unexpectedText[4],
"element": unexpectedText[5],
// "expecting": namespace,
"got": "Text",
};
}
const invalidAttributeRegexPattern = unexpectedTextRegexPattern.replace(
`(Did not expect text in element (.+) content)`,
`(Invalid attribute (.+) for element (.+))`,
);
const invalidAttributeRegex = new RegExp( invalidAttributeRegexPattern, 'gi' );
const invalidAttribute = invalidAttributeRegex.exec( currentValue );
if ( invalidAttribute ) {
return {
"message": invalidAttribute[0],
"file": invalidAttribute[1],
"line": invalidAttribute[2],
"type": invalidAttribute[3].replace( 'Relax-NG ', '' ),
"error": invalidAttribute[4],
"element": invalidAttribute[6],
// "expecting": namespace,
"got": invalidAttribute[5],
};
}
const unexpectedElementRegexPattern = invalidAttributeRegexPattern.replace(
`(Invalid attribute (.+) for element (.+))`,
`(Did not expect element (.+) there)`,
);
const unexpectedElementRegex = new RegExp( unexpectedElementRegexPattern, 'gi' );
const unexpectedElement = unexpectedElementRegex.exec( currentValue );
/* istanbul ignore else: covered later */
if ( unexpectedElement ) {
return {
"message": unexpectedElement[0],
"file": unexpectedElement[1],
"line": unexpectedElement[2],
"type": unexpectedElement[3].replace( 'Relax-NG ', '' ),
"error": unexpectedElement[4],
// "element": unexpectedElement[6],
// "expecting": namespace,
"got": unexpectedElement[5],
};
}
/* istanbul ignore next: defensive */
const otherValidationErrorRegexPattern = unexpectedElementRegexPattern.replace(
`(Did not expect element (.+) there)`,
`(.*)`,
);
/* istanbul ignore next: defensive */
const otherValidationErrorRegex = new RegExp( otherValidationErrorRegexPattern, 'gi' );
/* istanbul ignore next: defensive */
const otherValidationError = otherValidationErrorRegex.exec( currentValue );
/* istanbul ignore next: defensive */
if ( otherValidationError ) {
return {
"message": otherValidationError[0],
"file": otherValidationError[1],
"line": otherValidationError[2],
"type": otherValidationError[3].replace( 'Relax-NG ', '' ),
"error": otherValidationError[4],
// "element": otherValidationError[6],
// "expecting": namespace,
"got": otherValidationError[5],
};
}
/* istanbul ignore next: defensive */
throw new Validation.DomainError( currentValue );
} );
reject( validationErrors );
} else {
// xmllint prints diagnostic information, good or bad, to stderr
/* istanbul ignore else: defensive */
if ( stderr.match( new RegExp( `${this.hvmlPath} validates` ) ) ) {
resolve( true );
} else {
resolve( stderr );
}
}
} );
} ) );
}
appendChild( child ) {
const errorData = {
...this._baseErrorData,
"methodName": "appendChild",
};
switch ( child.constructor ) {
case Video:
case Series:
super.appendChild( child );
break;
default:
throw new Validation.EnumError( {
...errorData,
// "message": `${child.constructor.name} can not be a child of ${this.constructor.name}`,
"fieldName": "child",
"expected": ["Video"],
"badValues": [child],
} );
}
}
}
// function parse( path, encoding = 'utf8', cb ) {}
// toJson
module.exports = {
HVML,
Series,
Group,
Video,
};
global.HVML = {
...global.HVML,
HVML,
};