Skip to content

Commit 85922ec

Browse files
nahuel-polyapiaarongoinRichardDzurussudiptatjeupharis
authored
Road to R27 [EU1] (#47)
* some cleanup and bringing over hidden files * bringing over the deploy workflow * adding CI/CD workflows * updating to use npm cache instead of yarn * Bringing in Richard's updates! * Some missed cleanup, missing dev dependencies, and fixed build. * hard pinned package versions (#2) * adding husky pre-commit hook for linting * # Feature (4156): P3) Bug with deploying a client function after it a… (#1) * # Feature (4156): P3) Bug with deploying a client function after it as deployed as a server function - Refactoring npm client - Verification added for checking existing function by name and context - color updated * Fixing bug where client was not resolving dependencies correctly * adding missing dependency for testing, and fixing issue where some names in the generated schemas were not being wrapped in quotes * Handling x-poly-refs contained with function arguments that are themselves function types (fixes webhook types and more) * improve logging of failed api function calls (#4) * improve logging of failed api function calls * Update templates/api-index.js.hbs Co-authored-by: Aaron Goin <aarongoin@users.noreply.github.com> * onward --------- Co-authored-by: Aaron Goin <aarongoin@users.noreply.github.com> * P2) (MS) npm client: add direct execute option and MTLS option (#3) * adds direct execute and mtls options support * reversed unintended change * fixed metric names + http agent to be created only once * version increment * lost my logging in code review, lets go agane (#6) * P3) VSCode Extension: Add a Refresh Button to Tree View #4107 (#5) * # Feature (4107): P3) VSCode Extension: Add a Refresh Button to Tree View - load config now can return value - Add or Update config function added * # Feature (4107): P3) VSCode Extension: Add a Refresh Button to Tree View - load config now can return value - Add or Update config function added - Version updated * 4372 update contexts info from terminal (#8) * # Feature (4107): P3) VSCode Extension: Add a Refresh Button to Tree View - load config now can return value - Add or Update config function added - if contexts is empty then it will not save in .config.env * schema generation improvements Supporting $refs defined inline within a schema. Fixing bug where allowing additional attributes on objects by default. Fixing bug where additional attributes generated name was wrapped in extra quotes. Fixing bug where schemas without contexts would fail to be generated. Improving schema generation to remove the extra interfaces which just cause noise for users. Removing yarn.lock since we only use NPM in this repo * Bumping to 0.23.19 to follow Richard's PR * # Feature (2790): P4) Ability to control npx poly generate via an extra view in VS code extension (can repurpose the configuration UI) (#11) - Local config updated - Version updated * try new action * Revert "try new action" This reverts commit 540feeb. * Bug fixes and improvements - Catching axios errors and scrubbing them of polyapi tokens and secrets - Fixing schema generation to remove extra, empty interfaces - Adding support for schemas with refs to inline definitions - Fixing bug where schemas with no contexts would not be generated - Fixing bug where schema public namespace was not Pascal cased * fixing generated webhooks and server functions * try a KISS version of auto deploy prebuilt (#12) * P1) Update typescript client to remove warnings (#7) * ts-json-schema-generator used instead of outdated package + eslint upgrade * eslint hardcode * eslintignore removed * eslint.config.js renamed to eslint.config.mjs to prevent errors * lock file updated * fix complex types * fix server function runtime * downgrade package to fix the wrong export of subpackage issue (#14) * Improving safety of scrubKeys utility * lets test the auto-update prebuilt functionality * Changed command structure to fix windows glide bug (#15) * Changed command structure to fix windows glide bug * Added comment to explain strange syntax * Allowed directories to be specified in the command * Updated excludeCommand quotations and comment * Updated version * Added package-lock.json * Dirty deployables are now added to git after being updated (#16) * Dirty deployables are now added to git after being updated * changed slice to replace * Changed log to warn * Re-fixed glide commit bug (#18) * Adding support for tabi tables, and fixing small bug when generating empty object type (#13) * Adding support for tabi tables, and fixing small bug when generating empty object type * Fix update query * Fix type on update query * sime minor tweaks to tabi query types * lint and fixing deleteOne response * adding count query and fixing tests * 4324 p2 add new field cachepolylibrary false to customfunction table if its set to true do the behavior now behind faascachingenabled (#19) * adds support for cachePolyLibrary for server functions in glide and cache-poly-library flag * increment version * P3) TS Client: Log PolyAPI Library version on function startup (#20) * welcome message for users with package version * show welcome message on first use * Updating server function configs to support more properties, allowing for setting description via the config, and fixing bug where tabi tables could not be lowercase * 4504 p3 glide bug npx poly prepare does not find any deployables in windows (#21) * Changed command structure to fix windows glide bug * Added comment to explain strange syntax * Allowed directories to be specified in the command * Updated excludeCommand quotations and comment * Updated version * Added package-lock.json * Fixed config name TypeError * Revert "Fixed config name TypeError" This reverts commit 7b32086. * Fixed windows find deployables command to ignore files without polyConfig * Making sure api function call errors aren't logged unless LOGS_ENABLED environment flag is truthy * Remove the welcome message for now * Windows glide duplicate deployables fix (#22) * Changed windows command for finding deployables to ensure that the same file is not found multiple times * Added replace to remove file paths in glide prepare * version * version * Removing the updateOne and deleteOne queries from Tabi for now since they don't really work! * Warn on schema fallback (#25) * Added warning when falling back to unknown type * Bumped version * Moved warning to schemaTypes to ensure that warnings are not duplicated * Added falling back message * added scrubbing to api function requestArgs (#27) * added scrubbing to api function requestArgs * Changed iteration to go through keys, added scrubbing to scrubKeys, changed * to 8 * closed some holes and fixed some edge cases * cleaning the scrubbing * bumped version * changed Record to Partial<Record> * Changed import path (#29) * Fix scrub import again (#30) * reversed imports * bumped version * added scrub to exports * Changed warning message (#31) * Changed warning message * reworded message * removed the afro * assigned scrub to a variable instead of just doing nothing with it (#33) * assigned scrub to a variable instead of just doing nothing with it * update --------- Co-authored-by: Dan Fellin <dan@highwaterlabs.com> * missed on scrub call to args * lets link to the OSS repo doh * fix * Commented out warnings (#34) * Commented out warnings * bumped version * bump form-data * fixing glide deployment to also check remote destination to confirm if deployment already exists or if it really needs updated (#39) * added visibility argument to function add command (#32) * added visibility argument to function add command * bumped version * Added visibility to sync * Updated properties and removed enum typecasting * bumped version * bumped version * force image update * Adding support for listening over websockets for gql subscription event (#42) * bumping axios version * tracking dependencies, also fixing some logging, and adding the updateOne and deleteOne queries to tabi tables * Separate out public function internal dependencies from non-public ones * fix dependency parsing for client functions, and making new feature work with glide deployments * Fixing type error in the tabi count result type * fix small potential bug trying to save specs.json when lib hasn't been generated * keeping backwards compatibility for sfx requirements * R27 🚀 (#43) * some cleanup and bringing over hidden files * bringing over the deploy workflow * adding CI/CD workflows * updating to use npm cache instead of yarn * Bringing in Richard's updates! * Some missed cleanup, missing dev dependencies, and fixed build. * hard pinned package versions (#2) * adding husky pre-commit hook for linting * # Feature (4156): P3) Bug with deploying a client function after it a… (#1) * # Feature (4156): P3) Bug with deploying a client function after it as deployed as a server function - Refactoring npm client - Verification added for checking existing function by name and context - color updated * Fixing bug where client was not resolving dependencies correctly * adding missing dependency for testing, and fixing issue where some names in the generated schemas were not being wrapped in quotes * Handling x-poly-refs contained with function arguments that are themselves function types (fixes webhook types and more) * improve logging of failed api function calls (#4) * improve logging of failed api function calls * Update templates/api-index.js.hbs Co-authored-by: Aaron Goin <aarongoin@users.noreply.github.com> * onward --------- Co-authored-by: Aaron Goin <aarongoin@users.noreply.github.com> * P2) (MS) npm client: add direct execute option and MTLS option (#3) * adds direct execute and mtls options support * reversed unintended change * fixed metric names + http agent to be created only once * version increment * lost my logging in code review, lets go agane (#6) * P3) VSCode Extension: Add a Refresh Button to Tree View #4107 (#5) * # Feature (4107): P3) VSCode Extension: Add a Refresh Button to Tree View - load config now can return value - Add or Update config function added * # Feature (4107): P3) VSCode Extension: Add a Refresh Button to Tree View - load config now can return value - Add or Update config function added - Version updated * 4372 update contexts info from terminal (#8) * # Feature (4107): P3) VSCode Extension: Add a Refresh Button to Tree View - load config now can return value - Add or Update config function added - if contexts is empty then it will not save in .config.env * schema generation improvements Supporting $refs defined inline within a schema. Fixing bug where allowing additional attributes on objects by default. Fixing bug where additional attributes generated name was wrapped in extra quotes. Fixing bug where schemas without contexts would fail to be generated. Improving schema generation to remove the extra interfaces which just cause noise for users. Removing yarn.lock since we only use NPM in this repo * Bumping to 0.23.19 to follow Richard's PR * # Feature (2790): P4) Ability to control npx poly generate via an extra view in VS code extension (can repurpose the configuration UI) (#11) - Local config updated - Version updated * try new action * Revert "try new action" This reverts commit 540feeb. * Bug fixes and improvements - Catching axios errors and scrubbing them of polyapi tokens and secrets - Fixing schema generation to remove extra, empty interfaces - Adding support for schemas with refs to inline definitions - Fixing bug where schemas with no contexts would not be generated - Fixing bug where schema public namespace was not Pascal cased * fixing generated webhooks and server functions * try a KISS version of auto deploy prebuilt (#12) * P1) Update typescript client to remove warnings (#7) * ts-json-schema-generator used instead of outdated package + eslint upgrade * eslint hardcode * eslintignore removed * eslint.config.js renamed to eslint.config.mjs to prevent errors * lock file updated * fix complex types * fix server function runtime * downgrade package to fix the wrong export of subpackage issue (#14) * Improving safety of scrubKeys utility * lets test the auto-update prebuilt functionality * Changed command structure to fix windows glide bug (#15) * Changed command structure to fix windows glide bug * Added comment to explain strange syntax * Allowed directories to be specified in the command * Updated excludeCommand quotations and comment * Updated version * Added package-lock.json * Dirty deployables are now added to git after being updated (#16) * Dirty deployables are now added to git after being updated * changed slice to replace * Changed log to warn * Re-fixed glide commit bug (#18) * Adding support for tabi tables, and fixing small bug when generating empty object type (#13) * Adding support for tabi tables, and fixing small bug when generating empty object type * Fix update query * Fix type on update query * sime minor tweaks to tabi query types * lint and fixing deleteOne response * adding count query and fixing tests * 4324 p2 add new field cachepolylibrary false to customfunction table if its set to true do the behavior now behind faascachingenabled (#19) * adds support for cachePolyLibrary for server functions in glide and cache-poly-library flag * increment version * P3) TS Client: Log PolyAPI Library version on function startup (#20) * welcome message for users with package version * show welcome message on first use * Updating server function configs to support more properties, allowing for setting description via the config, and fixing bug where tabi tables could not be lowercase * 4504 p3 glide bug npx poly prepare does not find any deployables in windows (#21) * Changed command structure to fix windows glide bug * Added comment to explain strange syntax * Allowed directories to be specified in the command * Updated excludeCommand quotations and comment * Updated version * Added package-lock.json * Fixed config name TypeError * Revert "Fixed config name TypeError" This reverts commit 7b32086. * Fixed windows find deployables command to ignore files without polyConfig * Making sure api function call errors aren't logged unless LOGS_ENABLED environment flag is truthy * Remove the welcome message for now * Windows glide duplicate deployables fix (#22) * Changed windows command for finding deployables to ensure that the same file is not found multiple times * Added replace to remove file paths in glide prepare * version * version * Removing the updateOne and deleteOne queries from Tabi for now since they don't really work! * Warn on schema fallback (#25) * Added warning when falling back to unknown type * Bumped version * Moved warning to schemaTypes to ensure that warnings are not duplicated * Added falling back message * added scrubbing to api function requestArgs (#27) * added scrubbing to api function requestArgs * Changed iteration to go through keys, added scrubbing to scrubKeys, changed * to 8 * closed some holes and fixed some edge cases * cleaning the scrubbing * bumped version * changed Record to Partial<Record> * Changed import path (#29) * Fix scrub import again (#30) * reversed imports * bumped version * added scrub to exports * Changed warning message (#31) * Changed warning message * reworded message * removed the afro * assigned scrub to a variable instead of just doing nothing with it (#33) * assigned scrub to a variable instead of just doing nothing with it * update --------- Co-authored-by: Dan Fellin <dan@highwaterlabs.com> * missed on scrub call to args * lets link to the OSS repo doh * fix * Commented out warnings (#34) * Commented out warnings * bumped version * bump form-data * fixing glide deployment to also check remote destination to confirm if deployment already exists or if it really needs updated (#39) * added visibility argument to function add command (#32) * added visibility argument to function add command * bumped version * Added visibility to sync * Updated properties and removed enum typecasting * bumped version * bumped version * force image update * Adding support for listening over websockets for gql subscription event (#42) * bumping axios version * tracking dependencies, also fixing some logging, and adding the updateOne and deleteOne queries to tabi tables * Separate out public function internal dependencies from non-public ones * fix dependency parsing for client functions, and making new feature work with glide deployments * Fixing type error in the tabi count result type * fix small potential bug trying to save specs.json when lib hasn't been generated * keeping backwards compatibility for sfx requirements --------- Co-authored-by: Aaron Goin <aarongoin@users.noreply.github.com> Co-authored-by: Richard <github.agonize754@passmail.net> Co-authored-by: SudiptaTJ <sudipta.kumar@techjays.com> Co-authored-by: Dan Fellin <dan@polyapi.io> Co-authored-by: Dan Fellin <dan@highwaterlabs.com> Co-authored-by: Daniel-Estoll <115661842+Daniel-Estoll@users.noreply.github.com> * Fixed transpiler to handle case where package.json file does not exist. * Turning on strict null checks to prevent bugs like the one I'm fixing with function requirements! * Revert "Turning on strict null checks to prevent bugs like the one I'm fixing with function requirements!" This reverts commit 6c0e2f5. * Slimmed down changes for hotfixing * Generating SDK into temp directory and then swapping it in more atomically for the lib directory * Bump version to deploy sdk generate fix! * More robust internal dependency parsing * comments --------- Co-authored-by: Aaron Goin <aarongoin@users.noreply.github.com> Co-authored-by: Richard <github.agonize754@passmail.net> Co-authored-by: SudiptaTJ <sudipta.kumar@techjays.com> Co-authored-by: Dan Fellin <dan@polyapi.io> Co-authored-by: Dan Fellin <dan@highwaterlabs.com> Co-authored-by: Daniel-Estoll <115661842+Daniel-Estoll@users.noreply.github.com>
1 parent b0b18a7 commit 85922ec

23 files changed

+565
-289
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,5 @@ const unregister = poly.myWebhookContext.paymentReceieved(event => {
7575
unregister();
7676
```
7777

78-
Happy hacking!
78+
Happy hacking!
79+
.

package-lock.json

Lines changed: 10 additions & 10 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "polyapi",
3-
"version": "0.24.20",
3+
"version": "0.25.7",
44
"description": "Poly is a CLI tool to help create and manage your Poly definitions.",
55
"license": "MIT",
66
"repository": {
@@ -51,7 +51,7 @@
5151
"@typescript-eslint/eslint-plugin": "8.32.1",
5252
"@typescript-eslint/parser": "8.32.1",
5353
"adm-zip": "0.5.16",
54-
"axios": "1.8.3",
54+
"axios": "1.12.0",
5555
"chalk": "4.1.2",
5656
"comment-json": "4.2.3",
5757
"dotenv": "16.0.3",

src/api.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,8 @@ export const createOrUpdateServerFunction = async (
9898
code: string,
9999
visibility: string,
100100
typeSchemas: Record<string, any>,
101-
requirements: string[],
101+
externalDependencies: Record<string, string> | undefined,
102+
internalDependencies: Record<string, Array<{ path: string; id: string }>> | undefined,
102103
other?: Record<string, any>,
103104
executionApiKey?: string,
104105
) => {
@@ -112,7 +113,10 @@ export const createOrUpdateServerFunction = async (
112113
code,
113114
visibility,
114115
typeSchemas,
115-
requirements,
116+
// Keeping backwards compatability on requirements
117+
requirements: externalDependencies ? Object.keys(externalDependencies) : null,
118+
externalDependencies,
119+
internalDependencies,
116120
executionApiKey,
117121
...other,
118122
},
@@ -177,6 +181,8 @@ export const createOrUpdateClientFunction = async (
177181
code: string,
178182
visibility: string,
179183
typeSchemas: Record<string, any>,
184+
externalDependencies: Record<string, string> | undefined,
185+
internalDependencies: Record<string, Array<{ path: string; id: string }>> | undefined,
180186
other?: Record<string, any>,
181187
) => {
182188
return (
@@ -189,6 +195,8 @@ export const createOrUpdateClientFunction = async (
189195
code,
190196
visibility,
191197
typeSchemas,
198+
externalDependencies,
199+
internalDependencies,
192200
...other,
193201
},
194202
{

src/cli.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,11 @@ void yargs
7171
demandOption: false,
7272
type: 'string',
7373
},
74-
functionIds: {
75-
describe: 'Function IDs to generate',
74+
ids: {
75+
describe: 'Resource IDs to generate',
7676
demandOption: false,
7777
type: 'string',
78+
alias: 'functionIds',
7879
},
7980
customPath: {
8081
describe: 'Custom path to .poly directory (internal use only)',
@@ -93,7 +94,7 @@ void yargs
9394
exitWhenNoConfig,
9495
contexts,
9596
names,
96-
functionIds,
97+
ids,
9798
customPath = DEFAULT_POLY_PATH,
9899
noTypes = false,
99100
}) => {
@@ -113,7 +114,7 @@ void yargs
113114
polyPath: customPath,
114115
contexts: contexts?.split(','),
115116
names: names?.split(','),
116-
functionIds: functionIds?.split(','),
117+
ids: ids?.split(','),
117118
noTypes,
118119
});
119120
},

src/commands/function.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,15 @@ export const addOrUpdateCustomFunction = async (
7979
}
8080

8181
const typeSchemas = generateTypeSchemas(file, DeployableTypeEntries.map(d => d[0]), name);
82+
const [externalDependencies, internalDependencies] = await getDependencies(code, file, tsConfigBaseUrl);
8283

8384
if (server) {
8485
shell.echo(
8586
'-n',
8687
`${updating ? 'Updating' : 'Adding'} custom server side function...`,
8788
);
8889

89-
const dependencies = getDependencies(code, file, tsConfigBaseUrl);
90-
if (dependencies.length) {
90+
if (externalDependencies) {
9191
shell.echo(
9292
chalk.yellow(
9393
'Please note that deploying your functions will take a few minutes because it makes use of libraries other than polyapi.',
@@ -106,7 +106,8 @@ export const addOrUpdateCustomFunction = async (
106106
code,
107107
visibility,
108108
typeSchemas,
109-
dependencies,
109+
externalDependencies,
110+
internalDependencies,
110111
other,
111112
executionApiKey,
112113
);
@@ -142,14 +143,16 @@ export const addOrUpdateCustomFunction = async (
142143
code,
143144
visibility,
144145
typeSchemas,
146+
externalDependencies,
147+
internalDependencies,
145148
);
146149
shell.echo(chalk.green('DONE'));
147150
shell.echo(`Client Function ID: ${customFunction.id}`);
148151
}
149152

150153
await generateSingleCustomFunction(polyPath, customFunction.id, updating);
151154
} catch (e) {
152-
shell.echo(chalk.red('ERROR\n'));
153-
shell.echo(`${e.response?.data?.message || e.message}`);
155+
shell.echo(chalk.redBright('ERROR\n'));
156+
shell.echo(chalk.red((e instanceof Error ? e.message : e.response?.data?.message) || 'Unexpected error.'));
154157
}
155158
};

src/commands/generate/index.ts

Lines changed: 51 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
ApiFunctionSpecification,
99
AuthFunctionSpecification,
1010
CustomFunctionSpecification,
11+
GraphQLSubscriptionSpecification,
1112
ServerFunctionSpecification,
1213
ServerVariableSpecification,
1314
Specification,
@@ -17,10 +18,9 @@ import {
1718
import { getSpecs } from '../../api';
1819
import { loadConfig, addOrUpdateConfig } from '../../config';
1920
import {
20-
generateContextDataFile,
21-
getContextDataFileContent,
21+
writeCachedSpecs,
22+
getCachedSpecs,
2223
getPolyLibPath,
23-
getSpecsFromContextData,
2424
showErrGettingSpecs,
2525
getStringPaths,
2626
loadTemplate,
@@ -53,15 +53,17 @@ const getApiBaseUrl = () =>
5353

5454
const getApiKey = () => process.env.POLY_API_KEY;
5555

56-
const prepareDir = async (polyPath: string) => {
57-
const libPath = getPolyLibPath(polyPath);
56+
const prepareDir = async (polyPath: string, temp = false) => {
57+
let libPath = getPolyLibPath(polyPath);
58+
if (temp) libPath = libPath.replace('/lib', '/temp');
5859

5960
fs.rmSync(libPath, { recursive: true, force: true });
6061
fs.mkdirSync(libPath, { recursive: true });
6162
fs.mkdirSync(`${libPath}/api`);
6263
fs.mkdirSync(`${libPath}/client`);
6364
fs.mkdirSync(`${libPath}/auth`);
6465
fs.mkdirSync(`${libPath}/webhooks`);
66+
fs.mkdirSync(`${libPath}/subscriptions`);
6567
fs.mkdirSync(`${libPath}/server`);
6668
fs.mkdirSync(`${libPath}/vari`);
6769
fs.mkdirSync(`${libPath}/tabi`);
@@ -144,6 +146,9 @@ const generateJSFiles = async (
144146
const tables = specs.filter(
145147
(spec) => spec.type === 'table',
146148
) as TableSpecification[];
149+
const gqlSubscriptions = specs.filter(
150+
(spec) => spec.type === 'graphqlSubscription',
151+
) as GraphQLSubscriptionSpecification[];
147152

148153
await generateIndexJSFile(libPath);
149154
await generatePolyCustomJSFile(libPath);
@@ -158,6 +163,7 @@ const generateJSFiles = async (
158163
'custom functions',
159164
);
160165
await tryAsync(generateWebhooksJSFiles(libPath, webhookHandles), 'webhooks');
166+
await tryAsync(generateGraphQLSubscriptionJSFiles(libPath, gqlSubscriptions), 'GraphQL subscriptions');
161167
await tryAsync(
162168
generateAuthFunctionJSFiles(libPath, authFunctions),
163169
'auth functions',
@@ -284,6 +290,21 @@ const generateWebhooksJSFiles = async (
284290
fs.copyFileSync(templateUrl('webhooks-index.js'), `${libPath}/webhooks/index.js`);
285291
};
286292

293+
const generateGraphQLSubscriptionJSFiles = async (
294+
libPath: string,
295+
specifications: GraphQLSubscriptionSpecification[],
296+
) => {
297+
const template = handlebars.compile(loadTemplate('graphql-subscriptions.js.hbs'));
298+
fs.writeFileSync(
299+
`${libPath}/subscriptions/subscriptions.js`,
300+
template({
301+
specifications,
302+
apiKey: getApiKey(),
303+
}),
304+
);
305+
fs.copyFileSync(templateUrl('graphql-subscriptions-index.js'), `${libPath}/subscriptions/index.js`);
306+
}
307+
287308
const generateServerFunctionJSFiles = async (
288309
libPath: string,
289310
specifications: ServerFunctionSpecification[],
@@ -441,11 +462,11 @@ const generateSingleCustomFunction = async (
441462
updated ? 'Regenerating TypeScript SDK...' : 'Generating TypeScript SDK...',
442463
);
443464

444-
const libPath = getPolyLibPath(polyPath);
445-
let contextData: Record<string, any> = {};
465+
let libPath = getPolyLibPath(polyPath);
466+
let prevSpecs: Specification[] = [];
446467

447468
try {
448-
contextData = getContextDataFileContent(libPath);
469+
prevSpecs = getCachedSpecs(libPath);
449470
} catch (error) {
450471
shell.echo(chalk.red('ERROR'));
451472
shell.echo('Error while fetching local context data.');
@@ -454,8 +475,6 @@ const generateSingleCustomFunction = async (
454475
return;
455476
}
456477

457-
const prevSpecs = getSpecsFromContextData(contextData);
458-
459478
let specs: Specification[] = [];
460479

461480
try {
@@ -479,11 +498,18 @@ const generateSingleCustomFunction = async (
479498
specs = prevSpecs;
480499
}
481500

482-
await prepareDir(polyPath);
501+
await prepareDir(polyPath, true);
502+
libPath = getPolyLibPath(polyPath);
503+
const tempPath = libPath.replace('/lib', '/temp');
504+
505+
writeCachedSpecs(tempPath, specs);
483506

484507
setGenerationErrors(false);
485508

486-
await generateSpecs(libPath, specs, noTypes);
509+
await generateSpecs(tempPath, specs, noTypes);
510+
// Now remove old lib and rename temp directory to force a switchover in typescript
511+
fs.rmSync(libPath, { recursive: true, force: true });
512+
fs.renameSync(tempPath, libPath);
487513

488514
if (getGenerationErrors()) {
489515
shell.echo(
@@ -532,13 +558,13 @@ const generate = async ({
532558
polyPath,
533559
contexts,
534560
names,
535-
functionIds,
561+
ids,
536562
noTypes,
537563
}: {
538564
polyPath: string;
539565
contexts?: string[];
540566
names?: string[];
541-
functionIds?: string[];
567+
ids?: string[];
542568
noTypes: boolean;
543569
}) => {
544570
let specs: Specification[] = [];
@@ -548,20 +574,26 @@ const generate = async ({
548574
: 'Generating Poly TypeScript SDK...';
549575
shell.echo('-n', generateMsg);
550576

551-
await prepareDir(polyPath);
577+
await prepareDir(polyPath, true);
552578
loadConfig(polyPath);
553579

554-
try {
555-
specs = await getSpecs(contexts, names, functionIds, noTypes);
580+
const libPath = getPolyLibPath(polyPath);
581+
const tempPath = libPath.replace('/lib', '/temp');
556582

557-
updateLocalConfig(polyPath, contexts, names, functionIds, noTypes);
583+
try {
584+
specs = await getSpecs(contexts, names, ids, noTypes);
585+
writeCachedSpecs(tempPath, specs);
586+
updateLocalConfig(polyPath, contexts, names, ids, noTypes);
558587
} catch (error) {
559588
showErrGettingSpecs(error);
560589
return;
561590
}
562591

563592
setGenerationErrors(false);
564-
await generateSpecs(getPolyLibPath(polyPath), specs, noTypes);
593+
await generateSpecs(tempPath, specs, noTypes);
594+
// Now remove old lib and rename temp directory to force a switchover in typescript
595+
fs.rmSync(libPath, { recursive: true, force: true });
596+
fs.renameSync(tempPath, libPath);
565597

566598
if (getGenerationErrors()) {
567599
shell.echo(
@@ -638,8 +670,6 @@ export const generateSpecs = async (
638670
);
639671
}
640672

641-
generateContextDataFile(libPath, filteredSpecs);
642-
643673
if (missingNames.length) {
644674
setGenerationErrors(true);
645675
missingNames.map((s) => echoGenerationError(s));

src/commands/generate/schemaTypes.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,7 @@ const printSchemaTreeAsTypes = (
558558
depth + 1,
559559
);
560560
} catch (err) {
561-
console.error(err);
561+
shell.echo(chalk.red(err));
562562
echoGenerationError(child as SchemaSpec);
563563
setGenerationErrors(true);
564564
}

0 commit comments

Comments
 (0)