brikz.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. export default (
  2. function Brikz (api, apiKey, initKey) {
  3. var brikz = this, backup = {};
  4. apiKey = apiKey || 'exports';
  5. initKey = initKey || '__init__';
  6. function mixin(src, target, what) {
  7. for (var keys = Object.keys(what || src), l = keys.length, i = 0; i < l; ++i) {
  8. if (src == null) {
  9. target[keys[i]] = undefined;
  10. } else {
  11. var value = src[keys[i]];
  12. if (typeof value !== "undefined") {
  13. target[keys[i]] = value;
  14. }
  15. }
  16. }
  17. return target;
  18. }
  19. Object.defineProperties(this, {
  20. rebuild: {value: null, enumerable: false, configurable: true, writable: true}
  21. });
  22. var exclude = mixin(this, {});
  23. this.rebuild = function () {
  24. Object.keys(backup).forEach(function (key) {
  25. mixin(null, api, (backup[key] || 0)[apiKey] || {});
  26. });
  27. var oapi = mixin(api, {}), order = [], chk = {};
  28. function ensure(key) {
  29. if (key in exclude) {
  30. return null;
  31. }
  32. var b = brikz[key], bak = backup[key];
  33. mixin(null, api, api);
  34. while (typeof b === "function") {
  35. (b.deps || []).forEach(ensure);
  36. b = new b(brikz, api, bak);
  37. }
  38. brikz[key] = b;
  39. if (b && !chk[key]) {
  40. chk[key] = true;
  41. order.push(b);
  42. }
  43. if (b && !b[apiKey]) {
  44. b[apiKey] = mixin(api, {});
  45. }
  46. }
  47. Object.keys(brikz).forEach(ensure);
  48. mixin(oapi, mixin(null, api, api));
  49. order.forEach(function (brik) {
  50. mixin(brik[apiKey] || {}, api);
  51. });
  52. order.forEach(function (brik) {
  53. if (brik[initKey]) {
  54. brik[initKey]();
  55. if (brik[initKey].once) {
  56. delete brik[initKey];
  57. }
  58. }
  59. });
  60. backup = mixin(brikz, {});
  61. };
  62. }
  63. );