test.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /* jshint esversion: 6 */
  2. /* eslint "indent": [ "error", 4, { "SwitchCase": 1 } ] */
  3. /* eslint "no-console": off */
  4. const fs = require('fs');
  5. const path = require('path');
  6. const process = require('process');
  7. const child_process = require('child_process');
  8. const http = require('http');
  9. const https = require('https');
  10. const url = require('url');
  11. const protobuf = require('protobufjs');
  12. const sidebar = require('../src/view-sidebar.js');
  13. const view = require('../src/view.js');
  14. const zip = require('../src/zip');
  15. const gzip = require('../src/gzip');
  16. const tar = require('../src/tar');
  17. const xmldom = require('xmldom');
  18. global.protobuf = protobuf;
  19. global.DOMParser = xmldom.DOMParser;
  20. global.TextDecoder = class {
  21. constructor(encoding) {
  22. global.TextDecoder._TextDecoder = global.TextDecoder._TextDecoder || require('util').TextDecoder;
  23. if (encoding !== 'ascii') {
  24. this._textDecoder = new global.TextDecoder._TextDecoder(encoding);
  25. }
  26. }
  27. decode(data) {
  28. if (this._textDecoder) {
  29. return this._textDecoder.decode(data);
  30. }
  31. if (data.length < 32) {
  32. return String.fromCharCode.apply(null, data);
  33. }
  34. var buffer = [];
  35. var start = 0;
  36. do {
  37. var end = start + 32;
  38. if (end > data.length) {
  39. end = data.length;
  40. }
  41. buffer.push(String.fromCharCode.apply(null, data.subarray(start, end)));
  42. start = end;
  43. }
  44. while (start < data.length);
  45. return buffer.join('');
  46. }
  47. };
  48. var type = process.argv.length > 2 ? process.argv[2] : null;
  49. var models = JSON.parse(fs.readFileSync(__dirname + '/models.json', 'utf-8'));
  50. var dataFolder = __dirname + '/data';
  51. class TestHost {
  52. constructor() {
  53. this._document = new HTMLDocument();
  54. }
  55. get document() {
  56. return this._document;
  57. }
  58. initialize(/* view */) {
  59. }
  60. environment(name) {
  61. if (name == 'zoom') {
  62. return 'none';
  63. }
  64. return null;
  65. }
  66. screen(/* name */) {
  67. }
  68. require(id) {
  69. try {
  70. var file = path.join(path.join(__dirname, '../src'), id + '.js');
  71. return Promise.resolve(require(file));
  72. }
  73. catch (error) {
  74. return Promise.reject(error);
  75. }
  76. }
  77. request(base, file, encoding) {
  78. var pathname = path.join(base || path.join(__dirname, '../src'), file);
  79. if (!fs.existsSync(pathname)) {
  80. return Promise.reject(new Error('File not found.'));
  81. }
  82. return Promise.resolve(fs.readFileSync(pathname, encoding));
  83. }
  84. event(/* category, action, label, value */) {
  85. }
  86. exception(err /*, fatal */) {
  87. this._raise('exception', { exception: err });
  88. }
  89. on(event, callback) {
  90. this._events = this._events || {};
  91. this._events[event] = this._events[event] || [];
  92. this._events[event].push(callback);
  93. }
  94. _raise(event, data) {
  95. if (this._events && this._events[event]) {
  96. for (var callback of this._events[event]) {
  97. callback(this, data);
  98. }
  99. }
  100. }
  101. }
  102. class TestContext {
  103. constructor(host, folder, identifier, buffer) {
  104. this._host = host;
  105. this._folder = folder;
  106. this._identifier = identifier;
  107. this._buffer = buffer;
  108. }
  109. request(file, encoding) {
  110. return this._host.request(this._folder, file, encoding);
  111. }
  112. get identifier() {
  113. return this._identifier;
  114. }
  115. get buffer() {
  116. return this._buffer;
  117. }
  118. }
  119. class HTMLDocument {
  120. constructor() {
  121. this._elements = {};
  122. this.documentElement = new HTMLHtmlElement();
  123. this.body = new HTMLBodyElement();
  124. }
  125. createElementNS(/* namespace, name */) {
  126. return new HTMLHtmlElement();
  127. }
  128. createTextNode(/* text */) {
  129. return new HTMLHtmlElement();
  130. }
  131. getElementById(id) {
  132. var element = this._elements[id];
  133. if (!element) {
  134. element = new HTMLHtmlElement();
  135. this._elements[id] = element;
  136. }
  137. return element;
  138. }
  139. addEventListener(/* event, callback */) {
  140. }
  141. removeEventListener(/* event, callback */) {
  142. }
  143. }
  144. class HTMLHtmlElement {
  145. constructor() {
  146. this._attributes = {};
  147. this.style = new CSSStyleDeclaration();
  148. }
  149. appendChild(/* node */) {
  150. }
  151. setAttribute(name, value) {
  152. this._attributes[name] = value;
  153. }
  154. getBBox() {
  155. return { x: 0, y: 0, width: 10, height: 10 };
  156. }
  157. getElementsByClassName(/* name */) {
  158. return null;
  159. }
  160. addEventListener(/* event, callback */) {
  161. }
  162. removeEventListener(/* event, callback */) {
  163. }
  164. }
  165. class HTMLBodyElement {
  166. constructor() {
  167. this.style = new CSSStyleDeclaration();
  168. }
  169. addEventListener(/* event, callback */) {
  170. }
  171. }
  172. class CSSStyleDeclaration {
  173. constructor() {
  174. this._properties = {};
  175. }
  176. setProperty(name, value) {
  177. this._properties[name] = value;
  178. }
  179. }
  180. function makeDir(dir) {
  181. if (!fs.existsSync(dir)){
  182. makeDir(path.dirname(dir));
  183. fs.mkdirSync(dir);
  184. }
  185. }
  186. function decompress(buffer, identifier) {
  187. var archive = null;
  188. var extension = identifier.split('.').pop().toLowerCase();
  189. if (extension == 'gz' || extension == 'tgz') {
  190. archive = new gzip.Archive(buffer);
  191. if (archive.entries.length == 1) {
  192. var entry = archive.entries[0];
  193. if (entry.name) {
  194. identifier = entry.name;
  195. }
  196. else {
  197. identifier = identifier.substring(0, identifier.lastIndexOf('.'));
  198. if (extension == 'tgz') {
  199. identifier += '.tar';
  200. }
  201. }
  202. buffer = entry.data;
  203. archive = null;
  204. }
  205. }
  206. switch (identifier.split('.').pop().toLowerCase()) {
  207. case 'tar':
  208. archive = new tar.Archive(buffer);
  209. break;
  210. case 'zip':
  211. archive = new zip.Archive(buffer);
  212. break;
  213. }
  214. return archive;
  215. }
  216. function request(location, cookie, callback) {
  217. var data = [];
  218. var position = 0;
  219. var protocol = url.parse(location).protocol;
  220. var httpModules = { 'http:': http, 'https:': https };
  221. var httpModule = httpModules[protocol];
  222. var httpRequest = httpModule.request(location, {
  223. rejectUnauthorized: false
  224. });
  225. if (cookie.length > 0) {
  226. httpRequest.setHeader('Cookie', cookie);
  227. }
  228. httpRequest.on('response', (response) => {
  229. if (response.statusCode == 200 && url.parse(location).hostname == 'drive.google.com' &&
  230. response.headers['set-cookie'].some((cookie) => cookie.startsWith('download_warning_'))) {
  231. cookie = response.headers['set-cookie'];
  232. var download = cookie.filter((cookie) => cookie.startsWith('download_warning_')).shift();
  233. var confirm = download.split(';').shift().split('=').pop();
  234. location = location + '&confirm=' + confirm;
  235. request(location, cookie, callback);
  236. return;
  237. }
  238. if (response.statusCode == 301 || response.statusCode == 302) {
  239. location = url.parse(response.headers.location).hostname ?
  240. response.headers.location :
  241. url.parse(location).protocol + '//' + url.parse(location).hostname + response.headers.location;
  242. request(location, cookie, callback);
  243. return;
  244. }
  245. if (response.statusCode != 200) {
  246. callback(new Error(response.statusCode.toString() + ' ' + location), null);
  247. return;
  248. }
  249. var length = response.headers['content-length'] ? Number(response.headers['content-length']) : -1;
  250. response.on("data", (chunk) => {
  251. position += chunk.length;
  252. if (length >= 0) {
  253. var label = location.length > 70 ? location.substring(0, 66) + '...' : location;
  254. process.stdout.write(' (' + (' ' + Math.floor(100 * (position / length))).slice(-3) + '%) ' + label + '\r');
  255. }
  256. else {
  257. process.stdout.write(' ' + position + ' bytes\r');
  258. }
  259. data.push(chunk);
  260. });
  261. response.on("end", () => {
  262. callback(null, Buffer.concat(data));
  263. });
  264. response.on("error", (err) => {
  265. callback(err, null);
  266. });
  267. });
  268. httpRequest.on('error', (err) => {
  269. callback(err, null);
  270. });
  271. httpRequest.end();
  272. }
  273. function download(folder, targets, sources, completed, callback) {
  274. if (targets.every((file) => fs.existsSync(folder + '/' + file))) {
  275. completed = completed.concat(targets);
  276. callback(null, completed);
  277. return;
  278. }
  279. if (!sources) {
  280. callback(new Error('Download source not specified.'), null);
  281. return;
  282. }
  283. var source = '';
  284. var sourceFiles = [];
  285. var startIndex = sources.indexOf('[');
  286. var endIndex = sources.indexOf(']');
  287. if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
  288. sourceFiles = sources.substring(startIndex + 1, endIndex).split(',').map((sourceFile) => sourceFile.trim());
  289. source = sources.substring(0, startIndex);
  290. sources = sources.substring(endIndex + 1);
  291. if (sources.startsWith(',')) {
  292. sources = sources.substring(1);
  293. }
  294. }
  295. else {
  296. var commaIndex = sources.indexOf(',');
  297. if (commaIndex != -1) {
  298. source = sources.substring(0, commaIndex);
  299. sources = sources.substring(commaIndex + 1);
  300. }
  301. else {
  302. source = sources;
  303. sources = '';
  304. }
  305. }
  306. var target;
  307. for (target of targets) {
  308. makeDir(path.dirname(folder + '/' + target));
  309. }
  310. request(source, [], (err, data) => {
  311. if (err) {
  312. callback(err, null);
  313. return;
  314. }
  315. if (sourceFiles.length > 0) {
  316. if (process.stdout.clearLine) {
  317. process.stdout.clearLine();
  318. }
  319. process.stdout.write(' decompress...\r');
  320. var archive = decompress(data, source.split('/').pop());
  321. // console.log(archive);
  322. for (var file of sourceFiles) {
  323. if (process.stdout.clearLine) {
  324. process.stdout.clearLine();
  325. }
  326. process.stdout.write(' write ' + file + '\n');
  327. var entry = archive.entries.filter((entry) => entry.name == file)[0];
  328. if (!entry) {
  329. callback(new Error("Entry not found '" + file + '. Archive contains entries: ' + JSON.stringify(archive.entries.map((entry) => entry.name)) + " ."), null);
  330. }
  331. var target = targets.shift();
  332. fs.writeFileSync(folder + '/' + target, entry.data, null);
  333. completed.push(target);
  334. }
  335. }
  336. else {
  337. target = targets.shift();
  338. if (process.stdout.clearLine) {
  339. process.stdout.clearLine();
  340. }
  341. process.stdout.write(' write ' + target + '\r');
  342. fs.writeFileSync(folder + '/' + target, data, null);
  343. completed.push(target);
  344. }
  345. if (process.stdout.clearLine) {
  346. process.stdout.clearLine();
  347. }
  348. if (sources.length > 0) {
  349. download(folder, targets, sources, completed, callback);
  350. return;
  351. }
  352. callback(null, completed);
  353. });
  354. }
  355. function loadModel(target, item) {
  356. var host = new TestHost();
  357. var exceptions = [];
  358. host.on('exception', (_, data) => {
  359. exceptions.push(data.exception);
  360. });
  361. var folder = path.dirname(target);
  362. var identifier = path.basename(target);
  363. var size = fs.statSync(target).size;
  364. var buffer = new Uint8Array(size);
  365. var fd = fs.openSync(target, 'r');
  366. fs.readSync(fd, buffer, 0, size, 0);
  367. fs.closeSync(fd);
  368. var context = new TestContext(host, folder, identifier, buffer);
  369. var modelFactoryService = new view.ModelFactoryService(host);
  370. var opened = false;
  371. return modelFactoryService.open(context).then((model) => {
  372. if (opened) {
  373. throw new Error("Model opened more than once '" + target + "'.");
  374. }
  375. opened = true;
  376. if (!model.format || (item.format && model.format != item.format)) {
  377. throw new Error("Invalid model format '" + model.format + "'.");
  378. }
  379. if (item.producer && model.producer != item.producer) {
  380. throw new Error("Invalid producer '" + model.producer + "'.");
  381. }
  382. if (item.runtime && model.runtime != item.runtime) {
  383. throw new Error("Invalid runtime '" + model.runtime + "'.");
  384. }
  385. for (var graph of model.graphs) {
  386. var input;
  387. var connection;
  388. for (input of graph.inputs) {
  389. input.name.toString();
  390. input.name.length;
  391. for (connection of input.connections) {
  392. connection.id.toString();
  393. connection.id.length;
  394. if (connection.type) {
  395. connection.type.toString();
  396. }
  397. }
  398. }
  399. var output;
  400. for (output of graph.outputs) {
  401. output.name.toString();
  402. output.name.length;
  403. for (connection of output.connections) {
  404. connection.id.toString();
  405. if (connection.type) {
  406. connection.type.toString();
  407. }
  408. }
  409. }
  410. for (var node of graph.nodes) {
  411. node.name.toString();
  412. node.name.length;
  413. node.documentation.toString();
  414. node.category.toString();
  415. for (var attribute of node.attributes) {
  416. attribute.name.toString();
  417. attribute.name.length;
  418. var value = sidebar.NodeSidebar.formatAttributeValue(attribute.value, attribute.type)
  419. if (value && value.length > 1000) {
  420. value = value.substring(0, 1000) + '...';
  421. }
  422. value = value.split('<');
  423. }
  424. for (input of node.inputs) {
  425. input.name.toString();
  426. input.name.length;
  427. for (connection of input.connections) {
  428. connection.id.toString();
  429. connection.id.length;
  430. if (connection.type) {
  431. connection.type.toString();
  432. }
  433. if (connection.initializer) {
  434. connection.initializer.toString();
  435. }
  436. }
  437. }
  438. for (output of node.outputs) {
  439. output.name.toString();
  440. output.name.length;
  441. for (connection of output.connections) {
  442. connection.id.toString();
  443. connection.id.length;
  444. if (connection.type) {
  445. connection.type.toString();
  446. }
  447. }
  448. }
  449. if (node.chain) {
  450. for (var chain of node.chain) {
  451. chain.name.toString();
  452. chain.name.length;
  453. }
  454. }
  455. }
  456. }
  457. if (exceptions.length > 0) {
  458. throw exceptions[0];
  459. }
  460. return model;
  461. });
  462. }
  463. function render(model) {
  464. try {
  465. var host = new TestHost();
  466. var currentView = new view.View(host);
  467. if (!currentView.showAttributes) {
  468. currentView.toggleAttributes();
  469. }
  470. if (!currentView.showInitializers) {
  471. currentView.toggleInitializers();
  472. }
  473. return currentView.renderGraph(model.graphs[0]);
  474. }
  475. catch (error) {
  476. return Promise.reject(error);
  477. }
  478. }
  479. function next() {
  480. if (models.length == 0) {
  481. return;
  482. }
  483. var item = models.shift();
  484. if (!item.type) {
  485. console.error("Property 'type' is required for item '" + JSON.stringify(item) + "'.");
  486. return;
  487. }
  488. if (type && item.type != type) {
  489. next();
  490. return;
  491. }
  492. var targets = item.target.split(',');
  493. if (process.stdout.clearLine) {
  494. process.stdout.clearLine();
  495. }
  496. var folder = dataFolder + '/' + item.type;
  497. process.stdout.write(item.type + '/' + targets[0] + '\n');
  498. var sources = item.source;
  499. download(folder, targets, sources, [], (err, completed) => {
  500. if (err) {
  501. if (item.script) {
  502. try {
  503. var root = path.dirname(__dirname);
  504. var command = item.script[0].replace('${root}', root);
  505. var args = item.script[1].replace('${root}', root);
  506. console.log(' ' + command + ' ' + args);
  507. child_process.execSync(command + ' ' + args, { stdio: [ 0, 1 , 2] });
  508. completed = targets;
  509. }
  510. catch (err) {
  511. console.error(err);
  512. return;
  513. }
  514. }
  515. else {
  516. console.error(err);
  517. return;
  518. }
  519. }
  520. loadModel(folder + '/' + completed[0], item).then((model) => {
  521. if (item.render != 'skip') {
  522. render(model).then(() => {
  523. if (item.error) {
  524. console.error('Expected error.');
  525. return;
  526. }
  527. next();
  528. }).catch((error) => {
  529. if (!item.error || item.error != error.message) {
  530. console.error(err);
  531. }
  532. next();
  533. });
  534. }
  535. else {
  536. next();
  537. }
  538. }).catch((error) => {
  539. if (!item.error || item.error != error.message) {
  540. console.error(error);
  541. return;
  542. }
  543. next();
  544. });
  545. });
  546. }
  547. next();