@uiwwsw/react-query-helper 1.0.1 → 1.0.10

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/README.md CHANGED
@@ -25,6 +25,8 @@
25
25
 
26
26
  > React Query Helper는 TypeScript API 함수로부터 React Query 훅과 옵션 객체를 자동 생성해 주는 CLI 도구입니다. 설정만 해두면 반복적인 훅 작성 시간을 절약하고 프로젝트 전체에 걸쳐 일관된 데이터 패칭 규칙을 유지할 수 있습니다.
27
27
 
28
+ 기본적으로 각 파일의 `export`된 함수만 생성 대상으로 분석합니다.
29
+
28
30
  ---
29
31
 
30
32
  ## 목차
@@ -32,12 +34,12 @@
32
34
  - [주요 특징](#주요-특징)
33
35
  - [빠른 시작](#빠른-시작)
34
36
  - [설치](#설치)
35
- - [설정 파일 만들기](#설정-파일-만들기)
37
+ - [초기 설정 파일 생성](#초기-설정-파일-생성)
36
38
  - [코드 생성 실행](#코드-생성-실행)
37
39
  - [CLI 명령어](#cli-명령어)
38
40
  - [설정 옵션](#설정-옵션)
39
41
  - [생성 결과 예시](#생성-결과-예시)
40
- - [템플릿 커스터마이징](#템플릿-커스터마이징)
42
+ - [헬퍼 경로 커스터마이징](#헬퍼-경로-커스터마이징)
41
43
  - [베스트 프랙티스](#베스트-프랙티스)
42
44
  - [스타 히스토리](#스타-히스토리)
43
45
  - [기여](#기여)
@@ -46,10 +48,12 @@
46
48
  ## 주요 특징
47
49
 
48
50
  - **설정 기반 자동화**: `rqh.config.ts`만 구성하면 API 디렉토리 감지부터 출력 디렉토리 지정까지 모두 자동화됩니다.
51
+ - **초기화 지원**: `react-query-helper --init`으로 기본 설정 파일을 바로 생성할 수 있습니다.
49
52
  - **Watch & Generate 모드**: 개발 중 실시간 감시(`--watch`), 초기 세팅이나 재생성 시 일괄 생성(`--generate`)을 모두 지원합니다.
50
53
  - **일관된 옵션 관리**: `queryOption`, `mutationOption`, `infiniteOption` 유틸리티로 전역 캐싱 전략과 에러 핸들링을 통일할 수 있습니다.
51
54
  - **Prettier 통합**: 생성된 파일은 자동으로 포맷팅되어 코드 리뷰 시 불필요한 변경을 줄입니다.
52
- - **템플릿 확장성**: 기본 템플릿 대신 사용자 정의 템플릿을 지정해 조직의 코딩 규칙을 쉽게 반영할 수 있습니다.
55
+ - **헬퍼 import 경로 커스터마이징**: `templateDir`로 생성 코드가 참조할 헬퍼 모듈 경로를 바꿀 수 있습니다.
56
+ - **보수적인 infinite 기본값**: `infiniteOption`은 안전한 기본 옵션만 제공하고, 실제 `pageParam` 처리 규칙은 호출부에서 override 하도록 설계되어 있습니다.
53
57
 
54
58
  ## 빠른 시작
55
59
 
@@ -61,19 +65,27 @@ bun add @uiwwsw/react-query-helper
61
65
  npm install --save-dev @uiwwsw/react-query-helper
62
66
  ```
63
67
 
64
- ### 설정 파일 만들기
68
+ ### 초기 설정 파일 생성
65
69
 
66
- 루트에 `rqh.config.ts` 파일을 생성하고 다음과 같이 채워주세요.
70
+ 설치 후 아래 명령으로 루트에 `rqh.config.ts`를 자동 생성할 수 있습니다.
71
+
72
+ ```bash
73
+ npx react-query-helper --init
74
+ # 또는
75
+ bunx react-query-helper --init
76
+ ```
77
+
78
+ 생성되는 파일 예시는 다음과 같습니다.
67
79
 
68
80
  ```ts
69
81
  // rqh.config.ts
70
- import type { AutoQueryConfig } from "./src/config";
82
+ import type { AutoQueryConfig } from "@uiwwsw/react-query-helper";
71
83
 
72
84
  const config: AutoQueryConfig = {
73
85
  sourceDir: "./libs", // API 함수들이 위치한 경로
74
86
  outputDir: "./src/options", // 생성된 코드가 저장될 경로
75
- // ignoredFiles: ["types.ts"],
76
- // templateDir: "./custom-templates",
87
+ ignoredFiles: ["domain.ts", "adaptor.ts"],
88
+ templateDir: "@uiwwsw/react-query-helper",
77
89
  };
78
90
 
79
91
  export default config;
@@ -87,6 +99,7 @@ export default config;
87
99
  // package.json
88
100
  {
89
101
  "scripts": {
102
+ "init:rqh": "react-query-helper --init",
90
103
  "watch": "react-query-helper --watch",
91
104
  "generate": "react-query-helper --generate"
92
105
  }
@@ -102,6 +115,7 @@ bun run generate # 전체 파일 일괄 생성
102
115
 
103
116
  | 명령어 | 설명 |
104
117
  | --- | --- |
118
+ | `react-query-helper --init` | 루트에 기본 `rqh.config.ts` 파일을 생성합니다. 이미 있으면 덮어쓰지 않습니다. |
105
119
  | `react-query-helper --watch` | `sourceDir`를 감시하여 변경될 때마다 코드를 갱신합니다. |
106
120
  | `react-query-helper --generate` | `sourceDir` 내 모든 API 파일을 분석하고 한 번에 코드를 생성합니다. |
107
121
  | `react-query-helper --help` | 사용 가능한 모든 옵션을 확인합니다. |
@@ -113,7 +127,33 @@ bun run generate # 전체 파일 일괄 생성
113
127
  | `sourceDir` | ✅ | API 함수가 포함된 TypeScript 디렉토리 (루트 기준 경로) |
114
128
  | `outputDir` | ✅ | 생성된 훅과 옵션 파일이 저장될 디렉토리 |
115
129
  | `ignoredFiles` | ❌ | 코드 생성에서 제외할 파일 이름 배열 |
116
- | `templateDir` | ❌ | 사용자 정의 템플릿이 위치한 디렉토리 |
130
+ | `templateDir` | ❌ | 생성된 코드에서 `queryOption` 계열을 import 할 모듈 경로 또는 상대 디렉토리 |
131
+
132
+ ## Infinite Query 기본값
133
+
134
+ `infiniteOption`은 API마다 페이지네이션 규칙이 다르기 때문에, 기본 구현에서는 `pageParam`을 자동 병합하지 않습니다.
135
+
136
+ 필요한 경우 생성된 옵션을 펼친 뒤 `queryFn`, `getNextPageParam`, `initialPageParam`을 직접 override 해서 사용하세요.
137
+
138
+ ```ts
139
+ const usersInfinite = {
140
+ ...getUsersInfiniteQueryOption({ page: 1 }),
141
+ initialPageParam: 1,
142
+ queryFn: ({ pageParam }) => getUsers({ page: pageParam }),
143
+ getNextPageParam: (lastPage) => lastPage.nextPage,
144
+ };
145
+ ```
146
+
147
+ ## 배포 방식
148
+
149
+ GitHub Actions의 npm 배포는 이제 `main` 푸시가 아니라 `v*` 태그 푸시 또는 수동 실행에서만 동작합니다.
150
+
151
+ 예시:
152
+
153
+ ```bash
154
+ git tag v1.0.3
155
+ git push origin v1.0.3
156
+ ```
117
157
 
118
158
  ## 생성 결과 예시
119
159
 
@@ -151,19 +191,27 @@ export const createUserInfiniteQueryOption = infiniteOption(
151
191
  );
152
192
  ```
153
193
 
154
- ## 템플릿 커스터마이징
194
+ ## 헬퍼 경로 커스터마이징
155
195
 
156
- 조직 맞춤 코딩 스타일이 필요하다면 템플릿 디렉토리를 지정하세요.
196
+ 조직 공용 헬퍼를 따로 두고 있다면 `templateDir`로 생성 코드의 import 경로를 바꿀 수 있습니다.
157
197
 
158
198
  ```ts
159
199
  const config: AutoQueryConfig = {
160
200
  sourceDir: "./libs",
161
201
  outputDir: "./src/options",
162
- templateDir: "./custom-templates", // EJS 템플릿 디렉토리
202
+ templateDir: "./src/query-helpers",
163
203
  };
164
204
  ```
165
205
 
166
- 템플릿 파일에서 React Query 옵션, 에러 핸들링, import 경로 등을 마음껏 수정할 수 있습니다. 변경 사항은 다음 실행 시 바로 반영됩니다.
206
+ 예를 들어 생성 파일은 기본 패키지 대신 아래처럼 지정한 경로를 import 하게 됩니다.
207
+
208
+ ```ts
209
+ import {
210
+ queryOption,
211
+ mutationOption,
212
+ infiniteOption,
213
+ } from "./src/query-helpers";
214
+ ```
167
215
 
168
216
  ## 베스트 프랙티스
169
217
 
package/dist/cli.js CHANGED
@@ -1,5 +1,4 @@
1
1
  #!/usr/bin/env node
2
- // @bun
3
2
  // node_modules/chokidar/esm/index.js
4
3
  import { stat as statcb } from "fs";
5
4
  import { stat as stat3, readdir as readdir2 } from "fs/promises";
@@ -7,9 +6,9 @@ import { EventEmitter } from "events";
7
6
  import * as sysPath2 from "path";
8
7
 
9
8
  // node_modules/readdirp/esm/index.js
10
- import { stat, lstat, readdir, realpath } from "fs/promises";
11
- import { Readable } from "stream";
12
- import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "path";
9
+ import { stat, lstat, readdir, realpath } from "node:fs/promises";
10
+ import { Readable } from "node:stream";
11
+ import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "node:path";
13
12
  var EntryTypes = {
14
13
  FILE_TYPE: "files",
15
14
  DIR_TYPE: "directories",
@@ -1573,8 +1572,8 @@ function watch(paths, options = {}) {
1573
1572
  // src/cli.ts
1574
1573
  import {
1575
1574
  basename as basename3,
1576
- dirname as dirname3,
1577
- extname as extname2,
1575
+ dirname as dirname4,
1576
+ extname as extname3,
1578
1577
  join as join4,
1579
1578
  relative as relative3,
1580
1579
  resolve as resolve3,
@@ -1590,8 +1589,10 @@ function analyzeFile(filePath) {
1590
1589
  const scriptKind = filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
1591
1590
  const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.Latest, true, scriptKind);
1592
1591
  const functionInfos = [];
1592
+ const hasExportModifier = (node) => ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
1593
1593
  ts.forEachChild(sourceFile, (node) => {
1594
1594
  if (ts.isVariableStatement(node)) {
1595
+ const isExported = hasExportModifier(node);
1595
1596
  node.declarationList.declarations.forEach((declaration) => {
1596
1597
  if (ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name)) {
1597
1598
  const initializer = declaration.initializer;
@@ -1599,7 +1600,7 @@ function analyzeFile(filePath) {
1599
1600
  const name = declaration.name.text;
1600
1601
  const parameters = initializer.parameters.map((param) => param.name.getText(sourceFile));
1601
1602
  const isAsync = initializer.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) || false;
1602
- functionInfos.push({ name, parameters, isAsync });
1603
+ functionInfos.push({ name, parameters, isAsync, isExported });
1603
1604
  }
1604
1605
  }
1605
1606
  });
@@ -1608,11 +1609,12 @@ function analyzeFile(filePath) {
1608
1609
  const name = node.name.text;
1609
1610
  const parameters = node.parameters.map((param) => param.name.getText(sourceFile));
1610
1611
  const isAsync = node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) || false;
1611
- functionInfos.push({ name, parameters, isAsync });
1612
+ const isExported = hasExportModifier(node);
1613
+ functionInfos.push({ name, parameters, isAsync, isExported });
1612
1614
  }
1613
1615
  }
1614
1616
  });
1615
- return functionInfos;
1617
+ return functionInfos.filter((info) => info.isExported);
1616
1618
  }
1617
1619
 
1618
1620
  // src/core/generator.ts
@@ -1643,28 +1645,83 @@ function generateOptionsCode(functionInfos, importPath, { keySegments, templateI
1643
1645
  }
1644
1646
 
1645
1647
  // src/config.ts
1646
- import { join as join3 } from "path";
1647
1648
  import { existsSync } from "fs";
1649
+ import { readFile, unlink, writeFile } from "fs/promises";
1650
+ import { randomUUID } from "crypto";
1651
+ import { dirname as dirname3, extname as extname2, join as join3 } from "path";
1652
+ import { pathToFileURL } from "url";
1653
+ import ts2 from "typescript";
1654
+
1655
+ class ConfigLoadError extends Error {
1656
+ configPath;
1657
+ cause;
1658
+ constructor(message, configPath, cause) {
1659
+ super(message);
1660
+ this.configPath = configPath;
1661
+ this.cause = cause;
1662
+ this.name = "ConfigLoadError";
1663
+ }
1664
+ }
1648
1665
  var defaultConfig = {
1649
1666
  sourceDir: "./libs",
1650
1667
  outputDir: "./src/options",
1651
1668
  ignoredFiles: ["domain.ts", "adaptor.ts"],
1652
1669
  templateDir: "@uiwwsw/react-query-helper"
1653
1670
  };
1671
+ var CONFIG_FILE_NAMES = [
1672
+ "rqh.config.ts",
1673
+ "rqh.config.mts",
1674
+ "rqh.config.cts",
1675
+ "rqh.config.js",
1676
+ "rqh.config.mjs",
1677
+ "rqh.config.cjs"
1678
+ ];
1679
+ var TYPESCRIPT_CONFIG_EXTENSIONS = new Set([".ts", ".mts", ".cts"]);
1680
+ async function importTypeScriptConfig(configPath) {
1681
+ const source = await readFile(configPath, "utf8");
1682
+ const transpiled = ts2.transpileModule(source, {
1683
+ compilerOptions: {
1684
+ module: ts2.ModuleKind.ESNext,
1685
+ target: ts2.ScriptTarget.ES2020,
1686
+ moduleResolution: ts2.ModuleResolutionKind.Bundler,
1687
+ esModuleInterop: true
1688
+ },
1689
+ fileName: configPath
1690
+ });
1691
+ const tempFilePath = join3(dirname3(configPath), `.rqh.config.${randomUUID()}.mjs`);
1692
+ await writeFile(tempFilePath, transpiled.outputText, "utf8");
1693
+ try {
1694
+ return await import(pathToFileURL(tempFilePath).href);
1695
+ } finally {
1696
+ await unlink(tempFilePath).catch(() => {
1697
+ return;
1698
+ });
1699
+ }
1700
+ }
1701
+ async function importConfig(configPath) {
1702
+ if (TYPESCRIPT_CONFIG_EXTENSIONS.has(extname2(configPath).toLowerCase())) {
1703
+ return importTypeScriptConfig(configPath);
1704
+ }
1705
+ return import(pathToFileURL(configPath).href);
1706
+ }
1707
+ function resolveConfigPath(cwd = process.cwd()) {
1708
+ return CONFIG_FILE_NAMES.map((fileName) => join3(cwd, fileName)).find((configPath) => existsSync(configPath));
1709
+ }
1654
1710
  async function loadConfig() {
1655
- const configPath = join3(process.cwd(), "rqh.config.ts");
1656
- if (existsSync(configPath)) {
1657
- try {
1658
- const userConfig = (await import(configPath)).default;
1659
- const mergedConfig = {
1660
- ...defaultConfig,
1661
- ...userConfig
1662
- };
1663
- return mergedConfig;
1664
- } catch (error) {
1665
- console.error("Failed to load rqh.config.js:", error);
1666
- return defaultConfig;
1711
+ const configPath = resolveConfigPath();
1712
+ if (configPath) {
1713
+ const importedConfig = await importConfig(configPath).catch((error) => {
1714
+ throw new ConfigLoadError(`Failed to load config from ${configPath}.`, configPath, error);
1715
+ });
1716
+ const userConfig = importedConfig.default ?? importedConfig;
1717
+ if (!userConfig || typeof userConfig !== "object") {
1718
+ throw new ConfigLoadError(`Config at ${configPath} must export an object.`, configPath);
1667
1719
  }
1720
+ const mergedConfig = {
1721
+ ...defaultConfig,
1722
+ ...userConfig
1723
+ };
1724
+ return mergedConfig;
1668
1725
  }
1669
1726
  return defaultConfig;
1670
1727
  }
@@ -1672,6 +1729,18 @@ async function loadConfig() {
1672
1729
  // src/cli.ts
1673
1730
  import prettier from "prettier";
1674
1731
  var config;
1732
+ var DEFAULT_CONFIG_FILE_NAME = "rqh.config.ts";
1733
+ var DEFAULT_CONFIG_TEMPLATE = `import type { AutoQueryConfig } from "@uiwwsw/react-query-helper";
1734
+
1735
+ const config: AutoQueryConfig = {
1736
+ sourceDir: "./libs",
1737
+ outputDir: "./src/options",
1738
+ ignoredFiles: ["domain.ts", "adaptor.ts"],
1739
+ templateDir: "@uiwwsw/react-query-helper",
1740
+ };
1741
+
1742
+ export default config;
1743
+ `;
1675
1744
  function ensureDirectory(directory) {
1676
1745
  if (!existsSync2(directory)) {
1677
1746
  mkdirSync(directory, { recursive: true });
@@ -1691,9 +1760,42 @@ function shouldProcess(filePath) {
1691
1760
  if (filePath.endsWith(".d.ts")) {
1692
1761
  return false;
1693
1762
  }
1694
- const extension = extname2(filePath).toLowerCase();
1763
+ const extension = extname3(filePath).toLowerCase();
1695
1764
  return extension === ".ts" || extension === ".tsx";
1696
1765
  }
1766
+ function printUsage() {
1767
+ console.log("Usage: react-query-helper [init | generate | watch | help]");
1768
+ console.log(" react-query-helper [--init | --generate | --watch | --help]");
1769
+ }
1770
+ function runInit() {
1771
+ const existingConfigPath = resolveConfigPath();
1772
+ if (existingConfigPath) {
1773
+ console.log(`Config already exists at ${existingConfigPath}`);
1774
+ return;
1775
+ }
1776
+ const configPath = resolve3(process.cwd(), DEFAULT_CONFIG_FILE_NAME);
1777
+ writeFileSync(configPath, DEFAULT_CONFIG_TEMPLATE, "utf8");
1778
+ console.log(`✅ Created ${configPath}`);
1779
+ console.log("Next steps:");
1780
+ console.log("1. Update sourceDir/outputDir if needed.");
1781
+ console.log("2. Run `react-query-helper --generate`.");
1782
+ }
1783
+ async function loadConfigOrExit() {
1784
+ try {
1785
+ return await loadConfig();
1786
+ } catch (error) {
1787
+ if (error instanceof ConfigLoadError) {
1788
+ console.error(`❌ ${error.message}`);
1789
+ if (error.cause) {
1790
+ console.error(error.cause);
1791
+ }
1792
+ } else {
1793
+ console.error("❌ Unexpected error while loading config:", error);
1794
+ }
1795
+ process.exitCode = 1;
1796
+ return null;
1797
+ }
1798
+ }
1697
1799
  async function processFile(filePath) {
1698
1800
  if (!shouldProcess(filePath)) {
1699
1801
  return;
@@ -1705,8 +1807,8 @@ async function processFile(filePath) {
1705
1807
  console.warn(`Skipping file outside of sourceDir: ${filePath}`);
1706
1808
  return;
1707
1809
  }
1708
- const relativeDir = dirname3(relativePath);
1709
- const fileName = basename3(filePath, extname2(filePath));
1810
+ const relativeDir = dirname4(relativePath);
1811
+ const fileName = basename3(filePath, extname3(filePath));
1710
1812
  if (config.ignoredFiles?.includes(basename3(filePath))) {
1711
1813
  console.log(`Skipping ignored file: ${filePath}`);
1712
1814
  return;
@@ -1714,14 +1816,14 @@ async function processFile(filePath) {
1714
1816
  try {
1715
1817
  const functionInfos = analyzeFile(filePath);
1716
1818
  if (functionInfos.length === 0) {
1717
- console.log(`No functions found in ${filePath}. Skipping code generation.`);
1819
+ console.log(`No exported functions found in ${filePath}. Skipping code generation.`);
1718
1820
  return;
1719
1821
  }
1720
1822
  const outputFolder = relativeDir === "." ? outputRoot : join4(outputRoot, relativeDir);
1721
1823
  const outputFile = join4(outputFolder, `${fileName}Options.ts`);
1722
- const generatedCode = generateOptionsCode(functionInfos, normalizeModulePath(relative3(dirname3(outputFile), filePath.replace(new RegExp(`${extname2(filePath)}$`), "")) || ".", true), {
1824
+ const generatedCode = generateOptionsCode(functionInfos, normalizeModulePath(relative3(dirname4(outputFile), filePath.replace(new RegExp(`${extname3(filePath)}$`), "")) || ".", true), {
1723
1825
  keySegments: relativeDir === "." ? [fileName] : relativeDir.split(sep).filter(Boolean),
1724
- templateImportPath: config.templateDir && config.templateDir.startsWith(".") ? normalizeModulePath(relative3(dirname3(outputFile), resolve3(process.cwd(), config.templateDir)) || ".", true) : config.templateDir ?? "@uiwwsw/react-query-helper"
1826
+ templateImportPath: config.templateDir && config.templateDir.startsWith(".") ? normalizeModulePath(relative3(dirname4(outputFile), resolve3(process.cwd(), config.templateDir)) || ".", true) : config.templateDir ?? "@uiwwsw/react-query-helper"
1725
1827
  });
1726
1828
  if (!existsSync2(outputFolder)) {
1727
1829
  mkdirSync(outputFolder, { recursive: true });
@@ -1730,14 +1832,18 @@ async function processFile(filePath) {
1730
1832
  parser: "typescript"
1731
1833
  });
1732
1834
  writeFileSync(outputFile, formattedCode, "utf8");
1733
- console.log(`\u2705 Generated options for ${filePath} -> ${outputFile}`);
1835
+ console.log(`✅ Generated options for ${filePath} -> ${outputFile}`);
1734
1836
  } catch (error) {
1735
- console.error(`\u274C Error processing file ${filePath}:`, error);
1837
+ console.error(`❌ Error processing file ${filePath}:`, error);
1736
1838
  }
1737
1839
  }
1738
1840
  async function runGenerate() {
1739
1841
  console.log("Generating options...");
1740
- config = await loadConfig();
1842
+ const loadedConfig = await loadConfigOrExit();
1843
+ if (!loadedConfig) {
1844
+ return;
1845
+ }
1846
+ config = loadedConfig;
1741
1847
  const sourcePath = join4(process.cwd(), config.sourceDir);
1742
1848
  const outputRootPath = join4(process.cwd(), config.outputDir);
1743
1849
  ensureDirectory(outputRootPath);
@@ -1759,11 +1865,15 @@ async function runGenerate() {
1759
1865
  for (const file of files) {
1760
1866
  await processFile(file);
1761
1867
  }
1762
- console.log("\u2705 Options generation completed!");
1868
+ console.log("✅ Options generation completed!");
1763
1869
  }
1764
1870
  async function runWatch() {
1765
1871
  console.log("Watching for file changes...");
1766
- config = await loadConfig();
1872
+ const loadedConfig = await loadConfigOrExit();
1873
+ if (!loadedConfig) {
1874
+ return;
1875
+ }
1876
+ config = loadedConfig;
1767
1877
  const sourcePath = join4(process.cwd(), config.sourceDir);
1768
1878
  const outputRootPath = join4(process.cwd(), config.outputDir);
1769
1879
  ensureDirectory(outputRootPath);
@@ -1788,28 +1898,33 @@ async function runWatch() {
1788
1898
  if (!shouldProcess(filePath)) {
1789
1899
  return;
1790
1900
  }
1791
- console.log(`\uD83D\uDDD1\uFE0F File unlinked: ${filePath}`);
1901
+ console.log(`\uD83D\uDDD1️ File unlinked: ${filePath}`);
1792
1902
  const sourceRoot = resolve3(process.cwd(), config.sourceDir);
1793
1903
  const outputRoot = resolve3(process.cwd(), config.outputDir);
1794
1904
  const relativePath = relative3(sourceRoot, filePath);
1795
1905
  if (relativePath.startsWith("..")) {
1796
1906
  return;
1797
1907
  }
1798
- const relativeDir = dirname3(relativePath);
1799
- const fileName = basename3(filePath, extname2(filePath));
1908
+ const relativeDir = dirname4(relativePath);
1909
+ const fileName = basename3(filePath, extname3(filePath));
1800
1910
  const outputFile = join4(relativeDir === "." ? outputRoot : join4(outputRoot, relativeDir), `${fileName}Options.ts`);
1801
1911
  if (existsSync2(outputFile)) {
1802
1912
  unlinkSync(outputFile);
1803
- console.log(`\uD83D\uDDD1\uFE0F Deleted ${outputFile}`);
1913
+ console.log(`\uD83D\uDDD1️ Deleted ${outputFile}`);
1804
1914
  }
1805
- }).on("error", (error) => console.error(`\u274C Watcher error: ${error}`));
1915
+ }).on("error", (error) => console.error(`❌ Watcher error: ${error}`));
1806
1916
  console.log(`\uD83D\uDC40 Watching ${sourcePath} for changes.`);
1807
1917
  }
1808
1918
  var args = process.argv.slice(2);
1809
- if (args.includes("--watch")) {
1919
+ var hasCommand = (...values) => values.some((value) => args.includes(value));
1920
+ if (hasCommand("help", "--help")) {
1921
+ printUsage();
1922
+ } else if (hasCommand("init", "--init")) {
1923
+ runInit();
1924
+ } else if (hasCommand("watch", "--watch")) {
1810
1925
  runWatch();
1811
- } else if (args.includes("--generate")) {
1926
+ } else if (hasCommand("generate", "--generate")) {
1812
1927
  runGenerate();
1813
1928
  } else {
1814
- console.log("Usage: bun run src/cli.ts [--watch | --generate]");
1929
+ printUsage();
1815
1930
  }
package/dist/config.d.ts CHANGED
@@ -1,8 +1,14 @@
1
+ export declare class ConfigLoadError extends Error {
2
+ readonly configPath?: string | undefined;
3
+ readonly cause?: unknown | undefined;
4
+ constructor(message: string, configPath?: string | undefined, cause?: unknown | undefined);
5
+ }
1
6
  export interface AutoQueryConfig {
2
7
  sourceDir: string;
3
8
  outputDir: string;
4
9
  templateDir?: string;
5
10
  ignoredFiles?: string[];
6
11
  }
12
+ export declare function resolveConfigPath(cwd?: string): string | undefined;
7
13
  export declare function loadConfig(): Promise<AutoQueryConfig>;
8
14
  //# sourceMappingURL=config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AASD,wBAAsB,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC,CAoB3D"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAOA,qBAAa,eAAgB,SAAQ,KAAK;aAGtB,UAAU,CAAC,EAAE,MAAM;aACnB,KAAK,CAAC,EAAE,OAAO;gBAF/B,OAAO,EAAE,MAAM,EACC,UAAU,CAAC,EAAE,MAAM,YAAA,EACnB,KAAK,CAAC,EAAE,OAAO,YAAA;CAKlC;AAED,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AAsDD,wBAAgB,iBAAiB,CAAC,GAAG,SAAgB,sBAIpD;AAED,wBAAsB,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC,CA4B3D"}
@@ -2,6 +2,7 @@ export interface FunctionInfo {
2
2
  name: string;
3
3
  parameters: string[];
4
4
  isAsync: boolean;
5
+ isExported: boolean;
5
6
  }
6
7
  export declare function analyzeFile(filePath: string): FunctionInfo[];
7
8
  //# sourceMappingURL=analyzer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"analyzer.d.ts","sourceRoot":"","sources":["../../src/core/analyzer.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,YAAY,EAAE,CAqC5D"}
1
+ {"version":3,"file":"analyzer.d.ts","sourceRoot":"","sources":["../../src/core/analyzer.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,YAAY,EAAE,CA4C5D"}
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- // @bun
2
1
  // src/core/analyzer.ts
3
2
  import ts from "typescript";
4
3
  import { readFileSync } from "fs";
@@ -7,8 +6,10 @@ function analyzeFile(filePath) {
7
6
  const scriptKind = filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
8
7
  const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.Latest, true, scriptKind);
9
8
  const functionInfos = [];
9
+ const hasExportModifier = (node) => ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
10
10
  ts.forEachChild(sourceFile, (node) => {
11
11
  if (ts.isVariableStatement(node)) {
12
+ const isExported = hasExportModifier(node);
12
13
  node.declarationList.declarations.forEach((declaration) => {
13
14
  if (ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name)) {
14
15
  const initializer = declaration.initializer;
@@ -16,7 +17,7 @@ function analyzeFile(filePath) {
16
17
  const name = declaration.name.text;
17
18
  const parameters = initializer.parameters.map((param) => param.name.getText(sourceFile));
18
19
  const isAsync = initializer.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) || false;
19
- functionInfos.push({ name, parameters, isAsync });
20
+ functionInfos.push({ name, parameters, isAsync, isExported });
20
21
  }
21
22
  }
22
23
  });
@@ -25,11 +26,12 @@ function analyzeFile(filePath) {
25
26
  const name = node.name.text;
26
27
  const parameters = node.parameters.map((param) => param.name.getText(sourceFile));
27
28
  const isAsync = node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) || false;
28
- functionInfos.push({ name, parameters, isAsync });
29
+ const isExported = hasExportModifier(node);
30
+ functionInfos.push({ name, parameters, isAsync, isExported });
29
31
  }
30
32
  }
31
33
  });
32
- return functionInfos;
34
+ return functionInfos.filter((info) => info.isExported);
33
35
  }
34
36
  // src/core/generator.ts
35
37
  function generateOptionsCode(functionInfos, importPath, { keySegments, templateImportPath }) {
@@ -58,28 +60,83 @@ function generateOptionsCode(functionInfos, importPath, { keySegments, templateI
58
60
  return newContent;
59
61
  }
60
62
  // src/config.ts
61
- import { join } from "path";
62
63
  import { existsSync } from "fs";
64
+ import { readFile, unlink, writeFile } from "fs/promises";
65
+ import { randomUUID } from "crypto";
66
+ import { dirname, extname, join } from "path";
67
+ import { pathToFileURL } from "url";
68
+ import ts2 from "typescript";
69
+
70
+ class ConfigLoadError extends Error {
71
+ configPath;
72
+ cause;
73
+ constructor(message, configPath, cause) {
74
+ super(message);
75
+ this.configPath = configPath;
76
+ this.cause = cause;
77
+ this.name = "ConfigLoadError";
78
+ }
79
+ }
63
80
  var defaultConfig = {
64
81
  sourceDir: "./libs",
65
82
  outputDir: "./src/options",
66
83
  ignoredFiles: ["domain.ts", "adaptor.ts"],
67
84
  templateDir: "@uiwwsw/react-query-helper"
68
85
  };
86
+ var CONFIG_FILE_NAMES = [
87
+ "rqh.config.ts",
88
+ "rqh.config.mts",
89
+ "rqh.config.cts",
90
+ "rqh.config.js",
91
+ "rqh.config.mjs",
92
+ "rqh.config.cjs"
93
+ ];
94
+ var TYPESCRIPT_CONFIG_EXTENSIONS = new Set([".ts", ".mts", ".cts"]);
95
+ async function importTypeScriptConfig(configPath) {
96
+ const source = await readFile(configPath, "utf8");
97
+ const transpiled = ts2.transpileModule(source, {
98
+ compilerOptions: {
99
+ module: ts2.ModuleKind.ESNext,
100
+ target: ts2.ScriptTarget.ES2020,
101
+ moduleResolution: ts2.ModuleResolutionKind.Bundler,
102
+ esModuleInterop: true
103
+ },
104
+ fileName: configPath
105
+ });
106
+ const tempFilePath = join(dirname(configPath), `.rqh.config.${randomUUID()}.mjs`);
107
+ await writeFile(tempFilePath, transpiled.outputText, "utf8");
108
+ try {
109
+ return await import(pathToFileURL(tempFilePath).href);
110
+ } finally {
111
+ await unlink(tempFilePath).catch(() => {
112
+ return;
113
+ });
114
+ }
115
+ }
116
+ async function importConfig(configPath) {
117
+ if (TYPESCRIPT_CONFIG_EXTENSIONS.has(extname(configPath).toLowerCase())) {
118
+ return importTypeScriptConfig(configPath);
119
+ }
120
+ return import(pathToFileURL(configPath).href);
121
+ }
122
+ function resolveConfigPath(cwd = process.cwd()) {
123
+ return CONFIG_FILE_NAMES.map((fileName) => join(cwd, fileName)).find((configPath) => existsSync(configPath));
124
+ }
69
125
  async function loadConfig() {
70
- const configPath = join(process.cwd(), "rqh.config.ts");
71
- if (existsSync(configPath)) {
72
- try {
73
- const userConfig = (await import(configPath)).default;
74
- const mergedConfig = {
75
- ...defaultConfig,
76
- ...userConfig
77
- };
78
- return mergedConfig;
79
- } catch (error) {
80
- console.error("Failed to load rqh.config.js:", error);
81
- return defaultConfig;
126
+ const configPath = resolveConfigPath();
127
+ if (configPath) {
128
+ const importedConfig = await importConfig(configPath).catch((error) => {
129
+ throw new ConfigLoadError(`Failed to load config from ${configPath}.`, configPath, error);
130
+ });
131
+ const userConfig = importedConfig.default ?? importedConfig;
132
+ if (!userConfig || typeof userConfig !== "object") {
133
+ throw new ConfigLoadError(`Config at ${configPath} must export an object.`, configPath);
82
134
  }
135
+ const mergedConfig = {
136
+ ...defaultConfig,
137
+ ...userConfig
138
+ };
139
+ return mergedConfig;
83
140
  }
84
141
  return defaultConfig;
85
142
  }
@@ -87,7 +144,7 @@ async function loadConfig() {
87
144
  var queryOption = (key, fn) => {
88
145
  return (...payload) => ({
89
146
  queryKey: [...key, ...payload],
90
- queryFn: () => fn(...payload),
147
+ queryFn: () => Promise.resolve(fn(...payload)),
91
148
  gcTime: Infinity,
92
149
  refetchOnWindowFocus: false
93
150
  });
@@ -95,34 +152,36 @@ var queryOption = (key, fn) => {
95
152
  var mutationOption = (key, fn) => {
96
153
  return () => ({
97
154
  mutationKey: key,
98
- mutationFn: fn
155
+ mutationFn: (variables) => {
156
+ if (Array.isArray(variables)) {
157
+ return Promise.resolve(fn(...variables));
158
+ }
159
+ if (typeof variables === "undefined") {
160
+ return Promise.resolve(fn(...[]));
161
+ }
162
+ return Promise.resolve(fn(...[variables]));
163
+ }
99
164
  });
100
165
  };
101
166
  var infiniteOption = (key, fn) => {
102
167
  return (...payload) => ({
103
168
  queryKey: [...key, ...payload],
104
- queryFn: ({ pageParam }) => {
105
- if (!pageParam)
106
- return fn(...payload);
107
- payload.map((param, index) => {
108
- if (typeof param === "object" && param !== null) {
109
- payload[index] = { ...param, ...pageParam };
110
- return param;
111
- }
112
- });
113
- return fn(...payload);
169
+ queryFn: () => Promise.resolve(fn(...payload)),
170
+ getNextPageParam: () => {
171
+ return;
114
172
  },
115
- getNextPageParam: (lastPage) => lastPage,
116
173
  initialPageParam: undefined,
117
174
  staleTime: Infinity,
118
175
  refetchOnWindowFocus: false
119
176
  });
120
177
  };
121
178
  export {
179
+ resolveConfigPath,
122
180
  queryOption,
123
181
  mutationOption,
124
182
  loadConfig,
125
183
  infiniteOption,
126
184
  generateOptionsCode,
127
- analyzeFile
185
+ analyzeFile,
186
+ ConfigLoadError
128
187
  };
@@ -1,7 +1,10 @@
1
- import type { MutationFunction, UseInfiniteQueryOptions, UseMutationOptions, UseQueryOptions } from "@tanstack/react-query";
2
- type QueryOptionType = <T extends unknown[], J>(key: readonly unknown[], fn: (...payload: T) => Promise<J>) => (...payload: T) => UseQueryOptions<J>;
3
- type MutationOptionType = <T, K>(key: readonly unknown[], fn: MutationFunction<T, K>) => () => UseMutationOptions<T, unknown, K>;
4
- type InfiniteOptionType = <T extends unknown[], K>(key: readonly unknown[], fn: (...payload: T) => Promise<K>) => (...payload: T) => UseInfiniteQueryOptions<K, unknown, K>;
1
+ import type { UseInfiniteQueryOptions, UseMutationOptions, UseQueryOptions } from "@tanstack/react-query";
2
+ type MaybePromise<T> = T | Promise<T>;
3
+ type AnyFn<TArgs extends unknown[] = unknown[], TResult = unknown> = (...payload: TArgs) => MaybePromise<TResult>;
4
+ type MutationVariables<TArgs extends unknown[]> = TArgs extends [] ? void : TArgs extends [infer Only] ? Only : TArgs;
5
+ type QueryOptionType = <T extends unknown[], J>(key: readonly unknown[], fn: AnyFn<T, J>) => (...payload: T) => UseQueryOptions<J>;
6
+ type MutationOptionType = <TArgs extends unknown[], TResult>(key: readonly unknown[], fn: AnyFn<TArgs, TResult>) => () => UseMutationOptions<TResult, unknown, MutationVariables<TArgs>>;
7
+ type InfiniteOptionType = <T extends unknown[], K>(key: readonly unknown[], fn: AnyFn<T, K>) => (...payload: T) => UseInfiniteQueryOptions<K>;
5
8
  export declare const queryOption: QueryOptionType;
6
9
  export declare const mutationOption: MutationOptionType;
7
10
  export declare const infiniteOption: InfiniteOptionType;
@@ -1 +1 @@
1
- {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../src/utils/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,eAAe,EAChB,MAAM,uBAAuB,CAAC;AAE/B,KAAK,eAAe,GAAG,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,EAC5C,GAAG,EAAE,SAAS,OAAO,EAAE,EACvB,EAAE,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,KAC9B,CAAC,GAAG,OAAO,EAAE,CAAC,KAAK,eAAe,CAAC,CAAC,CAAC,CAAC;AAC3C,KAAK,kBAAkB,GAAG,CAAC,CAAC,EAAE,CAAC,EAC7B,GAAG,EAAE,SAAS,OAAO,EAAE,EACvB,EAAE,EAAE,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAC,KACvB,MAAM,kBAAkB,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;AAC7C,KAAK,kBAAkB,GAAG,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,EAC/C,GAAG,EAAE,SAAS,OAAO,EAAE,EACvB,EAAE,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,KAC9B,CAAC,GAAG,OAAO,EAAE,CAAC,KAAK,uBAAuB,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;AAE/D,eAAO,MAAM,WAAW,EAAE,eAYzB,CAAC;AAEF,eAAO,MAAM,cAAc,EAAE,kBAS5B,CAAC;AACF,eAAO,MAAM,cAAc,EAAE,kBAwB5B,CAAC"}
1
+ {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../src/utils/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,uBAAuB,EACvB,kBAAkB,EAClB,eAAe,EAChB,MAAM,uBAAuB,CAAC;AAE/B,KAAK,YAAY,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AACtC,KAAK,KAAK,CAAC,KAAK,SAAS,OAAO,EAAE,GAAG,OAAO,EAAE,EAAE,OAAO,GAAG,OAAO,IAAI,CACnE,GAAG,OAAO,EAAE,KAAK,KACd,YAAY,CAAC,OAAO,CAAC,CAAC;AAC3B,KAAK,iBAAiB,CAAC,KAAK,SAAS,OAAO,EAAE,IAAI,KAAK,SAAS,EAAE,GAC9D,IAAI,GACJ,KAAK,SAAS,CAAC,MAAM,IAAI,CAAC,GACxB,IAAI,GACJ,KAAK,CAAC;AAEZ,KAAK,eAAe,GAAG,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,EAC5C,GAAG,EAAE,SAAS,OAAO,EAAE,EACvB,EAAE,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,KACZ,CAAC,GAAG,OAAO,EAAE,CAAC,KAAK,eAAe,CAAC,CAAC,CAAC,CAAC;AAE3C,KAAK,kBAAkB,GAAG,CAAC,KAAK,SAAS,OAAO,EAAE,EAAE,OAAO,EACzD,GAAG,EAAE,SAAS,OAAO,EAAE,EACvB,EAAE,EAAE,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,KACtB,MAAM,kBAAkB,CAAC,OAAO,EAAE,OAAO,EAAE,iBAAiB,CAAC,KAAK,CAAC,CAAC,CAAC;AAE1E,KAAK,kBAAkB,GAAG,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,EAC/C,GAAG,EAAE,SAAS,OAAO,EAAE,EACvB,EAAE,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,KACZ,CAAC,GAAG,OAAO,EAAE,CAAC,KAAK,uBAAuB,CAAC,CAAC,CAAC,CAAC;AAEnD,eAAO,MAAM,WAAW,EAAE,eAYzB,CAAC;AAEF,eAAO,MAAM,cAAc,EAAE,kBAmB5B,CAAC;AACF,eAAO,MAAM,cAAc,EAAE,kBAe5B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uiwwsw/react-query-helper",
3
- "version": "1.0.1",
3
+ "version": "1.0.10",
4
4
  "module": "dist/index.js",
5
5
  "type": "module",
6
6
  "types": "dist/index.d.ts",
@@ -31,7 +31,7 @@
31
31
  "dist"
32
32
  ],
33
33
  "bin": {
34
- "react-query-helper": "./dist/cli.js"
34
+ "react-query-helper": "dist/cli.js"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "scripts": {
46
46
  "start": "bun run src/index.ts",
47
- "build": "tsc && bun build src/cli.ts --outdir dist --target bun --external typescript --external prettier && bun build src/index.ts --outdir dist --target bun --external typescript --external prettier && node scripts/prepend-shebang.cjs dist/cli.js",
47
+ "build": "tsc && bun build src/cli.ts --outdir dist --target node --external typescript --external prettier && bun build src/index.ts --outdir dist --target node --external typescript --external prettier && node scripts/prepend-shebang.cjs dist/cli.js",
48
48
  "dev": "bun run src/cli.ts --watch",
49
49
  "generate": "bun run src/cli.ts --generate"
50
50
  },
@@ -60,5 +60,8 @@
60
60
  "fs": "^0.0.1-security",
61
61
  "prettier": "^3.6.2",
62
62
  "typescript": "^5.8.3"
63
+ },
64
+ "engines": {
65
+ "node": ">=24"
63
66
  }
64
- }
67
+ }