Skip to content

Instantly share code, notes, and snippets.

@palmin
Last active February 17, 2024 11:08
Show Gist options
  • Save palmin/64d143afdb5fccf966bc55cb40398c28 to your computer and use it in GitHub Desktop.
Save palmin/64d143afdb5fccf966bc55cb40398c28 to your computer and use it in GitHub Desktop.
var _require_cache_ = {};
function require(name) {
let local = FileManager.local();
// look for script with the given name in iCloud documents
// and current directory adding .js to filename is not present
let resolve = function(name) {
var filename = name;
if(name.indexOf('.js') < 0) {
filename += '.js';
}
const docs = "/var/mobile/Library/Mobile Documents/iCloud~dk~simonbs~Scriptable/Documents/";
let paths = [docs, '']; // TODO: Maybe add directory of calling script and shared module directory to paths
for (var k = 0; k < paths.length; ++k) {
let resolved = paths[k] + filename;
if(local.fileExists(resolved)) return resolved;
}
throw "unable to find '" + filename + "'";
};
// fetch object from either cache or filesystem
let procure = function(path) {
// check if we have this module cached
let cache = _require_cache_;
if(cache[path]) return cache[path];
// load and evaluate from filesystem
let content = local.readString(path);
var inner = new Function('exports', content);
var exports = {};
inner(exports);
// cache for next procurement
cache[path] = exports;
return exports;
};
let path = resolve(name);
return procure(path);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment