Skip to content

Commit

Permalink
format: format it
Browse files Browse the repository at this point in the history
  • Loading branch information
mildronize committed Jan 18, 2025
1 parent 8568ce5 commit 74ab963
Show file tree
Hide file tree
Showing 28 changed files with 974 additions and 936 deletions.
9 changes: 5 additions & 4 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"printWidth": 110,
"singleQuote": true,
"semi": true,
"useTabs": true
"printWidth": 140,
"singleQuote": true,
"semi": true,
"useTabs": false,
"tabWidth": 2
}
6 changes: 2 additions & 4 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
{
"recommendations": [
"ms-azuretools.vscode-azurefunctions"
]
}
"recommendations": ["ms-azuretools.vscode-azurefunctions"]
}
4 changes: 1 addition & 3 deletions host.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
}
}
},
"watchDirectories": [
"dist"
],
"watchDirectories": ["dist"],
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
Expand Down
17 changes: 17 additions & 0 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"build": "tsc",
"watch": "tsc -w",
"clean": "rimraf dist",
"format": "prettier --write .",
"dev": "run-p watch start tunnel",
"prestart": "npm run clean && npm run build",
"start": "func start",
Expand All @@ -21,6 +22,7 @@
"bun": "^1.1.43",
"pino": "^9.6.0",
"pino-pretty": "^13.0.0",
"prettier": "^3.4.2",
"release-it": "^18.1.1",
"rimraf": "^6.0.1",
"type-fest": "^4.32.0",
Expand Down
12 changes: 6 additions & 6 deletions scripts/_config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { LogLevel } from "./utils/logger";
import { LogLevel } from './utils/logger';

export const config = {
localEnvPath: '.dev.vars',
renew: false,
logLevel: 'info' as LogLevel,
telegramWebhookPath: '/api/telegramBot',
}
localEnvPath: '.dev.vars',
renew: false,
logLevel: 'info' as LogLevel,
telegramWebhookPath: '/api/telegramBot',
};
37 changes: 20 additions & 17 deletions scripts/libs/AzureFunctionsClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,27 @@ import { $ } from 'bun';
import { console } from 'inspector';

export interface AzureFunctionsClientOptions {
functionName: string;
functionAppName: string;
resourceGroup: string;
subscription: string;
functionName: string;
functionAppName: string;
resourceGroup: string;
subscription: string;
}

export class AzureFunctionsClient {
constructor(private readonly options: AzureFunctionsClientOptions) { }
// https://thadaw-my-bot.azurewebsites.net/api/telegramBot?code=
async getFunctionKey(keyName = 'default'): Promise<string | undefined> {
try {
const functionKeys = (await $`az functionapp function keys list --function-name ${this.options.functionName} --name ${this.options.functionAppName} --resource-group ${this.options.resourceGroup} --subscription "${this.options.subscription}"`).stdout.toString().trim();
const key: Record<string, string | null> = JSON.parse(functionKeys);
return key[keyName] ?? undefined;
} catch (error) {
console.error(error);
return undefined;
}
}

constructor(private readonly options: AzureFunctionsClientOptions) {}
// https://thadaw-my-bot.azurewebsites.net/api/telegramBot?code=
async getFunctionKey(keyName = 'default'): Promise<string | undefined> {
try {
const functionKeys = (
await $`az functionapp function keys list --function-name ${this.options.functionName} --name ${this.options.functionAppName} --resource-group ${this.options.resourceGroup} --subscription "${this.options.subscription}"`
).stdout
.toString()
.trim();
const key: Record<string, string | null> = JSON.parse(functionKeys);
return key[keyName] ?? undefined;
} catch (error) {
console.error(error);
return undefined;
}
}
}
111 changes: 53 additions & 58 deletions scripts/libs/SecretManager.ts
Original file line number Diff line number Diff line change
@@ -1,72 +1,67 @@

import fs from 'fs';
import { $ } from 'bun';

export interface SecretManagerOptions {
localEnvPath: string;
renew: boolean;
localEnvPath: string;
renew: boolean;
}

