roboto-js 1.0.4 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,10 +6,10 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports["default"] = void 0;
7
7
  var _lodash = _interopRequireDefault(require("lodash"));
8
8
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
9
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
10
9
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
11
10
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
12
11
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
12
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
13
13
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
14
14
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
15
15
  function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
@@ -39,6 +39,26 @@ var RbtObject = exports["default"] = /*#__PURE__*/function () {
39
39
  value: function set(path, value) {
40
40
  _lodash["default"].set(this._data, path, value);
41
41
  }
42
+ }, {
43
+ key: "getData",
44
+ value: function getData() {
45
+ return _objectSpread({}, this._data);
46
+ }
47
+ }, {
48
+ key: "setData",
49
+ value: function setData(newData) {
50
+ var _this = this;
51
+ // Ensure the input is an object
52
+ if (_typeof(newData) !== 'object' || newData === null) {
53
+ throw new Error('setData expects an object');
54
+ }
55
+
56
+ // Iterate over each key in the newData object
57
+ Object.keys(newData).forEach(function (key) {
58
+ // Update the corresponding key in this._data
59
+ _lodash["default"].set(_this._data, key, newData[key]);
60
+ });
61
+ }
42
62
  }, {
43
63
  key: "toRecord",
44
64
  value: function toRecord() {
@@ -46,6 +66,20 @@ var RbtObject = exports["default"] = /*#__PURE__*/function () {
46
66
  dataJson: JSON.stringify(this._data)
47
67
  });
48
68
  }
69
+ }, {
70
+ key: "clone",
71
+ value: function clone() {
72
+ // Create a deep copy of the current object's data
73
+ var clonedData = _lodash["default"].cloneDeep(this._internalData);
74
+
75
+ // Reset unique identifiers to ensure a new ID is generated upon saving
76
+ delete clonedData.id;
77
+ delete clonedData.id_revision;
78
+
79
+ // Create a new instance of RbtObject with the cloned data
80
+ var clonedObject = new RbtObject(clonedData, this._axios);
81
+ return clonedObject;
82
+ }
49
83
  }, {
50
84
  key: "save",
51
85
  value: function () {
@@ -73,17 +107,20 @@ var RbtObject = exports["default"] = /*#__PURE__*/function () {
73
107
  throw new Error(response.data.message);
74
108
  case 9:
75
109
  this._internalData = response.data;
110
+ this.id = response.data.id;
111
+ this.id_revision = response.data.id_revision;
112
+ this.type = response.data.type;
76
113
  return _context.abrupt("return", this);
77
- case 13:
78
- _context.prev = 13;
114
+ case 16:
115
+ _context.prev = 16;
79
116
  _context.t0 = _context["catch"](2);
80
117
  console.log('RbtObject.save.error:');
81
118
  console.log(_context.t0.response.data);
82
- case 17:
119
+ case 20:
83
120
  case "end":
84
121
  return _context.stop();
85
122
  }
86
- }, _callee, this, [[2, 13]]);
123
+ }, _callee, this, [[2, 16]]);
87
124
  }));
