misc.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import path, { dirname } from 'node:path';
  2. import fs from 'node:fs';
  3. import fsp from 'node:fs/promises';
  4. export const isTruthy = <T>(i: T | 0 | '' | false | null | undefined): i is T => !!i;
  5. export const fastStringArrayJoin = (arr: string[], sep: string) => {
  6. let result = '';
  7. for (let i = 0, len = arr.length; i < len; i++) {
  8. if (i !== 0) {
  9. result += sep;
  10. }
  11. result += arr[i];
  12. }
  13. return result;
  14. };
  15. interface Write {
  16. (
  17. destination: string,
  18. input: NodeJS.TypedArray | string,
  19. ): Promise<unknown>
  20. }
  21. export const writeFile: Write = async (destination: string, input, dir = dirname(destination)) => {
  22. if (!fs.existsSync(dir)) {
  23. await fsp.mkdir(dir, { recursive: true });
  24. }
  25. return fsp.writeFile(destination, input, { encoding: 'utf-8' });
  26. };
  27. export const removeFiles = async (files: string[]) => Promise.all(files.map((file) => fsp.rm(file, { force: true })));
  28. export const domainWildCardToRegex = (domain: string) => {
  29. let result = '^';
  30. for (let i = 0, len = domain.length; i < len; i++) {
  31. switch (domain[i]) {
  32. case '.':
  33. result += String.raw`\.`;
  34. break;
  35. case '*':
  36. result += '[a-zA-Z0-9-_.]*?';
  37. break;
  38. case '?':
  39. result += '[a-zA-Z0-9-_.]';
  40. break;
  41. default:
  42. result += domain[i];
  43. }
  44. }
  45. result += '$';
  46. return result;
  47. };
  48. const OUTPUT_SURGE_DIR = path.resolve(__dirname, '../../List');
  49. const OUTPUT_CLASH_DIR = path.resolve(__dirname, '../../Clash');
  50. const OUTPUT_SINGBOX_DIR = path.resolve(__dirname, '../../sing-box');
  51. export const output = (id: string, type: 'non_ip' | 'ip' | 'domainset') => {
  52. return [
  53. path.join(OUTPUT_SURGE_DIR, type, id + '.conf'),
  54. path.join(OUTPUT_CLASH_DIR, type, id + '.txt'),
  55. path.join(OUTPUT_SINGBOX_DIR, type, id + '.json')
  56. ] as const;
  57. };