| 299 | function API(name = "untitled", debug = false) { |
| 300 | const { isQX, isLoon, isSurge, isNode, isJSBox, isScriptable } = ENV(); |
| 301 | return new (class { |
| 302 | constructor(name, debug) { |
| 303 | this.name = name; |
| 304 | this.debug = debug; |
| 305 | |
| 306 | this.http = HTTP(); |
| 307 | this.env = ENV(); |
| 308 | |
| 309 | this.node = (() => { |
| 310 | if (isNode) { |
| 311 | const fs = require("fs"); |
| 312 | |
| 313 | return { |
| 314 | fs, |
| 315 | }; |
| 316 | } else { |
| 317 | return null; |
| 318 | } |
| 319 | })(); |
| 320 | this.initCache(); |
| 321 | |
| 322 | const delay = (t, v) => |
| 323 | new Promise(function (resolve) { |
| 324 | setTimeout(resolve.bind(null, v), t); |
| 325 | }); |
| 326 | |
| 327 | Promise.prototype.delay = function (t) { |
| 328 | return this.then(function (v) { |
| 329 | return delay(t, v); |
| 330 | }); |
| 331 | }; |
| 332 | } |
| 333 | |
| 334 | // persistence |
| 335 | // initialize cache |
| 336 | initCache() { |
| 337 | if (isQX) this.cache = JSON.parse($prefs.valueForKey(this.name) || "{}"); |
| 338 | if (isLoon || isSurge) |
| 339 | this.cache = JSON.parse($persistentStore.read(this.name) || "{}"); |
| 340 | |
| 341 | if (isNode) { |
| 342 | // create a json for root cache |
| 343 | let fpath = "root.json"; |
| 344 | if (!this.node.fs.existsSync(fpath)) { |
| 345 | this.node.fs.writeFileSync( |
| 346 | fpath, |
| 347 | JSON.stringify({}), |
| 348 | { |
| 349 | flag: "wx", |
| 350 | }, |
| 351 | (err) => console.log(err) |
| 352 | ); |
| 353 | } |
| 354 | this.root = {}; |
| 355 | |
| 356 | // create a json file with the given name if not exists |
| 357 | fpath = `${this.name}.json`; |
| 358 | if (!this.node.fs.existsSync(fpath)) { |
nothing calls this directly
no outgoing calls
no test coverage detected