shiftapi 0.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/fcjr/shiftapi/main/assets/logo-dark.svg">
4
+ <img src="https://raw.githubusercontent.com/fcjr/shiftapi/main/assets/logo.svg" alt="ShiftAPI Logo">
5
+ </picture>
6
+ </p>
7
+
8
+ # shiftapi
9
+
10
+ CLI and codegen core for [ShiftAPI](https://github.com/fcjr/shiftapi). Extracts the OpenAPI spec from your Go server and generates a fully-typed TypeScript client — no Vite required.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm install -D shiftapi
16
+ # or
17
+ pnpm add -D shiftapi
18
+ ```
19
+
20
+ ## Setup
21
+
22
+ Create a `shiftapi.config.ts` in your project root:
23
+
24
+ ```ts
25
+ import { defineConfig } from "shiftapi";
26
+
27
+ export default defineConfig({
28
+ server: "./cmd/server",
29
+ });
30
+ ```
31
+
32
+ ## CLI Usage
33
+
34
+ ```bash
35
+ shiftapi prepare
36
+ ```
37
+
38
+ This will:
39
+
40
+ 1. Find your `shiftapi.config.ts` (searching upward from cwd)
41
+ 2. Run your Go server to extract the OpenAPI 3.1 spec
42
+ 3. Generate TypeScript types via `openapi-typescript`
43
+ 4. Write `.shiftapi/client.d.ts` and `.shiftapi/client.js`
44
+ 5. Patch `tsconfig.json` with the required path mapping
45
+
46
+ Typically used in a `postinstall` script:
47
+
48
+ ```json
49
+ {
50
+ "scripts": {
51
+ "postinstall": "shiftapi prepare"
52
+ }
53
+ }
54
+ ```
55
+
56
+ ## Config Options
57
+
58
+ | Option | Type | Default | Description |
59
+ |--------|------|---------|-------------|
60
+ | `server` | `string` | **(required)** | Path to the Go server entry point (e.g. `"./cmd/server"`) |
61
+ | `baseUrl` | `string` | `"/"` | Base URL for the generated API client |
62
+ | `url` | `string` | `"http://localhost:8080"` | Go server address (used by the Vite plugin for dev proxy) |
63
+
64
+ ## License
65
+
66
+ MIT
@@ -0,0 +1,231 @@
1
+ // src/config.ts
2
+ import { existsSync } from "fs";
3
+ import { resolve, dirname } from "path";
4
+ import { createRequire } from "module";
5
+ function defineConfig(config) {
6
+ return config;
7
+ }
8
+ var CONFIG_FILENAMES = [
9
+ "shiftapi.config.ts",
10
+ "shiftapi.config.js",
11
+ "shiftapi.config.mjs"
12
+ ];
13
+ async function loadConfig(startDir, configPath) {
14
+ let resolvedPath;
15
+ if (configPath) {
16
+ resolvedPath = resolve(startDir, configPath);
17
+ if (!existsSync(resolvedPath)) {
18
+ throw new Error(`[shiftapi] Config file not found: ${resolvedPath}`);
19
+ }
20
+ } else {
21
+ resolvedPath = findConfigFile(startDir);
22
+ if (!resolvedPath) {
23
+ throw new Error(
24
+ `[shiftapi] Could not find shiftapi.config.ts (searched upward from ${startDir}). Create one with: import { defineConfig } from "shiftapi"`
25
+ );
26
+ }
27
+ }
28
+ const require2 = createRequire(import.meta.url);
29
+ const { createJiti } = require2("jiti");
30
+ const jiti = createJiti(resolvedPath);
31
+ const mod = await jiti.import(resolvedPath);
32
+ const config = mod.default ?? mod;
33
+ if (!config.server) {
34
+ throw new Error(
35
+ `[shiftapi] Config at ${resolvedPath} must specify a "server" field (path to Go entry point)`
36
+ );
37
+ }
38
+ return { config, configDir: dirname(resolvedPath) };
39
+ }
40
+ function findConfigFile(startDir) {
41
+ let dir = resolve(startDir);
42
+ const root = resolve("/");
43
+ while (true) {
44
+ for (const name of CONFIG_FILENAMES) {
45
+ const candidate = resolve(dir, name);
46
+ if (existsSync(candidate)) {
47
+ return candidate;
48
+ }
49
+ }
50
+ const parent = dirname(dir);
51
+ if (parent === dir || dir === root) {
52
+ return void 0;
53
+ }
54
+ dir = parent;
55
+ }
56
+ }
57
+
58
+ // src/extract.ts
59
+ import { execFileSync } from "child_process";
60
+ import { readFileSync, unlinkSync, rmSync, mkdtempSync } from "fs";
61
+ import { join } from "path";
62
+ import { tmpdir } from "os";
63
+ function extractSpec(serverEntry, goRoot) {
64
+ const tempDir = mkdtempSync(join(tmpdir(), "shiftapi-"));
65
+ const specPath = join(tempDir, "openapi.json");
66
+ try {
67
+ execFileSync("go", ["run", "-tags", "shiftapidev", serverEntry], {
68
+ cwd: goRoot,
69
+ env: {
70
+ ...process.env,
71
+ SHIFTAPI_EXPORT_SPEC: specPath
72
+ },
73
+ stdio: ["ignore", "pipe", "pipe"],
74
+ timeout: 3e4
75
+ });
76
+ } catch (err) {
77
+ const stderr = err instanceof Error && "stderr" in err ? String(err.stderr) : "";
78
+ throw new Error(
79
+ `shiftapi: Failed to extract OpenAPI spec.
80
+ Command: go run ${serverEntry}
81
+ CWD: ${goRoot}
82
+ Error: ${stderr || String(err)}`
83
+ );
84
+ }
85
+ let raw;
86
+ try {
87
+ raw = readFileSync(specPath, "utf-8");
88
+ } catch {
89
+ throw new Error(
90
+ `shiftapi: Spec file was not created at ${specPath}.
91
+ Make sure your Go server calls shiftapi.ListenAndServe().`
92
+ );
93
+ }
94
+ try {
95
+ unlinkSync(specPath);
96
+ rmSync(tempDir, { recursive: true });
97
+ } catch {
98
+ }
99
+ return JSON.parse(raw);
100
+ }
101
+
102
+ // src/generate.ts
103
+ import openapiTS, { astToString } from "openapi-typescript";
104
+ async function generateTypes(spec) {
105
+ const ast = await openapiTS(spec);
106
+ return astToString(ast);
107
+ }
108
+
109
+ // src/constants.ts
110
+ var MODULE_ID = "@shiftapi/client";
111
+ var RESOLVED_MODULE_ID = "\0" + MODULE_ID;
112
+ var DEV_API_PREFIX = "/__shiftapi";
113
+
114
+ // src/templates.ts
115
+ function indent(text, spaces = 2) {
116
+ const prefix = " ".repeat(spaces);
117
+ return text.split("\n").map((line) => line ? prefix + line : line).join("\n");
118
+ }
119
+ function dtsTemplate(generatedTypes) {
120
+ return `// Auto-generated by shiftapi. Do not edit.
121
+ declare module "@shiftapi/client" {
122
+ ${indent(generatedTypes)}
123
+
124
+ import type createClient from "openapi-fetch";
125
+
126
+ export const client: ReturnType<typeof createClient<paths>>;
127
+ export { createClient };
128
+ }
129
+ `;
130
+ }
131
+ function clientJsTemplate(baseUrl) {
132
+ return `// Auto-generated by shiftapi. Do not edit.
133
+ import createClient from "openapi-fetch";
134
+
135
+ /** Pre-configured, fully-typed API client. */
136
+ export const client = createClient({
137
+ baseUrl: ${JSON.stringify(baseUrl)},
138
+ });
139
+
140
+ export { createClient };
141
+ `;
142
+ }
143
+ function virtualModuleTemplate(baseUrl, devApiPrefix) {
144
+ const baseUrlExpr = devApiPrefix ? `import.meta.env.VITE_SHIFTAPI_BASE_URL || (import.meta.env.DEV ? ${JSON.stringify(devApiPrefix)} : ${JSON.stringify(baseUrl)})` : `import.meta.env.VITE_SHIFTAPI_BASE_URL || ${JSON.stringify(baseUrl)}`;
145
+ return `// Auto-generated by @shiftapi/vite-plugin
146
+ import createClient from "openapi-fetch";
147
+
148
+ /** Pre-configured, fully-typed API client. */
149
+ export const client = createClient({
150
+ baseUrl: ${baseUrlExpr},
151
+ });
152
+
153
+ export { createClient };
154
+ `;
155
+ }
156
+
157
+ // src/codegen.ts
158
+ import { resolve as resolve2, relative } from "path";
159
+ import { writeFileSync, readFileSync as readFileSync2, mkdirSync, existsSync as existsSync2 } from "fs";
160
+ import { parse, stringify } from "comment-json";
161
+ async function regenerateTypes(serverEntry, goRoot, baseUrl, isDev, previousTypes) {
162
+ const spec = extractSpec(serverEntry, resolve2(goRoot));
163
+ const types = await generateTypes(spec);
164
+ const changed = types !== previousTypes;
165
+ const virtualModuleSource = virtualModuleTemplate(
166
+ baseUrl,
167
+ isDev ? DEV_API_PREFIX : void 0
168
+ );
169
+ return { types, virtualModuleSource, changed };
170
+ }
171
+ function writeGeneratedFiles(typesRoot, generatedDts, baseUrl) {
172
+ const outDir = resolve2(typesRoot, ".shiftapi");
173
+ if (!existsSync2(outDir)) {
174
+ mkdirSync(outDir, { recursive: true });
175
+ }
176
+ writeFileSync(resolve2(outDir, "client.d.ts"), dtsTemplate(generatedDts));
177
+ writeFileSync(resolve2(outDir, "client.js"), clientJsTemplate(baseUrl));
178
+ writeFileSync(
179
+ resolve2(outDir, "tsconfig.json"),
180
+ JSON.stringify(
181
+ {
182
+ compilerOptions: {
183
+ paths: {
184
+ [MODULE_ID]: ["./client.d.ts"]
185
+ }
186
+ }
187
+ },
188
+ null,
189
+ 2
190
+ ) + "\n"
191
+ );
192
+ }
193
+ function patchTsConfig(tsconfigDir, typesRoot) {
194
+ const tsconfigPath = resolve2(tsconfigDir, "tsconfig.json");
195
+ if (!existsSync2(tsconfigPath)) return;
196
+ const raw = readFileSync2(tsconfigPath, "utf-8");
197
+ let tsconfig;
198
+ try {
199
+ tsconfig = parse(raw);
200
+ } catch (err) {
201
+ console.warn(
202
+ `[shiftapi] Failed to parse tsconfig.json: ${err instanceof Error ? err.message : String(err)}`
203
+ );
204
+ return;
205
+ }
206
+ const rel = relative(tsconfigDir, resolve2(typesRoot, ".shiftapi", "tsconfig.json"));
207
+ const extendsPath = rel.startsWith("..") ? rel : `./${rel}`;
208
+ if (tsconfig?.extends === extendsPath) return;
209
+ tsconfig.extends = extendsPath;
210
+ const detectedIndent = raw.match(/^[ \t]+/m)?.[0] ?? " ";
211
+ writeFileSync(tsconfigPath, stringify(tsconfig, null, detectedIndent) + "\n");
212
+ console.log(
213
+ "[shiftapi] Updated tsconfig.json to extend .shiftapi/tsconfig.json"
214
+ );
215
+ }
216
+
217
+ export {
218
+ defineConfig,
219
+ loadConfig,
220
+ extractSpec,
221
+ generateTypes,
222
+ MODULE_ID,
223
+ RESOLVED_MODULE_ID,
224
+ DEV_API_PREFIX,
225
+ dtsTemplate,
226
+ clientJsTemplate,
227
+ virtualModuleTemplate,
228
+ regenerateTypes,
229
+ writeGeneratedFiles,
230
+ patchTsConfig
231
+ };
@@ -0,0 +1,231 @@
1
+ // src/config.ts
2
+ import { existsSync } from "fs";
3
+ import { resolve, dirname } from "path";
4
+ import { createRequire } from "module";
5
+ function defineConfig(config) {
6
+ return config;
7
+ }
8
+ var CONFIG_FILENAMES = [
9
+ "shiftapi.config.ts",
10
+ "shiftapi.config.js",
11
+ "shiftapi.config.mjs"
12
+ ];
13
+ async function loadConfig(startDir, configPath) {
14
+ let resolvedPath;
15
+ if (configPath) {
16
+ resolvedPath = resolve(startDir, configPath);
17
+ if (!existsSync(resolvedPath)) {
18
+ throw new Error(`[shiftapi] Config file not found: ${resolvedPath}`);
19
+ }
20
+ } else {
21
+ resolvedPath = findConfigFile(startDir);
22
+ if (!resolvedPath) {
23
+ throw new Error(
24
+ `[shiftapi] Could not find shiftapi.config.ts (searched upward from ${startDir}). Create one with: import { defineConfig } from "@shiftapi/cli"`
25
+ );
26
+ }
27
+ }
28
+ const require2 = createRequire(import.meta.url);
29
+ const { createJiti } = require2("jiti");
30
+ const jiti = createJiti(resolvedPath);
31
+ const mod = await jiti.import(resolvedPath);
32
+ const config = mod.default ?? mod;
33
+ if (!config.server) {
34
+ throw new Error(
35
+ `[shiftapi] Config at ${resolvedPath} must specify a "server" field (path to Go entry point)`
36
+ );
37
+ }
38
+ return { config, configDir: dirname(resolvedPath) };
39
+ }
40
+ function findConfigFile(startDir) {
41
+ let dir = resolve(startDir);
42
+ const root = resolve("/");
43
+ while (true) {
44
+ for (const name of CONFIG_FILENAMES) {
45
+ const candidate = resolve(dir, name);
46
+ if (existsSync(candidate)) {
47
+ return candidate;
48
+ }
49
+ }
50
+ const parent = dirname(dir);
51
+ if (parent === dir || dir === root) {
52
+ return void 0;
53
+ }
54
+ dir = parent;
55
+ }
56
+ }
57
+
58
+ // src/extract.ts
59
+ import { execFileSync } from "child_process";
60
+ import { readFileSync, unlinkSync, rmSync, mkdtempSync } from "fs";
61
+ import { join } from "path";
62
+ import { tmpdir } from "os";
63
+ function extractSpec(serverEntry, goRoot) {
64
+ const tempDir = mkdtempSync(join(tmpdir(), "shiftapi-"));
65
+ const specPath = join(tempDir, "openapi.json");
66
+ try {
67
+ execFileSync("go", ["run", "-tags", "shiftapidev", serverEntry], {
68
+ cwd: goRoot,
69
+ env: {
70
+ ...process.env,
71
+ SHIFTAPI_EXPORT_SPEC: specPath
72
+ },
73
+ stdio: ["ignore", "pipe", "pipe"],
74
+ timeout: 3e4
75
+ });
76
+ } catch (err) {
77
+ const stderr = err instanceof Error && "stderr" in err ? String(err.stderr) : "";
78
+ throw new Error(
79
+ `@shiftapi/cli: Failed to extract OpenAPI spec.
80
+ Command: go run ${serverEntry}
81
+ CWD: ${goRoot}
82
+ Error: ${stderr || String(err)}`
83
+ );
84
+ }
85
+ let raw;
86
+ try {
87
+ raw = readFileSync(specPath, "utf-8");
88
+ } catch {
89
+ throw new Error(
90
+ `@shiftapi/cli: Spec file was not created at ${specPath}.
91
+ Make sure your Go server calls shiftapi.ListenAndServe().`
92
+ );
93
+ }
94
+ try {
95
+ unlinkSync(specPath);
96
+ rmSync(tempDir, { recursive: true });
97
+ } catch {
98
+ }
99
+ return JSON.parse(raw);
100
+ }
101
+
102
+ // src/generate.ts
103
+ import openapiTS, { astToString } from "openapi-typescript";
104
+ async function generateTypes(spec) {
105
+ const ast = await openapiTS(spec);
106
+ return astToString(ast);
107
+ }
108
+
109
+ // src/constants.ts
110
+ var MODULE_ID = "@shiftapi/client";
111
+ var RESOLVED_MODULE_ID = "\0" + MODULE_ID;
112
+ var DEV_API_PREFIX = "/__shiftapi";
113
+
114
+ // src/templates.ts
115
+ function indent(text, spaces = 2) {
116
+ const prefix = " ".repeat(spaces);
117
+ return text.split("\n").map((line) => line ? prefix + line : line).join("\n");
118
+ }
119
+ function dtsTemplate(generatedTypes) {
120
+ return `// Auto-generated by @shiftapi/cli. Do not edit.
121
+ declare module "@shiftapi/client" {
122
+ ${indent(generatedTypes)}
123
+
124
+ import type createClient from "openapi-fetch";
125
+
126
+ export const client: ReturnType<typeof createClient<paths>>;
127
+ export { createClient };
128
+ }
129
+ `;
130
+ }
131
+ function clientJsTemplate(baseUrl) {
132
+ return `// Auto-generated by @shiftapi/cli. Do not edit.
133
+ import createClient from "openapi-fetch";
134
+
135
+ /** Pre-configured, fully-typed API client. */
136
+ export const client = createClient({
137
+ baseUrl: ${JSON.stringify(baseUrl)},
138
+ });
139
+
140
+ export { createClient };
141
+ `;
142
+ }
143
+ function virtualModuleTemplate(baseUrl, devApiPrefix) {
144
+ const baseUrlExpr = devApiPrefix ? `import.meta.env.VITE_SHIFTAPI_BASE_URL || (import.meta.env.DEV ? ${JSON.stringify(devApiPrefix)} : ${JSON.stringify(baseUrl)})` : `import.meta.env.VITE_SHIFTAPI_BASE_URL || ${JSON.stringify(baseUrl)}`;
145
+ return `// Auto-generated by @shiftapi/vite-plugin
146
+ import createClient from "openapi-fetch";
147
+
148
+ /** Pre-configured, fully-typed API client. */
149
+ export const client = createClient({
150
+ baseUrl: ${baseUrlExpr},
151
+ });
152
+
153
+ export { createClient };
154
+ `;
155
+ }
156
+
157
+ // src/codegen.ts
158
+ import { resolve as resolve2, relative } from "path";
159
+ import { writeFileSync, readFileSync as readFileSync2, mkdirSync, existsSync as existsSync2 } from "fs";
160
+ import { parse, stringify } from "comment-json";
161
+ async function regenerateTypes(serverEntry, goRoot, baseUrl, isDev, previousTypes) {
162
+ const spec = extractSpec(serverEntry, resolve2(goRoot));
163
+ const types = await generateTypes(spec);
164
+ const changed = types !== previousTypes;
165
+ const virtualModuleSource = virtualModuleTemplate(
166
+ baseUrl,
167
+ isDev ? DEV_API_PREFIX : void 0
168
+ );
169
+ return { types, virtualModuleSource, changed };
170
+ }
171
+ function writeGeneratedFiles(typesRoot, generatedDts, baseUrl) {
172
+ const outDir = resolve2(typesRoot, ".shiftapi");
173
+ if (!existsSync2(outDir)) {
174
+ mkdirSync(outDir, { recursive: true });
175
+ }
176
+ writeFileSync(resolve2(outDir, "client.d.ts"), dtsTemplate(generatedDts));
177
+ writeFileSync(resolve2(outDir, "client.js"), clientJsTemplate(baseUrl));
178
+ writeFileSync(
179
+ resolve2(outDir, "tsconfig.json"),
180
+ JSON.stringify(
181
+ {
182
+ compilerOptions: {
183
+ paths: {
184
+ [MODULE_ID]: ["./client.d.ts"]
185
+ }
186
+ }
187
+ },
188
+ null,
189
+ 2
190
+ ) + "\n"
191
+ );
192
+ }
193
+ function patchTsConfig(tsconfigDir, typesRoot) {
194
+ const tsconfigPath = resolve2(tsconfigDir, "tsconfig.json");
195
+ if (!existsSync2(tsconfigPath)) return;
196
+ const raw = readFileSync2(tsconfigPath, "utf-8");
197
+ let tsconfig;
198
+ try {
199
+ tsconfig = parse(raw);
200
+ } catch (err) {
201
+ console.warn(
202
+ `[shiftapi] Failed to parse tsconfig.json: ${err instanceof Error ? err.message : String(err)}`
203
+ );
204
+ return;
205
+ }
206
+ const rel = relative(tsconfigDir, resolve2(typesRoot, ".shiftapi", "tsconfig.json"));
207
+ const extendsPath = rel.startsWith("..") ? rel : `./${rel}`;
208
+ if (tsconfig?.extends === extendsPath) return;
209
+ tsconfig.extends = extendsPath;
210
+ const detectedIndent = raw.match(/^[ \t]+/m)?.[0] ?? " ";
211
+ writeFileSync(tsconfigPath, stringify(tsconfig, null, detectedIndent) + "\n");
212
+ console.log(
213
+ "[shiftapi] Updated tsconfig.json to extend .shiftapi/tsconfig.json"
214
+ );
215
+ }
216
+
217
+ export {
218
+ defineConfig,
219
+ loadConfig,
220
+ extractSpec,
221
+ generateTypes,
222
+ MODULE_ID,
223
+ RESOLVED_MODULE_ID,
224
+ DEV_API_PREFIX,
225
+ dtsTemplate,
226
+ clientJsTemplate,
227
+ virtualModuleTemplate,
228
+ regenerateTypes,
229
+ writeGeneratedFiles,
230
+ patchTsConfig
231
+ };
@@ -0,0 +1,61 @@
1
+ // src/config.ts
2
+ import { existsSync } from "fs";
3
+ import { resolve, dirname } from "path";
4
+ import { createRequire } from "module";
5
+ function defineConfig(config) {
6
+ return config;
7
+ }
8
+ var CONFIG_FILENAMES = [
9
+ "shiftapi.config.ts",
10
+ "shiftapi.config.js",
11
+ "shiftapi.config.mjs"
12
+ ];
13
+ async function loadConfig(startDir, configPath) {
14
+ let resolvedPath;
15
+ if (configPath) {
16
+ resolvedPath = resolve(startDir, configPath);
17
+ if (!existsSync(resolvedPath)) {
18
+ throw new Error(`[shiftapi] Config file not found: ${resolvedPath}`);
19
+ }
20
+ } else {
21
+ resolvedPath = findConfigFile(startDir);
22
+ if (!resolvedPath) {
23
+ throw new Error(
24
+ `[shiftapi] Could not find shiftapi.config.ts (searched upward from ${startDir}). Create one with: import { defineConfig } from "@shiftapi/core"`
25
+ );
26
+ }
27
+ }
28
+ const require2 = createRequire(import.meta.url);
29
+ const { createJiti } = require2("jiti");
30
+ const jiti = createJiti(resolvedPath);
31
+ const mod = await jiti.import(resolvedPath);
32
+ const config = mod.default ?? mod;
33
+ if (!config.server) {
34
+ throw new Error(
35
+ `[shiftapi] Config at ${resolvedPath} must specify a "server" field (path to Go entry point)`
36
+ );
37
+ }
38
+ return { config, configDir: dirname(resolvedPath) };
39
+ }
40
+ function findConfigFile(startDir) {
41
+ let dir = resolve(startDir);
42
+ const root = resolve("/");
43
+ while (true) {
44
+ for (const name of CONFIG_FILENAMES) {
45
+ const candidate = resolve(dir, name);
46
+ if (existsSync(candidate)) {
47
+ return candidate;
48
+ }
49
+ }
50
+ const parent = dirname(dir);
51
+ if (parent === dir || dir === root) {
52
+ return void 0;
53
+ }
54
+ dir = parent;
55
+ }
56
+ }
57
+
58
+ export {
59
+ defineConfig,
60
+ loadConfig
61
+ };
@@ -0,0 +1,172 @@
1
+ // src/extract.ts
2
+ import { execFileSync } from "child_process";
3
+ import { readFileSync, unlinkSync, rmSync, mkdtempSync } from "fs";
4
+ import { join } from "path";
5
+ import { tmpdir } from "os";
6
+ function extractSpec(serverEntry, goRoot) {
7
+ const tempDir = mkdtempSync(join(tmpdir(), "shiftapi-"));
8
+ const specPath = join(tempDir, "openapi.json");
9
+ try {
10
+ execFileSync("go", ["run", "-tags", "shiftapidev", serverEntry], {
11
+ cwd: goRoot,
12
+ env: {
13
+ ...process.env,
14
+ SHIFTAPI_EXPORT_SPEC: specPath
15
+ },
16
+ stdio: ["ignore", "pipe", "pipe"],
17
+ timeout: 3e4
18
+ });
19
+ } catch (err) {
20
+ const stderr = err instanceof Error && "stderr" in err ? String(err.stderr) : "";
21
+ throw new Error(
22
+ `shiftapi: Failed to extract OpenAPI spec.
23
+ Command: go run ${serverEntry}
24
+ CWD: ${goRoot}
25
+ Error: ${stderr || String(err)}`
26
+ );
27
+ }
28
+ let raw;
29
+ try {
30
+ raw = readFileSync(specPath, "utf-8");
31
+ } catch {
32
+ throw new Error(
33
+ `shiftapi: Spec file was not created at ${specPath}.
34
+ Make sure your Go server calls shiftapi.ListenAndServe().`
35
+ );
36
+ }
37
+ try {
38
+ unlinkSync(specPath);
39
+ rmSync(tempDir, { recursive: true });
40
+ } catch {
41
+ }
42
+ return JSON.parse(raw);
43
+ }
44
+
45
+ // src/generate.ts
46
+ import openapiTS, { astToString } from "openapi-typescript";
47
+ async function generateTypes(spec) {
48
+ const ast = await openapiTS(spec);
49
+ return astToString(ast);
50
+ }
51
+
52
+ // src/constants.ts
53
+ var MODULE_ID = "@shiftapi/client";
54
+ var RESOLVED_MODULE_ID = "\0" + MODULE_ID;
55
+ var DEV_API_PREFIX = "/__shiftapi";
56
+
57
+ // src/templates.ts
58
+ function indent(text, spaces = 2) {
59
+ const prefix = " ".repeat(spaces);
60
+ return text.split("\n").map((line) => line ? prefix + line : line).join("\n");
61
+ }
62
+ function dtsTemplate(generatedTypes) {
63
+ return `// Auto-generated by shiftapi. Do not edit.
64
+ declare module "@shiftapi/client" {
65
+ ${indent(generatedTypes)}
66
+
67
+ import type createClient from "openapi-fetch";
68
+
69
+ export const client: ReturnType<typeof createClient<paths>>;
70
+ export { createClient };
71
+ }
72
+ `;
73
+ }
74
+ function clientJsTemplate(baseUrl) {
75
+ return `// Auto-generated by shiftapi. Do not edit.
76
+ import createClient from "openapi-fetch";
77
+
78
+ /** Pre-configured, fully-typed API client. */
79
+ export const client = createClient({
80
+ baseUrl: ${JSON.stringify(baseUrl)},
81
+ });
82
+
83
+ export { createClient };
84
+ `;
85
+ }
86
+ function virtualModuleTemplate(baseUrl, devApiPrefix) {
87
+ const baseUrlExpr = devApiPrefix ? `import.meta.env.VITE_SHIFTAPI_BASE_URL || (import.meta.env.DEV ? ${JSON.stringify(devApiPrefix)} : ${JSON.stringify(baseUrl)})` : `import.meta.env.VITE_SHIFTAPI_BASE_URL || ${JSON.stringify(baseUrl)}`;
88
+ return `// Auto-generated by @shiftapi/vite-plugin
89
+ import createClient from "openapi-fetch";
90
+
91
+ /** Pre-configured, fully-typed API client. */
92
+ export const client = createClient({
93
+ baseUrl: ${baseUrlExpr},
94
+ });
95
+
96
+ export { createClient };
97
+ `;
98
+ }
99
+
100
+ // src/codegen.ts
101
+ import { resolve, relative } from "path";
102
+ import { writeFileSync, readFileSync as readFileSync2, mkdirSync, existsSync } from "fs";
103
+ import { parse, stringify } from "comment-json";
104
+ async function regenerateTypes(serverEntry, goRoot, baseUrl, isDev, previousTypes) {
105
+ const spec = extractSpec(serverEntry, resolve(goRoot));
106
+ const types = await generateTypes(spec);
107
+ const changed = types !== previousTypes;
108
+ const virtualModuleSource = virtualModuleTemplate(
109
+ baseUrl,
110
+ isDev ? DEV_API_PREFIX : void 0
111
+ );
112
+ return { types, virtualModuleSource, changed };
113
+ }
114
+ function writeGeneratedFiles(typesRoot, generatedDts, baseUrl) {
115
+ const outDir = resolve(typesRoot, ".shiftapi");
116
+ if (!existsSync(outDir)) {
117
+ mkdirSync(outDir, { recursive: true });
118
+ }
119
+ writeFileSync(resolve(outDir, "client.d.ts"), dtsTemplate(generatedDts));
120
+ writeFileSync(resolve(outDir, "client.js"), clientJsTemplate(baseUrl));
121
+ writeFileSync(
122
+ resolve(outDir, "tsconfig.json"),
123
+ JSON.stringify(
124
+ {
125
+ compilerOptions: {
126
+ paths: {
127
+ [MODULE_ID]: ["./client.d.ts"]
128
+ }
129
+ }
130
+ },
131
+ null,
132
+ 2
133
+ ) + "\n"
134
+ );
135
+ }
136
+ function patchTsConfig(tsconfigDir, typesRoot) {
137
+ const tsconfigPath = resolve(tsconfigDir, "tsconfig.json");
138
+ if (!existsSync(tsconfigPath)) return;
139
+ const raw = readFileSync2(tsconfigPath, "utf-8");
140
+ let tsconfig;
141
+ try {
142
+ tsconfig = parse(raw);
143
+ } catch (err) {
144
+ console.warn(
145
+ `[shiftapi] Failed to parse tsconfig.json: ${err instanceof Error ? err.message : String(err)}`
146
+ );
147
+ return;
148
+ }
149
+ const rel = relative(tsconfigDir, resolve(typesRoot, ".shiftapi", "tsconfig.json"));
150
+ const extendsPath = rel.startsWith("..") ? rel : `./${rel}`;
151
+ if (tsconfig?.extends === extendsPath) return;
152
+ tsconfig.extends = extendsPath;
153
+ const detectedIndent = raw.match(/^[ \t]+/m)?.[0] ?? " ";
154
+ writeFileSync(tsconfigPath, stringify(tsconfig, null, detectedIndent) + "\n");
155
+ console.log(
156
+ "[shiftapi] Updated tsconfig.json to extend .shiftapi/tsconfig.json"
157
+ );
158
+ }
159
+
160
+ export {
161
+ extractSpec,
162
+ generateTypes,
163
+ MODULE_ID,
164
+ RESOLVED_MODULE_ID,
165
+ DEV_API_PREFIX,
166
+ dtsTemplate,
167
+ clientJsTemplate,
168
+ virtualModuleTemplate,
169
+ regenerateTypes,
170
+ writeGeneratedFiles,
171
+ patchTsConfig
172
+ };
@@ -0,0 +1,61 @@
1
+ // src/config.ts
2
+ import { existsSync } from "fs";
3
+ import { resolve, dirname } from "path";
4
+ import { createRequire } from "module";
5
+ function defineConfig(config) {
6
+ return config;
7
+ }
8
+ var CONFIG_FILENAMES = [
9
+ "shiftapi.config.ts",
10
+ "shiftapi.config.js",
11
+ "shiftapi.config.mjs"
12
+ ];
13
+ async function loadConfig(startDir, configPath) {
14
+ let resolvedPath;
15
+ if (configPath) {
16
+ resolvedPath = resolve(startDir, configPath);
17
+ if (!existsSync(resolvedPath)) {
18
+ throw new Error(`[shiftapi] Config file not found: ${resolvedPath}`);
19
+ }
20
+ } else {
21
+ resolvedPath = findConfigFile(startDir);
22
+ if (!resolvedPath) {
23
+ throw new Error(
24
+ `[shiftapi] Could not find shiftapi.config.ts (searched upward from ${startDir}). Create one with: import { defineConfig } from "shiftapi"`
25
+ );
26
+ }
27
+ }
28
+ const require2 = createRequire(import.meta.url);
29
+ const { createJiti } = require2("jiti");
30
+ const jiti = createJiti(resolvedPath);
31
+ const mod = await jiti.import(resolvedPath);
32
+ const config = mod.default ?? mod;
33
+ if (!config.server) {
34
+ throw new Error(
35
+ `[shiftapi] Config at ${resolvedPath} must specify a "server" field (path to Go entry point)`
36
+ );
37
+ }
38
+ return { config, configDir: dirname(resolvedPath) };
39
+ }
40
+ function findConfigFile(startDir) {
41
+ let dir = resolve(startDir);
42
+ const root = resolve("/");
43
+ while (true) {
44
+ for (const name of CONFIG_FILENAMES) {
45
+ const candidate = resolve(dir, name);
46
+ if (existsSync(candidate)) {
47
+ return candidate;
48
+ }
49
+ }
50
+ const parent = dirname(dir);
51
+ if (parent === dir || dir === root) {
52
+ return void 0;
53
+ }
54
+ dir = parent;
55
+ }
56
+ }
57
+
58
+ export {
59
+ defineConfig,
60
+ loadConfig
61
+ };
@@ -0,0 +1,26 @@
1
+ interface ShiftAPIConfig {
2
+ /** Path to the Go server entry point, relative to the config file (e.g., "./cmd/server") */
3
+ server: string;
4
+ /**
5
+ * Fallback base URL for the API client (default: "/").
6
+ * Can be overridden at build time via the `VITE_SHIFTAPI_BASE_URL` env var.
7
+ */
8
+ baseUrl?: string;
9
+ /**
10
+ * Address the Go server listens on (default: "http://localhost:8080").
11
+ * Used to auto-configure the Vite proxy in dev mode.
12
+ */
13
+ url?: string;
14
+ }
15
+ /** Identity helper for IntelliSense in `shiftapi.config.ts` files. */
16
+ declare function defineConfig(config: ShiftAPIConfig): ShiftAPIConfig;
17
+ /**
18
+ * Walk up from `startDir` looking for a shiftapi config file.
19
+ * Returns the parsed config and the directory containing it.
20
+ */
21
+ declare function loadConfig(startDir: string, configPath?: string): Promise<{
22
+ config: ShiftAPIConfig;
23
+ configDir: string;
24
+ }>;
25
+
26
+ export { type ShiftAPIConfig as S, defineConfig as d, loadConfig as l };
@@ -0,0 +1 @@
1
+ export { S as ShiftAPIConfig, d as defineConfig } from './index-PUAivaXi.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ defineConfig
3
+ } from "./chunk-QBXBYTBE.js";
4
+ export {
5
+ defineConfig
6
+ };
@@ -0,0 +1,32 @@
1
+ export { S as ShiftAPIConfig, d as defineConfig, l as loadConfig } from './index-PUAivaXi.js';
2
+
3
+ declare function regenerateTypes(serverEntry: string, goRoot: string, baseUrl: string, isDev: boolean, previousTypes: string): Promise<{
4
+ types: string;
5
+ virtualModuleSource: string;
6
+ changed: boolean;
7
+ }>;
8
+ declare function writeGeneratedFiles(typesRoot: string, generatedDts: string, baseUrl: string): void;
9
+ declare function patchTsConfig(tsconfigDir: string, typesRoot: string): void;
10
+
11
+ /**
12
+ * Extracts the OpenAPI spec from a Go shiftapi server by running it with
13
+ * the SHIFTAPI_EXPORT_SPEC environment variable set. The Go binary writes
14
+ * the spec to the given path and exits immediately.
15
+ */
16
+ declare function extractSpec(serverEntry: string, goRoot: string): object;
17
+
18
+ /**
19
+ * Generates TypeScript type definitions from an OpenAPI spec object
20
+ * using the openapi-typescript programmatic API.
21
+ */
22
+ declare function generateTypes(spec: object): Promise<string>;
23
+
24
+ declare function dtsTemplate(generatedTypes: string): string;
25
+ declare function clientJsTemplate(baseUrl: string): string;
26
+ declare function virtualModuleTemplate(baseUrl: string, devApiPrefix?: string): string;
27
+
28
+ declare const MODULE_ID = "@shiftapi/client";
29
+ declare const RESOLVED_MODULE_ID: string;
30
+ declare const DEV_API_PREFIX = "/__shiftapi";
31
+
32
+ export { DEV_API_PREFIX, MODULE_ID, RESOLVED_MODULE_ID, clientJsTemplate, dtsTemplate, extractSpec, generateTypes, patchTsConfig, regenerateTypes, virtualModuleTemplate, writeGeneratedFiles };
@@ -0,0 +1,32 @@
1
+ import {
2
+ DEV_API_PREFIX,
3
+ MODULE_ID,
4
+ RESOLVED_MODULE_ID,
5
+ clientJsTemplate,
6
+ dtsTemplate,
7
+ extractSpec,
8
+ generateTypes,
9
+ patchTsConfig,
10
+ regenerateTypes,
11
+ virtualModuleTemplate,
12
+ writeGeneratedFiles
13
+ } from "./chunk-M6SOET3R.js";
14
+ import {
15
+ defineConfig,
16
+ loadConfig
17
+ } from "./chunk-QBXBYTBE.js";
18
+ export {
19
+ DEV_API_PREFIX,
20
+ MODULE_ID,
21
+ RESOLVED_MODULE_ID,
22
+ clientJsTemplate,
23
+ defineConfig,
24
+ dtsTemplate,
25
+ extractSpec,
26
+ generateTypes,
27
+ loadConfig,
28
+ patchTsConfig,
29
+ regenerateTypes,
30
+ virtualModuleTemplate,
31
+ writeGeneratedFiles
32
+ };
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ extractSpec,
4
+ generateTypes,
5
+ patchTsConfig,
6
+ writeGeneratedFiles
7
+ } from "./chunk-M6SOET3R.js";
8
+ import {
9
+ loadConfig
10
+ } from "./chunk-QBXBYTBE.js";
11
+
12
+ // src/prepare.ts
13
+ import { resolve } from "path";
14
+ var command = process.argv[2];
15
+ if (command !== "prepare") {
16
+ console.error(`Usage: shiftapi prepare`);
17
+ process.exit(1);
18
+ }
19
+ async function main() {
20
+ const cwd = process.cwd();
21
+ console.log("[shiftapi] Preparing...");
22
+ const { config, configDir } = await loadConfig(cwd);
23
+ const serverEntry = config.server;
24
+ const baseUrl = config.baseUrl ?? "/";
25
+ const goRoot = configDir;
26
+ const spec = extractSpec(serverEntry, resolve(goRoot));
27
+ const types = await generateTypes(spec);
28
+ writeGeneratedFiles(configDir, types, baseUrl);
29
+ patchTsConfig(cwd, configDir);
30
+ console.log("[shiftapi] Done. Generated .shiftapi/client.d.ts and .shiftapi/client.js");
31
+ }
32
+ main().catch((err) => {
33
+ console.error(err instanceof Error ? err.message : String(err));
34
+ process.exit(1);
35
+ });
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "shiftapi",
3
+ "version": "0.0.14",
4
+ "description": "CLI and codegen for shiftapi – fully-typed TypeScript clients from Go servers",
5
+ "author": "Frank Chiarulli Jr. <frank@frankchiarulli.com>",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/fcjr/shiftapi",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/fcjr/shiftapi",
11
+ "directory": "packages/shiftapi"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/fcjr/shiftapi/issues"
15
+ },
16
+ "type": "module",
17
+ "main": "dist/index.js",
18
+ "types": "dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./internal": {
25
+ "types": "./dist/internal.d.ts",
26
+ "default": "./dist/internal.js"
27
+ }
28
+ },
29
+ "bin": {
30
+ "shiftapi": "./dist/prepare.js"
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "scripts": {
36
+ "build": "tsup src/index.ts src/internal.ts src/prepare.ts --format esm --dts",
37
+ "dev": "tsup src/index.ts src/internal.ts src/prepare.ts --format esm --dts --watch",
38
+ "test": "vitest run"
39
+ },
40
+ "dependencies": {
41
+ "comment-json": "^4.5.1",
42
+ "jiti": "^2.6.1",
43
+ "openapi-typescript": "^7.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^25.2.3",
47
+ "tsup": "^8.0.0",
48
+ "typescript": "^5.5.0",
49
+ "vitest": "^2.0.0"
50
+ }
51
+ }