url#pathToFileURL TypeScript Examples

The following examples show how to use url#pathToFileURL. 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: path.ts    From next-sitemap with MIT License 6 votes vote down vote up
getConfigFilePath = async () => {
  // Extract args from command
  const args = minimist(process.argv.slice(2))

  // Config file path
  const configPath = getPath(args.config || 'next-sitemap.config.js')

  // Check file stat
  return fs
    .stat(configPath)
    .then(() => pathToFileURL(configPath).toString())
    .catch((err) => {
      Logger.noConfigFile()
      throw err
    })
}
Example #2
Source File: configuration.ts    From cross-seed with Apache License 2.0 6 votes vote down vote up
export async function getFileConfig(): Promise<FileConfig> {
	const configPath = path.join(appDir(), "config.js");

	try {
		return (await import(pathToFileURL(configPath).toString())).default;
	} catch (e) {
		if (e.code !== "ERR_MODULE_NOT_FOUND") throw e;
		return {};
	}
}
Example #3
Source File: MessageUtilities.ts    From discord-qt with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Replaces emoji strings with placeholder squares.
 * @param content String to process.
 */
export async function processEmojiPlaceholders(content: string): Promise<string> {
  let newContent = content;
  const uContent = unescape(content);
  const emoIds = uContent.match(EMOJI_REGEX) || [];
  const size =
    uContent
      .replace(EMOJI_REGEX, '')
      .replace(/<\/?p>/g, '')
      .trim() === ''
      ? 48
      : 24;

  for (const emo of emoIds) {
    newContent = newContent.replace(
      escape(emo),
      `<img width="${size}" height="${size}" src="${pathToFileURL(EMOJI_PLACEHOLDER)}" />`
    );
  }

  return newContent;
}
Example #4
Source File: configLoader.ts    From language-tools with MIT License 6 votes vote down vote up
private async loadConfig(configPath: string, directory: string) {
        try {
            let config = this.disabled
                ? {}
                : (await this.dynamicImport(pathToFileURL(configPath)))?.default;

            if (!config) {
                throw new Error(
                    'Missing exports in the config. Make sure to include "export default config" or "module.exports = config"'
                );
            }
            config = {
                ...config,
                compilerOptions: {
                    ...DEFAULT_OPTIONS,
                    ...config.compilerOptions,
                    ...NO_GENERATE
                }
            };
            Logger.log('Loaded config at ', configPath);
            return config;
        } catch (err) {
            Logger.error('Error while loading config at ', configPath);
            Logger.error(err);
            const config = {
                ...this.useFallbackPreprocessor(directory, true),
                compilerOptions: {
                    ...DEFAULT_OPTIONS,
                    ...NO_GENERATE
                },
                loadConfigError: err
            };
            return config;
        }
    }
