Compare commits

..
Author SHA1 Message Date
nabarun c96385f40c Implement Gitea authentication and get access token 2024-02-26 16:23:35 +05:30
265 changed files with 3972 additions and 11766 deletions
-6
View File
@@ -1,7 +1 @@
node_modules/
yarn-error.log
.yarnrc.yml
.yarn/
.yarnrc
packages/backend/environments/local.toml
-6
View File
@@ -1,6 +0,0 @@
{
// IntelliSense for taiwind variants
"tailwindCSS.experimental.classRegex": [
["tv\\((([^()]*|\\([^()]*\\))*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]
]
}
+2 -15
View File
@@ -28,12 +28,6 @@
cd packages/backend
```
- Rename backend config file from [environments/local.toml.example](packages/backend/environments/local.toml.example) to `local.toml`
```bash
mv environments/local.toml.example environments/local.toml
```
- Set `gitHub.oAuth.clientId` and `gitHub.oAuth.clientSecret` in backend [config file](packages/backend/environments/local.toml)
- Client ID and secret will be available after [creating an OAuth app](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app)
- In "Homepage URL", type `http://localhost:3000`
@@ -187,24 +181,17 @@
cd packages/frontend
```
- Rename [.env.example](packages/frontend/.env.example) to `.env`
```bash
mv .env.example .env
```
- Copy the GitHub OAuth app client ID from previous steps and set it in frontend [.env](packages/frontend/.env) file
```env
REACT_APP_GITHUB_CLIENT_ID = <CLIENT_ID>
```
- Set `REACT_APP_GITHUB_PWA_TEMPLATE_REPO` and `REACT_APP_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO` in [.env](packages/frontend/.env) file
- Set `REACT_APP_GITHUB_TEMPLATE_REPO` in [.env](packages/frontend/.env) file
```env
# Set actual owner/name of the template repo that will be used for creating new repo
REACT_APP_GITHUB_PWA_TEMPLATE_REPO = cerc-io/test-progressive-web-app
REACT_APP_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO = cerc-io/image-upload-pwa-example
REACT_APP_GITHUB_TEMPLATE_REPO = cerc-io/test-progressive-web-app
```
### Frontend Production
+1 -10
View File
@@ -9,19 +9,10 @@ if [[ -d "$DEST_DIR" ]]; then
exit 1
fi
if [[ -f "$PKG_DIR/.env" ]]; then
echo "Using existing .env file"
else
mv "$PKG_DIR/.env.example" "$PKG_DIR/.env"
echo "Created .env file. Please populate with the correct values."
exit 1
fi
cat > $PKG_DIR/.env <<EOF
REACT_APP_SERVER_URL = 'LACONIC_HOSTED_CONFIG_app_server_url'
REACT_APP_GITHUB_CLIENT_ID = 'LACONIC_HOSTED_CONFIG_app_github_clientid'
REACT_APP_GITHUB_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_app_github_pwa_templaterepo'
REACT_APP_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_app_github_image_upload_templaterepo'
REACT_APP_GITHUB_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_app_github_templaterepo'
REACT_APP_WALLET_CONNECT_ID = 'LACONIC_HOSTED_CONFIG_app_wallet_connect_id'
EOF
+1 -4
View File
@@ -25,9 +25,6 @@
"allowArgumentsExplicitlyTypedAsAny": true
}
],
"@typescript-eslint/no-unused-vars": [
"error",
{ "ignoreRestSiblings": true }
]
"@typescript-eslint/no-unused-vars": ["error", { "ignoreRestSiblings": true }]
}
}
-1
View File
@@ -1,3 +1,2 @@
db
dist
environments/local.toml
@@ -17,6 +17,11 @@
clientId = ""
clientSecret = ""
[gitea]
[gitea.oAuth]
clientId = ""
clientSecret = ""
[registryConfig]
fetchDeploymentRecordDelay = 5000
restEndpoint = "http://localhost:1317"
+2
View File
@@ -21,6 +21,7 @@
"luxon": "^3.4.4",
"nanoid": "3",
"nanoid-dictionary": "^5.0.0-beta.1",
"node-fetch": "2",
"octokit": "^3.1.2",
"reflect-metadata": "^0.2.1",
"semver": "^7.6.0",
@@ -46,6 +47,7 @@
"devDependencies": {
"@types/express-session": "^1.17.10",
"@types/fs-extra": "^11.0.4",
"@types/node-fetch": "^2.6.11",
"@typescript-eslint/eslint-plugin": "^6.18.1",
"@typescript-eslint/parser": "^6.18.1",
"better-sqlite3": "^9.2.2",
+2 -2
View File
@@ -24,7 +24,7 @@ export interface GitHubConfig {
oAuth: {
clientId: string;
clientSecret: string;
};
}
}
export interface RegistryConfig {
@@ -39,7 +39,7 @@ export interface RegistryConfig {
amount: string;
denom: string;
gas: string;
};
}
}
export interface MiscConfig {
+1 -2
View File
@@ -1,6 +1,5 @@
import process from 'process';
export const DEFAULT_CONFIG_FILE_PATH =
process.env.SNOWBALL_BACKEND_CONFIG_FILE_PATH || 'environments/local.toml';
export const DEFAULT_CONFIG_FILE_PATH = process.env.SNOWBALL_BACKEND_CONFIG_FILE_PATH || 'environments/local.toml';
export const DEFAULT_GQL_PATH = '/graphql';
+47 -138
View File
@@ -1,10 +1,4 @@
import {
DataSource,
DeepPartial,
FindManyOptions,
FindOneOptions,
FindOptionsWhere
} from 'typeorm';
import { DataSource, DeepPartial, FindManyOptions, FindOneOptions, FindOptionsWhere } from 'typeorm';
import path from 'path';
import debug from 'debug';
import assert from 'assert';
@@ -80,18 +74,14 @@ export class Database {
return updateResult.affected > 0;
}
async getOrganizations (
options: FindManyOptions<Organization>
): Promise<Organization[]> {
async getOrganizations (options: FindManyOptions<Organization>): Promise<Organization[]> {
const organizationRepository = this.dataSource.getRepository(Organization);
const organizations = await organizationRepository.find(options);
return organizations;
}
async getOrganization (
options: FindOneOptions<Organization>
): Promise<Organization | null> {
async getOrganization (options: FindOneOptions<Organization>): Promise<Organization | null> {
const organizationRepository = this.dataSource.getRepository(Organization);
const organization = await organizationRepository.findOne(options);
@@ -133,11 +123,7 @@ export class Database {
const project = await projectRepository
.createQueryBuilder('project')
.leftJoinAndSelect(
'project.deployments',
'deployments',
'deployments.isCurrent = true'
)
.leftJoinAndSelect('project.deployments', 'deployments', 'deployments.isCurrent = true')
.leftJoinAndSelect('deployments.createdBy', 'user')
.leftJoinAndSelect('deployments.domain', 'domain')
.leftJoinAndSelect('project.owner', 'owner')
@@ -150,29 +136,19 @@ export class Database {
return project;
}
async getProjectsInOrganization (
userId: string,
organizationSlug: string
): Promise<Project[]> {
async getProjectsInOrganization (userId: string, organizationSlug: string): Promise<Project[]> {
const projectRepository = this.dataSource.getRepository(Project);
const projects = await projectRepository
.createQueryBuilder('project')
.leftJoinAndSelect(
'project.deployments',
'deployments',
'deployments.isCurrent = true'
)
.leftJoinAndSelect('project.deployments', 'deployments', 'deployments.isCurrent = true')
.leftJoinAndSelect('deployments.domain', 'domain')
.leftJoin('project.projectMembers', 'projectMembers')
.leftJoin('project.organization', 'organization')
.where(
'(project.ownerId = :userId OR projectMembers.userId = :userId) AND organization.slug = :organizationSlug',
{
userId,
organizationSlug
}
)
.where('(project.ownerId = :userId OR projectMembers.userId = :userId) AND organization.slug = :organizationSlug', {
userId,
organizationSlug
})
.getMany();
return projects;
@@ -181,9 +157,7 @@ export class Database {
/**
* Get deployments with specified filter
*/
async getDeployments (
options: FindManyOptions<Deployment>
): Promise<Deployment[]> {
async getDeployments (options: FindManyOptions<Deployment>): Promise<Deployment[]> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployments = await deploymentRepository.find(options);
@@ -208,9 +182,7 @@ export class Database {
});
}
async getDeployment (
options: FindOneOptions<Deployment>
): Promise<Deployment | null> {
async getDeployment (options: FindOneOptions<Deployment>): Promise<Deployment | null> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployment = await deploymentRepository.findOne(options);
@@ -238,11 +210,8 @@ export class Database {
return deployment;
}
async getProjectMembersByProjectId (
projectId: string
): Promise<ProjectMember[]> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
async getProjectMembersByProjectId (projectId: string): Promise<ProjectMember[]> {
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
const projectMembers = await projectMemberRepository.find({
relations: {
@@ -259,12 +228,8 @@ export class Database {
return projectMembers;
}
async getEnvironmentVariablesByProjectId (
projectId: string,
filter?: FindOptionsWhere<EnvironmentVariable>
): Promise<EnvironmentVariable[]> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
async getEnvironmentVariablesByProjectId (projectId: string, filter?: FindOptionsWhere<EnvironmentVariable>): Promise<EnvironmentVariable[]> {
const environmentVariableRepository = this.dataSource.getRepository(EnvironmentVariable);
const environmentVariables = await environmentVariableRepository.find({
where: {
@@ -279,12 +244,9 @@ export class Database {
}
async removeProjectMemberById (projectMemberId: string): Promise<boolean> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
const deleteResult = await projectMemberRepository.delete({
id: projectMemberId
});
const deleteResult = await projectMemberRepository.delete({ id: projectMemberId });
if (deleteResult.affected) {
return deleteResult.affected > 0;
@@ -293,63 +255,37 @@ export class Database {
}
}
async updateProjectMemberById (
projectMemberId: string,
data: DeepPartial<ProjectMember>
): Promise<boolean> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
const updateResult = await projectMemberRepository.update(
{ id: projectMemberId },
data
);
async updateProjectMemberById (projectMemberId: string, data: DeepPartial<ProjectMember>): Promise<boolean> {
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
const updateResult = await projectMemberRepository.update({ id: projectMemberId }, data);
return Boolean(updateResult.affected);
}
async addProjectMember (
data: DeepPartial<ProjectMember>
): Promise<ProjectMember> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
async addProjectMember (data: DeepPartial<ProjectMember>): Promise<ProjectMember> {
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
const newProjectMember = await projectMemberRepository.save(data);
return newProjectMember;
}
async addEnvironmentVariables (
data: DeepPartial<EnvironmentVariable>[]
): Promise<EnvironmentVariable[]> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
const savedEnvironmentVariables =
await environmentVariableRepository.save(data);
async addEnvironmentVariables (data: DeepPartial<EnvironmentVariable>[]): Promise<EnvironmentVariable[]> {
const environmentVariableRepository = this.dataSource.getRepository(EnvironmentVariable);
const savedEnvironmentVariables = await environmentVariableRepository.save(data);
return savedEnvironmentVariables;
}
async updateEnvironmentVariable (
environmentVariableId: string,
data: DeepPartial<EnvironmentVariable>
): Promise<boolean> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
const updateResult = await environmentVariableRepository.update(
{ id: environmentVariableId },
data
);
async updateEnvironmentVariable (environmentVariableId: string, data: DeepPartial<EnvironmentVariable>): Promise<boolean> {
const environmentVariableRepository = this.dataSource.getRepository(EnvironmentVariable);
const updateResult = await environmentVariableRepository.update({ id: environmentVariableId }, data);
return Boolean(updateResult.affected);
}
async deleteEnvironmentVariable (
environmentVariableId: string
): Promise<boolean> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
const deleteResult = await environmentVariableRepository.delete({
id: environmentVariableId
});
async deleteEnvironmentVariable (environmentVariableId: string): Promise<boolean> {
const environmentVariableRepository = this.dataSource.getRepository(EnvironmentVariable);
const deleteResult = await environmentVariableRepository.delete({ id: environmentVariableId });
if (deleteResult.affected) {
return deleteResult.affected > 0;
@@ -359,8 +295,7 @@ export class Database {
}
async getProjectMemberById (projectMemberId: string): Promise<ProjectMember> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
const projectMemberWithProject = await projectMemberRepository.find({
relations: {
@@ -372,7 +307,8 @@ export class Database {
where: {
id: projectMemberId
}
});
}
);
if (projectMemberWithProject.length === 0) {
throw new Error('Member does not exist');
@@ -381,49 +317,34 @@ export class Database {
return projectMemberWithProject[0];
}
async getProjectsBySearchText (
userId: string,
searchText: string
): Promise<Project[]> {
async getProjectsBySearchText (userId: string, searchText: string): Promise<Project[]> {
const projectRepository = this.dataSource.getRepository(Project);
const projects = await projectRepository
.createQueryBuilder('project')
.leftJoinAndSelect('project.organization', 'organization')
.leftJoin('project.projectMembers', 'projectMembers')
.where(
'(project.owner = :userId OR projectMembers.member.id = :userId) AND project.name LIKE :searchText',
{
userId,
searchText: `%${searchText}%`
}
)
.where('(project.owner = :userId OR projectMembers.member.id = :userId) AND project.name LIKE :searchText', {
userId,
searchText: `%${searchText}%`
})
.getMany();
return projects;
}
async updateDeploymentById (
deploymentId: string,
data: DeepPartial<Deployment>
): Promise<boolean> {
async updateDeploymentById (deploymentId: string, data: DeepPartial<Deployment>): Promise<boolean> {
return this.updateDeployment({ id: deploymentId }, data);
}
async updateDeployment (
criteria: FindOptionsWhere<Deployment>,
data: DeepPartial<Deployment>
): Promise<boolean> {
async updateDeployment (criteria: FindOptionsWhere<Deployment>, data: DeepPartial<Deployment>): Promise<boolean> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const updateResult = await deploymentRepository.update(criteria, data);
return Boolean(updateResult.affected);
}
async updateDeploymentsByProjectIds (
projectIds: string[],
data: DeepPartial<Deployment>
): Promise<boolean> {
async updateDeploymentsByProjectIds (projectIds: string[], data: DeepPartial<Deployment>): Promise<boolean> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const updateResult = await deploymentRepository
@@ -457,15 +378,9 @@ export class Database {
return projectRepository.save(newProject);
}
async updateProjectById (
projectId: string,
data: DeepPartial<Project>
): Promise<boolean> {
async updateProjectById (projectId: string, data: DeepPartial<Project>): Promise<boolean> {
const projectRepository = this.dataSource.getRepository(Project);
const updateResult = await projectRepository.update(
{ id: projectId },
data
);
const updateResult = await projectRepository.update({ id: projectId }, data);
return Boolean(updateResult.affected);
}
@@ -512,20 +427,14 @@ export class Database {
return domain;
}
async updateDomainById (
domainId: string,
data: DeepPartial<Domain>
): Promise<boolean> {
async updateDomainById (domainId: string, data: DeepPartial<Domain>): Promise<boolean> {
const domainRepository = this.dataSource.getRepository(Domain);
const updateResult = await domainRepository.update({ id: domainId }, data);
return Boolean(updateResult.affected);
}
async getDomainsByProjectId (
projectId: string,
filter?: FindOptionsWhere<Domain>
): Promise<Domain[]> {
async getDomainsByProjectId (projectId: string, filter?: FindOptionsWhere<Domain>): Promise<Domain[]> {
const domainRepository = this.dataSource.getRepository(Domain);
const domains = await domainRepository.find({
+16 -16
View File
@@ -27,26 +27,26 @@ export enum DeploymentStatus {
}
export interface ApplicationDeploymentRequest {
type: string;
version: string;
name: string;
application: string;
config: string;
meta: string;
type: string
version: string
name: string
application: string
config: string,
meta: string
}
export interface ApplicationRecord {
type: string;
version: string;
name: string;
description?: string;
homepage?: string;
license?: string;
author?: string;
repository?: string[];
app_version?: string;
repository_ref: string;
app_type: string;
version:string
name: string
description?: string
homepage?: string
license?: string
author?: string
repository?: string[],
app_version?: string
repository_ref: string
app_type: string
}
@Entity()
+1 -1
View File
@@ -39,7 +39,7 @@ export class Domain {
@ManyToOne(() => Domain)
@JoinColumn({ name: 'redirectToId' })
// eslint-disable-next-line no-use-before-define
// eslint-disable-next-line no-use-before-define
redirectTo!: Domain | null;
@Column({
+3 -7
View File
@@ -27,12 +27,8 @@ export class Organization {
@UpdateDateColumn()
updatedAt!: Date;
@OneToMany(
() => UserOrganization,
(userOrganization) => userOrganization.organization,
{
cascade: ['soft-remove']
}
)
@OneToMany(() => UserOrganization, userOrganization => userOrganization.organization, {
cascade: ['soft-remove']
})
userOrganizations!: UserOrganization[];
}
+1 -1
View File
@@ -76,7 +76,7 @@ export class Project {
@OneToMany(() => Deployment, (deployment) => deployment.project)
deployments!: Deployment[];
@OneToMany(() => ProjectMember, (projectMember) => projectMember.project, {
@OneToMany(() => ProjectMember, projectMember => projectMember.project, {
cascade: ['soft-remove']
})
projectMembers!: ProjectMember[];
+1 -1
View File
@@ -15,7 +15,7 @@ import { User } from './User';
export enum Permission {
View = 'View',
Edit = 'Edit',
Edit = 'Edit'
}
@Entity()
+4 -8
View File
@@ -39,17 +39,13 @@ export class User {
@CreateDateColumn()
updatedAt!: Date;
@OneToMany(() => ProjectMember, (projectMember) => projectMember.project, {
@OneToMany(() => ProjectMember, projectMember => projectMember.project, {
cascade: ['soft-remove']
})
projectMembers!: ProjectMember[];
@OneToMany(
() => UserOrganization,
(UserOrganization) => UserOrganization.member,
{
cascade: ['soft-remove']
}
)
@OneToMany(() => UserOrganization, UserOrganization => UserOrganization.member, {
cascade: ['soft-remove']
})
userOrganizations!: UserOrganization[];
}
+2 -9
View File
@@ -31,16 +31,9 @@ export const main = async (): Promise<void> => {
await db.init();
const registry = new Registry(registryConfig);
const service = new Service(
{ gitHubConfig: gitHub, registryConfig },
db,
app,
registry
);
const service = new Service({ gitHubConfig: gitHub, registryConfig }, db, app, registry);
const typeDefs = fs
.readFileSync(path.join(__dirname, 'schema.gql'))
.toString();
const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.gql')).toString();
const resolvers = await createResolvers(service);
await createAndStartServer(server, typeDefs, resolvers, service);
+30 -90
View File
@@ -6,11 +6,7 @@ import { DateTime } from 'luxon';
import { Registry as LaconicRegistry } from '@cerc-io/laconic-sdk';
import { RegistryConfig } from './config';
import {
ApplicationRecord,
Deployment,
ApplicationDeploymentRequest
} from './entity/Deployment';
import { ApplicationRecord, Deployment, ApplicationDeploymentRequest } from './entity/Deployment';
import { AppDeploymentRecord, PackageJSON } from './types';
const log = debug('snowball:registry');
@@ -24,13 +20,9 @@ export class Registry {
private registry: LaconicRegistry;
private registryConfig: RegistryConfig;
constructor (registryConfig: RegistryConfig) {
constructor (registryConfig : RegistryConfig) {
this.registryConfig = registryConfig;
this.registry = new LaconicRegistry(
registryConfig.gqlEndpoint,
registryConfig.restEndpoint,
registryConfig.chainId
);
this.registry = new LaconicRegistry(registryConfig.gqlEndpoint, registryConfig.restEndpoint, registryConfig.chainId);
}
async createApplicationRecord ({
@@ -40,38 +32,24 @@ export class Registry {
appType,
repoUrl
}: {
appName: string;
packageJSON: PackageJSON;
commitHash: string;
appType: string;
repoUrl: string;
}): Promise<{
applicationRecordId: string;
applicationRecordData: ApplicationRecord;
}> {
appName: string,
packageJSON: PackageJSON
commitHash: string,
appType: string,
repoUrl: string
}): Promise<{applicationRecordId: string, applicationRecordData: ApplicationRecord}> {
// Use laconic-sdk to publish record
// Reference: https://git.vdb.to/cerc-io/test-progressive-web-app/src/branch/main/scripts/publish-app-record.sh
// Fetch previous records
const records = await this.registry.queryRecords(
{
type: APP_RECORD_TYPE,
name: packageJSON.name
},
true
);
const records = await this.registry.queryRecords({
type: APP_RECORD_TYPE,
name: packageJSON.name
}, true);
// Get next version of record
const bondRecords = records.filter(
(record: any) => record.bondId === this.registryConfig.bondId
);
const [latestBondRecord] = bondRecords.sort(
(a: any, b: any) =>
new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
);
const nextVersion = semverInc(
latestBondRecord?.attributes.version ?? '0.0.0',
'patch'
);
const bondRecords = records.filter((record: any) => record.bondId === this.registryConfig.bondId);
const [latestBondRecord] = bondRecords.sort((a: any, b: any) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime());
const nextVersion = semverInc(latestBondRecord?.attributes.version ?? '0.0.0', 'patch');
assert(nextVersion, 'Application record version not valid');
@@ -86,12 +64,7 @@ export class Registry {
...(packageJSON.description && { description: packageJSON.description }),
...(packageJSON.homepage && { homepage: packageJSON.homepage }),
...(packageJSON.license && { license: packageJSON.license }),
...(packageJSON.author && {
author:
typeof packageJSON.author === 'object'
? JSON.stringify(packageJSON.author)
: packageJSON.author
}),
...(packageJSON.author && { author: typeof packageJSON.author === 'object' ? JSON.stringify(packageJSON.author) : packageJSON.author }),
...(packageJSON.version && { app_version: packageJSON.version })
};
@@ -111,29 +84,11 @@ export class Registry {
const crn = this.getCrn(appName);
log(`Setting name: ${crn} for record ID: ${result.data.id}`);
await this.registry.setName(
{ cid: result.data.id, crn },
this.registryConfig.privateKey,
this.registryConfig.fee
);
await this.registry.setName(
{ cid: result.data.id, crn: `${crn}@${applicationRecord.app_version}` },
this.registryConfig.privateKey,
this.registryConfig.fee
);
await this.registry.setName(
{
cid: result.data.id,
crn: `${crn}@${applicationRecord.repository_ref}`
},
this.registryConfig.privateKey,
this.registryConfig.fee
);
await this.registry.setName({ cid: result.data.id, crn }, this.registryConfig.privateKey, this.registryConfig.fee);
await this.registry.setName({ cid: result.data.id, crn: `${crn}@${applicationRecord.app_version}` }, this.registryConfig.privateKey, this.registryConfig.fee);
await this.registry.setName({ cid: result.data.id, crn: `${crn}@${applicationRecord.repository_ref}` }, this.registryConfig.privateKey, this.registryConfig.fee);
return {
applicationRecordId: result.data.id,
applicationRecordData: applicationRecord
};
return { applicationRecordId: result.data.id, applicationRecordData: applicationRecord };
}
async createApplicationDeploymentRequest (data: {
@@ -143,8 +98,8 @@ export class Registry {
repository: string,
environmentVariables: { [key: string]: string }
}): Promise<{
applicationDeploymentRequestId: string;
applicationDeploymentRequestData: ApplicationDeploymentRequest;
applicationDeploymentRequestId: string,
applicationDeploymentRequestData: ApplicationDeploymentRequest
}> {
const crn = this.getCrn(data.appName);
const records = await this.registry.resolveNames([crn]);
@@ -170,9 +125,7 @@ export class Registry {
env: data.environmentVariables
}),
meta: JSON.stringify({
note: `Added by Snowball @ ${DateTime.utc().toFormat(
"EEE LLL dd HH:mm:ss 'UTC' yyyy"
)}`,
note: `Added by Snowball @ ${DateTime.utc().toFormat('EEE LLL dd HH:mm:ss \'UTC\' yyyy')}`,
repository: data.repository,
repository_ref: data.deployment.commitHash
})
@@ -190,34 +143,21 @@ export class Registry {
log(`Application deployment request record published: ${result.data.id}`);
log('Application deployment request data:', applicationDeploymentRequest);
return {
applicationDeploymentRequestId: result.data.id,
applicationDeploymentRequestData: applicationDeploymentRequest
};
return { applicationDeploymentRequestId: result.data.id, applicationDeploymentRequestData: applicationDeploymentRequest };
}
/**
* Fetch ApplicationDeploymentRecords for deployments
*/
async getDeploymentRecords (
deployments: Deployment[]
): Promise<AppDeploymentRecord[]> {
async getDeploymentRecords (deployments: Deployment[]): Promise<AppDeploymentRecord[]> {
// Fetch ApplicationDeploymentRecords for corresponding ApplicationRecord set in deployments
// TODO: Implement Laconicd GQL query to filter records by multiple values for an attribute
const records = await this.registry.queryRecords(
{
type: APP_DEPLOYMENT_RECORD_TYPE
},
true
);
const records = await this.registry.queryRecords({
type: APP_DEPLOYMENT_RECORD_TYPE
}, true);
// Filter records with ApplicationRecord ids
return records.filter((record: AppDeploymentRecord) =>
deployments.some(
(deployment) =>
deployment.applicationRecordId === record.attributes.application
)
);
return records.filter((record: AppDeploymentRecord) => deployments.some(deployment => deployment.applicationRecordId === record.attributes.application));
}
getCrn (appName: string): string {
+38 -114
View File
@@ -6,6 +6,7 @@ import { Permission } from './entity/ProjectMember';
import { Domain } from './entity/Domain';
import { Project } from './entity/Project';
import { EnvironmentVariable } from './entity/EnvironmentVariable';
import { GitType } from './types';
const log = debug('snowball:resolver');
@@ -33,10 +34,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
return service.getDeploymentsByProjectId(projectId);
},
environmentVariables: async (
_: any,
{ projectId }: { projectId: string }
) => {
environmentVariables: async (_: any, { projectId }: { projectId: string }) => {
return service.getEnvironmentVariablesByProjectId(projectId);
},
@@ -48,24 +46,14 @@ export const createResolvers = async (service: Service): Promise<any> => {
return service.searchProjects(context.user, searchText);
},
domains: async (
_: any,
{
projectId,
filter
}: { projectId: string; filter?: FindOptionsWhere<Domain> }
) => {
domains: async (_:any, { projectId, filter }: { projectId: string, filter?: FindOptionsWhere<Domain> }) => {
return service.getDomainsByProjectId(projectId, filter);
}
},
// TODO: Return error in GQL response
Mutation: {
removeProjectMember: async (
_: any,
{ projectMemberId }: { projectMemberId: string },
context: any
) => {
removeProjectMember: async (_: any, { projectMemberId }: { projectMemberId: string }, context: any) => {
try {
return await service.removeProjectMember(context.user, projectMemberId);
} catch (err) {
@@ -74,18 +62,12 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
updateProjectMember: async (
_: any,
{
projectMemberId,
data
}: {
projectMemberId: string;
data: {
permissions: Permission[];
};
updateProjectMember: async (_: any, { projectMemberId, data }: {
projectMemberId: string,
data: {
permissions: Permission[]
}
) => {
}) => {
try {
return await service.updateProjectMember(projectMemberId, data);
} catch (err) {
@@ -94,19 +76,13 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
addProjectMember: async (
_: any,
{
projectId,
data
}: {
projectId: string;
data: {
email: string;
permissions: Permission[];
};
addProjectMember: async (_: any, { projectId, data }: {
projectId: string,
data: {
email: string,
permissions: Permission[]
}
) => {
}) => {
try {
return Boolean(await service.addProjectMember(projectId, data));
} catch (err) {
@@ -115,51 +91,25 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
addEnvironmentVariables: async (
_: any,
{
projectId,
data
}: {
projectId: string;
data: { environments: string[]; key: string; value: string }[];
}
) => {
addEnvironmentVariables: async (_: any, { projectId, data }: { projectId: string, data: { environments: string[], key: string, value: string}[] }) => {
try {
return Boolean(
await service.addEnvironmentVariables(projectId, data)
);
return Boolean(await service.addEnvironmentVariables(projectId, data));
} catch (err) {
log(err);
return false;
}
},
updateEnvironmentVariable: async (
_: any,
{
environmentVariableId,
data
}: {
environmentVariableId: string;
data: DeepPartial<EnvironmentVariable>;
}
) => {
updateEnvironmentVariable: async (_: any, { environmentVariableId, data }: { environmentVariableId: string, data : DeepPartial<EnvironmentVariable>}) => {
try {
return await service.updateEnvironmentVariable(
environmentVariableId,
data
);
return await service.updateEnvironmentVariable(environmentVariableId, data);
} catch (err) {
log(err);
return false;
}
},
removeEnvironmentVariable: async (
_: any,
{ environmentVariableId }: { environmentVariableId: string }
) => {
removeEnvironmentVariable: async (_: any, { environmentVariableId }: { environmentVariableId: string}) => {
try {
return await service.removeEnvironmentVariable(environmentVariableId);
} catch (err) {
@@ -168,11 +118,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
updateDeploymentToProd: async (
_: any,
{ deploymentId }: { deploymentId: string },
context: any
) => {
updateDeploymentToProd: async (_: any, { deploymentId }: { deploymentId: string }, context: any) => {
try {
return Boolean(await service.updateDeploymentToProd(context.user, deploymentId));
} catch (err) {
@@ -181,14 +127,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
addProject: async (
_: any,
{
organizationSlug,
data
}: { organizationSlug: string; data: DeepPartial<Project> },
context: any
) => {
addProject: async (_: any, { organizationSlug, data }: { organizationSlug: string, data: DeepPartial<Project> }, context: any) => {
try {
return await service.addProject(context.user, organizationSlug, data);
} catch (err) {
@@ -197,10 +136,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
updateProject: async (
_: any,
{ projectId, data }: { projectId: string; data: DeepPartial<Project> }
) => {
updateProject: async (_: any, { projectId, data }: { projectId: string, data: DeepPartial<Project> }) => {
try {
return await service.updateProject(projectId, data);
} catch (err) {
@@ -209,11 +145,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
redeployToProd: async (
_: any,
{ deploymentId }: { deploymentId: string },
context: any
) => {
redeployToProd: async (_: any, { deploymentId }: { deploymentId: string }, context: any) => {
try {
return Boolean(await service.redeployToProd(context.user, deploymentId));
} catch (err) {
@@ -226,8 +158,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
try {
return await service.deleteProject(projectId);
} catch (err) {
log(err);
return false;
log(err); return false;
}
},
@@ -240,13 +171,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
rollbackDeployment: async (
_: any,
{
projectId,
deploymentId
}: { deploymentId: string; projectId: string }
) => {
rollbackDeployment: async (_: any, { projectId, deploymentId }: {deploymentId: string, projectId: string }) => {
try {
return await service.rollbackDeployment(projectId, deploymentId);
} catch (err) {
@@ -255,10 +180,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
addDomain: async (
_: any,
{ projectId, data }: { projectId: string; data: { name: string } }
) => {
addDomain: async (_: any, { projectId, data }: { projectId: string, data: { name: string } }) => {
try {
return Boolean(await service.addDomain(projectId, data));
} catch (err) {
@@ -267,10 +189,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
updateDomain: async (
_: any,
{ domainId, data }: { domainId: string; data: DeepPartial<Domain> }
) => {
updateDomain: async (_: any, { domainId, data }: { domainId: string, data: DeepPartial<Domain>}) => {
try {
return await service.updateDomain(domainId, data);
} catch (err) {
@@ -279,11 +198,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
authenticateGitHub: async (
_: any,
{ code }: { code: string },
context: any
) => {
authenticateGitHub: async (_: any, { code }: { code: string }, context: any) => {
try {
return await service.authenticateGitHub(code, context.user);
} catch (err) {
@@ -292,6 +207,15 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
authenticateGit: async (_: any, { type, code }: { type: GitType, code: string }, context: any) => {
try {
return await service.authenticateGit(type, code, context.user);
} catch (err) {
log(err);
return false;
}
},
unauthenticateGitHub: async (_: any, __: object, context: any) => {
try {
return service.unauthenticateGitHub(context.user, { gitHubToken: null });
+9 -12
View File
@@ -26,6 +26,11 @@ enum DomainStatus {
Pending
}
enum GitType {
GitHub
Gitea
}
type User {
id: String!
name: String
@@ -188,19 +193,10 @@ type Query {
type Mutation {
addProjectMember(projectId: String!, data: AddProjectMemberInput): Boolean!
updateProjectMember(
projectMemberId: String!
data: UpdateProjectMemberInput
): Boolean!
updateProjectMember(projectMemberId: String!, data: UpdateProjectMemberInput): Boolean!
removeProjectMember(projectMemberId: String!): Boolean!
addEnvironmentVariables(
projectId: String!
data: [AddEnvironmentVariableInput!]
): Boolean!
updateEnvironmentVariable(
environmentVariableId: String!
data: UpdateEnvironmentVariableInput!
): Boolean!
addEnvironmentVariables(projectId: String!, data: [AddEnvironmentVariableInput!]): Boolean!
updateEnvironmentVariable(environmentVariableId: String!, data: UpdateEnvironmentVariableInput!): Boolean!
removeEnvironmentVariable(environmentVariableId: String!): Boolean!
updateDeploymentToProd(deploymentId: String!): Boolean!
addProject(organizationSlug: String!, data: AddProjectInput): Project!
@@ -212,5 +208,6 @@ type Mutation {
addDomain(projectId: String!, data: AddDomainInput!): Boolean!
updateDomain(domainId: String!, data: UpdateDomainInput!): Boolean!
authenticateGitHub(code: String!): AuthResult!
authenticateGit(type: GitType!, code: String!): AuthResult!
unauthenticateGitHub: Boolean!
}
+137 -184
View File
@@ -2,6 +2,7 @@ import assert from 'assert';
import debug from 'debug';
import { DeepPartial, FindOptionsWhere } from 'typeorm';
import { Octokit, RequestError } from 'octokit';
import fetch from 'node-fetch';
import { OAuthApp } from '@octokit/oauth-app';
@@ -15,16 +16,17 @@ import { Permission, ProjectMember } from './entity/ProjectMember';
import { User } from './entity/User';
import { Registry } from './registry';
import { GitHubConfig, RegistryConfig } from './config';
import { AppDeploymentRecord, GitPushEventPayload, PackageJSON } from './types';
import { AppDeploymentRecord, GitPushEventPayload, GitType, PackageJSON } from './types';
import { Role } from './entity/UserOrganization';
const log = debug('snowball:service');
const GITHUB_UNIQUE_WEBHOOK_ERROR = 'Hook already exists on this repository';
const GITEA_ACCESS_TOKEN_ENDPOINT = 'https://git.vdb.to/login/oauth/access_token';
interface Config {
gitHubConfig: GitHubConfig;
registryConfig: RegistryConfig;
gitHubConfig: GitHubConfig
registryConfig: RegistryConfig
}
export class Service {
@@ -72,9 +74,7 @@ export class Service {
});
if (deployments.length) {
log(
`Found ${deployments.length} deployments in ${DeploymentStatus.Building} state`
);
log(`Found ${deployments.length} deployments in ${DeploymentStatus.Building} state`);
// Fetch ApplicationDeploymentRecord for deployments
const records = await this.registry.getDeploymentRecords(deployments);
@@ -94,12 +94,10 @@ export class Service {
/**
* Update deployments with ApplicationDeploymentRecord data
*/
async updateDeploymentsWithRecordData (
records: AppDeploymentRecord[]
): Promise<void> {
async updateDeploymentsWithRecordData (records: AppDeploymentRecord[]): Promise<void> {
// Get deployments for ApplicationDeploymentRecords
const deployments = await this.db.getDeployments({
where: records.map((record) => ({
where: records.map(record => ({
applicationRecordId: record.attributes.application
})),
order: {
@@ -108,46 +106,38 @@ export class Service {
});
// Get project IDs of deployments that are in production environment
const productionDeploymentProjectIds = deployments.reduce(
(acc, deployment): Set<string> => {
if (deployment.environment === Environment.Production) {
acc.add(deployment.projectId);
}
const productionDeploymentProjectIds = deployments.reduce((acc, deployment): Set<string> => {
if (deployment.environment === Environment.Production) {
acc.add(deployment.projectId);
}
return acc;
},
new Set<string>()
);
return acc;
}, new Set<string>());
// Set old deployments isCurrent to false
await this.db.updateDeploymentsByProjectIds(
Array.from(productionDeploymentProjectIds),
{ isCurrent: false }
);
await this.db.updateDeploymentsByProjectIds(Array.from(productionDeploymentProjectIds), { isCurrent: false });
const recordToDeploymentsMap = deployments.reduce(
(acc: { [key: string]: Deployment }, deployment) => {
acc[deployment.applicationRecordId] = deployment;
return acc;
},
{}
);
const recordToDeploymentsMap = deployments.reduce((acc: {[key: string]: Deployment}, deployment) => {
acc[deployment.applicationRecordId] = deployment;
return acc;
}, {});
// Update deployment data for ApplicationDeploymentRecords
const deploymentUpdatePromises = records.map(async (record) => {
const deployment = recordToDeploymentsMap[record.attributes.application];
await this.db.updateDeploymentById(deployment.id, {
applicationDeploymentRecordId: record.id,
applicationDeploymentRecordData: record.attributes,
url: record.attributes.url,
status: DeploymentStatus.Ready,
isCurrent: deployment.environment === Environment.Production
});
log(
`Updated deployment ${deployment.id} with URL ${record.attributes.url}`
await this.db.updateDeploymentById(
deployment.id,
{
applicationDeploymentRecordId: record.id,
applicationDeploymentRecordData: record.attributes,
url: record.attributes.url,
status: DeploymentStatus.Ready,
isCurrent: deployment.environment === Environment.Production
}
);
log(`Updated deployment ${deployment.id} with URL ${record.attributes.url}`);
});
await Promise.all(deploymentUpdatePromises);
@@ -193,10 +183,7 @@ export class Service {
async getOctokit (userId: string): Promise<Octokit> {
const user = await this.db.getUser({ where: { id: userId } });
assert(
user && user.gitHubToken,
'User needs to be authenticated with GitHub token'
);
assert(user && user.gitHubToken, 'User needs to be authenticated with GitHub token');
return new Octokit({ auth: user.gitHubToken });
}
@@ -221,19 +208,13 @@ export class Service {
return dbDeployments;
}
async getEnvironmentVariablesByProjectId (
projectId: string
): Promise<EnvironmentVariable[]> {
const dbEnvironmentVariables =
await this.db.getEnvironmentVariablesByProjectId(projectId);
async getEnvironmentVariablesByProjectId (projectId: string): Promise<EnvironmentVariable[]> {
const dbEnvironmentVariables = await this.db.getEnvironmentVariablesByProjectId(projectId);
return dbEnvironmentVariables;
}
async getProjectMembersByProjectId (
projectId: string
): Promise<ProjectMember[]> {
const dbProjectMembers =
await this.db.getProjectMembersByProjectId(projectId);
async getProjectMembersByProjectId (projectId: string): Promise<ProjectMember[]> {
const dbProjectMembers = await this.db.getProjectMembersByProjectId(projectId);
return dbProjectMembers;
}
@@ -242,28 +223,20 @@ export class Service {
return dbProjects;
}
async getDomainsByProjectId (
projectId: string,
filter?: FindOptionsWhere<Domain>
): Promise<Domain[]> {
async getDomainsByProjectId (projectId: string, filter?: FindOptionsWhere<Domain>): Promise<Domain[]> {
const dbDomains = await this.db.getDomainsByProjectId(projectId, filter);
return dbDomains;
}
async updateProjectMember (
projectMemberId: string,
data: { permissions: Permission[] }
): Promise<boolean> {
async updateProjectMember (projectMemberId: string, data: {permissions: Permission[]}): Promise<boolean> {
return this.db.updateProjectMemberById(projectMemberId, data);
}
async addProjectMember (
projectId: string,
async addProjectMember (projectId: string,
data: {
email: string;
permissions: Permission[];
}
): Promise<ProjectMember> {
email: string,
permissions: Permission[]
}): Promise<ProjectMember> {
// TODO: Send invitation
let user = await this.db.getUser({
where: {
@@ -308,41 +281,29 @@ export class Service {
}
}
async addEnvironmentVariables (
projectId: string,
data: { environments: string[]; key: string; value: string }[]
): Promise<EnvironmentVariable[]> {
const formattedEnvironmentVariables = data
.map((environmentVariable) => {
return environmentVariable.environments.map((environment) => {
return {
key: environmentVariable.key,
value: environmentVariable.value,
environment: environment as Environment,
project: Object.assign(new Project(), {
id: projectId
})
};
async addEnvironmentVariables (projectId: string, data: { environments: string[], key: string, value: string}[]): Promise<EnvironmentVariable[]> {
const formattedEnvironmentVariables = data.map((environmentVariable) => {
return environmentVariable.environments.map((environment) => {
return ({
key: environmentVariable.key,
value: environmentVariable.value,
environment: environment as Environment,
project: Object.assign(new Project(), {
id: projectId
})
});
})
.flat();
});
}).flat();
const savedEnvironmentVariables = await this.db.addEnvironmentVariables(
formattedEnvironmentVariables
);
const savedEnvironmentVariables = await this.db.addEnvironmentVariables(formattedEnvironmentVariables);
return savedEnvironmentVariables;
}
async updateEnvironmentVariable (
environmentVariableId: string,
data: DeepPartial<EnvironmentVariable>
): Promise<boolean> {
async updateEnvironmentVariable (environmentVariableId: string, data : DeepPartial<EnvironmentVariable>): Promise<boolean> {
return this.db.updateEnvironmentVariable(environmentVariableId, data);
}
async removeEnvironmentVariable (
environmentVariableId: string
): Promise<boolean> {
async removeEnvironmentVariable (environmentVariableId: string): Promise<boolean> {
return this.db.deleteEnvironmentVariable(environmentVariableId);
}
@@ -358,10 +319,7 @@ export class Service {
throw new Error('Deployment does not exist');
}
const prodBranchDomains = await this.db.getDomainsByProjectId(
oldDeployment.project.id,
{ branch: oldDeployment.project.prodBranch }
);
const prodBranchDomains = await this.db.getDomainsByProjectId(oldDeployment.project.id, { branch: oldDeployment.project.prodBranch });
const octokit = await this.getOctokit(user.id);
@@ -386,9 +344,7 @@ export class Service {
recordData: { repoUrl?: string } = {}
): Promise<Deployment> {
assert(data.project?.repository, 'Project repository not found');
log(
`Creating deployment in project ${data.project.name} from branch ${data.branch}`
);
log(`Creating deployment in project ${data.project.name} from branch ${data.branch}`);
const [owner, repo] = data.project.repository.split('/');
const { data: packageJSONData } = await octokit.rest.repos.getContent({
@@ -408,22 +364,18 @@ export class Service {
assert(packageJSON.name, "name field doesn't exist in package.json");
if (!recordData.repoUrl) {
const { data: repoDetails } = await octokit.rest.repos.get({
owner,
repo
});
const { data: repoDetails } = await octokit.rest.repos.get({ owner, repo });
recordData.repoUrl = repoDetails.html_url;
}
// TODO: Set environment variables for each deployment (environment variables can`t be set in application record)
const { applicationRecordId, applicationRecordData } =
await this.registry.createApplicationRecord({
appName: repo,
packageJSON,
appType: data.project!.template!,
commitHash: data.commitHash!,
repoUrl: recordData.repoUrl
});
const { applicationRecordId, applicationRecordData } = await this.registry.createApplicationRecord({
appName: repo,
packageJSON,
appType: data.project!.template!,
commitHash: data.commitHash!,
repoUrl: recordData.repoUrl
});
// Update previous deployment with prod branch domain
// TODO: Fix unique constraint error for domain
@@ -489,9 +441,7 @@ export class Service {
const octokit = await this.getOctokit(user.id);
const [owner, repo] = project.repository.split('/');
const {
data: [latestCommit]
} = await octokit.rest.repos.listCommits({
const { data: [latestCommit] } = await octokit.rest.repos.listCommits({
owner,
repo,
sha: project.prodBranch,
@@ -528,10 +478,7 @@ export class Service {
owner,
repo,
config: {
url: new URL(
'api/github/webhook',
this.config.gitHubConfig.webhookUrl
).href,
url: new URL('api/github/webhook', this.config.gitHubConfig.webhookUrl).href,
content_type: 'json'
},
events: ['push']
@@ -539,13 +486,9 @@ export class Service {
} catch (err) {
// https://docs.github.com/en/rest/repos/webhooks?apiVersion=2022-11-28#create-a-repository-webhook--status-codes
if (
!(
err instanceof RequestError &&
err.status === 422 &&
(err.response?.data as any).errors.some(
(err: any) => err.message === GITHUB_UNIQUE_WEBHOOK_ERROR
)
)
!(err instanceof RequestError &&
err.status === 422 &&
(err.response?.data as any).errors.some((err: any) => err.message === GITHUB_UNIQUE_WEBHOOK_ERROR))
) {
throw err;
}
@@ -557,9 +500,7 @@ export class Service {
async handleGitHubPush (data: GitPushEventPayload): Promise<void> {
const { repository, ref, head_commit: headCommit } = data;
log(`Handling GitHub push event from repository: ${repository.full_name}`);
const projects = await this.db.getProjects({
where: { repository: repository.full_name }
});
const projects = await this.db.getProjects({ where: { repository: repository.full_name } });
if (!projects.length) {
log(`No projects found for repository ${repository.full_name}`);
@@ -571,29 +512,23 @@ export class Service {
for await (const project of projects) {
const octokit = await this.getOctokit(project.ownerId);
const [domain] = await this.db.getDomainsByProjectId(project.id, {
branch
});
const [domain] = await this.db.getDomainsByProjectId(project.id, { branch });
// Create deployment with branch and latest commit in GitHub data
await this.createDeployment(project.ownerId, octokit, {
project,
branch,
environment:
project.prodBranch === branch
? Environment.Production
: Environment.Preview,
domain,
commitHash: headCommit.id,
commitMessage: headCommit.message
});
await this.createDeployment(project.ownerId,
octokit,
{
project,
branch,
environment: project.prodBranch === branch ? Environment.Production : Environment.Preview,
domain,
commitHash: headCommit.id,
commitMessage: headCommit.message
});
}
}
async updateProject (
projectId: string,
data: DeepPartial<Project>
): Promise<boolean> {
async updateProject (projectId: string, data: DeepPartial<Project>): Promise<boolean> {
return this.db.updateProjectById(projectId, data);
}
@@ -610,9 +545,7 @@ export class Service {
});
if (domainsRedirectedFrom.length > 0) {
throw new Error(
'Cannot delete domain since it has redirects from other domains'
);
throw new Error('Cannot delete domain since it has redirects from other domains');
}
return this.db.deleteDomainById(domainId);
@@ -651,10 +584,7 @@ export class Service {
return newDeployment;
}
async rollbackDeployment (
projectId: string,
deploymentId: string
): Promise<boolean> {
async rollbackDeployment (projectId: string, deploymentId: string): Promise<boolean> {
// TODO: Implement transactions
const oldCurrentDeployment = await this.db.getDeployment({
relations: {
@@ -672,25 +602,16 @@ export class Service {
throw new Error('Current deployment doesnot exist');
}
const oldCurrentDeploymentUpdate = await this.db.updateDeploymentById(
oldCurrentDeployment.id,
{ isCurrent: false, domain: null }
);
const oldCurrentDeploymentUpdate = await this.db.updateDeploymentById(oldCurrentDeployment.id, { isCurrent: false, domain: null });
const newCurrentDeploymentUpdate = await this.db.updateDeploymentById(
deploymentId,
{ isCurrent: true, domain: oldCurrentDeployment?.domain }
);
const newCurrentDeploymentUpdate = await this.db.updateDeploymentById(deploymentId, { isCurrent: true, domain: oldCurrentDeployment?.domain });
return newCurrentDeploymentUpdate && oldCurrentDeploymentUpdate;
}
async addDomain (
projectId: string,
data: { name: string }
): Promise<{
primaryDomain: Domain;
redirectedDomain: Domain;
async addDomain (projectId: string, data: { name: string }): Promise<{
primaryDomain: Domain,
redirectedDomain: Domain
}> {
const currentProject = await this.db.getProjectById(projectId);
@@ -715,20 +636,12 @@ export class Service {
redirectTo: savedPrimaryDomain
};
const savedRedirectedDomain = await this.db.addDomain(
redirectedDomainDetails
);
const savedRedirectedDomain = await this.db.addDomain(redirectedDomainDetails);
return {
primaryDomain: savedPrimaryDomain,
redirectedDomain: savedRedirectedDomain
};
return { primaryDomain: savedPrimaryDomain, redirectedDomain: savedRedirectedDomain };
}
async updateDomain (
domainId: string,
data: DeepPartial<Domain>
): Promise<boolean> {
async updateDomain (domainId: string, data: DeepPartial<Domain>): Promise<boolean> {
const domain = await this.db.getDomain({
where: {
id: domainId
@@ -769,9 +682,7 @@ export class Service {
}
if (redirectedDomain.redirectToId) {
throw new Error(
'Unable to redirect to the domain because it is already redirecting elsewhere. Redirects cannot be chained.'
);
throw new Error('Unable to redirect to the domain because it is already redirecting elsewhere. Redirects cannot be chained.');
}
newDomain.redirectTo = redirectedDomain;
@@ -792,6 +703,48 @@ export class Service {
return { token };
}
async authenticateGit (type: GitType, code:string, user: User): Promise<{token: string}> {
let token: string;
switch (type) {
case GitType.GitHub:
({ authentication: { token } } = await this.oauthApp.createToken({
code
}));
break;
case GitType.Gitea: {
const response = await fetch(GITEA_ACCESS_TOKEN_ENDPOINT, {
method: 'post',
body: JSON.stringify({
// TODO: Fetch from config
client_id: '',
client_secret: '',
code,
grant_type: 'authorization_code',
// TODO: Get frontend app URL from config
redirect_uri: 'http://localhost:3000/organization/projects/create'
}),
headers: { 'Content-Type': 'application/json' }
});
assert(response.ok, `HTTP Error Response: ${response.status} ${response.statusText}`);
const data: any = await response.json();
({ access_token: token } = data);
break;
}
default: throw new Error(`Type ${type} not handled for Git authentication`);
}
assert(token, `Access token is not set for type ${type}`);
await this.db.updateUser(user, { gitHubToken: token });
return { token };
}
async unauthenticateGitHub (user: User, data: DeepPartial<User>): Promise<boolean> {
return this.db.updateUser(user, data);
}
+6 -1
View File
@@ -47,5 +47,10 @@ interface RegistryRecord {
}
export interface AppDeploymentRecord extends RegistryRecord {
attributes: AppDeploymentRecordAttributes;
attributes: AppDeploymentRecordAttributes
}
export enum GitType {
GitHub = 'GitHub',
Gitea = 'Gitea',
}
+2 -7
View File
@@ -37,15 +37,10 @@ export const getEntities = async (filePath: string): Promise<any> => {
return entities;
};
export const loadAndSaveData = async <Entity extends ObjectLiteral>(
entityType: EntityTarget<Entity>,
dataSource: DataSource,
entities: any,
relations?: any | undefined
): Promise<Entity[]> => {
export const loadAndSaveData = async <Entity extends ObjectLiteral>(entityType: EntityTarget<Entity>, dataSource: DataSource, entities: any, relations?: any | undefined): Promise<Entity[]> => {
const entityRepository = dataSource.getRepository(entityType);
const savedEntity: Entity[] = [];
const savedEntity:Entity[] = [];
for (const entityData of entities) {
let entity = entityRepository.create(entityData as DeepPartial<Entity>);
+1 -1
View File
@@ -18,4 +18,4 @@ const main = async () => {
deleteFile(config.database.dbPath);
};
main().catch((err) => log(err));
main().catch(err => log(err));
+20 -20
View File
@@ -1,9 +1,9 @@
[
{
"projectIndex": 0,
"domainIndex": 0,
"domainIndex":0,
"createdByIndex": 0,
"id": "ffhae3zq",
"id":"ffhae3zq",
"status": "Ready",
"environment": "Production",
"isCurrent": true,
@@ -18,9 +18,9 @@
},
{
"projectIndex": 0,
"domainIndex": 1,
"domainIndex":1,
"createdByIndex": 0,
"id": "vehagei8",
"id":"vehagei8",
"status": "Ready",
"environment": "Preview",
"isCurrent": false,
@@ -35,9 +35,9 @@
},
{
"projectIndex": 0,
"domainIndex": 2,
"domainIndex":2,
"createdByIndex": 0,
"id": "qmgekyte",
"id":"qmgekyte",
"status": "Ready",
"environment": "Development",
"isCurrent": false,
@@ -54,7 +54,7 @@
"projectIndex": 0,
"domainIndex": null,
"createdByIndex": 0,
"id": "f8wsyim6",
"id":"f8wsyim6",
"status": "Ready",
"environment": "Production",
"isCurrent": false,
@@ -69,9 +69,9 @@
},
{
"projectIndex": 1,
"domainIndex": 3,
"domainIndex":3,
"createdByIndex": 1,
"id": "eO8cckxk",
"id":"eO8cckxk",
"status": "Ready",
"environment": "Production",
"isCurrent": true,
@@ -86,9 +86,9 @@
},
{
"projectIndex": 1,
"domainIndex": 4,
"domainIndex":4,
"createdByIndex": 1,
"id": "yaq0t5yw",
"id":"yaq0t5yw",
"status": "Ready",
"environment": "Preview",
"isCurrent": false,
@@ -103,9 +103,9 @@
},
{
"projectIndex": 1,
"domainIndex": 5,
"domainIndex":5,
"createdByIndex": 1,
"id": "hwwr6sbx",
"id":"hwwr6sbx",
"status": "Ready",
"environment": "Development",
"isCurrent": false,
@@ -120,9 +120,9 @@
},
{
"projectIndex": 2,
"domainIndex": 9,
"domainIndex":9,
"createdByIndex": 2,
"id": "ndxje48a",
"id":"ndxje48a",
"status": "Ready",
"environment": "Production",
"isCurrent": true,
@@ -137,9 +137,9 @@
},
{
"projectIndex": 2,
"domainIndex": 7,
"domainIndex":7,
"createdByIndex": 2,
"id": "gtgpgvei",
"id":"gtgpgvei",
"status": "Ready",
"environment": "Preview",
"isCurrent": false,
@@ -154,9 +154,9 @@
},
{
"projectIndex": 2,
"domainIndex": 8,
"domainIndex":8,
"createdByIndex": 2,
"id": "b4bpthjr",
"id":"b4bpthjr",
"status": "Ready",
"environment": "Development",
"isCurrent": false,
@@ -173,7 +173,7 @@
"projectIndex": 3,
"domainIndex": 6,
"createdByIndex": 2,
"id": "b4bpthjr",
"id":"b4bpthjr",
"status": "Ready",
"environment": "Production",
"isCurrent": true,
+31 -9
View File
@@ -2,55 +2,77 @@
{
"memberIndex": 1,
"projectIndex": 0,
"permissions": ["View"],
"permissions": [
"View"
],
"isPending": false
},
{
"memberIndex": 2,
"projectIndex": 0,
"permissions": ["View", "Edit"],
"permissions": [
"View",
"Edit"
],
"isPending": false
},
{
"memberIndex": 2,
"projectIndex": 1,
"permissions": ["View"],
"permissions": [
"View"
],
"isPending": false
},
{
"memberIndex": 0,
"projectIndex": 2,
"permissions": ["View"],
"permissions": [
"View"
],
"isPending": false
},
{
"memberIndex": 1,
"projectIndex": 2,
"permissions": ["View", "Edit"],
"permissions": [
"View",
"Edit"
],
"isPending": false
},
{
"memberIndex": 0,
"projectIndex": 3,
"permissions": ["View"],
"permissions": [
"View"
],
"isPending": false
},
{
"memberIndex": 2,
"projectIndex": 3,
"permissions": ["View", "Edit"],
"permissions": [
"View",
"Edit"
],
"isPending": false
},
{
"memberIndex": 1,
"projectIndex": 4,
"permissions": ["View"],
"permissions": [
"View"
],
"isPending": false
},
{
"memberIndex": 2,
"projectIndex": 4,
"permissions": ["View", "Edit"],
"permissions": [
"View",
"Edit"
],
"isPending": false
}
]
+18 -80
View File
@@ -10,12 +10,7 @@ import { EnvironmentVariable } from '../src/entity/EnvironmentVariable';
import { Domain } from '../src/entity/Domain';
import { ProjectMember } from '../src/entity/ProjectMember';
import { Deployment } from '../src/entity/Deployment';
import {
checkFileExists,
getConfig,
getEntities,
loadAndSaveData
} from '../src/utils';
import { checkFileExists, getConfig, getEntities, loadAndSaveData } from '../src/utils';
import { Config } from '../src/config';
import { DEFAULT_CONFIG_FILE_PATH } from '../src/constants';
@@ -32,34 +27,19 @@ const ENVIRONMENT_VARIABLE_DATA_PATH = './fixtures/environment-variables.json';
const REDIRECTED_DOMAIN_DATA_PATH = './fixtures/redirected-domains.json';
const generateTestData = async (dataSource: DataSource) => {
const userEntities = await getEntities(
path.resolve(__dirname, USER_DATA_PATH)
);
const userEntities = await getEntities(path.resolve(__dirname, USER_DATA_PATH));
const savedUsers = await loadAndSaveData(User, dataSource, userEntities);
const orgEntities = await getEntities(
path.resolve(__dirname, ORGANIZATION_DATA_PATH)
);
const savedOrgs = await loadAndSaveData(
Organization,
dataSource,
orgEntities
);
const orgEntities = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
const savedOrgs = await loadAndSaveData(Organization, dataSource, orgEntities);
const projectRelations = {
owner: savedUsers,
organization: savedOrgs
};
const projectEntities = await getEntities(
path.resolve(__dirname, PROJECT_DATA_PATH)
);
const savedProjects = await loadAndSaveData(
Project,
dataSource,
projectEntities,
projectRelations
);
const projectEntities = await getEntities(path.resolve(__dirname, PROJECT_DATA_PATH));
const savedProjects = await loadAndSaveData(Project, dataSource, projectEntities, projectRelations);
const domainRepository = dataSource.getRepository(Domain);
@@ -67,30 +47,16 @@ const generateTestData = async (dataSource: DataSource) => {
project: savedProjects
};
const primaryDomainsEntities = await getEntities(
path.resolve(__dirname, PRIMARY_DOMAIN_DATA_PATH)
);
const savedPrimaryDomains = await loadAndSaveData(
Domain,
dataSource,
primaryDomainsEntities,
domainPrimaryRelations
);
const primaryDomainsEntities = await getEntities(path.resolve(__dirname, PRIMARY_DOMAIN_DATA_PATH));
const savedPrimaryDomains = await loadAndSaveData(Domain, dataSource, primaryDomainsEntities, domainPrimaryRelations);
const domainRedirectedRelations = {
project: savedProjects,
redirectTo: savedPrimaryDomains
};
const redirectDomainsEntities = await getEntities(
path.resolve(__dirname, REDIRECTED_DOMAIN_DATA_PATH)
);
await loadAndSaveData(
Domain,
dataSource,
redirectDomainsEntities,
domainRedirectedRelations
);
const redirectDomainsEntities = await getEntities(path.resolve(__dirname, REDIRECTED_DOMAIN_DATA_PATH));
await loadAndSaveData(Domain, dataSource, redirectDomainsEntities, domainRedirectedRelations);
const savedDomains = await domainRepository.find();
@@ -99,30 +65,16 @@ const generateTestData = async (dataSource: DataSource) => {
organization: savedOrgs
};
const userOrganizationsEntities = await getEntities(
path.resolve(__dirname, USER_ORGANIZATION_DATA_PATH)
);
await loadAndSaveData(
UserOrganization,
dataSource,
userOrganizationsEntities,
userOrganizationRelations
);
const userOrganizationsEntities = await getEntities(path.resolve(__dirname, USER_ORGANIZATION_DATA_PATH));
await loadAndSaveData(UserOrganization, dataSource, userOrganizationsEntities, userOrganizationRelations);
const projectMemberRelations = {
member: savedUsers,
project: savedProjects
};
const projectMembersEntities = await getEntities(
path.resolve(__dirname, PROJECT_MEMBER_DATA_PATH)
);
await loadAndSaveData(
ProjectMember,
dataSource,
projectMembersEntities,
projectMemberRelations
);
const projectMembersEntities = await getEntities(path.resolve(__dirname, PROJECT_MEMBER_DATA_PATH));
await loadAndSaveData(ProjectMember, dataSource, projectMembersEntities, projectMemberRelations);
const deploymentRelations = {
project: savedProjects,
@@ -130,29 +82,15 @@ const generateTestData = async (dataSource: DataSource) => {
createdBy: savedUsers
};
const deploymentsEntities = await getEntities(
path.resolve(__dirname, DEPLOYMENT_DATA_PATH)
);
await loadAndSaveData(
Deployment,
dataSource,
deploymentsEntities,
deploymentRelations
);
const deploymentsEntities = await getEntities(path.resolve(__dirname, DEPLOYMENT_DATA_PATH));
await loadAndSaveData(Deployment, dataSource, deploymentsEntities, deploymentRelations);
const environmentVariableRelations = {
project: savedProjects
};
const environmentVariablesEntities = await getEntities(
path.resolve(__dirname, ENVIRONMENT_VARIABLE_DATA_PATH)
);
await loadAndSaveData(
EnvironmentVariable,
dataSource,
environmentVariablesEntities,
environmentVariableRelations
);
const environmentVariablesEntities = await getEntities(path.resolve(__dirname, ENVIRONMENT_VARIABLE_DATA_PATH));
await loadAndSaveData(EnvironmentVariable, dataSource, environmentVariablesEntities, environmentVariableRelations);
};
const main = async () => {
+2 -10
View File
@@ -21,20 +21,12 @@ async function main () {
const bondId = await registry.getNextBondId(registryConfig.privateKey);
log('bondId:', bondId);
await registry.createBond(
{ denom: DENOM, amount: BOND_AMOUNT },
registryConfig.privateKey,
registryConfig.fee
);
await registry.createBond({ denom: DENOM, amount: BOND_AMOUNT }, registryConfig.privateKey, registryConfig.fee);
for await (const name of authorityNames) {
await registry.reserveAuthority({ name }, registryConfig.privateKey, registryConfig.fee);
log('Reserved authority name:', name);
await registry.setAuthorityBond(
{ name, bondId },
registryConfig.privateKey,
registryConfig.fee
);
await registry.setAuthorityBond({ name, bondId }, registryConfig.privateKey, registryConfig.fee);
log(`Bond ${bondId} set for authority ${name}`);
}
}
@@ -14,11 +14,7 @@ const log = debug('snowball:publish-deploy-records');
async function main () {
const { registryConfig, database, misc } = await getConfig<Config>(DEFAULT_CONFIG_FILE_PATH);
const registry = new Registry(
registryConfig.gqlEndpoint,
registryConfig.restEndpoint,
registryConfig.chainId
);
const registry = new Registry(registryConfig.gqlEndpoint, registryConfig.restEndpoint, registryConfig.chainId);
const dataSource = new DataSource({
type: 'better-sqlite3',
-99
View File
@@ -1,99 +0,0 @@
# deployer
- Install dependencies
```bash
yarn
```
```bash
brew install jq # if you do not have jq installed already
```
Example of how to make the necessary deploy edits [here](https://github.com/snowball-tools/snowballtools-base/pull/131/files).
- Replace variables in the following files
- [records/application-deployment-request.yml](records/application-deployment-request.yml)
- update the name & application version numbers
- `<CURRENT_DATE_TIME>`: Replace with current time which can be generated by command `date -u`
```yml
# Example
record:
...
meta:
note: Added by Snowball @ Friday 23 February 2024 06:35:50 AM UTC
...
```
- Update record version in [records/application-record.yml](records/application-record.yml)
```yml
record:
type: ApplicationRecord
version: <NEW_VERSION>
...
```
- Update commit hash in the following places:
- [records/application-record.yml](records/application-record.yml)
```yml
record:
...
repository_ref: <COMMIT_HASH>
...
```
- [records/application-deployment-request.yml](records/application-deployment-request.yml)
```yml
record:
...
meta:
...
repository_ref: <COMMIT_HASH>
```
- [deploy-frontend.sh](deploy-frontend.sh)
Also be sure to update the app version
```bash
...
RCD_APP_VERSION="<NEW_VERSION>"
REPO_REF="<COMMIT_HASH>"
...
```
- Run script to deploy app
```
./deploy-frontend.sh
```
- Commit the updated [ApplicationRecord](records/application-record.yml) and [ApplicationDeploymentRequest](records/application-deployment-request.yml) files to the repository
## Notes
- Any config env can be updated in [records/application-deployment-request.yml](records/application-deployment-request.yml)
```yml
record:
...
config:
env:
LACONIC_HOSTED_CONFIG_app_server_url: https://snowballtools-base-api-001.apps.snowballtools.com
...
```
- On changing `LACONIC_HOSTED_CONFIG_app_github_clientid`, the GitHub client ID and secret need to be changed in backend config too
## Troubleshoot
- Check deployment status [here](https://console.laconic.com/deployer).
- Check records [here](https://console.laconic.com/#/registry).
- If deployment fails due to low bond balance
- Check balances
```bash
# Account balance
yarn laconic cns account get
# Bond balance
yarn laconic cns bond get --id 8fcf44b2f326b4b63ac57547777f1c78b7d494e5966e508f09001af53cb440ac
```
- Command to refill bond
```bash
yarn laconic cns bond refill --id 8fcf44b2f326b4b63ac57547777f1c78b7d494e5966e508f09001af53cb440ac --type aphoton --quantity 10000000
```
-9
View File
@@ -1,9 +0,0 @@
services:
cns:
restEndpoint: http://console.laconic.com:1317
gqlEndpoint: http://console.laconic.com:9473/api
chainId: laconic_9000-1
gas: 1000000
fees: 200000aphoton
userKey: 0524fc22ea0a12e6c5cc4cfe08e73c95dffd0ab5ed72a59f459ed33134fa3b16
bondId: 8fcf44b2f326b4b63ac57547777f1c78b7d494e5966e508f09001af53cb440ac
-35
View File
@@ -1,35 +0,0 @@
#!/bin/bash
# Reference: https://git.vdb.to/cerc-io/test-progressive-web-app/src/branch/main/scripts
RECORD_FILE=records/application-record.yml
CONFIG_FILE=config.yml
RCD_APP_VERSION="0.1.3"
REPO_REF="513ca69d01bee857cf207a0605483205b384e218"
# Publish ApplicationRecord
RECORD_ID=$(yarn --silent laconic -c $CONFIG_FILE cns record publish --filename $RECORD_FILE | jq -r '.id')
echo "ApplicationRecord published"
echo $RECORD_ID
# Set name to record
REGISTRY_APP_CRN="crn://snowballtools/applications/snowballtools-base-frontend"
yarn --silent laconic -c $CONFIG_FILE cns name set "$REGISTRY_APP_CRN@${RCD_APP_VERSION}" "$RECORD_ID"
yarn --silent laconic -c $CONFIG_FILE cns name set "$REGISTRY_APP_CRN@${REPO_REF}" "$RECORD_ID"
# Set name if latest release
yarn --silent laconic -c $CONFIG_FILE cns name set "$REGISTRY_APP_CRN" "$RECORD_ID"
echo "$REGISTRY_APP_CRN set for ApplicationRecord"
# Check if record found for REGISTRY_APP_CRN
APP_RECORD=$(yarn --silent laconic -c $CONFIG_FILE cns name resolve "$REGISTRY_APP_CRN" | jq '.[0]')
if [ -z "$APP_RECORD" ] || [ "null" == "$APP_RECORD" ]; then
echo "No record found for $REGISTRY_APP_CRN."
exit 1
fi
RECORD_FILE=records/application-deployment-request.yml
DEPLOYMENT_REQUEST_ID=$(yarn --silent laconic -c $CONFIG_FILE cns record publish --filename $RECORD_FILE | jq -r '.id')
echo "ApplicationDeploymentRequest published"
echo $DEPLOYMENT_REQUEST_ID
-9
View File
@@ -1,9 +0,0 @@
{
"name": "deployer",
"version": "1.0.0",
"main": "index.js",
"private": true,
"devDependencies": {
"@cerc-io/laconic-registry-cli": "^0.1.10"
}
}
@@ -1,21 +0,0 @@
record:
type: ApplicationDeploymentRequest
version: '1.0.0'
name: snowballtools-base-frontend@0.1.3
application: crn://snowballtools/applications/snowballtools-base-frontend@0.1.3
dns: dashboard
config:
env:
LACONIC_HOSTED_CONFIG_app_server_url: https://snowballtools-base-api-001.apps.snowballtools.com
# If GitHub client ID is changed, same ID and corresponding secret has to be set in backend config
LACONIC_HOSTED_CONFIG_app_github_clientid: b7c63b235ca1dd5639ab
LACONIC_HOSTED_CONFIG_app_github_templaterepo: snowball-tools-platform/test-progressive-web-app
# New config env after changes for image upload PWA
LACONIC_HOSTED_CONFIG_app_github_pwa_templaterepo: snowball-tools-platform/test-progressive-web-app
LACONIC_HOSTED_CONFIG_app_github_image_upload_templaterepo: snowball-tools-platform/image-upload-pwa-example
LACONIC_HOSTED_CONFIG_app_wallet_connect_id: eda9ba18042a5ea500f358194611ece2
meta:
# Set CURRENT_DATE_TIME; Use command date -u
note: Added by Snowball @ Tue Feb 27 17:24:06 UTC 2024
repository: "https://git.vdb.to/cerc-io/snowballtools-base"
repository_ref: 513ca69d01bee857cf207a0605483205b384e218
@@ -1,10 +0,0 @@
record:
type: ApplicationRecord
version: 0.0.11
repository_ref: 513ca69d01bee857cf207a0605483205b384e218
repository: ["https://git.vdb.to/cerc-io/snowballtools-base"]
app_type: webapp
# name is set to repo name
name: snowballtools-base-frontend
# app_version is set from package.json
app_version: 0.1.3
+3 -2
View File
@@ -1,7 +1,8 @@
REACT_APP_SERVER_URL = 'http://localhost:8000'
REACT_APP_GITHUB_CLIENT_ID =
REACT_APP_GITHUB_PWA_TEMPLATE_REPO =
REACT_APP_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO =
REACT_APP_GITHUB_TEMPLATE_REPO =
REACT_APP_GITEA_CLIENT_ID =
REACT_APP_WALLET_CONNECT_ID =
-7
View File
@@ -1,7 +0,0 @@
REACT_APP_SERVER_URL = 'http://localhost:8000'
REACT_APP_GITHUB_CLIENT_ID =
REACT_APP_GITHUB_PWA_TEMPLATE_REPO =
REACT_APP_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO =
REACT_APP_WALLET_CONNECT_ID =
+1 -6
View File
@@ -16,10 +16,5 @@
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"settings": {
"react": {
"version": "detect"
}
}
]
}
-1
View File
@@ -13,7 +13,6 @@
# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
+4 -17
View File
@@ -1,19 +1,9 @@
{
"name": "frontend",
"version": "0.1.3",
"version": "0.1.0",
"private": true,
"dependencies": {
"@fontsource-variable/jetbrains-mono": "^5.0.19",
"@fontsource/inter": "^5.0.16",
"@material-tailwind/react": "^2.1.7",
"@radix-ui/react-avatar": "^1.0.4",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-radio-group": "^1.1.3",
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.4",
"@radix-ui/react-toast": "^1.1.5",
"@radix-ui/react-tooltip": "^1.0.7",
"@tanstack/react-query": "^5.22.2",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
@@ -26,15 +16,13 @@
"@web3modal/wagmi": "^4.0.5",
"assert": "^2.1.0",
"axios": "^1.6.7",
"clsx": "^2.1.0",
"date-fns": "^3.3.1",
"downshift": "^8.3.2",
"date-fns": "^3.0.1",
"downshift": "^8.2.3",
"eslint-config-react-app": "^7.0.1",
"gql-client": "^1.0.0",
"luxon": "^3.4.4",
"octokit": "^3.1.2",
"react": "^18.2.0",
"react-calendar": "^4.8.0",
"react-code-blocks": "^0.1.6",
"react-day-picker": "^8.9.1",
"react-dom": "^18.2.0",
@@ -46,7 +34,6 @@
"react-scripts": "5.0.1",
"react-timer-hook": "^3.0.7",
"siwe": "^2.1.4",
"tailwind-variants": "^0.2.0",
"typescript": "^4.9.5",
"usehooks-ts": "^2.10.0",
"vertical-stepper-nav": "^1.0.2",
@@ -91,6 +78,6 @@
"eslint-plugin-prettier": "^5.0.1",
"eslint-plugin-react": "^7.33.2",
"prettier": "^3.1.0",
"tailwindcss": "^3.4.1"
"tailwindcss": "^3.3.6"
}
}
+10 -21
View File
@@ -3,29 +3,18 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="snowball tools dashboard" />
<meta
name="description"
content="snowball tools dashboard"
/>
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link
rel="apple-touch-icon"
sizes="180x180"
href="%PUBLIC_URL%/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="%PUBLIC_URL%/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="%PUBLIC_URL%/favicon-16x16.png"
/>
<link rel="manifest" href="%PUBLIC_URL%/site.webmanifest" />
<meta name="msapplication-TileColor" content="#2d89ef" />
<meta name="theme-color" content="#ffffff" />
<link rel="apple-touch-icon" sizes="180x180" href="%PUBLIC_URL%/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/favicon-16x16.png">
<link rel="manifest" href="%PUBLIC_URL%/site.webmanifest">
<meta name="msapplication-TileColor" content="#2d89ef">
<meta name="theme-color" content="#ffffff">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>Snowball</title>
</head>
-1
View File
@@ -1 +0,0 @@
<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="500" height="500" fill="#0F86F5"/><path fill-rule="evenodd" clip-rule="evenodd" d="M191.873 125.126C224.893 126.765 250.458 150.121 274.042 172.995C297.925 196.158 323.089 221.108 324.868 254.114C326.718 288.42 308.902 321.108 283.281 344.355C258.67 366.687 225.288 373.859 191.873 374.788C157.228 375.752 119.038 374.394 95.1648 349.588C71.6207 325.125 74.6696 287.843 75.7341 254.114C76.7518 221.865 79.2961 188.525 101.009 164.41C123.845 139.047 157.543 123.423 191.873 125.126Z" fill="#4BA4F7"/><path fill-rule="evenodd" clip-rule="evenodd" d="M229.373 125.126C262.393 126.765 287.958 150.121 311.542 172.995C335.425 196.158 360.589 221.108 362.368 254.114C364.218 288.42 346.402 321.108 320.781 344.355C296.17 366.687 262.788 373.859 229.373 374.788C194.728 375.752 156.538 374.394 132.665 349.588C109.121 325.125 112.17 287.843 113.234 254.114C114.252 221.865 116.796 188.525 138.509 164.41C161.345 139.047 195.043 123.423 229.373 125.126Z" fill="#8AC4FA"/><path fill-rule="evenodd" clip-rule="evenodd" d="M266.873 125.126C299.893 126.765 325.458 150.121 349.042 172.995C372.925 196.158 398.089 221.108 399.868 254.114C401.718 288.42 383.902 321.108 358.281 344.355C333.67 366.687 300.288 373.859 266.873 374.788C232.228 375.752 194.038 374.394 170.165 349.588C146.621 325.125 149.67 287.843 150.734 254.114C151.752 221.865 154.296 188.525 176.009 164.41C198.845 139.047 232.543 123.423 266.873 125.126Z" fill="#CAE4FD"/><path fill-rule="evenodd" clip-rule="evenodd" d="M304.373 125.126C337.393 126.765 362.958 150.121 386.542 172.995C410.425 196.158 435.589 221.108 437.368 254.114C439.218 288.42 421.402 321.108 395.781 344.355C371.17 366.687 337.788 373.859 304.373 374.788C269.728 375.752 231.538 374.394 207.665 349.588C184.121 325.125 187.17 287.843 188.234 254.114C189.252 221.865 191.796 188.525 213.509 164.41C236.345 139.047 270.043 123.423 304.373 125.126Z" fill="white"/></svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

+17 -17
View File
@@ -1,19 +1,19 @@
{
"name": "Snowball Tools Dashboard",
"short_name": "snowball tools",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
"name": "Snowball Tools Dashboard",
"short_name": "snowball tools",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}
-10
View File
@@ -1,10 +0,0 @@
<svg width="333" height="5" viewBox="0 0 333 5" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 4L6.39555 1.30714C8.38078 0.47125 10.6192 0.47125 12.6045 1.30714L15.8955 2.69286C17.8808 3.52875 20.1192 3.52875 22.1045 2.69286L25.3955 1.30714C27.3808 0.47125 29.6192 0.47125 31.6045 1.30714L34.8955 2.69286C36.8808 3.52875 39.1192 3.52875 41.1045 2.69286L44.3955 1.30714C46.3808 0.47125 48.6192 0.47125 50.6045 1.30714L53.8955 2.69286C55.8808 3.52875 58.1192 3.52875 60.1045 2.69286L63.3955 1.30714C65.3808 0.47125 67.6192 0.47125 69.6045 1.30714L72.8955 2.69286C74.8808 3.52875 77.1192 3.52875 79.1045 2.69286L82.3955 1.30714C84.3808 0.47125 86.6192 0.47125 88.6045 1.30714L91.8955 2.69286C93.8808 3.52875 96.1192 3.52875 98.1045 2.69286L101.396 1.30714C103.381 0.47125 105.619 0.47125 107.604 1.30714L110.896 2.69286C112.881 3.52875 115.119 3.52875 117.104 2.69286L120.396 1.30714C122.381 0.47125 124.619 0.47125 126.604 1.30714L129.896 2.69286C131.881 3.52875 134.119 3.52875 136.104 2.69286L139.396 1.30714C141.381 0.47125 143.619 0.47125 145.604 1.30714L148.896 2.69286C150.881 3.52875 153.119 3.52875 155.104 2.69286L158.396 1.30714C160.381 0.47125 162.619 0.47125 164.604 1.30714L167.896 2.69286C169.881 3.52875 172.119 3.52875 174.104 2.69286L177.396 1.30714C179.381 0.47125 181.619 0.47125 183.604 1.30714L186.896 2.69286C188.881 3.52875 191.119 3.52875 193.104 2.69286L196.396 1.30714C198.381 0.47125 200.619 0.47125 202.604 1.30714L205.896 2.69286C207.881 3.52875 210.119 3.52875 212.104 2.69286L215.396 1.30714C217.381 0.47125 219.619 0.47125 221.604 1.30714L224.896 2.69286C226.881 3.52875 229.119 3.52875 231.104 2.69286L234.396 1.30714C236.381 0.47125 238.619 0.47125 240.604 1.30714L243.896 2.69286C245.881 3.52875 248.119 3.52875 250.104 2.69286L253.396 1.30714C255.381 0.47125 257.619 0.47125 259.604 1.30714L262.896 2.69286C264.881 3.52875 267.119 3.52875 269.104 2.69286L272.396 1.30714C274.381 0.47125 276.619 0.47125 278.604 1.30714L281.896 2.69286C283.881 3.52875 286.119 3.52875 288.104 2.69286L291.396 1.30714C293.381 0.47125 295.619 0.47125 297.604 1.30714L300.896 2.69286C302.881 3.52875 305.119 3.52875 307.104 2.69286L310.396 1.30714C312.381 0.47125 314.619 0.47125 316.604 1.30714L319.973 2.72566C321.913 3.54216 324.095 3.56183 326.049 2.78039L330.029 1.18845C331.936 0.425535 334.064 0.425535 335.971 1.18845L343 4" stroke="#DBEBF9"/>
<path d="M6.39555 1.30714L0 4H342.5L336.027 1.27434C334.087 0.457837 331.905 0.438174 329.951 1.21961L326.049 2.78039C324.095 3.56183 321.913 3.54216 319.973 2.72566L316.604 1.30714C314.619 0.47125 312.381 0.47125 310.396 1.30714L307.104 2.69286C305.119 3.52875 302.881 3.52875 300.896 2.69286L297.604 1.30714C295.619 0.47125 293.381 0.47125 291.396 1.30714L288.104 2.69286C286.119 3.52875 283.881 3.52875 281.896 2.69286L278.604 1.30714C276.619 0.47125 274.381 0.47125 272.396 1.30714L269.104 2.69286C267.119 3.52875 264.881 3.52875 262.896 2.69286L259.604 1.30714C257.619 0.47125 255.381 0.47125 253.396 1.30714L250.104 2.69286C248.119 3.52875 245.881 3.52875 243.896 2.69286L240.604 1.30714C238.619 0.47125 236.381 0.47125 234.396 1.30714L231.104 2.69286C229.119 3.52875 226.881 3.52875 224.896 2.69286L221.604 1.30714C219.619 0.47125 217.381 0.47125 215.396 1.30714L212.104 2.69286C210.119 3.52875 207.881 3.52875 205.896 2.69286L202.604 1.30714C200.619 0.47125 198.381 0.47125 196.396 1.30714L193.104 2.69286C191.119 3.52875 188.881 3.52875 186.896 2.69286L183.604 1.30714C181.619 0.47125 179.381 0.47125 177.396 1.30714L174.104 2.69286C172.119 3.52875 169.881 3.52875 167.896 2.69286L164.604 1.30714C162.619 0.47125 160.381 0.47125 158.396 1.30714L155.104 2.69286C153.119 3.52875 150.881 3.52875 148.896 2.69286L145.604 1.30714C143.619 0.47125 141.381 0.47125 139.396 1.30714L136.104 2.69286C134.119 3.52875 131.881 3.52875 129.896 2.69286L126.604 1.30714C124.619 0.47125 122.381 0.47125 120.396 1.30714L117.104 2.69286C115.119 3.52875 112.881 3.52875 110.896 2.69286L107.604 1.30714C105.619 0.47125 103.381 0.47125 101.396 1.30714L98.1045 2.69286C96.1192 3.52875 93.8808 3.52875 91.8955 2.69286L88.6045 1.30714C86.6192 0.47125 84.3808 0.47125 82.3955 1.30714L79.1045 2.69286C77.1192 3.52875 74.8808 3.52875 72.8955 2.69286L69.6045 1.30714C67.6192 0.47125 65.3808 0.47125 63.3955 1.30714L60.1045 2.69286C58.1192 3.52875 55.8808 3.52875 53.8955 2.69286L50.6045 1.30714C48.6192 0.47125 46.3808 0.47125 44.3955 1.30714L41.1045 2.69286C39.1192 3.52875 36.8808 3.52875 34.8955 2.69286L31.6045 1.30714C29.6192 0.47125 27.3808 0.47125 25.3955 1.30714L22.1045 2.69286C20.1192 3.52875 17.8808 3.52875 15.8955 2.69286L12.6045 1.30714C10.6192 0.47125 8.38078 0.47125 6.39555 1.30714Z" fill="url(#paint0_linear_1729_11298)"/>
<defs>
<linearGradient id="paint0_linear_1729_11298" x1="171.25" y1="0" x2="171.25" y2="4" gradientUnits="userSpaceOnUse">
<stop stop-color="#E6F4FF"/>
<stop offset="1" stop-color="#F9FCFF"/>
</linearGradient>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 4.8 KiB

@@ -0,0 +1,27 @@
[
{
"id": "1",
"name": "Progressive Web App (PWA)",
"icon": "^"
},
{
"id": "2",
"name": "Kotlin",
"icon": "^"
},
{
"id": "3",
"name": "React Native",
"icon": "^"
},
{
"id": "4",
"name": "Swift",
"icon": "^"
},
{
"id": "5",
"name": "Web app",
"icon": "^"
}
]
-32
View File
@@ -1,32 +0,0 @@
export default [
{
id: '1',
name: 'Progressive Web App (PWA)',
icon: '^',
repoFullName: `${process.env.REACT_APP_GITHUB_PWA_TEMPLATE_REPO}`,
},
{
id: '2',
name: 'Image Upload PWA',
icon: '^',
repoFullName: `${process.env.REACT_APP_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO}`,
},
{
id: '3',
name: 'Kotlin',
icon: '^',
repoFullName: '',
},
{
id: '4',
name: 'React Native',
icon: '^',
repoFullName: '',
},
{
id: '5',
name: 'Swift',
icon: '^',
repoFullName: '',
},
];
@@ -126,8 +126,7 @@ const DatePicker = ({
crossOrigin={undefined}
/>
</PopoverHandler>
{/* TODO: Figure out what placeholder is for */}
<PopoverContent placeholder={''}>
<PopoverContent>
{mode === 'single' && (
<DayPicker
mode="single"
@@ -146,23 +145,19 @@ const DatePicker = ({
/>
<HorizontalLine />
<div className="flex justify-end">
{/* TODO: Figure out what placeholder is for */}
<Button
size="sm"
className="rounded-full mr-2"
variant="outlined"
onClick={() => setIsOpen(false)}
placeholder={''}
>
Cancel
</Button>
{/* TODO: Figure out what placeholder is for */}
<Button
size="sm"
className="rounded-full"
color="gray"
onClick={() => handleRangeSelect()}
placeholder={''}
>
Select
</Button>
@@ -1,7 +1,7 @@
import React from 'react';
const HorizontalLine = () => {
return <hr className="h-px bg-gray-100 border-0" />;
return <hr className="h-px bg-gray-300 border-0" />;
};
export default HorizontalLine;
+16 -6
View File
@@ -1,23 +1,33 @@
import React, { forwardRef, RefAttributes } from 'react';
import { SearchIcon } from './shared/CustomIcon';
import { Input, InputProps } from './shared/Input';
import { Input, InputProps } from '@material-tailwind/react';
const SearchBar: React.ForwardRefRenderFunction<
HTMLInputElement,
InputProps & RefAttributes<HTMLInputElement>
> = ({ value, onChange, placeholder = 'Search', ...props }) => {
> = ({ value, onChange, placeholder = 'Search', ...props }, ref) => {
return (
<div className="relative flex w-full">
<div className="relative flex w-full gap-2">
<Input
leftIcon={<SearchIcon />}
onChange={onChange}
value={value}
type="search"
placeholder={placeholder}
appearance={'borderless'}
containerProps={{
className: 'min-w-[288px]',
}}
className="!border-t-blue-gray-300 pl-9 placeholder:text-blue-gray-300 focus:!border-blue-gray-300"
labelProps={{
className: 'before:content-none after:content-none',
}}
// TODO: Debug issue: https://github.com/creativetimofficial/material-tailwind/issues/427
crossOrigin={undefined}
{...props}
inputRef={ref}
/>
<div className="!absolute left-3 top-[13px]">
<i>^</i>
</div>
</div>
);
};
+36 -83
View File
@@ -2,20 +2,11 @@ import React, { useCallback, useEffect, useState } from 'react';
import { Link, NavLink, useNavigate, useParams } from 'react-router-dom';
import { Organization } from 'gql-client';
import { Option } from '@material-tailwind/react';
import { Typography, Option } from '@material-tailwind/react';
import { useDisconnect } from 'wagmi';
import { useGQLClient } from '../context/GQLClientContext';
import AsyncSelect from './shared/AsyncSelect';
import {
ChevronGrabberHorizontal,
FolderIcon,
GlobeIcon,
LifeBuoyIcon,
QuestionMarkRoundIcon,
SettingsSlidersIcon,
} from './shared/CustomIcon';
import { Tabs } from 'components/shared/Tabs';
const Sidebar = () => {
const { orgSlug } = useParams();
@@ -42,99 +33,61 @@ const Sidebar = () => {
}, [disconnect, navigate]);
return (
<div className="flex flex-col h-full p-4 pt-10">
<div className="flex flex-col h-full p-4">
<div className="grow">
<Link to={`/${orgSlug}`}>
<div className="flex items-center space-x-3 mb-10 ml-2">
<img
src="/logo.svg"
alt="Snowball Logo"
className="h-8 w-8 rounded-lg"
/>
<span className="text-2xl font-bold text-snowball-900">
Snowball
</span>
</div>
</Link>
<div>
<Link to={`/${orgSlug}`}>
<h3 className="text-black text-2xl">Snowball</h3>
</Link>
</div>
<AsyncSelect
containerProps={{ className: 'h-14 border-none' }}
labelProps={{ className: 'before:border-none after:border-none' }}
className="bg-white rounded-lg shadow border-none"
className="bg-white py-2"
value={selectedOrgSlug}
onChange={(value) => {
setSelectedOrgSlug(value!);
navigate(`/${value}`);
}}
selected={(_, index) => (
<div className="flex items-center space-x-3">
<img
src="/logo.svg"
alt="Application Logo"
className="h-8 w-8 rounded-lg"
/>
<div className="flex gap-2">
<div>^</div>
<div>
<div className="text-sm font-semibold">
{organizations[index!]?.name}
</div>
<div className="text-xs text-gray-500">Organization</div>
<span>{organizations[index!]?.name}</span>
<Typography>Organization</Typography>
</div>
</div>
)}
arrow={<ChevronGrabberHorizontal className="h-4 w-4 text-gray-500" />}
>
{/* TODO: Show label organization and manage in option */}
{organizations.map((org) => (
<Option key={org.id} value={org.slug}>
<div className="flex items-center space-x-3">
<img
src="/logo.svg"
alt="Application Logo"
className="h-8 w-8 rounded-lg"
/>
<div>
<div className="text-sm font-semibold">{org.name}</div>
<div className="text-xs text-gray-500">Organization</div>
</div>
</div>
^ {org.name}
{org.slug === selectedOrgSlug && <p className="float-right">^</p>}
</Option>
))}
</AsyncSelect>
<Tabs defaultValue="Projects" orientation="vertical" className="mt-10">
<Tabs.List>
{[
{ title: 'Projects', url: `/${orgSlug}/`, icon: <FolderIcon /> },
{
title: 'Settings',
url: `/${orgSlug}/settings`,
icon: <SettingsSlidersIcon />,
},
].map(({ title, icon, url }, index) => (
<NavLink to={url} key={index}>
<Tabs.Trigger icon={icon} value={title}>
{title}
</Tabs.Trigger>
</NavLink>
))}
</Tabs.List>
</Tabs>
<div>
<NavLink
to={`/${orgSlug}`}
className={({ isActive }) => (isActive ? 'text-blue-500' : '')}
>
<Typography>Projects</Typography>
</NavLink>
</div>
<div>
<NavLink
to={`/${orgSlug}/settings`}
className={({ isActive }) => (isActive ? 'text-blue-500' : '')}
>
<Typography>Settings</Typography>
</NavLink>
</div>
</div>
<div className="grow flex flex-col justify-end mb-8">
<Tabs defaultValue="Projects" orientation="vertical">
{/* TODO: use proper link buttons */}
<Tabs.List>
<Tabs.Trigger icon={<GlobeIcon />} value="">
<a className="cursor-pointer" onClick={handleLogOut}>
Log Out
</a>
</Tabs.Trigger>
<Tabs.Trigger icon={<QuestionMarkRoundIcon />} value="">
<a className="cursor-pointer">Documentation</a>
</Tabs.Trigger>
<Tabs.Trigger icon={<LifeBuoyIcon />} value="">
<a className="cursor-pointer">Support</a>
</Tabs.Trigger>
</Tabs.List>
</Tabs>
<div className="grow flex flex-col justify-end">
<a className="cursor-pointer" onClick={handleLogOut}>
Log Out
</a>
<a className="cursor-pointer">Documentation</a>
<a className="cursor-pointer">Support</a>
</div>
</div>
);
@@ -0,0 +1,65 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { Project } from 'gql-client';
import {
Menu,
MenuHandler,
MenuList,
MenuItem,
Typography,
Avatar,
} from '@material-tailwind/react';
import { relativeTimeMs } from '../../utils/time';
interface ProjectCardProps {
project: Project;
}
const ProjectCard: React.FC<ProjectCardProps> = ({ project }) => {
return (
<div className="bg-white border border-gray-200 rounded-lg shadow">
<div className="flex gap-2 p-2 items-center">
<Avatar variant="rounded" src={project.icon || '/gray.png'} />
<div className="grow">
<Link to={`projects/${project.id}`}>
<Typography>{project.name}</Typography>
<Typography color="gray" variant="small">
{project.deployments[0]?.domain?.name ??
'No Production Deployment'}
</Typography>
</Link>
</div>
<Menu placement="bottom-end">
<MenuHandler>
<button>...</button>
</MenuHandler>
<MenuList>
<MenuItem>^ Project settings</MenuItem>
<MenuItem className="text-red-500">^ Delete project</MenuItem>
</MenuList>
</Menu>
</div>
<div className="border-t-2 border-solid p-4 bg-gray-50">
{project.deployments.length > 0 ? (
<>
<Typography variant="small" color="gray">
^ {project.deployments[0].commitMessage}
</Typography>
<Typography variant="small" color="gray">
{relativeTimeMs(project.deployments[0].createdAt)} on ^&nbsp;
{project.deployments[0].branch}
</Typography>
</>
) : (
<Typography variant="small" color="gray">
No Production deployment
</Typography>
)}
</div>
</div>
);
};
export default ProjectCard;
@@ -1,71 +0,0 @@
import { VariantProps, tv } from 'tailwind-variants';
export const projectCardTheme = tv({
slots: {
wrapper: [
'bg-surface-card',
'shadow-card',
'rounded-2xl',
'flex',
'flex-col',
],
upperContent: ['px-4', 'py-4', 'flex', 'items-start', 'gap-3', 'relative'],
content: ['flex', 'flex-col', 'gap-1', 'flex-1'],
title: [
'text-sm',
'font-medium',
'text-elements-high-em',
'tracking-[-0.006em]',
],
description: ['text-xs', 'text-elements-low-em'],
icons: ['flex', 'items-center', 'gap-1'],
lowerContent: [
'bg-surface-card-hovered',
'px-4',
'py-4',
'flex',
'flex-col',
'gap-2',
'rounded-b-2xl',
],
latestDeployment: ['flex', 'items-center', 'gap-2'],
deploymentStatusContainer: [
'h-3',
'w-3',
'flex',
'items-center',
'justify-center',
],
deploymentStatus: ['w-1', 'h-1', 'rounded-full'],
deploymentName: ['text-xs', 'text-elements-low-em'],
deploymentText: [
'text-xs',
'text-elements-low-em',
'font-mono',
'flex',
'items-center',
'gap-2',
],
},
variants: {
status: {
success: {
deploymentStatus: ['bg-emerald-500'],
},
'in-progress': {
deploymentStatus: ['bg-orange-400'],
},
failure: {
deploymentStatus: ['bg-rose-500'],
},
pending: {
deploymentStatus: ['bg-gray-500'],
},
},
},
defaultVariants: {
status: 'pending',
},
});
export type ProjectCardTheme = VariantProps<typeof projectCardTheme>;
@@ -1,124 +0,0 @@
import React, { ComponentPropsWithoutRef, MouseEvent } from 'react';
import { ProjectCardTheme, projectCardTheme } from './ProjectCard.theme';
import { Project } from 'gql-client';
import { Button } from 'components/shared/Button';
import { WavyBorder } from 'components/shared/WavyBorder';
import {
BranchIcon,
ClockIcon,
GitHubLogo,
HorizontalDotIcon,
WarningDiamondIcon,
} from 'components/shared/CustomIcon';
import { relativeTimeMs } from 'utils/time';
import { Link } from 'react-router-dom';
import { Avatar } from 'components/shared/Avatar';
import { getInitials } from 'utils/geInitials';
import {
Menu,
MenuHandler,
MenuItem,
MenuList,
} from '@material-tailwind/react';
export interface ProjectCardProps
extends ComponentPropsWithoutRef<'div'>,
ProjectCardTheme {
project: Project;
}
export const ProjectCard = ({
className,
project,
status = 'failure',
...props
}: ProjectCardProps) => {
const theme = projectCardTheme();
const hasDeployment = project.deployments.length > 0;
// TODO: Update this to use the actual status from the API
const hasError = status === 'failure';
const handleOptionsClick = (
e: MouseEvent<HTMLButtonElement, globalThis.MouseEvent>,
) => {
e.stopPropagation();
};
return (
<div {...props} className={theme.wrapper({ className })}>
{/* Upper content */}
<div className={theme.upperContent()}>
{/* Icon container */}
<Avatar
size={48}
imageSrc={project.icon}
initials={getInitials(project.name)}
/>
{/* </div> */}
{/* Title and website */}
<Link to={`projects/${project.id}`} className={theme.content()}>
<p className={theme.title()}>{project.name}</p>
<p className={theme.description()}>
{project.deployments[0]?.domain?.name ?? 'No domain'}
</p>
</Link>
{/* Icons */}
<div className={theme.icons()}>
{hasError && <WarningDiamondIcon className="text-elements-danger" />}
<Menu placement="bottom-end">
<MenuHandler>
<Button
shape="default"
size="xs"
variant="ghost"
iconOnly
onClick={handleOptionsClick}
>
<HorizontalDotIcon />
</Button>
</MenuHandler>
<MenuList placeholder={''}>
<MenuItem placeholder={''}>Project settings</MenuItem>
<MenuItem className="text-red-500" placeholder={''}>
Delete project
</MenuItem>
</MenuList>
</Menu>
</div>
</div>
{/* Wave */}
<WavyBorder />
{/* Lower content */}
<div className={theme.lowerContent()}>
{/* Latest deployment */}
<div className={theme.latestDeployment()}>
{/* Dot icon */}
<div className={theme.deploymentStatusContainer()}>
<div className={theme.deploymentStatus({ status })} />
</div>
<p className={theme.deploymentText()}>
{hasDeployment
? project.deployments[0]?.commitMessage
: 'No production deployment'}
</p>
</div>
{/* Deployment and branch name */}
<div className={theme.deploymentText()}>
{hasDeployment ? (
<>
<GitHubLogo />
<span>{relativeTimeMs(project.deployments[0].createdAt)} on</span>
<BranchIcon />
<span>{project.deployments[0].branch}</span>
</>
) : (
<>
<ClockIcon />
<span>Created {relativeTimeMs(project.createdAt)}</span>
</>
)}
</div>
</div>
</div>
);
};
@@ -1 +0,0 @@
export * from './ProjectCard';
@@ -71,13 +71,12 @@ const ProjectSearchBar = ({ onChange }: ProjectsSearchProps) => {
className={`absolute w-1/2 max-h-52 -mt-1 overflow-y-auto ${
(!inputValue || !isOpen) && 'hidden'
}`}
placeholder={''}
>
<List {...getMenuProps()}>
{items.length ? (
<>
<div className="p-3">
<Typography variant="small" color="gray" placeholder={''}>
<Typography variant="small" color="gray">
Suggestions
</Typography>
</div>
@@ -85,25 +84,19 @@ const ProjectSearchBar = ({ onChange }: ProjectsSearchProps) => {
<ListItem
selected={highlightedIndex === index || selectedItem === item}
key={item.id}
placeholder={''}
{...getItemProps({ item, index })}
>
<ListItemPrefix placeholder={''}>
<Avatar
src={item.icon || '/gray.png'}
variant="rounded"
placeholder={''}
/>
<ListItemPrefix>
<Avatar src={item.icon || '/gray.png'} variant="rounded" />
</ListItemPrefix>
<div>
<Typography variant="h6" color="blue-gray" placeholder={''}>
<Typography variant="h6" color="blue-gray">
{item.name}
</Typography>
<Typography
variant="small"
color="gray"
className="font-normal"
placeholder={''}
>
{item.organization.name}
</Typography>
@@ -113,9 +106,7 @@ const ProjectSearchBar = ({ onChange }: ProjectsSearchProps) => {
</>
) : (
<div className="p-3">
<Typography placeholder={''}>
^ No projects matching this name
</Typography>
<Typography>^ No projects matching this name</Typography>
</div>
)}
</List>
@@ -1,101 +1,73 @@
import React from 'react';
import OauthPopup from 'react-oauth-popup';
import { GitType } from 'gql-client';
import { Button } from '@material-tailwind/react';
import { useGQLClient } from '../../../context/GQLClientContext';
import { Button } from 'components/shared/Button';
import {
GitIcon,
EllipsesIcon,
SnowballIcon,
GithubIcon,
GitTeaIcon,
} from 'components/shared/CustomIcon';
import { useToast } from 'components/shared/Toast';
import { IconWithFrame } from 'components/shared/IconWithFrame';
import { Heading } from 'components/shared/Heading';
import ConnectAccountTabPanel from './ConnectAccountTabPanel';
const SCOPES = 'repo user';
const GITHUB_OAUTH_URL = `https://github.com/login/oauth/authorize?client_id=${
process.env.REACT_APP_GITHUB_CLIENT_ID
}&scope=${encodeURIComponent(SCOPES)}`;
const REDIRECT_URI = `${window.location.origin}/organization/projects/create`;
const GITEA_OAUTH_URL = `https://git.vdb.to/login/oauth/authorize?client_id=${process.env.REACT_APP_GITEA_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code`;
interface ConnectAccountInterface {
onAuth: (token: string) => void;
}
const ConnectAccount: React.FC<ConnectAccountInterface> = ({
onAuth: onToken,
}: ConnectAccountInterface) => {
const ConnectAccount = ({ onAuth: onToken }: ConnectAccountInterface) => {
const client = useGQLClient();
const { toast, dismiss } = useToast();
const handleCode = async (code: string) => {
const handleCode = async (type: GitType, code: string) => {
// Pass code to backend and get access token
const {
authenticateGitHub: { token },
} = await client.authenticateGitHub(code);
authenticateGit: { token },
} = await client.authenticateGit(type, code);
// TODO: Handle token according to Git type
onToken(token);
toast({
onDismiss: dismiss,
id: 'connected-to-github',
title: 'The Git account is connected.',
variant: 'success',
});
};
// TODO: Use correct height
return (
<div className="bg-gray-100 flex flex-col p-4 gap-7 justify-center items-center text-center text-sm h-full rounded-2xl">
<div className="flex flex-col items-center max-w-[420px]">
{/** Icons */}
<div className="w-52 h-16 justify-center items-center gap-4 inline-flex mb-7">
<IconWithFrame icon={<GitIcon />} />
<EllipsesIcon className="items-center gap-1.5 flex" />
<IconWithFrame className="bg-blue-400" icon={<SnowballIcon />} />
</div>
{/** Text */}
<div className="flex flex-col gap-1.5 mb-6">
<Heading className="text-xl font-medium">
Connect to your Git account
</Heading>
<p className="text-center text-elements-mid-em">
Once connected, you can import a repository from your account or
start with one of our templates.
</p>
</div>
{/** CTA Buttons */}
<div className="flex flex-col w-full sm:w-auto sm:flex-row gap-2 sm:gap-3">
<OauthPopup
url={GITHUB_OAUTH_URL}
onCode={handleCode}
onClose={() => {}}
title="Snowball"
width={1000}
height={1000}
>
<Button
className="w-full sm:w-auto"
leftIcon={<GithubIcon />}
variant="tertiary"
>
Connect to GitHub
</Button>
</OauthPopup>
<Button
className="w-full sm:w-auto"
leftIcon={<GitTeaIcon />}
variant="tertiary"
>
Connect to GitTea
</Button>
</div>
<div className="bg-gray-100 flex flex-col p-4 justify-center items-center text-center text-sm h-full rounded-2xl">
<div>^</div>
<div>
<p>Connect to your git account</p>
<p>
Once connected, you can import a repository from your
<br />
account or start with one of our templates.
</p>
</div>
{/* TODO: Add ConnectAccountTabPanel */}
{/* <div className="rounded-l shadow p-2 flex-col justify-start items-start gap-2 inline-flex">
<ConnectAccountTabPanel />
</div> */}
<div className="mt-2 flex">
<OauthPopup
url={GITHUB_OAUTH_URL}
onCode={(code) => handleCode(GitType.GitHub, code)}
onClose={() => {}}
title="Snowball"
width={1000}
height={1000}
>
<Button className="rounded-full mx-2">Connect to Github</Button>
</OauthPopup>
<OauthPopup
url={GITEA_OAUTH_URL}
onCode={(code) => handleCode(GitType.Gitea, code)}
onClose={() => {}}
title="Snowball"
width={1000}
height={1000}
>
<Button className="rounded-full mx-2">Connect to Gitea</Button>
</OauthPopup>
</div>
<ConnectAccountTabPanel />
</div>
);
};
@@ -1,24 +1,21 @@
import React from 'react';
import { Tabs } from 'components/shared/Tabs';
import { Tabs, TabsHeader, Tab } from '@material-tailwind/react';
const ConnectAccountTabPanel: React.FC = () => {
const ConnectAccountTabPanel = () => {
return (
<Tabs
defaultValue="Connect Accounts Tab Panel"
orientation="horizontal"
className="mt-10"
>
<Tabs.List>
{[
{ title: 'Import a repository' },
{ title: 'Start with a template' },
].map(({ title }, index) => (
<Tabs.Trigger value={title} key={index}>
{title}
</Tabs.Trigger>
))}
</Tabs.List>
<Tabs className="grid bg-white h-32 p-2 m-4 rounded-md" value="import">
<TabsHeader className="grid grid-cols-2">
<Tab className="row-span-1" value="import">
Import a repository
</Tab>
<Tab className="row-span-2" value="template">
Start with a template
</Tab>
</TabsHeader>
{/* <TabsBody> */}
{/* TODO: Add content */}
{/* </TabsBody> */}
</Tabs>
);
};
@@ -5,9 +5,9 @@ import { Button, Typography } from '@material-tailwind/react';
import { DeployStep, DeployStatus } from './DeployStep';
import { Stopwatch, setStopWatchOffset } from '../../StopWatch';
import ConfirmDialog from 'components/shared/ConfirmDialog';
import ConfirmDialog from '../../shared/ConfirmDialog';
const TIMEOUT_DURATION = 5000;
const INTERVAL_DURATION = 5000;
const Deploy = () => {
const [searchParams] = useSearchParams();
const projectId = searchParams.get('projectId');
@@ -25,7 +25,7 @@ const Deploy = () => {
useEffect(() => {
const timerID = setTimeout(() => {
navigate(`/${orgSlug}/projects/create/success/${projectId}`);
}, TIMEOUT_DURATION);
}, INTERVAL_DURATION);
return () => clearInterval(timerID);
}, []);
@@ -43,12 +43,7 @@ const Deploy = () => {
</div>
</div>
<div>
<Button
onClick={handleOpen}
variant="outlined"
size="sm"
placeholder={''}
>
<Button onClick={handleOpen} variant="outlined" size="sm">
^ Cancel
</Button>
</div>
@@ -60,7 +55,7 @@ const Deploy = () => {
handleConfirm={handleCancel}
color="red"
>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
This will halt the deployment and you will have to start the process
from scratch.
</Typography>
@@ -62,12 +62,7 @@ const DeployStep = ({
<div className="p-2 text-sm text-gray-500 h-36 overflow-y-scroll">
{processLogs.map((log, key) => {
return (
<Typography
variant="small"
color="gray"
key={key}
placeholder={''}
>
<Typography variant="small" color="gray" key={key}>
{log}
</Typography>
);
@@ -80,7 +75,6 @@ const DeployStep = ({
toast.success('Logs copied');
}}
color="blue"
placeholder={''}
>
^ Copy log
</Button>
@@ -7,7 +7,6 @@ import { Chip, IconButton, Spinner } from '@material-tailwind/react';
import { relativeTimeISO } from '../../../utils/time';
import { GitRepositoryDetails } from '../../../types';
import { useGQLClient } from '../../../context/GQLClientContext';
import { GithubIcon, LockIcon } from 'components/shared/CustomIcon';
interface ProjectRepoCardProps {
repository: GitRepositoryDetails;
@@ -48,18 +47,16 @@ const ProjectRepoCard: React.FC<ProjectRepoCardProps> = ({ repository }) => {
className="group flex items-center gap-4 text-gray-500 text-xs hover:bg-gray-100 p-2 cursor-pointer"
onClick={createProject}
>
<div className="w-10 h-10 bg-white rounded-md justify-center items-center gap-1.5 inline-flex">
<GithubIcon />
</div>
<div>^</div>
<div className="grow">
<div>
<span className="text-black">{repository.full_name}</span>
{repository.visibility === 'private' && (
<Chip
className="normal-case inline ml-6 font-normal text-xs text-xs bg-orange-50 border border-orange-200 text-orange-600 items-center gap-1 inline-flex"
className="normal-case inline ml-6 font-normal"
size="sm"
value="Private"
icon={<LockIcon />}
icon={'^'}
/>
)}
</div>
@@ -69,9 +66,7 @@ const ProjectRepoCard: React.FC<ProjectRepoCardProps> = ({ repository }) => {
<Spinner className="h-4 w-4" />
) : (
<div className="hidden group-hover:block">
<IconButton size="sm" placeholder={''}>
{'>'}
</IconButton>
<IconButton size="sm">{'>'}</IconButton>
</div>
)}
</div>
@@ -9,7 +9,6 @@ import SearchBar from '../../SearchBar';
import ProjectRepoCard from './ProjectRepoCard';
import { GitOrgDetails, GitRepositoryDetails } from '../../../types';
import AsyncSelect from '../../shared/AsyncSelect';
import { GithubIcon } from 'components/shared/CustomIcon';
const DEFAULT_SEARCHED_REPO = '';
const REPOS_PER_PAGE = 5;
@@ -109,7 +108,7 @@ const RepositoryList = ({ octokit }: RepositoryListProps) => {
return (
<div className="p-4">
<div className="flex gap-2 mb-2 items-center">
<div className="flex gap-2 mb-2">
<div className="basis-1/3">
<AsyncSelect
value={selectedAccount}
@@ -117,14 +116,12 @@ const RepositoryList = ({ octokit }: RepositoryListProps) => {
>
{accounts.map((account) => (
<Option key={account.id} value={account.login}>
<div className="flex items-center gap-2 justify-start">
<GithubIcon /> {account.login}
</div>
^ {account.login}
</Option>
))}
</AsyncSelect>
</div>
<div className="basis-2/3 flex-grow flex items-center">
<div className="basis-2/3">
<SearchBar
value={searchedRepo}
onChange={(event) => setSearchedRepo(event.target.value)}
@@ -139,12 +136,11 @@ const RepositoryList = ({ octokit }: RepositoryListProps) => {
) : (
<div className="mt-4 p-6 flex items-center justify-center">
<div className="text-center">
<Typography placeholder={''}>No repository found</Typography>
<Typography>No repository found</Typography>
<Button
className="rounded-full mt-5"
size="sm"
onClick={handleResetFilters}
placeholder={''}
>
^ Reset filters
</Button>
@@ -18,15 +18,11 @@ interface TemplateCardProps {
const CardDetails = ({ template }: { template: TemplateDetails }) => {
return (
<div className="h-14 group bg-gray-200 border-gray-200 rounded-lg shadow p-4 flex items-center justify-between">
<Typography className="grow" placeholder={''}>
<Typography className="grow">
{template.icon} {template.name}
</Typography>
<div>
<IconButton
size="sm"
className="rounded-full hidden group-hover:block"
placeholder={''}
>
<IconButton size="sm" className="rounded-full hidden group-hover:block">
{'>'}
</IconButton>
</div>
@@ -13,29 +13,20 @@ const ActivityCard = ({ activity }: ActivityCardProps) => {
return (
<div className="group flex gap-2 hover:bg-gray-200 rounded mt-1">
<div className="w-8">
<Avatar
src={activity.author?.avatar_url}
variant="rounded"
size="sm"
placeholder={''}
/>
<Avatar src={activity.author?.avatar_url} variant="rounded" size="sm" />
</div>
<div className="grow">
<Typography placeholder={''}>{activity.commit.author?.name}</Typography>
<Typography variant="small" color="gray" placeholder={''}>
<Typography>{activity.commit.author?.name}</Typography>
<Typography variant="small" color="gray">
{relativeTimeISO(activity.commit.author!.date!)} ^{' '}
{activity.branch.name}
</Typography>
<Typography variant="small" color="gray" placeholder={''}>
<Typography variant="small" color="gray">
{activity.commit.message}
</Typography>
</div>
<div className="mr-2 self-center hidden group-hover:block">
<IconButton
size="sm"
className="rounded-full bg-gray-600"
placeholder={''}
>
<IconButton size="sm" className="rounded-full bg-gray-600">
{'>'}
</IconButton>
</div>
@@ -17,9 +17,9 @@ interface AssignDomainProps {
const AssignDomainDialog = ({ open, handleOpen }: AssignDomainProps) => {
return (
<Dialog open={open} handler={handleOpen} placeholder={''}>
<DialogHeader placeholder={''}>Assign Domain</DialogHeader>
<DialogBody placeholder={''}>
<Dialog open={open} handler={handleOpen}>
<DialogHeader>Assign Domain</DialogHeader>
<DialogBody>
In order to assign a domain to your production deployments, configure it
in the{' '}
{/* TODO: Fix selection of project settings tab on navigation to domains */}
@@ -36,13 +36,12 @@ const AssignDomainDialog = ({ open, handleOpen }: AssignDomainProps) => {
theme={atomOneLight}
/>
</DialogBody>
<DialogFooter className="flex justify-start" placeholder={''}>
<DialogFooter className="flex justify-start">
<Button
className="rounded-3xl"
variant="gradient"
color="blue"
onClick={handleOpen}
placeholder={''}
>
<span>Okay</span>
</Button>
@@ -93,12 +93,10 @@ const DeploymentDetailsCard = ({
<div className="col-span-3">
<div className="flex">
{deployment.url && (
<Typography className="basis-3/4" placeholder={''}>
{deployment.url}
</Typography>
<Typography className=" basis-3/4">{deployment.url}</Typography>
)}
</div>
<Typography color="gray" placeholder={''}>
<Typography color="gray">
{deployment.environment === Environment.Production
? `Production ${deployment.isCurrent ? '(Current)' : ''}`
: 'Preview'}
@@ -113,16 +111,14 @@ const DeploymentDetailsCard = ({
/>
</div>
<div className="col-span-2">
<Typography color="gray" placeholder={''}>
^ {deployment.branch}
</Typography>
<Typography color="gray" placeholder={''}>
<Typography color="gray">^ {deployment.branch}</Typography>
<Typography color="gray">
^ {deployment.commitHash.substring(0, SHORT_COMMIT_HASH_LENGTH)}{' '}
{deployment.commitMessage}
</Typography>
</div>
<div className="col-span-2 flex items-center">
<Typography color="gray" className="grow" placeholder={''}>
<Typography color="gray" className="grow">
^ {relativeTimeMs(deployment.createdAt)} ^{' '}
<Tooltip content={deployment.createdBy.name}>
{formatAddress(deployment.createdBy.name ?? '')}
@@ -132,22 +128,18 @@ const DeploymentDetailsCard = ({
<MenuHandler>
<button className="self-start">...</button>
</MenuHandler>
<MenuList placeholder={''}>
<MenuList>
<a href={deployment.url} target="_blank" rel="noreferrer">
<MenuItem disabled={!Boolean(deployment.url)} placeholder={''}>
^ Visit
</MenuItem>
<MenuItem disabled={!Boolean(deployment.url)}>^ Visit</MenuItem>
</a>
<MenuItem
onClick={() => setAssignDomainDialog(!assignDomainDialog)}
placeholder={''}
>
^ Assign domain
</MenuItem>
<MenuItem
onClick={() => setChangeToProduction(!changeToProduction)}
disabled={!(deployment.environment !== Environment.Production)}
placeholder={''}
>
^ Change to production
</MenuItem>
@@ -160,7 +152,6 @@ const DeploymentDetailsCard = ({
deployment.isCurrent
)
}
placeholder={''}
>
^ Redeploy to production
</MenuItem>
@@ -171,7 +162,6 @@ const DeploymentDetailsCard = ({
deployment.environment !== Environment.Production ||
!Boolean(currentDeployment)
}
placeholder={''}
>
^ Rollback to this version
</MenuItem>
@@ -190,22 +180,17 @@ const DeploymentDetailsCard = ({
}}
>
<div className="flex flex-col gap-2">
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Upon confirmation, this deployment will be changed to production.
</Typography>
<DeploymentDialogBodyCard deployment={deployment} />
<Typography variant="small" placeholder={''}>
<Typography variant="small">
The new deployment will be associated with these domains:
</Typography>
{prodBranchDomains.length > 0 &&
prodBranchDomains.map((value) => {
return (
<Typography
variant="small"
color="blue"
key={value.id}
placeholder={''}
>
<Typography variant="small" color="blue" key={value.id}>
^ {value.name}
</Typography>
);
@@ -224,16 +209,16 @@ const DeploymentDetailsCard = ({
}}
>
<div className="flex flex-col gap-2">
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Upon confirmation, new deployment will be created with the same
source code as current deployment.
</Typography>
<DeploymentDialogBodyCard deployment={deployment} />
<Typography variant="small" placeholder={''}>
<Typography variant="small">
These domains will point to your new deployment:
</Typography>
{deployment.domain?.name && (
<Typography variant="small" color="blue" placeholder={''}>
<Typography variant="small" color="blue">
{deployment.domain?.name}
</Typography>
)}
@@ -252,7 +237,7 @@ const DeploymentDetailsCard = ({
}}
>
<div className="flex flex-col gap-2">
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Upon confirmation, this deployment will replace your current
deployment
</Typography>
@@ -270,10 +255,10 @@ const DeploymentDetailsCard = ({
color: 'orange',
}}
/>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
These domains will point to your new deployment:
</Typography>
<Typography variant="small" color="blue" placeholder={''}>
<Typography variant="small" color="blue">
^ {currentDeployment.domain?.name}
</Typography>
</div>
@@ -20,7 +20,7 @@ const DeploymentDialogBodyCard = ({
deployment,
}: DeploymentDialogBodyCardProps) => {
return (
<Card className="p-2 shadow-none" placeholder={''}>
<Card className="p-2 shadow-none">
{chip && (
<Chip
className={`w-fit normal-case font-normal`}
@@ -30,16 +30,16 @@ const DeploymentDialogBodyCard = ({
/>
)}
{deployment.url && (
<Typography variant="small" className="text-black" placeholder={''}>
<Typography variant="small" className="text-black">
{deployment.url}
</Typography>
)}
<Typography variant="small" placeholder={''}>
<Typography variant="small">
^ {deployment.branch} ^{' '}
{deployment.commitHash.substring(0, SHORT_COMMIT_HASH_LENGTH)}{' '}
{deployment.commitMessage}
</Typography>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
^ {relativeTimeMs(deployment.createdAt)} ^{' '}
{formatAddress(deployment.createdBy.name ?? '')}
</Typography>
@@ -77,7 +77,6 @@ const FilterForm = ({ value, onChange }: FilterFormProps) => {
onClick={() => setSelectedStatus(StatusOptions.ALL_STATUS)}
className="rounded-full"
size="sm"
placeholder={''}
>
X
</IconButton>
@@ -21,9 +21,7 @@ const AddEnvironmentVariableRow = ({
return (
<div className="flex gap-1 p-2">
<div>
<Typography variant="small" placeholder={''}>
Key
</Typography>
<Typography variant="small">Key</Typography>
<Input
crossOrigin={undefined}
{...register(`variables.${index}.key`, {
@@ -32,9 +30,7 @@ const AddEnvironmentVariableRow = ({
/>
</div>
<div>
<Typography variant="small" placeholder={''}>
Value
</Typography>
<Typography variant="small">Value</Typography>
<Input
crossOrigin={undefined}
{...register(`variables.${index}.value`, {
@@ -47,7 +43,6 @@ const AddEnvironmentVariableRow = ({
size="sm"
onClick={() => onDelete()}
disabled={isDeleteDisabled}
placeholder={''}
>
{'>'}
</IconButton>
@@ -61,26 +61,23 @@ const AddMemberDialog = ({
}, []);
return (
<Dialog open={open} handler={handleOpen} placeholder={''}>
<DialogHeader className="flex justify-between" placeholder={''}>
<Dialog open={open} handler={handleOpen}>
<DialogHeader className="flex justify-between">
<div>Add member</div>
<Button
variant="outlined"
onClick={handleOpen}
className="mr-1 rounded-3xl"
placeholder={''}
>
X
</Button>
</DialogHeader>
<form onSubmit={handleSubmit(submitHandler)}>
<DialogBody className="flex flex-col gap-2 p-4" placeholder={''}>
<Typography variant="small" placeholder={''}>
<DialogBody className="flex flex-col gap-2 p-4">
<Typography variant="small">
We will send an invitation link to this email address.
</Typography>
<Typography variant="small" placeholder={''}>
Email address
</Typography>
<Typography variant="small">Email address</Typography>
<Input
type="email"
crossOrigin={undefined}
@@ -88,10 +85,8 @@ const AddMemberDialog = ({
required: 'email field cannot be empty',
})}
/>
<Typography variant="small" placeholder={''}>
Permissions
</Typography>
<Typography variant="small" placeholder={''}>
<Typography variant="small">Permissions</Typography>
<Typography variant="small">
You can change this later if required.
</Typography>
<Checkbox
@@ -107,13 +102,8 @@ const AddMemberDialog = ({
color="blue"
/>
</DialogBody>
<DialogFooter className="flex justify-start" placeholder={''}>
<Button
variant="outlined"
onClick={handleOpen}
className="mr-1"
placeholder={''}
>
<DialogFooter className="flex justify-start">
<Button variant="outlined" onClick={handleOpen} className="mr-1">
Cancel
</Button>
<Button
@@ -121,7 +111,6 @@ const AddMemberDialog = ({
color="blue"
type="submit"
disabled={!isValid}
placeholder={''}
>
Send invite
</Button>
@@ -53,21 +53,20 @@ const DeleteProjectDialog = ({
}, [client, project, handleOpen]);
return (
<Dialog open={open} handler={handleOpen} placeholder={''}>
<DialogHeader className="flex justify-between" placeholder={''}>
<Dialog open={open} handler={handleOpen}>
<DialogHeader className="flex justify-between">
<div>Delete project?</div>
<Button
variant="outlined"
onClick={handleOpen}
className="mr-1 rounded-3xl"
placeholder={''}
>
X
</Button>
</DialogHeader>
<form onSubmit={handleSubmit(deleteProjectHandler)}>
<DialogBody className="flex flex-col gap-2" placeholder={''}>
<Typography variant="paragraph" placeholder={''}>
<DialogBody className="flex flex-col gap-2">
<Typography variant="paragraph">
Deleting your project is irreversible. Enter your projects
name&nbsp;
<span className="bg-blue-100 text-blue-700">({project.name})</span>
@@ -81,17 +80,12 @@ const DeleteProjectDialog = ({
validate: (value) => value === project.name,
})}
/>
<Typography variant="small" color="red" placeholder={''}>
<Typography variant="small" color="red">
^ Deleting your project is irreversible.
</Typography>
</DialogBody>
<DialogFooter className="flex justify-start" placeholder={''}>
<Button
variant="outlined"
onClick={handleOpen}
className="mr-1"
placeholder={''}
>
<DialogFooter className="flex justify-start">
<Button variant="outlined" onClick={handleOpen} className="mr-1">
Cancel
</Button>
<Button
@@ -99,7 +93,6 @@ const DeleteProjectDialog = ({
color="red"
type="submit"
disabled={!isValid}
placeholder={''}
>
Yes, Delete project
</Button>
@@ -1,8 +1,9 @@
import React, { useState } from 'react';
import { Card, Collapse, Typography } from '@material-tailwind/react';
import { Environment, EnvironmentVariable } from 'gql-client/dist/src/types';
import EditEnvironmentVariableRow from './EditEnvironmentVariableRow';
import { Environment, EnvironmentVariable } from 'gql-client';
interface DisplayEnvironmentVariablesProps {
environment: Environment;
@@ -29,11 +30,11 @@ const DisplayEnvironmentVariables = ({
</div>
<Collapse open={openCollapse}>
{variables.length === 0 ? (
<Card className="bg-gray-300 flex items-center p-4" placeholder={''}>
<Typography variant="small" className="text-black" placeholder={''}>
<Card className="bg-gray-300 flex items-center p-4">
<Typography variant="small" className="text-black">
No environment variables added yet.
</Typography>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Once you add them, theyll show up here.
</Typography>
</Card>
@@ -68,7 +68,7 @@ const DomainCard = ({
<>
<div className="flex justify-between py-3">
<div className="flex justify-start gap-1">
<Typography variant="h6" placeholder={''}>
<Typography variant="h6">
<i>^</i> {domain.name}
</Typography>
<Chip
@@ -97,20 +97,18 @@ const DomainCard = ({
<MenuHandler>
<button className="border-2 rounded-full w-8 h-8">...</button>
</MenuHandler>
<MenuList placeholder={''}>
<MenuList>
<MenuItem
className="text-black"
onClick={() => {
setEditDialogOpen((preVal) => !preVal);
}}
placeholder={''}
>
^ Edit domain
</MenuItem>
<MenuItem
className="text-red-500"
onClick={() => setDeleteDialogOpen((preVal) => !preVal)}
placeholder={''}
>
^ Delete domain
</MenuItem>
@@ -129,7 +127,7 @@ const DomainCard = ({
}}
color="red"
>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Once deleted, the project{' '}
<span className="bg-blue-100 rounded-sm p-0.5 text-blue-700">
{project.name}
@@ -142,21 +140,15 @@ const DomainCard = ({
</ConfirmDialog>
</div>
<Typography variant="small" placeholder={''}>
Production
</Typography>
<Typography variant="small">Production</Typography>
{domain.status === DomainStatus.Pending && (
<Card className="bg-gray-200 p-4 text-sm" placeholder={''}>
<Card className="bg-gray-200 p-4 text-sm">
{refreshStatus === RefreshStatus.IDLE ? (
<Typography variant="small" placeholder={''}>
<Typography variant="small">
^ Add these records to your domain and refresh to check
</Typography>
) : refreshStatus === RefreshStatus.CHECKING ? (
<Typography
variant="small"
className="text-blue-500"
placeholder={''}
>
<Typography variant="small" className="text-blue-500">
^ Checking records for {domain.name}
</Typography>
) : (
@@ -122,32 +122,27 @@ const EditDomainDialog = ({
}, [domain]);
return (
<Dialog open={open} handler={handleOpen} placeholder={''}>
<DialogHeader className="flex justify-between" placeholder={''}>
<Dialog open={open} handler={handleOpen}>
<DialogHeader className="flex justify-between">
<div>Edit domain</div>
<Button
variant="outlined"
onClick={handleOpen}
className="mr-1 rounded-3xl"
placeholder={''}
>
X
</Button>
</DialogHeader>
<form onSubmit={handleSubmit(updateDomainHandler)}>
<DialogBody className="flex flex-col gap-2 p-4" placeholder={''}>
<Typography variant="small" placeholder={''}>
Domain name
</Typography>
<DialogBody className="flex flex-col gap-2 p-4">
<Typography variant="small">Domain name</Typography>
<Input crossOrigin={undefined} {...register('name')} />
<Typography variant="small" placeholder={''}>
Redirect to
</Typography>
<Typography variant="small">Redirect to</Typography>
<Controller
name="redirectedTo"
control={control}
render={({ field }) => (
<Select {...field} disabled={isDisableDropdown} placeholder={''}>
<Select {...field} disabled={isDisableDropdown}>
{redirectOptions.map((option, key) => (
<Option key={key} value={option}>
^ {option}
@@ -159,16 +154,14 @@ const EditDomainDialog = ({
{isDisableDropdown && (
<div className="flex p-2 gap-2 text-black bg-gray-300 rounded-lg">
<div>^</div>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Domain {domainRedirectedFrom ? domainRedirectedFrom.name : ''}
redirects to this domain so you can not redirect this doman
further.
</Typography>
</div>
)}
<Typography variant="small" placeholder={''}>
Git branch
</Typography>
<Typography variant="small">Git branch</Typography>
<Input
crossOrigin={undefined}
{...register('branch', {
@@ -181,22 +174,13 @@ const EditDomainDialog = ({
}
/>
{!isValid && (
<Typography
variant="small"
className="text-red-500"
placeholder={''}
>
<Typography variant="small" className="text-red-500">
We couldn&apos;t find this branch in the connected Git repository.
</Typography>
)}
</DialogBody>
<DialogFooter className="flex justify-start" placeholder={''}>
<Button
variant="outlined"
onClick={handleOpen}
className="mr-1"
placeholder={''}
>
<DialogFooter className="flex justify-start">
<Button variant="outlined" onClick={handleOpen} className="mr-1">
Cancel
</Button>
<Button
@@ -204,7 +188,6 @@ const EditDomainDialog = ({
color="blue"
type="submit"
disabled={!isDirty}
placeholder={''}
>
Save changes
</Button>
@@ -84,9 +84,7 @@ const EditEnvironmentVariableRow = ({
<>
<div className="flex gap-1 p-2">
<div>
<Typography variant="small" placeholder={''}>
Key
</Typography>
<Typography variant="small">Key</Typography>
<Input
crossOrigin={undefined}
disabled={!edit}
@@ -94,9 +92,7 @@ const EditEnvironmentVariableRow = ({
/>
</div>
<div>
<Typography variant="small" placeholder={''}>
Value
</Typography>
<Typography variant="small">Value</Typography>
<Input
crossOrigin={undefined}
disabled={!edit}
@@ -118,7 +114,6 @@ const EditEnvironmentVariableRow = ({
<IconButton
onClick={handleSubmit(updateEnvironmentVariableHandler)}
size="sm"
placeholder={''}
>
{'S'}
</IconButton>
@@ -130,7 +125,6 @@ const EditEnvironmentVariableRow = ({
reset();
setEdit((preVal) => !preVal);
}}
placeholder={''}
>
{'C'}
</IconButton>
@@ -144,7 +138,6 @@ const EditEnvironmentVariableRow = ({
onClick={() => {
setEdit((preVal) => !preVal);
}}
placeholder={''}
>
{'E'}
</IconButton>
@@ -153,7 +146,6 @@ const EditEnvironmentVariableRow = ({
<IconButton
size="sm"
onClick={() => setDeleteDialogOpen((preVal) => !preVal)}
placeholder={''}
>
{'D'}
</IconButton>
@@ -170,7 +162,7 @@ const EditEnvironmentVariableRow = ({
handleConfirm={removeEnvironmentVariableHandler}
color="red"
>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Are you sure you want to delete the variable&nbsp;
<span className="bg-blue-100">{variable.key}</span>?
</Typography>
@@ -104,7 +104,6 @@ const MemberCard = ({
selected={(_, index) => (
<span>{DROPDOWN_OPTIONS[index!]?.label}</span>
)}
placeholder={''}
>
{DROPDOWN_OPTIONS.map((permission, key) => (
<Option key={key} value={permission.value}>
@@ -133,7 +132,6 @@ const MemberCard = ({
onClick={() => {
setRemoveMemberDialogOpen((prevVal) => !prevVal);
}}
placeholder={''}
>
D
</IconButton>
@@ -154,7 +152,7 @@ const MemberCard = ({
}}
color="red"
>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Once removed, {formatAddress(member.name ?? '')} (
{formatAddress(ethAddress)}@{emailDomain}) will not be able to access
this project.
@@ -17,19 +17,14 @@ const RepoConnectedSection = ({
<div className="flex gap-4">
<div>^</div>
<div className="grow">
<Typography variant="small" placeholder={''}>
{linkedRepo.full_name}
</Typography>
<Typography variant="small" placeholder={''}>
Connected just now
</Typography>
<Typography variant="small">{linkedRepo.full_name}</Typography>
<Typography variant="small">Connected just now</Typography>
</div>
<div>
<Button
onClick={() => setDisconnectRepoDialogOpen(true)}
variant="outlined"
size="sm"
placeholder={''}
>
^ Disconnect
</Button>
@@ -44,7 +39,7 @@ const RepoConnectedSection = ({
}}
color="red"
>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Any data tied to your Git project may become misconfigured. Are you
sure you want to continue?
</Typography>
@@ -54,18 +54,14 @@ const SetupDomain = () => {
className="flex flex-col gap-6 w-full"
>
<div>
<Typography variant="h5" placeholder={''}>
Setup domain name
</Typography>
<Typography variant="small" placeholder={''}>
<Typography variant="h5">Setup domain name</Typography>
<Typography variant="small">
Add your domain and setup redirects
</Typography>
</div>
<div className="w-auto">
<Typography variant="small" placeholder={''}>
Domain name
</Typography>
<Typography variant="small">Domain name</Typography>
<Input
type="text"
variant="outlined"
@@ -80,7 +76,7 @@ const SetupDomain = () => {
{isValid && (
<div>
<Typography placeholder={''}>Primary domain</Typography>
<Typography>Primary domain</Typography>
<div className="flex flex-col gap-3">
<Radio
label={domainStr}
@@ -112,7 +108,6 @@ const SetupDomain = () => {
className="w-fit"
color={isValid ? 'blue' : 'gray'}
type="submit"
placeholder={''}
>
<i>^</i> Next
</Button>
@@ -23,7 +23,6 @@ const WebhookCard = ({ webhookUrl, onDelete }: WebhookCardProps) => {
navigator.clipboard.writeText(webhookUrl);
toast.success('Copied to clipboard');
}}
placeholder={''}
>
C
</Button>
@@ -33,7 +32,6 @@ const WebhookCard = ({ webhookUrl, onDelete }: WebhookCardProps) => {
onClick={() => {
setDeleteDialogOpen(true);
}}
placeholder={''}
>
X
</Button>
@@ -50,7 +48,7 @@ const WebhookCard = ({ webhookUrl, onDelete }: WebhookCardProps) => {
}}
color="red"
>
<Typography variant="small" placeholder={''}>
<Typography variant="small">
Are you sure you want to delete the variable{' '}
<span className="bg-blue-100 p-0.5 rounded-sm">{webhookUrl}</span>?
</Typography>
@@ -9,7 +9,7 @@ const AsyncSelect = React.forwardRef((props: SelectProps, ref: any) => {
useEffect(() => setKey((preVal) => preVal + 1), [props]);
return <Select key={key} ref={ref} {...props} placeholder={''} />;
return <Select key={key} ref={ref} {...props} />;
});
AsyncSelect.displayName = 'AsyncSelect';
@@ -1,74 +0,0 @@
import { tv, type VariantProps } from 'tailwind-variants';
export const avatarTheme = tv(
{
base: ['relative', 'block', 'rounded-full', 'overflow-hidden'],
slots: {
image: [
'h-full',
'w-full',
'rounded-[inherit]',
'object-cover',
'object-center',
],
fallback: [
'grid',
'select-none',
'place-content-center',
'h-full',
'w-full',
'rounded-[inherit]',
'font-medium',
],
},
variants: {
type: {
gray: {
fallback: ['text-elements-highEm', 'bg-base-bg-emphasized'],
},
orange: {
fallback: ['text-elements-warning', 'bg-base-bg-emphasized-warning'],
},
blue: {
fallback: ['text-elements-info', 'bg-base-bg-emphasized-info'],
},
},
size: {
18: {
base: ['rounded-md', 'h-[18px]', 'w-[18px]', 'text-[0.625rem]'],
},
20: {
base: ['rounded-md', 'h-5', 'w-5', 'text-[0.625rem]'],
},
24: {
base: ['rounded-md', 'h-6', 'w-6', 'text-[0.625rem]'],
},
28: {
base: ['rounded-lg', 'h-[28px]', 'w-[28px]', 'text-[0.625rem]'],
},
32: {
base: ['rounded-lg', 'h-8', 'w-8', 'text-xs'],
},
36: {
base: ['rounded-xl', 'h-[36px]', 'w-[36px]', 'text-xs'],
},
40: {
base: ['rounded-xl', 'h-10', 'w-10', 'text-sm'],
},
44: {
base: ['rounded-xl', 'h-[44px]', 'w-[44px]', 'text-sm'],
},
48: {
base: ['rounded-xl', 'h-[48px]', 'w-[48px]', 'text-sm'],
},
},
},
defaultVariants: {
size: 24,
type: 'gray',
},
},
{ responsiveVariants: true },
);
export type AvatarVariants = VariantProps<typeof avatarTheme>;
@@ -1,40 +0,0 @@
import React from 'react';
import { type ComponentPropsWithoutRef, type ComponentProps } from 'react';
import { avatarTheme, type AvatarVariants } from './Avatar.theme';
import * as PrimitiveAvatar from '@radix-ui/react-avatar';
export type AvatarProps = ComponentPropsWithoutRef<'div'> & {
imageSrc?: string | null;
initials?: string;
imageProps?: ComponentProps<typeof PrimitiveAvatar.Image>;
fallbackProps?: ComponentProps<typeof PrimitiveAvatar.Fallback>;
} & AvatarVariants;
export const Avatar = ({
className,
size,
type,
imageSrc,
imageProps,
fallbackProps,
initials,
}: AvatarProps) => {
const { base, image, fallback } = avatarTheme({ size, type });
return (
<PrimitiveAvatar.Root className={base({ className })}>
{imageSrc && (
<PrimitiveAvatar.Image
{...imageProps}
className={image({ className: imageProps?.className })}
src={imageSrc}
/>
)}
<PrimitiveAvatar.Fallback asChild {...fallbackProps}>
<div className={fallback({ className: fallbackProps?.className })}>
{initials}
</div>
</PrimitiveAvatar.Fallback>
</PrimitiveAvatar.Root>
);
};

Some files were not shown because too many files have changed in this diff Show More