@rvoh/psychic 3.0.5 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/src/cli/helpers/PackageManager.js +10 -0
- package/dist/cjs/src/generate/helpers/reduxBindings/writeInitializer.js +3 -1
- package/dist/cjs/src/generate/helpers/syncOpenapiTypescript/generateInitializer.js +3 -1
- package/dist/cjs/src/generate/helpers/zustandBindings/generateStoreFromSdk.js +74 -0
- package/dist/cjs/src/generate/helpers/zustandBindings/printFinalStepsMessage.js +10 -13
- package/dist/cjs/src/generate/helpers/zustandBindings/writeInitializer.js +23 -14
- package/dist/cjs/src/generate/openapi/zustandBindings.js +1 -0
- package/dist/cjs/src/openapi-renderer/SerializerOpenapiRenderer.js +44 -3
- package/dist/cjs/src/package-exports/system.js +1 -0
- package/dist/esm/src/cli/helpers/PackageManager.js +10 -0
- package/dist/esm/src/generate/helpers/reduxBindings/writeInitializer.js +3 -1
- package/dist/esm/src/generate/helpers/syncOpenapiTypescript/generateInitializer.js +3 -1
- package/dist/esm/src/generate/helpers/zustandBindings/generateStoreFromSdk.js +74 -0
- package/dist/esm/src/generate/helpers/zustandBindings/printFinalStepsMessage.js +10 -13
- package/dist/esm/src/generate/helpers/zustandBindings/writeInitializer.js +23 -14
- package/dist/esm/src/generate/openapi/zustandBindings.js +1 -0
- package/dist/esm/src/openapi-renderer/SerializerOpenapiRenderer.js +44 -3
- package/dist/esm/src/package-exports/system.js +1 -0
- package/dist/types/src/cli/helpers/PackageManager.d.ts +1 -0
- package/dist/types/src/generate/helpers/zustandBindings/generateStoreFromSdk.d.ts +9 -0
- package/dist/types/src/generate/openapi/zustandBindings.d.ts +1 -0
- package/dist/types/src/package-exports/system.d.ts +1 -0
- package/package.json +3 -3
|
@@ -32,4 +32,14 @@ export default class PackageManager {
|
|
|
32
32
|
return `${this.packageManager} ${cmd}`;
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
|
+
static exec(cmd) {
|
|
36
|
+
switch (this.packageManager) {
|
|
37
|
+
case 'npm':
|
|
38
|
+
return `npm exec -- ${cmd}`;
|
|
39
|
+
case 'yarn':
|
|
40
|
+
return `yarn ${cmd}`;
|
|
41
|
+
default:
|
|
42
|
+
return `${this.packageManager} exec ${cmd}`;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
35
45
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { camelize, pascalize } from '@rvoh/dream/utils';
|
|
2
2
|
import * as fs from 'node:fs/promises';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
|
+
import PackageManager from '../../../cli/helpers/PackageManager.js';
|
|
4
5
|
import psychicPath from '../../../helpers/path/psychicPath.js';
|
|
5
6
|
export default async function writeInitializer({ exportName }) {
|
|
6
7
|
const pascalized = pascalize(exportName);
|
|
@@ -22,6 +23,7 @@ export default async function writeInitializer({ exportName }) {
|
|
|
22
23
|
await fs.mkdir(destDir, { recursive: true });
|
|
23
24
|
}
|
|
24
25
|
const filePath = path.join('.', 'src', 'conf', 'openapi', `${camelized}.openapi-codegen.json`);
|
|
26
|
+
const execCmd = PackageManager.exec(`rtk-query-codegen-openapi ${filePath}`);
|
|
25
27
|
const contents = `\
|
|
26
28
|
import { DreamCLI } from '@rvoh/dream/system'
|
|
27
29
|
import { PsychicApp } from '@rvoh/psychic'
|
|
@@ -31,7 +33,7 @@ export default function initialize${pascalized}(psy: PsychicApp) {
|
|
|
31
33
|
psy.on('cli:sync', async () => {
|
|
32
34
|
if (AppEnv.isDevelopmentOrTest) {
|
|
33
35
|
await DreamCLI.logger.logProgress(\`[${camelized}] syncing...\`, async () => {
|
|
34
|
-
await DreamCLI.spawn('
|
|
36
|
+
await DreamCLI.spawn('${execCmd}', {
|
|
35
37
|
onStdout: message => {
|
|
36
38
|
DreamCLI.logger.logContinueProgress(\`[${camelized}]\` + ' ' + message, {
|
|
37
39
|
logPrefixColor: 'green',
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { hyphenize } from '@rvoh/dream/utils';
|
|
2
2
|
import * as fs from 'node:fs/promises';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
|
+
import PackageManager from '../../../cli/helpers/PackageManager.js';
|
|
4
5
|
import psychicPath from '../../../helpers/path/psychicPath.js';
|
|
5
6
|
export default async function generateInitializer(openapiFilepath, outfile, initializerFilename) {
|
|
6
7
|
if (!/\.d\.ts$/.test(outfile))
|
|
@@ -15,6 +16,7 @@ export default async function generateInitializer(openapiFilepath, outfile, init
|
|
|
15
16
|
catch {
|
|
16
17
|
await fs.mkdir(destDir, { recursive: true });
|
|
17
18
|
}
|
|
19
|
+
const execCmd = PackageManager.exec(`openapi-typescript ${openapiFilepath} -o ${outfile}`);
|
|
18
20
|
const contents = `\
|
|
19
21
|
import { DreamCLI } from '@rvoh/dream/system'
|
|
20
22
|
import { PsychicApp } from "@rvoh/psychic"
|
|
@@ -24,7 +26,7 @@ export default (psy: PsychicApp) => {
|
|
|
24
26
|
psy.on('cli:sync', async () => {
|
|
25
27
|
if (AppEnv.isDevelopmentOrTest) {
|
|
26
28
|
await DreamCLI.logger.logProgress(\`[${hyphenized}] extracting types from ${openapiFilepath} to ${outfile}...\`, async () => {
|
|
27
|
-
await DreamCLI.spawn('
|
|
29
|
+
await DreamCLI.spawn('${execCmd}')
|
|
28
30
|
})
|
|
29
31
|
}
|
|
30
32
|
})
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
/**
|
|
4
|
+
* Reads the generated sdk.gen.ts file, extracts exported function names,
|
|
5
|
+
* and generates a store.gen.ts file with Zustand stores wrapping each
|
|
6
|
+
* SDK function.
|
|
7
|
+
*
|
|
8
|
+
* This is called during `psy sync` after @hey-api/openapi-ts has generated
|
|
9
|
+
* the SDK, so that the store stays in sync with the API.
|
|
10
|
+
*/
|
|
11
|
+
export default async function generateZustandStoreFromSdk(outputDir) {
|
|
12
|
+
const sdkPath = path.join(outputDir, 'sdk.gen.ts');
|
|
13
|
+
const storePath = path.join(outputDir, 'store.gen.ts');
|
|
14
|
+
let sdkContents;
|
|
15
|
+
try {
|
|
16
|
+
sdkContents = (await fs.readFile(sdkPath)).toString();
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return; // sdk.gen.ts doesn't exist yet, nothing to generate from
|
|
20
|
+
}
|
|
21
|
+
const functionNames = extractExportedFunctionNames(sdkContents);
|
|
22
|
+
if (functionNames.length === 0)
|
|
23
|
+
return;
|
|
24
|
+
const storeLines = functionNames.map(name => {
|
|
25
|
+
const hookName = 'use' + name.charAt(0).toUpperCase() + name.slice(1);
|
|
26
|
+
return `export const ${hookName} = createSdkStore(sdk.${name})`;
|
|
27
|
+
});
|
|
28
|
+
const contents = `\
|
|
29
|
+
// This file is auto-generated during sync — do not edit
|
|
30
|
+
import { create } from 'zustand'
|
|
31
|
+
import * as sdk from './sdk.gen'
|
|
32
|
+
|
|
33
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
34
|
+
type SdkFn = (...args: any[]) => Promise<{ data?: any; error?: any }>
|
|
35
|
+
|
|
36
|
+
interface SdkStore<TData, TArgs extends unknown[]> {
|
|
37
|
+
data: TData | undefined
|
|
38
|
+
error: unknown
|
|
39
|
+
isLoading: boolean
|
|
40
|
+
fetch: (...args: TArgs) => Promise<TData | undefined>
|
|
41
|
+
reset: () => void
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function createSdkStore<T extends SdkFn>(fn: T) {
|
|
45
|
+
type TData = Awaited<ReturnType<T>>['data']
|
|
46
|
+
return create<SdkStore<TData, Parameters<T>>>()((set) => ({
|
|
47
|
+
data: undefined as TData | undefined,
|
|
48
|
+
error: undefined as unknown,
|
|
49
|
+
isLoading: false,
|
|
50
|
+
|
|
51
|
+
fetch: async (...args: Parameters<T>) => {
|
|
52
|
+
set({ isLoading: true, error: undefined })
|
|
53
|
+
const { data, error } = await (fn as SdkFn)(...args)
|
|
54
|
+
set({ data, error, isLoading: false })
|
|
55
|
+
return data as TData | undefined
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
reset: () => set({ data: undefined, error: undefined, isLoading: false }),
|
|
59
|
+
}))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
${storeLines.join('\n')}
|
|
63
|
+
`;
|
|
64
|
+
await fs.writeFile(storePath, contents);
|
|
65
|
+
}
|
|
66
|
+
function extractExportedFunctionNames(sdkContents) {
|
|
67
|
+
const names = [];
|
|
68
|
+
const pattern = /export const (\w+)\s*=/g;
|
|
69
|
+
let match;
|
|
70
|
+
while ((match = pattern.exec(sdkContents)) !== null) {
|
|
71
|
+
names.push(match[1]);
|
|
72
|
+
}
|
|
73
|
+
return names;
|
|
74
|
+
}
|
|
@@ -8,17 +8,19 @@ export default function printFinalStepsMessage(opts) {
|
|
|
8
8
|
const usageLine = colorize(` const { data, error } = await getAdminCities()`, {
|
|
9
9
|
color: 'green',
|
|
10
10
|
});
|
|
11
|
-
const
|
|
12
|
-
|
|
11
|
+
const storeImportLine = colorize(`+ import { useGetAdminCities } from '${opts.outputDir}/store.gen'`, {
|
|
12
|
+
color: 'green',
|
|
13
|
+
});
|
|
13
14
|
DreamCLI.logger.log(`
|
|
14
15
|
Finished generating @hey-api/openapi-ts bindings for your application.
|
|
15
16
|
|
|
16
17
|
First, you will need to be sure to sync, so that the typed API functions
|
|
17
|
-
are generated from your openapi schema:
|
|
18
|
+
and Zustand store are generated from your openapi schema:
|
|
18
19
|
|
|
19
20
|
pnpm psy sync
|
|
20
21
|
|
|
21
|
-
This will generate typed API functions
|
|
22
|
+
This will generate typed API functions in ${opts.outputDir}/sdk.gen.ts
|
|
23
|
+
and a Zustand store in ${opts.outputDir}/store.gen.ts
|
|
22
24
|
|
|
23
25
|
To use the generated API, first import the client config at your app's
|
|
24
26
|
entry point to configure the base URL and credentials:
|
|
@@ -32,16 +34,11 @@ ${sdkImportLine}
|
|
|
32
34
|
// all functions are fully typed with request params and response types
|
|
33
35
|
${usageLine}
|
|
34
36
|
|
|
35
|
-
|
|
37
|
+
Or use the auto-generated Zustand store hooks for state management:
|
|
36
38
|
|
|
37
|
-
|
|
38
|
-
${sdkImportLine}
|
|
39
|
+
${storeImportLine}
|
|
39
40
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
fetchCities: async () => {
|
|
43
|
-
${zustandLine}
|
|
44
|
-
},
|
|
45
|
-
}))
|
|
41
|
+
// each hook provides { data, error, isLoading, fetch, reset }
|
|
42
|
+
const { data, isLoading, fetch } = useGetAdminCities()
|
|
46
43
|
`, { logPrefix: '' });
|
|
47
44
|
}
|
|
@@ -1,36 +1,26 @@
|
|
|
1
1
|
import { camelize, pascalize } from '@rvoh/dream/utils';
|
|
2
2
|
import * as fs from 'node:fs/promises';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
|
+
import PackageManager from '../../../cli/helpers/PackageManager.js';
|
|
4
5
|
import psychicPath from '../../../helpers/path/psychicPath.js';
|
|
5
6
|
export default async function writeInitializer({ exportName, schemaFile, outputDir, }) {
|
|
6
7
|
const pascalized = pascalize(exportName);
|
|
7
8
|
const camelized = camelize(exportName);
|
|
9
|
+
const execCmd = PackageManager.exec(`openapi-ts -i ${schemaFile} -o ${outputDir}`);
|
|
8
10
|
const destDir = path.join(psychicPath('conf'), 'initializers', 'openapi');
|
|
9
11
|
const initializerFilename = `${camelized}.ts`;
|
|
10
12
|
const initializerPath = path.join(destDir, initializerFilename);
|
|
11
|
-
try {
|
|
12
|
-
await fs.access(initializerPath);
|
|
13
|
-
return; // early return if the file already exists
|
|
14
|
-
}
|
|
15
|
-
catch {
|
|
16
|
-
// noop
|
|
17
|
-
}
|
|
18
|
-
try {
|
|
19
|
-
await fs.access(destDir);
|
|
20
|
-
}
|
|
21
|
-
catch {
|
|
22
|
-
await fs.mkdir(destDir, { recursive: true });
|
|
23
|
-
}
|
|
24
13
|
const contents = `\
|
|
25
14
|
import { DreamCLI } from '@rvoh/dream/system'
|
|
26
15
|
import { PsychicApp } from '@rvoh/psychic'
|
|
16
|
+
import { generateZustandStoreFromSdk } from '@rvoh/psychic/system'
|
|
27
17
|
import AppEnv from '../../AppEnv.js'
|
|
28
18
|
|
|
29
19
|
export default function initialize${pascalized}(psy: PsychicApp) {
|
|
30
20
|
psy.on('cli:sync', async () => {
|
|
31
21
|
if (AppEnv.isDevelopmentOrTest) {
|
|
32
22
|
await DreamCLI.logger.logProgress(\`[${camelized}] syncing...\`, async () => {
|
|
33
|
-
await DreamCLI.spawn('
|
|
23
|
+
await DreamCLI.spawn('${execCmd}', {
|
|
34
24
|
onStdout: message => {
|
|
35
25
|
DreamCLI.logger.logContinueProgress(\`[${camelized}]\` + ' ' + message, {
|
|
36
26
|
logPrefixColor: 'green',
|
|
@@ -38,9 +28,28 @@ export default function initialize${pascalized}(psy: PsychicApp) {
|
|
|
38
28
|
},
|
|
39
29
|
})
|
|
40
30
|
})
|
|
31
|
+
|
|
32
|
+
await DreamCLI.logger.logProgress(\`[${camelized}] generating zustand store...\`, async () => {
|
|
33
|
+
await generateZustandStoreFromSdk('${outputDir}')
|
|
34
|
+
})
|
|
41
35
|
}
|
|
42
36
|
})
|
|
43
37
|
}\
|
|
44
38
|
`;
|
|
39
|
+
try {
|
|
40
|
+
const existingContents = (await fs.readFile(initializerPath)).toString();
|
|
41
|
+
if (existingContents === contents) {
|
|
42
|
+
return; // early return if the file already matches exactly
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// noop — file doesn't exist yet
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
await fs.access(destDir);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
await fs.mkdir(destDir, { recursive: true });
|
|
53
|
+
}
|
|
45
54
|
await fs.writeFile(initializerPath, contents);
|
|
46
55
|
}
|
|
@@ -14,6 +14,7 @@ import writeInitializer from '../helpers/zustandBindings/writeInitializer.js';
|
|
|
14
14
|
* * generates the client config file if it does not exist
|
|
15
15
|
* * generates an initializer, which taps into the sync hooks
|
|
16
16
|
* to automatically run the @hey-api/openapi-ts CLI util
|
|
17
|
+
* and generate a zustand store from the SDK output
|
|
17
18
|
* * prints a helpful message, instructing devs on the final
|
|
18
19
|
* steps for using the generated typed API functions
|
|
19
20
|
* within their client application.
|
|
@@ -139,13 +139,16 @@ export default class SerializerOpenapiRenderer {
|
|
|
139
139
|
const openapi = attribute.options.openapi;
|
|
140
140
|
newlyReferencedSerializers = allSerializersFromHandWrittenOpenapi(openapi);
|
|
141
141
|
let target;
|
|
142
|
+
let delegatedAssociationOptional = false;
|
|
142
143
|
if (attributeType === 'delegatedAttribute' && DataTypeForOpenapi?.isDream) {
|
|
143
144
|
const source = DataTypeForOpenapi;
|
|
144
|
-
|
|
145
|
-
const associatedModelOrModels =
|
|
145
|
+
const association = source['getAssociationMetadata'](attribute.targetName);
|
|
146
|
+
const associatedModelOrModels = association?.modelCB();
|
|
146
147
|
target = Array.isArray(associatedModelOrModels)
|
|
147
148
|
? associatedModelOrModels[0]
|
|
148
149
|
: associatedModelOrModels;
|
|
150
|
+
delegatedAssociationOptional = !!association
|
|
151
|
+
?.optional;
|
|
149
152
|
}
|
|
150
153
|
else if (attributeType === 'delegatedAttribute') {
|
|
151
154
|
target = undefined;
|
|
@@ -153,11 +156,36 @@ export default class SerializerOpenapiRenderer {
|
|
|
153
156
|
else {
|
|
154
157
|
target = DataTypeForOpenapi;
|
|
155
158
|
}
|
|
156
|
-
|
|
159
|
+
const resolvedSchema = allSerializersToRefsInOpenapi(target?.isDream
|
|
157
160
|
? dreamColumnOpenapiShape(this.serializer.globalName, target, attribute.name, openapi, {
|
|
158
161
|
suppressResponseEnums: this.suppressResponseEnums,
|
|
159
162
|
})
|
|
160
163
|
: openapiShorthandToOpenapi(openapi));
|
|
164
|
+
const optional = attributeType === 'delegatedAttribute' &&
|
|
165
|
+
(attribute.options.optional ?? delegatedAssociationOptional);
|
|
166
|
+
if (optional && !openapiSchemaIncludesNull(resolvedSchema)) {
|
|
167
|
+
const schemaRecord = resolvedSchema;
|
|
168
|
+
if (typeof schemaRecord.type === 'string') {
|
|
169
|
+
accumulator[outputAttributeName] = {
|
|
170
|
+
...schemaRecord,
|
|
171
|
+
type: [schemaRecord.type, 'null'],
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
else if (Array.isArray(schemaRecord.type)) {
|
|
175
|
+
accumulator[outputAttributeName] = {
|
|
176
|
+
...schemaRecord,
|
|
177
|
+
type: [...schemaRecord.type, 'null'],
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
accumulator[outputAttributeName] = {
|
|
182
|
+
anyOf: [resolvedSchema, NULL_OBJECT_OPENAPI],
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
accumulator[outputAttributeName] = resolvedSchema;
|
|
188
|
+
}
|
|
161
189
|
return accumulator;
|
|
162
190
|
}
|
|
163
191
|
/////////////////////////////////////////////
|
|
@@ -375,3 +403,16 @@ function descendantSerializers(serializer, alreadyExtractedDescendantSerializers
|
|
|
375
403
|
// throws an error)
|
|
376
404
|
class CallingSerializersThrewError extends Error {
|
|
377
405
|
}
|
|
406
|
+
function openapiSchemaIncludesNull(schema) {
|
|
407
|
+
if (typeof schema !== 'object' || schema === null)
|
|
408
|
+
return false;
|
|
409
|
+
const schemaRecord = schema;
|
|
410
|
+
if (Array.isArray(schemaRecord.type) && schemaRecord.type.includes('null'))
|
|
411
|
+
return true;
|
|
412
|
+
if (schemaRecord.type === 'null')
|
|
413
|
+
return true;
|
|
414
|
+
if (Array.isArray(schemaRecord.anyOf) &&
|
|
415
|
+
schemaRecord.anyOf.some((member) => openapiSchemaIncludesNull(member)))
|
|
416
|
+
return true;
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { default as generateZustandStoreFromSdk } from '../generate/helpers/zustandBindings/generateStoreFromSdk.js';
|
|
1
2
|
export { default as PsychicBin } from '../bin/index.js';
|
|
2
3
|
export { default as PsychicLogos } from '../cli/helpers/PsychicLogos.js';
|
|
3
4
|
export { default as PsychicCLI } from '../cli/index.js';
|
|
@@ -32,4 +32,14 @@ export default class PackageManager {
|
|
|
32
32
|
return `${this.packageManager} ${cmd}`;
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
|
+
static exec(cmd) {
|
|
36
|
+
switch (this.packageManager) {
|
|
37
|
+
case 'npm':
|
|
38
|
+
return `npm exec -- ${cmd}`;
|
|
39
|
+
case 'yarn':
|
|
40
|
+
return `yarn ${cmd}`;
|
|
41
|
+
default:
|
|
42
|
+
return `${this.packageManager} exec ${cmd}`;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
35
45
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { camelize, pascalize } from '@rvoh/dream/utils';
|
|
2
2
|
import * as fs from 'node:fs/promises';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
|
+
import PackageManager from '../../../cli/helpers/PackageManager.js';
|
|
4
5
|
import psychicPath from '../../../helpers/path/psychicPath.js';
|
|
5
6
|
export default async function writeInitializer({ exportName }) {
|
|
6
7
|
const pascalized = pascalize(exportName);
|
|
@@ -22,6 +23,7 @@ export default async function writeInitializer({ exportName }) {
|
|
|
22
23
|
await fs.mkdir(destDir, { recursive: true });
|
|
23
24
|
}
|
|
24
25
|
const filePath = path.join('.', 'src', 'conf', 'openapi', `${camelized}.openapi-codegen.json`);
|
|
26
|
+
const execCmd = PackageManager.exec(`rtk-query-codegen-openapi ${filePath}`);
|
|
25
27
|
const contents = `\
|
|
26
28
|
import { DreamCLI } from '@rvoh/dream/system'
|
|
27
29
|
import { PsychicApp } from '@rvoh/psychic'
|
|
@@ -31,7 +33,7 @@ export default function initialize${pascalized}(psy: PsychicApp) {
|
|
|
31
33
|
psy.on('cli:sync', async () => {
|
|
32
34
|
if (AppEnv.isDevelopmentOrTest) {
|
|
33
35
|
await DreamCLI.logger.logProgress(\`[${camelized}] syncing...\`, async () => {
|
|
34
|
-
await DreamCLI.spawn('
|
|
36
|
+
await DreamCLI.spawn('${execCmd}', {
|
|
35
37
|
onStdout: message => {
|
|
36
38
|
DreamCLI.logger.logContinueProgress(\`[${camelized}]\` + ' ' + message, {
|
|
37
39
|
logPrefixColor: 'green',
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { hyphenize } from '@rvoh/dream/utils';
|
|
2
2
|
import * as fs from 'node:fs/promises';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
|
+
import PackageManager from '../../../cli/helpers/PackageManager.js';
|
|
4
5
|
import psychicPath from '../../../helpers/path/psychicPath.js';
|
|
5
6
|
export default async function generateInitializer(openapiFilepath, outfile, initializerFilename) {
|
|
6
7
|
if (!/\.d\.ts$/.test(outfile))
|
|
@@ -15,6 +16,7 @@ export default async function generateInitializer(openapiFilepath, outfile, init
|
|
|
15
16
|
catch {
|
|
16
17
|
await fs.mkdir(destDir, { recursive: true });
|
|
17
18
|
}
|
|
19
|
+
const execCmd = PackageManager.exec(`openapi-typescript ${openapiFilepath} -o ${outfile}`);
|
|
18
20
|
const contents = `\
|
|
19
21
|
import { DreamCLI } from '@rvoh/dream/system'
|
|
20
22
|
import { PsychicApp } from "@rvoh/psychic"
|
|
@@ -24,7 +26,7 @@ export default (psy: PsychicApp) => {
|
|
|
24
26
|
psy.on('cli:sync', async () => {
|
|
25
27
|
if (AppEnv.isDevelopmentOrTest) {
|
|
26
28
|
await DreamCLI.logger.logProgress(\`[${hyphenized}] extracting types from ${openapiFilepath} to ${outfile}...\`, async () => {
|
|
27
|
-
await DreamCLI.spawn('
|
|
29
|
+
await DreamCLI.spawn('${execCmd}')
|
|
28
30
|
})
|
|
29
31
|
}
|
|
30
32
|
})
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
/**
|
|
4
|
+
* Reads the generated sdk.gen.ts file, extracts exported function names,
|
|
5
|
+
* and generates a store.gen.ts file with Zustand stores wrapping each
|
|
6
|
+
* SDK function.
|
|
7
|
+
*
|
|
8
|
+
* This is called during `psy sync` after @hey-api/openapi-ts has generated
|
|
9
|
+
* the SDK, so that the store stays in sync with the API.
|
|
10
|
+
*/
|
|
11
|
+
export default async function generateZustandStoreFromSdk(outputDir) {
|
|
12
|
+
const sdkPath = path.join(outputDir, 'sdk.gen.ts');
|
|
13
|
+
const storePath = path.join(outputDir, 'store.gen.ts');
|
|
14
|
+
let sdkContents;
|
|
15
|
+
try {
|
|
16
|
+
sdkContents = (await fs.readFile(sdkPath)).toString();
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return; // sdk.gen.ts doesn't exist yet, nothing to generate from
|
|
20
|
+
}
|
|
21
|
+
const functionNames = extractExportedFunctionNames(sdkContents);
|
|
22
|
+
if (functionNames.length === 0)
|
|
23
|
+
return;
|
|
24
|
+
const storeLines = functionNames.map(name => {
|
|
25
|
+
const hookName = 'use' + name.charAt(0).toUpperCase() + name.slice(1);
|
|
26
|
+
return `export const ${hookName} = createSdkStore(sdk.${name})`;
|
|
27
|
+
});
|
|
28
|
+
const contents = `\
|
|
29
|
+
// This file is auto-generated during sync — do not edit
|
|
30
|
+
import { create } from 'zustand'
|
|
31
|
+
import * as sdk from './sdk.gen'
|
|
32
|
+
|
|
33
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
34
|
+
type SdkFn = (...args: any[]) => Promise<{ data?: any; error?: any }>
|
|
35
|
+
|
|
36
|
+
interface SdkStore<TData, TArgs extends unknown[]> {
|
|
37
|
+
data: TData | undefined
|
|
38
|
+
error: unknown
|
|
39
|
+
isLoading: boolean
|
|
40
|
+
fetch: (...args: TArgs) => Promise<TData | undefined>
|
|
41
|
+
reset: () => void
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function createSdkStore<T extends SdkFn>(fn: T) {
|
|
45
|
+
type TData = Awaited<ReturnType<T>>['data']
|
|
46
|
+
return create<SdkStore<TData, Parameters<T>>>()((set) => ({
|
|
47
|
+
data: undefined as TData | undefined,
|
|
48
|
+
error: undefined as unknown,
|
|
49
|
+
isLoading: false,
|
|
50
|
+
|
|
51
|
+
fetch: async (...args: Parameters<T>) => {
|
|
52
|
+
set({ isLoading: true, error: undefined })
|
|
53
|
+
const { data, error } = await (fn as SdkFn)(...args)
|
|
54
|
+
set({ data, error, isLoading: false })
|
|
55
|
+
return data as TData | undefined
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
reset: () => set({ data: undefined, error: undefined, isLoading: false }),
|
|
59
|
+
}))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
${storeLines.join('\n')}
|
|
63
|
+
`;
|
|
64
|
+
await fs.writeFile(storePath, contents);
|
|
65
|
+
}
|
|
66
|
+
function extractExportedFunctionNames(sdkContents) {
|
|
67
|
+
const names = [];
|
|
68
|
+
const pattern = /export const (\w+)\s*=/g;
|
|
69
|
+
let match;
|
|
70
|
+
while ((match = pattern.exec(sdkContents)) !== null) {
|
|
71
|
+
names.push(match[1]);
|
|
72
|
+
}
|
|
73
|
+
return names;
|
|
74
|
+
}
|
|
@@ -8,17 +8,19 @@ export default function printFinalStepsMessage(opts) {
|
|
|
8
8
|
const usageLine = colorize(` const { data, error } = await getAdminCities()`, {
|
|
9
9
|
color: 'green',
|
|
10
10
|
});
|
|
11
|
-
const
|
|
12
|
-
|
|
11
|
+
const storeImportLine = colorize(`+ import { useGetAdminCities } from '${opts.outputDir}/store.gen'`, {
|
|
12
|
+
color: 'green',
|
|
13
|
+
});
|
|
13
14
|
DreamCLI.logger.log(`
|
|
14
15
|
Finished generating @hey-api/openapi-ts bindings for your application.
|
|
15
16
|
|
|
16
17
|
First, you will need to be sure to sync, so that the typed API functions
|
|
17
|
-
are generated from your openapi schema:
|
|
18
|
+
and Zustand store are generated from your openapi schema:
|
|
18
19
|
|
|
19
20
|
pnpm psy sync
|
|
20
21
|
|
|
21
|
-
This will generate typed API functions
|
|
22
|
+
This will generate typed API functions in ${opts.outputDir}/sdk.gen.ts
|
|
23
|
+
and a Zustand store in ${opts.outputDir}/store.gen.ts
|
|
22
24
|
|
|
23
25
|
To use the generated API, first import the client config at your app's
|
|
24
26
|
entry point to configure the base URL and credentials:
|
|
@@ -32,16 +34,11 @@ ${sdkImportLine}
|
|
|
32
34
|
// all functions are fully typed with request params and response types
|
|
33
35
|
${usageLine}
|
|
34
36
|
|
|
35
|
-
|
|
37
|
+
Or use the auto-generated Zustand store hooks for state management:
|
|
36
38
|
|
|
37
|
-
|
|
38
|
-
${sdkImportLine}
|
|
39
|
+
${storeImportLine}
|
|
39
40
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
fetchCities: async () => {
|
|
43
|
-
${zustandLine}
|
|
44
|
-
},
|
|
45
|
-
}))
|
|
41
|
+
// each hook provides { data, error, isLoading, fetch, reset }
|
|
42
|
+
const { data, isLoading, fetch } = useGetAdminCities()
|
|
46
43
|
`, { logPrefix: '' });
|
|
47
44
|
}
|
|
@@ -1,36 +1,26 @@
|
|
|
1
1
|
import { camelize, pascalize } from '@rvoh/dream/utils';
|
|
2
2
|
import * as fs from 'node:fs/promises';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
|
+
import PackageManager from '../../../cli/helpers/PackageManager.js';
|
|
4
5
|
import psychicPath from '../../../helpers/path/psychicPath.js';
|
|
5
6
|
export default async function writeInitializer({ exportName, schemaFile, outputDir, }) {
|
|
6
7
|
const pascalized = pascalize(exportName);
|
|
7
8
|
const camelized = camelize(exportName);
|
|
9
|
+
const execCmd = PackageManager.exec(`openapi-ts -i ${schemaFile} -o ${outputDir}`);
|
|
8
10
|
const destDir = path.join(psychicPath('conf'), 'initializers', 'openapi');
|
|
9
11
|
const initializerFilename = `${camelized}.ts`;
|
|
10
12
|
const initializerPath = path.join(destDir, initializerFilename);
|
|
11
|
-
try {
|
|
12
|
-
await fs.access(initializerPath);
|
|
13
|
-
return; // early return if the file already exists
|
|
14
|
-
}
|
|
15
|
-
catch {
|
|
16
|
-
// noop
|
|
17
|
-
}
|
|
18
|
-
try {
|
|
19
|
-
await fs.access(destDir);
|
|
20
|
-
}
|
|
21
|
-
catch {
|
|
22
|
-
await fs.mkdir(destDir, { recursive: true });
|
|
23
|
-
}
|
|
24
13
|
const contents = `\
|
|
25
14
|
import { DreamCLI } from '@rvoh/dream/system'
|
|
26
15
|
import { PsychicApp } from '@rvoh/psychic'
|
|
16
|
+
import { generateZustandStoreFromSdk } from '@rvoh/psychic/system'
|
|
27
17
|
import AppEnv from '../../AppEnv.js'
|
|
28
18
|
|
|
29
19
|
export default function initialize${pascalized}(psy: PsychicApp) {
|
|
30
20
|
psy.on('cli:sync', async () => {
|
|
31
21
|
if (AppEnv.isDevelopmentOrTest) {
|
|
32
22
|
await DreamCLI.logger.logProgress(\`[${camelized}] syncing...\`, async () => {
|
|
33
|
-
await DreamCLI.spawn('
|
|
23
|
+
await DreamCLI.spawn('${execCmd}', {
|
|
34
24
|
onStdout: message => {
|
|
35
25
|
DreamCLI.logger.logContinueProgress(\`[${camelized}]\` + ' ' + message, {
|
|
36
26
|
logPrefixColor: 'green',
|
|
@@ -38,9 +28,28 @@ export default function initialize${pascalized}(psy: PsychicApp) {
|
|
|
38
28
|
},
|
|
39
29
|
})
|
|
40
30
|
})
|
|
31
|
+
|
|
32
|
+
await DreamCLI.logger.logProgress(\`[${camelized}] generating zustand store...\`, async () => {
|
|
33
|
+
await generateZustandStoreFromSdk('${outputDir}')
|
|
34
|
+
})
|
|
41
35
|
}
|
|
42
36
|
})
|
|
43
37
|
}\
|
|
44
38
|
`;
|
|
39
|
+
try {
|
|
40
|
+
const existingContents = (await fs.readFile(initializerPath)).toString();
|
|
41
|
+
if (existingContents === contents) {
|
|
42
|
+
return; // early return if the file already matches exactly
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// noop — file doesn't exist yet
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
await fs.access(destDir);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
await fs.mkdir(destDir, { recursive: true });
|
|
53
|
+
}
|
|
45
54
|
await fs.writeFile(initializerPath, contents);
|
|
46
55
|
}
|
|
@@ -14,6 +14,7 @@ import writeInitializer from '../helpers/zustandBindings/writeInitializer.js';
|
|
|
14
14
|
* * generates the client config file if it does not exist
|
|
15
15
|
* * generates an initializer, which taps into the sync hooks
|
|
16
16
|
* to automatically run the @hey-api/openapi-ts CLI util
|
|
17
|
+
* and generate a zustand store from the SDK output
|
|
17
18
|
* * prints a helpful message, instructing devs on the final
|
|
18
19
|
* steps for using the generated typed API functions
|
|
19
20
|
* within their client application.
|
|
@@ -139,13 +139,16 @@ export default class SerializerOpenapiRenderer {
|
|
|
139
139
|
const openapi = attribute.options.openapi;
|
|
140
140
|
newlyReferencedSerializers = allSerializersFromHandWrittenOpenapi(openapi);
|
|
141
141
|
let target;
|
|
142
|
+
let delegatedAssociationOptional = false;
|
|
142
143
|
if (attributeType === 'delegatedAttribute' && DataTypeForOpenapi?.isDream) {
|
|
143
144
|
const source = DataTypeForOpenapi;
|
|
144
|
-
|
|
145
|
-
const associatedModelOrModels =
|
|
145
|
+
const association = source['getAssociationMetadata'](attribute.targetName);
|
|
146
|
+
const associatedModelOrModels = association?.modelCB();
|
|
146
147
|
target = Array.isArray(associatedModelOrModels)
|
|
147
148
|
? associatedModelOrModels[0]
|
|
148
149
|
: associatedModelOrModels;
|
|
150
|
+
delegatedAssociationOptional = !!association
|
|
151
|
+
?.optional;
|
|
149
152
|
}
|
|
150
153
|
else if (attributeType === 'delegatedAttribute') {
|
|
151
154
|
target = undefined;
|
|
@@ -153,11 +156,36 @@ export default class SerializerOpenapiRenderer {
|
|
|
153
156
|
else {
|
|
154
157
|
target = DataTypeForOpenapi;
|
|
155
158
|
}
|
|
156
|
-
|
|
159
|
+
const resolvedSchema = allSerializersToRefsInOpenapi(target?.isDream
|
|
157
160
|
? dreamColumnOpenapiShape(this.serializer.globalName, target, attribute.name, openapi, {
|
|
158
161
|
suppressResponseEnums: this.suppressResponseEnums,
|
|
159
162
|
})
|
|
160
163
|
: openapiShorthandToOpenapi(openapi));
|
|
164
|
+
const optional = attributeType === 'delegatedAttribute' &&
|
|
165
|
+
(attribute.options.optional ?? delegatedAssociationOptional);
|
|
166
|
+
if (optional && !openapiSchemaIncludesNull(resolvedSchema)) {
|
|
167
|
+
const schemaRecord = resolvedSchema;
|
|
168
|
+
if (typeof schemaRecord.type === 'string') {
|
|
169
|
+
accumulator[outputAttributeName] = {
|
|
170
|
+
...schemaRecord,
|
|
171
|
+
type: [schemaRecord.type, 'null'],
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
else if (Array.isArray(schemaRecord.type)) {
|
|
175
|
+
accumulator[outputAttributeName] = {
|
|
176
|
+
...schemaRecord,
|
|
177
|
+
type: [...schemaRecord.type, 'null'],
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
accumulator[outputAttributeName] = {
|
|
182
|
+
anyOf: [resolvedSchema, NULL_OBJECT_OPENAPI],
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
accumulator[outputAttributeName] = resolvedSchema;
|
|
188
|
+
}
|
|
161
189
|
return accumulator;
|
|
162
190
|
}
|
|
163
191
|
/////////////////////////////////////////////
|
|
@@ -375,3 +403,16 @@ function descendantSerializers(serializer, alreadyExtractedDescendantSerializers
|
|
|
375
403
|
// throws an error)
|
|
376
404
|
class CallingSerializersThrewError extends Error {
|
|
377
405
|
}
|
|
406
|
+
function openapiSchemaIncludesNull(schema) {
|
|
407
|
+
if (typeof schema !== 'object' || schema === null)
|
|
408
|
+
return false;
|
|
409
|
+
const schemaRecord = schema;
|
|
410
|
+
if (Array.isArray(schemaRecord.type) && schemaRecord.type.includes('null'))
|
|
411
|
+
return true;
|
|
412
|
+
if (schemaRecord.type === 'null')
|
|
413
|
+
return true;
|
|
414
|
+
if (Array.isArray(schemaRecord.anyOf) &&
|
|
415
|
+
schemaRecord.anyOf.some((member) => openapiSchemaIncludesNull(member)))
|
|
416
|
+
return true;
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { default as generateZustandStoreFromSdk } from '../generate/helpers/zustandBindings/generateStoreFromSdk.js';
|
|
1
2
|
export { default as PsychicBin } from '../bin/index.js';
|
|
2
3
|
export { default as PsychicLogos } from '../cli/helpers/PsychicLogos.js';
|
|
3
4
|
export { default as PsychicCLI } from '../cli/index.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads the generated sdk.gen.ts file, extracts exported function names,
|
|
3
|
+
* and generates a store.gen.ts file with Zustand stores wrapping each
|
|
4
|
+
* SDK function.
|
|
5
|
+
*
|
|
6
|
+
* This is called during `psy sync` after @hey-api/openapi-ts has generated
|
|
7
|
+
* the SDK, so that the store stays in sync with the API.
|
|
8
|
+
*/
|
|
9
|
+
export default function generateZustandStoreFromSdk(outputDir: string): Promise<void>;
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* * generates the client config file if it does not exist
|
|
9
9
|
* * generates an initializer, which taps into the sync hooks
|
|
10
10
|
* to automatically run the @hey-api/openapi-ts CLI util
|
|
11
|
+
* and generate a zustand store from the SDK output
|
|
11
12
|
* * prints a helpful message, instructing devs on the final
|
|
12
13
|
* steps for using the generated typed API functions
|
|
13
14
|
* within their client application.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { default as generateZustandStoreFromSdk } from '../generate/helpers/zustandBindings/generateStoreFromSdk.js';
|
|
1
2
|
export { default as PsychicBin } from '../bin/index.js';
|
|
2
3
|
export { default as PsychicLogos } from '../cli/helpers/PsychicLogos.js';
|
|
3
4
|
export { default as PsychicCLI } from '../cli/index.js';
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "@rvoh/psychic",
|
|
4
4
|
"description": "Typescript web framework",
|
|
5
|
-
"version": "3.
|
|
5
|
+
"version": "3.1.1",
|
|
6
6
|
"author": "RVOHealth",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"@koa/cors": "^5.0.0",
|
|
76
76
|
"@koa/etag": "^5.0.2",
|
|
77
77
|
"@koa/router": "^15.3.0",
|
|
78
|
-
"@rvoh/dream": "^2.
|
|
78
|
+
"@rvoh/dream": "^2.6.0",
|
|
79
79
|
"@types/koa": "^3.0.1",
|
|
80
80
|
"@types/koa-bodyparser": "^4.3.12",
|
|
81
81
|
"@types/koa-conditional-get": "^2.0.3",
|
|
@@ -92,7 +92,7 @@
|
|
|
92
92
|
"@koa/cors": "^5.0.0",
|
|
93
93
|
"@koa/etag": "^5.0.2",
|
|
94
94
|
"@koa/router": "^15.3.1",
|
|
95
|
-
"@rvoh/dream": "^2.
|
|
95
|
+
"@rvoh/dream": "^2.6.0",
|
|
96
96
|
"@rvoh/dream-spec-helpers": "^2.1.1",
|
|
97
97
|
"@rvoh/psychic-spec-helpers": "3.0.0",
|
|
98
98
|
"@types/koa": "^3.0.1",
|