path#resolve TypeScript Examples

The following examples show how to use path#resolve. 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: utils.ts    From h1z1-server with GNU General Public License v3.0 7 votes vote down vote up
clearFolderCache = (
  currentFolderDirname: string,
  folderPath: string
) => {
  const resolvedPath = resolve(currentFolderDirname, folderPath);
  Object.keys(require.cache).forEach((key: string) => {
    if (key.includes(resolvedPath)) {
      delete require.cache[key];
    }
  });
}
Example #2
Source File: snapshots-utils.ts    From ui5-language-assistant with Apache License 2.0 7 votes vote down vote up
export function getSnapshotDiagnosticsLSPResponsePath(
  sourcesTestDir: string
): string {
  const snapshotResponsePath = resolve(
    sourcesTestDir,
    OUTPUT_LSP_RESPONSE_FILE_NAME
  );
  return snapshotResponsePath;
}
Example #3
Source File: index.ts    From nestjs-proto-gen-ts with MIT License 6 votes vote down vote up
private resolveRootPath(root: Root): void {
        const paths = this.options.path;
        const length = paths.length;

        // Search include paths when resolving imports
        root.resolvePath = (origin, target) => {
            let resolved = util.path.resolve(util.path.normalize(origin), util.path.normalize(target), false);

            const idx = resolved.lastIndexOf('google/protobuf/');

            if (idx > -1) {
                const altname = resolved.substring(idx);

                if (resolved.match(/google\/protobuf\//g).length > 1) {
                    resolved = resolved.split('google/protobuf')[0] + util.path.normalize(target);
                }

                if (altname in common) {
                    resolved = altname;
                }
            }

            if (existsSync(resolved)) {
                return resolved;
            }

            for (let i = 0; i < length; ++i) {
                const iresolved = util.path.resolve(paths[i] + '/', target);

                if (existsSync(iresolved)) {
                    return iresolved;
                }
            }

            return resolved;
        };
    }
Example #4
Source File: sibling-operations.ts    From graphql-eslint with MIT License 6 votes vote down vote up
handleVirtualPath = (documents: Source[]): Source[] => {
  const filepathMap: Record<string, number> = Object.create(null);

  return documents.map(source => {
    const { location } = source;
    if (['.gql', '.graphql'].some(extension => location.endsWith(extension))) {
      return source;
    }
    filepathMap[location] ??= -1;
    const index = (filepathMap[location] += 1);
    return {
      ...source,
      location: resolve(location, `${index}_document.graphql`),
    };
  });
}
Example #5
Source File: webpack.config.ts    From serverless-SAM-typescript-boilerplate with Apache License 2.0 6 votes vote down vote up
webpackConfig: Configuration = {
  entry: entries,
  target: 'node',
  mode: conf.prodMode ? 'production' : 'development',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    alias: tsPaths,
  },
  output: {
    path: resolve(__dirname, 'dist'),
    filename: '[name].js',
    libraryTarget: 'commonjs2',
  },
  devtool: 'source-map',
  plugins: [],
}
Example #6
Source File: 1631140092497-userCountries.ts    From Corsace with MIT License 6 votes vote down vote up
public async up (queryRunner: QueryRunner): Promise<void> {
        // Old migration code, super slow and doesn't work for restricted users
        if (process.env.NODE_ENV === "production") {
            await queryRunner.query("ALTER TABLE `user` ADD `country` tinytext NOT NULL");

            const users = await User
                .createQueryBuilder("user")
                .getMany();

            await Promise.all(users.map(async user => {
                const apiUser = (await osuClient.user.get(user.osu.userID)) as APIUser;
                user.country = apiUser.country.toString();
                return user.save();
            }));
        } else {
            const bigSql = await streamToString(createReadStream(resolve(__dirname, "1631140092497-userCountries.sql.gz")).pipe(createGunzip()));
            const sqlInstructions = bigSql.split("\n").filter(sql => sql.trim().length !== 0);
            for(const sqlInstruction of sqlInstructions)
                if(sqlInstruction.trim().length !== 0)
                    await queryRunner.query(sqlInstruction);
        }
    }
Example #7
Source File: emailing.ts    From Cromwell with MIT License 6 votes vote down vote up
getEmailTemplate = async (fileName: string, props?: Record<string, any>): Promise<string | undefined> => {
    // User can create his own template and override original 
    const mailUserPath = resolve(getServerTempDir(), 'emails', fileName);
    const serverDir = getServerDir();
    const mailOriginalPath = serverDir ? resolve(serverDir, 'static/emails', fileName) : undefined;

    let emailContent;
    if (await fs.pathExists(mailUserPath)) {
        emailContent = (await fs.readFile(mailUserPath)).toString();
    } else if (mailOriginalPath && await fs.pathExists(mailOriginalPath)) {
        emailContent = (await fs.readFile(mailOriginalPath)).toString();
    }

    if (emailContent) {
        emailContent = Handlebars.compile(emailContent)(props ?? {});
    }

    return emailContent;
}
Example #8
Source File: builder.ts    From nx-plugins with MIT License 6 votes vote down vote up
export function runBuilder(
  options: NxDeployItDeployBuilderSchema,
  context: BuilderContext
): Observable<BuilderOutput> {
  if (!context?.target?.project) {
    return of({ success: false });
  }
  const configuration = context.target.configuration || 'dev';

  const project = getProjectConfig(context);
  const applicationType = getApplicationType(project.architect);

  return from(context.getTargetOptions(context.target)).pipe(
    switchMap((targetOptions: DeployTargetOptions) => {
      const cwd = dirname(
        resolve(context.workspaceRoot, targetOptions.main as string)
      );

      createStackIfNotExist(cwd, configuration, context.target.project);

      const adapter = getAdapterByApplicationType(
        applicationType,
        project,
        options
      );

      return adapter.deploy(
        context,
        cwd,
        options,
        configuration,
        targetOptions
      );
    })
  );
}
Example #9
Source File: webpack.main.config.ts    From angular-electron-admin with Apache License 2.0 6 votes vote down vote up
mainConfig: Configuration = {
  mode: process.env.NODE_ENV as MODE_TYPE,
  target: 'electron-main',
  devtool: 'source-map',
  entry: {
    main: resolve(__dirname, '../../src/main/main.ts')
  },
  output: {
    filename: '[name].js',
    path: resolve(__dirname, '../../dist/main'),
    libraryTarget: 'commonjs',
  },
  externals: [...dependencies],
  node: {
    __dirname: process.env.NODE_ENV !== 'production',
    __filename: process.env.NODE_ENV !== 'production'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              configFile: resolve(__dirname, '../../src/tsconfig.main.json'),
            },
          },
        ],
        exclude: /node_modules/,
      },
    ]
  },
  plugins: [],
  resolve: {
    extensions: ['.ts', '.json', '.js']
  },
}
Example #10
Source File: databaseUtils.ts    From context-mod with MIT License 6 votes vote down vote up
convertSqlJsLocation = (suffix: string, rawConfig: DatabaseConfig, logger: Logger) => {
    if (rawConfig.type === 'sqljs' && typeof rawConfig.location === 'string' && rawConfig.location.trim().toLocaleLowerCase() !== ':memory:' && !rawConfig.location.toLocaleLowerCase().includes(suffix)) {
        const pathInfo = parsePath(rawConfig.location);
        const suffixedFilename = `${pathInfo.name}-${suffix}${pathInfo.ext}`;
        logger.debug(`To prevent web and app databases from overwriting each other (when using sqljs) the database location will be changed to be domain-specific: ${pathInfo.name}${pathInfo.ext} => ${suffixedFilename} -- this may be disabled by including the word '${suffix}' in your original filepath location.`, {leaf: 'Database'});
        return {...rawConfig, location: resolve(pathInfo.dir, suffixedFilename)}
    }
    return rawConfig;
}
Example #11
Source File: index.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
constructor(config: Config) {
    super(config);

    const { cwd, outDir, allFiles } = config;

    this.outDirAbs = resolve(cwd, outDir || DEFAULT_OUT_PATH);

    this.allContracts = allFiles.map((fp) => normalizeName(getFilename(fp)));
  }
Example #12
Source File: GenGenCodeGen.ts    From gengen with MIT License 6 votes vote down vote up
protected copyLibs(settings: IOptions): void {
        const output = settings.output;
        promises.copyFile(resolve(__dirname, '../../libs/types.ts'), `${output}/types.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/Guid.ts'), `${output}/Guid.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/utils.ts'), `${output}/utils.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/mappers.ts'), `${output}/mappers.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/date-converters.ts'), `${output}/date-converters.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/base-http.service.ts'), `${output}/base-http.service.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/download.service.ts'), `${output}/download.service.ts`);
    }
Example #13
Source File: event-store-heroes.module.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
eventStoreSubsystems: IEventStoreSubsystems = {
  subscriptions: {
    persistent: [
      {
        // Event stream category (before the -)
        stream: '$ce-hero',
        group: 'data',
        settingsForCreation: {
          subscriptionSettings: {
            resolveLinkTos: true,
            minCheckpointCount: 1,
          },
        },
        onError: (err: Error) =>
          console.log(`An error occurred : ${err.message}`),
      },
    ],
  },
  projections: [
    {
      name: 'hero-dragon',
      file: resolve(`${__dirname}/projections/hero-dragon.js`),
      mode: 'continuous',
      enabled: true,
      checkPointsEnabled: true,
      emitEnabled: true,
    },
  ],
  onConnectionFail: (err: Error) =>
    console.log(`Connection to Event store hooked : ${err}`),
}
Example #14
Source File: ui5-model.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
// Exported for test purposes
export function getCacheFilePath(
  cacheFolder: string | undefined,
  libName: string
): string | undefined {
  if (cacheFolder === undefined) {
    return undefined;
  }
  return resolve(cacheFolder, libName + ".json");
}
Example #15
Source File: spParser.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
export function parseFile(
  file: string,
  items: FileItems,
  itemsRepository: ItemsRepository,
  searchTokens: boolean,
  IsBuiltIn: boolean
) {
  if (!existsSync(file)) {
    return;
  }
  let data = readFileSync(file, "utf-8");

  // Test for symbolic links
  let match = data.match(/^(?:\.\.\/)+(?:[\/\w\-])+\.\w+/);
  if (match !== null) {
    let folderpath = dirname(file);
    file = resolve(folderpath, match[0]);
    data = readFileSync(file, "utf-8");
  }
  parseText(data, file, items, itemsRepository, searchTokens, IsBuiltIn);
}
Example #16
Source File: cpGHPages.ts    From fzstd with MIT License 5 votes vote down vote up
baseDir = resolve(__dirname, '..')
Example #17
Source File: index.ts    From api-security-audit-action with GNU Affero General Public License v3.0 5 votes vote down vote up
(async () => {
  try {
    const githubServerUrl = env("GITHUB_SERVER_URL");
    const githubRepository = env("GITHUB_REPOSITORY");
    const apiToken = core.getInput("api-token", { required: false });
    const minScore = core.getInput("min-score", { required: true });
    const uploadToCodeScanning = core.getInput("upload-to-code-scanning", {
      required: true,
    });
    const ignoreFailures = core.getInput("ignore-failures", { required: true });
    const userAgent = `GithubAction-CICD/2.0`;
    const platformUrl = core.getInput("platform-url", { required: true });
    const logLevel = core.getInput("log-level", { required: true });
    const rootDirectory = core.getInput("root-directory", { required: false });
    const defaultCollectionName = core.getInput("default-collection-name", {
      required: false,
    });
    const repositoryUrl = `${githubServerUrl}/${githubRepository}`;

    const reference = getReference();
    if (!reference) {
      core.setFailed("Unable to get the branch/tag/PR name");
      return;
    }

    const shareEveryone = getInputValue(
      "share-everyone",
      {
        OFF: undefined,
        READ_ONLY: SharingType.ReadOnly,
        READ_WRITE: SharingType.ReadWrite,
      },
      undefined
    );

    const rootDir = resolve(process.cwd(), rootDirectory || ".");

    const result = await audit({
      rootDir,
      referer: repositoryUrl,
      userAgent,
      apiToken,
      onboardingUrl:
        "https://docs.42crunch.com/latest/content/tasks/integrate_github_actions.htm",
      platformUrl,
      logger: logger(logLevel),
      lineNumbers: uploadToCodeScanning !== "false",
      reference,
      repoName: repositoryUrl,
      cicdName: "github",
      minScore,
      shareEveryone,
      defaultCollectionName,
    });

    if (uploadToCodeScanning !== "false") {
      core.info("Uploading results to Code Scanning");
      const sarif = await produceSarif(result.files);
      await uploadSarif(sarif);
    }

    if (ignoreFailures == "false") {
      if (result!.failures > 0) {
        core.setFailed(`Completed with ${result!.failures} failure(s)`);
      } else if (result.files.size === 0) {
        core.setFailed("No OpenAPI files found");
      }
    } else {
      core.info("Configued to ignore failures");
    }
  } catch (ex) {
    core.setFailed(
      `Error: ${ex.message} ${(ex?.code || "", ex?.response?.body || "")}`
    );
  }
})();
Example #18
Source File: impl.ts    From kassette with MIT License 5 votes vote down vote up
public async init() {
    const { root, tlsCAKeyPath } = this._config;
    const tlsCAFilePath = tlsCAKeyPath ? resolve(root, tlsCAKeyPath) : null;
    if (tlsCAFilePath) {
      try {
        let ca: pki.Certificate | undefined;
        let key: pki.PrivateKey | undefined;
        let extraItems = 0;
        const content = await promises.readFile(tlsCAFilePath, 'utf8');
        for (const object of pem.decode(content)) {
          const isCertificate =
            object.type === 'CERTIFICATE' ||
            object.type === 'X509 CERTIFICATE' ||
            object.type === 'TRUSTED CERTIFICATE';
          const isPrivateKey = object.type === 'PRIVATE KEY' || object.type === 'RSA PRIVATE KEY';
          const body = asn1.fromDer(object.body);
          if (isCertificate && !ca) {
            ca = pki.certificateFromAsn1(body);
          } else if (isPrivateKey && !key) {
            key = pki.privateKeyFromAsn1(body);
          } else {
            extraItems++;
          }
        }
        if (!ca || !key || extraItems > 0) {
          throw new Error(
            `${tlsCAKeyPath} should contain exactly one certificate and one private key.`,
          );
        }
        ca.privateKey = key;
        this._caObject = ca;
        this._caPem = pki.certificateToPem(ca);
      } catch (error) {
        if (error.code !== 'ENOENT') {
          throw error;
        }
      }
    }
    if (!this._caObject) {
      const ca = await createCertificate(['DO NOT TRUST kassette TLS interception certificate'], {
        keySize: this._config.tlsKeySize,
      });
      this._caObject = ca.object;
      this._caPem = ca.cert;
      if (tlsCAFilePath) {
        await promises.writeFile(tlsCAFilePath, `${ca.cert}\n${ca.key}`);
      }
    }
  }