88
125
  function save() {
89
126
  return _save.apply(this, arguments);
package/package.json CHANGED
@@ -1,10 +1,14 @@
1
1
  {
2
2
  "name": "roboto-js",
3
- "version": "1.0.4",
3
+ "version": "1.0.15",
4
+ "type": "module",
4
5
  "description": "",
5
- "main": "dist/index.js",
6
+ "main": "dist/cjs/index.cjs",
6
7
  "scripts": {
7
- "build": "babel src --out-dir dist",
8
+ "build": "npm run build:cjs && npm run build:esm",
9
+ "build:cjs": "babel src --out-dir dist/cjs --presets=@babel/preset-env --extensions \".js,.jsx\" --out-file-extension .cjs && npm run postbuild:cjs",
10
+ "build:esm": "babel src --out-dir dist/esm --presets=@babel/preset-env --no-babelrc --config-file ./babel.esm.config.json",
11
+ "postbuild:cjs": "node postbuild-cjs.js",
8
12
  "test": "echo \"Error: no test specified\" && exit 1",
9
13
  "prepublishOnly": "npm run build"
10
14
  },
@@ -13,6 +17,7 @@
13
17
  "dependencies": {
14
18
  "axios": "^1.5.1",
15
19
  "crypto-js": "^4.1.1",
20
+ "idb": "^8.0.0",
16
21
  "lodash": "^4.17.21"
17
22
  },
18
23
  "devDependencies": {
@@ -20,4 +25,4 @@
20
25
  "@babel/core": "^7.23.2",
21
26
  "@babel/preset-env": "^7.23.2"
22
27
  }
23
- }
28
+ }
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "roboto-js",
3
+ "version": "1.0.14",
4
+ "type": "module",
5
+ "description": "",
6
+ "main": "dist/cjs/index.cjs",
7
+ "exports": {
8
+ "import": "./dist/esm/index.js",
9
+ "require": "./dist/cjs/index.cjs"
10
+ },
11
+ "scripts": {
12
+ "build": "npm run build:cjs && npm run build:esm",
13
+ "build:cjs": "babel src --out-dir dist/cjs --presets=@babel/preset-env --extensions \".js,.jsx\" --out-file-extension .cjs && npm run postbuild:cjs",
14
+ "build:esm": "babel src --out-dir dist/esm --presets=@babel/preset-env --no-babelrc --config-file ./babel.esm.config.json",
15
+ "postbuild:cjs": "node postbuild-cjs.js",
16
+ "test": "echo \"Error: no test specified\" && exit 1",
17
+ "prepublishOnly": "npm run build"
18
+ },
19
+ "author": "",
20
+ "license": "ISC",
21
+ "dependencies": {
22
+ "axios": "^1.5.1",
23
+ "crypto-js": "^4.1.1",
24
+ "idb": "^8.0.0",
25
+ "lodash": "^4.17.21"
26
+ },
27
+ "devDependencies": {
28
+ "@babel/cli": "^7.23.0",
29
+ "@babel/core": "^7.23.2",
30
+ "@babel/preset-env": "^7.23.2"
31
+ }
32
+ }
@@ -0,0 +1,26 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+
4
+ const directory = './dist/cjs';
5
+
6
+ async function updateCjsImports() {
7
+ try {
8
+ const files = await fs.readdir(directory);
9
+ for (const file of files) {
10
+ if (file.endsWith('.cjs')) {
11
+ const filePath = path.join(directory, file);
12
+ try {
13
+ const data = await fs.readFile(filePath, 'utf8');
14
+ const result = data.replace(/\.js/g, '.cjs');
15
+ await fs.writeFile(filePath, result, 'utf8');
16
+ } catch (err) {
17
+ console.error(`Error reading/writing ${file}:`, err);
18
+ }
19
+ }
20
+ }
21
+ } catch (err) {
22
+ console.error('Error listing directory files:', err);
23
+ }
24
+ }
25
+
26
+ updateCjsImports();
package/src/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import RbtApi from './rbt_api';
3
- import RbtObject from './rbt_object';
2
+ import RbtApi from './rbt_api.js';
3
+ import RbtObject from './rbt_object.js';
4
4
 
