flux.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Experimental
  2. var flux = {};
  3. var json = require('./json');
  4. flux.ModelFactory = class {
  5. match(context) {
  6. const identifier = context.identifier;
  7. const extension = identifier.split('.').pop().toLowerCase();
  8. const stream = context.stream;
  9. if (stream && extension === 'bson') {
  10. return 'flux.bson';
  11. }
  12. return null;
  13. }
  14. open(context) {
  15. return Promise.resolve().then(() => {
  16. let root = null;
  17. try {
  18. const stream = context.stream;
  19. const reader = json.BinaryReader.open(stream);
  20. root = reader.read();
  21. }
  22. catch (error) {
  23. const message = error && error.message ? error.message : error.toString();
  24. throw new flux.Error('File format is not Flux BSON (' + message.replace(/\.$/, '') + ').');
  25. }
  26. return context.metadata('flux-metadata.json').then((metadata) => {
  27. const backref = (obj, root) => {
  28. if (Array.isArray(obj)) {
  29. for (let i = 0; i < obj.length; i++) {
  30. obj[i] = backref(obj[i], root);
  31. }
  32. }
  33. else if (obj === Object(obj)) {
  34. if (obj.tag == 'backref' && obj.ref) {
  35. if (!root._backrefs[obj.ref - 1]) {
  36. throw new flux.Error("Invalid backref '" + obj.ref + "'.");
  37. }
  38. obj = root._backrefs[obj.ref - 1];
  39. }
  40. for (const key of Object.keys(obj)) {
  41. if (obj !== root || key !== '_backrefs') {
  42. obj[key] = backref(obj[key], root);
  43. }
  44. }
  45. }
  46. return obj;
  47. };
  48. const obj = backref(root, root);
  49. const model = obj.model;
  50. if (!model) {
  51. throw new flux.Error('File does not contain Flux model.');
  52. }
  53. return new flux.Model(metadata, model);
  54. });
  55. });
  56. }
  57. };
  58. flux.Model = class {
  59. constructor(/* root */) {
  60. this._format = 'Flux';
  61. this._graphs = [];
  62. }
  63. get format() {
  64. return this._format;
  65. }
  66. get graphs() {
  67. return this._graphs;
  68. }
  69. };
  70. flux.Error = class extends Error {
  71. constructor(message) {
  72. super(message);
  73. this.name = 'Flux Error';
  74. }
  75. };
  76. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  77. module.exports.ModelFactory = flux.ModelFactory;
  78. }