Example #19
Source File: debugDispather.ts    From vscode-autohotkey with MIT License 5 votes vote down vote up
/**
	 * Start executing the given program.
	 */
	public async start(args: LaunchRequestArguments) {

		let { runtime, dbgpSettings = {} } = args;
		const { max_children, max_data } = { max_children: 300, max_data: 131072, ...dbgpSettings };
		if (!runtime) {
			runtime = Global.getConfig(ConfigKey.executePath);
		}

		this.breakPointHandler = new BreakPointHandler();
		this.stackHandler = new StackHandler()
		this.variableHandler = new VariableHandler()
		this.startArgs = args;
		const port = await getPort({ port: getPort.makeRange(9000, 9100) });
		this.debugServer = new DebugServer(port)
		this.commandHandler = new CommandHandler(this.debugServer)
		this.debugServer.start()
			.on("init", () => {
				this.breakPointHandler.loopPoints((bp) => { this.setBreakPonit(bp) })
				this.sendComand(`feature_set -n max_children -v ${max_children}`);
				this.sendComand(`feature_set -n max_data -v ${max_data}`);
				this.sendComand(`feature_set -n max_depth -v 2`); // Get properties recursively. Therefore fixed at 2
				this.sendComand('stdout -c 1')
				this.sendComand('stderr -c 1')
				this.sendComand('run');
			})
			.on("stream", (stream) => {
				this.emit('output', Buffer.from(stream.content, 'base64').toString())
			})
			.on("response", (response: DbgpResponse) => {
				if (response.attr.command) {
					this.commandHandler.callback(response.attr.transaction_id, response)
					switch (response.attr.command) {
						case 'run':
						case 'step_into':
						case 'step_over':
						case 'step_out':
							this.processRunResponse(response);
							break;
						case 'stop':
							this.end();
							break;
					}
				}
			})
		if (!args.program) {
			args.program = await RunnerService.getPathByActive()
		}

		if (!existsSync(runtime)) {
			Out.log(`Autohotkey Execute Bin Not Found : ${runtime}`)
			this.end();
			return;
		}

		const ahkProcess = spawn(runtime, ["/ErrorStdOut", `/debug=localhost:${port}`, args.program], { cwd: `${resolve(args.program, '..')}` })
		ahkProcess.stderr.on("data", err => {
			this.emit('output', err.toString("utf8"))
			this.end()
		})
	}
