@ciderjs/gasnuki 0.2.8 → 0.2.9
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/cli.cjs +77 -0
- package/dist/cli.d.cts +7 -0
- package/dist/cli.d.mts +7 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.mjs +60 -0
- package/dist/index.cjs +14 -0
- package/dist/index.d.cts +23 -0
- package/dist/index.d.mts +23 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.mjs +7 -0
- package/dist/promise.cjs +19 -0
- package/dist/promise.d.cts +8 -0
- package/dist/promise.d.mts +8 -0
- package/dist/promise.d.ts +8 -0
- package/dist/promise.mjs +17 -0
- package/dist/shared/gasnuki.93G9yyCy.cjs +409 -0
- package/dist/shared/gasnuki.CS974pL-.mjs +389 -0
- package/package.json +1 -1
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
#! /usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const commander = require('commander');
|
|
6
|
+
const index = require('./shared/gasnuki.93G9yyCy.cjs');
|
|
7
|
+
require('chokidar');
|
|
8
|
+
require('consola');
|
|
9
|
+
require('node:fs');
|
|
10
|
+
require('ts-morph');
|
|
11
|
+
require('jiti');
|
|
12
|
+
|
|
13
|
+
function _interopNamespaceCompat(e) {
|
|
14
|
+
if (e && typeof e === 'object' && 'default' in e) return e;
|
|
15
|
+
const n = Object.create(null);
|
|
16
|
+
if (e) {
|
|
17
|
+
for (const k in e) {
|
|
18
|
+
n[k] = e[k];
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
n.default = e;
|
|
22
|
+
return n;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const path__namespace = /*#__PURE__*/_interopNamespaceCompat(path);
|
|
26
|
+
|
|
27
|
+
const version = "0.2.9";
|
|
28
|
+
|
|
29
|
+
const parseArgs = async (command) => {
|
|
30
|
+
const cliOpts = command.opts();
|
|
31
|
+
const fileConfig = await index.loadConfig(path__namespace.resolve(cliOpts.project));
|
|
32
|
+
const defaultOpts = {};
|
|
33
|
+
for (const option of command.options) {
|
|
34
|
+
const key = option.attributeName();
|
|
35
|
+
defaultOpts[key] = option.defaultValue;
|
|
36
|
+
}
|
|
37
|
+
const explicitCliOpts = {};
|
|
38
|
+
for (const option of command.options) {
|
|
39
|
+
const key = option.attributeName();
|
|
40
|
+
if (command.getOptionValueSource(key) === "cli") {
|
|
41
|
+
explicitCliOpts[key] = cliOpts[key];
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const finalOptions = {
|
|
45
|
+
...defaultOpts,
|
|
46
|
+
...fileConfig,
|
|
47
|
+
...explicitCliOpts,
|
|
48
|
+
project: cliOpts.project,
|
|
49
|
+
watch: cliOpts.watch
|
|
50
|
+
};
|
|
51
|
+
await index.generateTypes(finalOptions);
|
|
52
|
+
};
|
|
53
|
+
const cli = async () => {
|
|
54
|
+
const program = new commander.Command();
|
|
55
|
+
program.name("gasnuki").description(
|
|
56
|
+
"Generate type definitions and utilities for Google Apps Script client-side API"
|
|
57
|
+
);
|
|
58
|
+
program.version(version, "-v, --version");
|
|
59
|
+
program.action(async (_param, command) => await parseArgs(command)).option(
|
|
60
|
+
"-p, --project <project>",
|
|
61
|
+
"Project root directory path",
|
|
62
|
+
process.cwd().replace(/\\/g, "/")
|
|
63
|
+
).option(
|
|
64
|
+
"-s, --srcDir <dir>",
|
|
65
|
+
"Source directory name (relative to project root)",
|
|
66
|
+
"server"
|
|
67
|
+
).option(
|
|
68
|
+
"-o, --outDir <dir>",
|
|
69
|
+
"Output directory name (relative to project root)",
|
|
70
|
+
"types"
|
|
71
|
+
).option("-f, --outputFile <file>", "Output file name", "appsscript.ts").option("-w, --watch", "Watch for changes and re-generate types", false);
|
|
72
|
+
await program.parseAsync(process.argv);
|
|
73
|
+
};
|
|
74
|
+
cli();
|
|
75
|
+
|
|
76
|
+
exports.cli = cli;
|
|
77
|
+
exports.parseArgs = parseArgs;
|
package/dist/cli.d.cts
ADDED
package/dist/cli.d.mts
ADDED
package/dist/cli.d.ts
ADDED
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#! /usr/bin/env node
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { Command } from 'commander';
|
|
4
|
+
import { l as loadConfig, g as generateTypes } from './shared/gasnuki.CS974pL-.mjs';
|
|
5
|
+
import 'chokidar';
|
|
6
|
+
import 'consola';
|
|
7
|
+
import 'node:fs';
|
|
8
|
+
import 'ts-morph';
|
|
9
|
+
import 'jiti';
|
|
10
|
+
|
|
11
|
+
const version = "0.2.9";
|
|
12
|
+
|
|
13
|
+
const parseArgs = async (command) => {
|
|
14
|
+
const cliOpts = command.opts();
|
|
15
|
+
const fileConfig = await loadConfig(path.resolve(cliOpts.project));
|
|
16
|
+
const defaultOpts = {};
|
|
17
|
+
for (const option of command.options) {
|
|
18
|
+
const key = option.attributeName();
|
|
19
|
+
defaultOpts[key] = option.defaultValue;
|
|
20
|
+
}
|
|
21
|
+
const explicitCliOpts = {};
|
|
22
|
+
for (const option of command.options) {
|
|
23
|
+
const key = option.attributeName();
|
|
24
|
+
if (command.getOptionValueSource(key) === "cli") {
|
|
25
|
+
explicitCliOpts[key] = cliOpts[key];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const finalOptions = {
|
|
29
|
+
...defaultOpts,
|
|
30
|
+
...fileConfig,
|
|
31
|
+
...explicitCliOpts,
|
|
32
|
+
project: cliOpts.project,
|
|
33
|
+
watch: cliOpts.watch
|
|
34
|
+
};
|
|
35
|
+
await generateTypes(finalOptions);
|
|
36
|
+
};
|
|
37
|
+
const cli = async () => {
|
|
38
|
+
const program = new Command();
|
|
39
|
+
program.name("gasnuki").description(
|
|
40
|
+
"Generate type definitions and utilities for Google Apps Script client-side API"
|
|
41
|
+
);
|
|
42
|
+
program.version(version, "-v, --version");
|
|
43
|
+
program.action(async (_param, command) => await parseArgs(command)).option(
|
|
44
|
+
"-p, --project <project>",
|
|
45
|
+
"Project root directory path",
|
|
46
|
+
process.cwd().replace(/\\/g, "/")
|
|
47
|
+
).option(
|
|
48
|
+
"-s, --srcDir <dir>",
|
|
49
|
+
"Source directory name (relative to project root)",
|
|
50
|
+
"server"
|
|
51
|
+
).option(
|
|
52
|
+
"-o, --outDir <dir>",
|
|
53
|
+
"Output directory name (relative to project root)",
|
|
54
|
+
"types"
|
|
55
|
+
).option("-f, --outputFile <file>", "Output file name", "appsscript.ts").option("-w, --watch", "Watch for changes and re-generate types", false);
|
|
56
|
+
await program.parseAsync(process.argv);
|
|
57
|
+
};
|
|
58
|
+
cli();
|
|
59
|
+
|
|
60
|
+
export { cli, parseArgs };
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
require('node:path');
|
|
4
|
+
require('chokidar');
|
|
5
|
+
require('consola');
|
|
6
|
+
const index = require('./shared/gasnuki.93G9yyCy.cjs');
|
|
7
|
+
require('node:fs');
|
|
8
|
+
require('ts-morph');
|
|
9
|
+
require('jiti');
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
exports.defineConfig = index.defineConfig;
|
|
14
|
+
exports.generateTypes = index.generateTypes;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* User-defined configuration for gasnuki.
|
|
3
|
+
* `project` and `watch` options are excluded as they are runtime flags.
|
|
4
|
+
*/
|
|
5
|
+
type UserConfig = Partial<Omit<GenerateOptions, 'watch' | 'project'>>;
|
|
6
|
+
/**
|
|
7
|
+
* A helper function to define the gasnuki configuration with type safety.
|
|
8
|
+
* @param config The configuration object.
|
|
9
|
+
* @returns The configuration object.
|
|
10
|
+
*/
|
|
11
|
+
declare function defineConfig(config: UserConfig): UserConfig;
|
|
12
|
+
|
|
13
|
+
interface GenerateOptions {
|
|
14
|
+
project: string;
|
|
15
|
+
srcDir: string;
|
|
16
|
+
outDir: string;
|
|
17
|
+
outputFile: string;
|
|
18
|
+
watch: boolean;
|
|
19
|
+
}
|
|
20
|
+
declare const generateTypes: ({ project, srcDir, outDir, outputFile, watch, }: GenerateOptions) => Promise<void>;
|
|
21
|
+
|
|
22
|
+
export { defineConfig, generateTypes };
|
|
23
|
+
export type { GenerateOptions, UserConfig };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* User-defined configuration for gasnuki.
|
|
3
|
+
* `project` and `watch` options are excluded as they are runtime flags.
|
|
4
|
+
*/
|
|
5
|
+
type UserConfig = Partial<Omit<GenerateOptions, 'watch' | 'project'>>;
|
|
6
|
+
/**
|
|
7
|
+
* A helper function to define the gasnuki configuration with type safety.
|
|
8
|
+
* @param config The configuration object.
|
|
9
|
+
* @returns The configuration object.
|
|
10
|
+
*/
|
|
11
|
+
declare function defineConfig(config: UserConfig): UserConfig;
|
|
12
|
+
|
|
13
|
+
interface GenerateOptions {
|
|
14
|
+
project: string;
|
|
15
|
+
srcDir: string;
|
|
16
|
+
outDir: string;
|
|
17
|
+
outputFile: string;
|
|
18
|
+
watch: boolean;
|
|
19
|
+
}
|
|
20
|
+
declare const generateTypes: ({ project, srcDir, outDir, outputFile, watch, }: GenerateOptions) => Promise<void>;
|
|
21
|
+
|
|
22
|
+
export { defineConfig, generateTypes };
|
|
23
|
+
export type { GenerateOptions, UserConfig };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* User-defined configuration for gasnuki.
|
|
3
|
+
* `project` and `watch` options are excluded as they are runtime flags.
|
|
4
|
+
*/
|
|
5
|
+
type UserConfig = Partial<Omit<GenerateOptions, 'watch' | 'project'>>;
|
|
6
|
+
/**
|
|
7
|
+
* A helper function to define the gasnuki configuration with type safety.
|
|
8
|
+
* @param config The configuration object.
|
|
9
|
+
* @returns The configuration object.
|
|
10
|
+
*/
|
|
11
|
+
declare function defineConfig(config: UserConfig): UserConfig;
|
|
12
|
+
|
|
13
|
+
interface GenerateOptions {
|
|
14
|
+
project: string;
|
|
15
|
+
srcDir: string;
|
|
16
|
+
outDir: string;
|
|
17
|
+
outputFile: string;
|
|
18
|
+
watch: boolean;
|
|
19
|
+
}
|
|
20
|
+
declare const generateTypes: ({ project, srcDir, outDir, outputFile, watch, }: GenerateOptions) => Promise<void>;
|
|
21
|
+
|
|
22
|
+
export { defineConfig, generateTypes };
|
|
23
|
+
export type { GenerateOptions, UserConfig };
|
package/dist/index.mjs
ADDED
package/dist/promise.cjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const getPromisedServerScripts = (mockupFunctions = {}) => {
|
|
4
|
+
return new Proxy(mockupFunctions, {
|
|
5
|
+
get(target, method) {
|
|
6
|
+
if (!("google" in globalThis) || !google?.script?.run) {
|
|
7
|
+
return target[method];
|
|
8
|
+
}
|
|
9
|
+
if (!(method in google.script.run)) {
|
|
10
|
+
throw Error(`Method ${method} not found in AppsScript.`);
|
|
11
|
+
}
|
|
12
|
+
return (...args) => new Promise((resolve, reject) => {
|
|
13
|
+
google.script.run.withSuccessHandler(resolve).withFailureHandler(reject)[method](...args);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
exports.getPromisedServerScripts = getPromisedServerScripts;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
type Promised<T> = {
|
|
2
|
+
[K in keyof T]: T[K] extends (...args: infer A) => infer R ? (...args: A) => Promise<R> : T[K];
|
|
3
|
+
};
|
|
4
|
+
type PartialScriptType<T> = Partial<Promised<T>>;
|
|
5
|
+
declare const getPromisedServerScripts: <T extends Record<string, (...args: any[]) => any> = Omit<typeof google.script.run, "withSuccessHandler" | "withFailureHandler" | "withUserObject">>(mockupFunctions?: PartialScriptType<T>) => Promised<T>;
|
|
6
|
+
|
|
7
|
+
export { getPromisedServerScripts };
|
|
8
|
+
export type { PartialScriptType, Promised };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
type Promised<T> = {
|
|
2
|
+
[K in keyof T]: T[K] extends (...args: infer A) => infer R ? (...args: A) => Promise<R> : T[K];
|
|
3
|
+
};
|
|
4
|
+
type PartialScriptType<T> = Partial<Promised<T>>;
|
|
5
|
+
declare const getPromisedServerScripts: <T extends Record<string, (...args: any[]) => any> = Omit<typeof google.script.run, "withSuccessHandler" | "withFailureHandler" | "withUserObject">>(mockupFunctions?: PartialScriptType<T>) => Promised<T>;
|
|
6
|
+
|
|
7
|
+
export { getPromisedServerScripts };
|
|
8
|
+
export type { PartialScriptType, Promised };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
type Promised<T> = {
|
|
2
|
+
[K in keyof T]: T[K] extends (...args: infer A) => infer R ? (...args: A) => Promise<R> : T[K];
|
|
3
|
+
};
|
|
4
|
+
type PartialScriptType<T> = Partial<Promised<T>>;
|
|
5
|
+
declare const getPromisedServerScripts: <T extends Record<string, (...args: any[]) => any> = Omit<typeof google.script.run, "withSuccessHandler" | "withFailureHandler" | "withUserObject">>(mockupFunctions?: PartialScriptType<T>) => Promised<T>;
|
|
6
|
+
|
|
7
|
+
export { getPromisedServerScripts };
|
|
8
|
+
export type { PartialScriptType, Promised };
|
package/dist/promise.mjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const getPromisedServerScripts = (mockupFunctions = {}) => {
|
|
2
|
+
return new Proxy(mockupFunctions, {
|
|
3
|
+
get(target, method) {
|
|
4
|
+
if (!("google" in globalThis) || !google?.script?.run) {
|
|
5
|
+
return target[method];
|
|
6
|
+
}
|
|
7
|
+
if (!(method in google.script.run)) {
|
|
8
|
+
throw Error(`Method ${method} not found in AppsScript.`);
|
|
9
|
+
}
|
|
10
|
+
return (...args) => new Promise((resolve, reject) => {
|
|
11
|
+
google.script.run.withSuccessHandler(resolve).withFailureHandler(reject)[method](...args);
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export { getPromisedServerScripts };
|
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const chokidar = require('chokidar');
|
|
5
|
+
const consola = require('consola');
|
|
6
|
+
const fs = require('node:fs');
|
|
7
|
+
const tsMorph = require('ts-morph');
|
|
8
|
+
const jiti = require('jiti');
|
|
9
|
+
|
|
10
|
+
function _interopNamespaceCompat(e) {
|
|
11
|
+
if (e && typeof e === 'object' && 'default' in e) return e;
|
|
12
|
+
const n = Object.create(null);
|
|
13
|
+
if (e) {
|
|
14
|
+
for (const k in e) {
|
|
15
|
+
n[k] = e[k];
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
n.default = e;
|
|
19
|
+
return n;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const path__namespace = /*#__PURE__*/_interopNamespaceCompat(path);
|
|
23
|
+
const chokidar__namespace = /*#__PURE__*/_interopNamespaceCompat(chokidar);
|
|
24
|
+
const fs__namespace = /*#__PURE__*/_interopNamespaceCompat(fs);
|
|
25
|
+
|
|
26
|
+
const text = "export type RemoveReturnType<T> = {\n [P in keyof T]: T[P] extends (...args: infer A) => any\n ? (...args: A) => void\n : T[P];\n};\n\ntype _AppsScriptRun = RemoveReturnType<ServerScripts> & {\n [key: string]: (...args: any[]) => any;\n withSuccessHandler: <T = string | number | boolean | undefined, U = any>(\n callback: (returnValues: T, userObject?: U) => void,\n ) => _AppsScriptRun;\n withFailureHandler: <U = any>(\n callback: (error: Error, userObject?: U) => void,\n ) => _AppsScriptRun;\n withUserObject: <U = any>(userObject: U) => _AppsScriptRun;\n};\n\ntype _AppsScriptHistoryFunction = (\n stateObject: object,\n params: object,\n hash: string,\n) => void;\n\ninterface _WebAppLocationType {\n hash: string;\n parameter: Record<string, string>;\n parameters: Record<string, string[]>;\n}\n\nexport declare interface GoogleClientSideApi {\n script: {\n run: _AppsScriptRun;\n url: {\n getLocation: (callback: (location: _WebAppLocationType) => void) => void;\n };\n history: {\n push: _AppsScriptHistoryFunction;\n replace: _AppsScriptHistoryFunction;\n setChangeHandler: (\n callback: (e: { state: object; location: _WebAppLocationType }) => void,\n ) => void;\n };\n };\n}\n\ndeclare global {\n const google: GoogleClientSideApi;\n}\n";
|
|
27
|
+
|
|
28
|
+
const getInterfaceMethodDefinition_ = (name, node) => {
|
|
29
|
+
const typeParameters = node.getTypeParameters?.() ?? [];
|
|
30
|
+
const typeParamsString = typeParameters.length > 0 ? `<${typeParameters.map((tp) => tp.getText()).join(", ")}>` : "";
|
|
31
|
+
const parameters = node.getParameters().map((param) => {
|
|
32
|
+
const paramName = param.getName();
|
|
33
|
+
const type = param.getTypeNode()?.getText() ?? param.getType().getText(node) ?? "any";
|
|
34
|
+
const questionToken = param.hasQuestionToken() ? "?" : "";
|
|
35
|
+
return `${paramName}${questionToken}: ${type}`;
|
|
36
|
+
}).join(", ");
|
|
37
|
+
const returnTypeNode = node.getReturnTypeNode();
|
|
38
|
+
let returnType;
|
|
39
|
+
if (returnTypeNode != null) {
|
|
40
|
+
returnType = returnTypeNode.getText();
|
|
41
|
+
} else {
|
|
42
|
+
const inferredReturnType = node.getReturnType();
|
|
43
|
+
if (inferredReturnType.isVoid()) {
|
|
44
|
+
returnType = "void";
|
|
45
|
+
} else {
|
|
46
|
+
returnType = inferredReturnType.getText(node);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
let jsDocString = "";
|
|
50
|
+
const jsDocOwner = "getJsDocs" in node ? node : "getParentOrThrow" in node && // @ts-expect-error variable declaration
|
|
51
|
+
node.getParentOrThrow().getKind() === tsMorph.SyntaxKind.VariableDeclaration ? (
|
|
52
|
+
// @ts-expect-error variable declaration
|
|
53
|
+
node.getParentOrThrow()
|
|
54
|
+
) : null;
|
|
55
|
+
if (jsDocOwner != null) {
|
|
56
|
+
const jsDocs = "getJsDocs" in jsDocOwner ? jsDocOwner.getJsDocs() : [];
|
|
57
|
+
if (jsDocs.length > 0) {
|
|
58
|
+
const firstDoc = jsDocs[0];
|
|
59
|
+
jsDocString = `${firstDoc.getFullText().trim()}
|
|
60
|
+
`;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return `${jsDocString}${name}${typeParamsString}(${parameters}): ${returnType};`;
|
|
64
|
+
};
|
|
65
|
+
const SIMPLE_TRIGGER_FUNCTION_NAMES = [
|
|
66
|
+
"onOpen",
|
|
67
|
+
"onEdit",
|
|
68
|
+
"onInstall",
|
|
69
|
+
"onSelectionChange",
|
|
70
|
+
"doGet",
|
|
71
|
+
"doPost"
|
|
72
|
+
];
|
|
73
|
+
const generateAppsScriptTypes = async ({
|
|
74
|
+
project: projectPath,
|
|
75
|
+
srcDir,
|
|
76
|
+
outDir,
|
|
77
|
+
outputFile
|
|
78
|
+
}) => {
|
|
79
|
+
const absoluteSrcDir = path__namespace.resolve(projectPath, srcDir);
|
|
80
|
+
const absoluteOutDir = path__namespace.resolve(projectPath, outDir);
|
|
81
|
+
const absoluteOutputFile = path__namespace.resolve(absoluteOutDir, outputFile);
|
|
82
|
+
consola.consola.info("Starting AppsScript type generation with gasnuki...");
|
|
83
|
+
consola.consola.info(` AppsScript Source Directory: ${absoluteSrcDir}`);
|
|
84
|
+
consola.consola.info(` Output File: ${absoluteOutputFile}`);
|
|
85
|
+
const project = new tsMorph.Project({
|
|
86
|
+
tsConfigFilePath: path__namespace.resolve(projectPath, "tsconfig.json"),
|
|
87
|
+
skipAddingFilesFromTsConfig: true
|
|
88
|
+
});
|
|
89
|
+
const sourceFilesPattern = path__namespace.join(absoluteSrcDir, "**/*.ts").replace(/\\/g, "/");
|
|
90
|
+
const testFilesPattern = `!${path__namespace.join(absoluteSrcDir, "**/*.{test,spec}.ts").replace(/\\/g, "/")}`;
|
|
91
|
+
project.addSourceFilesAtPaths([sourceFilesPattern, testFilesPattern]);
|
|
92
|
+
const sourceFiles = project.getSourceFiles();
|
|
93
|
+
consola.consola.info(`Found ${sourceFiles.length} source file(s).`);
|
|
94
|
+
const methodDefinitions = [];
|
|
95
|
+
const exportedDeclarations = [];
|
|
96
|
+
const exportedDeclarationNames = /* @__PURE__ */ new Set();
|
|
97
|
+
const exportedFunctions = [];
|
|
98
|
+
for (const sourceFile of sourceFiles) {
|
|
99
|
+
for (const iface of sourceFile.getInterfaces()) {
|
|
100
|
+
if (iface.isExported() && !iface.getName()?.endsWith("_")) {
|
|
101
|
+
exportedDeclarations.push(iface);
|
|
102
|
+
exportedDeclarationNames.add(iface.getName());
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const typeAlias of sourceFile.getTypeAliases()) {
|
|
106
|
+
if (typeAlias.isExported() && !typeAlias.getName().endsWith("_")) {
|
|
107
|
+
exportedDeclarations.push(typeAlias);
|
|
108
|
+
exportedDeclarationNames.add(typeAlias.getName());
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
for (const func of sourceFile.getFunctions()) {
|
|
112
|
+
const name = func.getName();
|
|
113
|
+
if (func.isExported() && name && !name.endsWith("_") && !SIMPLE_TRIGGER_FUNCTION_NAMES.includes(name)) {
|
|
114
|
+
exportedDeclarations.push(func);
|
|
115
|
+
exportedDeclarationNames.add(name);
|
|
116
|
+
methodDefinitions.push(getInterfaceMethodDefinition_(name, func));
|
|
117
|
+
exportedFunctions.push(func);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (const varStmt of sourceFile.getVariableStatements()) {
|
|
121
|
+
if (!varStmt.isExported()) continue;
|
|
122
|
+
for (const varDecl of varStmt.getDeclarations()) {
|
|
123
|
+
const name = varDecl.getName();
|
|
124
|
+
const initializer = varDecl.getInitializer();
|
|
125
|
+
if (!name.endsWith("_") && !SIMPLE_TRIGGER_FUNCTION_NAMES.includes(name) && initializer && (initializer.getKind() === tsMorph.SyntaxKind.ArrowFunction || initializer.getKind() === tsMorph.SyntaxKind.FunctionExpression)) {
|
|
126
|
+
const funcExpr = initializer;
|
|
127
|
+
exportedDeclarations.push(varDecl);
|
|
128
|
+
exportedDeclarationNames.add(name);
|
|
129
|
+
methodDefinitions.push(getInterfaceMethodDefinition_(name, funcExpr));
|
|
130
|
+
exportedFunctions.push(funcExpr);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const collectSymbolsFromType = (type, foundSymbols) => {
|
|
136
|
+
const symbol = type.getAliasSymbol() ?? type.getSymbol();
|
|
137
|
+
if (symbol && !foundSymbols.has(symbol)) {
|
|
138
|
+
foundSymbols.add(symbol);
|
|
139
|
+
if (type.isObject()) {
|
|
140
|
+
for (const prop of type.getProperties()) {
|
|
141
|
+
const propDecl = prop.getDeclarations()[0];
|
|
142
|
+
if (propDecl) {
|
|
143
|
+
collectSymbolsFromType(propDecl.getType(), foundSymbols);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
for (const typeArg of type.getTypeArguments()) {
|
|
149
|
+
collectSymbolsFromType(typeArg, foundSymbols);
|
|
150
|
+
}
|
|
151
|
+
if (type.isUnion()) {
|
|
152
|
+
for (const unionType of type.getUnionTypes()) {
|
|
153
|
+
collectSymbolsFromType(unionType, foundSymbols);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (type.isIntersection()) {
|
|
157
|
+
for (const intersectionType of type.getIntersectionTypes()) {
|
|
158
|
+
collectSymbolsFromType(intersectionType, foundSymbols);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
const returnValueSymbols = /* @__PURE__ */ new Set();
|
|
163
|
+
for (const func of exportedFunctions) {
|
|
164
|
+
collectSymbolsFromType(func.getReturnType(), returnValueSymbols);
|
|
165
|
+
}
|
|
166
|
+
const symbolsToProcess = /* @__PURE__ */ new Set();
|
|
167
|
+
for (const decl of exportedDeclarations) {
|
|
168
|
+
if (decl.getKind() === tsMorph.SyntaxKind.FunctionDeclaration || decl.getKind() === tsMorph.SyntaxKind.VariableDeclaration && (decl.getInitializer()?.getKind() === tsMorph.SyntaxKind.ArrowFunction || decl.getInitializer()?.getKind() === tsMorph.SyntaxKind.FunctionExpression)) {
|
|
169
|
+
const func = decl.getKind() === tsMorph.SyntaxKind.FunctionDeclaration ? decl : decl.getInitializer();
|
|
170
|
+
const parameters = func.getParameters();
|
|
171
|
+
for (const param of parameters) {
|
|
172
|
+
const typeRefs = param.getDescendantsOfKind(tsMorph.SyntaxKind.TypeReference);
|
|
173
|
+
for (const typeRef of typeRefs) {
|
|
174
|
+
const symbol = typeRef.getType().getAliasSymbol() ?? typeRef.getType().getSymbol();
|
|
175
|
+
if (symbol) symbolsToProcess.add(symbol);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const returnTypeNode = func.getReturnTypeNode();
|
|
179
|
+
if (returnTypeNode) {
|
|
180
|
+
const typeRefs = returnTypeNode.getDescendantsOfKind(
|
|
181
|
+
tsMorph.SyntaxKind.TypeReference
|
|
182
|
+
);
|
|
183
|
+
for (const typeRef of typeRefs) {
|
|
184
|
+
const symbol = typeRef.getType().getAliasSymbol() ?? typeRef.getType().getSymbol();
|
|
185
|
+
if (symbol) symbolsToProcess.add(symbol);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
} else if (decl.getKind() === tsMorph.SyntaxKind.InterfaceDeclaration || decl.getKind() === tsMorph.SyntaxKind.TypeAliasDeclaration) {
|
|
189
|
+
const typeRefs = decl.getDescendantsOfKind(tsMorph.SyntaxKind.TypeReference);
|
|
190
|
+
for (const typeRef of typeRefs) {
|
|
191
|
+
const symbol = typeRef.getType().getAliasSymbol() ?? typeRef.getType().getSymbol();
|
|
192
|
+
if (symbol) symbolsToProcess.add(symbol);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const importsMap = /* @__PURE__ */ new Map();
|
|
197
|
+
const inlineDefinitions = /* @__PURE__ */ new Map();
|
|
198
|
+
const processedSymbols = /* @__PURE__ */ new Set();
|
|
199
|
+
while (symbolsToProcess.size > 0) {
|
|
200
|
+
const symbol = symbolsToProcess.values().next().value;
|
|
201
|
+
if (!symbol) continue;
|
|
202
|
+
symbolsToProcess.delete(symbol);
|
|
203
|
+
const symbolName = symbol.getName();
|
|
204
|
+
if (processedSymbols.has(symbolName) || exportedDeclarationNames.has(symbolName) || symbolName === "__type") {
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const symbolFlags = symbol.getFlags();
|
|
208
|
+
if (symbolFlags & tsMorph.SymbolFlags.TypeParameter) {
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const declaration = symbol.getDeclarations()[0];
|
|
212
|
+
if (!declaration) {
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const sourceFile = declaration.getSourceFile();
|
|
216
|
+
if (sourceFile.getFilePath().includes("node_modules")) {
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
processedSymbols.add(symbolName);
|
|
220
|
+
const isLocalDefinition = declaration.getParent()?.getKind() !== tsMorph.SyntaxKind.SourceFile;
|
|
221
|
+
if (isLocalDefinition) {
|
|
222
|
+
if (returnValueSymbols.has(symbol)) {
|
|
223
|
+
const declText = declaration.getText();
|
|
224
|
+
inlineDefinitions.set(symbolName, declText);
|
|
225
|
+
const tempSourceFile = project.createSourceFile(
|
|
226
|
+
`__temp_${symbolName}.ts`,
|
|
227
|
+
declText
|
|
228
|
+
);
|
|
229
|
+
for (const descendant of tempSourceFile.getDescendantsOfKind(
|
|
230
|
+
tsMorph.SyntaxKind.TypeReference
|
|
231
|
+
)) {
|
|
232
|
+
const newSymbol = descendant.getType().getAliasSymbol() ?? descendant.getType().getSymbol();
|
|
233
|
+
if (newSymbol) {
|
|
234
|
+
symbolsToProcess.add(newSymbol);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
tempSourceFile.delete();
|
|
238
|
+
}
|
|
239
|
+
} else {
|
|
240
|
+
let modulePath = path__namespace.relative(absoluteOutDir, sourceFile.getFilePath()).replace(/\\/g, "/");
|
|
241
|
+
modulePath = modulePath.replace(/\.(d\.)?ts$/, "");
|
|
242
|
+
if (modulePath.endsWith("/index")) {
|
|
243
|
+
modulePath = modulePath.slice(0, -6);
|
|
244
|
+
}
|
|
245
|
+
if (modulePath === "index" || modulePath === "") {
|
|
246
|
+
modulePath = ".";
|
|
247
|
+
}
|
|
248
|
+
if (!modulePath.startsWith(".")) {
|
|
249
|
+
modulePath = `./${modulePath}`;
|
|
250
|
+
}
|
|
251
|
+
if (!importsMap.has(modulePath)) {
|
|
252
|
+
importsMap.set(modulePath, /* @__PURE__ */ new Set());
|
|
253
|
+
}
|
|
254
|
+
importsMap.get(modulePath)?.add(symbolName);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (!fs__namespace.existsSync(absoluteOutDir)) {
|
|
258
|
+
fs__namespace.mkdirSync(absoluteOutDir, { recursive: true });
|
|
259
|
+
consola.consola.info(`Created output directory: ${absoluteOutDir}`);
|
|
260
|
+
}
|
|
261
|
+
const generatorName = "gasnuki";
|
|
262
|
+
let outputContent = `// Auto-generated by ${generatorName}
|
|
263
|
+
// Do NOT edit this file manually.
|
|
264
|
+
|
|
265
|
+
`;
|
|
266
|
+
const sortedModulePaths = [...importsMap.keys()].sort((a, b) => {
|
|
267
|
+
const aIsRelative = a.startsWith(".");
|
|
268
|
+
const bIsRelative = b.startsWith(".");
|
|
269
|
+
if (aIsRelative !== bIsRelative) return aIsRelative ? 1 : -1;
|
|
270
|
+
return a.localeCompare(b);
|
|
271
|
+
});
|
|
272
|
+
if (sortedModulePaths.length > 0) {
|
|
273
|
+
const importStatements = sortedModulePaths.map((modulePath) => {
|
|
274
|
+
const imports = [...importsMap.get(modulePath) ?? []].sort();
|
|
275
|
+
const finalModulePath = modulePath === "." ? "./index" : modulePath;
|
|
276
|
+
return `import type { ${imports.join(", ")} } from '${finalModulePath}';`;
|
|
277
|
+
});
|
|
278
|
+
outputContent += `${importStatements.join("\n")}
|
|
279
|
+
|
|
280
|
+
`;
|
|
281
|
+
}
|
|
282
|
+
if (inlineDefinitions.size > 0) {
|
|
283
|
+
outputContent += `${[...inlineDefinitions.values()].join("\n\n")}
|
|
284
|
+
|
|
285
|
+
`;
|
|
286
|
+
}
|
|
287
|
+
const exportedTypeDefinitions = exportedDeclarations.filter(
|
|
288
|
+
(d) => d.getKind() === tsMorph.SyntaxKind.InterfaceDeclaration || d.getKind() === tsMorph.SyntaxKind.TypeAliasDeclaration
|
|
289
|
+
).map((decl) => decl.getText());
|
|
290
|
+
if (exportedTypeDefinitions.length > 0) {
|
|
291
|
+
outputContent += `${exportedTypeDefinitions.join("\n\n")}
|
|
292
|
+
|
|
293
|
+
`;
|
|
294
|
+
}
|
|
295
|
+
if (methodDefinitions.length > 0) {
|
|
296
|
+
const formattedMethods = methodDefinitions.map(
|
|
297
|
+
(method) => method.split("\n").map((line) => ` ${line}`).join("\n")
|
|
298
|
+
).join("\n\n");
|
|
299
|
+
outputContent += `export type ServerScripts = {
|
|
300
|
+
${formattedMethods}
|
|
301
|
+
}
|
|
302
|
+
`;
|
|
303
|
+
consola.consola.info(
|
|
304
|
+
`Interface 'ServerScript' type definitions written to ${absoluteOutputFile} (${methodDefinitions.length} function(s), ${exportedTypeDefinitions.length + inlineDefinitions.size} type(s)).`
|
|
305
|
+
);
|
|
306
|
+
} else {
|
|
307
|
+
outputContent += "export type ServerScripts = {}\n";
|
|
308
|
+
consola.consola.info(
|
|
309
|
+
`Interface 'ServerScript' type definitions written to ${absoluteOutputFile} (no functions found).`
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
outputContent += `
|
|
313
|
+
// Auto-generated Types for GoogleAppsScript in client-side code
|
|
314
|
+
|
|
315
|
+
${text}`;
|
|
316
|
+
fs__namespace.writeFileSync(absoluteOutputFile, outputContent);
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
function defineConfig(config) {
|
|
320
|
+
return config;
|
|
321
|
+
}
|
|
322
|
+
async function loadConfig(projectRoot) {
|
|
323
|
+
const configFileExtensions = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
|
|
324
|
+
let foundConfigPath;
|
|
325
|
+
let foundConfigFileName;
|
|
326
|
+
for (const configFileExtension of configFileExtensions) {
|
|
327
|
+
const configFile = `gasnuki.config${configFileExtension}`;
|
|
328
|
+
const fullPath = path__namespace.resolve(projectRoot, configFile);
|
|
329
|
+
if (fs__namespace.existsSync(fullPath)) {
|
|
330
|
+
foundConfigPath = fullPath;
|
|
331
|
+
foundConfigFileName = configFile;
|
|
332
|
+
break;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
if (!foundConfigPath || !foundConfigFileName) {
|
|
336
|
+
return {};
|
|
337
|
+
}
|
|
338
|
+
try {
|
|
339
|
+
const jiti$1 = jiti.createJiti(projectRoot, {
|
|
340
|
+
fsCache: false,
|
|
341
|
+
moduleCache: false,
|
|
342
|
+
interopDefault: true
|
|
343
|
+
});
|
|
344
|
+
const configModule = await jiti$1.import(foundConfigPath, {
|
|
345
|
+
default: true
|
|
346
|
+
});
|
|
347
|
+
consola.consola.success(`Loaded configuration from ${foundConfigFileName}`);
|
|
348
|
+
return configModule;
|
|
349
|
+
} catch (error) {
|
|
350
|
+
consola.consola.error(`Error loading ${foundConfigFileName}:`, error);
|
|
351
|
+
return {};
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const generateTypes = async ({
|
|
356
|
+
project,
|
|
357
|
+
srcDir,
|
|
358
|
+
outDir,
|
|
359
|
+
outputFile,
|
|
360
|
+
watch
|
|
361
|
+
}) => {
|
|
362
|
+
const runGeneration = async (triggeredBy) => {
|
|
363
|
+
const reason = triggeredBy ? ` (${triggeredBy})` : "";
|
|
364
|
+
consola.consola.info(`Generating AppsScript types${reason}...`);
|
|
365
|
+
try {
|
|
366
|
+
await generateAppsScriptTypes({ project, srcDir, outDir, outputFile });
|
|
367
|
+
consola.consola.info("Type generation complete.");
|
|
368
|
+
} catch (e) {
|
|
369
|
+
consola.consola.error(`Type generation failed: ${e.message}`, e);
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
await runGeneration();
|
|
373
|
+
if (watch) {
|
|
374
|
+
const sourcePathToWatch = path__namespace.resolve(project, srcDir).replace(/\\/g, "/");
|
|
375
|
+
consola.consola.info(
|
|
376
|
+
`Watching for changes in ${sourcePathToWatch}... (Press Ctrl+C to stop)`
|
|
377
|
+
);
|
|
378
|
+
const watcher = chokidar__namespace.watch(sourcePathToWatch, {
|
|
379
|
+
ignored: ["node_modules", "dist"],
|
|
380
|
+
persistent: true,
|
|
381
|
+
ignoreInitial: true
|
|
382
|
+
});
|
|
383
|
+
const eventHandler = async (filePath, eventName) => {
|
|
384
|
+
consola.consola.info(`Watcher is called triggered on ${eventName}`);
|
|
385
|
+
const relativePath = path__namespace.relative(project, filePath);
|
|
386
|
+
await runGeneration(relativePath);
|
|
387
|
+
};
|
|
388
|
+
watcher.on("ready", async () => {
|
|
389
|
+
console.log("...waiting...");
|
|
390
|
+
watcher.on("all", async (event, path2) => {
|
|
391
|
+
consola.consola.info(`Watcher is called triggered on ${event}: ${path2}`);
|
|
392
|
+
await eventHandler(path2, event);
|
|
393
|
+
});
|
|
394
|
+
});
|
|
395
|
+
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
396
|
+
process.on(signal, async () => {
|
|
397
|
+
await watcher.close();
|
|
398
|
+
consola.consola.info("Watcher is closed.");
|
|
399
|
+
process.exit(0);
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
} else {
|
|
403
|
+
process.exit(0);
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
exports.defineConfig = defineConfig;
|
|
408
|
+
exports.generateTypes = generateTypes;
|
|
409
|
+
exports.loadConfig = loadConfig;
|
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
import * as path from 'node:path';
|
|
2
|
+
import * as chokidar from 'chokidar';
|
|
3
|
+
import { consola } from 'consola';
|
|
4
|
+
import * as fs from 'node:fs';
|
|
5
|
+
import { Project, SyntaxKind, SymbolFlags } from 'ts-morph';
|
|
6
|
+
import { createJiti } from 'jiti';
|
|
7
|
+
|
|
8
|
+
const text = "export type RemoveReturnType<T> = {\n [P in keyof T]: T[P] extends (...args: infer A) => any\n ? (...args: A) => void\n : T[P];\n};\n\ntype _AppsScriptRun = RemoveReturnType<ServerScripts> & {\n [key: string]: (...args: any[]) => any;\n withSuccessHandler: <T = string | number | boolean | undefined, U = any>(\n callback: (returnValues: T, userObject?: U) => void,\n ) => _AppsScriptRun;\n withFailureHandler: <U = any>(\n callback: (error: Error, userObject?: U) => void,\n ) => _AppsScriptRun;\n withUserObject: <U = any>(userObject: U) => _AppsScriptRun;\n};\n\ntype _AppsScriptHistoryFunction = (\n stateObject: object,\n params: object,\n hash: string,\n) => void;\n\ninterface _WebAppLocationType {\n hash: string;\n parameter: Record<string, string>;\n parameters: Record<string, string[]>;\n}\n\nexport declare interface GoogleClientSideApi {\n script: {\n run: _AppsScriptRun;\n url: {\n getLocation: (callback: (location: _WebAppLocationType) => void) => void;\n };\n history: {\n push: _AppsScriptHistoryFunction;\n replace: _AppsScriptHistoryFunction;\n setChangeHandler: (\n callback: (e: { state: object; location: _WebAppLocationType }) => void,\n ) => void;\n };\n };\n}\n\ndeclare global {\n const google: GoogleClientSideApi;\n}\n";
|
|
9
|
+
|
|
10
|
+
const getInterfaceMethodDefinition_ = (name, node) => {
|
|
11
|
+
const typeParameters = node.getTypeParameters?.() ?? [];
|
|
12
|
+
const typeParamsString = typeParameters.length > 0 ? `<${typeParameters.map((tp) => tp.getText()).join(", ")}>` : "";
|
|
13
|
+
const parameters = node.getParameters().map((param) => {
|
|
14
|
+
const paramName = param.getName();
|
|
15
|
+
const type = param.getTypeNode()?.getText() ?? param.getType().getText(node) ?? "any";
|
|
16
|
+
const questionToken = param.hasQuestionToken() ? "?" : "";
|
|
17
|
+
return `${paramName}${questionToken}: ${type}`;
|
|
18
|
+
}).join(", ");
|
|
19
|
+
const returnTypeNode = node.getReturnTypeNode();
|
|
20
|
+
let returnType;
|
|
21
|
+
if (returnTypeNode != null) {
|
|
22
|
+
returnType = returnTypeNode.getText();
|
|
23
|
+
} else {
|
|
24
|
+
const inferredReturnType = node.getReturnType();
|
|
25
|
+
if (inferredReturnType.isVoid()) {
|
|
26
|
+
returnType = "void";
|
|
27
|
+
} else {
|
|
28
|
+
returnType = inferredReturnType.getText(node);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
let jsDocString = "";
|
|
32
|
+
const jsDocOwner = "getJsDocs" in node ? node : "getParentOrThrow" in node && // @ts-expect-error variable declaration
|
|
33
|
+
node.getParentOrThrow().getKind() === SyntaxKind.VariableDeclaration ? (
|
|
34
|
+
// @ts-expect-error variable declaration
|
|
35
|
+
node.getParentOrThrow()
|
|
36
|
+
) : null;
|
|
37
|
+
if (jsDocOwner != null) {
|
|
38
|
+
const jsDocs = "getJsDocs" in jsDocOwner ? jsDocOwner.getJsDocs() : [];
|
|
39
|
+
if (jsDocs.length > 0) {
|
|
40
|
+
const firstDoc = jsDocs[0];
|
|
41
|
+
jsDocString = `${firstDoc.getFullText().trim()}
|
|
42
|
+
`;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return `${jsDocString}${name}${typeParamsString}(${parameters}): ${returnType};`;
|
|
46
|
+
};
|
|
47
|
+
const SIMPLE_TRIGGER_FUNCTION_NAMES = [
|
|
48
|
+
"onOpen",
|
|
49
|
+
"onEdit",
|
|
50
|
+
"onInstall",
|
|
51
|
+
"onSelectionChange",
|
|
52
|
+
"doGet",
|
|
53
|
+
"doPost"
|
|
54
|
+
];
|
|
55
|
+
const generateAppsScriptTypes = async ({
|
|
56
|
+
project: projectPath,
|
|
57
|
+
srcDir,
|
|
58
|
+
outDir,
|
|
59
|
+
outputFile
|
|
60
|
+
}) => {
|
|
61
|
+
const absoluteSrcDir = path.resolve(projectPath, srcDir);
|
|
62
|
+
const absoluteOutDir = path.resolve(projectPath, outDir);
|
|
63
|
+
const absoluteOutputFile = path.resolve(absoluteOutDir, outputFile);
|
|
64
|
+
consola.info("Starting AppsScript type generation with gasnuki...");
|
|
65
|
+
consola.info(` AppsScript Source Directory: ${absoluteSrcDir}`);
|
|
66
|
+
consola.info(` Output File: ${absoluteOutputFile}`);
|
|
67
|
+
const project = new Project({
|
|
68
|
+
tsConfigFilePath: path.resolve(projectPath, "tsconfig.json"),
|
|
69
|
+
skipAddingFilesFromTsConfig: true
|
|
70
|
+
});
|
|
71
|
+
const sourceFilesPattern = path.join(absoluteSrcDir, "**/*.ts").replace(/\\/g, "/");
|
|
72
|
+
const testFilesPattern = `!${path.join(absoluteSrcDir, "**/*.{test,spec}.ts").replace(/\\/g, "/")}`;
|
|
73
|
+
project.addSourceFilesAtPaths([sourceFilesPattern, testFilesPattern]);
|
|
74
|
+
const sourceFiles = project.getSourceFiles();
|
|
75
|
+
consola.info(`Found ${sourceFiles.length} source file(s).`);
|
|
76
|
+
const methodDefinitions = [];
|
|
77
|
+
const exportedDeclarations = [];
|
|
78
|
+
const exportedDeclarationNames = /* @__PURE__ */ new Set();
|
|
79
|
+
const exportedFunctions = [];
|
|
80
|
+
for (const sourceFile of sourceFiles) {
|
|
81
|
+
for (const iface of sourceFile.getInterfaces()) {
|
|
82
|
+
if (iface.isExported() && !iface.getName()?.endsWith("_")) {
|
|
83
|
+
exportedDeclarations.push(iface);
|
|
84
|
+
exportedDeclarationNames.add(iface.getName());
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
for (const typeAlias of sourceFile.getTypeAliases()) {
|
|
88
|
+
if (typeAlias.isExported() && !typeAlias.getName().endsWith("_")) {
|
|
89
|
+
exportedDeclarations.push(typeAlias);
|
|
90
|
+
exportedDeclarationNames.add(typeAlias.getName());
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
for (const func of sourceFile.getFunctions()) {
|
|
94
|
+
const name = func.getName();
|
|
95
|
+
if (func.isExported() && name && !name.endsWith("_") && !SIMPLE_TRIGGER_FUNCTION_NAMES.includes(name)) {
|
|
96
|
+
exportedDeclarations.push(func);
|
|
97
|
+
exportedDeclarationNames.add(name);
|
|
98
|
+
methodDefinitions.push(getInterfaceMethodDefinition_(name, func));
|
|
99
|
+
exportedFunctions.push(func);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
for (const varStmt of sourceFile.getVariableStatements()) {
|
|
103
|
+
if (!varStmt.isExported()) continue;
|
|
104
|
+
for (const varDecl of varStmt.getDeclarations()) {
|
|
105
|
+
const name = varDecl.getName();
|
|
106
|
+
const initializer = varDecl.getInitializer();
|
|
107
|
+
if (!name.endsWith("_") && !SIMPLE_TRIGGER_FUNCTION_NAMES.includes(name) && initializer && (initializer.getKind() === SyntaxKind.ArrowFunction || initializer.getKind() === SyntaxKind.FunctionExpression)) {
|
|
108
|
+
const funcExpr = initializer;
|
|
109
|
+
exportedDeclarations.push(varDecl);
|
|
110
|
+
exportedDeclarationNames.add(name);
|
|
111
|
+
methodDefinitions.push(getInterfaceMethodDefinition_(name, funcExpr));
|
|
112
|
+
exportedFunctions.push(funcExpr);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const collectSymbolsFromType = (type, foundSymbols) => {
|
|
118
|
+
const symbol = type.getAliasSymbol() ?? type.getSymbol();
|
|
119
|
+
if (symbol && !foundSymbols.has(symbol)) {
|
|
120
|
+
foundSymbols.add(symbol);
|
|
121
|
+
if (type.isObject()) {
|
|
122
|
+
for (const prop of type.getProperties()) {
|
|
123
|
+
const propDecl = prop.getDeclarations()[0];
|
|
124
|
+
if (propDecl) {
|
|
125
|
+
collectSymbolsFromType(propDecl.getType(), foundSymbols);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
for (const typeArg of type.getTypeArguments()) {
|
|
131
|
+
collectSymbolsFromType(typeArg, foundSymbols);
|
|
132
|
+
}
|
|
133
|
+
if (type.isUnion()) {
|
|
134
|
+
for (const unionType of type.getUnionTypes()) {
|
|
135
|
+
collectSymbolsFromType(unionType, foundSymbols);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (type.isIntersection()) {
|
|
139
|
+
for (const intersectionType of type.getIntersectionTypes()) {
|
|
140
|
+
collectSymbolsFromType(intersectionType, foundSymbols);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
const returnValueSymbols = /* @__PURE__ */ new Set();
|
|
145
|
+
for (const func of exportedFunctions) {
|
|
146
|
+
collectSymbolsFromType(func.getReturnType(), returnValueSymbols);
|
|
147
|
+
}
|
|
148
|
+
const symbolsToProcess = /* @__PURE__ */ new Set();
|
|
149
|
+
for (const decl of exportedDeclarations) {
|
|
150
|
+
if (decl.getKind() === SyntaxKind.FunctionDeclaration || decl.getKind() === SyntaxKind.VariableDeclaration && (decl.getInitializer()?.getKind() === SyntaxKind.ArrowFunction || decl.getInitializer()?.getKind() === SyntaxKind.FunctionExpression)) {
|
|
151
|
+
const func = decl.getKind() === SyntaxKind.FunctionDeclaration ? decl : decl.getInitializer();
|
|
152
|
+
const parameters = func.getParameters();
|
|
153
|
+
for (const param of parameters) {
|
|
154
|
+
const typeRefs = param.getDescendantsOfKind(SyntaxKind.TypeReference);
|
|
155
|
+
for (const typeRef of typeRefs) {
|
|
156
|
+
const symbol = typeRef.getType().getAliasSymbol() ?? typeRef.getType().getSymbol();
|
|
157
|
+
if (symbol) symbolsToProcess.add(symbol);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const returnTypeNode = func.getReturnTypeNode();
|
|
161
|
+
if (returnTypeNode) {
|
|
162
|
+
const typeRefs = returnTypeNode.getDescendantsOfKind(
|
|
163
|
+
SyntaxKind.TypeReference
|
|
164
|
+
);
|
|
165
|
+
for (const typeRef of typeRefs) {
|
|
166
|
+
const symbol = typeRef.getType().getAliasSymbol() ?? typeRef.getType().getSymbol();
|
|
167
|
+
if (symbol) symbolsToProcess.add(symbol);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
} else if (decl.getKind() === SyntaxKind.InterfaceDeclaration || decl.getKind() === SyntaxKind.TypeAliasDeclaration) {
|
|
171
|
+
const typeRefs = decl.getDescendantsOfKind(SyntaxKind.TypeReference);
|
|
172
|
+
for (const typeRef of typeRefs) {
|
|
173
|
+
const symbol = typeRef.getType().getAliasSymbol() ?? typeRef.getType().getSymbol();
|
|
174
|
+
if (symbol) symbolsToProcess.add(symbol);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const importsMap = /* @__PURE__ */ new Map();
|
|
179
|
+
const inlineDefinitions = /* @__PURE__ */ new Map();
|
|
180
|
+
const processedSymbols = /* @__PURE__ */ new Set();
|
|
181
|
+
while (symbolsToProcess.size > 0) {
|
|
182
|
+
const symbol = symbolsToProcess.values().next().value;
|
|
183
|
+
if (!symbol) continue;
|
|
184
|
+
symbolsToProcess.delete(symbol);
|
|
185
|
+
const symbolName = symbol.getName();
|
|
186
|
+
if (processedSymbols.has(symbolName) || exportedDeclarationNames.has(symbolName) || symbolName === "__type") {
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const symbolFlags = symbol.getFlags();
|
|
190
|
+
if (symbolFlags & SymbolFlags.TypeParameter) {
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const declaration = symbol.getDeclarations()[0];
|
|
194
|
+
if (!declaration) {
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
const sourceFile = declaration.getSourceFile();
|
|
198
|
+
if (sourceFile.getFilePath().includes("node_modules")) {
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
processedSymbols.add(symbolName);
|
|
202
|
+
const isLocalDefinition = declaration.getParent()?.getKind() !== SyntaxKind.SourceFile;
|
|
203
|
+
if (isLocalDefinition) {
|
|
204
|
+
if (returnValueSymbols.has(symbol)) {
|
|
205
|
+
const declText = declaration.getText();
|
|
206
|
+
inlineDefinitions.set(symbolName, declText);
|
|
207
|
+
const tempSourceFile = project.createSourceFile(
|
|
208
|
+
`__temp_${symbolName}.ts`,
|
|
209
|
+
declText
|
|
210
|
+
);
|
|
211
|
+
for (const descendant of tempSourceFile.getDescendantsOfKind(
|
|
212
|
+
SyntaxKind.TypeReference
|
|
213
|
+
)) {
|
|
214
|
+
const newSymbol = descendant.getType().getAliasSymbol() ?? descendant.getType().getSymbol();
|
|
215
|
+
if (newSymbol) {
|
|
216
|
+
symbolsToProcess.add(newSymbol);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
tempSourceFile.delete();
|
|
220
|
+
}
|
|
221
|
+
} else {
|
|
222
|
+
let modulePath = path.relative(absoluteOutDir, sourceFile.getFilePath()).replace(/\\/g, "/");
|
|
223
|
+
modulePath = modulePath.replace(/\.(d\.)?ts$/, "");
|
|
224
|
+
if (modulePath.endsWith("/index")) {
|
|
225
|
+
modulePath = modulePath.slice(0, -6);
|
|
226
|
+
}
|
|
227
|
+
if (modulePath === "index" || modulePath === "") {
|
|
228
|
+
modulePath = ".";
|
|
229
|
+
}
|
|
230
|
+
if (!modulePath.startsWith(".")) {
|
|
231
|
+
modulePath = `./${modulePath}`;
|
|
232
|
+
}
|
|
233
|
+
if (!importsMap.has(modulePath)) {
|
|
234
|
+
importsMap.set(modulePath, /* @__PURE__ */ new Set());
|
|
235
|
+
}
|
|
236
|
+
importsMap.get(modulePath)?.add(symbolName);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (!fs.existsSync(absoluteOutDir)) {
|
|
240
|
+
fs.mkdirSync(absoluteOutDir, { recursive: true });
|
|
241
|
+
consola.info(`Created output directory: ${absoluteOutDir}`);
|
|
242
|
+
}
|
|
243
|
+
const generatorName = "gasnuki";
|
|
244
|
+
let outputContent = `// Auto-generated by ${generatorName}
|
|
245
|
+
// Do NOT edit this file manually.
|
|
246
|
+
|
|
247
|
+
`;
|
|
248
|
+
const sortedModulePaths = [...importsMap.keys()].sort((a, b) => {
|
|
249
|
+
const aIsRelative = a.startsWith(".");
|
|
250
|
+
const bIsRelative = b.startsWith(".");
|
|
251
|
+
if (aIsRelative !== bIsRelative) return aIsRelative ? 1 : -1;
|
|
252
|
+
return a.localeCompare(b);
|
|
253
|
+
});
|
|
254
|
+
if (sortedModulePaths.length > 0) {
|
|
255
|
+
const importStatements = sortedModulePaths.map((modulePath) => {
|
|
256
|
+
const imports = [...importsMap.get(modulePath) ?? []].sort();
|
|
257
|
+
const finalModulePath = modulePath === "." ? "./index" : modulePath;
|
|
258
|
+
return `import type { ${imports.join(", ")} } from '${finalModulePath}';`;
|
|
259
|
+
});
|
|
260
|
+
outputContent += `${importStatements.join("\n")}
|
|
261
|
+
|
|
262
|
+
`;
|
|
263
|
+
}
|
|
264
|
+
if (inlineDefinitions.size > 0) {
|
|
265
|
+
outputContent += `${[...inlineDefinitions.values()].join("\n\n")}
|
|
266
|
+
|
|
267
|
+
`;
|
|
268
|
+
}
|
|
269
|
+
const exportedTypeDefinitions = exportedDeclarations.filter(
|
|
270
|
+
(d) => d.getKind() === SyntaxKind.InterfaceDeclaration || d.getKind() === SyntaxKind.TypeAliasDeclaration
|
|
271
|
+
).map((decl) => decl.getText());
|
|
272
|
+
if (exportedTypeDefinitions.length > 0) {
|
|
273
|
+
outputContent += `${exportedTypeDefinitions.join("\n\n")}
|
|
274
|
+
|
|
275
|
+
`;
|
|
276
|
+
}
|
|
277
|
+
if (methodDefinitions.length > 0) {
|
|
278
|
+
const formattedMethods = methodDefinitions.map(
|
|
279
|
+
(method) => method.split("\n").map((line) => ` ${line}`).join("\n")
|
|
280
|
+
).join("\n\n");
|
|
281
|
+
outputContent += `export type ServerScripts = {
|
|
282
|
+
${formattedMethods}
|
|
283
|
+
}
|
|
284
|
+
`;
|
|
285
|
+
consola.info(
|
|
286
|
+
`Interface 'ServerScript' type definitions written to ${absoluteOutputFile} (${methodDefinitions.length} function(s), ${exportedTypeDefinitions.length + inlineDefinitions.size} type(s)).`
|
|
287
|
+
);
|
|
288
|
+
} else {
|
|
289
|
+
outputContent += "export type ServerScripts = {}\n";
|
|
290
|
+
consola.info(
|
|
291
|
+
`Interface 'ServerScript' type definitions written to ${absoluteOutputFile} (no functions found).`
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
outputContent += `
|
|
295
|
+
// Auto-generated Types for GoogleAppsScript in client-side code
|
|
296
|
+
|
|
297
|
+
${text}`;
|
|
298
|
+
fs.writeFileSync(absoluteOutputFile, outputContent);
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
function defineConfig(config) {
|
|
302
|
+
return config;
|
|
303
|
+
}
|
|
304
|
+
async function loadConfig(projectRoot) {
|
|
305
|
+
const configFileExtensions = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
|
|
306
|
+
let foundConfigPath;
|
|
307
|
+
let foundConfigFileName;
|
|
308
|
+
for (const configFileExtension of configFileExtensions) {
|
|
309
|
+
const configFile = `gasnuki.config${configFileExtension}`;
|
|
310
|
+
const fullPath = path.resolve(projectRoot, configFile);
|
|
311
|
+
if (fs.existsSync(fullPath)) {
|
|
312
|
+
foundConfigPath = fullPath;
|
|
313
|
+
foundConfigFileName = configFile;
|
|
314
|
+
break;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if (!foundConfigPath || !foundConfigFileName) {
|
|
318
|
+
return {};
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
const jiti = createJiti(projectRoot, {
|
|
322
|
+
fsCache: false,
|
|
323
|
+
moduleCache: false,
|
|
324
|
+
interopDefault: true
|
|
325
|
+
});
|
|
326
|
+
const configModule = await jiti.import(foundConfigPath, {
|
|
327
|
+
default: true
|
|
328
|
+
});
|
|
329
|
+
consola.success(`Loaded configuration from ${foundConfigFileName}`);
|
|
330
|
+
return configModule;
|
|
331
|
+
} catch (error) {
|
|
332
|
+
consola.error(`Error loading ${foundConfigFileName}:`, error);
|
|
333
|
+
return {};
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const generateTypes = async ({
|
|
338
|
+
project,
|
|
339
|
+
srcDir,
|
|
340
|
+
outDir,
|
|
341
|
+
outputFile,
|
|
342
|
+
watch
|
|
343
|
+
}) => {
|
|
344
|
+
const runGeneration = async (triggeredBy) => {
|
|
345
|
+
const reason = triggeredBy ? ` (${triggeredBy})` : "";
|
|
346
|
+
consola.info(`Generating AppsScript types${reason}...`);
|
|
347
|
+
try {
|
|
348
|
+
await generateAppsScriptTypes({ project, srcDir, outDir, outputFile });
|
|
349
|
+
consola.info("Type generation complete.");
|
|
350
|
+
} catch (e) {
|
|
351
|
+
consola.error(`Type generation failed: ${e.message}`, e);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
await runGeneration();
|
|
355
|
+
if (watch) {
|
|
356
|
+
const sourcePathToWatch = path.resolve(project, srcDir).replace(/\\/g, "/");
|
|
357
|
+
consola.info(
|
|
358
|
+
`Watching for changes in ${sourcePathToWatch}... (Press Ctrl+C to stop)`
|
|
359
|
+
);
|
|
360
|
+
const watcher = chokidar.watch(sourcePathToWatch, {
|
|
361
|
+
ignored: ["node_modules", "dist"],
|
|
362
|
+
persistent: true,
|
|
363
|
+
ignoreInitial: true
|
|
364
|
+
});
|
|
365
|
+
const eventHandler = async (filePath, eventName) => {
|
|
366
|
+
consola.info(`Watcher is called triggered on ${eventName}`);
|
|
367
|
+
const relativePath = path.relative(project, filePath);
|
|
368
|
+
await runGeneration(relativePath);
|
|
369
|
+
};
|
|
370
|
+
watcher.on("ready", async () => {
|
|
371
|
+
console.log("...waiting...");
|
|
372
|
+
watcher.on("all", async (event, path2) => {
|
|
373
|
+
consola.info(`Watcher is called triggered on ${event}: ${path2}`);
|
|
374
|
+
await eventHandler(path2, event);
|
|
375
|
+
});
|
|
376
|
+
});
|
|
377
|
+
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
378
|
+
process.on(signal, async () => {
|
|
379
|
+
await watcher.close();
|
|
380
|
+
consola.info("Watcher is closed.");
|
|
381
|
+
process.exit(0);
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
} else {
|
|
385
|
+
process.exit(0);
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
export { defineConfig as d, generateTypes as g, loadConfig as l };
|