UNPKG

ipfs-gateway-emulator

Version:

A server emulating IPFS gateway behaviour, for local preview and end-to-end tests

106 lines (90 loc) 2.87 kB
import {startServer} from './server.js'; const USAGE = `ipfs-gateway-emulator An IPFS gateway emulator. Serves a directory the way a path gateway does, so that "works locally, breaks on IPFS" problems surface before deploying. Synopsis $ ipfs-emulator [options] Options -d, --directory <path> Directory to serve. Defaults to the current directory. -p, --port <number> Port to listen on. Defaults to 8080. --only [root|hash] Serve only one addressing scheme. "hash" serves only /ipfs/<cid>/..., any other value serves only root paths. Passing the flag with no value serves both. --fail <status>:<dirs> Make comma-separated directories fail with the given status, to exercise client error handling. -h, --help Print this help. -v, --version Print the version. Project home: https://github.com/wighawag/ipfs-gateway-emulator `; /** * Parse argv. * * `--only` is deliberately value-optional: callers use `--only -d build`, where * the flag is present but carries no value. A value is only consumed when the * next argument is not itself a flag, so the following `-d` is never swallowed. */ export function parseArgs(argv) { const options = {port: 8080, directory: '.'}; const valueAhead = (index) => { const next = argv[index + 1]; return next !== undefined && !next.startsWith('-'); }; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; switch (arg) { case '-h': case '--help': options.help = true; break; case '-v': case '--version': options.version = true; break; case '-d': case '--directory': options.directory = argv[++i]; break; case '-p': case '--port': options.port = Number.parseInt(argv[++i], 10); break; case '--only': options.only = valueAhead(i) ? argv[++i] : undefined; break; case '--fail': options.fail = valueAhead(i) ? argv[++i] : undefined; break; default: if (arg.startsWith('-')) { throw new Error(`Unknown option: ${arg}`); } } } if (options.directory === undefined) { throw new Error('--directory requires a value'); } if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535) { throw new Error('--port requires a valid port number'); } return options; } /** Run the CLI. Returns the server, or undefined when it only printed output. */ export function run(argv, {log = console.log, logError = console.error, version = '0.0.0'} = {}) { let options; try { options = parseArgs(argv); } catch (error) { logError(error.message); process.exitCode = 1; return undefined; } if (options.help) { log(USAGE); return undefined; } if (options.version) { log(version); return undefined; } return startServer({...options, log}); }