5
5
  export {
6
6
  RbtApi,
@@ -13,25 +13,41 @@ export default class Roboto{
13
13
 
14
14
  constructor() {
15
15
 
16
+ const isBrowser = typeof window !== "undefined";
17
+
16
18
  this.config = {
17
- apiKey: process.env.NEXT_PUBLIC_ROBOTO_API_KEY,
18
- baseUrl: 'https://' + (process.env.NEXT_PUBLIC_ROBOTO_HOST),
19
+ apiKey: isBrowser ? process.env.NEXT_PUBLIC_ROBOTO_API_KEY : process.env.ROBOTO_API_KEY,
20
+ baseUrl: 'https://' + (isBrowser ? process.env.NEXT_PUBLIC_ROBOTO_HOST : process.env.ROBOTO_HOST),
19
21
  };
20
22
 
21
23
  this.api = RbtApi.configure(this.config);
22
-
24
+ if(isBrowser){
25
+ this.api.initLocalDb();
26
+ }
23
27
  }
24
28
 
25
29
  async login(params){
26
30
  return this.api.login(params);
27
31
  }
32
+
33
+ async registerUser(params){
34
+ return this.api.registerUser(params);
35
+ }
36
+
37
+ async createFile(data={}){
38
+ return this.api.createFile(data);
39
+ }
28
40
 
29
41
  async create(params, data={}){
30
42
  return this.api.create(params, data);
31
43
  }
32
44
 
33
- async query(params){
34
- return this.api.query(params);
45
+ async load(type, ids){
46
+ return this.api.load(type, ids);
47
+ }
48
+
49
+ async query(type, params){
50
+ return this.api.query(type, params);
35
51
  }
36
52
 
37
53
  }
package/src/rbt_api.js CHANGED
@@ -1,29 +1,50 @@
1
1
  import axios from 'axios';
2
2
  import CryptoJS from 'crypto-js';
3
3
  import RbtObject from './rbt_object.js';
4
+ import RbtFile from './rbt_file.js';
4
5
  import _ from 'lodash';
6
+ import { openDB } from 'idb';
5
7
 
6
8
  export default class RbtApi {
7
9
 
8
10
  constructor(axiosInstance) {
9
11
  this.axios = axiosInstance;
12
+ this.localDb = null;
10
13
  this.iac_session = null;
11
14
  this.authtoken = null;
12
15
  }
13
16
 
14
17
  static configure({ apiKey, baseUrl }) {
15
18
  if (!RbtApi.instance) {
19
+ const isClient = typeof window !== 'undefined';
20
+
21
+ const authtoken = (isClient)? localStorage.getItem('authtoken'): null;
22
+
16
23
  const axiosInstance = axios.create({
17
24
  baseURL: baseUrl,
18
25
  headers: {
19
- accesskey: apiKey
26
+ accesskey: apiKey,
27
+ authtoken: authtoken
20
28
  }
21
29
  });
30
+
22
31
  RbtApi.instance = new RbtApi(axiosInstance);
23
32
  }
24
33
  return RbtApi.instance;
25
34
  }
26
35
 
36
+ async initLocalDb(){
37
+
38
+ this.localDb = await openDB('RBTFileDatabase', 1, {
39
+ upgrade(db) {
40
+ if (!db.objectStoreNames.contains('files')) {
41
+ db.createObjectStore('files', { autoIncrement: true });
42
+ }
43
+ },
44
+ });
45
+
46
+ }
47
+
27
48
  async login(params) {
28
49
  try {
29
50
  // create a md5 hash of the password using crypto-js
@@ -40,6 +61,10 @@ export default class RbtApi {
40
61
  this.iac_session = response.data;
41
62
  // update axios instance headers with authtoken
42
63
  this.axios.defaults.headers.common['authtoken'] = response.data.authToken;
64
+ localStorage.setItem('authtoken', response.data.authToken);
65
+
66
+
67
+
43
68
  return response.data;
44
69
  } catch (e) {
45
70
 
@@ -47,9 +72,40 @@ export default class RbtApi {
47
72
  }
48
73
  }
49
74
 
75
+ async registerUser(dataHash={}) {
76
+ try {
77
+ const response = await this.axios.post('/user_service/registerUser', [dataHash]);
78
+ const record = response.data;
79
+
80
+ if(dataHash){
81
+ record.data = dataHash;
82
+ }
83
+ return new RbtObject(record, this.axios);
84
+ } catch (e) {
85
+ return this._handleError(e);
86
+ }
87
+ }
88
+
89
+ async createFile(dataHash){
90
+
91
+ //return this.create('<@filekit.file>', dataHash);
92
+ try {
93
+ const response = await this.axios.post('/object_service/createObject', ['<@filekit.file>', dataHash]);
94
+ const record = response.data;
95
+
96
+ if(dataHash){
97
+ record.data = dataHash;
98
+ }
99
+ return new RbtFile(record, this.axios, this.localDb);
100
+
101
+ } catch (e) {
102
+ return this._handleError(e);
103
+ }
104
+ }
105
+
106
+
50
107
  async create(type, dataHash={}) {
51
108
  try {
52
- debugger;
53
109
  const response = await this.axios.post('/object_service/createObject', [type, dataHash]);
54
110
  const record = response.data;
55
111
 
@@ -80,6 +136,24 @@ export default class RbtApi {
80
136
  }
81
137
  }
82
138
 
139
+ async load(type, ids){
140
+
141
+ try{
142
+ debugger;
143
+ if(Array.isArray(ids)){
144
+ return this.query(type, { where: "id IN ("+ids.join(',')+")" });
145
+ }
146
+ else{
147
+ let res = await this.query(type, { where: "id="+ids});
148
+ return res[0];
149
+ }
150
+
151
+ } catch (e) {
152
+ return this._handleError(e);
153
+ }
154
+
155
+ }
156
+
83
157
  _handleError(err){
84
158
 
85
159
  if(_.isObject(err)){
@@ -0,0 +1,292 @@
1
+
2
+ import _ from 'lodash';
3
+ import { EventEmitter } from 'events'; // Make sure to use a browser-compatible version if in the browser
4
+
5
+ export default class RbtFile extends EventEmitter{
6
+
7
+ static FRAME_SIZE = 1024 * 1024; // 1MB, for example
8
+
9
+ constructor(record, axiosInstance, localDb) {
10
+
11
+ super(); // Call the constructor of EventEmitter
12
+ this.id = record.id;
13
+ this._axios = axiosInstance;
14
+ this._internalData = record;
15
+ this._data = record.data ? record.data : (record.dataJson ? JSON.parse(record.dataJson) : {});
16
+ this._localDb = localDb;
17
+ this.progress = 0;
18
+
19
+ this.fileHeader = {};
20
+ }
21
+
22
+ get(path) {
23
+ return get(this._data, path);
24
+ }
25
+
26
+ set(path, value) {
27
+ set(this._data, path, value);
28
+ }
29
+
30
+ getData() {
31
+ return { ...this._data };
32
+ }
33
+
34
+ toRecord() {
35
+ return {
36
+ ...this._internalData,
37
+ dataJson: JSON.stringify(this._data)
38
+ };
39
+ }
40
+
41
+ async save() {
42
+ if (!this._internalData.type) {
43
+ throw new Error('Cannot save object without type');
44
+ }
45
+
46
+ try {
47
+ const record = this.toRecord();
48
+ const response = await this._axios.post('/object_service/saveObject', [record]);
49
+
50
+ if (response.data.ok === false) {
51
+ throw new Error(response.data.message);
52
+ }
53
+
54
+ this._internalData = response.data;
55
+
56
+ return this;
57
+
58
+ } catch (e) {
59
+ console.error('RbtFile.save.error:', e.response?.data);
60
+ throw e; // Propagate the error
61
+ }
62
+ }
63
+
64
+ async delete() {
65
+ if (!this._internalData.type) {
66
+ throw new Error('Cannot delete object without type');
67
+ }
68
+
69
+ try {
70
+ const record = this.toRecord();
71
+ const response = await this._axios.post('/object_service/deleteObject', [record]);
72
+
73
+ if (response.data.ok === false) {
74
+ throw new Error(response.data.message);
75
+ }
76
+
77
+ this._internalData = response.data;
78
+ return this;
79
+
80
+ } catch (e) {
81
+ console.error('RbtFile.delete.error:', e.response?.data);
82
+ throw e; // Propagate the error
83
+ }
84
+ }
85
+
86
+ async getFileBlobUrl() {
87
+ const db = this._localDb;
88
+ const tx = db.transaction('files', 'readonly');
89
+ const cursor = await tx.store.openCursor();
90
+ if (!cursor) return null;
91
+ const fileData = cursor.value.chunk; // Assuming the first chunk has enough data
92
+ const blob = new Blob([fileData], { type: 'application/octet-stream' });
93
+ return URL.createObjectURL(blob);
94
+ }
95
+
96
+ setProgress(newProgress) {
97
+ this.progress = newProgress;
98
+ console.log(`Progress: ${this.progress * 100}%`);
99
+ this.emit('progress', this.progress); // Emit a progress event
100
+
101
+ }
102
+
103
+
104
+ async readAndStoreFile(file) {
105
+ let offset = 0;
106
+ this.fileHeader = {
107
+ id: this.id,
108
+ name: file.name,
109
+ size: file.size,
110
+ ext: this._extractFileExtension(file.name),
111
+ mimeType: file.type,
112
+ numFrames: Math.ceil(file.size / RbtFile.FRAME_SIZE)
113
+ };
114
+
115
+ while (offset < file.size) {
116
+ const chunk = file.slice(offset, offset + RbtFile.FRAME_SIZE);
117
+ await new Promise((resolve, reject) => {
118
+ const reader = new FileReader();
119
+ reader.onload = async (e) => {
120
+ const arrayBuffer = e.target.result;
121
+ const frameIndex = offset / RbtFile.FRAME_SIZE;
122
+ await this._storeChunkInIDB(arrayBuffer, frameIndex, this.fileHeader);
123
+ this.setProgress((frameIndex + 1) / this.fileHeader.numFrames);
124
+ resolve();
125
+ };
126
+ reader.onerror = () => reject(reader.error);
127
+ reader.readAsArrayBuffer(chunk);
128
+ });
129
+ offset += RbtFile.FRAME_SIZE;
130
+ }
131
+ }
132
+
133
+ _extractFileExtension(fileName) {
134
+ // Find the last dot in the filename
135
+ const lastDotIndex = fileName.lastIndexOf('.');
136
+
137
+ // No dot found, or the dot is the first character (hidden files)
138
+ if (lastDotIndex === -1 || lastDotIndex === 0) return '';
139
+
140
+ // Extract the extension
141
+ return fileName.substring(lastDotIndex + 1);
142
+ }
143
+
144
+ async _storeChunkInIDB(chunk, frameIndex, fileHeader) {
145
+ const db = this._localDb;
146
+ if (!db) {
147
+ console.error('Database not initialized');
148
+ return;
149
+ }
150
+ const tx = db.transaction('files', 'readwrite');
151
+ const frameKey = `${this.id}_${frameIndex}`; // Unique key combining id and frameIndex
152
+ await tx.store.put({ key: frameKey, chunk, fileHeader }, frameKey);
153
+ await tx.done;
154
+ }
155
+
156
+ async _readFrameFromIDB(frameIndex) {
157
+ const db = this._localDb;
158
+ if (!db) {
159
+ console.error('Database not initialized');
160
+ return null;
161
+ }
162
+ const frameKey = `${this.id}_${frameIndex}`; // Same key as used in _storeChunkInIDB
163
+ const tx = db.transaction('files', 'readonly');
164
+ const frame = await tx.store.get(frameKey);
165
+
166
+ return frame ? frame.chunk : null;
167
+ }
168
+
169
+ async uploadFile() {
170
+ if (!this.fileHeader || !this.fileHeader.numFrames) {
171
+ throw new Error("File not ready for upload.");
172
+ }
173
+
174
+ this.fileRecord = this.toRecord();
175
+
176
+ let frameRes;
177
+
178
+ for (let frameIndex = 0; frameIndex < this.fileHeader.numFrames; frameIndex++) {
179
+ try {
180
+ const frameData = await this._readFrameFromIDB(frameIndex);
181
+ if (!frameData) {
182
+ throw new Error(`Failed to read frame ${frameIndex}`);
183
+ }
184
+
185
+ frameRes = await this._uploadFrameToServer(frameData, frameIndex, this.fileHeader, this.fileRecord);
186
+
187
+ // Update progress after each frame is uploaded
188
+ this.setProgress((frameIndex + 1) / this.fileHeader.numFrames);
189
+ } catch (error) {
190
+ console.error(`Error uploading frame ${frameIndex}:`, error);
191
+ throw error; // Stop the upload process if an error occurs
192
+ }
193
+ }
194
+
195
+
196
+ //
197
+ // DONE UPLOADING, PROCESSING
198
+ //
199
+
200
+ try {
201
+ const statusRes = await this._checkUploadStatusUntilDone(this.fileRecord);
202
+
203
+ this.set('remoteSrc', statusRes.remoteSrc);
204
+ this.set('progress', 1);
205
+ await this.save();
206
+ } catch (error) {
207
+ console.error('Error during upload status check:', error);
208
+ // Handle error, possibly update UI or retry logic
209
+ }
210
+
211
+ }
212
+
213
+ async _uploadFrameToServer(frameData, frameIndex, fileHeader, fileRecord) {
214
+
215
+ const base64Data = this.convertToBase64(frameData);
216
+ const payload = [
217
+ "@filekit.ffs_server_receiveAndStore_toS3_flow",
218
+ {
219
+ "fileObject": fileRecord, // using fileRecord from newFile.toRecord()
220
+ "fileHeader": fileHeader,
221
+ "frameIndex": frameIndex,
222
+ "frameData": `rpcBase64:${base64Data}`,
223
+ "timeout": 86400000
224
+ }
225
+ ];
226
+
227
+ console.log(payload);
228
+
229
+ const response = await this._axios.post('/file_service/ffs_runFlow', payload);
230
+
231
+ if (!response || response.status != 200) {
232
+ throw new Error('Error uploading frame to server');
233
+ }
234
+
235
+ return response;
236
+ }
237
+
238
+
239
+ async _checkUploadStatusUntilDone(fileRecord) {
240
+
241
+ return new Promise((resolve, reject) => {
242
+ const intervalId = setInterval(async () => {
243
+ try {
244
+ const statusRes = await this._uploadGetStatusUpdate(fileRecord);
245
+ if (statusRes.data && statusRes.data.fileHeader && statusRes.data.fileHeader.status === 'DONE') {
246
+ clearInterval(intervalId); // Stop the interval
247
+ resolve(statusRes.data.fileHeader); // Resolve the promise with the final status
248
+ } else {
249
+ // Optionally update progress or handle other status cases here
250
+ //this.emit('progress', statusRes.progress); // Emit progress updates if available
251
+ }
252
+ } catch (error) {
253
+ clearInterval(intervalId); // Stop the interval on error
254
+ reject(error); // Reject the promise if there's an error
255
+ }
256
+ }, 2000); // Check every 2 seconds
257
+ });
258
+
259
+ }
260
+
261
+
262
+
263
+ async _uploadGetStatusUpdate(fileRecord){
264
+
265
+ const payload = [
266
+ "@filekit.ffs_server_receiveAndStore_toS3_flow",
267
+ {
268
+ "fileObject": fileRecord, // using fileRecord from newFile.toRecord()
269
+ "getStatusUpdate": true
270
+ }
271
+ ];
272
+
273
+ console.log(payload);
274
+
275
+ const response = await this._axios.post('/file_service/ffs_runFlow', payload);
276
+
277
+ if (!response || response.status != 200) {
278
+ throw new Error('Error getting upload status');
279
+ }
280
+
281
+ return response;
282
+
283
+
284
+ }
285
+
286
+ convertToBase64(buffer) {
287
+ return btoa(
288
+ new Uint8Array(buffer)
289
+ .reduce((data, byte) => data + String.fromCharCode(byte), '')
290
+ );
291
+ }
292
+ }