@uiwwsw/react-query-helper 1.2.7 → 2.0.1
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/CHANGELOG.md +46 -0
- package/README.md +107 -268
- package/README_EN.md +168 -0
- package/dist/cli.d.ts +0 -1
- package/dist/cli.js +681 -2031
- package/dist/config-loader.d.ts +10 -6
- package/dist/config-loader.js +201 -0
- package/dist/config.d.ts +2 -3
- package/dist/core/analyzer.d.ts +3 -1
- package/dist/core/analyzer.js +123 -0
- package/dist/core/generator.d.ts +6 -3
- package/dist/core/generator.js +121 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +113 -35
- package/dist/utils/query.d.ts +72 -11
- package/package.json +29 -20
- package/dist/cli.d.ts.map +0 -1
- package/dist/config-loader.d.ts.map +0 -1
- package/dist/config.d.ts.map +0 -1
- package/dist/core/analyzer.d.ts.map +0 -1
- package/dist/core/generator.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/utils/query.d.ts.map +0 -1
package/dist/config-loader.d.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import type { AutoQueryConfig } from "./config";
|
|
1
|
+
import type { AutoQueryConfig } from "./config.js";
|
|
2
|
+
import type { FunctionInfo } from "./core/analyzer.js";
|
|
2
3
|
export declare class ConfigLoadError extends Error {
|
|
3
4
|
readonly configPath?: string | undefined;
|
|
4
5
|
readonly cause?: unknown | undefined;
|
|
5
6
|
constructor(message: string, configPath?: string | undefined, cause?: unknown | undefined);
|
|
6
7
|
}
|
|
7
8
|
export interface CustomAnalyzerModule {
|
|
8
|
-
analyzeFile: (filePath: string, config: ResolvedAutoQueryConfig) => Promise<
|
|
9
|
+
analyzeFile: (filePath: string, config: ResolvedAutoQueryConfig) => Promise<FunctionInfo[]> | FunctionInfo[];
|
|
9
10
|
}
|
|
10
11
|
export interface CustomTemplateModule {
|
|
11
12
|
generateOptionsCode: (params: {
|
|
12
|
-
functionInfos:
|
|
13
|
+
functionInfos: FunctionInfo[];
|
|
13
14
|
importPath: string;
|
|
14
15
|
keySegments: string[];
|
|
15
16
|
fileName: string;
|
|
@@ -22,10 +23,13 @@ export interface ResolvedAutoQueryConfig extends AutoQueryConfig {
|
|
|
22
23
|
configDir: string;
|
|
23
24
|
resolvedSourceDir: string;
|
|
24
25
|
resolvedOutputDir: string;
|
|
25
|
-
resolvedTemplateDir
|
|
26
|
+
resolvedTemplateDir: string;
|
|
26
27
|
resolvedCustomAnalyzerPath?: string;
|
|
27
28
|
resolvedCustomTemplatePath?: string;
|
|
28
29
|
}
|
|
29
30
|
export declare function resolveConfigPath(cwd?: string): string | undefined;
|
|
30
|
-
export declare function
|
|
31
|
-
|
|
31
|
+
export declare function loadModule(specifier: string, configDir: string): Promise<Record<string, unknown>>;
|
|
32
|
+
export declare function loadConfig(options?: {
|
|
33
|
+
cwd?: string;
|
|
34
|
+
configPath?: string;
|
|
35
|
+
}): Promise<ResolvedAutoQueryConfig>;
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// src/config-loader.ts
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { dirname, join, resolve, isAbsolute } from "node:path";
|
|
4
|
+
import { createJiti } from "jiti";
|
|
5
|
+
|
|
6
|
+
// src/core/generator.ts
|
|
7
|
+
import ts from "typescript";
|
|
8
|
+
function validIdentifier(name) {
|
|
9
|
+
const scanner = ts.createScanner(
|
|
10
|
+
ts.ScriptTarget.Latest,
|
|
11
|
+
false,
|
|
12
|
+
ts.LanguageVariant.Standard,
|
|
13
|
+
name
|
|
14
|
+
);
|
|
15
|
+
const token = scanner.scan();
|
|
16
|
+
return (token === ts.SyntaxKind.Identifier || token >= ts.SyntaxKind.AbstractKeyword && token <= ts.SyntaxKind.OfKeyword && token !== ts.SyntaxKind.AwaitKeyword) && scanner.getTokenText() === name && scanner.scan() === ts.SyntaxKind.EndOfFileToken;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// src/config-loader.ts
|
|
20
|
+
var ConfigLoadError = class extends Error {
|
|
21
|
+
constructor(message, configPath, cause) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.configPath = configPath;
|
|
24
|
+
this.cause = cause;
|
|
25
|
+
this.name = "ConfigLoadError";
|
|
26
|
+
}
|
|
27
|
+
configPath;
|
|
28
|
+
cause;
|
|
29
|
+
};
|
|
30
|
+
var configNames = ["ts", "mts", "cts", "js", "mjs", "cjs"].map(
|
|
31
|
+
(ext) => `rqh.config.${ext}`
|
|
32
|
+
);
|
|
33
|
+
function resolveConfigPath(cwd = process.cwd()) {
|
|
34
|
+
let dir = resolve(cwd);
|
|
35
|
+
while (true) {
|
|
36
|
+
const found = configNames.map((name) => join(dir, name)).filter(existsSync);
|
|
37
|
+
if (found.length > 1)
|
|
38
|
+
throw new ConfigLoadError(
|
|
39
|
+
`Multiple config files found: ${found.join(", ")}`
|
|
40
|
+
);
|
|
41
|
+
if (found[0]) return found[0];
|
|
42
|
+
const parent = dirname(dir);
|
|
43
|
+
if (parent === dir) return;
|
|
44
|
+
dir = parent;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async function loadModule(specifier, configDir) {
|
|
48
|
+
const jiti = createJiti(join(configDir, "rqh.loader.cjs"), {
|
|
49
|
+
interopDefault: false,
|
|
50
|
+
moduleCache: false,
|
|
51
|
+
fsCache: false
|
|
52
|
+
});
|
|
53
|
+
return await jiti.import(specifier);
|
|
54
|
+
}
|
|
55
|
+
function object(value, label) {
|
|
56
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
57
|
+
throw new Error(`${label} must be an object.`);
|
|
58
|
+
}
|
|
59
|
+
function keys(value, allowed, label) {
|
|
60
|
+
for (const key of Object.keys(value))
|
|
61
|
+
if (!allowed.includes(key))
|
|
62
|
+
throw new Error(`Unknown ${label} option: ${key}`);
|
|
63
|
+
}
|
|
64
|
+
function string(value, label) {
|
|
65
|
+
if (typeof value !== "string" || !value.trim())
|
|
66
|
+
throw new Error(`${label} must be a non-empty string.`);
|
|
67
|
+
}
|
|
68
|
+
function strings(value, label) {
|
|
69
|
+
if (!Array.isArray(value) || value.some((v) => typeof v !== "string" || !v.trim()))
|
|
70
|
+
throw new Error(`${label} must be an array of non-empty strings.`);
|
|
71
|
+
}
|
|
72
|
+
function choice(value, allowed, label) {
|
|
73
|
+
if (!allowed.includes(value))
|
|
74
|
+
throw new Error(`${label} must be one of: ${allowed.join(", ")}`);
|
|
75
|
+
}
|
|
76
|
+
function validate(value) {
|
|
77
|
+
object(value, "Config");
|
|
78
|
+
keys(
|
|
79
|
+
value,
|
|
80
|
+
[
|
|
81
|
+
"sourceDir",
|
|
82
|
+
"outputDir",
|
|
83
|
+
"templateDir",
|
|
84
|
+
"sourceImportAlias",
|
|
85
|
+
"ignoredFiles",
|
|
86
|
+
"analyzer",
|
|
87
|
+
"template",
|
|
88
|
+
"customAnalyzerPath",
|
|
89
|
+
"customTemplatePath"
|
|
90
|
+
],
|
|
91
|
+
"config"
|
|
92
|
+
);
|
|
93
|
+
for (const field of [
|
|
94
|
+
"sourceDir",
|
|
95
|
+
"outputDir",
|
|
96
|
+
"templateDir",
|
|
97
|
+
"sourceImportAlias",
|
|
98
|
+
"customAnalyzerPath",
|
|
99
|
+
"customTemplatePath"
|
|
100
|
+
])
|
|
101
|
+
if (field in value) string(value[field], field);
|
|
102
|
+
if ("ignoredFiles" in value) strings(value.ignoredFiles, "ignoredFiles");
|
|
103
|
+
if (value.analyzer !== void 0) {
|
|
104
|
+
const a = value.analyzer;
|
|
105
|
+
object(a, "analyzer");
|
|
106
|
+
keys(
|
|
107
|
+
a,
|
|
108
|
+
["exportFilter", "functionMatchMode", "includeNames", "excludeNames"],
|
|
109
|
+
"analyzer"
|
|
110
|
+
);
|
|
111
|
+
if (a.exportFilter !== void 0)
|
|
112
|
+
choice(a.exportFilter, ["exported-only", "all"], "exportFilter");
|
|
113
|
+
if (a.functionMatchMode !== void 0)
|
|
114
|
+
choice(
|
|
115
|
+
a.functionMatchMode,
|
|
116
|
+
["all", "async-only", "sync-only"],
|
|
117
|
+
"functionMatchMode"
|
|
118
|
+
);
|
|
119
|
+
for (const field of ["includeNames", "excludeNames"])
|
|
120
|
+
if (a[field] !== void 0) strings(a[field], field);
|
|
121
|
+
}
|
|
122
|
+
if (value.template !== void 0) {
|
|
123
|
+
const t = value.template;
|
|
124
|
+
object(t, "template");
|
|
125
|
+
keys(
|
|
126
|
+
t,
|
|
127
|
+
[
|
|
128
|
+
"enabledArtifacts",
|
|
129
|
+
"artifactStrategy",
|
|
130
|
+
"keyStyle",
|
|
131
|
+
"importNames",
|
|
132
|
+
"outputNames",
|
|
133
|
+
"artifactsByName"
|
|
134
|
+
],
|
|
135
|
+
"template"
|
|
136
|
+
);
|
|
137
|
+
const artifacts = ["query", "mutation", "infinite"];
|
|
138
|
+
const artifactList = (v) => {
|
|
139
|
+
strings(v, "artifacts");
|
|
140
|
+
v.forEach((a) => choice(a, artifacts, "artifact"));
|
|
141
|
+
};
|
|
142
|
+
if (t.enabledArtifacts !== void 0) artifactList(t.enabledArtifacts);
|
|
143
|
+
if (t.artifactStrategy !== void 0)
|
|
144
|
+
choice(t.artifactStrategy, ["all", "smart"], "artifactStrategy");
|
|
145
|
+
if (t.keyStyle !== void 0)
|
|
146
|
+
choice(t.keyStyle, ["path", "file-only", "function-only"], "keyStyle");
|
|
147
|
+
if (t.artifactsByName !== void 0) {
|
|
148
|
+
object(t.artifactsByName, "artifactsByName");
|
|
149
|
+
Object.values(t.artifactsByName).forEach(artifactList);
|
|
150
|
+
}
|
|
151
|
+
for (const field of ["importNames", "outputNames"])
|
|
152
|
+
if (t[field] !== void 0) {
|
|
153
|
+
object(t[field], field);
|
|
154
|
+
keys(t[field], artifacts, field);
|
|
155
|
+
for (const name of Object.values(t[field])) {
|
|
156
|
+
if (typeof name !== "string" || !validIdentifier(name))
|
|
157
|
+
throw new Error(`Invalid identifier in ${field}: ${name}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async function loadConfig(options = {}) {
|
|
163
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
164
|
+
const configPath = options.configPath ? resolve(cwd, options.configPath) : resolveConfigPath(cwd);
|
|
165
|
+
try {
|
|
166
|
+
const mod = configPath ? await loadModule(configPath, dirname(configPath)) : { default: {} };
|
|
167
|
+
const user = configPath && /\.(cts|cjs|js)$/.test(configPath) ? mod?.default ?? mod : mod?.default;
|
|
168
|
+
validate(user);
|
|
169
|
+
const config = {
|
|
170
|
+
sourceDir: "./libs",
|
|
171
|
+
outputDir: "./src/options",
|
|
172
|
+
ignoredFiles: ["domain.ts", "adaptor.ts"],
|
|
173
|
+
templateDir: "@uiwwsw/react-query-helper",
|
|
174
|
+
...user
|
|
175
|
+
};
|
|
176
|
+
const configDir = configPath ? dirname(configPath) : cwd;
|
|
177
|
+
const modulePath = (path) => path?.startsWith(".") || path && isAbsolute(path) ? resolve(configDir, path) : path;
|
|
178
|
+
return {
|
|
179
|
+
...config,
|
|
180
|
+
configDir,
|
|
181
|
+
configPath,
|
|
182
|
+
resolvedSourceDir: resolve(configDir, config.sourceDir),
|
|
183
|
+
resolvedOutputDir: resolve(configDir, config.outputDir),
|
|
184
|
+
resolvedTemplateDir: modulePath(config.templateDir),
|
|
185
|
+
resolvedCustomAnalyzerPath: modulePath(config.customAnalyzerPath),
|
|
186
|
+
resolvedCustomTemplatePath: modulePath(config.customTemplatePath)
|
|
187
|
+
};
|
|
188
|
+
} catch (error) {
|
|
189
|
+
throw new ConfigLoadError(
|
|
190
|
+
`Invalid configuration ${configPath ?? "(defaults)"}: ${error instanceof Error ? error.message : String(error)}`,
|
|
191
|
+
configPath,
|
|
192
|
+
error
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
export {
|
|
197
|
+
ConfigLoadError,
|
|
198
|
+
loadConfig,
|
|
199
|
+
loadModule,
|
|
200
|
+
resolveConfigPath
|
|
201
|
+
};
|
package/dist/config.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { AnalyzerConfig } from "./core/analyzer";
|
|
2
|
-
import type { TemplateConfig } from "./core/generator";
|
|
1
|
+
import type { AnalyzerConfig } from "./core/analyzer.js";
|
|
2
|
+
import type { TemplateConfig } from "./core/generator.js";
|
|
3
3
|
export interface AutoQueryConfig {
|
|
4
4
|
sourceDir: string;
|
|
5
5
|
outputDir: string;
|
|
@@ -11,4 +11,3 @@ export interface AutoQueryConfig {
|
|
|
11
11
|
customAnalyzerPath?: string;
|
|
12
12
|
customTemplatePath?: string;
|
|
13
13
|
}
|
|
14
|
-
//# sourceMappingURL=config.d.ts.map
|
package/dist/core/analyzer.d.ts
CHANGED
|
@@ -8,9 +8,11 @@ export interface AnalyzerConfig {
|
|
|
8
8
|
}
|
|
9
9
|
export interface FunctionInfo {
|
|
10
10
|
name: string;
|
|
11
|
+
importName?: string;
|
|
11
12
|
parameters: string[];
|
|
13
|
+
optionalParameters?: boolean[];
|
|
14
|
+
restParameterIndex?: number;
|
|
12
15
|
isAsync: boolean;
|
|
13
16
|
isExported: boolean;
|
|
14
17
|
}
|
|
15
18
|
export declare function analyzeFile(filePath: string, config?: AnalyzerConfig): FunctionInfo[];
|
|
16
|
-
//# sourceMappingURL=analyzer.d.ts.map
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// src/core/analyzer.ts
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
function unwrap(node) {
|
|
5
|
+
if (!node) return;
|
|
6
|
+
if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) return node;
|
|
7
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node)) {
|
|
8
|
+
return unwrap(node.expression);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function has(node, kind) {
|
|
12
|
+
return ts.canHaveModifiers(node) && ts.getModifiers(node)?.some((m) => m.kind === kind);
|
|
13
|
+
}
|
|
14
|
+
function analyzeFile(filePath, config = {}) {
|
|
15
|
+
const source = ts.createSourceFile(
|
|
16
|
+
filePath,
|
|
17
|
+
readFileSync(filePath, "utf8"),
|
|
18
|
+
ts.ScriptTarget.Latest,
|
|
19
|
+
true,
|
|
20
|
+
filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
|
|
21
|
+
);
|
|
22
|
+
const diagnostics = source.parseDiagnostics;
|
|
23
|
+
if (diagnostics.length)
|
|
24
|
+
throw new Error(
|
|
25
|
+
ts.formatDiagnosticsWithColorAndContext(diagnostics, {
|
|
26
|
+
getCanonicalFileName: (f) => f,
|
|
27
|
+
getCurrentDirectory: () => process.cwd(),
|
|
28
|
+
getNewLine: () => "\n"
|
|
29
|
+
})
|
|
30
|
+
);
|
|
31
|
+
const functions = /* @__PURE__ */ new Map();
|
|
32
|
+
const exports = /* @__PURE__ */ new Map();
|
|
33
|
+
const identifiers = /* @__PURE__ */ new Set();
|
|
34
|
+
const collectIdentifiers = (node) => {
|
|
35
|
+
if (ts.isIdentifier(node)) identifiers.add(node.text);
|
|
36
|
+
ts.forEachChild(node, collectIdentifiers);
|
|
37
|
+
};
|
|
38
|
+
collectIdentifiers(source);
|
|
39
|
+
const anonymousName = () => {
|
|
40
|
+
let name = "defaultExport";
|
|
41
|
+
while (identifiers.has(name)) name += "_";
|
|
42
|
+
identifiers.add(name);
|
|
43
|
+
return name;
|
|
44
|
+
};
|
|
45
|
+
function collect(name, fn) {
|
|
46
|
+
if (!fn.body) return;
|
|
47
|
+
functions.set(name, {
|
|
48
|
+
name,
|
|
49
|
+
parameters: fn.parameters.map((p) => p.name.getText(source)),
|
|
50
|
+
optionalParameters: fn.parameters.map(
|
|
51
|
+
(p) => !!(p.questionToken || p.initializer)
|
|
52
|
+
),
|
|
53
|
+
restParameterIndex: fn.parameters.findIndex((p) => !!p.dotDotDotToken),
|
|
54
|
+
isAsync: !!has(fn, ts.SyntaxKind.AsyncKeyword),
|
|
55
|
+
isExported: false
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
for (const node of source.statements) {
|
|
59
|
+
if (has(node, ts.SyntaxKind.DeclareKeyword)) continue;
|
|
60
|
+
if (ts.isVariableStatement(node)) {
|
|
61
|
+
for (const decl of node.declarationList.declarations) {
|
|
62
|
+
const fn = unwrap(decl.initializer);
|
|
63
|
+
if (!ts.isIdentifier(decl.name) || !fn) continue;
|
|
64
|
+
collect(decl.name.text, fn);
|
|
65
|
+
if (has(node, ts.SyntaxKind.ExportKeyword))
|
|
66
|
+
exports.set(decl.name.text, decl.name.text);
|
|
67
|
+
}
|
|
68
|
+
} else if (ts.isFunctionDeclaration(node) && node.body) {
|
|
69
|
+
const name = node.name?.text ?? anonymousName();
|
|
70
|
+
collect(name, node);
|
|
71
|
+
if (has(node, ts.SyntaxKind.ExportKeyword))
|
|
72
|
+
exports.set(
|
|
73
|
+
has(node, ts.SyntaxKind.DefaultKeyword) ? "default" : name,
|
|
74
|
+
name
|
|
75
|
+
);
|
|
76
|
+
} else if (ts.isExportDeclaration(node) && !node.moduleSpecifier && !node.isTypeOnly && node.exportClause && ts.isNamedExports(node.exportClause)) {
|
|
77
|
+
for (const item of node.exportClause.elements) {
|
|
78
|
+
if (!item.isTypeOnly)
|
|
79
|
+
exports.set(item.name.text, (item.propertyName ?? item.name).text);
|
|
80
|
+
}
|
|
81
|
+
} else if (ts.isExportAssignment(node)) {
|
|
82
|
+
if (node.isExportEquals)
|
|
83
|
+
throw new Error(
|
|
84
|
+
"CommonJS export assignment is not supported for API files."
|
|
85
|
+
);
|
|
86
|
+
if (ts.isIdentifier(node.expression))
|
|
87
|
+
exports.set("default", node.expression.text);
|
|
88
|
+
else {
|
|
89
|
+
const fn = unwrap(node.expression);
|
|
90
|
+
if (fn) {
|
|
91
|
+
const name = anonymousName();
|
|
92
|
+
collect(name, fn);
|
|
93
|
+
exports.set("default", name);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const result = [];
|
|
99
|
+
const emitted = /* @__PURE__ */ new Map();
|
|
100
|
+
for (const [exportName, localName] of exports) {
|
|
101
|
+
const info = functions.get(localName);
|
|
102
|
+
if (info) {
|
|
103
|
+
const name = exportName === "default" ? localName : exportName;
|
|
104
|
+
if (emitted.has(name)) {
|
|
105
|
+
if (emitted.get(name) !== localName)
|
|
106
|
+
throw new Error("Conflicting exports; rename the default export.");
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
emitted.set(name, localName);
|
|
110
|
+
result.push({ ...info, name, importName: exportName, isExported: true });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (config.exportFilter === "all") {
|
|
114
|
+
for (const [name, info] of functions)
|
|
115
|
+
if (![...exports.values()].includes(name)) result.push(info);
|
|
116
|
+
}
|
|
117
|
+
return result.filter(
|
|
118
|
+
(info) => (config.functionMatchMode !== "async-only" || info.isAsync) && (config.functionMatchMode !== "sync-only" || !info.isAsync) && (!config.includeNames?.length || config.includeNames.includes(info.name)) && !config.excludeNames?.includes(info.name)
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
export {
|
|
122
|
+
analyzeFile
|
|
123
|
+
};
|
package/dist/core/generator.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
import type { FunctionInfo } from "./analyzer";
|
|
1
|
+
import type { FunctionInfo } from "./analyzer.js";
|
|
2
2
|
export type GeneratedArtifact = "query" | "mutation" | "infinite";
|
|
3
3
|
export type KeyStyle = "path" | "file-only" | "function-only";
|
|
4
|
+
export type ArtifactStrategy = "all" | "smart";
|
|
4
5
|
export interface TemplateConfig {
|
|
5
6
|
importNames?: Partial<Record<GeneratedArtifact, string>>;
|
|
6
7
|
outputNames?: Partial<Record<GeneratedArtifact, string>>;
|
|
7
8
|
enabledArtifacts?: GeneratedArtifact[];
|
|
8
9
|
keyStyle?: KeyStyle;
|
|
10
|
+
artifactStrategy?: ArtifactStrategy;
|
|
11
|
+
artifactsByName?: Record<string, GeneratedArtifact[]>;
|
|
9
12
|
}
|
|
10
13
|
interface GenerateOptionsParams {
|
|
11
14
|
keySegments: string[];
|
|
@@ -13,6 +16,6 @@ interface GenerateOptionsParams {
|
|
|
13
16
|
templateImportPath: string;
|
|
14
17
|
template?: TemplateConfig;
|
|
15
18
|
}
|
|
16
|
-
export declare function
|
|
19
|
+
export declare function validIdentifier(name: string): boolean;
|
|
20
|
+
export declare function generateOptionsCode(functionInfos: FunctionInfo[], importPath: string, { keySegments, fileName, templateImportPath, template, }: GenerateOptionsParams): string;
|
|
17
21
|
export {};
|
|
18
|
-
//# sourceMappingURL=generator.d.ts.map
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// src/core/generator.ts
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
var imports = {
|
|
4
|
+
query: "queryOption",
|
|
5
|
+
mutation: "mutationOption",
|
|
6
|
+
infinite: "infiniteOption"
|
|
7
|
+
};
|
|
8
|
+
var suffixes = {
|
|
9
|
+
query: "QueryOption",
|
|
10
|
+
mutation: "MutationOption",
|
|
11
|
+
infinite: "InfiniteQueryOption"
|
|
12
|
+
};
|
|
13
|
+
var mutationPattern = /^(create|post|add|update|put|patch|delete|remove|set|send|upload|signIn|signOut|login|logout|mutate)(?=[A-Z_\d]|$)/;
|
|
14
|
+
var queryPattern = /^(get|list|fetch|find|read|load|search|retrieve|detail|details)(?=[A-Z_\d]|$)/;
|
|
15
|
+
function validIdentifier(name) {
|
|
16
|
+
const scanner = ts.createScanner(
|
|
17
|
+
ts.ScriptTarget.Latest,
|
|
18
|
+
false,
|
|
19
|
+
ts.LanguageVariant.Standard,
|
|
20
|
+
name
|
|
21
|
+
);
|
|
22
|
+
const token = scanner.scan();
|
|
23
|
+
return (token === ts.SyntaxKind.Identifier || token >= ts.SyntaxKind.AbstractKeyword && token <= ts.SyntaxKind.OfKeyword && token !== ts.SyntaxKind.AwaitKeyword) && scanner.getTokenText() === name && scanner.scan() === ts.SyntaxKind.EndOfFileToken;
|
|
24
|
+
}
|
|
25
|
+
function generateOptionsCode(functionInfos, importPath, {
|
|
26
|
+
keySegments,
|
|
27
|
+
fileName,
|
|
28
|
+
templateImportPath,
|
|
29
|
+
template = {}
|
|
30
|
+
}) {
|
|
31
|
+
const enabled = template.enabledArtifacts ?? [
|
|
32
|
+
"query",
|
|
33
|
+
"mutation",
|
|
34
|
+
"infinite"
|
|
35
|
+
];
|
|
36
|
+
const strategy = template.artifactStrategy ?? "smart";
|
|
37
|
+
const rows = functionInfos.map((info) => {
|
|
38
|
+
let artifacts = template.artifactsByName?.[info.name] ?? enabled;
|
|
39
|
+
if (!template.artifactsByName?.[info.name] && strategy === "smart") {
|
|
40
|
+
artifacts = artifacts.filter(
|
|
41
|
+
(a) => mutationPattern.test(info.name) ? a === "mutation" : queryPattern.test(info.name) ? a !== "mutation" : a !== "infinite"
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
info,
|
|
46
|
+
artifacts: [...new Set(artifacts.filter((a) => enabled.includes(a)))]
|
|
47
|
+
};
|
|
48
|
+
}).filter((row) => row.artifacts.length);
|
|
49
|
+
if (!rows.length) return "";
|
|
50
|
+
const occupied = /* @__PURE__ */ new Set();
|
|
51
|
+
function reserve(name) {
|
|
52
|
+
if (!validIdentifier(name) || occupied.has(name))
|
|
53
|
+
throw new Error(`Invalid or duplicate generated identifier: ${name}`);
|
|
54
|
+
occupied.add(name);
|
|
55
|
+
return name;
|
|
56
|
+
}
|
|
57
|
+
for (const { info } of rows) {
|
|
58
|
+
if (!info.isExported)
|
|
59
|
+
throw new Error(
|
|
60
|
+
`Cannot import private function ${info.name}. Export it or use a custom template.`
|
|
61
|
+
);
|
|
62
|
+
reserve(info.name);
|
|
63
|
+
}
|
|
64
|
+
for (const { info, artifacts } of rows) {
|
|
65
|
+
reserve(`${info.name}Key`);
|
|
66
|
+
for (const a of artifacts)
|
|
67
|
+
reserve(`${info.name}${template.outputNames?.[a] ?? suffixes[a]}`);
|
|
68
|
+
}
|
|
69
|
+
const helpers = /* @__PURE__ */ new Map();
|
|
70
|
+
const helperImports = [];
|
|
71
|
+
for (const a of new Set(rows.flatMap((row) => row.artifacts))) {
|
|
72
|
+
const name = template.importNames?.[a] ?? imports[a];
|
|
73
|
+
if (!validIdentifier(name))
|
|
74
|
+
throw new Error(`Invalid helper import: ${name}`);
|
|
75
|
+
let alias = `__rqh_${a}`;
|
|
76
|
+
while (occupied.has(alias)) alias += "_";
|
|
77
|
+
reserve(alias);
|
|
78
|
+
helpers.set(a, alias);
|
|
79
|
+
helperImports.push(`${name} as ${alias}`);
|
|
80
|
+
}
|
|
81
|
+
let code = `import { ${rows.map(
|
|
82
|
+
({ info }) => info.importName && info.importName !== info.name ? `${info.importName === "default" ? "default" : JSON.stringify(info.importName)} as ${info.name}` : info.name
|
|
83
|
+
).join(", ")} } from ${JSON.stringify(importPath)};
|
|
84
|
+
`;
|
|
85
|
+
code += `import { ${helperImports.join(", ")} } from ${JSON.stringify(templateImportPath)};
|
|
86
|
+
|
|
87
|
+
`;
|
|
88
|
+
for (const { info, artifacts } of rows) {
|
|
89
|
+
const base = template.keyStyle === "function-only" ? [] : template.keyStyle === "file-only" ? [fileName] : [...keySegments, fileName];
|
|
90
|
+
const keyName = `${info.name}Key`;
|
|
91
|
+
code += `export const ${keyName} = ${JSON.stringify([...base, info.name])} as const;
|
|
92
|
+
`;
|
|
93
|
+
for (const artifact of artifacts) {
|
|
94
|
+
const helper = helpers.get(artifact);
|
|
95
|
+
let expression = `${helper}(${keyName}, ${info.name})`;
|
|
96
|
+
if (artifact === "mutation") {
|
|
97
|
+
const hasRest = info.restParameterIndex !== void 0 && info.restParameterIndex >= 0;
|
|
98
|
+
if (info.parameters.length > 1 && !hasRest && info.parameters.every(validIdentifier)) {
|
|
99
|
+
const typeName = reserve(`${info.name}MutationVariables`);
|
|
100
|
+
code += `export type ${typeName} = {
|
|
101
|
+
${info.parameters.map(
|
|
102
|
+
(p, i) => ` ${p}${info.optionalParameters?.[i] ? "?" : ""}: Parameters<typeof ${info.name}>[${i}];`
|
|
103
|
+
).join("\n")}
|
|
104
|
+
};
|
|
105
|
+
`;
|
|
106
|
+
expression = `${helper}<Parameters<typeof ${info.name}>, Awaited<ReturnType<typeof ${info.name}>>, ${typeName}>(${keyName}, ${info.name}, { mapVariablesToArgs: (variables) => [${info.parameters.map((p) => `variables.${p}`).join(", ")}] })`;
|
|
107
|
+
} else if (info.parameters.length > 1 || hasRest) {
|
|
108
|
+
expression = `${helper}(${keyName}, ${info.name}, { variablesMode: "tuple" })`;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
code += `export const ${info.name}${template.outputNames?.[artifact] ?? suffixes[artifact]} = ${expression};
|
|
112
|
+
`;
|
|
113
|
+
}
|
|
114
|
+
code += "\n";
|
|
115
|
+
}
|
|
116
|
+
return code;
|
|
117
|
+
}
|
|
118
|
+
export {
|
|
119
|
+
generateOptionsCode,
|
|
120
|
+
validIdentifier
|
|
121
|
+
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export * from
|
|
2
|
-
|
|
1
|
+
export * from "./utils/query.js";
|
|
2
|
+
export type { AutoQueryConfig } from "./config.js";
|
package/dist/index.js
CHANGED
|
@@ -1,40 +1,118 @@
|
|
|
1
1
|
// src/utils/query.ts
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import {
|
|
3
|
+
infiniteQueryOptions,
|
|
4
|
+
mutationOptions,
|
|
5
|
+
queryOptions
|
|
6
|
+
} from "@tanstack/react-query";
|
|
7
|
+
function resolveArgs(payload, overrides) {
|
|
8
|
+
const args = [...overrides.args ?? payload];
|
|
9
|
+
return overrides.mapArgs ? overrides.mapArgs(args) : args;
|
|
10
|
+
}
|
|
11
|
+
function resolveKey(base, args, append, override) {
|
|
12
|
+
return override ?? [...base, ...args, ...append ?? []];
|
|
13
|
+
}
|
|
14
|
+
function queryOption(key, fn) {
|
|
15
|
+
function build(payload, overrides = {}) {
|
|
16
|
+
const args = resolveArgs(payload, overrides);
|
|
17
|
+
const {
|
|
18
|
+
queryKey: customKey,
|
|
19
|
+
appendQueryKey,
|
|
20
|
+
args: _args,
|
|
21
|
+
mapArgs: _mapArgs,
|
|
22
|
+
queryFn: customFn,
|
|
23
|
+
...options
|
|
24
|
+
} = overrides;
|
|
25
|
+
const queryKey = resolveKey(
|
|
26
|
+
key,
|
|
27
|
+
["query", args],
|
|
28
|
+
appendQueryKey,
|
|
29
|
+
customKey
|
|
30
|
+
);
|
|
31
|
+
const queryFn = async (context) => customFn ? customFn({ ...context, args }) : fn(...args);
|
|
32
|
+
return {
|
|
33
|
+
...queryOptions({
|
|
34
|
+
...options,
|
|
35
|
+
queryKey,
|
|
36
|
+
queryFn
|
|
37
|
+
}),
|
|
38
|
+
queryFn
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
const factory = (...payload) => build(payload);
|
|
42
|
+
function withOptions(overrides, ...payload) {
|
|
43
|
+
return build(payload, overrides);
|
|
44
|
+
}
|
|
45
|
+
factory.withOptions = withOptions;
|
|
46
|
+
return factory;
|
|
47
|
+
}
|
|
48
|
+
function mutationOption(key, fn, ...configuration) {
|
|
49
|
+
const config = configuration[0];
|
|
50
|
+
function build(overrides = {}) {
|
|
51
|
+
const {
|
|
52
|
+
mutationKey,
|
|
53
|
+
appendMutationKey,
|
|
54
|
+
mapVariablesToArgs,
|
|
55
|
+
mutationFn: customFn,
|
|
56
|
+
...options
|
|
57
|
+
} = overrides;
|
|
58
|
+
const mapper = mapVariablesToArgs ?? config?.mapVariablesToArgs;
|
|
59
|
+
const mutationFn = async (variables, context) => {
|
|
60
|
+
const args = mapper ? mapper(variables) : config?.variablesMode === "tuple" ? variables : variables === void 0 ? [] : [variables];
|
|
61
|
+
if (!Array.isArray(args))
|
|
62
|
+
throw new TypeError("Mutation argument mapping must return an array.");
|
|
63
|
+
return customFn ? customFn({ ...context, variables, args }) : fn(...args);
|
|
64
|
+
};
|
|
65
|
+
return {
|
|
66
|
+
...mutationOptions({
|
|
67
|
+
...options,
|
|
68
|
+
mutationKey: mutationKey ?? [...key, ...appendMutationKey ?? []],
|
|
69
|
+
mutationFn
|
|
70
|
+
}),
|
|
71
|
+
mutationFn
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const factory = () => build();
|
|
75
|
+
factory.withOptions = build;
|
|
76
|
+
return factory;
|
|
77
|
+
}
|
|
78
|
+
function infiniteOption(key, fn) {
|
|
79
|
+
function build(payload, overrides) {
|
|
80
|
+
const args = resolveArgs(payload, overrides);
|
|
81
|
+
const {
|
|
82
|
+
queryKey: customKey,
|
|
83
|
+
appendQueryKey,
|
|
84
|
+
args: _args,
|
|
85
|
+
mapArgs: _mapArgs,
|
|
86
|
+
pageParamToArgs,
|
|
87
|
+
queryFn: customFn,
|
|
88
|
+
...options
|
|
89
|
+
} = overrides;
|
|
90
|
+
const queryKey = resolveKey(
|
|
91
|
+
key,
|
|
92
|
+
["infinite", args],
|
|
93
|
+
appendQueryKey,
|
|
94
|
+
customKey
|
|
95
|
+
);
|
|
96
|
+
const queryFn = async (context) => {
|
|
97
|
+
if (customFn) return customFn({ ...context, args });
|
|
98
|
+
return fn(
|
|
99
|
+
...pageParamToArgs ? pageParamToArgs(context.pageParam, [...args]) : args
|
|
100
|
+
);
|
|
101
|
+
};
|
|
102
|
+
return {
|
|
103
|
+
...infiniteQueryOptions({ ...options, queryKey, queryFn }),
|
|
104
|
+
queryFn
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const factory = (...payload) => build(payload, {
|
|
108
|
+
initialPageParam: void 0,
|
|
109
|
+
getNextPageParam: () => void 0
|
|
8
110
|
});
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
mutationKey: key,
|
|
13
|
-
mutationFn: (variables) => {
|
|
14
|
-
if (Array.isArray(variables)) {
|
|
15
|
-
return Promise.resolve(fn(...variables));
|
|
16
|
-
}
|
|
17
|
-
if (typeof variables === "undefined") {
|
|
18
|
-
return Promise.resolve(fn(...[]));
|
|
19
|
-
}
|
|
20
|
-
return Promise.resolve(fn(...[variables]));
|
|
21
|
-
}
|
|
22
|
-
});
|
|
23
|
-
};
|
|
24
|
-
var infiniteOption = (key, fn) => {
|
|
25
|
-
return (...payload) => ({
|
|
26
|
-
queryKey: [...key, ...payload],
|
|
27
|
-
queryFn: () => Promise.resolve(fn(...payload)),
|
|
28
|
-
getNextPageParam: () => {
|
|
29
|
-
return;
|
|
30
|
-
},
|
|
31
|
-
initialPageParam: undefined,
|
|
32
|
-
staleTime: Infinity,
|
|
33
|
-
refetchOnWindowFocus: false
|
|
34
|
-
});
|
|
35
|
-
};
|
|
111
|
+
factory.withOptions = (overrides, ...payload) => build(payload, overrides);
|
|
112
|
+
return factory;
|
|
113
|
+
}
|
|
36
114
|
export {
|
|
37
|
-
|
|
115
|
+
infiniteOption,
|
|
38
116
|
mutationOption,
|
|
39
|
-
|
|
117
|
+
queryOption
|
|
40
118
|
};
|