Skip to content

Commit

Permalink
Merge pull request #5 from sushruth/sushruth/package-size-optimization
Browse files Browse the repository at this point in the history
v0.2.11 - Optimization + features
  • Loading branch information
sushruth authored Dec 1, 2021
2 parents faadf9a + e784eea commit d05ee7a
Show file tree
Hide file tree
Showing 17 changed files with 162 additions and 113 deletions.
61 changes: 22 additions & 39 deletions .pnp.data.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
Binary file not shown.
Binary file not shown.
7 changes: 3 additions & 4 deletions packages/ado-auth/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ado-auth",
"version": "0.2.9",
"version": "0.2.11",
"displayName": "ADO Authenticator",
"license": "MIT",
"main": "./bin/src/cli.js",
Expand All @@ -20,17 +20,16 @@
"compile": "node ./scripts/build.mjs --minify",
"typegen": "tsc",
"build": "yarn compile && yarn typegen",
"prepublish": "yarn build && yarn typegen"
"prepublish": "yarn build"
},
"repository": {
"type": "git",
"url": "https://github.com/sushruth/ado-auth"
},
"bin": "./bin/src/cli.js",
"dependencies": {
"colorette": "2.0.16",
"dayjs": "1.10.7",
"js-yaml": "4.1.0",
"kleur": "^4.1.4",
"light-spinner": "1.0.4",
"opener": "1.5.2",
"sade": "1.7.4"
Expand Down
2 changes: 1 addition & 1 deletion packages/ado-auth/src/api-stuff/server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { bold, green } from 'colorette'
import http, { Server } from 'http'
import { bold, green } from 'kleur/colors'
import { SERVER_TIMEOUT } from '../lib/constants'
import { CliOptions, Token } from '../lib/types'
import { logger } from '../logger/logger'
Expand Down
8 changes: 4 additions & 4 deletions packages/ado-auth/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env node
import { bold, greenBright } from 'colorette'
import { bold, red } from 'kleur/colors'
import sade from 'sade'
import { version } from '../package.json'
import { CLIENT_ID, DEFAULT_HOST, SERVER_PORT } from './lib/constants'
Expand Down Expand Up @@ -34,20 +34,20 @@ cli.action(async (config: CliOptions) => {
if (!config.clientId) {
config.clientId = CLIENT_ID
} else {
logger.debug('Using client id - ', greenBright(bold(config.clientId)))
logger.debug('Using client id - ', red(bold(config.clientId)))
}

if (config.host !== DEFAULT_HOST) {
logger.debug(
'Using cusotm host for authentication - ',
greenBright(bold(config.host))
red(bold(config.host))
)
}

if (config.port !== SERVER_PORT) {
logger.debug(
'Using custom port for auth callback - ',
greenBright(bold(config.port))
red(bold(`${config.port}`))
)
}

Expand Down
10 changes: 6 additions & 4 deletions packages/ado-auth/src/file-stuff/prepare.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import dayjs from 'dayjs'
import fs from 'fs'
import { PrepareReturn, PrepareTypes } from './prepare.types'
import { TokenStore } from '../lib/types'
import { PrepareReturn, PrepareTypes } from './prepare.types'

export function prepare(rcPath: string): PrepareReturn {
if (fs.existsSync(rcPath)) {
// handle when file exists
const file = fs.readFileSync(rcPath, 'utf-8')
try {
const data: TokenStore = JSON.parse(file)
if (!dayjs(data.expires_on).isAfter(dayjs().subtract(1, 'minute'))) {
// expires in less than 1 minute
const isGoingToExpireInFiveMinutes =
new Date(data.expires_on) < new Date(Date.now() - 5 * 60 * 1000)

if (isGoingToExpireInFiveMinutes) {
// expires in less than 5 minutes
return {
type: PrepareTypes.refetch,
data,
Expand Down
2 changes: 1 addition & 1 deletion packages/ado-auth/src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { yellow, bold } from 'colorette'
import { bold, yellow } from 'kleur/colors'

export const SERVER_TIMEOUT = 60000
export const SERVER_PORT = 35287
Expand Down
8 changes: 4 additions & 4 deletions packages/ado-auth/src/lib/operate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { bold, green, magenta, yellow } from 'colorette'
import { bold, green, magenta } from 'kleur/colors'
import os from 'os'
import path from 'path'
import { auth } from '../api-stuff/auth'
Expand Down Expand Up @@ -37,13 +37,13 @@ export async function operate(config: CliOptions) {
let token: Token | undefined = undefined

if (report.type === PrepareTypes.fetch) {
logger.debug(bold(magenta('Trying to get auth token')))
logger.debug(magenta(bold('Trying to get auth token')))
token = await auth(rcPath, config)
} else if (report.type === PrepareTypes.refetch) {
logger.debug(bold(magenta('Trying to refetch auth token')))
logger.debug(magenta(bold('Trying to refetch auth token')))
token = await refetch(report.data, rcPath, config)
} else if (report.type === PrepareTypes.noop) {
logger.debug('✅ ', bold(green('Valid token exists!')))
logger.debug('✅ ', green(bold('Valid token exists!')))
token = report.data
}

Expand Down
116 changes: 90 additions & 26 deletions packages/ado-auth/src/lib/readConfig.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import { execSync } from 'child_process'
import { blue, bold, red } from 'colorette'
import { execSync, ExecSyncOptionsWithStringEncoding } from 'child_process'
import { blue, red } from 'kleur/colors'
import { logger } from '../logger/logger'
import { npmString, yarnString } from './constants'

const defaultRegex = /^(https?)?:?\/\/registry\.(yarnpkg|npmjs)\.(com|org).*/i
const defaultRegistryRegex =
/^(https?)?:?\/\/registry\.(yarnpkg|npmjs)\.(com|org).*/i

const adoRegistryRegexes = [
/^\/\/pkgs\.dev\.azure\.com/i,
/^\/\/(.*?).pkgs\.visualstudio\.com/i,
]

function isAdoRegistry(registry: string) {
return adoRegistryRegexes.filter((ex) => ex.test(registry)).length > 0
}

const commands = {
npm: 'npm config get registry',
Expand All @@ -13,19 +23,68 @@ const commands = {

type Tool = keyof typeof commands

const execParams: ExecSyncOptionsWithStringEncoding = {
encoding: 'utf8',
cwd: process.cwd(),
}

function replaceHttps(input: string = '') {
return input.replace(/^https?:/, '')
}

function getScopeRegistries(tool: Tool) {
try {
if (tool === 'npm' || tool === 'yarn') {
const config = JSON.parse(execSync(`npm config list --json`, execParams))

const registries: string[] = []

for (const entry in config) {
if (/@(.*?):registry/.test(entry)) {
registries.push(replaceHttps(config[entry]))
}
}

return registries
} else if (tool === 'yarn2') {
const registries: string[] = []

const npmScopes = JSON.parse(
execSync('yarn config get npmScopes --json', execParams)
)

for (const entry of npmScopes) {
registries.push(replaceHttps(entry.npmRegistryServer))
}

return registries
}
} catch (error) {
logger.debug('No scoped registries found')
}
}

const toolNames: Record<Tool, string> = {
npm: npmString,
yarn: yarnString,
yarn2: yarnString,
}

function isValidRegistryEntry(registry: string) {
return (
!/undefined/i.test(registry) &&
isAdoRegistry(registry) &&
!defaultRegistryRegex.test(registry)
)
}

function getRegistry(tool: Exclude<Tool, 'yarn2'>) {
let registry = ''
let registries: string[] = []

let toolToUse: Tool = tool

if (tool === 'yarn') {
const version = execSync('yarn -v', { encoding: 'utf8' })?.trim()
const version = execSync('yarn -v', execParams)?.trim()
const match = version.match(/(\d+)\.*/i)

if (Number(match?.[1]) >= 2) {
Expand All @@ -34,15 +93,18 @@ function getRegistry(tool: Exclude<Tool, 'yarn2'>) {
}

try {
registry = execSync(commands[toolToUse], {
encoding: 'utf8',
cwd: process.cwd(),
})
?.trim()
.replace(/^https?:/, '') // remove https

if (defaultRegex.test(registry) || /undefined/i.test(registry)) {
registry = ''
const registry = execSync(commands[toolToUse], execParams)?.trim()

if (isValidRegistryEntry(registry)) {
registries.push(replaceHttps(registry))
}

logger.debug('Trying to add scoped registries')

for (const entry of getScopeRegistries(toolToUse) || []) {
if (isValidRegistryEntry(entry)) {
registries.push(entry)
}
}
} catch (error) {
logger.debug(
Expand All @@ -51,33 +113,35 @@ function getRegistry(tool: Exclude<Tool, 'yarn2'>) {
)
}

if (!registry) {
logger.debug(`No custom ${toolNames[toolToUse]} registry found.`)
} else {
if (!registries.length) {
logger.debug(
`${toolNames[toolToUse]} config contains this registry -> `,
blue(registry)
`No custom ${toolNames[toolToUse]} Azure DevOps registry found.`
)
} else {
logger.debug(`${toolNames[toolToUse]} config contains these registries -> `)
for (const registry of registries) {
logger.debug(`\t ${blue(registry)}`)
}
}

return registry
return registries
}

export function readConfig() {
let npmRegistry: string | undefined
let npmRegistries: string[] = []

try {
npmRegistry = getRegistry('npm')
npmRegistries.push(...getRegistry('npm'))
} catch (error) {
if (error instanceof Error) {
logger.debug('running npm failed - ', red(error.message))
}
}

let yarnRegistry: string | undefined
let yarnRegistries: string[] = []

try {
yarnRegistry = getRegistry('yarn')
yarnRegistries.push(...getRegistry('yarn'))
} catch (error) {
if (error instanceof Error) {
logger.debug('running yarn failed - ', red(error.message))
Expand All @@ -86,8 +150,8 @@ export function readConfig() {

return new Set(
[
...getRegistryEntries(npmRegistry),
...getRegistryEntries(yarnRegistry),
...npmRegistries.flatMap((reg) => getRegistryEntries(reg)),
...yarnRegistries.flatMap((reg) => getRegistryEntries(reg)),
].filter(Boolean)
)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/ado-auth/src/lib/spinner.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { dim } from 'kleur/colors'
import Spin from 'light-spinner'
import { dim } from 'colorette'
import { IOption } from 'light-spinner/dist/interface'

export type PrefixedSpinnerOptions = IOption & {
Expand Down
Loading

0 comments on commit d05ee7a

Please sign in to comment.