Example #5
Source File: docs.ts    From WebCord with MIT License 5 votes vote down vote up
function handleUrls(container:HTMLElement, article:HTMLElement, header:HTMLElement, mdPrevious: string):void {
    for(const link of container.getElementsByTagName('a')){
        link.onclick = () => {
            window.history.replaceState("", "", pathToFileURL(mdPrevious))
            // Handle links with the whitelisted protocols
            if(new URL(link.href).protocol.match(trustedProtocolRegExp)) {
                open(link.href)
            // Handle in-document links
            } else if (link.href.startsWith(document.URL.replace(/#.*/, '')+'#')) {
                const id = getId(link.href);
                if (id) {
                    const element = document.getElementById(id)
                    if(element) element.scrollIntoView({behavior: "smooth"});
                }
            // Handle markdown links and 'LICENSE' files.
            } else if(link.href.match(/^file:\/\/.+(\.md|LICENSE)(#[a-z0-9-]+)?$/)) {
                const mdFile = fileURLToPath(link.href);
                const id = getId(link.href);
                const oldHeader = menuHeader.innerHTML
                menuHeader.innerText = basename(mdFile);
                document.body.removeChild(article);
                if(existsSync(mdFile)){
                    loadMarkdown(container,mdFile);
                    mdPrevious = mdFile;
                } else {
                    // Fix for HTML links ('<a>' elements) that are unhandled by marked.
                    const relFile = relative(document.URL, link.href);
                    const mdFile = resolve(mdPrevious, relFile);
                    if(!existsSync(mdFile)) {
                        // Failsafe: revert all changes done so far...
                        console.error("File '"+mdFile+"' does not exists!");
                        document.body.appendChild(article);
                        window.history.pushState("", "", htmlFileUrl);
                        menuHeader.innerHTML = oldHeader;
                        return false;
                    }
                    loadMarkdown(container,mdFile);
                    mdPrevious = mdFile;
                    console.log(relFile);
                }
                window.scroll(0,0);
                handleUrls(container, article, header, mdPrevious);
                fixImages(container);
                document.body.appendChild(article);
                if (id) {
                    const element = document.getElementById(id);
                    if (element) element.scrollIntoView();
                }
            }
            window.history.pushState("", "", htmlFileUrl)
            return false;
        }
    }
}
Example #6
Source File: main.ts    From WowUp with GNU General Public License v3.0 5 votes vote down vote up
function loadMainUrl(window: BrowserWindow) {
  const url = pathToFileURL(join(__dirname, "..", "dist", "index.html"));
  return window?.loadURL(url.toString());
}
Example #7
Source File: setup.ts    From vite-plugin-ssr with MIT License 5 votes vote down vote up
async function dynamicImport(filePath: string): Promise<unknown> {
  return new Function('file', 'return import(file)')(pathToFileURL(filePath).href)
}
Example #8
Source File: AttachmentsPanel.ts    From discord-qt with GNU General Public License v3.0 5 votes vote down vote up
private updateComponent() {
    const { layout } = this;

    (layout.nodeChildren as Set<QWidget>).forEach((w) => {
      w.hide();
      layout.removeWidget(w);
    });

    for (const file of this.files) {
      const attach = new QLabel(this);

      attach.setFixedSize(120, 60);
      attach.setAlignment(AlignmentFlag.AlignCenter);
      attach.setProperty('toolTip', __('RIGHT_CLICK_REMOVE'));
      attach.addEventListener(WidgetEventTypes.MouseButtonPress, (e) => {
        const event = new QMouseEvent(e as any);

        if ((event.button() & MouseButton.RightButton) === MouseButton.RightButton) {
          this.files.delete(file);
          this.updateComponent();
        }
      });

      const url = pathToFileURL(file);
      const ext = extname(file).replace(/\./g, '').toUpperCase();

      if (!PIXMAP_EXTS.includes(ext)) {
        attach.setPixmap(AttachmentsPanel.fileIcon);
      } else {
        pictureWorker
          .loadImage(url.href, { roundify: false })
          .then((path) => {
            if (this.native.destroyed) {
              return;
            }

            const pix = new QPixmap(path);

            if (pix.width() < 1) {
              attach.setPixmap(AttachmentsPanel.fileIcon);
            } else {
              attach.setPixmap(pix.scaled(120, 60, 1, 1));
            }
          })
          .catch(() => {
            error(`Couldn't access file ${file}.`);
            attach.setPixmap(AttachmentsPanel.fileIcon);
          });
      }

      this.layout.insertWidget(this.layout.nodeChildren.size, attach);
    }

    if (this.files.size) {
      this.show();
    } else {
      this.hide();
    }
  }
Example #9
Source File: MessageUtilities.ts    From discord-qt with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Replaces emoji strings with actual emoji images.
 * @param content String to process.
 */
export async function processEmojis(content: string, message: MessageItem): Promise<string> {
  let newContent = content;
  const uContent = unescape(content);
  const emoIds = uContent.match(EMOJI_REGEX) || [];
  const size =
    uContent
      .replace(EMOJI_REGEX, '')
      .replace(/<\/?p>/g, '')
      .trim() === ''
      ? 48
      : 24;

  const promises: Promise<any>[] = emoIds.map((emo) => {
    const [type, name, id] = emo.replace('<', '').replace('>', '').split(':');
    const format = type === 'a' ? 'gif' : 'png';

    return resolveEmoji({ emoji_id: id, emoji_name: name })
      .then((emojiPath) => {
        // @ts-ignore
        const uri = new URL(app.client.rest.cdn.Emoji(id, format));

        uri.searchParams.append('emoji_name', name);

        const pix = new QPixmap(emojiPath);

        if (message.native.destroyed) {
          return;
        }

        const larger = pix.width() > pix.height() ? 'width' : 'height';

        newContent = newContent.replace(
          escape(emo),
          `<a href='${uri.href}'><img ${larger}=${size} src='${pathToFileURL(emojiPath)}'></a>`
        );
      })
      .catch(() => {
        debug(`Emoji <:${name}:${id}> was not resolved.`);
      });
  });

  try {
    await Promise.all(promises);
  } catch (e) {}

  return newContent;
}
Example #10
Source File: dynamicImport.ts    From telefunc with MIT License 5 votes vote down vote up
async function dynamicImport(filePath: string): Promise<Record<string, unknown>> {
  return new Function('file', 'return import(file)')(pathToFileURL(filePath).href)
}
Example #11
Source File: createDryRunner.ts    From backstage with Apache License 2.0 4 votes vote down vote up
/**
 * Executes a dry-run of the provided template.
 *
 * The provided content will be extracted into a temporary directory
 * which is then use as the base for any relative file fetch paths.
 *
 * @internal
 */
export function createDryRunner(options: TemplateTesterCreateOptions) {
  return async function dryRun(input: DryRunInput): Promise<DryRunResult> {
    let contentPromise;

    const workflowRunner = new NunjucksWorkflowRunner({
      ...options,
      actionRegistry: new DecoratedActionsRegistry(options.actionRegistry, [
        createTemplateAction({
          id: 'dry-run:extract',
          supportsDryRun: true,
          async handler(ctx) {
            contentPromise = serializeDirectoryContents(ctx.workspacePath);
            await contentPromise.catch(() => {});
          },
        }),
      ]),
    });

    const dryRunId = uuid();
    const log = new Array<{ body: JsonObject }>();
    const contentsPath = resolveSafeChildPath(
      options.workingDirectory,
      `dry-run-content-${dryRunId}`,
    );

    try {
      await deserializeDirectoryContents(contentsPath, input.directoryContents);

      const result = await workflowRunner.execute({
        spec: {
          ...input.spec,
          steps: [
            ...input.spec.steps,
            {
              id: dryRunId,
              name: 'dry-run:extract',
              action: 'dry-run:extract',
            },
          ],
          templateInfo: {
            entityRef: 'template:default/dry-run',
            baseUrl: pathToFileURL(
              resolveSafeChildPath(contentsPath, 'template.yaml'),
            ).toString(),
          },
        },
        secrets: input.secrets,
        // No need to update this at the end of the run, so just hard-code it
        done: false,
        isDryRun: true,
        getWorkspaceName: async () => `dry-run-${dryRunId}`,
        async emitLog(message: string, logMetadata?: JsonObject) {
          if (logMetadata?.stepId === dryRunId) {
            return;
          }
          log.push({
            body: {
              ...logMetadata,
              message,
            },
          });
        },
        async complete() {
          throw new Error('Not implemented');
        },
      });

      if (!contentPromise) {
        throw new Error('Content extraction step was skipped');
      }
      const directoryContents = await contentPromise;

      return {
        log,
        directoryContents,
        output: result.output,
      };
    } finally {
      await fs.remove(contentsPath);
    }
  };
}
Example #12
Source File: configLoader.test.ts    From language-tools with MIT License 4 votes vote down vote up
describe('ConfigLoader', () => {
    function configFrom(path: string) {
        return {
            compilerOptions: {
                dev: true,
                generate: false
            },
            preprocess: pathToFileURL(path).toString()
        };
    }

    function normalizePath(filePath: string): string {
        return path.join(...filePath.split('/'));
    }

    async function assertFindsConfig(
        configLoader: ConfigLoader,
        filePath: string,
        configPath: string
    ) {
        filePath = normalizePath(filePath);
        configPath = normalizePath(configPath);
        assert.deepStrictEqual(configLoader.getConfig(filePath), configFrom(configPath));
        assert.deepStrictEqual(await configLoader.awaitConfig(filePath), configFrom(configPath));
    }

    it('should load all config files below and the one inside/above given directory', async () => {
        const configLoader = new ConfigLoader(
            (() => ['svelte.config.js', 'below/svelte.config.js']) as any,
            { existsSync: () => true },
            path,
            (module: URL) => Promise.resolve({ default: { preprocess: module.toString() } })
        );
        await configLoader.loadConfigs(normalizePath('/some/path'));

        await assertFindsConfig(
            configLoader,
            '/some/path/comp.svelte',
            '/some/path/svelte.config.js'
        );
        await assertFindsConfig(
            configLoader,
            '/some/path/aside/comp.svelte',
            '/some/path/svelte.config.js'
        );
        await assertFindsConfig(
            configLoader,
            '/some/path/below/comp.svelte',
            '/some/path/below/svelte.config.js'
        );
        await assertFindsConfig(
            configLoader,
            '/some/path/below/further/comp.svelte',
            '/some/path/below/svelte.config.js'
        );
    });

    it('finds first above if none found inside/below directory', async () => {
        const configLoader = new ConfigLoader(
            () => [],
            {
                existsSync: (p) =>
                    typeof p === 'string' && p.endsWith(path.join('some', 'svelte.config.js'))
            },
            path,
            (module: URL) => Promise.resolve({ default: { preprocess: module.toString() } })
        );
        await configLoader.loadConfigs(normalizePath('/some/path'));

        await assertFindsConfig(configLoader, '/some/path/comp.svelte', '/some/svelte.config.js');
    });

    it('adds fallback if no config found', async () => {
        const configLoader = new ConfigLoader(
            () => [],
            { existsSync: () => false },
            path,
            (module: URL) => Promise.resolve({ default: { preprocess: module.toString() } })
        );
        await configLoader.loadConfigs(normalizePath('/some/path'));

        assert.deepStrictEqual(
            // Can't do the equal-check directly, instead check if it's the expected object props
            // of svelte-preprocess
            Object.keys(
                configLoader.getConfig(normalizePath('/some/path/comp.svelte'))?.preprocess || {}
            ).sort(),
            ['defaultLanguages', 'markup', 'script', 'style'].sort()
        );
    });

    it('will not load config multiple times if config loading started in parallel', async () => {
        let firstGlobCall = true;
        let nrImportCalls = 0;
        const configLoader = new ConfigLoader(
            (() => {
                if (firstGlobCall) {
                    firstGlobCall = false;
                    return ['svelte.config.js'];
                } else {
                    return [];
                }
            }) as any,
            {
                existsSync: (p) =>
                    typeof p === 'string' &&
                    p.endsWith(path.join('some', 'path', 'svelte.config.js'))
            },
            path,
            (module: URL) => {
                nrImportCalls++;
                return new Promise((resolve) => {
                    setTimeout(() => resolve({ default: { preprocess: module.toString() } }), 500);
                });
            }
        );
        await Promise.all([
            configLoader.loadConfigs(normalizePath('/some/path')),
            configLoader.loadConfigs(normalizePath('/some/path/sub')),
            configLoader.awaitConfig(normalizePath('/some/path/file.svelte'))
        ]);

        await assertFindsConfig(
            configLoader,
            '/some/path/comp.svelte',
            '/some/path/svelte.config.js'
        );
        await assertFindsConfig(
            configLoader,
            '/some/path/sub/comp.svelte',
            '/some/path/svelte.config.js'
        );
        assert.deepStrictEqual(nrImportCalls, 1);
    });

    it('can deal with missing config', () => {
        const configLoader = new ConfigLoader(
            () => [],
            { existsSync: () => false },
            path,
            () => Promise.resolve('unimportant')
        );
        assert.deepStrictEqual(
            configLoader.getConfig(normalizePath('/some/file.svelte')),
            undefined
        );
    });

    it('should await config', async () => {
        const configLoader = new ConfigLoader(
            () => [],
            { existsSync: () => true },
            path,
            (module: URL) => Promise.resolve({ default: { preprocess: module.toString() } })
        );
        assert.deepStrictEqual(
            await configLoader.awaitConfig(normalizePath('some/file.svelte')),
            configFrom(normalizePath('some/svelte.config.js'))
        );
    });

    it('should not load config when disabled', async () => {
        const moduleLoader = spy();
        const configLoader = new ConfigLoader(
            () => [],
            { existsSync: () => true },
            path,
            moduleLoader
        );
        configLoader.setDisabled(true);
        await configLoader.awaitConfig(normalizePath('some/file.svelte'));
        assert.deepStrictEqual(moduleLoader.notCalled, true);
    });
});