@automateinc/fleet-types 1.0.103 → 1.0.104

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.
@@ -2,9 +2,8 @@
2
2
 
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { existsSync } from "node:fs";
5
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
5
+ import { mkdir, writeFile } from "node:fs/promises";
6
6
  import { createRequire } from "node:module";
7
- import { tmpdir } from "node:os";
8
7
  import path from "node:path";
9
8
  import { loadEnvFile } from "node:process";
10
9
  import { fileURLToPath } from "node:url";
@@ -51,184 +50,128 @@ async function generateTypes() {
51
50
  const apiRoot = path.resolve(callerRoot, fleetApiPath);
52
51
  const outputPath = path.resolve(callerRoot, fleetApiTypesPath);
53
52
  const routerSourcePath = path.join(apiRoot, "src/routers/trpc/index.ts");
54
- const prismaTypesPath = path.join(apiRoot, "prisma/types.d.ts");
53
+ const apiTsconfigPath = path.join(apiRoot, "tsconfig.json");
55
54
  const executableExtension = process.platform === "win32" ? ".cmd" : "";
56
- const apiTscPath = path.join(apiRoot, `node_modules/.bin/tsc${executableExtension}`);
57
55
  const callerBiomePath = path.join(callerRoot, `node_modules/.bin/biome${executableExtension}`);
58
56
  const packageBiomePath = path.join(packageRoot, `node_modules/.bin/biome${executableExtension}`);
59
57
  const biomePath = existsSync(callerBiomePath) ? callerBiomePath : packageBiomePath;
60
- const temporaryDirectory = await mkdtemp(path.join(tmpdir(), "fleet-trpc-types-"));
61
- const declarationOutputDirectory = path.join(temporaryDirectory, "declarations");
62
- const declarationTsconfigPath = path.join(temporaryDirectory, "tsconfig.json");
63
- const prismaJsonShimPath = path.join(temporaryDirectory, "prisma-json.d.ts");
64
- const serviceProviderShimPath = path.join(temporaryDirectory, "service-provider.d.ts");
65
58
  const requireFromPackage = createRequire(path.join(packageRoot, "package.json"));
66
59
  const ts = requireFromPackage("typescript");
60
+ const configResult = ts.readConfigFile(apiTsconfigPath, ts.sys.readFile);
67
61
 
68
- try {
69
- const prismaTypesContent = await readFile(prismaTypesPath, "utf8");
70
- const prismaTypesSource = ts.createSourceFile(prismaTypesPath, prismaTypesContent, ts.ScriptTarget.Latest, true);
71
- let coordsType;
72
- const findCoordsType = node => {
73
- if (ts.isModuleDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === "PrismaJson") {
74
- const body = node.body;
75
- if (body && ts.isModuleBlock(body)) {
76
- coordsType = body.statements.find(
77
- statement => ts.isTypeAliasDeclaration(statement) && statement.name.text === "Coords",
78
- );
79
- }
80
- }
81
- ts.forEachChild(node, findCoordsType);
82
- };
83
- findCoordsType(prismaTypesSource);
84
- if (!coordsType) {
85
- throw new Error(`PrismaJson.Coords was not found in ${prismaTypesPath}.`);
86
- }
87
- const coordsTypeDeclaration = ts
88
- .createPrinter({ newLine: ts.NewLineKind.LineFeed })
89
- .printNode(ts.EmitHint.Unspecified, coordsType, prismaTypesSource);
90
-
91
- await writeFile(
92
- prismaJsonShimPath,
93
- `export {};\ndeclare global { namespace PrismaJson { ${coordsTypeDeclaration} } }\n`,
94
- );
95
- await writeFile(
96
- serviceProviderShimPath,
97
- `interface Permission {
98
- name: string;
99
- }
62
+ if (configResult.error) {
63
+ throw new Error(formatTypeScriptDiagnostics(ts, [configResult.error], apiRoot));
64
+ }
100
65
 
101
- interface AuthenticatedUser {
102
- id: number;
103
- dailyHours: number | null;
104
- permissionGroups: { permissions: Permission[] }[];
105
- permissions: Permission[];
106
- team: { folderKey: string | null; id: number } | null;
107
- }
66
+ const parsedConfig = ts.parseJsonConfigFileContent(
67
+ configResult.config,
68
+ ts.sys,
69
+ apiRoot,
70
+ {
71
+ declaration: true,
72
+ declarationMap: false,
73
+ emitDeclarationOnly: true,
74
+ incremental: false,
75
+ noEmit: false,
76
+ noEmitOnError: false,
77
+ },
78
+ apiTsconfigPath,
79
+ );
80
+
81
+ if (parsedConfig.errors.length > 0) {
82
+ throw new Error(formatTypeScriptDiagnostics(ts, parsedConfig.errors, apiRoot));
83
+ }
108
84
 
109
- interface DecodedToken {
110
- permissions: string[];
111
- type: "USER" | "EMPLOYEE";
112
- user: { id: string; role: string };
113
- }
85
+ const program = ts.createProgram({
86
+ options: parsedConfig.options,
87
+ rootNames: parsedConfig.fileNames,
88
+ });
89
+ const routerSource = program.getSourceFile(routerSourcePath);
114
90
 
115
- interface CacheOptions {
116
- tags?: string[];
117
- ttl?: number;
118
- }
91
+ if (!routerSource) {
92
+ throw new Error(`Unable to load AppRouter source at ${routerSourcePath}.`);
93
+ }
119
94
 
120
- export declare class ServiceProvider {
121
- static getAuthenticationService(): {
122
- decodeToken(token: string): DecodedToken;
123
- login(email: string, password: string, tokenExpiry?: string): Promise<string>;
124
- };
125
- static getCachingService(): {
126
- fnc<T>(key: string, fn: Promise<T> | (() => Promise<T>), options?: CacheOptions): Promise<T>;
127
- };
128
- static getDatabaseService(): {
129
- getPrisma(): {
130
- user: {
131
- findFirst(args: unknown): Promise<AuthenticatedUser | null>;
132
- };
133
- userAttendance: {
134
- findFirst(args: unknown): Promise<{ id: number } | null>;
135
- };
136
- };
137
- };
138
- static getEncryptionService(): {
139
- decodeId(encodedId: string, prefix: string): number;
140
- };
141
- }
142
- `,
143
- );
144
- await writeFile(
145
- declarationTsconfigPath,
146
- `${JSON.stringify(
147
- {
148
- compilerOptions: {
149
- declaration: true,
150
- declarationMap: false,
151
- emitDeclarationOnly: true,
152
- incremental: true,
153
- noEmit: false,
154
- outDir: declarationOutputDirectory,
155
- paths: {
156
- "@/*": [path.join(apiRoot, "src/*")],
157
- "@/providers": [serviceProviderShimPath],
158
- "@/providers/service.provider": [serviceProviderShimPath],
159
- },
160
- tsBuildInfoFile: path.join(temporaryDirectory, "tsconfig.tsbuildinfo"),
161
- typeRoots: [path.join(apiRoot, "node_modules/@types")],
162
- },
163
- extends: path.join(apiRoot, "tsconfig.json"),
164
- files: [routerSourcePath, prismaJsonShimPath],
165
- },
166
- null,
167
- 2,
168
- )}\n`,
169
- );
170
-
171
- const typeScriptResult = spawnSync(apiTscPath, ["--project", declarationTsconfigPath, "--pretty"], {
172
- cwd: apiRoot,
95
+ const sourceDiagnostics = [
96
+ ...program.getSyntacticDiagnostics(routerSource),
97
+ ...program.getSemanticDiagnostics(routerSource),
98
+ ].filter(diagnostic => diagnostic.category === ts.DiagnosticCategory.Error);
99
+
100
+ if (sourceDiagnostics.length > 0) {
101
+ throw new Error(formatTypeScriptDiagnostics(ts, sourceDiagnostics, apiRoot));
102
+ }
103
+
104
+ let emittedDeclaration;
105
+ const emitResult = program.emit(
106
+ routerSource,
107
+ (fileName, content) => {
108
+ if (fileName.endsWith(".d.ts")) emittedDeclaration = content;
109
+ },
110
+ undefined,
111
+ true,
112
+ );
113
+ const emitDiagnostics = emitResult.diagnostics.filter(
114
+ diagnostic => diagnostic.category === ts.DiagnosticCategory.Error,
115
+ );
116
+
117
+ if (emitDiagnostics.length > 0) {
118
+ throw new Error(formatTypeScriptDiagnostics(ts, emitDiagnostics, apiRoot));
119
+ }
120
+ if (!emittedDeclaration) {
121
+ throw new Error(`TypeScript did not emit a declaration for ${routerSourcePath}.`);
122
+ }
123
+
124
+ const emittedPath = routerSourcePath.replace(/\.ts$/, ".d.ts");
125
+ const sourceFile = ts.createSourceFile(emittedPath, emittedDeclaration, ts.ScriptTarget.Latest, true);
126
+ const statements = sourceFile.statements.filter(
127
+ statement =>
128
+ ts.isImportDeclaration(statement) ||
129
+ ts.isImportEqualsDeclaration(statement) ||
130
+ (ts.isVariableStatement(statement) &&
131
+ statement.declarationList.declarations.some(
132
+ declaration => ts.isIdentifier(declaration.name) && declaration.name.text === "appRouter",
133
+ )) ||
134
+ (ts.isTypeAliasDeclaration(statement) && statement.name.text === "AppRouter"),
135
+ );
136
+
137
+ if (!statements.some(statement => ts.isTypeAliasDeclaration(statement))) {
138
+ throw new Error("AppRouter was not found in the emitted declaration.");
139
+ }
140
+
141
+ const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
142
+ const appRouterDeclaration = statements
143
+ .map(statement => printer.printNode(ts.EmitHint.Unspecified, statement, sourceFile))
144
+ .join("\n")
145
+ .replace(/^(?: {4})+/gm, indentation => "\t".repeat(indentation.length / 4));
146
+
147
+ await mkdir(path.dirname(outputPath), { recursive: true });
148
+ await writeFile(
149
+ outputPath,
150
+ `// Generated by \`npx @automateinc/fleet-types generate\`. Do not edit manually.\n${appRouterDeclaration}\n`,
151
+ );
152
+
153
+ if (existsSync(biomePath)) {
154
+ const biomeResult = spawnSync(biomePath, ["format", "--write", outputPath], {
155
+ cwd: callerRoot,
173
156
  stdio: "inherit",
174
157
  });
175
-
176
- if (typeScriptResult.error) {
177
- throw typeScriptResult.error;
158
+ if (biomeResult.error) {
159
+ throw biomeResult.error;
178
160
  }
179
- if (typeScriptResult.status !== 0) {
180
- throw new Error(`TypeScript declaration generation failed with exit code ${typeScriptResult.status}.`);
181
- }
182
-
183
- const emittedPath = path
184
- .join(declarationOutputDirectory, path.relative(path.join(apiRoot, "src"), routerSourcePath))
185
- .replace(/\.ts$/, ".d.ts");
186
- const emittedDeclaration = await readFile(emittedPath, "utf8");
187
- const sourceFile = ts.createSourceFile(emittedPath, emittedDeclaration, ts.ScriptTarget.Latest, true);
188
- const statements = sourceFile.statements.filter(
189
- statement =>
190
- ts.isImportDeclaration(statement) ||
191
- ts.isImportEqualsDeclaration(statement) ||
192
- (ts.isVariableStatement(statement) &&
193
- statement.declarationList.declarations.some(
194
- declaration => ts.isIdentifier(declaration.name) && declaration.name.text === "appRouter",
195
- )) ||
196
- (ts.isTypeAliasDeclaration(statement) && statement.name.text === "AppRouter"),
197
- );
198
-
199
- if (!statements.some(statement => ts.isTypeAliasDeclaration(statement))) {
200
- throw new Error("AppRouter was not found in the emitted declaration.");
161
+ if (biomeResult.status !== 0) {
162
+ throw new Error(`Biome formatting failed with exit code ${biomeResult.status}.`);
201
163
  }
164
+ }
202
165
 
203
- const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
204
- const appRouterDeclaration = statements
205
- .map(statement => printer.printNode(ts.EmitHint.Unspecified, statement, sourceFile))
206
- .join("\n")
207
- .replace(/^(?: {4})+/gm, indentation => "\t".repeat(indentation.length / 4));
208
-
209
- await mkdir(path.dirname(outputPath), { recursive: true });
210
- await writeFile(
211
- outputPath,
212
- `// Generated by \`npx @automateinc/fleet-types generate\`. Do not edit manually.\n${appRouterDeclaration}\n`,
213
- );
214
-
215
- if (existsSync(biomePath)) {
216
- const biomeResult = spawnSync(biomePath, ["format", "--write", outputPath], {
217
- cwd: callerRoot,
218
- stdio: "inherit",
219
- });
220
- if (biomeResult.error) {
221
- throw biomeResult.error;
222
- }
223
- if (biomeResult.status !== 0) {
224
- throw new Error(`Biome formatting failed with exit code ${biomeResult.status}.`);
225
- }
226
- }
166
+ console.log(`Generated ${path.relative(callerRoot, outputPath)} from ${routerSourcePath}`);
167
+ }
227
168
 
228
- console.log(`Generated ${path.relative(callerRoot, outputPath)} from ${routerSourcePath}`);
229
- } finally {
230
- await rm(temporaryDirectory, { force: true, recursive: true });
231
- }
169
+ function formatTypeScriptDiagnostics(ts, diagnostics, currentDirectory) {
170
+ return ts.formatDiagnosticsWithColorAndContext(diagnostics, {
171
+ getCanonicalFileName: fileName => fileName,
172
+ getCurrentDirectory: () => currentDirectory,
173
+ getNewLine: () => "\n",
174
+ });
232
175
  }
233
176
 
234
177
  function printUsage() {
@@ -2,7 +2,7 @@
2
2
  export declare const appRouter: import("@trpc/server").TRPCBuiltRouter<
3
3
  {
4
4
  ctx: {
5
- client: "FLEET_MOBILE" | "FLEET_MOBILE_USER" | "FLEET_WEB" | undefined;
5
+ client: "FLEET_WEB" | "FLEET_MOBILE" | "FLEET_MOBILE_USER" | undefined;
6
6
  regionId: string | undefined;
7
7
  request: import("express").Request<
8
8
  import("express-serve-static-core").ParamsDictionary,
@@ -21,7 +21,7 @@ export declare const appRouter: import("@trpc/server").TRPCBuiltRouter<
21
21
  auth: import("@trpc/server").TRPCBuiltRouter<
22
22
  {
23
23
  ctx: {
24
- client: "FLEET_MOBILE" | "FLEET_MOBILE_USER" | "FLEET_WEB" | undefined;
24
+ client: "FLEET_WEB" | "FLEET_MOBILE" | "FLEET_MOBILE_USER" | undefined;
25
25
  regionId: string | undefined;
26
26
  request: import("express").Request<
27
27
  import("express-serve-static-core").ParamsDictionary,
@@ -47,6 +47,13 @@ export declare const appRouter: import("@trpc/server").TRPCBuiltRouter<
47
47
  };
48
48
  meta: object;
49
49
  }>;
50
+ refreshToken: import("@trpc/server").TRPCMutationProcedure<{
51
+ input: void;
52
+ output: {
53
+ token: string;
54
+ };
55
+ meta: object;
56
+ }>;
50
57
  }>
51
58
  >;
52
59
  }>
package/package.json CHANGED
@@ -57,5 +57,5 @@
57
57
  "test": "echo \"Error: no test specified\" && exit 1"
58
58
  },
59
59
  "types": "dist/types/index.d.ts",
60
- "version": "1.0.103"
60
+ "version": "1.0.104"
61
61
  }