Example #20
Source File: testkit.ts    From graphql-eslint with MIT License 5 votes vote down vote up
fromMockFile(path: string): string {
    return readFileSync(resolve(__dirname, `../tests/mocks/${path}`), 'utf-8');
  }
Example #21
Source File: webpack.config.ts    From serverless-SAM-typescript-boilerplate with Apache License 2.0 5 votes vote down vote up
tsPaths = Object.keys(compilerOptions.paths).reduce(
  (paths, path) =>
    Object.assign(paths, { [`${path}`]: resolve(__dirname, compilerOptions.paths[path][0]) }),
  {}
)
Example #22
Source File: 1614784355565-MCA2020seeding.ts    From Corsace with MIT License 5 votes vote down vote up
public async up (queryRunner: QueryRunner): Promise<void> {
        const bigSql = await streamToString(createReadStream(resolve(__dirname, "1614784355565-MCA2020seeding.sql.gz")).pipe(createGunzip()));
        const sqlInstructions = bigSql.split("\n").filter(sql => sql.trim().length !== 0);
        for(const sqlInstruction of sqlInstructions)
            if(sqlInstruction.trim().length !== 0)
                await queryRunner.query(sqlInstruction);
    }
Example #23
Source File: create.ts    From Cromwell with MIT License 5 votes vote down vote up
createTask = async (name?: string, noInstall?: boolean, type?: string) => {
  if (!name) {
    console.error('You must provide App name, eg.: npx crw create my-app')
    return;
  }

  const dir = resolve(process.cwd(), name + '');
  await fs.ensureDir(dir);
  await fs.ensureDir(resolve(dir, 'static'));

  if (type === 't') type = 'theme';
  if (type === 'p') type = 'plugin';
  if (type !== 'theme' && type !== 'plugin') type = 'basic';

  if (type === 'basic') {
    await downloader('https://github.com/CromwellCMS/templates/tree/main/basic', dir, { muteLog: true });
  }

  if (type === 'theme') {
    await downloader('https://github.com/CromwellCMS/templates/tree/main/theme', dir, { muteLog: true });
  }

  if (type === 'plugin') {
    await downloader('https://github.com/CromwellCMS/templates/tree/main/plugin', dir, { muteLog: true });
  }

  if (!noInstall) {
    spawnSync(`npm i -g yarn`, [], { shell: true, stdio: 'inherit', cwd: dir });

    if (type === 'theme' || type === 'plugin') {
      spawnSync(`yarn`, [], { shell: true, stdio: 'inherit', cwd: dir });

    } else {
      spawnSync(`yarn add @cromwell/cms @cromwell/theme-store @cromwell/theme-blog @cromwell/plugin-main-menu @cromwell/plugin-newsletter @cromwell/plugin-product-filter @cromwell/plugin-product-showcase @cromwell/plugin-stripe @cromwell/plugin-paypal --exact --non-interactive`
        , [], { shell: true, stdio: 'inherit', cwd: dir });
    }
  }

  if (type === 'theme') {
    console.log(`\n Created Theme boilerplate. Run\x1b[36m cd ${name} && npx cromwell b -w\x1b[0m to start development server`)
  }

  if (type === 'basic') {
    const pckg = await fs.readJSON(resolve(dir, 'package.json'));
    pckg.name = name;
    await fs.outputJSON(resolve(dir, 'package.json'), pckg, { spaces: 2 });

    console.log(`\n Created basic boilerplate. Run\x1b[36m cd ${name} && npx cromwell start\x1b[0m to launch Cromwell CMS`)
  }
}