Repository navigation
npx smart_sig #261
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
npx smart_sig #261
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -76,5 +76,8 @@ | |
| "files": [ | ||
| "dist", | ||
| "src" | ||
| ] | ||
| ], | ||
| "bin": { | ||
| "transloadit": "./dist/cli.js" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| import path from 'node:path' | ||
| import process from 'node:process' | ||
| import { fileURLToPath } from 'node:url' | ||
| import { Transloadit } from './Transloadit.ts' | ||
| import type { OptionalAuthParams } from './apiTypes.ts' | ||
|
|
||
| export async function readStdin(): Promise<string> { | ||
| if (process.stdin.isTTY) return '' | ||
|
|
||
| process.stdin.setEncoding('utf8') | ||
| let data = '' | ||
|
|
||
| for await (const chunk of process.stdin) { | ||
| data += chunk | ||
| } | ||
|
|
||
| return data | ||
| } | ||
|
|
||
| function fail(message: string): void { | ||
| console.error(message) | ||
| process.exitCode = 1 | ||
| } | ||
|
|
||
| export async function runSmartSig(providedInput?: string): Promise<void> { | ||
| const authKey = process.env.TRANSLOADIT_KEY || process.env.TRANSLOADIT_AUTH_KEY | ||
| const authSecret = process.env.TRANSLOADIT_SECRET || process.env.TRANSLOADIT_AUTH_SECRET | ||
|
|
||
| if (!authKey || !authSecret) { | ||
| fail( | ||
| 'Missing credentials. Please set TRANSLOADIT_KEY and TRANSLOADIT_SECRET environment variables.', | ||
| ) | ||
| return | ||
| } | ||
|
|
||
| const rawInput = providedInput ?? (await readStdin()) | ||
| const input = rawInput.trim() | ||
| let params: OptionalAuthParams = {} | ||
|
|
||
| if (input !== '') { | ||
| try { | ||
| const parsed = JSON.parse(input) | ||
| if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) { | ||
| fail('Invalid params provided via stdin. Expected a JSON object.') | ||
| return | ||
| } | ||
|
|
||
| params = parsed as OptionalAuthParams | ||
| } catch (error: unknown) { | ||
| fail(`Failed to parse JSON from stdin: ${(error as Error).message}`) | ||
| return | ||
| } | ||
| } | ||
|
|
||
| const client = new Transloadit({ authKey, authSecret }) | ||
| const signature = client.calcSignature(params) | ||
| process.stdout.write(`${JSON.stringify(signature)}\n`) | ||
| } | ||
|
|
||
| export async function main(args = process.argv.slice(2)): Promise<void> { | ||
| const [command] = args | ||
|
|
||
| switch (command) { | ||
| case 'smart_sig': { | ||
| await runSmartSig() | ||
| break | ||
| } | ||
|
|
||
| case '-h': | ||
| case '--help': | ||
| case undefined: { | ||
| process.stdout.write( | ||
| [ | ||
| 'Usage:', | ||
| ' npx transloadit smart_sig Read params JSON from stdin and output signed payload.', | ||
| '', | ||
| 'Environment variables:', | ||
| ' TRANSLOADIT_KEY, TRANSLOADIT_SECRET', | ||
| ].join('\n'), | ||
| ) | ||
| if (command === undefined) process.exitCode = 1 | ||
| break | ||
| } | ||
|
|
||
| default: { | ||
| fail(`Unknown command: ${command}`) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| const currentFile = path.resolve(fileURLToPath(import.meta.url)) | ||
| const invokedFile = typeof process.argv[1] === 'string' ? path.resolve(process.argv[1]) : '' | ||
|
|
||
| if (currentFile === invokedFile) { | ||
| void main().catch((error) => { | ||
| fail((error as Error).message) | ||
|
kvz marked this conversation as resolved.
Outdated
|
||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| import { afterEach, describe, expect, it, vi } from 'vitest' | ||
| import { main, runSmartSig } from '../../src/cli.ts' | ||
| import { Transloadit } from '../../src/Transloadit.ts' | ||
|
|
||
| const mockedExpiresDate = '2025-01-01T00:00:00.000Z' | ||
| const mockExpires = () => | ||
| vi | ||
| .spyOn(Transloadit.prototype as unknown as { _getExpiresDate: () => string }, '_getExpiresDate') | ||
| .mockReturnValue(mockedExpiresDate) | ||
|
|
||
| const resetExitCode = () => { | ||
| process.exitCode = undefined | ||
| } | ||
|
|
||
| afterEach(() => { | ||
| vi.restoreAllMocks() | ||
| vi.unstubAllEnvs() | ||
| resetExitCode() | ||
| }) | ||
|
|
||
| describe('cli smart_sig', () => { | ||
| it('prints signature JSON built from stdin params', async () => { | ||
| mockExpires() | ||
| vi.stubEnv('TRANSLOADIT_KEY', 'key') | ||
| vi.stubEnv('TRANSLOADIT_SECRET', 'secret') | ||
|
|
||
| const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) | ||
| const stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
|
|
||
| const params = { template_id: '123' } | ||
| await runSmartSig(JSON.stringify(params)) | ||
|
|
||
| expect(stderrSpy).not.toHaveBeenCalled() | ||
| expect(stdoutSpy).toHaveBeenCalledTimes(1) | ||
| const output = stdoutSpy.mock.calls[0]?.[0] | ||
| const parsed = JSON.parse(`${output}`.trim()) | ||
|
|
||
| const client = new Transloadit({ authKey: 'key', authSecret: 'secret' }) | ||
| const expected = client.calcSignature({ template_id: '123' }) | ||
| expect(parsed).toEqual(expected) | ||
| expect(process.exitCode).toBeUndefined() | ||
|
|
||
| }) | ||
|
|
||
| it('fails when credentials are missing', async () => { | ||
| const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) | ||
| const stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
|
|
||
| await runSmartSig('{}') | ||
|
|
||
| expect(stdoutSpy).not.toHaveBeenCalled() | ||
| expect(stderrSpy).toHaveBeenCalledWith( | ||
| 'Missing credentials. Please set TRANSLOADIT_KEY and TRANSLOADIT_SECRET environment variables.', | ||
| ) | ||
| expect(process.exitCode).toBe(1) | ||
|
|
||
| }) | ||
|
|
||
| it('fails when stdin is not valid JSON', async () => { | ||
| mockExpires() | ||
| vi.stubEnv('TRANSLOADIT_KEY', 'key') | ||
| vi.stubEnv('TRANSLOADIT_SECRET', 'secret') | ||
|
|
||
| const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) | ||
| const stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
|
|
||
| await runSmartSig('this is not json') | ||
|
|
||
| expect(stdoutSpy).not.toHaveBeenCalled() | ||
| expect(stderrSpy).toHaveBeenCalled() | ||
| expect(stderrSpy.mock.calls[0]?.[0]).toContain('Failed to parse JSON from stdin') | ||
| expect(process.exitCode).toBe(1) | ||
|
|
||
| }) | ||
|
|
||
| it('fails when params are not an object', async () => { | ||
| mockExpires() | ||
| vi.stubEnv('TRANSLOADIT_KEY', 'key') | ||
| vi.stubEnv('TRANSLOADIT_SECRET', 'secret') | ||
|
|
||
| const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) | ||
| const stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
|
|
||
| await runSmartSig('[]') | ||
|
|
||
| expect(stdoutSpy).not.toHaveBeenCalled() | ||
| expect(stderrSpy).toHaveBeenCalledWith('Invalid params provided via stdin. Expected a JSON object.') | ||
| expect(process.exitCode).toBe(1) | ||
|
|
||
| }) | ||
|
|
||
| it('prints usage when no command is provided', async () => { | ||
| const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) | ||
| const stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
|
|
||
| await main([]) | ||
|
|
||
| expect(stderrSpy).not.toHaveBeenCalled() | ||
| expect(stdoutSpy).toHaveBeenCalled() | ||
| const message = `${stdoutSpy.mock.calls[0]?.[0]}` | ||
| expect(message).toContain('Usage:') | ||
| expect(message).toContain('npx transloadit smart_sig') | ||
| expect(process.exitCode).toBe(1) | ||
|
|
||
| }) | ||
| }) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.