Skip to content

Commit

Permalink
bundle sdk with tsup instead of tsc transpilation
Browse files Browse the repository at this point in the history
  • Loading branch information
zvictor committed Jul 2, 2022
1 parent 5a2b45a commit 28d2f99
Show file tree
Hide file tree
Showing 6 changed files with 148 additions and 65 deletions.
34 changes: 26 additions & 8 deletions commands/build-sdk.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,16 +169,34 @@ export { faugra }`

fs.writeFileSync(
tmpTsconfigFile,
`{"extends": "${tsconfigFile}", "include": ["${outputFile}"], "compilerOptions": {"outDir": "${locateCache()}"}}`
`{
"extends": "${tsconfigFile}", "include": ["${outputFile}"], "compilerOptions": {
"preserveSymlinks": true,
"outDir": "${locateCache()}",
${/* https://github.com/microsoft/TypeScript/issues/42873#issuecomment-1131425209 */ ''}
"baseUrl": "${path.join(__dirname, '..')}",
"paths": { "*": ["node_modules/*/"]}
}
}`
)

execaSync(findBin(`tsc`), ['--project', tmpTsconfigFile], {
stdio: ['pipe', process.stdout, process.stderr],
cwd: process.cwd(),
})

fs.renameSync(locateCache(`sdk.js`), locateCache(`sdk.cjs`))
fs.renameSync(locateCache(`sdk.js.map`), locateCache(`sdk.cjs.map`))
const { stdout } = execaSync(
findBin(`tsup`),
[
outputFile,
'--config',
path.join(__dirname, '..', 'tsup.config.ts'),
'--out-dir',
locateCache(),
'--tsconfig',
tmpTsconfigFile,
],
{
stdio: ['ignore', 'pipe', process.stderr],
cwd: process.cwd(),
}
)
debug(stdout)

debug(`The sdk has been transpiled and cached`)
return outputFile
Expand Down
2 changes: 1 addition & 1 deletion commands/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const runCallback = () => {
const cmd = process.env.CALLBACK.split(' ')

execaSync(cmd.shift(), cmd, {
stdio: ['pipe', process.stdout, process.stderr],
stdio: ['ignore', process.stdout, process.stderr],
cwd: process.cwd(),
})

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
},
"main": "./index.cjs",
"types": "./.cache/sdk.d.ts",
"browser": ".cache/sdk.js",
"files": [
"/commands",
"/scripts",
Expand Down Expand Up @@ -62,6 +61,7 @@
"p-queue": "7.2.0",
"resolve-as-bin": "2.1.0",
"tempy": "3.0.0",
"tsup": "6.1.3",
"typescript": "4.7.3"
},
"optionalDependencies": {
Expand Down
86 changes: 43 additions & 43 deletions tests/fixtures/basic.sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,21 @@ export type UserPage = {
before?: Maybe<Scalars['String']>;
};

export type AllUsersQueryVariables = Exact<{
_size?: InputMaybe<Scalars['Int']>;
_cursor?: InputMaybe<Scalars['String']>;
}>;


export type AllUsersQuery = { __typename?: 'Query', allUsers: { __typename?: 'UserPage', after?: string | null, before?: string | null, data: Array<{ __typename?: 'User', _id: string, _ts: any, username: string } | null> } };

export type FindUserByIdQueryVariables = Exact<{
id: Scalars['ID'];
}>;


export type FindUserByIdQuery = { __typename?: 'Query', findUserByID?: { __typename?: 'User', _id: string, _ts: any, username: string } | null };

export type CreateUserMutationVariables = Exact<{
data: UserInput;
}>;
Expand Down Expand Up @@ -135,22 +150,29 @@ export type UpdateUserMutationVariables = Exact<{

export type UpdateUserMutation = { __typename?: 'Mutation', updateUser?: { __typename?: 'User', _id: string, _ts: any, username: string } | null };

export type AllUsersQueryVariables = Exact<{
_size?: InputMaybe<Scalars['Int']>;
_cursor?: InputMaybe<Scalars['String']>;
}>;


export type AllUsersQuery = { __typename?: 'Query', allUsers: { __typename?: 'UserPage', after?: string | null, before?: string | null, data: Array<{ __typename?: 'User', _id: string, _ts: any, username: string } | null> } };

export type FindUserByIdQueryVariables = Exact<{
id: Scalars['ID'];
}>;


export type FindUserByIdQuery = { __typename?: 'Query', findUserByID?: { __typename?: 'User', _id: string, _ts: any, username: string } | null };


export const AllUsersDocument = gql`
query allUsers($_size: Int, $_cursor: String) {
allUsers(_size: $_size, _cursor: $_cursor) {
data {
_id
_ts
username
}
after
before
}
}
`;
export const FindUserByIdDocument = gql`
query findUserByID($id: ID!) {
findUserByID(id: $id) {
_id
_ts
username
}
}
`;
export const CreateUserDocument = gql`
mutation createUser($data: UserInput!) {
createUser(data: $data) {
Expand Down Expand Up @@ -187,28 +209,6 @@ export const UpdateUserDocument = gql`
}
}
`;
export const AllUsersDocument = gql`
query allUsers($_size: Int, $_cursor: String) {
allUsers(_size: $_size, _cursor: $_cursor) {
data {
_id
_ts
username
}
after
before
}
}
`;
export const FindUserByIdDocument = gql`
query findUserByID($id: ID!) {
findUserByID(id: $id) {
_id
_ts
username
}
}
`;

export type SdkFunctionWrapper = <T>(action: (requestHeaders?:Record<string, string>) => Promise<T>, operationName: string, operationType?: string) => Promise<T>;

Expand All @@ -217,6 +217,12 @@ const defaultWrapper: SdkFunctionWrapper = (action, _operationName, _operationTy

export function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {
return {
allUsers(variables?: AllUsersQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<AllUsersQuery> {
return withWrapper((wrappedRequestHeaders) => client.request<AllUsersQuery>(AllUsersDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'allUsers', 'query');
},
findUserByID(variables: FindUserByIdQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<FindUserByIdQuery> {
return withWrapper((wrappedRequestHeaders) => client.request<FindUserByIdQuery>(FindUserByIdDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'findUserByID', 'query');
},
createUser(variables: CreateUserMutationVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<CreateUserMutation> {
return withWrapper((wrappedRequestHeaders) => client.request<CreateUserMutation>(CreateUserDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'createUser', 'mutation');
},
Expand All @@ -228,12 +234,6 @@ export function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper =
},
updateUser(variables: UpdateUserMutationVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<UpdateUserMutation> {
return withWrapper((wrappedRequestHeaders) => client.request<UpdateUserMutation>(UpdateUserDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'updateUser', 'mutation');
},
allUsers(variables?: AllUsersQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<AllUsersQuery> {
return withWrapper((wrappedRequestHeaders) => client.request<AllUsersQuery>(AllUsersDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'allUsers', 'query');
},
findUserByID(variables: FindUserByIdQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<FindUserByIdQuery> {
return withWrapper((wrappedRequestHeaders) => client.request<FindUserByIdQuery>(FindUserByIdDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'findUserByID', 'query');
}
};
}
Expand Down
78 changes: 66 additions & 12 deletions tests/specs/build-sdk.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,15 @@ test('build an sdk for basic schema and non-standard cache', async () => {

expect(listFiles(cache.DEFAULT)).toEqual([].sort())
expect(listFiles(cache.TEST)).toEqual(
['sdk.d.ts', 'sdk.d.ts.map', 'sdk.cjs', 'sdk.cjs.map', 'sdk.ts', 'tsconfig.json'].sort()
[
'sdk.d.ts',
'sdk.mjs',
'sdk.mjs.map',
'sdk.cjs',
'sdk.cjs.map',
'sdk.ts',
'tsconfig.json',
].sort()
)

expect(exitCode).toBe(0)
Expand All @@ -161,6 +169,7 @@ test('build an sdk for basic schema and non-standard cache', async () => {
// When we use a non-standard cache we can't build in strict mode
execaSync(findBin('tsc'), ['index.ts', '--declaration', '--outDir', './build'], {
env: { FAUGRA_CACHE: cache.TEST },
stdio: ['ignore', process.stdout, process.stderr],
cwd,
})
).not.toThrow()
Expand All @@ -179,9 +188,20 @@ test('build an sdk for basic schema and non-standard cache', async () => {
expect(() =>
execaSync(
findBin('tsup'),
['index.ts', '--dts', '--out-dir', './build', '--format', 'esm', '--tsconfig', tsconfig],
[
'index.ts',
'--dts',
'--out-dir',
'./build',
'--format',
'esm',
'--no-config',
'--tsconfig',
tsconfig,
],
{
env: { FAUGRA_CACHE: cache.TEST },
stdio: ['ignore', process.stdout, process.stderr],
cwd,
}
)
Expand All @@ -201,9 +221,20 @@ test('build an sdk for basic schema and non-standard cache', async () => {
expect(() =>
execaSync(
findBin('tsup'),
['index.ts', '--dts', '--out-dir', './build', '--format', 'cjs', '--tsconfig', tsconfig],
[
'index.ts',
'--dts',
'--out-dir',
'./build',
'--format',
'cjs',
'--no-config',
'--tsconfig',
tsconfig,
],
{
env: { FAUGRA_CACHE: cache.TEST },
stdio: ['ignore', process.stdout, process.stderr],
cwd,
}
)
Expand Down Expand Up @@ -233,6 +264,7 @@ test('build an sdk for basic schema and non-standard cache', async () => {
],
{
env: { FAUGRA_CACHE: cache.TEST },
stdio: ['ignore', process.stdout, process.stderr],
cwd,
}
)
Expand All @@ -255,6 +287,7 @@ test('build an sdk for basic schema and non-standard cache', async () => {
['--sourcemap', '--outdir=./build', '--format=cjs', `--tsconfig=${tsconfig}`, 'index.ts'],
{
env: { FAUGRA_CACHE: cache.TEST },
stdio: ['ignore', process.stdout, process.stderr],
cwd,
}
)
Expand Down Expand Up @@ -299,7 +332,15 @@ test(`build an sdk for the 'modularized' example, with standard cache`, async ()

expect(listFiles(cache.TEST)).toEqual([].sort())
expect(listFiles(cache.DEFAULT)).toEqual(
['sdk.d.ts', 'sdk.d.ts.map', 'sdk.cjs', 'sdk.cjs.map', 'sdk.ts', 'tsconfig.json'].sort()
[
'sdk.d.ts',
'sdk.mjs',
'sdk.mjs.map',
'sdk.cjs',
'sdk.cjs.map',
'sdk.ts',
'tsconfig.json',
].sort()
)

expect(exitCode).toBe(0)
Expand All @@ -320,6 +361,7 @@ test(`build an sdk for the 'modularized' example, with standard cache`, async ()
expect(() =>
execaSync(findBin('tsc'), ['--declaration', '--strict'], {
env: {},
stdio: ['ignore', process.stdout, process.stderr],
cwd,
})
).not.toThrow()
Expand All @@ -336,10 +378,15 @@ test(`build an sdk for the 'modularized' example, with standard cache`, async ()
await resetBuild(cwd)

expect(() =>
execaSync(findBin('tsup'), ['index.ts', '--dts', '--out-dir', './build', '--format', 'esm'], {
env: {},
cwd,
})
execaSync(
findBin('tsup'),
['index.ts', '--dts', '--out-dir', './build', '--format', 'esm', '--no-config'],
{
env: {},
stdio: ['ignore', process.stdout, process.stderr],
cwd,
}
)
).not.toThrow()

outputCheck.modularized(
Expand All @@ -354,10 +401,15 @@ test(`build an sdk for the 'modularized' example, with standard cache`, async ()
await resetBuild(cwd)

expect(() =>
execaSync(findBin('tsup'), ['index.ts', '--dts', '--out-dir', './build', '--format', 'cjs'], {
env: {},
cwd,
})
execaSync(
findBin('tsup'),
['index.ts', '--dts', '--out-dir', './build', '--format', 'cjs', '--no-config'],
{
env: {},
stdio: ['ignore', process.stdout, process.stderr],
cwd,
}
)
).not.toThrow()

outputCheck.modularized(
Expand All @@ -377,6 +429,7 @@ test(`build an sdk for the 'modularized' example, with standard cache`, async ()
['--sourcemap', '--outdir=./build', '--format=esm', '--target=es6', 'index.ts'],
{
env: {},
stdio: ['ignore', process.stdout, process.stderr],
cwd,
}
)
Expand Down Expand Up @@ -406,6 +459,7 @@ test(`build an sdk for the 'modularized' example, with standard cache`, async ()
],
{
env: {},
stdio: ['ignore', process.stdout, process.stderr],
cwd,
}
)
Expand Down
11 changes: 11 additions & 0 deletions tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineConfig } from 'tsup'

export default defineConfig({
format: ['esm', 'cjs'],
sourcemap: true,
dts: true,
watch: false,
outExtension: ({ format }) => ({
js: `.${format === 'esm' ? 'mjs' : format}`,
}),
})

0 comments on commit 28d2f99

Please sign in to comment.