Skip to content

Instantly share code, notes, and snippets.

@ZicklePop
Last active December 9, 2023 05:21
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ZicklePop/603b19dd3b9e09f99030bc24e616ca6c to your computer and use it in GitHub Desktop.
unpkg importer for scriptable.app, downloads modules to `iCloud Drive/Scriptable/modules`
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: green; icon-glyph: archive;
// unpkg: like NPM but not as good
// and available in Scriptable
//
// Examples:
// - const _ = await unpkg('lodash')
// - const CryptoJS = await unpkg('crypto-js')
// - const OAuth = await unpkg('oauth-1.0a')
const unpkg = (package, file, version) => {
return new Promise((callback) => {
const jsFile = file || package
const pkgVersion = version ? `@${version}` : ''
const fm = FileManager.iCloud()
const modulesPath = fm.joinPath(fm.documentsDirectory(), 'modules/')
const modulePath = fm.joinPath(modulesPath, `${package}${pkgVersion}/`)
const filePath = fm.joinPath(modulePath, `${jsFile.split('/')[jsFile.split('/').length-1]}.js`)
if (!fm.fileExists(modulePath)) {
fm.createDirectory(modulePath, true)
}
if (!fm.fileExists(filePath) ) {
const req = new Request(`https://unpkg.com/${package}${pkgVersion}/${jsFile}.js`)
req.loadString().then(res => {
fm.writeString(filePath, `${res}`).then(() => {
callback(importModule(filePath))
})
})
} else {
fm.downloadFileFromiCloud(filePath).then(() => {
callback(importModule(filePath))
})
}
})
}
module.exports = unpkg
@kopischke
Copy link

kopischke commented Jan 13, 2020

Great module, that will come in very handy. You can simplify lines 16 to 21 by using Scriptable’s ability to create intermediate directories when using createDirectory, i.e. this will have the same effect:

if (!fm.fileExists(modulePath)) fm.createDirectory(modulePath, true)

@ZicklePop
Copy link
Author

oh cool, thanks! i was hoping that was an option

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment