Skip to content

Commit

Permalink
Merge pull request #14 from rudderlabs/fix/js-types-build
Browse files Browse the repository at this point in the history
fix: add typescript types for build
  • Loading branch information
akashrpo authored Feb 23, 2024
2 parents 716a87e + d16f574 commit 7fba60f
Show file tree
Hide file tree
Showing 10 changed files with 48 additions and 31 deletions.
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"bin": "./dist/src/cli/index.js",
"scripts": {
"dev": "TS_NODE_FILES=true NODE_ENV=development ts-node ./src/cli",
"build": "rm -rf dist && yarn rudder-typer prod && tsc && copyfiles --up 1 \"src/**/*.hbs\" dist/src/",
"build": "rm -rf dist && tsc && copyfiles --up 1 \"src/**/*.hbs\" dist/src/",
"test": "jest --testPathIgnorePatterns 'tests/e2e/.*' 'example' --coverage",
"e2e": "make e2e",
"update": "make update",
Expand All @@ -36,6 +36,7 @@
"@types/prettier": "^1.16.3",
"@types/prompts": "2.0.0",
"@types/react": "^17.0.11",
"@types/semver": "^7.5.7",
"@typescript-eslint/eslint-plugin": "^4.9.0",
"@typescript-eslint/parser": "^4.9.0",
"copyfiles": "^2.1.0",
Expand Down Expand Up @@ -73,7 +74,7 @@
"object-assign": "^4.1.1",
"prettier": "^1.17.0",
"react": "^16.9.0",
"semver": "^6.3.0",
"semver": "^6.3.1",
"sort-keys": "^3.0.0",
"typescript": "^4.1.2",
"yargs": "^16.1.1"
Expand Down Expand Up @@ -110,7 +111,7 @@
"useTabs": true,
"semi": false,
"singleQuote": true,
"trailingComma": "es5",
"trailingComma": "es6",
"printWidth": 100
}
],
Expand Down
13 changes: 7 additions & 6 deletions src/cli/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { version } from '../../../package.json'
import { wrapError, isWrappedError } from '../commands/error'
import { sanitizeTrackingPlan } from './trackingplans'
import { set } from 'lodash'
import { APIError } from '../types'

export namespace RudderAPI {
export type GetTrackingPlanResponse = TrackingPlan
Expand Down Expand Up @@ -150,25 +151,25 @@ async function apiGet<Response>(url: string, token: string, email: string): Prom
const { body } = await resp
return body
} catch (error) {
const err = error as APIError
// Don't include the user's authorization token. Overwrite the header value from this error.
const tokenHeader = `Bearer ${token.trim().substring(0, 10)}... (token redacted)`
error = set(error, 'gotOptions.headers.authorization', tokenHeader)
error = set(err, 'gotOptions.headers.authorization', tokenHeader)

if (error.statusCode === 401 || error.statusCode === 403) {
if (err.statusCode === 401 || err.statusCode === 403) {
throw wrapError(
'Permission denied by Rudder API',
error,
err,
`Failed while querying the ${url} endpoint`,
"Verify you are using the right API token by running 'npx rudder-typer tokens'"
)
} else if (error.code === 'ETIMEDOUT') {
} else if (err.code === 'ETIMEDOUT') {
throw wrapError(
'Rudder API request timed out',
error,
err,
`Failed while querying the ${url} endpoint`
)
}

throw error
}
}
2 changes: 1 addition & 1 deletion src/cli/api/trackingplans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export async function writeTrackingPlan(
await verifyDirectoryExists(path, 'file')

// Perform some pre-processing on the Tracking Plan before writing it.
const planJSON = flow<RudderAPI.TrackingPlan, RudderAPI.TrackingPlan, string>(
const planJSON = flow<RudderAPI.TrackingPlan [], RudderAPI.TrackingPlan, string>(
// Enforce a deterministic ordering to reduce verson control deltas.
plan => sanitizeTrackingPlan(plan),
plan => stringify(plan, { space: '\t' })
Expand Down
13 changes: 8 additions & 5 deletions src/cli/commands/build.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import figures from 'figures'
import { Init } from './init'
import { getEmail } from '../config/config'
import { toTrackingPlanId } from '../api/trackingplans'
import { APIError } from '../types'

const readFile = promisify(fs.readFile)
const readdir = promisify(fs.readdir)
Expand Down Expand Up @@ -171,7 +172,7 @@ export const UpdatePlanStep: React.FC<UpdatePlanStepProps> = ({
email,
})
} catch (error) {
handleError(error)
handleError(error as WrappedError)
if (isWrappedError(error)) {
setAPIError(error.description)
} else {
Expand Down Expand Up @@ -284,11 +285,12 @@ export const ClearFilesStep: React.FC<ClearFilesProps> = ({ config, configPath,
try {
await clearFolder(path)
} catch (error) {
const err = error as Error;
return wrapError(
'Failed to clear generated files',
error,
err,
`Failed on: '${trackingPlanConfig.path}'`,
error.message
err.message
)
}
})
Expand Down Expand Up @@ -317,10 +319,11 @@ export const ClearFilesStep: React.FC<ClearFilesProps> = ({ config, configPath,
await unlink(fullPath)
}
} catch (error) {
const err = error as APIError;
// Note: none of our generators produce folders, but if we ever do, then we'll need to
// update this logic to handle recursively traversing directores. For now, we just ignore
// any directories.
if (error.code !== 'EISDIR') {
if (err.code !== 'EISDIR') {
throw error
}
}
Expand Down Expand Up @@ -450,7 +453,7 @@ function useStep<Arg>(
onDone(result)
}
} catch (error) {
handleFatalError(toUnexpectedError(error))
handleFatalError(toUnexpectedError(error as Error))
}
}

Expand Down
22 changes: 13 additions & 9 deletions src/cli/commands/init.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ import { orderBy } from 'lodash'
import { Build } from './build'
import Fuse from 'fuse.js'
import { StandardProps, DebugContext } from '../index'
import { ErrorContext, wrapError } from './error'
import { ErrorContext, WrappedError, wrapError } from './error'
import { APIError } from '../types'

const readir = promisify(fs.readdir)

Expand Down Expand Up @@ -430,7 +431,7 @@ const APITokenPrompt: React.FC<APITokenPromptProps> = ({ step, config, configPat
canBeSet: method !== tokens.script.method,
})
} catch (error) {
handleFatalError(error)
handleFatalError(error as WrappedError)
}
}

Expand All @@ -450,11 +451,12 @@ const APITokenPrompt: React.FC<APITokenPromptProps> = ({ step, config, configPat
try {
await storeToken(state.token, state.email)
} catch (error) {
const err = error as APIError
handleFatalError(
wrapError(
'Unable to save token to ~/.ruddertyper',
error,
`Failed due to an ${error.code} error (${error.errno}).`
err,
`Failed due to an ${err.code} error (${err.errno}).`
)
)
return
Expand Down Expand Up @@ -618,19 +620,20 @@ const TrackingPlanPrompt: React.FC<TrackingPlanPromptProps> = ({
setTrackingPlans(await fetchTrackingPlans({ token, email }))
setIsLoading(false)
} catch (error) {
if (error.statusCode === 403) {
const err = error as APIError
if (err.statusCode === 403) {
return handleFatalError(
wrapError(
'Failed to authenticate with the RudderStack API',
error,
err,
'You may be using a malformed/invalid token or a legacy personal access token'
)
)
} else {
return handleFatalError(
wrapError(
'Unable to fetch Tracking Plans',
error,
err,
'Check your internet connectivity and try again'
)
)
Expand Down Expand Up @@ -744,11 +747,12 @@ const SummaryPrompt: React.FC<SummaryPromptProps> = ({
setIsLoading(false)
onConfirm(config)
} catch (error) {
const err = error as APIError
handleFatalError(
wrapError(
'Unable to write ruddertyper.yml',
error,
`Failed due to an ${error.code} error (${error.errno}).`
err,
`Failed due to an ${err.code} error (${err.errno}).`
)
)
return
Expand Down
4 changes: 2 additions & 2 deletions src/cli/commands/version.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Box, Color, useApp } from 'ink'
import { version as ruddertyperVersion } from '../../../package.json'
import latest from 'latest-version'
import { StandardProps } from '../index'
import { ErrorContext } from './error'
import { ErrorContext, WrappedError } from './error'
import semver from 'semver'

export const Version: React.FC<StandardProps> = () => {
Expand All @@ -28,7 +28,7 @@ export const Version: React.FC<StandardProps> = () => {
setLatestVersion(latestVersion)
} catch (error) {
// If we can't access NPM, then ignore this version check.
handleError(error)
handleError(error as WrappedError)
}
setIsLoading(false)
exit()
Expand Down
8 changes: 5 additions & 3 deletions src/cli/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Config, validateConfig } from './schema'
import { validateToken, RudderAPI } from '../api'
import { wrapError } from '../commands/error'
import { runScript, Scripts } from './scripts'
import { APIError } from '../types'

const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
Expand Down Expand Up @@ -35,17 +36,18 @@ export async function getConfig(path = './'): Promise<Config | undefined> {
encoding: 'utf-8',
})
} catch (error) {
const err = error as APIError
throw wrapError(
'Unable to open ruddertyper.yml',
error,
`Failed due to an ${error.code} error (${error.errno}).`,
err,
`Failed due to an ${err.code} error (${err.errno}).`,
configPath
)
}

const rawConfig = yaml.safeLoad(file)

return validateConfig(rawConfig)
return validateConfig(rawConfig as Config)
}

// setConfig writes a config out to a ruddertyper.yml file.
Expand Down
4 changes: 2 additions & 2 deletions src/cli/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ function toYargsHandler<P = unknown>(
!cliOptions ||
!cliOptions.validateDefault ||
args._.length === 0 ||
['update', 'u'].includes(args._[0])
['update', 'u'].includes(args._[0] as string)

// Attempt to read a config, if one is available.
const cfg = await getConfig(args.config)
Expand Down Expand Up @@ -199,7 +199,7 @@ function toYargsHandler<P = unknown>(
const { waitUntilExit } = render(
<DebugContext.Provider value={{ debug: args.debug }}>
<ErrorBoundary
error={error}
error={error as Error}
anonymousId={anonymousId}
analyticsProps={await rudderTyperLibraryProperties(args)}
debug={args.debug}
Expand Down
5 changes: 5 additions & 0 deletions src/cli/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface APIError extends Error {
code: string;
statusCode: number;
errno: number;
}
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"resolveJsonModule": true,
"esModuleInterop": true,
"jsx": "react",
"skipLibCheck": true,
"typeRoots": ["./node_modules/@types", "./src/@types"]
},
"include": ["src/**/*"]
Expand Down

0 comments on commit 7fba60f

Please sign in to comment.