path#relative JavaScript Examples

The following examples show how to use path#relative. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: logger.js    From aresrpg with MIT License 6 votes vote down vote up
export default function logger({
  url = null,
  name = strip_extension(relative(root, fileURLToPath(url))),
}) {
  return pino({
    base: { name },
    level: 'info',
  })
}
Example #2
Source File: aem-component-loader.js    From aem with MIT License 6 votes vote down vote up
getResourceType = (rootContext, context) => {
  const segs = relative(rootContext, context).split(pathSeparator);
  // if component is in different module, it will be below a node_modules
  let idx = segs.indexOf(NAME_NODE_MODULES);
  if (idx >= 0) {
    // remove all segments including node_modules
    segs.splice(0, idx + 1);
  }
  // if component is below a jcr_root
  idx = segs.indexOf(NAME_JCR_ROOT);
  if (idx >= 0) {
    // remove all segments including jcr_root
    segs.splice(0, idx + 1);
    if (segs[0] === NAME_APPS || segs[1] === NAME_LIBS) {
      segs.splice(0, 1);
    }
  }
  return segs.join('/');
}
Example #3
Source File: pluginUtils.js    From fes.js with MIT License 5 votes vote down vote up
export function pathToObj({ path, type, cwd }) {
    let pkg = null;
    let isPkgPlugin = false;
    const pkgJSONPath = pkgUp.sync({ cwd: path });
    if (pkgJSONPath) {
        // eslint-disable-next-line
        pkg = require(pkgJSONPath);
        isPkgPlugin = winPath(join(dirname(pkgJSONPath), pkg.main || 'index.js'))
            === winPath(path);
    }

    let id;
    if (isPkgPlugin) {
        id = pkg.name;
    } else if (winPath(path).startsWith(winPath(cwd))) {
        id = `./${winPath(relative(cwd, path))}`;
    } else if (pkgJSONPath) {
        id = winPath(join(pkg.name, relative(dirname(pkgJSONPath), path)));
    } else {
        id = winPath(path);
    }
    id = id.replace('@fesjs/preset-built-in/lib/plugins', '@@');
    id = id.replace(/\.js$/, '');

    const key = isPkgPlugin
        ? pkgNameToKey(pkg.name, type)
        : nameToKey(basename(path, extname(path)));

    return {
        id,
        key,
        path: winPath(path),
        apply() {
            // use function to delay require
            try {
                // eslint-disable-next-line
                const ret = require(path);
                // use the default member for es modules
                return compatESModuleRequire(ret);
            } catch (e) {
                throw new Error(`Register ${path} failed, since ${e.message}`);
            }
        },
        defaultConfig: null
    };
}
Example #4
Source File: Generator.js    From fes.js with MIT License 5 votes vote down vote up
copyTpl(opts) {
      const tpl = readFileSync(opts.templatePath, 'utf-8');
      const content = Mustache.render(tpl, opts.context);
      mkdirp.sync(dirname(opts.target));
      console.log(`${chalk.green('Write:')} ${relative(this.cwd, opts.target)}`);
      writeFileSync(opts.target, content, 'utf-8');
  }
Example #5
Source File: configHelpers.js    From twin.macro with MIT License 5 votes vote down vote up
getRelativePath = ({ comparePath, state }) => {
  const { filename } = state.file.opts
  const pathName = parse(filename).dir
  return relative(pathName, comparePath)
}
Example #6
Source File: index.js    From kit with MIT License 5 votes vote down vote up
/**
 * @param {import('types').ValidatedConfig} config
 * @param {string} cwd
 */
export async function build(config, cwd = process.cwd()) {
	const { lib } = config.kit.files;
	const { dir } = config.kit.package;

	if (!fs.existsSync(lib)) {
		throw new Error(`${lib} does not exist`);
	}

	rimraf(dir);
	mkdirp(dir);

	// Make sure generated tsconfig is up-to-date
	write_tsconfig(config.kit, cwd);

	const files = scan(config);

	if (config.kit.package.emitTypes) {
		await emit_dts(config, cwd, files);
	}

	const pkg = generate_pkg(cwd, files);

	if (!pkg.svelte && files.some((file) => file.is_svelte)) {
		// Several heuristics in Kit/vite-plugin-svelte to tell Vite to mark Svelte packages
		// rely on the "svelte" property. Vite/Rollup/Webpack plugin can all deal with it.
		// See https://github.com/sveltejs/kit/issues/1959 for more info and related threads.
		if (pkg.exports['.']) {
			const svelte_export =
				typeof pkg.exports['.'] === 'string'
					? pkg.exports['.']
					: pkg.exports['.'].import || pkg.exports['.'].default;
			if (svelte_export) {
				pkg.svelte = svelte_export;
			} else {
				console.warn(
					'Cannot generate a "svelte" entry point because the "." entry in "exports" is not a string. If you set it by hand, please also set one of the options as a "svelte" entry point\n'
				);
			}
		} else {
			console.warn(
				'Cannot generate a "svelte" entry point because the "." entry in "exports" is missing. Please specify one or set a "svelte" entry point yourself\n'
			);
		}
	}

	write(join(dir, 'package.json'), JSON.stringify(pkg, null, 2));

	for (const file of files) {
		await process_file(config, file);
	}

	const whitelist = fs.readdirSync(cwd).filter((file) => {
		const lowercased = file.toLowerCase();
		return essential_files.some((name) => lowercased.startsWith(name.toLowerCase()));
	});

	for (const pathname of whitelist) {
		const full_path = join(cwd, pathname);
		if (fs.lstatSync(full_path).isDirectory()) continue; // just to be sure

		const package_path = join(dir, pathname);
		if (!fs.existsSync(package_path)) fs.copyFileSync(full_path, package_path);
	}

	const from = relative(cwd, lib);
	const to = relative(cwd, dir);
	console.log(colors.bold().green(`${from} -> ${to}`));
	console.log(`Successfully built '${pkg.name}' package. To publish it to npm:`);
	console.log(colors.bold().cyan(`  cd ${to}`));
	console.log(colors.bold().cyan('  npm publish\n'));
}
Example #7
Source File: js.js    From ucompress with ISC License 4 votes vote down vote up
JS = (
  source, dest, options = {},
  /* istanbul ignore next */ known = umap(new Map),
  initialSource = dirname(source),
  initialDest = dirname(dest)
) => known.get(dest) || known.set(dest, minify(source, options).then(
  ({original, code, map}) => {
    const modules = [];
    const newCode = [];
    if (options.noImport)
      newCode.push(code);
    else {
      const baseSource = dirname(source);
      const baseDest = dirname(dest);
      const re = /(["'`])(?:(?=(\\?))\2.)*?\1/g;
      let i = 0, match;
      while (match = re.exec(code)) {
        const {0: whole, 1: quote, index} = match;
        const chunk = code.slice(i, index);
        const next = index + whole.length;
        let content = whole;
        newCode.push(chunk);
        /* istanbul ignore else */
        if (
          /(?:\bfrom\b|\bimport\b\(?)\s*$/.test(chunk) &&
          (!/\(\s*$/.test(chunk) || /^\s*\)/.test(code.slice(next)))
        ) {
          const module = whole.slice(1, -1);
          if (/^[a-z@][a-z0-9/._-]+$/i.test(module)) {
            try {
              const {length} = module;
              let path = $require.resolve(module, {paths: [baseSource]});
              /* istanbul ignore next */
              if (!path.includes(module) && /(\/|\\[^ ])/.test(module)) {
                const sep = RegExp.$1[0];
                const source = module.split(sep);
                const target = path.split(sep);
                const js = source.length;
                for (let j = 0, i = target.indexOf(source[0]); i < target.length; i++) {
                  if (j < js && target[i] !== source[j++])
                    target[i] = source[j - 1];
                }
                path = target.join(sep);
                path = [
                  path.slice(0, path.lastIndexOf('node_modules')),
                  'node_modules',
                  source[0]
                ].join(sep);
              }
              else {
                let oldPath = path;
                do path = dirname(oldPath);
                while (
                  path !== oldPath &&
                  path.slice(-length) !== module &&
                  (oldPath = path)
                );
              }
              const i = path.lastIndexOf('node_modules');
              /* istanbul ignore if */
              if (i < 0)
                throw new Error('node_modules folder not found');
              const {exports: e, module: m, main, type} = $require(
                join(path, 'package.json')
              );
              /* istanbul ignore next */
              const index = (e && (e.import || e['.'].import)) || m || (type === 'module' && main);
              /* istanbul ignore if */
              if (!index)
                throw new Error('no entry file found');
              const newSource = resolve(path, index);
              const newDest = resolve(initialDest, path.slice(i), index);
              modules.push(JS(
                newSource, newDest,
                options, known,
                initialSource, initialDest
              ));
              path = uModules(
                noBackSlashes(relative(dirname(source), newSource))
              );
              /* istanbul ignore next */
              content = `${quote}${path[0] === '.' ? path : `./${path}`}${quote}`;
            }
            catch ({message}) {
              console.warn(`unable to import "${module}"`, message);
            }
          }
          /* istanbul ignore else */
          else if (!/^([a-z]+:)?\/\//i.test(module)) {
            modules.push(JS(
              resolve(baseSource, module),
              resolve(baseDest, module),
              options, known,
              initialSource, initialDest
            ));
          }
        }
        newCode.push(content);
        i = next;
      }
      newCode.push(code.slice(i));
    }
    let smCode = newCode.join('');
    if (options.sourceMap) {
      const destSource = dest.replace(/(\.m?js)$/i, `$1.source$1`);
      const json = parse(map);
      const file = basename(dest);
      json.file = file;
      json.sources = [basename(destSource)];
      smCode = smCode.replace(source, file);
      modules.push(
        saveCode(source, `${dest}.map`, stringify(json), options),
        saveCode(source, destSource, original, options)
      );
    }
    return Promise.all(
      modules.concat(saveCode(source, dest, smCode, options))
    ).then(
      () => dest,
      /* istanbul ignore next */
      err => Promise.reject(err)
    );
  }
))
Example #8
Source File: index.js    From tinyjam with ISC License 4 votes vote down vote up
export default function tinyjam(src, dest = src, options = {}) {
    options = Object.assign({}, defaultOptions, options);

    // Markdown renderer options
    const {breaks, smartypants, highlight} = options;
    const markedOptions = {breaks, smartypants, highlight, smartLists: true};

    const proto = {};
    const root = createCtx('.'); // root data object
    proto.root = root; // add data root access to all leaf nodes

    const templates = [];
    const cache = {}; // include cache

    fs.mkdirSync(dest, {recursive: true}); // make sure destination exists

    walk(src, root); // process files, collect data and templates to render

    // render templates; we do it later to make sure all data is collected first
    for (const {ejs, path, data, dir, name, ext, isCollection} of templates) {
        if (isCollection) {
            for (const key of Object.keys(data)) {
                render(ejs, path, data[key], dir, key, ext);
            }
        } else {
            render(ejs, path, data, dir, name, ext);
        }
    }

    function log(msg) {
        if (options.log) console.log(msg);
    }

    function render(ejs, filename, data, dir, name, ext) {
        const path = join(dir, name) + ext;
        const template = compile(ejs, {
            locals: Object.keys(data).concat(['root', 'rootPath']),
            filename, read, resolve, cache
        });
        log(`render  ${path}`);
        fs.writeFileSync(join(dest, path), template(data));
    }

    function resolve(parent, filename) {
        return join(dirname(parent), filename);
    }

    function read(filename) {
        return fs.readFileSync(filename, 'utf8');
    }

    // create an object to be used as evalulation data in a template
    function createCtx(rootPath, properties) {
        // prototype magic to make sure all data objects have access to root/rootPath
        // in templates and includes without them being enumerable
        const ctx = Object.create(proto, {rootPath: {value: rootPath, enumerable: false}});
        if (properties) Object.assign(ctx, properties);
        return ctx;
    }

    // recursively walk through and process files inside the source directory
    function walk(dir, data) {
        const files = fs.readdirSync(dir);

        for (const file of files) {
            const path = join(dir, file);
            if (relative(path, dest) === '') continue;

            const shortPath = relative(src, path);
            const ext = extname(path);
            const name = basename(path, ext);
            const rootPath = relative(dirname(shortPath), '');
            const destPath = join(dest, shortPath);

            if (file[0] === '.' || file === 'node_modules' || ext === '.lock' || name.endsWith('-lock')) {
                log(`skip    ${shortPath}`);
                continue;
            }

            const stats = fs.lstatSync(path);

            if (stats.isDirectory()) {
                fs.mkdirSync(destPath, {recursive: true});
                data[file] = createCtx(join(rootPath, '..'));
                walk(path, data[file]);
                continue;
            }

            if (ext === '.md') {
                log(`read    ${shortPath}`);
                const {body, attributes} = parseFrontMatter(fs.readFileSync(path, 'utf8'));

                data[name] = createCtx(rootPath, {...attributes, body: marked(body, markedOptions)});

            } else if (ext === '.yml' || ext === '.yaml') {
                log(`read    ${shortPath}`);
                data[name] = createCtx(rootPath, yaml.load(fs.readFileSync(path, 'utf8')));

            } else if (ext === '.ejs') {
                if (name[0] === '_') { // skip includes
                    log(`skip    ${shortPath}`);
                    continue;
                }
                log(`compile ${shortPath}`);
                templates.push({
                    data,
                    name,
                    path,
                    ejs: fs.readFileSync(path, 'utf8'),
                    isCollection: name === 'item',
                    dir: dirname(shortPath),
                    ext: extname(name) ? '' : '.html'
                });

            } else if (path !== destPath) {
                log(`copy    ${shortPath}`);
                fs.copyFileSync(path, destPath);
            }
        }
    }
}
Example #9
Source File: index.js    From kit with MIT License 4 votes vote down vote up
/**
 * @param {import('types').ValidatedConfig} config
 */
export async function watch(config, cwd = process.cwd()) {
	await build(config, cwd);

	const message = `\nWatching ${relative(cwd, config.kit.files.lib)} for changes...\n`;

	console.log(message);

	const { lib } = config.kit.files;
	const { dir } = config.kit.package;

	/** @type {Array<{ file: import('./types').File, type: string }>} */
	const pending = [];

	/** @type {Array<(value?: any) => void>} */
	const fulfillers = [];

	/** @type {NodeJS.Timeout} */
	let timeout;

	const watcher = chokidar.watch(lib, { ignoreInitial: true });
	const ready = new Promise((resolve) => watcher.on('ready', resolve));

	watcher.on('all', async (type, path) => {
		const file = analyze(config, relative(lib, path));
		if (!file.is_included) return;

		pending.push({ file, type });

		clearTimeout(timeout);
		timeout = setTimeout(async () => {
			const files = scan(config);

			let should_update_pkg = false;

			const events = pending.slice();
			pending.length = 0;

			for (const { file, type } of events) {
				if ((type === 'unlink' || type === 'add') && file.is_exported) {
					should_update_pkg = true;
				}

				if (type === 'unlink') {
					for (const candidate of [
						file.name,
						`${file.base}.d.ts`,
						`${file.base}.d.mts`,
						`${file.base}.d.cts`
					]) {
						const resolved = join(dir, candidate);

						if (fs.existsSync(resolved)) {
							fs.unlinkSync(resolved);

							const parent = dirname(resolved);
							if (parent !== dir && fs.readdirSync(parent).length === 0) {
								fs.rmdirSync(parent);
							}
						}
					}
					console.log(`Removed ${file.dest}`);
				}

				if (type === 'add' || type === 'change') {
					await process_file(config, file);
					console.log(`Processing ${file.name}`);
				}
			}

			if (should_update_pkg) {
				const pkg = generate_pkg(cwd, files);
				write(join(dir, 'package.json'), JSON.stringify(pkg, null, 2));
				console.log('Updated package.json');
			}

			if (config.kit.package.emitTypes) {
				await emit_dts(config, cwd, scan(config));
				console.log('Updated .d.ts files');
			}

			console.log(message);

			fulfillers.forEach((fn) => fn());
		}, 100);
	});

	return {
		watcher,
		ready,
		settled: () =>
			new Promise((fulfil, reject) => {
				fulfillers.push(fulfil);
				setTimeout(() => reject(new Error('Timed out')), 1000);
			})
	};
}