export class SecretManager {
constructor(public options: SecretManagerOptions) {
console.log('SecretManager created');
}

async start(): Promise<string> {
console.log('Starting secret generation');
const secret = this.getSecret();
if (!this.options.renew) {
console.log('Renew option not set, skipping secret upload');
return secret;
}
this.saveSecret(secret, this.options.localEnvPath);
await this.uploadSecret(secret);
return secret;
}
constructor(public options: SecretManagerOptions) {
console.log('SecretManager created');
}

/**
* Randomly generates a secret string of a given length.
* @param length - Length of the secret string
* @returns A randomly generated secret string
*/
getSecret(length: number = 100): string {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
async start(): Promise<string> {
console.log('Starting secret generation');
const secret = this.getSecret();
if (!this.options.renew) {
console.log('Renew option not set, skipping secret upload');
return secret;
}
this.saveSecret(secret, this.options.localEnvPath);
await this.uploadSecret(secret);
return secret;
}

for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
result += characters[randomIndex];
}
/**
* Randomly generates a secret string of a given length.
* @param length - Length of the secret string
* @returns A randomly generated secret string
*/
getSecret(length: number = 100): string {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';

return result;
}
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
result += characters[randomIndex];
}

async saveSecret(secret: string, targetPath: string): Promise<void> {
const localEnvExists = fs.existsSync(targetPath);
if (!localEnvExists) {
await fs.promises.writeFile(targetPath, '');
}
// Renew the secret, by replacing the old one
let localEnv = fs.readFileSync(targetPath, 'utf-8');
if(localEnv.includes('WEBHOOK_SECRET=')) {
localEnv = localEnv.replace(/WEBHOOK_SECRET=.*/, `WEBHOOK_SECRET=${secret}`);
} else {
localEnv += `\nWEBHOOK_SECRET=${secret}`;
}
await fs.promises.writeFile(targetPath, localEnv);
}
return result;
}

async uploadSecret(secret: string): Promise<void> {
// Upload the secret to Cloudflare Workers Secrets
console.log('Uploading secret to Cloudflare Workers Secrets');
const tmpFile = `.dev.tmp.vars`;
await this.saveSecret(secret, tmpFile);
await $`npx wrangler secret bulk ${tmpFile}`;
// Clean up the temporary file
fs.unlinkSync(tmpFile);
async saveSecret(secret: string, targetPath: string): Promise<void> {
const localEnvExists = fs.existsSync(targetPath);
if (!localEnvExists) {
await fs.promises.writeFile(targetPath, '');
}
// Renew the secret, by replacing the old one
let localEnv = fs.readFileSync(targetPath, 'utf-8');
if (localEnv.includes('WEBHOOK_SECRET=')) {
localEnv = localEnv.replace(/WEBHOOK_SECRET=.*/, `WEBHOOK_SECRET=${secret}`);
} else {
localEnv += `\nWEBHOOK_SECRET=${secret}`;
}
await fs.promises.writeFile(targetPath, localEnv);
}

}
async uploadSecret(secret: string): Promise<void> {
// Upload the secret to Cloudflare Workers Secrets
console.log('Uploading secret to Cloudflare Workers Secrets');
const tmpFile = `.dev.tmp.vars`;
await this.saveSecret(secret, tmpFile);
await $`npx wrangler secret bulk ${tmpFile}`;
// Clean up the temporary file
fs.unlinkSync(tmpFile);
}
}



24 changes: 12 additions & 12 deletions scripts/libs/TelegramClient.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { ConsoleLogger, Logger } from "../utils/logger";
import { ConsoleLogger, Logger } from '../utils/logger';

export interface TelegramBotClientOptions {
logger?: Logger;
token: string;
logger?: Logger;
token: string;
}

export class TelegramBotClient {
private logger: Logger;
constructor(private readonly options: TelegramBotClientOptions) {
this.logger = options.logger ?? new ConsoleLogger();
}
private logger: Logger;
constructor(private readonly options: TelegramBotClientOptions) {
this.logger = options.logger ?? new ConsoleLogger();
}

async setWebhook(url: string) {
const targetUrl = `https://api.telegram.org/bot${this.options.token}/setWebhook?url=${url}`;
this.logger.info(`Setting webhook to ${targetUrl.replace(this.options.token, '**BOT_TOKEN**')}`);
await fetch(targetUrl);
}
async setWebhook(url: string) {
const targetUrl = `https://api.telegram.org/bot${this.options.token}/setWebhook?url=${url}`;
this.logger.info(`Setting webhook to ${targetUrl.replace(this.options.token, '**BOT_TOKEN**')}`);
await fetch(targetUrl);
}
}
Loading

0 comments on commit 74ab963

Please sign in to comment.