@willbooster/shared-lib-node 7.0.3 → 7.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/env.cjs +1 -1
- package/dist/env.cjs.map +1 -1
- package/dist/env.js +1 -1
- package/dist/env.js.map +1 -1
- package/dist/hash.cjs +1 -1
- package/dist/hash.cjs.map +1 -1
- package/dist/hash.js +1 -1
- package/dist/hash.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.js +1 -1
- package/dist/spawn.cjs.map +1 -1
- package/dist/spawn.d.ts +1 -1
- package/dist/spawn.js.map +1 -1
- package/package.json +12 -12
- package/dist/glob.cjs +0 -2
- package/dist/glob.cjs.map +0 -1
- package/dist/glob.d.ts +0 -38
- package/dist/glob.js +0 -2
- package/dist/glob.js.map +0 -1
package/dist/env.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("node:fs"),n=require("node:path"),o=require("dotenv");function t(o,t){let r=(o.env??[]).map(e=>n.resolve(t,e.toString()));const i=o.cascadeEnv??(o.cascadeNodeEnv?process.env.NODE_ENV||"development":o.autoCascadeEnv?process.env.WB_ENV||process.env.NODE_ENV||"development":void 0);if("string"==typeof i){if(0===r.length&&(r.push(n.join(t,".env")),o.includeRootEnv)){const o=n.resolve(t,"..","..");e.existsSync(n.join(o,"package.json"))&&r.push(n.join(o,".env"))}r=r.flatMap(e=>i?[`${e}.${i}.local`,`${e}.local`,`${e}.${i}`,e]:[`${e}.local`,e])}r=r.filter(n=>e.existsSync(n)).map(e=>n.relative(t,e)),o.verbose&&(console.info(`WB_ENV: ${process.env.WB_ENV}, NODE_ENV: ${process.env.NODE_ENV}`),console.info("Reading env files:",r.join(", ")));const a=[],c={};for(const e of r){let r=0;for(const[o,i]of Object.entries(s(n.join(t,e))))o in c||(c[o]=i,r++);a.push([e,r]),o.verbose&&r>0&&console.info(`Read ${r} environment variables from ${e}`)}if(o.checkEnv){const e=Object.keys(s(n.join(t,o.checkEnv))
|
|
1
|
+
"use strict";var e=require("node:fs"),n=require("node:path"),o=require("dotenv");function t(o,t){let r=(o.env??[]).map(e=>n.resolve(t,e.toString()));const i=o.cascadeEnv??(o.cascadeNodeEnv?process.env.NODE_ENV||"development":o.autoCascadeEnv?process.env.WB_ENV||process.env.NODE_ENV||"development":void 0);if("string"==typeof i){if(0===r.length&&(r.push(n.join(t,".env")),o.includeRootEnv)){const o=n.resolve(t,"..","..");e.existsSync(n.join(o,"package.json"))&&r.push(n.join(o,".env"))}r=r.flatMap(e=>i?[`${e}.${i}.local`,`${e}.local`,`${e}.${i}`,e]:[`${e}.local`,e])}r=r.filter(n=>e.existsSync(n)).map(e=>n.relative(t,e)),o.verbose&&(console.info(`WB_ENV: ${process.env.WB_ENV}, NODE_ENV: ${process.env.NODE_ENV}`),console.info("Reading env files:",r.join(", ")));const a=[],c={};for(const e of r){let r=0;for(const[o,i]of Object.entries(s(n.join(t,e))))o in c||(c[o]=i,r++);a.push([e,r]),o.verbose&&r>0&&console.info(`Read ${r} environment variables from ${e}`)}if(o.checkEnv){const e=Object.keys(s(n.join(t,o.checkEnv))).filter(e=>!(e in c));if(e.length>0)throw new Error(`Missing environment variables in [${r.join(", ")}]: [${e.join(", ")}]`)}return[c,a]}const r=new Map;function s(e){const t=r.get(e);if(t)return t;const s=o.config({path:n.resolve(e),processEnv:{}}).parsed??{};return r.set(e,s),s}exports.readAndApplyEnvironmentVariables=function(e,n){const[o]=t(e,n);return Object.assign(process.env,o),o},exports.readEnvironmentVariables=t,exports.removeNpmAndYarnEnvironmentVariables=function(e){e.PATH&&e.BERRY_BIN_FOLDER&&(e.PATH=e.PATH.replace(`${e.BERRY_BIN_FOLDER}:`,"").replaceAll(/\/private\/var\/folders\/[^:]+:/g,"").replaceAll(/\/var\/tmp\/[^:]+:/g,"").replaceAll(/\/tmp\/[^:]+:/g,""));for(const n of Object.keys(e)){const o=n.toUpperCase();(o.startsWith("NPM_")||o.startsWith("YARN_")||o.startsWith("BERRY_")||"PROJECT_CWD"===o||"INIT_CWD"===o)&&delete e[n]}},exports.yargsOptionsBuilderForEnv={env:{description:".env files to be loaded.",type:"array"},"cascade-env":{description:"Environment to load cascading .env files (e.g., `.env`, `.env.<environment>`, `.env.local` and `.env.<environment>.local`). Preferred over `cascade-node-env` and `auto-cascade-env`.",type:"string"},"cascade-node-env":{description:'Same with --cascade-env=<NODE_ENV || "development">. Preferred over `auto-cascade-env`.',type:"boolean"},"auto-cascade-env":{description:'Same with --cascade-env=<WB_ENV || NODE_ENV || "development">.',type:"boolean",default:!0},"include-root-env":{description:"Include .env files in root directory if the project is in a monorepo and --env option is not used.",type:"boolean",default:!0},"check-env":{description:"Check whether the keys of the loaded .env files are same with the given .env file.",type:"string",default:".env.example"},verbose:{description:"Whether to show verbose information",type:"boolean",alias:"v"}};
|
|
2
2
|
//# sourceMappingURL=env.cjs.map
|
package/dist/env.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env.cjs","sources":["../src/env.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { config } from 'dotenv';\nimport type { ArgumentsCamelCase, InferredOptionTypes } from 'yargs';\n\nexport const yargsOptionsBuilderForEnv = {\n env: {\n description: '.env files to be loaded.',\n type: 'array',\n },\n 'cascade-env': {\n description:\n 'Environment to load cascading .env files (e.g., `.env`, `.env.<environment>`, `.env.local` and `.env.<environment>.local`). Preferred over `cascade-node-env` and `auto-cascade-env`.',\n type: 'string',\n },\n 'cascade-node-env': {\n description: 'Same with --cascade-env=<NODE_ENV || \"development\">. Preferred over `auto-cascade-env`.',\n type: 'boolean',\n },\n 'auto-cascade-env': {\n description: 'Same with --cascade-env=<WB_ENV || NODE_ENV || \"development\">.',\n type: 'boolean',\n default: true,\n },\n 'include-root-env': {\n description: 'Include .env files in root directory if the project is in a monorepo and --env option is not used.',\n type: 'boolean',\n default: true,\n },\n 'check-env': {\n description: 'Check whether the keys of the loaded .env files are same with the given .env file.',\n type: 'string',\n default: '.env.example',\n },\n verbose: {\n description: 'Whether to show verbose information',\n type: 'boolean',\n alias: 'v',\n },\n} as const;\n\nexport type EnvReaderOptions = Partial<ArgumentsCamelCase<InferredOptionTypes<typeof yargsOptionsBuilderForEnv>>>;\n\n/**\n * This function reads environment variables from `.env` files.\n * Note it does not assign them in `process.env`.\n * @return [envVars, [envPaths, envVarCount][]]\n * */\nexport function readEnvironmentVariables(\n argv: EnvReaderOptions,\n cwd: string\n): [Record<string, string>, [string, number][]] {\n let envPaths = (argv.env ?? []).map((envPath) => path.resolve(cwd, envPath.toString()));\n const cascade =\n argv.cascadeEnv ??\n (argv.cascadeNodeEnv\n ? process.env.NODE_ENV || 'development'\n : argv.autoCascadeEnv\n ? process.env.WB_ENV || process.env.NODE_ENV || 'development'\n : undefined);\n if (typeof cascade === 'string') {\n if (envPaths.length === 0) {\n envPaths.push(path.join(cwd, '.env'));\n if (argv.includeRootEnv) {\n const rootPath = path.resolve(cwd, '..', '..');\n if (fs.existsSync(path.join(rootPath, 'package.json'))) {\n envPaths.push(path.join(rootPath, '.env'));\n }\n }\n }\n envPaths = envPaths.flatMap((envPath) =>\n cascade\n ? [`${envPath}.${cascade}.local`, `${envPath}.local`, `${envPath}.${cascade}`, envPath]\n : [`${envPath}.local`, envPath]\n );\n }\n envPaths = envPaths.filter((envPath) => fs.existsSync(envPath)).map((envPath) => path.relative(cwd, envPath));\n if (argv.verbose) {\n console.info(`WB_ENV: ${process.env.WB_ENV}, NODE_ENV: ${process.env.NODE_ENV}`);\n console.info('Reading env files:', envPaths.join(', '));\n }\n\n const envPathAndEnvVarCountPairs: [string, number][] = [];\n const envVars: Record<string, string> = {};\n for (const envPath of envPaths) {\n let count = 0;\n for (const [key, value] of Object.entries(readEnvFile(path.join(cwd, envPath)))) {\n if (!(key in envVars)) {\n envVars[key] = value;\n count++;\n }\n }\n envPathAndEnvVarCountPairs.push([envPath, count]);\n if (argv.verbose && count > 0) {\n console.info(`Read ${count} environment variables from ${envPath}`);\n }\n }\n\n if (argv.checkEnv) {\n const exampleKeys = Object.keys(readEnvFile(path.join(cwd, argv.checkEnv))
|
|
1
|
+
{"version":3,"file":"env.cjs","sources":["../src/env.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { config } from 'dotenv';\nimport type { ArgumentsCamelCase, InferredOptionTypes } from 'yargs';\n\nexport const yargsOptionsBuilderForEnv = {\n env: {\n description: '.env files to be loaded.',\n type: 'array',\n },\n 'cascade-env': {\n description:\n 'Environment to load cascading .env files (e.g., `.env`, `.env.<environment>`, `.env.local` and `.env.<environment>.local`). Preferred over `cascade-node-env` and `auto-cascade-env`.',\n type: 'string',\n },\n 'cascade-node-env': {\n description: 'Same with --cascade-env=<NODE_ENV || \"development\">. Preferred over `auto-cascade-env`.',\n type: 'boolean',\n },\n 'auto-cascade-env': {\n description: 'Same with --cascade-env=<WB_ENV || NODE_ENV || \"development\">.',\n type: 'boolean',\n default: true,\n },\n 'include-root-env': {\n description: 'Include .env files in root directory if the project is in a monorepo and --env option is not used.',\n type: 'boolean',\n default: true,\n },\n 'check-env': {\n description: 'Check whether the keys of the loaded .env files are same with the given .env file.',\n type: 'string',\n default: '.env.example',\n },\n verbose: {\n description: 'Whether to show verbose information',\n type: 'boolean',\n alias: 'v',\n },\n} as const;\n\nexport type EnvReaderOptions = Partial<ArgumentsCamelCase<InferredOptionTypes<typeof yargsOptionsBuilderForEnv>>>;\n\n/**\n * This function reads environment variables from `.env` files.\n * Note it does not assign them in `process.env`.\n * @return [envVars, [envPaths, envVarCount][]]\n * */\nexport function readEnvironmentVariables(\n argv: EnvReaderOptions,\n cwd: string\n): [Record<string, string>, [string, number][]] {\n let envPaths = (argv.env ?? []).map((envPath) => path.resolve(cwd, envPath.toString()));\n const cascade =\n argv.cascadeEnv ??\n (argv.cascadeNodeEnv\n ? process.env.NODE_ENV || 'development'\n : argv.autoCascadeEnv\n ? process.env.WB_ENV || process.env.NODE_ENV || 'development'\n : undefined);\n if (typeof cascade === 'string') {\n if (envPaths.length === 0) {\n envPaths.push(path.join(cwd, '.env'));\n if (argv.includeRootEnv) {\n const rootPath = path.resolve(cwd, '..', '..');\n if (fs.existsSync(path.join(rootPath, 'package.json'))) {\n envPaths.push(path.join(rootPath, '.env'));\n }\n }\n }\n envPaths = envPaths.flatMap((envPath) =>\n cascade\n ? [`${envPath}.${cascade}.local`, `${envPath}.local`, `${envPath}.${cascade}`, envPath]\n : [`${envPath}.local`, envPath]\n );\n }\n envPaths = envPaths.filter((envPath) => fs.existsSync(envPath)).map((envPath) => path.relative(cwd, envPath));\n if (argv.verbose) {\n console.info(`WB_ENV: ${process.env.WB_ENV}, NODE_ENV: ${process.env.NODE_ENV}`);\n console.info('Reading env files:', envPaths.join(', '));\n }\n\n const envPathAndEnvVarCountPairs: [string, number][] = [];\n const envVars: Record<string, string> = {};\n for (const envPath of envPaths) {\n let count = 0;\n for (const [key, value] of Object.entries(readEnvFile(path.join(cwd, envPath)))) {\n if (!(key in envVars)) {\n envVars[key] = value;\n count++;\n }\n }\n envPathAndEnvVarCountPairs.push([envPath, count]);\n if (argv.verbose && count > 0) {\n console.info(`Read ${count} environment variables from ${envPath}`);\n }\n }\n\n if (argv.checkEnv) {\n const exampleKeys = Object.keys(readEnvFile(path.join(cwd, argv.checkEnv)));\n const missingKeys = exampleKeys.filter((key) => !(key in envVars));\n if (missingKeys.length > 0) {\n throw new Error(`Missing environment variables in [${envPaths.join(', ')}]: [${missingKeys.join(', ')}]`);\n }\n }\n return [envVars, envPathAndEnvVarCountPairs];\n}\n\n/**\n * This function read environment variables from `.env` files and assign them in `process.env`.\n * */\nexport function readAndApplyEnvironmentVariables(\n argv: EnvReaderOptions,\n cwd: string\n): Record<string, string | undefined> {\n const [envVars] = readEnvironmentVariables(argv, cwd);\n Object.assign(process.env, envVars);\n return envVars;\n}\n\nconst cachedEnvVars = new Map<string, Record<string, string>>();\n\nfunction readEnvFile(filePath: string): Record<string, string> {\n const cached = cachedEnvVars.get(filePath);\n if (cached) return cached;\n\n const parsed = config({ path: path.resolve(filePath), processEnv: {} }).parsed ?? {};\n cachedEnvVars.set(filePath, parsed);\n return parsed;\n}\n\n/**\n * This function removes environment variables related to npm and yarn from the given environment variables.\n * */\nexport function removeNpmAndYarnEnvironmentVariables(envVars: Record<string, string | undefined>): void {\n // Remove npm & yarn environment variables from process.env\n if (envVars.PATH && envVars.BERRY_BIN_FOLDER) {\n envVars.PATH = envVars.PATH.replace(`${envVars.BERRY_BIN_FOLDER}:`, '')\n // Temporary directory in macOS\n .replaceAll(/\\/private\\/var\\/folders\\/[^:]+:/g, '')\n // Temporary directories in Linux\n .replaceAll(/\\/var\\/tmp\\/[^:]+:/g, '')\n .replaceAll(/\\/tmp\\/[^:]+:/g, '');\n }\n for (const key of Object.keys(envVars)) {\n const upperKey = key.toUpperCase();\n if (\n upperKey.startsWith('NPM_') ||\n upperKey.startsWith('YARN_') ||\n upperKey.startsWith('BERRY_') ||\n upperKey === 'PROJECT_CWD' ||\n upperKey === 'INIT_CWD'\n ) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete envVars[key];\n }\n }\n}\n"],"names":["readEnvironmentVariables","argv","cwd","envPaths","env","map","envPath","path","resolve","toString","cascade","cascadeEnv","cascadeNodeEnv","process","NODE_ENV","autoCascadeEnv","WB_ENV","undefined","length","push","join","includeRootEnv","rootPath","fs","existsSync","flatMap","filter","relative","verbose","console","info","envPathAndEnvVarCountPairs","envVars","count","key","value","Object","entries","readEnvFile","checkEnv","missingKeys","keys","Error","cachedEnvVars","Map","filePath","cached","get","parsed","config","processEnv","set","assign","PATH","BERRY_BIN_FOLDER","replace","replaceAll","upperKey","toUpperCase","startsWith","description","type","default","alias"],"mappings":"iFAiDO,SAASA,EACdC,EACAC,GAEA,IAAIC,GAAYF,EAAKG,KAAO,IAAIC,IAAKC,GAAYC,EAAKC,QAAQN,EAAKI,EAAQG,aAC3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ACNE,MAAO"}
|
package/dist/env.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"node:fs";import n from"node:path";import{config as o}from"dotenv";const t={env:{description:".env files to be loaded.",type:"array"},"cascade-env":{description:"Environment to load cascading .env files (e.g., `.env`, `.env.<environment>`, `.env.local` and `.env.<environment>.local`). Preferred over `cascade-node-env` and `auto-cascade-env`.",type:"string"},"cascade-node-env":{description:'Same with --cascade-env=<NODE_ENV || "development">. Preferred over `auto-cascade-env`.',type:"boolean"},"auto-cascade-env":{description:'Same with --cascade-env=<WB_ENV || NODE_ENV || "development">.',type:"boolean",default:!0},"include-root-env":{description:"Include .env files in root directory if the project is in a monorepo and --env option is not used.",type:"boolean",default:!0},"check-env":{description:"Check whether the keys of the loaded .env files are same with the given .env file.",type:"string",default:".env.example"},verbose:{description:"Whether to show verbose information",type:"boolean",alias:"v"}};function s(o,t){let s=(o.env??[]).map(e=>n.resolve(t,e.toString()));const r=o.cascadeEnv??(o.cascadeNodeEnv?process.env.NODE_ENV||"development":o.autoCascadeEnv?process.env.WB_ENV||process.env.NODE_ENV||"development":void 0);if("string"==typeof r){if(0===s.length&&(s.push(n.join(t,".env")),o.includeRootEnv)){const o=n.resolve(t,"..","..");e.existsSync(n.join(o,"package.json"))&&s.push(n.join(o,".env"))}s=s.flatMap(e=>r?[`${e}.${r}.local`,`${e}.local`,`${e}.${r}`,e]:[`${e}.local`,e])}s=s.filter(n=>e.existsSync(n)).map(e=>n.relative(t,e)),o.verbose&&(console.info(`WB_ENV: ${process.env.WB_ENV}, NODE_ENV: ${process.env.NODE_ENV}`),console.info("Reading env files:",s.join(", ")));const i=[],c={};for(const e of s){let s=0;for(const[o,r]of Object.entries(a(n.join(t,e))))o in c||(c[o]=r,s++);i.push([e,s]),o.verbose&&s>0&&console.info(`Read ${s} environment variables from ${e}`)}if(o.checkEnv){const e=Object.keys(a(n.join(t,o.checkEnv))
|
|
1
|
+
import e from"node:fs";import n from"node:path";import{config as o}from"dotenv";const t={env:{description:".env files to be loaded.",type:"array"},"cascade-env":{description:"Environment to load cascading .env files (e.g., `.env`, `.env.<environment>`, `.env.local` and `.env.<environment>.local`). Preferred over `cascade-node-env` and `auto-cascade-env`.",type:"string"},"cascade-node-env":{description:'Same with --cascade-env=<NODE_ENV || "development">. Preferred over `auto-cascade-env`.',type:"boolean"},"auto-cascade-env":{description:'Same with --cascade-env=<WB_ENV || NODE_ENV || "development">.',type:"boolean",default:!0},"include-root-env":{description:"Include .env files in root directory if the project is in a monorepo and --env option is not used.",type:"boolean",default:!0},"check-env":{description:"Check whether the keys of the loaded .env files are same with the given .env file.",type:"string",default:".env.example"},verbose:{description:"Whether to show verbose information",type:"boolean",alias:"v"}};function s(o,t){let s=(o.env??[]).map(e=>n.resolve(t,e.toString()));const r=o.cascadeEnv??(o.cascadeNodeEnv?process.env.NODE_ENV||"development":o.autoCascadeEnv?process.env.WB_ENV||process.env.NODE_ENV||"development":void 0);if("string"==typeof r){if(0===s.length&&(s.push(n.join(t,".env")),o.includeRootEnv)){const o=n.resolve(t,"..","..");e.existsSync(n.join(o,"package.json"))&&s.push(n.join(o,".env"))}s=s.flatMap(e=>r?[`${e}.${r}.local`,`${e}.local`,`${e}.${r}`,e]:[`${e}.local`,e])}s=s.filter(n=>e.existsSync(n)).map(e=>n.relative(t,e)),o.verbose&&(console.info(`WB_ENV: ${process.env.WB_ENV}, NODE_ENV: ${process.env.NODE_ENV}`),console.info("Reading env files:",s.join(", ")));const i=[],c={};for(const e of s){let s=0;for(const[o,r]of Object.entries(a(n.join(t,e))))o in c||(c[o]=r,s++);i.push([e,s]),o.verbose&&s>0&&console.info(`Read ${s} environment variables from ${e}`)}if(o.checkEnv){const e=Object.keys(a(n.join(t,o.checkEnv))).filter(e=>!(e in c));if(e.length>0)throw new Error(`Missing environment variables in [${s.join(", ")}]: [${e.join(", ")}]`)}return[c,i]}function r(e,n){const[o]=s(e,n);return Object.assign(process.env,o),o}const i=new Map;function a(e){const t=i.get(e);if(t)return t;const s=o({path:n.resolve(e),processEnv:{}}).parsed??{};return i.set(e,s),s}function c(e){e.PATH&&e.BERRY_BIN_FOLDER&&(e.PATH=e.PATH.replace(`${e.BERRY_BIN_FOLDER}:`,"").replaceAll(/\/private\/var\/folders\/[^:]+:/g,"").replaceAll(/\/var\/tmp\/[^:]+:/g,"").replaceAll(/\/tmp\/[^:]+:/g,""));for(const n of Object.keys(e)){const o=n.toUpperCase();(o.startsWith("NPM_")||o.startsWith("YARN_")||o.startsWith("BERRY_")||"PROJECT_CWD"===o||"INIT_CWD"===o)&&delete e[n]}}export{r as readAndApplyEnvironmentVariables,s as readEnvironmentVariables,c as removeNpmAndYarnEnvironmentVariables,t as yargsOptionsBuilderForEnv};
|
|
2
2
|
//# sourceMappingURL=env.js.map
|
package/dist/env.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env.js","sources":["../src/env.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { config } from 'dotenv';\nimport type { ArgumentsCamelCase, InferredOptionTypes } from 'yargs';\n\nexport const yargsOptionsBuilderForEnv = {\n env: {\n description: '.env files to be loaded.',\n type: 'array',\n },\n 'cascade-env': {\n description:\n 'Environment to load cascading .env files (e.g., `.env`, `.env.<environment>`, `.env.local` and `.env.<environment>.local`). Preferred over `cascade-node-env` and `auto-cascade-env`.',\n type: 'string',\n },\n 'cascade-node-env': {\n description: 'Same with --cascade-env=<NODE_ENV || \"development\">. Preferred over `auto-cascade-env`.',\n type: 'boolean',\n },\n 'auto-cascade-env': {\n description: 'Same with --cascade-env=<WB_ENV || NODE_ENV || \"development\">.',\n type: 'boolean',\n default: true,\n },\n 'include-root-env': {\n description: 'Include .env files in root directory if the project is in a monorepo and --env option is not used.',\n type: 'boolean',\n default: true,\n },\n 'check-env': {\n description: 'Check whether the keys of the loaded .env files are same with the given .env file.',\n type: 'string',\n default: '.env.example',\n },\n verbose: {\n description: 'Whether to show verbose information',\n type: 'boolean',\n alias: 'v',\n },\n} as const;\n\nexport type EnvReaderOptions = Partial<ArgumentsCamelCase<InferredOptionTypes<typeof yargsOptionsBuilderForEnv>>>;\n\n/**\n * This function reads environment variables from `.env` files.\n * Note it does not assign them in `process.env`.\n * @return [envVars, [envPaths, envVarCount][]]\n * */\nexport function readEnvironmentVariables(\n argv: EnvReaderOptions,\n cwd: string\n): [Record<string, string>, [string, number][]] {\n let envPaths = (argv.env ?? []).map((envPath) => path.resolve(cwd, envPath.toString()));\n const cascade =\n argv.cascadeEnv ??\n (argv.cascadeNodeEnv\n ? process.env.NODE_ENV || 'development'\n : argv.autoCascadeEnv\n ? process.env.WB_ENV || process.env.NODE_ENV || 'development'\n : undefined);\n if (typeof cascade === 'string') {\n if (envPaths.length === 0) {\n envPaths.push(path.join(cwd, '.env'));\n if (argv.includeRootEnv) {\n const rootPath = path.resolve(cwd, '..', '..');\n if (fs.existsSync(path.join(rootPath, 'package.json'))) {\n envPaths.push(path.join(rootPath, '.env'));\n }\n }\n }\n envPaths = envPaths.flatMap((envPath) =>\n cascade\n ? [`${envPath}.${cascade}.local`, `${envPath}.local`, `${envPath}.${cascade}`, envPath]\n : [`${envPath}.local`, envPath]\n );\n }\n envPaths = envPaths.filter((envPath) => fs.existsSync(envPath)).map((envPath) => path.relative(cwd, envPath));\n if (argv.verbose) {\n console.info(`WB_ENV: ${process.env.WB_ENV}, NODE_ENV: ${process.env.NODE_ENV}`);\n console.info('Reading env files:', envPaths.join(', '));\n }\n\n const envPathAndEnvVarCountPairs: [string, number][] = [];\n const envVars: Record<string, string> = {};\n for (const envPath of envPaths) {\n let count = 0;\n for (const [key, value] of Object.entries(readEnvFile(path.join(cwd, envPath)))) {\n if (!(key in envVars)) {\n envVars[key] = value;\n count++;\n }\n }\n envPathAndEnvVarCountPairs.push([envPath, count]);\n if (argv.verbose && count > 0) {\n console.info(`Read ${count} environment variables from ${envPath}`);\n }\n }\n\n if (argv.checkEnv) {\n const exampleKeys = Object.keys(readEnvFile(path.join(cwd, argv.checkEnv))
|
|
1
|
+
{"version":3,"file":"env.js","sources":["../src/env.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { config } from 'dotenv';\nimport type { ArgumentsCamelCase, InferredOptionTypes } from 'yargs';\n\nexport const yargsOptionsBuilderForEnv = {\n env: {\n description: '.env files to be loaded.',\n type: 'array',\n },\n 'cascade-env': {\n description:\n 'Environment to load cascading .env files (e.g., `.env`, `.env.<environment>`, `.env.local` and `.env.<environment>.local`). Preferred over `cascade-node-env` and `auto-cascade-env`.',\n type: 'string',\n },\n 'cascade-node-env': {\n description: 'Same with --cascade-env=<NODE_ENV || \"development\">. Preferred over `auto-cascade-env`.',\n type: 'boolean',\n },\n 'auto-cascade-env': {\n description: 'Same with --cascade-env=<WB_ENV || NODE_ENV || \"development\">.',\n type: 'boolean',\n default: true,\n },\n 'include-root-env': {\n description: 'Include .env files in root directory if the project is in a monorepo and --env option is not used.',\n type: 'boolean',\n default: true,\n },\n 'check-env': {\n description: 'Check whether the keys of the loaded .env files are same with the given .env file.',\n type: 'string',\n default: '.env.example',\n },\n verbose: {\n description: 'Whether to show verbose information',\n type: 'boolean',\n alias: 'v',\n },\n} as const;\n\nexport type EnvReaderOptions = Partial<ArgumentsCamelCase<InferredOptionTypes<typeof yargsOptionsBuilderForEnv>>>;\n\n/**\n * This function reads environment variables from `.env` files.\n * Note it does not assign them in `process.env`.\n * @return [envVars, [envPaths, envVarCount][]]\n * */\nexport function readEnvironmentVariables(\n argv: EnvReaderOptions,\n cwd: string\n): [Record<string, string>, [string, number][]] {\n let envPaths = (argv.env ?? []).map((envPath) => path.resolve(cwd, envPath.toString()));\n const cascade =\n argv.cascadeEnv ??\n (argv.cascadeNodeEnv\n ? process.env.NODE_ENV || 'development'\n : argv.autoCascadeEnv\n ? process.env.WB_ENV || process.env.NODE_ENV || 'development'\n : undefined);\n if (typeof cascade === 'string') {\n if (envPaths.length === 0) {\n envPaths.push(path.join(cwd, '.env'));\n if (argv.includeRootEnv) {\n const rootPath = path.resolve(cwd, '..', '..');\n if (fs.existsSync(path.join(rootPath, 'package.json'))) {\n envPaths.push(path.join(rootPath, '.env'));\n }\n }\n }\n envPaths = envPaths.flatMap((envPath) =>\n cascade\n ? [`${envPath}.${cascade}.local`, `${envPath}.local`, `${envPath}.${cascade}`, envPath]\n : [`${envPath}.local`, envPath]\n );\n }\n envPaths = envPaths.filter((envPath) => fs.existsSync(envPath)).map((envPath) => path.relative(cwd, envPath));\n if (argv.verbose) {\n console.info(`WB_ENV: ${process.env.WB_ENV}, NODE_ENV: ${process.env.NODE_ENV}`);\n console.info('Reading env files:', envPaths.join(', '));\n }\n\n const envPathAndEnvVarCountPairs: [string, number][] = [];\n const envVars: Record<string, string> = {};\n for (const envPath of envPaths) {\n let count = 0;\n for (const [key, value] of Object.entries(readEnvFile(path.join(cwd, envPath)))) {\n if (!(key in envVars)) {\n envVars[key] = value;\n count++;\n }\n }\n envPathAndEnvVarCountPairs.push([envPath, count]);\n if (argv.verbose && count > 0) {\n console.info(`Read ${count} environment variables from ${envPath}`);\n }\n }\n\n if (argv.checkEnv) {\n const exampleKeys = Object.keys(readEnvFile(path.join(cwd, argv.checkEnv)));\n const missingKeys = exampleKeys.filter((key) => !(key in envVars));\n if (missingKeys.length > 0) {\n throw new Error(`Missing environment variables in [${envPaths.join(', ')}]: [${missingKeys.join(', ')}]`);\n }\n }\n return [envVars, envPathAndEnvVarCountPairs];\n}\n\n/**\n * This function read environment variables from `.env` files and assign them in `process.env`.\n * */\nexport function readAndApplyEnvironmentVariables(\n argv: EnvReaderOptions,\n cwd: string\n): Record<string, string | undefined> {\n const [envVars] = readEnvironmentVariables(argv, cwd);\n Object.assign(process.env, envVars);\n return envVars;\n}\n\nconst cachedEnvVars = new Map<string, Record<string, string>>();\n\nfunction readEnvFile(filePath: string): Record<string, string> {\n const cached = cachedEnvVars.get(filePath);\n if (cached) return cached;\n\n const parsed = config({ path: path.resolve(filePath), processEnv: {} }).parsed ?? {};\n cachedEnvVars.set(filePath, parsed);\n return parsed;\n}\n\n/**\n * This function removes environment variables related to npm and yarn from the given environment variables.\n * */\nexport function removeNpmAndYarnEnvironmentVariables(envVars: Record<string, string | undefined>): void {\n // Remove npm & yarn environment variables from process.env\n if (envVars.PATH && envVars.BERRY_BIN_FOLDER) {\n envVars.PATH = envVars.PATH.replace(`${envVars.BERRY_BIN_FOLDER}:`, '')\n // Temporary directory in macOS\n .replaceAll(/\\/private\\/var\\/folders\\/[^:]+:/g, '')\n // Temporary directories in Linux\n .replaceAll(/\\/var\\/tmp\\/[^:]+:/g, '')\n .replaceAll(/\\/tmp\\/[^:]+:/g, '');\n }\n for (const key of Object.keys(envVars)) {\n const upperKey = key.toUpperCase();\n if (\n upperKey.startsWith('NPM_') ||\n upperKey.startsWith('YARN_') ||\n upperKey.startsWith('BERRY_') ||\n upperKey === 'PROJECT_CWD' ||\n upperKey === 'INIT_CWD'\n ) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete envVars[key];\n }\n }\n}\n"],"names":["yargsOptionsBuilderForEnv","env","description","type","default","verbose","alias","readEnvironmentVariables","argv","cwd","envPaths","map","envPath","path","resolve","toString","cascade","cascadeEnv","cascadeNodeEnv","process","NODE_ENV","autoCascadeEnv","WB_ENV","undefined","length","push","join","includeRootEnv","rootPath","fs","existsSync","flatMap","filter","relative","console","info","envPathAndEnvVarCountPairs","envVars","count","key","value","Object","entries","readEnvFile","checkEnv","missingKeys","keys","Error","readAndApplyEnvironmentVariables","assign","cachedEnvVars","Map","filePath","cached","get","parsed","config","processEnv","set","removeNpmAndYarnEnvironmentVariables","PATH","BERRY_BIN_FOLDER","replace","replaceAll","upperKey","toUpperCase","startsWith"],"mappings":"gFAMO,MAAMA,EAA4B,CACvCC,IAAK,CACHC,YAAa,2BACbC,KAAM,SAER,cAAe,CACbD,YACE,wLACFC,KAAM,UAER,mBAAoB,CAClBD,YAAa,0FACbC,KAAM,WAER,mBAAoB,CAClBD,YAAa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s
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("node:crypto"),r=require("node:fs"),t=require("node:path");async function s(e,...s){let i="";try{i=await r.promises.readFile(e,"utf8")}catch{}const o=await a(...s);return i!==o&&(await r.promises.mkdir(t.dirname(e),{recursive:!0}),await r.promises.writeFile(e,o,"utf8"),!0)}async function a(...s){const a=e.createHash("sha512");for(const e of s.sort()){const s=await r.promises.stat(e);if(s.isDirectory()){const s=await r.promises.readdir(e,{withFileTypes:!0,recursive:!0});for(const e of s.sort((e,r)=>e.name.localeCompare(r.name)))e.isFile()&&a.update(await r.promises.readFile(t.join(e.parentPath,e.name),"utf8"))}else s.isFile()&&a.update(await r.promises.readFile(e,"utf8"))}return a.digest("hex")}exports.calculateHashFromFiles=a,exports.canSkipSeed=async function(e,...r){return!(!Number(process.env.ALLOW_TO_SKIP_SEED)&&"true"!==(process.env.ALLOW_TO_SKIP_SEED
|
|
1
|
+
"use strict";var e=require("node:crypto"),r=require("node:fs"),t=require("node:path");async function s(e,...s){let i="";try{i=await r.promises.readFile(e,"utf8")}catch{}const o=await a(...s);return i!==o&&(await r.promises.mkdir(t.dirname(e),{recursive:!0}),await r.promises.writeFile(e,o,"utf8"),!0)}async function a(...s){const a=e.createHash("sha512");for(const e of s.sort()){const s=await r.promises.stat(e);if(s.isDirectory()){const s=await r.promises.readdir(e,{withFileTypes:!0,recursive:!0});for(const e of s.sort((e,r)=>e.name.localeCompare(r.name)))e.isFile()&&a.update(await r.promises.readFile(t.join(e.parentPath,e.name),"utf8"))}else s.isFile()&&a.update(await r.promises.readFile(e,"utf8"))}return a.digest("hex")}exports.calculateHashFromFiles=a,exports.canSkipSeed=async function(e,...r){return!(!Number(process.env.ALLOW_TO_SKIP_SEED)&&"true"!==(process.env.ALLOW_TO_SKIP_SEED??"").toLowerCase()||await s(e,...r))},exports.updateHashFromFiles=s;
|
|
2
2
|
//# sourceMappingURL=hash.cjs.map
|
package/dist/hash.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hash.cjs","sources":["../src/hash.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Check whether seed command can be skipped or not and update hash file if needed.\n * Note that process.env.ALLOW_TO_SKIP_SEED should be set to non-zero number or 'true' to skip seed.\n * @param hashFilePath Path to the hash file.\n * @param paths Paths to the files or directories.\n * @returns Whether seed command can be skipped.\n */\nexport async function canSkipSeed(hashFilePath: string, ...paths: string[]): Promise<boolean> {\n return (\n (!!Number(process.env.ALLOW_TO_SKIP_SEED) || (process.env.ALLOW_TO_SKIP_SEED
|
|
1
|
+
{"version":3,"file":"hash.cjs","sources":["../src/hash.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Check whether seed command can be skipped or not and update hash file if needed.\n * Note that process.env.ALLOW_TO_SKIP_SEED should be set to non-zero number or 'true' to skip seed.\n * @param hashFilePath Path to the hash file.\n * @param paths Paths to the files or directories.\n * @returns Whether seed command can be skipped.\n */\nexport async function canSkipSeed(hashFilePath: string, ...paths: string[]): Promise<boolean> {\n return (\n (!!Number(process.env.ALLOW_TO_SKIP_SEED) || (process.env.ALLOW_TO_SKIP_SEED ?? '').toLowerCase() === 'true') &&\n !(await updateHashFromFiles(hashFilePath, ...paths))\n );\n}\n\n/**\n * Update hash file if the hash is different from the current one.\n * @param hashFilePath Path to the hash file.\n * @param paths Paths to the files or directories.\n * @returns Whether the hash file was updated.\n */\nexport async function updateHashFromFiles(hashFilePath: string, ...paths: string[]): Promise<boolean> {\n let oldHash = '';\n try {\n oldHash = await fs.promises.readFile(hashFilePath, 'utf8');\n } catch {\n // do nothing\n }\n const newHash = await calculateHashFromFiles(...paths);\n if (oldHash === newHash) return false;\n\n await fs.promises.mkdir(path.dirname(hashFilePath), { recursive: true });\n await fs.promises.writeFile(hashFilePath, newHash, 'utf8');\n return true;\n}\n\n/**\n * Calculate hash from files.\n * @param paths Paths to the files or directories.\n * @returns Hash string.\n */\nexport async function calculateHashFromFiles(...paths: string[]): Promise<string> {\n const hash = crypto.createHash('sha512');\n for (const fileOrDirPath of paths.sort()) {\n const stat = await fs.promises.stat(fileOrDirPath);\n if (stat.isDirectory()) {\n // Get all files in the directory recursively\n const dirents = await fs.promises.readdir(fileOrDirPath, { withFileTypes: true, recursive: true });\n for (const dirent of dirents.sort((d1, d2) => d1.name.localeCompare(d2.name))) {\n if (dirent.isFile()) {\n // Use parentPath property which is available in Node.js 18.17.0 or later\n hash.update(\n await fs.promises.readFile(\n path.join((dirent as unknown as Record<'parentPath', string>).parentPath, dirent.name),\n 'utf8'\n )\n );\n }\n }\n } else if (stat.isFile()) {\n hash.update(await fs.promises.readFile(fileOrDirPath, 'utf8'));\n }\n }\n return hash.digest('hex');\n}\n"],"names":["async","updateHashFromFiles","hashFilePath","paths","oldHash","fs","promises","readFile","newHash","calculateHashFromFiles","mkdir","path","dirname","recursive","writeFile","hash","crypto","createHash","fileOrDirPath","sort","stat","isDirectory","dirents","readdir","withFileTypes","dirent","d1","d2","name","localeCompare","isFile","update","join","parentPath","digest","Number","process","env","ALLOW_TO_SKIP_SEED","toLowerCase"],"mappings":"sFAwBOA,eAAeC,EAAoBC,KAAyBC,GACjE,IAAIC,EAAU,GACd,IACEA,QAAgBC,EAAGC,SAASC,SAASL,EAAc,OACrD,CAAE,MACA,CAEF,MAAMM,QAAgBC,KAA0BN,GAChD,OAAIC,IAAYI,UAEVH,EAAGC,SAASI,MAAMC,EAAKC,QAAQV,GAAe,CAAEW,WAAW,UAC3DR,EAAGC,SAASQ,UAAUZ,EAAcM,EAAS,SAC5C,EACT,CAOOR,eAAeS,KAA0BN,GAC9C,MAAMY,EAAOC,EAAOC,WAAW,UAC/B,IAAK,MAAMC,KAAiBf,EAAMgB,OAAQ,CACxC,MAAMC,QAAaf,EAAGC,SAASc,KAAKF,GACpC,GAAIE,EAAKC,cAAe,CAEtB,MAAMC,QAAgBjB,EAAGC,SAASiB,QAAQL,EAAe,CAAEM,eAAe,EAAMX,WAAW,IAC3F,IAAK,MAAMY,KAAUH,EAAQH,KAAK,CAACO,EAAIC,IAAOD,EAAGE,KAAKC,cAAcF,EAAGC,OACjEH,EAAOK,UAETf,EAAKgB,aACG1B,EAAGC,SAASC,SAChBI,EAAKqB,KAAMP,EAAmDQ,WAAYR,EAAOG,MACjF,QAKV,MAAWR,EAAKU,UACdf,EAAKgB,aAAa1B,EAAGC,SAASC,SAASW,EAAe,QAE1D,CACA,OAAOH,EAAKmB,OAAO,MACrB,sDAxDOlC,eAA2BE,KAAyBC,GACzD,SACKgC,OAAOC,QAAQC,IAAIC,qBAAgF,UAAxDF,QAAQC,IAAIC,oBAAsB,IAAIC,qBAC5EtC,EAAoBC,KAAiBC,GAEjD"}
|
package/dist/hash.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"node:crypto";import t from"node:fs";import r from"node:path";async function i(e,...t){return!(!Number(process.env.ALLOW_TO_SKIP_SEED)&&"true"!==(process.env.ALLOW_TO_SKIP_SEED
|
|
1
|
+
import e from"node:crypto";import t from"node:fs";import r from"node:path";async function i(e,...t){return!(!Number(process.env.ALLOW_TO_SKIP_SEED)&&"true"!==(process.env.ALLOW_TO_SKIP_SEED??"").toLowerCase()||await a(e,...t))}async function a(e,...i){let a="";try{a=await t.promises.readFile(e,"utf8")}catch{}const o=await s(...i);return a!==o&&(await t.promises.mkdir(r.dirname(e),{recursive:!0}),await t.promises.writeFile(e,o,"utf8"),!0)}async function s(...i){const a=e.createHash("sha512");for(const e of i.sort()){const i=await t.promises.stat(e);if(i.isDirectory()){const i=await t.promises.readdir(e,{withFileTypes:!0,recursive:!0});for(const e of i.sort((e,t)=>e.name.localeCompare(t.name)))e.isFile()&&a.update(await t.promises.readFile(r.join(e.parentPath,e.name),"utf8"))}else i.isFile()&&a.update(await t.promises.readFile(e,"utf8"))}return a.digest("hex")}export{s as calculateHashFromFiles,i as canSkipSeed,a as updateHashFromFiles};
|
|
2
2
|
//# sourceMappingURL=hash.js.map
|
package/dist/hash.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hash.js","sources":["../src/hash.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Check whether seed command can be skipped or not and update hash file if needed.\n * Note that process.env.ALLOW_TO_SKIP_SEED should be set to non-zero number or 'true' to skip seed.\n * @param hashFilePath Path to the hash file.\n * @param paths Paths to the files or directories.\n * @returns Whether seed command can be skipped.\n */\nexport async function canSkipSeed(hashFilePath: string, ...paths: string[]): Promise<boolean> {\n return (\n (!!Number(process.env.ALLOW_TO_SKIP_SEED) || (process.env.ALLOW_TO_SKIP_SEED
|
|
1
|
+
{"version":3,"file":"hash.js","sources":["../src/hash.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Check whether seed command can be skipped or not and update hash file if needed.\n * Note that process.env.ALLOW_TO_SKIP_SEED should be set to non-zero number or 'true' to skip seed.\n * @param hashFilePath Path to the hash file.\n * @param paths Paths to the files or directories.\n * @returns Whether seed command can be skipped.\n */\nexport async function canSkipSeed(hashFilePath: string, ...paths: string[]): Promise<boolean> {\n return (\n (!!Number(process.env.ALLOW_TO_SKIP_SEED) || (process.env.ALLOW_TO_SKIP_SEED ?? '').toLowerCase() === 'true') &&\n !(await updateHashFromFiles(hashFilePath, ...paths))\n );\n}\n\n/**\n * Update hash file if the hash is different from the current one.\n * @param hashFilePath Path to the hash file.\n * @param paths Paths to the files or directories.\n * @returns Whether the hash file was updated.\n */\nexport async function updateHashFromFiles(hashFilePath: string, ...paths: string[]): Promise<boolean> {\n let oldHash = '';\n try {\n oldHash = await fs.promises.readFile(hashFilePath, 'utf8');\n } catch {\n // do nothing\n }\n const newHash = await calculateHashFromFiles(...paths);\n if (oldHash === newHash) return false;\n\n await fs.promises.mkdir(path.dirname(hashFilePath), { recursive: true });\n await fs.promises.writeFile(hashFilePath, newHash, 'utf8');\n return true;\n}\n\n/**\n * Calculate hash from files.\n * @param paths Paths to the files or directories.\n * @returns Hash string.\n */\nexport async function calculateHashFromFiles(...paths: string[]): Promise<string> {\n const hash = crypto.createHash('sha512');\n for (const fileOrDirPath of paths.sort()) {\n const stat = await fs.promises.stat(fileOrDirPath);\n if (stat.isDirectory()) {\n // Get all files in the directory recursively\n const dirents = await fs.promises.readdir(fileOrDirPath, { withFileTypes: true, recursive: true });\n for (const dirent of dirents.sort((d1, d2) => d1.name.localeCompare(d2.name))) {\n if (dirent.isFile()) {\n // Use parentPath property which is available in Node.js 18.17.0 or later\n hash.update(\n await fs.promises.readFile(\n path.join((dirent as unknown as Record<'parentPath', string>).parentPath, dirent.name),\n 'utf8'\n )\n );\n }\n }\n } else if (stat.isFile()) {\n hash.update(await fs.promises.readFile(fileOrDirPath, 'utf8'));\n }\n }\n return hash.digest('hex');\n}\n"],"names":["async","canSkipSeed","hashFilePath","paths","Number","process","env","ALLOW_TO_SKIP_SEED","toLowerCase","updateHashFromFiles","oldHash","fs","promises","readFile","newHash","calculateHashFromFiles","mkdir","path","dirname","recursive","writeFile","hash","crypto","createHash","fileOrDirPath","sort","stat","isDirectory","dirents","readdir","withFileTypes","dirent","d1","d2","name","localeCompare","isFile","update","join","parentPath","digest"],"mappings":"2EAWOA,eAAeC,EAAYC,KAAyBC,GACzD,SACKC,OAAOC,QAAQC,IAAIC,qBAAgF,UAAxDF,QAAQC,IAAIC,oBAAsB,IAAIC,qBAC5EC,EAAoBP,KAAiBC,GAEjD,CAQOH,eAAeS,EAAoBP,KAAyBC,GACjE,IAAIO,EAAU,GACd,IACEA,QAAgBC,EAAGC,SAASC,SAASX,EAAc,OACrD,CAAE,MACA,CAEF,MAAMY,QAAgBC,KAA0BZ,GAChD,OAAIO,IAAYI,UAEVH,EAAGC,SAASI,MAAMC,EAAKC,QAAQhB,GAAe,CAAEiB,WAAW,UAC3DR,EAAGC,SAASQ,UAAUlB,EAAcY,EAAS,SAC5C,EACT,CAOOd,eAAee,KAA0BZ,GAC9C,MAAMkB,EAAOC,EAAOC,WAAW,UAC/B,IAAK,MAAMC,KAAiBrB,EAAMsB,OAAQ,CACxC,MAAMC,QAAaf,EAAGC,SAASc,KAAKF,GACpC,GAAIE,EAAKC,cAAe,CAEtB,MAAMC,QAAgBjB,EAAGC,SAASiB,QAAQL,EAAe,CAAEM,eAAe,EAAMX,WAAW,IAC3F,IAAK,MAAMY,KAAUH,EAAQH,KAAK,CAACO,EAAIC,IAAOD,EAAGE,KAAKC,cAAcF,EAAGC,OACjEH,EAAOK,UAETf,EAAKgB,aACG1B,EAAGC,SAASC,SAChBI,EAAKqB,KAAMP,EAAmDQ,WAAYR,EAAOG,MACjF,QAKV,MAAWR,EAAKU,UACdf,EAAKgB,aAAa1B,EAAGC,SAASC,SAASW,EAAe,QAE1D,CACA,OAAOH,EAAKmB,OAAO,MACrB"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("./env.cjs"),r=require("./exists.cjs"),s=require("./
|
|
1
|
+
"use strict";var e=require("./env.cjs"),r=require("./exists.cjs"),s=require("./hash.cjs"),n=require("./spawn.cjs");exports.readAndApplyEnvironmentVariables=e.readAndApplyEnvironmentVariables,exports.readEnvironmentVariables=e.readEnvironmentVariables,exports.removeNpmAndYarnEnvironmentVariables=e.removeNpmAndYarnEnvironmentVariables,exports.yargsOptionsBuilderForEnv=e.yargsOptionsBuilderForEnv,exports.existsAsync=r.existsAsync,exports.calculateHashFromFiles=s.calculateHashFromFiles,exports.canSkipSeed=s.canSkipSeed,exports.updateHashFromFiles=s.updateHashFromFiles,exports.spawnAsync=n.spawnAsync;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
export { readEnvironmentVariables, readAndApplyEnvironmentVariables, removeNpmAndYarnEnvironmentVariables, yargsOptionsBuilderForEnv, } from './env.js';
|
|
2
2
|
export type { EnvReaderOptions } from './env.js';
|
|
3
3
|
export { existsAsync } from './exists.js';
|
|
4
|
-
export { glob, globSync } from './glob.js';
|
|
5
4
|
export { calculateHashFromFiles, canSkipSeed, updateHashFromFiles } from './hash.js';
|
|
6
5
|
export { spawnAsync } from './spawn.js';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{readAndApplyEnvironmentVariables,readEnvironmentVariables,removeNpmAndYarnEnvironmentVariables,yargsOptionsBuilderForEnv}from"./env.js";export{existsAsync}from"./exists.js";export{
|
|
1
|
+
export{readAndApplyEnvironmentVariables,readEnvironmentVariables,removeNpmAndYarnEnvironmentVariables,yargsOptionsBuilderForEnv}from"./env.js";export{existsAsync}from"./exists.js";export{calculateHashFromFiles,canSkipSeed,updateHashFromFiles}from"./hash.js";export{spawnAsync}from"./spawn.js";
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/spawn.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spawn.cjs","sources":["../src/spawn.ts"],"sourcesContent":["import type {\n SpawnOptions,\n SpawnOptionsWithoutStdio,\n SpawnOptionsWithStdioTuple,\n SpawnSyncReturns,\n StdioNull,\n StdioPipe,\n} from 'node:child_process';\nimport { spawn } from 'node:child_process';\n\nimport treeKill from 'tree-kill';\n\n/**\n * Return type for spawnAsync function, based on SpawnSyncReturns but without output and error properties\n */\nexport type SpawnAsyncReturns = Omit<SpawnSyncReturns<string>, 'output' | 'error'>;\n\n/**\n * Options for spawnAsync function, extending various Node.js spawn options with additional functionality\n */\nexport type SpawnAsyncOptions = (\n | SpawnOptionsWithoutStdio\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>\n | SpawnOptions\n) & {\n /** Input string to write to the spawned process's stdin */\n input?: string;\n /** If true, stderr output will be merged into stdout */\n mergeOutAndError?: boolean;\n /** If true, the spawned process will be killed when the parent process exits */\n killOnExit?: boolean;\n /** If true, enables verbose logging of process operations */\n verbose?: boolean;\n /** If true, stdout data will be printed to console as it's received */\n printingStdout?: boolean;\n /** If true, stderr data will be printed to console as it's received */\n printingStderr?: boolean;\n};\n\n/**\n * Spawns a child process asynchronously and returns a promise that resolves with the process results\n *\n * This function provides a Promise-based wrapper around Node.js's spawn function with additional features:\n * - Automatic encoding of stdout/stderr as UTF-8\n * - Option to merge stderr into stdout\n * - Option to automatically kill the process on parent exit\n * - Option to provide input via stdin\n * - Verbose logging capability\n *\n * @param command - The command to run\n * @param args - List of string arguments\n * @param options - Configuration options for the spawned process\n * @returns Promise that resolves with the process results including pid, stdout, stderr, status, and signal\n * @throws Will reject the promise if the process fails to spawn or encounters an error\n *\n * @example\n * ```typescript\n * const result = await spawnAsync('ls', ['-la'], { verbose: true });\n * console.log(result.stdout);\n * ```\n */\nexport async function spawnAsync(\n command: string,\n args?:
|
|
1
|
+
{"version":3,"file":"spawn.cjs","sources":["../src/spawn.ts"],"sourcesContent":["import type {\n SpawnOptions,\n SpawnOptionsWithoutStdio,\n SpawnOptionsWithStdioTuple,\n SpawnSyncReturns,\n StdioNull,\n StdioPipe,\n} from 'node:child_process';\nimport { spawn } from 'node:child_process';\n\nimport treeKill from 'tree-kill';\n\n/**\n * Return type for spawnAsync function, based on SpawnSyncReturns but without output and error properties\n */\nexport type SpawnAsyncReturns = Omit<SpawnSyncReturns<string>, 'output' | 'error'>;\n\n/**\n * Options for spawnAsync function, extending various Node.js spawn options with additional functionality\n */\nexport type SpawnAsyncOptions = (\n | SpawnOptionsWithoutStdio\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>\n | SpawnOptions\n) & {\n /** Input string to write to the spawned process's stdin */\n input?: string;\n /** If true, stderr output will be merged into stdout */\n mergeOutAndError?: boolean;\n /** If true, the spawned process will be killed when the parent process exits */\n killOnExit?: boolean;\n /** If true, enables verbose logging of process operations */\n verbose?: boolean;\n /** If true, stdout data will be printed to console as it's received */\n printingStdout?: boolean;\n /** If true, stderr data will be printed to console as it's received */\n printingStderr?: boolean;\n};\n\n/**\n * Spawns a child process asynchronously and returns a promise that resolves with the process results\n *\n * This function provides a Promise-based wrapper around Node.js's spawn function with additional features:\n * - Automatic encoding of stdout/stderr as UTF-8\n * - Option to merge stderr into stdout\n * - Option to automatically kill the process on parent exit\n * - Option to provide input via stdin\n * - Verbose logging capability\n *\n * @param command - The command to run\n * @param args - List of string arguments\n * @param options - Configuration options for the spawned process\n * @returns Promise that resolves with the process results including pid, stdout, stderr, status, and signal\n * @throws Will reject the promise if the process fails to spawn or encounters an error\n *\n * @example\n * ```typescript\n * const result = await spawnAsync('ls', ['-la'], { verbose: true });\n * console.log(result.stdout);\n * ```\n */\nexport async function spawnAsync(\n command: string,\n args?: readonly string[],\n options?: SpawnAsyncOptions\n): Promise<SpawnAsyncReturns> {\n return new Promise((resolve, reject) => {\n try {\n const proc = spawn(command, args ?? [], options ?? {});\n // `setEncoding` is undefined in Bun\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n proc.stdout?.setEncoding?.('utf8');\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n proc.stderr?.setEncoding?.('utf8');\n\n let stdout = '';\n let stderr = '';\n proc.stdout?.on('data', (data: string) => {\n stdout += data;\n if (options?.printingStdout) {\n process.stdout.write(data);\n }\n });\n proc.stderr?.on('data', (data: string) => {\n if (options?.mergeOutAndError) {\n stdout += data;\n } else {\n stderr += data;\n }\n if (options?.printingStderr) {\n process.stderr.write(data);\n }\n });\n\n let stopped = false;\n const stopProcess = (): void => {\n if (stopped || !proc.pid) return;\n\n stopped = true;\n if (options?.verbose) {\n console.info(`treeKill(${proc.pid})`);\n }\n treeKill(proc.pid);\n };\n if (options?.killOnExit) {\n process.on('beforeExit', stopProcess);\n process.on('SIGINT', stopProcess);\n }\n\n proc.on('error', (error) => {\n process.removeListener('beforeExit', stopProcess);\n process.removeListener('SIGINT', stopProcess);\n proc.removeAllListeners('close');\n reject(error);\n });\n proc.on('close', (code: number | null, signal: NodeJS.Signals | null) => {\n process.removeListener('beforeExit', stopProcess);\n process.removeListener('SIGINT', stopProcess);\n if (proc.pid === undefined) {\n reject(new Error('Process has no pid.'));\n } else {\n resolve({\n pid: proc.pid,\n stdout,\n stderr,\n status: code,\n signal,\n });\n }\n });\n\n if (options?.input) {\n proc.stdin?.write(options.input);\n proc.stdin?.end();\n }\n } catch (error) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n }\n });\n}\n"],"names":["async","command","args","options","Promise","resolve","reject","proc","spawn","stdout","setEncoding","stderr","on","data","printingStdout","process","write","mergeOutAndError","printingStderr","stopped","stopProcess","pid","verbose","console","info","treeKill","killOnExit","error","removeListener","removeAllListeners","code","signal","undefined","Error","status","input","stdin","end"],"mappings":"2FAoEOA,eACLC,EACAC,EACAC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out);
|
|
43
43
|
* ```
|
|
44
44
|
*/
|
|
45
|
-
export declare function spawnAsync(command: string, args?:
|
|
45
|
+
export declare function spawnAsync(command: string, args?: readonly string[], options?: SpawnAsyncOptions): Promise<SpawnAsyncReturns>;
|
package/dist/spawn.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spawn.js","sources":["../src/spawn.ts"],"sourcesContent":["import type {\n SpawnOptions,\n SpawnOptionsWithoutStdio,\n SpawnOptionsWithStdioTuple,\n SpawnSyncReturns,\n StdioNull,\n StdioPipe,\n} from 'node:child_process';\nimport { spawn } from 'node:child_process';\n\nimport treeKill from 'tree-kill';\n\n/**\n * Return type for spawnAsync function, based on SpawnSyncReturns but without output and error properties\n */\nexport type SpawnAsyncReturns = Omit<SpawnSyncReturns<string>, 'output' | 'error'>;\n\n/**\n * Options for spawnAsync function, extending various Node.js spawn options with additional functionality\n */\nexport type SpawnAsyncOptions = (\n | SpawnOptionsWithoutStdio\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>\n | SpawnOptions\n) & {\n /** Input string to write to the spawned process's stdin */\n input?: string;\n /** If true, stderr output will be merged into stdout */\n mergeOutAndError?: boolean;\n /** If true, the spawned process will be killed when the parent process exits */\n killOnExit?: boolean;\n /** If true, enables verbose logging of process operations */\n verbose?: boolean;\n /** If true, stdout data will be printed to console as it's received */\n printingStdout?: boolean;\n /** If true, stderr data will be printed to console as it's received */\n printingStderr?: boolean;\n};\n\n/**\n * Spawns a child process asynchronously and returns a promise that resolves with the process results\n *\n * This function provides a Promise-based wrapper around Node.js's spawn function with additional features:\n * - Automatic encoding of stdout/stderr as UTF-8\n * - Option to merge stderr into stdout\n * - Option to automatically kill the process on parent exit\n * - Option to provide input via stdin\n * - Verbose logging capability\n *\n * @param command - The command to run\n * @param args - List of string arguments\n * @param options - Configuration options for the spawned process\n * @returns Promise that resolves with the process results including pid, stdout, stderr, status, and signal\n * @throws Will reject the promise if the process fails to spawn or encounters an error\n *\n * @example\n * ```typescript\n * const result = await spawnAsync('ls', ['-la'], { verbose: true });\n * console.log(result.stdout);\n * ```\n */\nexport async function spawnAsync(\n command: string,\n args?:
|
|
1
|
+
{"version":3,"file":"spawn.js","sources":["../src/spawn.ts"],"sourcesContent":["import type {\n SpawnOptions,\n SpawnOptionsWithoutStdio,\n SpawnOptionsWithStdioTuple,\n SpawnSyncReturns,\n StdioNull,\n StdioPipe,\n} from 'node:child_process';\nimport { spawn } from 'node:child_process';\n\nimport treeKill from 'tree-kill';\n\n/**\n * Return type for spawnAsync function, based on SpawnSyncReturns but without output and error properties\n */\nexport type SpawnAsyncReturns = Omit<SpawnSyncReturns<string>, 'output' | 'error'>;\n\n/**\n * Options for spawnAsync function, extending various Node.js spawn options with additional functionality\n */\nexport type SpawnAsyncOptions = (\n | SpawnOptionsWithoutStdio\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>\n | SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>\n | SpawnOptions\n) & {\n /** Input string to write to the spawned process's stdin */\n input?: string;\n /** If true, stderr output will be merged into stdout */\n mergeOutAndError?: boolean;\n /** If true, the spawned process will be killed when the parent process exits */\n killOnExit?: boolean;\n /** If true, enables verbose logging of process operations */\n verbose?: boolean;\n /** If true, stdout data will be printed to console as it's received */\n printingStdout?: boolean;\n /** If true, stderr data will be printed to console as it's received */\n printingStderr?: boolean;\n};\n\n/**\n * Spawns a child process asynchronously and returns a promise that resolves with the process results\n *\n * This function provides a Promise-based wrapper around Node.js's spawn function with additional features:\n * - Automatic encoding of stdout/stderr as UTF-8\n * - Option to merge stderr into stdout\n * - Option to automatically kill the process on parent exit\n * - Option to provide input via stdin\n * - Verbose logging capability\n *\n * @param command - The command to run\n * @param args - List of string arguments\n * @param options - Configuration options for the spawned process\n * @returns Promise that resolves with the process results including pid, stdout, stderr, status, and signal\n * @throws Will reject the promise if the process fails to spawn or encounters an error\n *\n * @example\n * ```typescript\n * const result = await spawnAsync('ls', ['-la'], { verbose: true });\n * console.log(result.stdout);\n * ```\n */\nexport async function spawnAsync(\n command: string,\n args?: readonly string[],\n options?: SpawnAsyncOptions\n): Promise<SpawnAsyncReturns> {\n return new Promise((resolve, reject) => {\n try {\n const proc = spawn(command, args ?? [], options ?? {});\n // `setEncoding` is undefined in Bun\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n proc.stdout?.setEncoding?.('utf8');\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n proc.stderr?.setEncoding?.('utf8');\n\n let stdout = '';\n let stderr = '';\n proc.stdout?.on('data', (data: string) => {\n stdout += data;\n if (options?.printingStdout) {\n process.stdout.write(data);\n }\n });\n proc.stderr?.on('data', (data: string) => {\n if (options?.mergeOutAndError) {\n stdout += data;\n } else {\n stderr += data;\n }\n if (options?.printingStderr) {\n process.stderr.write(data);\n }\n });\n\n let stopped = false;\n const stopProcess = (): void => {\n if (stopped || !proc.pid) return;\n\n stopped = true;\n if (options?.verbose) {\n console.info(`treeKill(${proc.pid})`);\n }\n treeKill(proc.pid);\n };\n if (options?.killOnExit) {\n process.on('beforeExit', stopProcess);\n process.on('SIGINT', stopProcess);\n }\n\n proc.on('error', (error) => {\n process.removeListener('beforeExit', stopProcess);\n process.removeListener('SIGINT', stopProcess);\n proc.removeAllListeners('close');\n reject(error);\n });\n proc.on('close', (code: number | null, signal: NodeJS.Signals | null) => {\n process.removeListener('beforeExit', stopProcess);\n process.removeListener('SIGINT', stopProcess);\n if (proc.pid === undefined) {\n reject(new Error('Process has no pid.'));\n } else {\n resolve({\n pid: proc.pid,\n stdout,\n stderr,\n status: code,\n signal,\n });\n }\n });\n\n if (options?.input) {\n proc.stdin?.write(options.input);\n proc.stdin?.end();\n }\n } catch (error) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n }\n });\n}\n"],"names":["async","spawnAsync","command","args","options","Promise","resolve","reject","proc","spawn","stdout","setEncoding","stderr","on","data","printingStdout","process","write","mergeOutAndError","printingStderr","stopped","stopProcess","pid","verbose","console","info","treeKill","killOnExit","error","removeListener","removeAllListeners","code","signal","undefined","Error","status","input","stdin","end"],"mappings":"oEAoEOA,eAAeC,EACpBC,EACAC,EACAC,GAEA,OAAO,IAAIC,QAAQ,CAACC,EAASC,KAC3B,IACE,MAAMC,EAAOC,EAAMP,EAASC,GAAQ,GAAIC,GAAW,IAGnDI,EAAKE,QAAQC,cAAc,QAE3BH,EAAKI,QAAQD,cAAc,QAE3B,IAAID,EAAS,GACTE,EAAS,GACbJ,EAAKE,QAAQG,GAAG,OAASC,IACvBJ,GAAUI,EACNV,GAASW,gBACXC,QAAQN,OAAOO,MAAMH,KAGzBN,EAAKI,QAAQC,GAAG,OAASC,IACnBV,GAASc,iBACXR,GAAUI,EAEVF,GAAUE,EAERV,GAASe,gBACXH,QAAQJ,OAAOK,MAAMH,KAIzB,IAAIM,GAAU,EACd,MAAMC,EAAcA,MACdD,GAAYZ,EAAKc,MAErBF,GAAU,EACNhB,GAASmB,SACXC,QAAQC,KAAK,YAAYjB,EAAKc,QAEhCI,EAASlB,EAAKc,OAEZlB,GAASuB,aACXX,QAAQH,GAAG,aAAcQ,GACzBL,QAAQH,GAAG,SAAUQ,IAGvBb,EAAKK,GAAG,QAAUe,IAChBZ,QAAQa,eAAe,aAAcR,GACrCL,QAAQa,eAAe,SAAUR,GACjCb,EAAKsB,mBAAmB,SACxBvB,EAAOqB,KAETpB,EAAKK,GAAG,QAAS,CAACkB,EAAqBC,KACrChB,QAAQa,eAAe,aAAcR,GACrCL,QAAQa,eAAe,SAAUR,QAChBY,IAAbzB,EAAKc,IACPf,EAAO,IAAI2B,MAAM,wBAEjB5B,EAAQ,CACNgB,IAAKd,EAAKc,IACVZ,SACAE,SACAuB,OAAQJ,EACRC,aAKF5B,GAASgC,QACX5B,EAAK6B,OAAOpB,MAAMb,EAAQgC,OAC1B5B,EAAK6B,OAAOC,MAEhB,CAAE,MAAOV,GAEPrB,EAAOqB,EACT,GAEJ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@willbooster/shared-lib-node",
|
|
3
|
-
"version": "7.0.
|
|
3
|
+
"version": "7.0.5",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"author": "WillBooster Inc.",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -26,13 +26,13 @@
|
|
|
26
26
|
],
|
|
27
27
|
"scripts": {
|
|
28
28
|
"build": "build-ts lib",
|
|
29
|
-
"check-all-for-ai": "yarn check-for-ai && yarn test
|
|
29
|
+
"check-all-for-ai": "yarn check-for-ai && yarn test",
|
|
30
30
|
"check-for-ai": "yarn install > /dev/null && yarn format > /dev/null 2> /dev/null || true && yarn lint-fix --quiet && yarn typecheck",
|
|
31
31
|
"cleanup": "yarn format && yarn lint-fix",
|
|
32
32
|
"format": "sort-package-json && yarn prettify",
|
|
33
33
|
"lint": "eslint --color",
|
|
34
34
|
"lint-fix": "yarn lint --fix",
|
|
35
|
-
"prettify": "prettier --cache --color --write \"**/{.*/,}*.{cjs,css,cts,htm,html,java,js,json,json5,jsonc,jsx,md,mjs,mts,scss,ts,tsx,vue,yaml,yml}\" \"!**/test{-,/}fixtures/**\"",
|
|
35
|
+
"prettify": "prettier --cache --color --write \"**/{.*/,}*.{cjs,css,cts,htm,html,java,js,json,json5,jsonc,jsx,md,mjs,mts,scss,ts,tsx,vue,yaml,yml}\" \"!**/test{-,/}fixtures/**\" || true",
|
|
36
36
|
"test": "vitest test/",
|
|
37
37
|
"typecheck": "tsc --noEmit --Pretty"
|
|
38
38
|
},
|
|
@@ -45,27 +45,27 @@
|
|
|
45
45
|
"@types/bun": "1.2.19",
|
|
46
46
|
"@types/eslint": "9.6.1",
|
|
47
47
|
"@types/micromatch": "4.0.9",
|
|
48
|
-
"@types/node": "24.1
|
|
49
|
-
"@willbooster/eslint-config-ts": "11.4.
|
|
48
|
+
"@types/node": "24.2.1",
|
|
49
|
+
"@willbooster/eslint-config-ts": "11.4.4",
|
|
50
50
|
"@willbooster/prettier-config": "10.2.0",
|
|
51
|
-
"build-ts": "15.0.
|
|
52
|
-
"eslint": "9.
|
|
51
|
+
"build-ts": "15.0.19",
|
|
52
|
+
"eslint": "9.33.0",
|
|
53
53
|
"eslint-config-flat-gitignore": "2.1.0",
|
|
54
54
|
"eslint-config-prettier": "10.1.8",
|
|
55
55
|
"eslint-import-resolver-typescript": "4.4.4",
|
|
56
56
|
"eslint-plugin-import-x": "4.16.1",
|
|
57
57
|
"eslint-plugin-sort-class-members": "1.21.0",
|
|
58
58
|
"eslint-plugin-sort-destructure-keys": "2.0.0",
|
|
59
|
-
"eslint-plugin-unicorn": "
|
|
59
|
+
"eslint-plugin-unicorn": "60.0.0",
|
|
60
60
|
"eslint-plugin-unused-imports": "4.1.4",
|
|
61
61
|
"globals": "16.3.0",
|
|
62
|
-
"lint-staged": "16.1.
|
|
62
|
+
"lint-staged": "16.1.5",
|
|
63
63
|
"micromatch": "4.0.8",
|
|
64
64
|
"prettier": "3.6.2",
|
|
65
|
-
"prettier-plugin-java": "2.7.
|
|
65
|
+
"prettier-plugin-java": "2.7.4",
|
|
66
66
|
"sort-package-json": "3.4.0",
|
|
67
|
-
"typescript": "5.
|
|
68
|
-
"typescript-eslint": "8.
|
|
67
|
+
"typescript": "5.9.2",
|
|
68
|
+
"typescript-eslint": "8.39.0",
|
|
69
69
|
"vitest": "3.2.4"
|
|
70
70
|
},
|
|
71
71
|
"publishConfig": {
|
package/dist/glob.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var e=require("node:fs"),s=require("node:path");function n(e,n){if(!n)return!1;const i=s.join(e.parentPath,e.name).replaceAll("\\","/");return n.some(e=>e.test(i))}exports.glob=async function*(i,l){if(process.versions.bun){const e=new(require(String("bun")).Glob)(i);for await(const i of e.scan({cwd:l.cwd,onlyFiles:l.onlyFiles})){const e=s.parse(i),o={name:e.base,parentPath:s.resolve(l.cwd??".",e.dir)};n(o,l.excludes)||(yield o)}}else for await(const s of e.promises.glob(i,{...l,exclude:l.excludes?.length?e=>n(e,l.excludes):void 0,withFileTypes:!0}))l.onlyFiles&&!s.isFile()||s.isFile()&&n(s,l.excludes)||(yield s)},exports.globSync=function(i,l){if(process.versions.bun){const e=new(require(String("bun")).Glob)(i),o=[];for(const i of e.scanSync({cwd:l.cwd,onlyFiles:l.onlyFiles})){const e=s.parse(i),r={name:e.base,parentPath:s.resolve(l.cwd??".",e.dir)};n(r,l.excludes)||o.push(r)}return o}return e.globSync(i,{...l,exclude:l.excludes?e=>n(e,l.excludes):void 0,withFileTypes:!0}).filter(e=>!(l.onlyFiles&&!e.isFile()||e.isFile()&&n(e,l.excludes)))};
|
|
2
|
-
//# sourceMappingURL=glob.cjs.map
|
package/dist/glob.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"glob.cjs","sources":["../src/glob.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { Glob } from 'bun';\n\n/**\n * Represents a file system entry with name and parent path information.\n */\ntype NodeJsDirentLike = {\n /** The name of the file or directory */\n name: string;\n /** The absolute path to the parent directory */\n parentPath: string;\n};\n\n/**\n * Asynchronously glob for files and directories.\n * @param pattern - The glob pattern to match files and directories\n * @param options - Configuration options for globbing\n * @param options.cwd - The working directory to start globbing from\n * @param options.excludes - Regular expressions to exclude from the results\n * @param options.onlyFiles - If true, only return files (not directories)\n * @returns An async iterator of matching files and directories\n */\nexport async function* glob(\n pattern: string,\n options: { cwd?: string; excludes?: RegExp[]; onlyFiles: boolean }\n): NodeJS.AsyncIterator<NodeJsDirentLike> {\n // cf. https://bun.sh/guides/util/detect-bun\n if (process.versions.bun) {\n // Use require & String to avoid loading bun on Next.js\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-unsafe-assignment,unicorn/prefer-module\n const bun = require(String('bun'));\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access\n const bunGlob = new bun.Glob(pattern) as Glob;\n for await (const direntPath of bunGlob.scan({ cwd: options.cwd, onlyFiles: options.onlyFiles })) {\n const parsedDirentPath = path.parse(direntPath);\n const dirent = {\n name: parsedDirentPath.base,\n parentPath: path.resolve(options.cwd ?? '.', parsedDirentPath.dir),\n };\n if (isExcluded(dirent, options.excludes)) continue;\n\n yield dirent;\n }\n } else {\n for await (const dirent of fs.promises.glob(pattern, {\n ...options,\n exclude: options.excludes?.length ? (dirent) => isExcluded(dirent, options.excludes) : undefined,\n withFileTypes: true,\n })) {\n if (options.onlyFiles && !dirent.isFile()) continue;\n // We need double-check here because files are ignored by `exclude` option.\n if (dirent.isFile() && isExcluded(dirent, options.excludes)) continue;\n\n yield dirent;\n }\n }\n}\n\n/**\n * Synchronously glob for files and directories.\n * @param pattern - The glob pattern to match files and directories\n * @param options - Configuration options for globbing\n * @param options.cwd - The working directory to start globbing from\n * @param options.excludes - Regular expressions to exclude from the results\n * @param options.onlyFiles - If true, only return files (not directories)\n * @returns An array of matching files and directories\n */\nexport function globSync(\n pattern: string,\n options: { cwd?: string; excludes?: RegExp[]; onlyFiles: boolean }\n): NodeJsDirentLike[] {\n // cf. https://bun.sh/guides/util/detect-bun\n if (process.versions.bun) {\n // Use require & String to avoid loading bun on Next.js\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-unsafe-assignment,unicorn/prefer-module\n const bun = require(String('bun'));\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access\n const bunGlob = new bun.Glob(pattern) as Glob;\n const dirents: NodeJsDirentLike[] = [];\n for (const direntPath of bunGlob.scanSync({ cwd: options.cwd, onlyFiles: options.onlyFiles })) {\n const parsedDirentPath = path.parse(direntPath);\n const dirent = {\n name: parsedDirentPath.base,\n parentPath: path.resolve(options.cwd ?? '.', parsedDirentPath.dir),\n };\n if (isExcluded(dirent, options.excludes)) continue;\n\n dirents.push(dirent);\n }\n return dirents;\n } else {\n return (\n fs\n .globSync(pattern, {\n ...options,\n exclude: options.excludes ? (dirent) => isExcluded(dirent, options.excludes) : undefined,\n withFileTypes: true,\n })\n // We need double-check here because files are ignored by `exclude` option.\n .filter(\n (dirent) =>\n !(options.onlyFiles && !dirent.isFile()) && !(dirent.isFile() && isExcluded(dirent, options.excludes))\n )\n );\n }\n}\n\nfunction isExcluded(dirent: NodeJsDirentLike, excludes?: RegExp[]): boolean {\n if (!excludes) return false;\n\n const targetPath = path.join(dirent.parentPath, dirent.name).replaceAll('\\\\', '/');\n return excludes.some((pattern) => pattern.test(targetPath));\n}\n"],"names":["isExcluded","dirent","excludes","targetPath","path","join","parentPath","name","replaceAll","some","pattern","test","async","options","process","versions","bun","bunGlob","require","String","Glob","direntPath","scan","cwd","onlyFiles","parsedDirentPath","parse","base","resolve","dir","fs","promises","glob","exclude","length","undefined","withFileTypes","isFile","dirents","scanSync","push","globSync","filter"],"mappings":"6DA6GA,SA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A,OAAOqC,CACT,CACE,OACER,EACGW,SAAS/B,EAAS,IACdG,EACHoB,QAASpB,EAAQX,SAAYD,GAAWD,EAAWC,EAAQY,EAAQX,eAAYiC,EAC/EC,eAAe,IAGhBM,OACEzC,KACGY,EAAQW,YAAcvB,EAAOoC,UAAepC,EAAOoC,UAAYrC,EAAWC,EAAQY,EAAQX,WAIxG"}
|
package/dist/glob.d.ts
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Represents a file system entry with name and parent path information.
|
|
3
|
-
*/
|
|
4
|
-
type NodeJsDirentLike = {
|
|
5
|
-
/** The name of the file or directory */
|
|
6
|
-
name: string;
|
|
7
|
-
/** The absolute path to the parent directory */
|
|
8
|
-
parentPath: string;
|
|
9
|
-
};
|
|
10
|
-
/**
|
|
11
|
-
* Asynchronously glob for files and directories.
|
|
12
|
-
* @param pattern - The glob pattern to match files and directories
|
|
13
|
-
* @param options - Configuration options for globbing
|
|
14
|
-
* @param options.cwd - The working directory to start globbing from
|
|
15
|
-
* @param options.excludes - Regular expressions to exclude from the results
|
|
16
|
-
* @param options.onlyFiles - If true, only return files (not directories)
|
|
17
|
-
* @returns An async iterator of matching files and directories
|
|
18
|
-
*/
|
|
19
|
-
export declare function glob(pattern: string, options: {
|
|
20
|
-
cwd?: string;
|
|
21
|
-
excludes?: RegExp[];
|
|
22
|
-
onlyFiles: boolean;
|
|
23
|
-
}): NodeJS.AsyncIterator<NodeJsDirentLike>;
|
|
24
|
-
/**
|
|
25
|
-
* Synchronously glob for files and directories.
|
|
26
|
-
* @param pattern - The glob pattern to match files and directories
|
|
27
|
-
* @param options - Configuration options for globbing
|
|
28
|
-
* @param options.cwd - The working directory to start globbing from
|
|
29
|
-
* @param options.excludes - Regular expressions to exclude from the results
|
|
30
|
-
* @param options.onlyFiles - If true, only return files (not directories)
|
|
31
|
-
* @returns An array of matching files and directories
|
|
32
|
-
*/
|
|
33
|
-
export declare function globSync(pattern: string, options: {
|
|
34
|
-
cwd?: string;
|
|
35
|
-
excludes?: RegExp[];
|
|
36
|
-
onlyFiles: boolean;
|
|
37
|
-
}): NodeJsDirentLike[];
|
|
38
|
-
export {};
|
package/dist/glob.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"node:fs";import s from"node:path";async function*n(n,o){if(process.versions.bun){const e=new(require(String("bun")).Glob)(n);for await(const n of e.scan({cwd:o.cwd,onlyFiles:o.onlyFiles})){const e=s.parse(n),l={name:e.base,parentPath:s.resolve(o.cwd??".",e.dir)};i(l,o.excludes)||(yield l)}}else for await(const s of e.promises.glob(n,{...o,exclude:o.excludes?.length?e=>i(e,o.excludes):void 0,withFileTypes:!0}))o.onlyFiles&&!s.isFile()||s.isFile()&&i(s,o.excludes)||(yield s)}function o(n,o){if(process.versions.bun){const e=new(require(String("bun")).Glob)(n),l=[];for(const n of e.scanSync({cwd:o.cwd,onlyFiles:o.onlyFiles})){const e=s.parse(n),r={name:e.base,parentPath:s.resolve(o.cwd??".",e.dir)};i(r,o.excludes)||l.push(r)}return l}return e.globSync(n,{...o,exclude:o.excludes?e=>i(e,o.excludes):void 0,withFileTypes:!0}).filter(e=>!(o.onlyFiles&&!e.isFile()||e.isFile()&&i(e,o.excludes)))}function i(e,n){if(!n)return!1;const o=s.join(e.parentPath,e.name).replaceAll("\\","/");return n.some(e=>e.test(o))}export{n as glob,o as globSync};
|
|
2
|
-
//# sourceMappingURL=glob.js.map
|
package/dist/glob.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"glob.js","sources":["../src/glob.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { Glob } from 'bun';\n\n/**\n * Represents a file system entry with name and parent path information.\n */\ntype NodeJsDirentLike = {\n /** The name of the file or directory */\n name: string;\n /** The absolute path to the parent directory */\n parentPath: string;\n};\n\n/**\n * Asynchronously glob for files and directories.\n * @param pattern - The glob pattern to match files and directories\n * @param options - Configuration options for globbing\n * @param options.cwd - The working directory to start globbing from\n * @param options.excludes - Regular expressions to exclude from the results\n * @param options.onlyFiles - If true, only return files (not directories)\n * @returns An async iterator of matching files and directories\n */\nexport async function* glob(\n pattern: string,\n options: { cwd?: string; excludes?: RegExp[]; onlyFiles: boolean }\n): NodeJS.AsyncIterator<NodeJsDirentLike> {\n // cf. https://bun.sh/guides/util/detect-bun\n if (process.versions.bun) {\n // Use require & String to avoid loading bun on Next.js\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-unsafe-assignment,unicorn/prefer-module\n const bun = require(String('bun'));\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access\n const bunGlob = new bun.Glob(pattern) as Glob;\n for await (const direntPath of bunGlob.scan({ cwd: options.cwd, onlyFiles: options.onlyFiles })) {\n const parsedDirentPath = path.parse(direntPath);\n const dirent = {\n name: parsedDirentPath.base,\n parentPath: path.resolve(options.cwd ?? '.', parsedDirentPath.dir),\n };\n if (isExcluded(dirent, options.excludes)) continue;\n\n yield dirent;\n }\n } else {\n for await (const dirent of fs.promises.glob(pattern, {\n ...options,\n exclude: options.excludes?.length ? (dirent) => isExcluded(dirent, options.excludes) : undefined,\n withFileTypes: true,\n })) {\n if (options.onlyFiles && !dirent.isFile()) continue;\n // We need double-check here because files are ignored by `exclude` option.\n if (dirent.isFile() && isExcluded(dirent, options.excludes)) continue;\n\n yield dirent;\n }\n }\n}\n\n/**\n * Synchronously glob for files and directories.\n * @param pattern - The glob pattern to match files and directories\n * @param options - Configuration options for globbing\n * @param options.cwd - The working directory to start globbing from\n * @param options.excludes - Regular expressions to exclude from the results\n * @param options.onlyFiles - If true, only return files (not directories)\n * @returns An array of matching files and directories\n */\nexport function globSync(\n pattern: string,\n options: { cwd?: string; excludes?: RegExp[]; onlyFiles: boolean }\n): NodeJsDirentLike[] {\n // cf. https://bun.sh/guides/util/detect-bun\n if (process.versions.bun) {\n // Use require & String to avoid loading bun on Next.js\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-unsafe-assignment,unicorn/prefer-module\n const bun = require(String('bun'));\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access\n const bunGlob = new bun.Glob(pattern) as Glob;\n const dirents: NodeJsDirentLike[] = [];\n for (const direntPath of bunGlob.scanSync({ cwd: options.cwd, onlyFiles: options.onlyFiles })) {\n const parsedDirentPath = path.parse(direntPath);\n const dirent = {\n name: parsedDirentPath.base,\n parentPath: path.resolve(options.cwd ?? '.', parsedDirentPath.dir),\n };\n if (isExcluded(dirent, options.excludes)) continue;\n\n dirents.push(dirent);\n }\n return dirents;\n } else {\n return (\n fs\n .globSync(pattern, {\n ...options,\n exclude: options.excludes ? (dirent) => isExcluded(dirent, options.excludes) : undefined,\n withFileTypes: true,\n })\n // We need double-check here because files are ignored by `exclude` option.\n .filter(\n (dirent) =>\n !(options.onlyFiles && !dirent.isFile()) && !(dirent.isFile() && isExcluded(dirent, options.excludes))\n )\n );\n }\n}\n\nfunction isExcluded(dirent: NodeJsDirentLike, excludes?: RegExp[]): boolean {\n if (!excludes) return false;\n\n const targetPath = path.join(dirent.parentPath, dirent.name).replaceAll('\\\\', '/');\n return excludes.some((pattern) => pattern.test(targetPath));\n}\n"],"names":["async","glob","pattern","options","process","versions","bun","bunGlob","require","String","Glob","direntPath","scan","cwd","onlyFiles","parsedDirentPath","path","parse","dirent","name","base","parentPath","resolve","dir","isExcluded","excludes","fs","promises","exclude","length","undefined","withFileTypes","isFile","globSync","dirents","scanSync","push","filter","targetPath","join","replaceAll","some","test"],"mappings":"gDAwBOA,eAAgBC,EACrBC,EACAC,GAGA,GAAIC,QAAQC,SAASC,IAAK,CAGxB,MAEMC,EAAU,IAFJC,QAAQC,OAAO,QAEHC,MAAKR,GAC7B,UAAW,MAAMS,KAAcJ,EAAQK,KAAK,CAAEC,IAAKV,EAAQU,IAAKC,UAAWX,EAAQW,YAAc,CAC/F,MAAMC,EAAmBC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