Compare commits
34 Commits
feature/up
...
feat/subpa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a134e20cdf | ||
|
|
a501282f2b | ||
|
|
eb248fa0df | ||
|
|
f1e4ac7fc4 | ||
|
|
28059ddc60 | ||
|
|
64517a53af | ||
|
|
79a9285f93 | ||
|
|
aebcbac979 | ||
|
|
d19d96ba9c | ||
|
|
312940009e | ||
|
|
8703a0dcfd | ||
|
|
03e21e0b0c | ||
|
|
d6e4b6497f | ||
|
|
2f1fca2917 | ||
|
|
04092d8597 | ||
|
|
4caf0053cd | ||
|
|
93ce86f32d | ||
|
|
4ebf850cb6 | ||
|
|
76af7d5e10 | ||
|
|
507fe69efe | ||
|
|
23e3739718 | ||
|
|
5428a73811 | ||
|
|
4a154e6569 | ||
|
|
0aa5825d8b | ||
|
|
bdb63e99d5 | ||
|
|
6daa043a1b | ||
|
|
8175ec640a | ||
|
|
b5307e4a89 | ||
|
|
19294802be | ||
|
|
cbe3e14b47 | ||
|
|
01df1663ad | ||
|
|
abd5288da8 | ||
|
|
a89bc473f6 | ||
|
|
57cb59027b |
@@ -59,3 +59,6 @@ VITE_BACKEND_API_URL=http://localhost:3170/v1
|
||||
# Terms Of Service And Privacy Policy Links (Optional)
|
||||
VITE_APP_TOS_LINK=https://docs.hoppscotch.io/support/terms
|
||||
VITE_APP_PRIVACY_POLICY_LINK=https://docs.hoppscotch.io/support/privacy
|
||||
|
||||
# Set to `true` for subpath based access
|
||||
ENABLE_SUBPATH_BASED_ACCESS=false
|
||||
|
||||
11
Caddyfile
Normal file
11
Caddyfile
Normal file
@@ -0,0 +1,11 @@
|
||||
:3500 {
|
||||
handle_path /admin* {
|
||||
reverse_proxy localhost:3100
|
||||
}
|
||||
|
||||
handle_path /backend* {
|
||||
reverse_proxy localhost:3170
|
||||
}
|
||||
|
||||
reverse_proxy localhost:3000 # Proxy other requests to your server running on port 3001
|
||||
}
|
||||
15
aio-multiport-setup.Caddyfile
Normal file
15
aio-multiport-setup.Caddyfile
Normal file
@@ -0,0 +1,15 @@
|
||||
:3000 {
|
||||
try_files {path} /
|
||||
root * /site/selfhost-web
|
||||
file_server
|
||||
}
|
||||
|
||||
:3100 {
|
||||
try_files {path} /
|
||||
root * /site/sh-admin
|
||||
file_server
|
||||
}
|
||||
|
||||
:80 {
|
||||
respond 404
|
||||
}
|
||||
33
aio-subpath-access.Caddyfile
Normal file
33
aio-subpath-access.Caddyfile
Normal file
@@ -0,0 +1,33 @@
|
||||
:3000 {
|
||||
respond 404
|
||||
}
|
||||
|
||||
:3100 {
|
||||
respond 404
|
||||
}
|
||||
|
||||
:80 {
|
||||
# Serve the `selfhost-web` SPA by default
|
||||
root * /site/selfhost-web
|
||||
file_server
|
||||
|
||||
handle_path /admin* {
|
||||
root * /site/sh-admin-subpath-access
|
||||
file_server
|
||||
|
||||
# Ensures any non-existent file in the server is routed to the SPA
|
||||
try_files {path} /
|
||||
}
|
||||
|
||||
# Handle requests under `/backend*` path
|
||||
handle_path /backend* {
|
||||
reverse_proxy localhost:8080
|
||||
}
|
||||
|
||||
# Catch-all route for unknown paths, serves `selfhost-web` SPA
|
||||
handle {
|
||||
root * /site/selfhost-web
|
||||
file_server
|
||||
try_files {path} /
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
:3000 {
|
||||
try_files {path} /
|
||||
root * /site/selfhost-web
|
||||
file_server
|
||||
}
|
||||
|
||||
:3100 {
|
||||
try_files {path} /
|
||||
root * /site/sh-admin
|
||||
file_server
|
||||
}
|
||||
@@ -49,7 +49,8 @@ execSync(`npx import-meta-env -x build.env -e build.env -p "/site/**/*"`)
|
||||
|
||||
fs.rmSync("build.env")
|
||||
|
||||
const caddyProcess = runChildProcessWithPrefix("caddy", ["run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"], "App/Admin Dashboard Caddy")
|
||||
const caddyFileName = process.env.ENABLE_SUBPATH_BASED_ACCESS === 'true' ? 'aio-subpath-access.Caddyfile' : 'aio-multiport-setup.Caddyfile'
|
||||
const caddyProcess = runChildProcessWithPrefix("caddy", ["run", "--config", `/etc/caddy/${caddyFileName}`, "--adapter", "caddyfile"], "App/Admin Dashboard Caddy")
|
||||
const backendProcess = runChildProcessWithPrefix("pnpm", ["run", "start:prod"], "Backend Server")
|
||||
|
||||
caddyProcess.on("exit", (code) => {
|
||||
|
||||
@@ -17,7 +17,7 @@ services:
|
||||
environment:
|
||||
# Edit the below line to match your PostgresDB URL if you have an outside DB (make sure to update the .env file as well)
|
||||
- DATABASE_URL=postgresql://postgres:testpass@hoppscotch-db:5432/hoppscotch?connect_timeout=300
|
||||
- PORT=3170
|
||||
- PORT=8080
|
||||
volumes:
|
||||
# Uncomment the line below when modifying code. Only applicable when using the "dev" target.
|
||||
# - ./packages/hoppscotch-backend/:/usr/src/app
|
||||
@@ -26,6 +26,7 @@ services:
|
||||
hoppscotch-db:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "3180:80"
|
||||
- "3170:3170"
|
||||
|
||||
# The main hoppscotch app. This will be hosted at port 3000
|
||||
@@ -42,7 +43,8 @@ services:
|
||||
depends_on:
|
||||
- hoppscotch-backend
|
||||
ports:
|
||||
- "3000:8080"
|
||||
- "3080:80"
|
||||
- "3000:3000"
|
||||
|
||||
# The Self Host dashboard for managing the app. This will be hosted at port 3100
|
||||
# NOTE: To do TLS or play around with how the app is hosted, you can look into the Caddyfile for
|
||||
@@ -58,7 +60,8 @@ services:
|
||||
depends_on:
|
||||
- hoppscotch-backend
|
||||
ports:
|
||||
- "3100:8080"
|
||||
- "3280:80"
|
||||
- "3100:3100"
|
||||
|
||||
# The service that spins up all 3 services at once in one container
|
||||
hoppscotch-aio:
|
||||
@@ -75,7 +78,8 @@ services:
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "3100:3100"
|
||||
- "3170:3170"
|
||||
- "3170:8080"
|
||||
- "3080:80"
|
||||
|
||||
# The preset DB service, you can delete/comment the below lines if
|
||||
# you are using an external postgres instance
|
||||
|
||||
0
individual-containers-subpath-access.Caddyfile
Normal file
0
individual-containers-subpath-access.Caddyfile
Normal file
@@ -17,12 +17,12 @@
|
||||
"types": "dist/index.d.ts",
|
||||
"sideEffects": false,
|
||||
"dependencies": {
|
||||
"@codemirror/language": "^6.9.0",
|
||||
"@lezer/highlight": "^1.1.6",
|
||||
"@lezer/lr": "^1.3.10"
|
||||
"@codemirror/language": "^6.9.2",
|
||||
"@lezer/highlight": "1.1.4",
|
||||
"@lezer/lr": "^1.3.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@lezer/generator": "^1.5.0",
|
||||
"@lezer/generator": "^1.5.1",
|
||||
"mocha": "^9.2.2",
|
||||
"rollup": "^3.29.3",
|
||||
"rollup-plugin-dts": "^6.0.2",
|
||||
|
||||
3
packages/hoppscotch-backend/Caddyfile
Normal file
3
packages/hoppscotch-backend/Caddyfile
Normal file
@@ -0,0 +1,3 @@
|
||||
:3170 {
|
||||
reverse_proxy localhost:80
|
||||
}
|
||||
3
packages/hoppscotch-backend/backend-multiport.Caddyfile
Normal file
3
packages/hoppscotch-backend/backend-multiport.Caddyfile
Normal file
@@ -0,0 +1,3 @@
|
||||
:80 :3170 {
|
||||
reverse_proxy localhost:8080
|
||||
}
|
||||
7
packages/hoppscotch-backend/backend-subpath.Caddyfile
Normal file
7
packages/hoppscotch-backend/backend-subpath.Caddyfile
Normal file
@@ -0,0 +1,7 @@
|
||||
:80 :3170 {
|
||||
handle_path /backend* {
|
||||
reverse_proxy localhost:8080
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hoppscotch-backend",
|
||||
"version": "2023.8.2",
|
||||
"version": "2023.8.3",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
@@ -46,7 +46,6 @@
|
||||
"graphql-query-complexity": "^0.12.0",
|
||||
"graphql-redis-subscriptions": "^2.6.0",
|
||||
"graphql-subscriptions": "^2.0.0",
|
||||
"graphql-ws": "^5.14.2",
|
||||
"handlebars": "^4.7.7",
|
||||
"io-ts": "^2.2.16",
|
||||
"luxon": "^3.2.1",
|
||||
@@ -67,6 +66,7 @@
|
||||
"@nestjs/schematics": "^10.0.2",
|
||||
"@nestjs/testing": "^10.2.6",
|
||||
"@relmify/jest-fp-ts": "^2.0.2",
|
||||
"@types/argon2": "^0.15.0",
|
||||
"@types/bcrypt": "^5.0.0",
|
||||
"@types/cookie": "^0.5.1",
|
||||
"@types/cookie-parser": "^1.4.3",
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- A unique constraint covering the columns `[id]` on the table `Shortcode` will be added. If there are existing duplicate values, this will fail.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "Shortcode" ADD COLUMN "embedProperties" JSONB,
|
||||
ADD COLUMN "updatedOn" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Shortcode_id_key" ON "Shortcode"("id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Shortcode" ADD CONSTRAINT "Shortcode_creatorUid_fkey" FOREIGN KEY ("creatorUid") REFERENCES "User"("uid") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -68,11 +68,13 @@ model TeamRequest {
|
||||
}
|
||||
|
||||
model Shortcode {
|
||||
id String @id
|
||||
request Json
|
||||
creatorUid String?
|
||||
createdOn DateTime @default(now())
|
||||
|
||||
id String @id @unique
|
||||
request Json
|
||||
embedProperties Json?
|
||||
creatorUid String?
|
||||
User User? @relation(fields: [creatorUid], references: [uid])
|
||||
createdOn DateTime @default(now())
|
||||
updatedOn DateTime @updatedAt @default(now())
|
||||
@@unique(fields: [id, creatorUid], name: "creator_uid_shortcode_unique")
|
||||
}
|
||||
|
||||
@@ -102,6 +104,7 @@ model User {
|
||||
currentGQLSession Json?
|
||||
createdOn DateTime @default(now()) @db.Timestamp(3)
|
||||
invitedUsers InvitedUsers[]
|
||||
shortcodes Shortcode[]
|
||||
}
|
||||
|
||||
model Account {
|
||||
|
||||
71
packages/hoppscotch-backend/prod_run.mjs
Normal file
71
packages/hoppscotch-backend/prod_run.mjs
Normal file
@@ -0,0 +1,71 @@
|
||||
#!/usr/local/bin/node
|
||||
// @ts-check
|
||||
|
||||
import { execSync, spawn } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import process from 'process';
|
||||
|
||||
function runChildProcessWithPrefix(command, args, prefix) {
|
||||
const childProcess = spawn(command, args);
|
||||
|
||||
childProcess.stdout.on('data', (data) => {
|
||||
const output = data.toString().trim().split('\n');
|
||||
output.forEach((line) => {
|
||||
console.log(`${prefix} | ${line}`);
|
||||
});
|
||||
});
|
||||
|
||||
childProcess.stderr.on('data', (data) => {
|
||||
const error = data.toString().trim().split('\n');
|
||||
error.forEach((line) => {
|
||||
console.error(`${prefix} | ${line}`);
|
||||
});
|
||||
});
|
||||
|
||||
childProcess.on('close', (code) => {
|
||||
console.log(`${prefix} Child process exited with code ${code}`);
|
||||
});
|
||||
|
||||
childProcess.on('error', (stuff) => {
|
||||
console.log('error');
|
||||
console.log(stuff);
|
||||
});
|
||||
|
||||
return childProcess;
|
||||
}
|
||||
|
||||
const caddyFileName =
|
||||
process.env.ENABLE_SUBPATH_BASED_ACCESS === 'true'
|
||||
? 'backend-subpath.Caddyfile'
|
||||
: 'backend-multiport.Caddyfile';
|
||||
const caddyProcess = runChildProcessWithPrefix(
|
||||
'caddy',
|
||||
['run', '--config', `/etc/caddy/${caddyFileName}`, '--adapter', 'caddyfile'],
|
||||
'App/Admin Dashboard Caddy',
|
||||
);
|
||||
const backendProcess = runChildProcessWithPrefix(
|
||||
'pnpm',
|
||||
['run', 'start:prod'],
|
||||
'Backend Server',
|
||||
);
|
||||
|
||||
caddyProcess.on('exit', (code) => {
|
||||
console.log(`Exiting process because Caddy Server exited with code ${code}`);
|
||||
process.exit(code);
|
||||
});
|
||||
|
||||
backendProcess.on('exit', (code) => {
|
||||
console.log(
|
||||
`Exiting process because Backend Server exited with code ${code}`,
|
||||
);
|
||||
process.exit(code);
|
||||
});
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
console.log('SIGINT received, exiting...');
|
||||
|
||||
caddyProcess.kill('SIGINT');
|
||||
backendProcess.kill('SIGINT');
|
||||
|
||||
process.exit(0);
|
||||
});
|
||||
@@ -74,7 +74,7 @@ export class AdminService {
|
||||
|
||||
try {
|
||||
await this.mailerService.sendUserInvitationEmail(inviteeEmail, {
|
||||
template: 'code-your-own',
|
||||
template: 'user-invitation',
|
||||
variables: {
|
||||
inviteeEmail: inviteeEmail,
|
||||
magicLink: `${process.env.VITE_BASE_URL}`,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { HttpException, Module } from '@nestjs/common';
|
||||
import { ForbiddenException, HttpException, Module } from '@nestjs/common';
|
||||
import { GraphQLModule } from '@nestjs/graphql';
|
||||
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
|
||||
import { UserModule } from './user/user.module';
|
||||
@@ -20,35 +20,28 @@ import { ShortcodeModule } from './shortcode/shortcode.module';
|
||||
import { COOKIES_NOT_FOUND } from './errors';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { AppController } from './app.controller';
|
||||
import { Context } from 'graphql-ws';
|
||||
import {
|
||||
ApolloServerPluginLandingPageLocalDefault,
|
||||
ApolloServerPluginLandingPageProductionDefault,
|
||||
} from '@apollo/server/plugin/landingPage/default';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
GraphQLModule.forRoot<ApolloDriverConfig>({
|
||||
driver: ApolloDriver,
|
||||
buildSchemaOptions: {
|
||||
numberScalarMode: 'integer',
|
||||
},
|
||||
playground: false,
|
||||
plugins: [
|
||||
process.env.PRODUCTION !== 'true'
|
||||
? ApolloServerPluginLandingPageLocalDefault()
|
||||
: ApolloServerPluginLandingPageProductionDefault(),
|
||||
],
|
||||
playground: process.env.PRODUCTION !== 'true',
|
||||
autoSchemaFile: true,
|
||||
installSubscriptionHandlers: true,
|
||||
subscriptions: {
|
||||
'graphql-ws': {
|
||||
'subscriptions-transport-ws': {
|
||||
path: '/graphql',
|
||||
onConnect: (context: Context<any, any>) => {
|
||||
onConnect: (_, websocket) => {
|
||||
try {
|
||||
const cookies = subscriptionContextCookieParser(
|
||||
context.extra.request.headers.cookie,
|
||||
websocket.upgradeReq.headers.cookie,
|
||||
);
|
||||
context['cookies'] = cookies;
|
||||
|
||||
return {
|
||||
headers: { ...websocket?.upgradeReq?.headers, cookies },
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(COOKIES_NOT_FOUND, 400, {
|
||||
cause: new Error(COOKIES_NOT_FOUND),
|
||||
@@ -62,6 +55,7 @@ import {
|
||||
res,
|
||||
connection,
|
||||
}),
|
||||
driver: ApolloDriver,
|
||||
}),
|
||||
ThrottlerModule.forRoot([
|
||||
{
|
||||
|
||||
@@ -229,7 +229,7 @@ export class AuthService {
|
||||
}
|
||||
|
||||
await this.mailerService.sendEmail(email, {
|
||||
template: 'code-your-own',
|
||||
template: 'user-invitation',
|
||||
variables: {
|
||||
inviteeEmail: email,
|
||||
magicLink: `${url}/enter?token=${generatedTokens.token}`,
|
||||
|
||||
@@ -60,13 +60,13 @@ export const authCookieHandler = (
|
||||
res.cookie(AuthTokenType.ACCESS_TOKEN, authTokens.access_token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: process.env.PRODUCTION !== 'true' ? 'none' : 'lax',
|
||||
sameSite: 'lax',
|
||||
maxAge: accessTokenValidity,
|
||||
});
|
||||
res.cookie(AuthTokenType.REFRESH_TOKEN, authTokens.refresh_token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: process.env.PRODUCTION !== 'true' ? 'none' : 'lax',
|
||||
sameSite: 'lax',
|
||||
maxAge: refreshTokenValidity,
|
||||
});
|
||||
|
||||
|
||||
@@ -318,18 +318,6 @@ export const TEAM_INVITATION_NOT_FOUND =
|
||||
*/
|
||||
export const SHORTCODE_NOT_FOUND = 'shortcode/not_found' as const;
|
||||
|
||||
/**
|
||||
* Invalid ShortCode format
|
||||
* (ShortcodeService)
|
||||
*/
|
||||
export const SHORTCODE_INVALID_JSON = 'shortcode/invalid_json' as const;
|
||||
|
||||
/**
|
||||
* ShortCode already exists in DB
|
||||
* (ShortcodeService)
|
||||
*/
|
||||
export const SHORTCODE_ALREADY_EXISTS = 'shortcode/already_exists' as const;
|
||||
|
||||
/**
|
||||
* Invalid or non-existent TEAM ENVIRONMENT ID
|
||||
* (TeamEnvironmentsService)
|
||||
@@ -621,3 +609,24 @@ export const MAILER_SMTP_URL_UNDEFINED = 'mailer/smtp_url_undefined' as const;
|
||||
*/
|
||||
export const MAILER_FROM_ADDRESS_UNDEFINED =
|
||||
'mailer/from_address_undefined' as const;
|
||||
|
||||
/**
|
||||
* SharedRequest invalid request JSON format
|
||||
* (ShortcodeService)
|
||||
*/
|
||||
export const SHORTCODE_INVALID_REQUEST_JSON =
|
||||
'shortcode/request_invalid_format' as const;
|
||||
|
||||
/**
|
||||
* SharedRequest invalid properties JSON format
|
||||
* (ShortcodeService)
|
||||
*/
|
||||
export const SHORTCODE_INVALID_PROPERTIES_JSON =
|
||||
'shortcode/properties_invalid_format' as const;
|
||||
|
||||
/**
|
||||
* SharedRequest invalid properties not found
|
||||
* (ShortcodeService)
|
||||
*/
|
||||
export const SHORTCODE_PROPERTIES_NOT_FOUND =
|
||||
'shortcode/properties_not_found' as const;
|
||||
|
||||
@@ -8,7 +8,7 @@ export type MailDescription = {
|
||||
};
|
||||
|
||||
export type UserMagicLinkMailDescription = {
|
||||
template: 'code-your-own';
|
||||
template: 'user-invitation';
|
||||
variables: {
|
||||
inviteeEmail: string;
|
||||
magicLink: string;
|
||||
@@ -16,7 +16,7 @@ export type UserMagicLinkMailDescription = {
|
||||
};
|
||||
|
||||
export type AdminUserInvitationMailDescription = {
|
||||
template: 'code-your-own';
|
||||
template: 'user-invitation';
|
||||
variables: {
|
||||
inviteeEmail: string;
|
||||
magicLink: string;
|
||||
|
||||
@@ -27,7 +27,7 @@ export class MailerService {
|
||||
case 'team-invitation':
|
||||
return `${mailDesc.variables.invitee} invited you to join ${mailDesc.variables.invite_team_name} in Hoppscotch`;
|
||||
|
||||
case 'code-your-own':
|
||||
case 'user-invitation':
|
||||
return 'Sign in to Hoppscotch';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
-->
|
||||
<style type="text/css" rel="stylesheet" media="all">
|
||||
/* Base ------------------------------ */
|
||||
|
||||
|
||||
@import url("https://fonts.googleapis.com/css?family=Nunito+Sans:400,700&display=swap");
|
||||
body {
|
||||
width: 100% !important;
|
||||
@@ -22,19 +22,19 @@
|
||||
margin: 0;
|
||||
-webkit-text-size-adjust: none;
|
||||
}
|
||||
|
||||
|
||||
a {
|
||||
color: #3869D4;
|
||||
}
|
||||
|
||||
|
||||
a img {
|
||||
border: none;
|
||||
}
|
||||
|
||||
|
||||
td {
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
|
||||
.preheader {
|
||||
display: none !important;
|
||||
visibility: hidden;
|
||||
@@ -47,13 +47,13 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Type ------------------------------ */
|
||||
|
||||
|
||||
body,
|
||||
td,
|
||||
th {
|
||||
font-family: "Nunito Sans", Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
|
||||
h1 {
|
||||
margin-top: 0;
|
||||
color: #333333;
|
||||
@@ -61,7 +61,7 @@
|
||||
font-weight: bold;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
|
||||
h2 {
|
||||
margin-top: 0;
|
||||
color: #333333;
|
||||
@@ -69,7 +69,7 @@
|
||||
font-weight: bold;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
|
||||
h3 {
|
||||
margin-top: 0;
|
||||
color: #333333;
|
||||
@@ -77,12 +77,12 @@
|
||||
font-weight: bold;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
|
||||
td,
|
||||
th {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
|
||||
p,
|
||||
ul,
|
||||
ol,
|
||||
@@ -91,25 +91,25 @@
|
||||
font-size: 16px;
|
||||
line-height: 1.625;
|
||||
}
|
||||
|
||||
|
||||
p.sub {
|
||||
font-size: 13px;
|
||||
}
|
||||
/* Utilities ------------------------------ */
|
||||
|
||||
|
||||
.align-right {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
|
||||
.align-left {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
|
||||
.align-center {
|
||||
text-align: center;
|
||||
}
|
||||
/* Buttons ------------------------------ */
|
||||
|
||||
|
||||
.button {
|
||||
background-color: #3869D4;
|
||||
border-top: 10px solid #3869D4;
|
||||
@@ -124,7 +124,7 @@
|
||||
-webkit-text-size-adjust: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
|
||||
.button--green {
|
||||
background-color: #22BC66;
|
||||
border-top: 10px solid #22BC66;
|
||||
@@ -132,7 +132,7 @@
|
||||
border-bottom: 10px solid #22BC66;
|
||||
border-left: 18px solid #22BC66;
|
||||
}
|
||||
|
||||
|
||||
.button--red {
|
||||
background-color: #FF6136;
|
||||
border-top: 10px solid #FF6136;
|
||||
@@ -140,7 +140,7 @@
|
||||
border-bottom: 10px solid #FF6136;
|
||||
border-left: 18px solid #FF6136;
|
||||
}
|
||||
|
||||
|
||||
@media only screen and (max-width: 500px) {
|
||||
.button {
|
||||
width: 100% !important;
|
||||
@@ -148,21 +148,21 @@
|
||||
}
|
||||
}
|
||||
/* Attribute list ------------------------------ */
|
||||
|
||||
|
||||
.attributes {
|
||||
margin: 0 0 21px;
|
||||
}
|
||||
|
||||
|
||||
.attributes_content {
|
||||
background-color: #F4F4F7;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
|
||||
.attributes_item {
|
||||
padding: 0;
|
||||
}
|
||||
/* Related Items ------------------------------ */
|
||||
|
||||
|
||||
.related {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
@@ -171,31 +171,31 @@
|
||||
-premailer-cellpadding: 0;
|
||||
-premailer-cellspacing: 0;
|
||||
}
|
||||
|
||||
|
||||
.related_item {
|
||||
padding: 10px 0;
|
||||
color: #CBCCCF;
|
||||
font-size: 15px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
|
||||
.related_item-title {
|
||||
display: block;
|
||||
margin: .5em 0 0;
|
||||
}
|
||||
|
||||
|
||||
.related_item-thumb {
|
||||
display: block;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
|
||||
.related_heading {
|
||||
border-top: 1px solid #CBCCCF;
|
||||
text-align: center;
|
||||
padding: 25px 0 10px;
|
||||
}
|
||||
/* Discount Code ------------------------------ */
|
||||
|
||||
|
||||
.discount {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
@@ -206,33 +206,33 @@
|
||||
background-color: #F4F4F7;
|
||||
border: 2px dashed #CBCCCF;
|
||||
}
|
||||
|
||||
|
||||
.discount_heading {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
|
||||
.discount_body {
|
||||
text-align: center;
|
||||
font-size: 15px;
|
||||
}
|
||||
/* Social Icons ------------------------------ */
|
||||
|
||||
|
||||
.social {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
|
||||
.social td {
|
||||
padding: 0;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
|
||||
.social_icon {
|
||||
height: 20px;
|
||||
margin: 0 8px 10px 8px;
|
||||
padding: 0;
|
||||
}
|
||||
/* Data table ------------------------------ */
|
||||
|
||||
|
||||
.purchase {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
@@ -241,7 +241,7 @@
|
||||
-premailer-cellpadding: 0;
|
||||
-premailer-cellspacing: 0;
|
||||
}
|
||||
|
||||
|
||||
.purchase_content {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
@@ -250,50 +250,50 @@
|
||||
-premailer-cellpadding: 0;
|
||||
-premailer-cellspacing: 0;
|
||||
}
|
||||
|
||||
|
||||
.purchase_item {
|
||||
padding: 10px 0;
|
||||
color: #51545E;
|
||||
font-size: 15px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
|
||||
.purchase_heading {
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid #EAEAEC;
|
||||
}
|
||||
|
||||
|
||||
.purchase_heading p {
|
||||
margin: 0;
|
||||
color: #85878E;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
|
||||
.purchase_footer {
|
||||
padding-top: 15px;
|
||||
border-top: 1px solid #EAEAEC;
|
||||
}
|
||||
|
||||
|
||||
.purchase_total {
|
||||
margin: 0;
|
||||
text-align: right;
|
||||
font-weight: bold;
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
|
||||
.purchase_total--label {
|
||||
padding: 0 15px 0 0;
|
||||
}
|
||||
|
||||
|
||||
body {
|
||||
background-color: #F2F4F6;
|
||||
color: #51545E;
|
||||
}
|
||||
|
||||
|
||||
p {
|
||||
color: #51545E;
|
||||
}
|
||||
|
||||
|
||||
.email-wrapper {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
@@ -303,7 +303,7 @@
|
||||
-premailer-cellspacing: 0;
|
||||
background-color: #F2F4F6;
|
||||
}
|
||||
|
||||
|
||||
.email-content {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
@@ -313,16 +313,16 @@
|
||||
-premailer-cellspacing: 0;
|
||||
}
|
||||
/* Masthead ----------------------- */
|
||||
|
||||
|
||||
.email-masthead {
|
||||
padding: 25px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
|
||||
.email-masthead_logo {
|
||||
width: 94px;
|
||||
}
|
||||
|
||||
|
||||
.email-masthead_name {
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
@@ -331,7 +331,7 @@
|
||||
text-shadow: 0 1px 0 white;
|
||||
}
|
||||
/* Body ------------------------------ */
|
||||
|
||||
|
||||
.email-body {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
@@ -340,7 +340,7 @@
|
||||
-premailer-cellpadding: 0;
|
||||
-premailer-cellspacing: 0;
|
||||
}
|
||||
|
||||
|
||||
.email-body_inner {
|
||||
width: 570px;
|
||||
margin: 0 auto;
|
||||
@@ -350,7 +350,7 @@
|
||||
-premailer-cellspacing: 0;
|
||||
background-color: #FFFFFF;
|
||||
}
|
||||
|
||||
|
||||
.email-footer {
|
||||
width: 570px;
|
||||
margin: 0 auto;
|
||||
@@ -360,11 +360,11 @@
|
||||
-premailer-cellspacing: 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
|
||||
.email-footer p {
|
||||
color: #A8AAAF;
|
||||
}
|
||||
|
||||
|
||||
.body-action {
|
||||
width: 100%;
|
||||
margin: 30px auto;
|
||||
@@ -374,25 +374,25 @@
|
||||
-premailer-cellspacing: 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
|
||||
.body-sub {
|
||||
margin-top: 25px;
|
||||
padding-top: 25px;
|
||||
border-top: 1px solid #EAEAEC;
|
||||
}
|
||||
|
||||
|
||||
.content-cell {
|
||||
padding: 45px;
|
||||
}
|
||||
/*Media Queries ------------------------------ */
|
||||
|
||||
|
||||
@media only screen and (max-width: 600px) {
|
||||
.email-body_inner,
|
||||
.email-footer {
|
||||
width: 100% !important;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body,
|
||||
.email-body,
|
||||
|
||||
@@ -69,5 +69,7 @@ export type TopicDef = {
|
||||
[topic: `team_req/${string}/req_deleted`]: string;
|
||||
[topic: `team/${string}/invite_added`]: TeamInvitation;
|
||||
[topic: `team/${string}/invite_removed`]: string;
|
||||
[topic: `shortcode/${string}/${'created' | 'revoked'}`]: Shortcode;
|
||||
[
|
||||
topic: `shortcode/${string}/${'created' | 'revoked' | 'updated'}`
|
||||
]: Shortcode;
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Field, ID, ObjectType } from '@nestjs/graphql';
|
||||
@ObjectType()
|
||||
export class Shortcode {
|
||||
@Field(() => ID, {
|
||||
description: 'The shortcode. 12 digit alphanumeric.',
|
||||
description: 'The 12 digit alphanumeric code',
|
||||
})
|
||||
id: string;
|
||||
|
||||
@@ -12,6 +12,12 @@ export class Shortcode {
|
||||
})
|
||||
request: string;
|
||||
|
||||
@Field({
|
||||
description: 'JSON string representing the properties for an embed',
|
||||
nullable: true,
|
||||
})
|
||||
properties: string;
|
||||
|
||||
@Field({
|
||||
description: 'Timestamp of when the Shortcode was created',
|
||||
})
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PrismaModule } from 'src/prisma/prisma.module';
|
||||
import { PubSubModule } from 'src/pubsub/pubsub.module';
|
||||
import { UserModule } from 'src/user/user.module';
|
||||
@@ -7,14 +6,7 @@ import { ShortcodeResolver } from './shortcode.resolver';
|
||||
import { ShortcodeService } from './shortcode.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
PrismaModule,
|
||||
UserModule,
|
||||
PubSubModule,
|
||||
JwtModule.register({
|
||||
secret: process.env.JWT_SECRET,
|
||||
}),
|
||||
],
|
||||
imports: [PrismaModule, UserModule, PubSubModule],
|
||||
providers: [ShortcodeService, ShortcodeResolver],
|
||||
exports: [ShortcodeService],
|
||||
})
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
Args,
|
||||
Context,
|
||||
ID,
|
||||
Mutation,
|
||||
Query,
|
||||
@@ -11,14 +10,12 @@ import * as E from 'fp-ts/Either';
|
||||
import { UseGuards } from '@nestjs/common';
|
||||
import { Shortcode } from './shortcode.model';
|
||||
import { ShortcodeService } from './shortcode.service';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
import { throwErr } from 'src/utils';
|
||||
import { GqlUser } from 'src/decorators/gql-user.decorator';
|
||||
import { GqlAuthGuard } from 'src/guards/gql-auth.guard';
|
||||
import { User } from 'src/user/user.model';
|
||||
import { PubSubService } from 'src/pubsub/pubsub.service';
|
||||
import { AuthUser } from '../types/AuthUser';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { PaginationArgs } from 'src/types/input-types.args';
|
||||
import { GqlThrottlerGuard } from 'src/guards/gql-throttler.guard';
|
||||
import { SkipThrottle } from '@nestjs/throttler';
|
||||
@@ -28,9 +25,7 @@ import { SkipThrottle } from '@nestjs/throttler';
|
||||
export class ShortcodeResolver {
|
||||
constructor(
|
||||
private readonly shortcodeService: ShortcodeService,
|
||||
private readonly userService: UserService,
|
||||
private readonly pubsub: PubSubService,
|
||||
private jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
/* Queries */
|
||||
@@ -64,20 +59,53 @@ export class ShortcodeResolver {
|
||||
@Mutation(() => Shortcode, {
|
||||
description: 'Create a shortcode for the given request.',
|
||||
})
|
||||
@UseGuards(GqlAuthGuard)
|
||||
async createShortcode(
|
||||
@GqlUser() user: AuthUser,
|
||||
@Args({
|
||||
name: 'request',
|
||||
description: 'JSON string of the request object',
|
||||
})
|
||||
request: string,
|
||||
@Context() ctx: any,
|
||||
@Args({
|
||||
name: 'properties',
|
||||
description: 'JSON string of the properties of the embed',
|
||||
nullable: true,
|
||||
})
|
||||
properties: string,
|
||||
) {
|
||||
const decodedAccessToken = this.jwtService.verify(
|
||||
ctx.req.cookies['access_token'],
|
||||
);
|
||||
const result = await this.shortcodeService.createShortcode(
|
||||
request,
|
||||
decodedAccessToken?.sub,
|
||||
properties,
|
||||
user,
|
||||
);
|
||||
|
||||
if (E.isLeft(result)) throwErr(result.left);
|
||||
return result.right;
|
||||
}
|
||||
|
||||
@Mutation(() => Shortcode, {
|
||||
description: 'Update a user generated Shortcode',
|
||||
})
|
||||
@UseGuards(GqlAuthGuard)
|
||||
async updateEmbedProperties(
|
||||
@GqlUser() user: AuthUser,
|
||||
@Args({
|
||||
name: 'code',
|
||||
type: () => ID,
|
||||
description: 'The Shortcode to update',
|
||||
})
|
||||
code: string,
|
||||
@Args({
|
||||
name: 'properties',
|
||||
description: 'JSON string of the properties of the embed',
|
||||
})
|
||||
properties: string,
|
||||
) {
|
||||
const result = await this.shortcodeService.updateEmbedProperties(
|
||||
code,
|
||||
user.uid,
|
||||
properties,
|
||||
);
|
||||
|
||||
if (E.isLeft(result)) throwErr(result.left);
|
||||
@@ -114,6 +142,16 @@ export class ShortcodeResolver {
|
||||
return this.pubsub.asyncIterator(`shortcode/${user.uid}/created`);
|
||||
}
|
||||
|
||||
@Subscription(() => Shortcode, {
|
||||
description: 'Listen for Shortcode updates',
|
||||
resolve: (value) => value,
|
||||
})
|
||||
@SkipThrottle()
|
||||
@UseGuards(GqlAuthGuard)
|
||||
myShortcodesUpdated(@GqlUser() user: AuthUser) {
|
||||
return this.pubsub.asyncIterator(`shortcode/${user.uid}/updated`);
|
||||
}
|
||||
|
||||
@Subscription(() => Shortcode, {
|
||||
description: 'Listen for shortcode deletion',
|
||||
resolve: (value) => value,
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { mockDeep, mockReset } from 'jest-mock-extended';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import {
|
||||
SHORTCODE_ALREADY_EXISTS,
|
||||
SHORTCODE_INVALID_JSON,
|
||||
SHORTCODE_INVALID_PROPERTIES_JSON,
|
||||
SHORTCODE_INVALID_REQUEST_JSON,
|
||||
SHORTCODE_NOT_FOUND,
|
||||
SHORTCODE_PROPERTIES_NOT_FOUND,
|
||||
} from 'src/errors';
|
||||
import { Shortcode } from './shortcode.model';
|
||||
import { ShortcodeService } from './shortcode.service';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
import { AuthUser } from 'src/types/AuthUser';
|
||||
|
||||
const mockPrisma = mockDeep<PrismaService>();
|
||||
|
||||
@@ -22,7 +24,7 @@ const mockFB = {
|
||||
doc: mockDocFunc,
|
||||
},
|
||||
};
|
||||
const mockUserService = new UserService(mockFB as any, mockPubSub as any);
|
||||
const mockUserService = new UserService(mockPrisma as any, mockPubSub as any);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
@@ -38,18 +40,34 @@ beforeEach(() => {
|
||||
});
|
||||
const createdOn = new Date();
|
||||
|
||||
const shortCodeWithOutUser = {
|
||||
id: '123',
|
||||
request: '{}',
|
||||
const user: AuthUser = {
|
||||
uid: '123344',
|
||||
email: 'dwight@dundermifflin.com',
|
||||
displayName: 'Dwight Schrute',
|
||||
photoURL: 'https://en.wikipedia.org/wiki/Dwight_Schrute',
|
||||
isAdmin: false,
|
||||
refreshToken: 'hbfvdkhjbvkdvdfjvbnkhjb',
|
||||
createdOn: createdOn,
|
||||
creatorUid: null,
|
||||
currentGQLSession: {},
|
||||
currentRESTSession: {},
|
||||
};
|
||||
|
||||
const shortCodeWithUser = {
|
||||
const mockEmbed = {
|
||||
id: '123',
|
||||
request: '{}',
|
||||
embedProperties: '{}',
|
||||
createdOn: createdOn,
|
||||
creatorUid: 'user_uid_1',
|
||||
creatorUid: user.uid,
|
||||
updatedOn: createdOn,
|
||||
};
|
||||
|
||||
const mockShortcode = {
|
||||
id: '123',
|
||||
request: '{}',
|
||||
embedProperties: null,
|
||||
createdOn: createdOn,
|
||||
creatorUid: user.uid,
|
||||
updatedOn: createdOn,
|
||||
};
|
||||
|
||||
const shortcodes = [
|
||||
@@ -58,33 +76,38 @@ const shortcodes = [
|
||||
request: {
|
||||
hello: 'there',
|
||||
},
|
||||
creatorUid: 'testuser',
|
||||
embedProperties: {
|
||||
foo: 'bar',
|
||||
},
|
||||
creatorUid: user.uid,
|
||||
createdOn: new Date(),
|
||||
updatedOn: createdOn,
|
||||
},
|
||||
{
|
||||
id: 'blablabla1',
|
||||
request: {
|
||||
hello: 'there',
|
||||
},
|
||||
creatorUid: 'testuser',
|
||||
embedProperties: {
|
||||
foo: 'bar',
|
||||
},
|
||||
creatorUid: user.uid,
|
||||
createdOn: new Date(),
|
||||
updatedOn: createdOn,
|
||||
},
|
||||
];
|
||||
|
||||
describe('ShortcodeService', () => {
|
||||
describe('getShortCode', () => {
|
||||
test('should return a valid shortcode with valid shortcode ID', async () => {
|
||||
mockPrisma.shortcode.findFirstOrThrow.mockResolvedValueOnce(
|
||||
shortCodeWithOutUser,
|
||||
);
|
||||
test('should return a valid Shortcode with valid Shortcode ID', async () => {
|
||||
mockPrisma.shortcode.findFirstOrThrow.mockResolvedValueOnce(mockEmbed);
|
||||
|
||||
const result = await shortcodeService.getShortCode(
|
||||
shortCodeWithOutUser.id,
|
||||
);
|
||||
const result = await shortcodeService.getShortCode(mockEmbed.id);
|
||||
expect(result).toEqualRight(<Shortcode>{
|
||||
id: shortCodeWithOutUser.id,
|
||||
createdOn: shortCodeWithOutUser.createdOn,
|
||||
request: JSON.stringify(shortCodeWithOutUser.request),
|
||||
id: mockEmbed.id,
|
||||
createdOn: mockEmbed.createdOn,
|
||||
request: JSON.stringify(mockEmbed.request),
|
||||
properties: JSON.stringify(mockEmbed.embedProperties),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -99,10 +122,10 @@ describe('ShortcodeService', () => {
|
||||
});
|
||||
|
||||
describe('fetchUserShortCodes', () => {
|
||||
test('should return list of shortcodes with valid inputs and no cursor', async () => {
|
||||
test('should return list of Shortcode with valid inputs and no cursor', async () => {
|
||||
mockPrisma.shortcode.findMany.mockResolvedValueOnce(shortcodes);
|
||||
|
||||
const result = await shortcodeService.fetchUserShortCodes('testuser', {
|
||||
const result = await shortcodeService.fetchUserShortCodes(user.uid, {
|
||||
cursor: null,
|
||||
take: 10,
|
||||
});
|
||||
@@ -110,20 +133,22 @@ describe('ShortcodeService', () => {
|
||||
{
|
||||
id: shortcodes[0].id,
|
||||
request: JSON.stringify(shortcodes[0].request),
|
||||
properties: JSON.stringify(shortcodes[0].embedProperties),
|
||||
createdOn: shortcodes[0].createdOn,
|
||||
},
|
||||
{
|
||||
id: shortcodes[1].id,
|
||||
request: JSON.stringify(shortcodes[1].request),
|
||||
properties: JSON.stringify(shortcodes[1].embedProperties),
|
||||
createdOn: shortcodes[1].createdOn,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('should return list of shortcodes with valid inputs and cursor', async () => {
|
||||
test('should return list of Shortcode with valid inputs and cursor', async () => {
|
||||
mockPrisma.shortcode.findMany.mockResolvedValue([shortcodes[1]]);
|
||||
|
||||
const result = await shortcodeService.fetchUserShortCodes('testuser', {
|
||||
const result = await shortcodeService.fetchUserShortCodes(user.uid, {
|
||||
cursor: 'blablabla',
|
||||
take: 10,
|
||||
});
|
||||
@@ -131,6 +156,7 @@ describe('ShortcodeService', () => {
|
||||
{
|
||||
id: shortcodes[1].id,
|
||||
request: JSON.stringify(shortcodes[1].request),
|
||||
properties: JSON.stringify(shortcodes[1].embedProperties),
|
||||
createdOn: shortcodes[1].createdOn,
|
||||
},
|
||||
]);
|
||||
@@ -139,7 +165,7 @@ describe('ShortcodeService', () => {
|
||||
test('should return an empty array for an invalid cursor', async () => {
|
||||
mockPrisma.shortcode.findMany.mockResolvedValue([]);
|
||||
|
||||
const result = await shortcodeService.fetchUserShortCodes('testuser', {
|
||||
const result = await shortcodeService.fetchUserShortCodes(user.uid, {
|
||||
cursor: 'invalidcursor',
|
||||
take: 10,
|
||||
});
|
||||
@@ -171,77 +197,111 @@ describe('ShortcodeService', () => {
|
||||
});
|
||||
|
||||
describe('createShortcode', () => {
|
||||
test('should throw SHORTCODE_INVALID_JSON error if incoming request data is invalid', async () => {
|
||||
test('should throw SHORTCODE_INVALID_REQUEST_JSON error if incoming request data is invalid', async () => {
|
||||
const result = await shortcodeService.createShortcode(
|
||||
'invalidRequest',
|
||||
'user_uid_1',
|
||||
null,
|
||||
user,
|
||||
);
|
||||
expect(result).toEqualLeft(SHORTCODE_INVALID_JSON);
|
||||
expect(result).toEqualLeft(SHORTCODE_INVALID_REQUEST_JSON);
|
||||
});
|
||||
|
||||
test('should successfully create a new shortcode with valid user uid', async () => {
|
||||
// generateUniqueShortCodeID --> getShortCode
|
||||
test('should throw SHORTCODE_INVALID_PROPERTIES_JSON error if incoming properties data is invalid', async () => {
|
||||
const result = await shortcodeService.createShortcode(
|
||||
'{}',
|
||||
'invalid_data',
|
||||
user,
|
||||
);
|
||||
expect(result).toEqualLeft(SHORTCODE_INVALID_PROPERTIES_JSON);
|
||||
});
|
||||
|
||||
test('should successfully create a new Embed with valid user uid', async () => {
|
||||
// generateUniqueShortCodeID --> getShortcode
|
||||
mockPrisma.shortcode.findFirstOrThrow.mockRejectedValueOnce(
|
||||
'NotFoundError',
|
||||
);
|
||||
mockPrisma.shortcode.create.mockResolvedValueOnce(shortCodeWithUser);
|
||||
mockPrisma.shortcode.create.mockResolvedValueOnce(mockEmbed);
|
||||
|
||||
const result = await shortcodeService.createShortcode('{}', 'user_uid_1');
|
||||
expect(result).toEqualRight({
|
||||
id: shortCodeWithUser.id,
|
||||
createdOn: shortCodeWithUser.createdOn,
|
||||
request: JSON.stringify(shortCodeWithUser.request),
|
||||
const result = await shortcodeService.createShortcode('{}', '{}', user);
|
||||
expect(result).toEqualRight(<Shortcode>{
|
||||
id: mockEmbed.id,
|
||||
createdOn: mockEmbed.createdOn,
|
||||
request: JSON.stringify(mockEmbed.request),
|
||||
properties: JSON.stringify(mockEmbed.embedProperties),
|
||||
});
|
||||
});
|
||||
|
||||
test('should successfully create a new shortcode with null user uid', async () => {
|
||||
// generateUniqueShortCodeID --> getShortCode
|
||||
test('should successfully create a new ShortCode with valid user uid', async () => {
|
||||
// generateUniqueShortCodeID --> getShortcode
|
||||
mockPrisma.shortcode.findFirstOrThrow.mockRejectedValueOnce(
|
||||
'NotFoundError',
|
||||
);
|
||||
mockPrisma.shortcode.create.mockResolvedValueOnce(shortCodeWithUser);
|
||||
mockPrisma.shortcode.create.mockResolvedValueOnce(mockShortcode);
|
||||
|
||||
const result = await shortcodeService.createShortcode('{}', null);
|
||||
expect(result).toEqualRight({
|
||||
id: shortCodeWithUser.id,
|
||||
createdOn: shortCodeWithUser.createdOn,
|
||||
request: JSON.stringify(shortCodeWithOutUser.request),
|
||||
const result = await shortcodeService.createShortcode('{}', null, user);
|
||||
expect(result).toEqualRight(<Shortcode>{
|
||||
id: mockShortcode.id,
|
||||
createdOn: mockShortcode.createdOn,
|
||||
request: JSON.stringify(mockShortcode.request),
|
||||
properties: mockShortcode.embedProperties,
|
||||
});
|
||||
});
|
||||
|
||||
test('should send pubsub message to `shortcode/{uid}/created` on successful creation of shortcode', async () => {
|
||||
// generateUniqueShortCodeID --> getShortCode
|
||||
test('should send pubsub message to `shortcode/{uid}/created` on successful creation of a Shortcode', async () => {
|
||||
// generateUniqueShortCodeID --> getShortcode
|
||||
mockPrisma.shortcode.findFirstOrThrow.mockRejectedValueOnce(
|
||||
'NotFoundError',
|
||||
);
|
||||
mockPrisma.shortcode.create.mockResolvedValueOnce(shortCodeWithUser);
|
||||
mockPrisma.shortcode.create.mockResolvedValueOnce(mockShortcode);
|
||||
|
||||
const result = await shortcodeService.createShortcode('{}', null, user);
|
||||
|
||||
const result = await shortcodeService.createShortcode('{}', 'user_uid_1');
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`shortcode/${shortCodeWithUser.creatorUid}/created`,
|
||||
{
|
||||
id: shortCodeWithUser.id,
|
||||
createdOn: shortCodeWithUser.createdOn,
|
||||
request: JSON.stringify(shortCodeWithUser.request),
|
||||
`shortcode/${mockShortcode.creatorUid}/created`,
|
||||
<Shortcode>{
|
||||
id: mockShortcode.id,
|
||||
createdOn: mockShortcode.createdOn,
|
||||
request: JSON.stringify(mockShortcode.request),
|
||||
properties: mockShortcode.embedProperties,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('should send pubsub message to `shortcode/{uid}/created` on successful creation of an Embed', async () => {
|
||||
// generateUniqueShortCodeID --> getShortcode
|
||||
mockPrisma.shortcode.findFirstOrThrow.mockRejectedValueOnce(
|
||||
'NotFoundError',
|
||||
);
|
||||
mockPrisma.shortcode.create.mockResolvedValueOnce(mockEmbed);
|
||||
|
||||
const result = await shortcodeService.createShortcode('{}', '{}', user);
|
||||
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`shortcode/${mockEmbed.creatorUid}/created`,
|
||||
<Shortcode>{
|
||||
id: mockEmbed.id,
|
||||
createdOn: mockEmbed.createdOn,
|
||||
request: JSON.stringify(mockEmbed.request),
|
||||
properties: JSON.stringify(mockEmbed.embedProperties),
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('revokeShortCode', () => {
|
||||
test('should return true on successful deletion of shortcode with valid inputs', async () => {
|
||||
mockPrisma.shortcode.delete.mockResolvedValueOnce(shortCodeWithUser);
|
||||
test('should return true on successful deletion of Shortcode with valid inputs', async () => {
|
||||
mockPrisma.shortcode.delete.mockResolvedValueOnce(mockEmbed);
|
||||
|
||||
const result = await shortcodeService.revokeShortCode(
|
||||
shortCodeWithUser.id,
|
||||
shortCodeWithUser.creatorUid,
|
||||
mockEmbed.id,
|
||||
mockEmbed.creatorUid,
|
||||
);
|
||||
|
||||
expect(mockPrisma.shortcode.delete).toHaveBeenCalledWith({
|
||||
where: {
|
||||
creator_uid_shortcode_unique: {
|
||||
creatorUid: shortCodeWithUser.creatorUid,
|
||||
id: shortCodeWithUser.id,
|
||||
creatorUid: mockEmbed.creatorUid,
|
||||
id: mockEmbed.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -249,52 +309,53 @@ describe('ShortcodeService', () => {
|
||||
expect(result).toEqualRight(true);
|
||||
});
|
||||
|
||||
test('should return SHORTCODE_NOT_FOUND error when shortcode is invalid and user uid is valid', async () => {
|
||||
test('should return SHORTCODE_NOT_FOUND error when Shortcode is invalid and user uid is valid', async () => {
|
||||
mockPrisma.shortcode.delete.mockRejectedValue('RecordNotFound');
|
||||
expect(
|
||||
shortcodeService.revokeShortCode('invalid', 'testuser'),
|
||||
).resolves.toEqualLeft(SHORTCODE_NOT_FOUND);
|
||||
});
|
||||
|
||||
test('should return SHORTCODE_NOT_FOUND error when shortcode is valid and user uid is invalid', async () => {
|
||||
test('should return SHORTCODE_NOT_FOUND error when Shortcode is valid and user uid is invalid', async () => {
|
||||
mockPrisma.shortcode.delete.mockRejectedValue('RecordNotFound');
|
||||
expect(
|
||||
shortcodeService.revokeShortCode('blablablabla', 'invalidUser'),
|
||||
).resolves.toEqualLeft(SHORTCODE_NOT_FOUND);
|
||||
});
|
||||
|
||||
test('should return SHORTCODE_NOT_FOUND error when both shortcode and user uid are invalid', async () => {
|
||||
test('should return SHORTCODE_NOT_FOUND error when both Shortcode and user uid are invalid', async () => {
|
||||
mockPrisma.shortcode.delete.mockRejectedValue('RecordNotFound');
|
||||
expect(
|
||||
shortcodeService.revokeShortCode('invalid', 'invalid'),
|
||||
).resolves.toEqualLeft(SHORTCODE_NOT_FOUND);
|
||||
});
|
||||
|
||||
test('should send pubsub message to `shortcode/{uid}/revoked` on successful deletion of shortcode', async () => {
|
||||
mockPrisma.shortcode.delete.mockResolvedValueOnce(shortCodeWithUser);
|
||||
test('should send pubsub message to `shortcode/{uid}/revoked` on successful deletion of Shortcode', async () => {
|
||||
mockPrisma.shortcode.delete.mockResolvedValueOnce(mockEmbed);
|
||||
|
||||
const result = await shortcodeService.revokeShortCode(
|
||||
shortCodeWithUser.id,
|
||||
shortCodeWithUser.creatorUid,
|
||||
mockEmbed.id,
|
||||
mockEmbed.creatorUid,
|
||||
);
|
||||
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`shortcode/${shortCodeWithUser.creatorUid}/revoked`,
|
||||
`shortcode/${mockEmbed.creatorUid}/revoked`,
|
||||
{
|
||||
id: shortCodeWithUser.id,
|
||||
createdOn: shortCodeWithUser.createdOn,
|
||||
request: JSON.stringify(shortCodeWithUser.request),
|
||||
id: mockEmbed.id,
|
||||
createdOn: mockEmbed.createdOn,
|
||||
request: JSON.stringify(mockEmbed.request),
|
||||
properties: JSON.stringify(mockEmbed.embedProperties),
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteUserShortCodes', () => {
|
||||
test('should successfully delete all users shortcodes with valid user uid', async () => {
|
||||
test('should successfully delete all users Shortcodes with valid user uid', async () => {
|
||||
mockPrisma.shortcode.deleteMany.mockResolvedValueOnce({ count: 1 });
|
||||
|
||||
const result = await shortcodeService.deleteUserShortCodes(
|
||||
shortCodeWithUser.creatorUid,
|
||||
mockEmbed.creatorUid,
|
||||
);
|
||||
expect(result).toEqual(1);
|
||||
});
|
||||
@@ -303,9 +364,81 @@ describe('ShortcodeService', () => {
|
||||
mockPrisma.shortcode.deleteMany.mockResolvedValueOnce({ count: 0 });
|
||||
|
||||
const result = await shortcodeService.deleteUserShortCodes(
|
||||
shortCodeWithUser.creatorUid,
|
||||
mockEmbed.creatorUid,
|
||||
);
|
||||
expect(result).toEqual(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateShortcode', () => {
|
||||
test('should return SHORTCODE_PROPERTIES_NOT_FOUND error when updatedProps in invalid', async () => {
|
||||
const result = await shortcodeService.updateEmbedProperties(
|
||||
mockEmbed.id,
|
||||
user.uid,
|
||||
'',
|
||||
);
|
||||
expect(result).toEqualLeft(SHORTCODE_PROPERTIES_NOT_FOUND);
|
||||
});
|
||||
|
||||
test('should return SHORTCODE_PROPERTIES_NOT_FOUND error when updatedProps in invalid JSON format', async () => {
|
||||
const result = await shortcodeService.updateEmbedProperties(
|
||||
mockEmbed.id,
|
||||
user.uid,
|
||||
'{kk',
|
||||
);
|
||||
expect(result).toEqualLeft(SHORTCODE_INVALID_PROPERTIES_JSON);
|
||||
});
|
||||
|
||||
test('should return SHORTCODE_NOT_FOUND error when Shortcode ID is invalid', async () => {
|
||||
mockPrisma.shortcode.update.mockRejectedValue('RecordNotFound');
|
||||
const result = await shortcodeService.updateEmbedProperties(
|
||||
'invalidID',
|
||||
user.uid,
|
||||
'{}',
|
||||
);
|
||||
expect(result).toEqualLeft(SHORTCODE_NOT_FOUND);
|
||||
});
|
||||
|
||||
test('should successfully update a Shortcodes with valid inputs', async () => {
|
||||
mockPrisma.shortcode.update.mockResolvedValueOnce({
|
||||
...mockEmbed,
|
||||
embedProperties: '{"foo":"bar"}',
|
||||
});
|
||||
|
||||
const result = await shortcodeService.updateEmbedProperties(
|
||||
mockEmbed.id,
|
||||
user.uid,
|
||||
'{"foo":"bar"}',
|
||||
);
|
||||
expect(result).toEqualRight({
|
||||
id: mockEmbed.id,
|
||||
createdOn: mockEmbed.createdOn,
|
||||
request: JSON.stringify(mockEmbed.request),
|
||||
properties: JSON.stringify('{"foo":"bar"}'),
|
||||
});
|
||||
});
|
||||
|
||||
test('should send pubsub message to `shortcode/{uid}/updated` on successful Update of Shortcode', async () => {
|
||||
mockPrisma.shortcode.update.mockResolvedValueOnce({
|
||||
...mockEmbed,
|
||||
embedProperties: '{"foo":"bar"}',
|
||||
});
|
||||
|
||||
const result = await shortcodeService.updateEmbedProperties(
|
||||
mockEmbed.id,
|
||||
user.uid,
|
||||
'{"foo":"bar"}',
|
||||
);
|
||||
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`shortcode/${mockEmbed.creatorUid}/updated`,
|
||||
{
|
||||
id: mockEmbed.id,
|
||||
createdOn: mockEmbed.createdOn,
|
||||
request: JSON.stringify(mockEmbed.request),
|
||||
properties: JSON.stringify('{"foo":"bar"}'),
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import * as T from 'fp-ts/Task';
|
||||
import * as O from 'fp-ts/Option';
|
||||
import * as TO from 'fp-ts/TaskOption';
|
||||
import * as E from 'fp-ts/Either';
|
||||
import { PrismaService } from 'src/prisma/prisma.service';
|
||||
import { SHORTCODE_INVALID_JSON, SHORTCODE_NOT_FOUND } from 'src/errors';
|
||||
import {
|
||||
SHORTCODE_INVALID_PROPERTIES_JSON,
|
||||
SHORTCODE_INVALID_REQUEST_JSON,
|
||||
SHORTCODE_NOT_FOUND,
|
||||
SHORTCODE_PROPERTIES_NOT_FOUND,
|
||||
} from 'src/errors';
|
||||
import { UserDataHandler } from 'src/user/user.data.handler';
|
||||
import { Shortcode } from './shortcode.model';
|
||||
import { Shortcode as DBShortCode } from '@prisma/client';
|
||||
@@ -46,10 +50,14 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
* @param shortcodeInfo Prisma Shortcode type
|
||||
* @returns GQL Shortcode
|
||||
*/
|
||||
private returnShortCode(shortcodeInfo: DBShortCode): Shortcode {
|
||||
private cast(shortcodeInfo: DBShortCode): Shortcode {
|
||||
return <Shortcode>{
|
||||
id: shortcodeInfo.id,
|
||||
request: JSON.stringify(shortcodeInfo.request),
|
||||
properties:
|
||||
shortcodeInfo.embedProperties != null
|
||||
? JSON.stringify(shortcodeInfo.embedProperties)
|
||||
: null,
|
||||
createdOn: shortcodeInfo.createdOn,
|
||||
};
|
||||
}
|
||||
@@ -94,7 +102,7 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
const shortcodeInfo = await this.prisma.shortcode.findFirstOrThrow({
|
||||
where: { id: shortcode },
|
||||
});
|
||||
return E.right(this.returnShortCode(shortcodeInfo));
|
||||
return E.right(this.cast(shortcodeInfo));
|
||||
} catch (error) {
|
||||
return E.left(SHORTCODE_NOT_FOUND);
|
||||
}
|
||||
@@ -104,14 +112,22 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
* Create a new ShortCode
|
||||
*
|
||||
* @param request JSON string of request details
|
||||
* @param userUID user UID, if present
|
||||
* @param userInfo user UI
|
||||
* @param properties JSON string of embed properties, if present
|
||||
* @returns Either of ShortCode or error
|
||||
*/
|
||||
async createShortcode(request: string, userUID: string | null) {
|
||||
const shortcodeData = stringToJson(request);
|
||||
if (E.isLeft(shortcodeData)) return E.left(SHORTCODE_INVALID_JSON);
|
||||
async createShortcode(
|
||||
request: string,
|
||||
properties: string | null = null,
|
||||
userInfo: AuthUser,
|
||||
) {
|
||||
const requestData = stringToJson(request);
|
||||
if (E.isLeft(requestData) || !requestData.right)
|
||||
return E.left(SHORTCODE_INVALID_REQUEST_JSON);
|
||||
|
||||
const user = await this.userService.findUserById(userUID);
|
||||
const parsedProperties = stringToJson(properties);
|
||||
if (E.isLeft(parsedProperties))
|
||||
return E.left(SHORTCODE_INVALID_PROPERTIES_JSON);
|
||||
|
||||
const generatedShortCode = await this.generateUniqueShortCodeID();
|
||||
if (E.isLeft(generatedShortCode)) return E.left(generatedShortCode.left);
|
||||
@@ -119,8 +135,9 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
const createdShortCode = await this.prisma.shortcode.create({
|
||||
data: {
|
||||
id: generatedShortCode.right,
|
||||
request: shortcodeData.right,
|
||||
creatorUid: O.isNone(user) ? null : user.value.uid,
|
||||
request: requestData.right,
|
||||
embedProperties: parsedProperties.right ?? undefined,
|
||||
creatorUid: userInfo.uid,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -128,11 +145,11 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
if (createdShortCode.creatorUid) {
|
||||
this.pubsub.publish(
|
||||
`shortcode/${createdShortCode.creatorUid}/created`,
|
||||
this.returnShortCode(createdShortCode),
|
||||
this.cast(createdShortCode),
|
||||
);
|
||||
}
|
||||
|
||||
return E.right(this.returnShortCode(createdShortCode));
|
||||
return E.right(this.cast(createdShortCode));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -156,7 +173,7 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
});
|
||||
|
||||
const fetchedShortCodes: Shortcode[] = shortCodes.map((code) =>
|
||||
this.returnShortCode(code),
|
||||
this.cast(code),
|
||||
);
|
||||
|
||||
return fetchedShortCodes;
|
||||
@@ -182,7 +199,7 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
|
||||
this.pubsub.publish(
|
||||
`shortcode/${deletedShortCodes.creatorUid}/revoked`,
|
||||
this.returnShortCode(deletedShortCodes),
|
||||
this.cast(deletedShortCodes),
|
||||
);
|
||||
|
||||
return E.right(true);
|
||||
@@ -205,4 +222,45 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
|
||||
return deletedShortCodes.count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a created Shortcode
|
||||
* @param shortcodeID Shortcode ID
|
||||
* @param uid User Uid
|
||||
* @returns Updated Shortcode
|
||||
*/
|
||||
async updateEmbedProperties(
|
||||
shortcodeID: string,
|
||||
uid: string,
|
||||
updatedProps: string,
|
||||
) {
|
||||
if (!updatedProps) return E.left(SHORTCODE_PROPERTIES_NOT_FOUND);
|
||||
|
||||
const parsedProperties = stringToJson(updatedProps);
|
||||
if (E.isLeft(parsedProperties) || !parsedProperties.right)
|
||||
return E.left(SHORTCODE_INVALID_PROPERTIES_JSON);
|
||||
|
||||
try {
|
||||
const updatedShortcode = await this.prisma.shortcode.update({
|
||||
where: {
|
||||
creator_uid_shortcode_unique: {
|
||||
creatorUid: uid,
|
||||
id: shortcodeID,
|
||||
},
|
||||
},
|
||||
data: {
|
||||
embedProperties: parsedProperties.right,
|
||||
},
|
||||
});
|
||||
|
||||
this.pubsub.publish(
|
||||
`shortcode/${updatedShortcode.creatorUid}/updated`,
|
||||
this.cast(updatedShortcode),
|
||||
);
|
||||
|
||||
return E.right(this.cast(updatedShortcode));
|
||||
} catch (error) {
|
||||
return E.left(SHORTCODE_NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@hoppscotch/common",
|
||||
"private": true,
|
||||
"version": "2023.8.2",
|
||||
"version": "2023.8.3",
|
||||
"scripts": {
|
||||
"dev": "pnpm exec npm-run-all -p -l dev:*",
|
||||
"test": "vitest --run",
|
||||
@@ -17,22 +17,22 @@
|
||||
"postinstall": "pnpm run gql-codegen",
|
||||
"do-test": "pnpm run test",
|
||||
"do-lint": "pnpm run prod-lint",
|
||||
"do-typecheck": "pnpm run lint",
|
||||
"do-typecheck": "node type-check.mjs",
|
||||
"do-lintfix": "pnpm run lintfix"
|
||||
},
|
||||
"dependencies": {
|
||||
"@apidevtools/swagger-parser": "^10.1.0",
|
||||
"@codemirror/autocomplete": "^6.9.0",
|
||||
"@codemirror/commands": "^6.2.4",
|
||||
"@codemirror/lang-javascript": "^6.1.9",
|
||||
"@codemirror/autocomplete": "^6.10.2",
|
||||
"@codemirror/commands": "^6.3.0",
|
||||
"@codemirror/lang-javascript": "^6.2.1",
|
||||
"@codemirror/lang-json": "^6.0.1",
|
||||
"@codemirror/lang-xml": "^6.0.2",
|
||||
"@codemirror/language": "^6.9.0",
|
||||
"@codemirror/language": "^6.9.2",
|
||||
"@codemirror/legacy-modes": "^6.3.3",
|
||||
"@codemirror/lint": "^6.4.0",
|
||||
"@codemirror/search": "^6.5.1",
|
||||
"@codemirror/state": "^6.2.1",
|
||||
"@codemirror/view": "^6.16.0",
|
||||
"@codemirror/lint": "^6.4.2",
|
||||
"@codemirror/search": "^6.5.4",
|
||||
"@codemirror/state": "^6.3.1",
|
||||
"@codemirror/view": "^6.22.0",
|
||||
"@fontsource-variable/inter": "^5.0.8",
|
||||
"@fontsource-variable/material-symbols-rounded": "^5.0.7",
|
||||
"@fontsource-variable/roboto-mono": "^5.0.9",
|
||||
@@ -41,9 +41,7 @@
|
||||
"@hoppscotch/js-sandbox": "workspace:^",
|
||||
"@hoppscotch/ui": "workspace:^",
|
||||
"@hoppscotch/vue-toasted": "^0.1.0",
|
||||
"@lezer/highlight": "^1.1.6",
|
||||
"@sentry/tracing": "^7.64.0",
|
||||
"@sentry/vue": "^7.64.0",
|
||||
"@lezer/highlight": "1.1.4",
|
||||
"@urql/core": "^4.1.1",
|
||||
"@urql/devtools": "^2.0.3",
|
||||
"@urql/exchange-auth": "^2.1.6",
|
||||
@@ -139,6 +137,7 @@
|
||||
"eslint": "^8.47.0",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"eslint-plugin-vue": "^9.17.0",
|
||||
"glob": "^10.3.10",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss": "^8.4.23",
|
||||
"prettier-plugin-tailwindcss": "^0.5.6",
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
// Read more: https://github.com/vuejs/core/pull/3399
|
||||
export {}
|
||||
|
||||
declare module 'vue' {
|
||||
declare module "vue" {
|
||||
export interface GlobalComponents {
|
||||
AppActionHandler: typeof import('./components/app/ActionHandler.vue')['default']
|
||||
AppAnnouncement: typeof import('./components/app/Announcement.vue')['default']
|
||||
AppBanner: typeof import('./components/app/Banner.vue')['default']
|
||||
AppContextMenu: typeof import('./components/app/ContextMenu.vue')['default']
|
||||
AppDeveloperOptions: typeof import('./components/app/DeveloperOptions.vue')['default']
|
||||
AppFooter: typeof import('./components/app/Footer.vue')['default']
|
||||
@@ -140,6 +141,7 @@ declare module 'vue' {
|
||||
HttpTests: typeof import('./components/http/Tests.vue')['default']
|
||||
HttpURLEncodedParams: typeof import('./components/http/URLEncodedParams.vue')['default']
|
||||
IconLucideActivity: typeof import('~icons/lucide/activity')['default']
|
||||
IconLucideAlertCircle: typeof import('~icons/lucide/alert-circle')['default']
|
||||
IconLucideAlertTriangle: typeof import('~icons/lucide/alert-triangle')['default']
|
||||
IconLucideArrowLeft: typeof import('~icons/lucide/arrow-left')['default']
|
||||
IconLucideArrowUpRight: typeof import('~icons/lucide/arrow-up-right')['default']
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
<template>
|
||||
<div
|
||||
class="group relative flex items-center bg-error px-4 py-2 text-tiny transition"
|
||||
role="alert"
|
||||
>
|
||||
<icon-lucide-info class="mr-2" />
|
||||
<span class="text-secondaryDark">
|
||||
<span class="md:hidden">
|
||||
{{ t("helpers.offline_short") }}
|
||||
</span>
|
||||
<span class="<md:hidden">
|
||||
{{ t("helpers.offline") }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from "~/composables/i18n"
|
||||
|
||||
const t = useI18n()
|
||||
</script>
|
||||
54
packages/hoppscotch-common/src/components/app/Banner.vue
Normal file
54
packages/hoppscotch-common/src/components/app/Banner.vue
Normal file
@@ -0,0 +1,54 @@
|
||||
<template>
|
||||
<div
|
||||
:role="bannerRole"
|
||||
class="flex items-center px-4 py-2 text-tiny"
|
||||
:class="bannerColor"
|
||||
>
|
||||
<component :is="bannerIcon" class="mr-2 text-white" />
|
||||
|
||||
<span class="text-white">
|
||||
<span v-if="banner.alternateText" class="md:hidden">
|
||||
{{ banner.alternateText }}
|
||||
</span>
|
||||
<span class="<md:hidden">
|
||||
{{ banner.text }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue"
|
||||
|
||||
import { BannerContent, BannerType } from "~/services/banner.service"
|
||||
|
||||
import IconAlertCircle from "~icons/lucide/alert-circle"
|
||||
import IconAlertTriangle from "~icons/lucide/alert-triangle"
|
||||
import IconInfo from "~icons/lucide/info"
|
||||
|
||||
const props = defineProps<{
|
||||
banner: BannerContent
|
||||
}>()
|
||||
|
||||
const ariaRoles: Record<BannerType, string> = {
|
||||
error: "alert",
|
||||
warning: "status",
|
||||
info: "status",
|
||||
}
|
||||
|
||||
const bgColors: Record<BannerType, string> = {
|
||||
error: "bg-red-700",
|
||||
warning: "bg-yellow-700",
|
||||
info: "bg-stone-800",
|
||||
}
|
||||
|
||||
const icons = {
|
||||
info: IconInfo,
|
||||
warning: IconAlertCircle,
|
||||
error: IconAlertTriangle,
|
||||
}
|
||||
|
||||
const bannerColor = computed(() => bgColors[props.banner.type])
|
||||
const bannerIcon = computed(() => icons[props.banner.type])
|
||||
const bannerRole = computed(() => ariaRoles[props.banner.type])
|
||||
</script>
|
||||
@@ -215,7 +215,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<AppAnnouncement v-if="!network.isOnline" />
|
||||
<AppBanner v-if="banner" :banner="banner" />
|
||||
<TeamsModal :show="showTeamsModal" @hide-modal="showTeamsModal = false" />
|
||||
<TeamsInvite
|
||||
v-if="workspace.type === 'team' && workspace.teamID"
|
||||
@@ -264,6 +264,7 @@ import IconUsers from "~icons/lucide/users"
|
||||
import { pipe } from "fp-ts/function"
|
||||
import * as TE from "fp-ts/TaskEither"
|
||||
import { deleteTeam as backendDeleteTeam } from "~/helpers/backend/mutations/Team"
|
||||
import { BannerService } from "~/services/banner.service"
|
||||
|
||||
const t = useI18n()
|
||||
const toast = useToast()
|
||||
@@ -281,8 +282,21 @@ const showTeamsModal = ref(false)
|
||||
const breakpoints = useBreakpoints(breakpointsTailwind)
|
||||
const mdAndLarger = breakpoints.greater("md")
|
||||
|
||||
const { content: banner } = useService(BannerService)
|
||||
const network = reactive(useNetwork())
|
||||
|
||||
watch(network, () => {
|
||||
if (network.isOnline) {
|
||||
banner.value = null
|
||||
return
|
||||
}
|
||||
banner.value = {
|
||||
type: "info",
|
||||
text: t("helpers.offline"),
|
||||
alternateText: t("helpers.offline_short"),
|
||||
}
|
||||
})
|
||||
|
||||
const currentUser = useReadonlyStream(
|
||||
platform.auth.getProbableUserStream(),
|
||||
platform.auth.getProbableUser()
|
||||
|
||||
@@ -18,13 +18,12 @@
|
||||
"
|
||||
>
|
||||
<WorkspaceCurrent :section="t('tab.collections')" />
|
||||
|
||||
<HoppSmartInput
|
||||
<input
|
||||
v-model="filterTexts"
|
||||
:placeholder="t('action.search')"
|
||||
input-styles="py-2 pl-4 pr-2 bg-transparent !border-0"
|
||||
type="search"
|
||||
:autofocus="false"
|
||||
autocomplete="off"
|
||||
class="flex h-8 w-full bg-transparent p-4 py-2"
|
||||
:placeholder="t('action.search')"
|
||||
:disabled="collectionsType.type === 'team-collections'"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -66,7 +66,7 @@
|
||||
/>
|
||||
<HoppSmartTabs
|
||||
v-model="selectedEnvTab"
|
||||
:styles="`sticky overflow-x-auto my-2 border border-divider rounded flex-shrink-0 z-0 top-0 bg-primary ${
|
||||
:styles="`sticky overflow-x-auto my-2 border border-divider rounded flex-shrink-0 z-10 top-0 bg-primary ${
|
||||
!isTeamSelected || workspace.type === 'personal'
|
||||
? 'bg-primaryLight'
|
||||
: ''
|
||||
|
||||
@@ -30,8 +30,8 @@
|
||||
v-model="graphqlFieldsFilterText"
|
||||
type="search"
|
||||
autocomplete="off"
|
||||
class="flex h-8 w-full bg-transparent p-4 py-2"
|
||||
:placeholder="`${t('action.search')}`"
|
||||
class="flex flex-1 bg-transparent p-4 py-2"
|
||||
/>
|
||||
<div class="flex">
|
||||
<HoppButtonSecondary
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
v-model="filterText"
|
||||
type="search"
|
||||
autocomplete="off"
|
||||
class="flex flex-1 bg-transparent p-4 py-2"
|
||||
class="flex h-8 w-full bg-transparent p-4 py-2"
|
||||
:placeholder="`${t('action.search')}`"
|
||||
/>
|
||||
<div class="flex">
|
||||
|
||||
@@ -256,7 +256,7 @@ import * as E from "fp-ts/Either"
|
||||
import * as O from "fp-ts/Option"
|
||||
import * as A from "fp-ts/Array"
|
||||
import draggable from "vuedraggable-es"
|
||||
import { RequestOptionTabs } from "./RequestOptions.vue"
|
||||
import { RESTOptionTabs } from "./RequestOptions.vue"
|
||||
import { useCodemirror } from "@composables/codemirror"
|
||||
import { commonHeaders } from "~/helpers/headers"
|
||||
import { useI18n } from "@composables/i18n"
|
||||
@@ -295,7 +295,7 @@ const deletionToast = ref<{ goAway: (delay: number) => void } | null>(null)
|
||||
const props = defineProps<{ modelValue: HoppRESTRequest }>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "change-tab", value: RequestOptionTabs): void
|
||||
(e: "change-tab", value: RESTOptionTabs): void
|
||||
(e: "update:modelValue", value: HoppRESTRequest): void
|
||||
}>()
|
||||
|
||||
|
||||
@@ -35,12 +35,12 @@
|
||||
v-if="
|
||||
!teamDetails.loading &&
|
||||
E.isRight(teamDetails.data) &&
|
||||
teamDetails.data.right.team.teamMembers
|
||||
teamDetails.data.right.team?.teamMembers
|
||||
"
|
||||
class="rounded border border-divider"
|
||||
>
|
||||
<HoppSmartPlaceholder
|
||||
v-if="teamDetails.data.right.team.teamMembers === 0"
|
||||
v-if="teamDetails.data.right.team.teamMembers.length === 0"
|
||||
:src="`/images/states/${colorMode.value}/add_group.svg`"
|
||||
:alt="`${t('empty.members')}`"
|
||||
:text="t('empty.members')"
|
||||
|
||||
@@ -88,7 +88,7 @@
|
||||
>
|
||||
<div
|
||||
v-for="(invitee, index) in pendingInvites.data.right.team
|
||||
.teamInvitations"
|
||||
?.teamInvitations"
|
||||
:key="`invitee-${index}`"
|
||||
class="flex divide-x divide-dividerLight"
|
||||
>
|
||||
@@ -122,7 +122,7 @@
|
||||
<HoppSmartPlaceholder
|
||||
v-if="
|
||||
E.isRight(pendingInvites.data) &&
|
||||
pendingInvites.data.right.team.teamInvitations.length === 0
|
||||
pendingInvites.data.right.team?.teamInvitations.length === 0
|
||||
"
|
||||
:text="t('empty.pending_invites')"
|
||||
>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Ref, onBeforeUnmount, onMounted, reactive, watch } from "vue"
|
||||
import { BehaviorSubject } from "rxjs"
|
||||
import { HoppRESTDocument } from "./rest/document"
|
||||
import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"
|
||||
import { RequestOptionTabs } from "~/components/http/RequestOptions.vue"
|
||||
import { RESTOptionTabs } from "~/components/http/RequestOptions.vue"
|
||||
import { HoppGQLSaveContext } from "./graphql/document"
|
||||
import { GQLOptionTabs } from "~/components/graphql/RequestOptions.vue"
|
||||
import { computed } from "vue"
|
||||
@@ -113,7 +113,7 @@ type HoppActionArgsMap = {
|
||||
request: HoppGQLRequest
|
||||
}
|
||||
"request.open-tab": {
|
||||
tab: RequestOptionTabs | GQLOptionTabs
|
||||
tab: RESTOptionTabs | GQLOptionTabs
|
||||
}
|
||||
|
||||
"tab.duplicate-tab": {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { HoppModule } from "."
|
||||
import { Container, Service } from "dioc"
|
||||
import { diocPlugin } from "dioc/vue"
|
||||
import { DebugService } from "~/services/debug.service"
|
||||
import { platform } from "~/platform"
|
||||
|
||||
const serviceContainer = new Container()
|
||||
|
||||
@@ -34,5 +35,8 @@ export default <HoppModule>{
|
||||
app.use(diocPlugin, {
|
||||
container: serviceContainer,
|
||||
})
|
||||
for (const service of platform.addedServices ?? []) {
|
||||
serviceContainer.bind(service)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -58,7 +58,13 @@ export const FALLBACK_LANG = pipe(
|
||||
)
|
||||
|
||||
// A reference to the i18n instance
|
||||
let i18nInstance: I18n<any, any, any> | null = null
|
||||
let i18nInstance: I18n<
|
||||
Record<string, unknown>,
|
||||
Record<string, unknown>,
|
||||
Record<string, unknown>,
|
||||
string,
|
||||
true
|
||||
> | null = null
|
||||
|
||||
const resolveCurrentLocale = () =>
|
||||
pipe(
|
||||
@@ -119,7 +125,6 @@ export const changeAppLanguage = async (locale: string) => {
|
||||
* Returns the i18n instance
|
||||
*/
|
||||
export function getI18n() {
|
||||
// @ts-expect-error Something weird with the i18n errors
|
||||
return i18nInstance!.global.t
|
||||
}
|
||||
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
import { HoppModule } from "."
|
||||
import * as Sentry from "@sentry/vue"
|
||||
import { BrowserTracing } from "@sentry/tracing"
|
||||
import { Route } from "@sentry/vue/types/router"
|
||||
import { RouteLocationNormalized, Router } from "vue-router"
|
||||
import { settingsStore } from "~/newstore/settings"
|
||||
import { App } from "vue"
|
||||
import { APP_IS_IN_DEV_MODE } from "~/helpers/dev"
|
||||
import { gqlClientError$ } from "~/helpers/backend/GQLClient"
|
||||
import { platform } from "~/platform"
|
||||
|
||||
/**
|
||||
* The tag names we allow giving to Sentry
|
||||
*/
|
||||
type SentryTag = "BACKEND_OPERATIONS"
|
||||
|
||||
interface SentryVueRouter {
|
||||
onError: (fn: (err: Error) => void) => void
|
||||
beforeEach: (fn: (to: Route, from: Route, next: () => void) => void) => void
|
||||
}
|
||||
|
||||
function normalizedRouteToSentryRoute(route: RouteLocationNormalized): Route {
|
||||
return {
|
||||
matched: route.matched,
|
||||
// route.params' type translates just to a fancy version of this, hence assertion
|
||||
params: route.params as Route["params"],
|
||||
path: route.path,
|
||||
// route.query's type translates just to a fancy version of this, hence assertion
|
||||
query: route.query as Route["query"],
|
||||
name: route.name,
|
||||
}
|
||||
}
|
||||
|
||||
function getInstrumentationVueRouter(router: Router): SentryVueRouter {
|
||||
return <SentryVueRouter>{
|
||||
onError: router.onError,
|
||||
beforeEach(func) {
|
||||
router.beforeEach((to, from, next) => {
|
||||
func(
|
||||
normalizedRouteToSentryRoute(to),
|
||||
normalizedRouteToSentryRoute(from),
|
||||
next
|
||||
)
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let sentryActive = false
|
||||
|
||||
function initSentry(dsn: string, router: Router, app: App) {
|
||||
Sentry.init({
|
||||
app,
|
||||
dsn,
|
||||
release: import.meta.env.VITE_SENTRY_RELEASE_TAG ?? undefined,
|
||||
environment: APP_IS_IN_DEV_MODE
|
||||
? "dev"
|
||||
: import.meta.env.VITE_SENTRY_ENVIRONMENT,
|
||||
integrations: [
|
||||
new BrowserTracing({
|
||||
routingInstrumentation: Sentry.vueRouterInstrumentation(
|
||||
getInstrumentationVueRouter(router)
|
||||
),
|
||||
// TODO: We may want to limit this later on
|
||||
tracingOrigins: [new URL(import.meta.env.VITE_BACKEND_GQL_URL).origin],
|
||||
}),
|
||||
],
|
||||
tracesSampleRate: 0.8,
|
||||
})
|
||||
sentryActive = true
|
||||
}
|
||||
|
||||
function deinitSentry() {
|
||||
Sentry.close()
|
||||
sentryActive = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports a set of related errors to Sentry
|
||||
* @param errs The errors to report
|
||||
* @param tag The tag for the errord
|
||||
* @param extraTags Additional tag data to add
|
||||
* @param extras Extra information to attach
|
||||
*/
|
||||
function reportErrors(
|
||||
errs: Error[],
|
||||
tag: SentryTag,
|
||||
extraTags: Record<string, string | number | boolean> | null = null,
|
||||
extras: any = undefined
|
||||
) {
|
||||
if (sentryActive) {
|
||||
Sentry.withScope((scope) => {
|
||||
scope.setTag("tag", tag)
|
||||
if (extraTags) {
|
||||
Object.entries(extraTags).forEach(([key, value]) => {
|
||||
scope.setTag(key, value)
|
||||
})
|
||||
}
|
||||
if (extras !== null && extras === undefined) scope.setExtras(extras)
|
||||
|
||||
scope.addAttachment({
|
||||
filename: "extras-dump.json",
|
||||
data: JSON.stringify(extras),
|
||||
contentType: "application/json",
|
||||
})
|
||||
|
||||
errs.forEach((err) => Sentry.captureException(err))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports a specific error to Sentry
|
||||
* @param err The error to report
|
||||
* @param tag The tag for the error
|
||||
* @param extraTags Additional tag data to add
|
||||
* @param extras Extra information to attach
|
||||
*/
|
||||
function reportError(
|
||||
err: Error,
|
||||
tag: SentryTag,
|
||||
extraTags: Record<string, string | number | boolean> | null = null,
|
||||
extras: any = undefined
|
||||
) {
|
||||
reportErrors([err], tag, extraTags, extras)
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to events occuring in various subsystems in the app
|
||||
* for personalized error reporting
|
||||
*/
|
||||
function subscribeToAppEventsForReporting() {
|
||||
gqlClientError$.subscribe((ev) => {
|
||||
switch (ev.type) {
|
||||
case "SUBSCRIPTION_CONN_CALLBACK_ERR_REPORT":
|
||||
reportErrors(ev.errors, "BACKEND_OPERATIONS", { from: ev.type })
|
||||
break
|
||||
|
||||
case "CLIENT_REPORTED_ERROR":
|
||||
reportError(
|
||||
ev.error,
|
||||
"BACKEND_OPERATIONS",
|
||||
{ from: ev.type },
|
||||
{ op: ev.op }
|
||||
)
|
||||
break
|
||||
|
||||
case "GQL_CLIENT_REPORTED_ERROR":
|
||||
reportError(
|
||||
new Error("Backend Query Failed"),
|
||||
"BACKEND_OPERATIONS",
|
||||
{ opType: ev.opType },
|
||||
{
|
||||
opResult: ev.opResult,
|
||||
}
|
||||
)
|
||||
break
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to app system events for adding
|
||||
* additional data tags for the error reporting
|
||||
*/
|
||||
function subscribeForAppDataTags() {
|
||||
const currentUser$ = platform.auth.getCurrentUserStream()
|
||||
|
||||
currentUser$.subscribe((user) => {
|
||||
if (sentryActive) {
|
||||
Sentry.setTag("user_logged_in", !!user)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export default <HoppModule>{
|
||||
onRouterInit(app, router) {
|
||||
if (!import.meta.env.VITE_SENTRY_DSN) {
|
||||
console.log(
|
||||
"Sentry tracing is not enabled because 'VITE_SENTRY_DSN' env is not defined"
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (settingsStore.value.TELEMETRY_ENABLED) {
|
||||
initSentry(import.meta.env.VITE_SENTRY_DSN, router, app)
|
||||
}
|
||||
|
||||
settingsStore.subject$.subscribe(({ TELEMETRY_ENABLED }) => {
|
||||
if (!TELEMETRY_ENABLED && sentryActive) {
|
||||
deinitSentry()
|
||||
} else if (TELEMETRY_ENABLED && !sentryActive) {
|
||||
initSentry(import.meta.env.VITE_SENTRY_DSN!, router, app)
|
||||
}
|
||||
})
|
||||
|
||||
subscribeToAppEventsForReporting()
|
||||
subscribeForAppDataTags()
|
||||
},
|
||||
}
|
||||
@@ -60,6 +60,7 @@
|
||||
<div class="space-y-4 py-4">
|
||||
<div class="flex items-center">
|
||||
<HoppSmartToggle
|
||||
v-if="hasPlatformTelemetry"
|
||||
:on="TELEMETRY_ENABLED"
|
||||
@change="showConfirmModal"
|
||||
>
|
||||
@@ -134,6 +135,7 @@ import { InterceptorService } from "~/services/interceptor.service"
|
||||
import { pipe } from "fp-ts/function"
|
||||
import * as O from "fp-ts/Option"
|
||||
import * as A from "fp-ts/Array"
|
||||
import { platform } from "~/platform"
|
||||
|
||||
const t = useI18n()
|
||||
const colorMode = useColorMode()
|
||||
@@ -163,6 +165,8 @@ const TELEMETRY_ENABLED = useSetting("TELEMETRY_ENABLED")
|
||||
const EXPAND_NAVIGATION = useSetting("EXPAND_NAVIGATION")
|
||||
const SIDEBAR_ON_LEFT = useSetting("SIDEBAR_ON_LEFT")
|
||||
|
||||
const hasPlatformTelemetry = Boolean(platform.platformFeatureFlags.hasTelemetry)
|
||||
|
||||
const confirmRemove = ref(false)
|
||||
|
||||
const proxySettings = computed(() => ({
|
||||
|
||||
@@ -9,10 +9,12 @@ import { AnalyticsPlatformDef } from "./analytics"
|
||||
import { InterceptorsPlatformDef } from "./interceptors"
|
||||
import { HoppModule } from "~/modules"
|
||||
import { InspectorsPlatformDef } from "./inspectors"
|
||||
import { Service } from "dioc"
|
||||
|
||||
export type PlatformDef = {
|
||||
ui?: UIPlatformDef
|
||||
addedHoppModules?: HoppModule[]
|
||||
addedServices?: Array<typeof Service<unknown> & { ID: string }>
|
||||
auth: AuthPlatformDef
|
||||
analytics?: AnalyticsPlatformDef
|
||||
sync: {
|
||||
@@ -26,6 +28,7 @@ export type PlatformDef = {
|
||||
additionalInspectors?: InspectorsPlatformDef
|
||||
platformFeatureFlags: {
|
||||
exportAsGIST: boolean
|
||||
hasTelemetry: boolean
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vitest"
|
||||
import { BannerContent, BannerService } from "../banner.service"
|
||||
import { TestContainer } from "dioc/testing"
|
||||
|
||||
describe("BannerService", () => {
|
||||
const container = new TestContainer()
|
||||
const service = container.bind(BannerService)
|
||||
|
||||
it("initally there are no banners defined", () => {
|
||||
expect(service.content.value).toEqual(null)
|
||||
})
|
||||
|
||||
it("should be able to set and retrieve banner content", () => {
|
||||
const sampleBanner: BannerContent = {
|
||||
type: "info",
|
||||
text: "Info Banner",
|
||||
}
|
||||
|
||||
const banner = service.content
|
||||
banner.value = sampleBanner
|
||||
const retrievedBanner = service.content.value
|
||||
|
||||
expect(retrievedBanner).toEqual(sampleBanner)
|
||||
})
|
||||
|
||||
it("should be able to update the banner content", () => {
|
||||
const updatedBanner: BannerContent = {
|
||||
type: "warning",
|
||||
text: "Updated Banner Content",
|
||||
alternateText: "Updated Banner",
|
||||
}
|
||||
|
||||
service.content.value = updatedBanner
|
||||
const retrievedBanner = service.content.value
|
||||
|
||||
expect(retrievedBanner).toEqual(updatedBanner)
|
||||
})
|
||||
})
|
||||
28
packages/hoppscotch-common/src/services/banner.service.ts
Normal file
28
packages/hoppscotch-common/src/services/banner.service.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { Service } from "dioc"
|
||||
import { ref } from "vue"
|
||||
|
||||
/**
|
||||
* The different types of banners that can be used.
|
||||
*/
|
||||
export type BannerType = "info" | "warning" | "error"
|
||||
|
||||
export type BannerContent = {
|
||||
type: BannerType
|
||||
text: string
|
||||
// Can be used to display an alternate text when display size is small
|
||||
alternateText?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* This service is used to display a banner on the app.
|
||||
* It can used to display information, warnings or errors.
|
||||
*/
|
||||
export class BannerService extends Service {
|
||||
public static readonly ID = "BANNER_SERVICE"
|
||||
|
||||
/**
|
||||
* This is a reactive variable that can be used to set the contents of the banner
|
||||
* and use it to render the banner on components.
|
||||
*/
|
||||
public content = ref<BannerContent | null>(null)
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
function generateREForProtocol(protocol) {
|
||||
return [
|
||||
new RegExp(
|
||||
`${protocol}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`
|
||||
`${protocol}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:[0-9]+)?(\\/[^?#]*)?(\\?[^#]*)?(#.*)?$`
|
||||
),
|
||||
new RegExp(
|
||||
`${protocol}(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9/])$`
|
||||
`${protocol}(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9/])(:[0-9]+)?(\\/[^?#]*)?(\\?[^#]*)?(#.*)?$`
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
92
packages/hoppscotch-common/type-check.mjs
Normal file
92
packages/hoppscotch-common/type-check.mjs
Normal file
@@ -0,0 +1,92 @@
|
||||
import fs from "fs"
|
||||
import { glob } from "glob"
|
||||
import path from "path"
|
||||
import ts from "typescript"
|
||||
import vueTsc from "vue-tsc"
|
||||
|
||||
import { fileURLToPath } from "url"
|
||||
|
||||
/**
|
||||
* Helper function to find files to perform type check on
|
||||
*/
|
||||
const findFilesToPerformTypeCheck = (directoryPaths, filePatterns) => {
|
||||
const files = []
|
||||
|
||||
directoryPaths.forEach((directoryPath) => {
|
||||
if (!fs.existsSync(directoryPath)) {
|
||||
console.error(`Directory not found: ${directoryPath}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
files.push(
|
||||
...glob.sync(filePatterns, {
|
||||
cwd: directoryPath,
|
||||
ignore: ["**/__tests__/**", "**/*.d.ts"],
|
||||
absolute: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
return files
|
||||
}
|
||||
|
||||
// Derive the current file's directory path `__dirname` from the URL of this module `__filename`
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = path.dirname(__filename)
|
||||
|
||||
// Define the directory paths and file patterns to perform type checks on
|
||||
const directoryPaths = [path.resolve(__dirname, "src", "services")]
|
||||
const filePatterns = ["**/*.ts"]
|
||||
|
||||
const tsConfigFileName = path.resolve(__dirname, "tsconfig.json")
|
||||
const tsConfig = ts.readConfigFile(tsConfigFileName, ts.sys.readFile)
|
||||
const { options } = ts.parseJsonConfigFileContent(
|
||||
tsConfig.config,
|
||||
ts.sys,
|
||||
__dirname
|
||||
)
|
||||
|
||||
const files = findFilesToPerformTypeCheck(directoryPaths, filePatterns)
|
||||
|
||||
const host = ts.createCompilerHost(options)
|
||||
const program = vueTsc.createProgram({
|
||||
rootNames: files,
|
||||
options: { ...options, noEmit: true },
|
||||
host,
|
||||
})
|
||||
|
||||
// Perform type checking
|
||||
const diagnostics = ts
|
||||
.getPreEmitDiagnostics(program)
|
||||
// Filter diagnostics to include only errors from files in the specified directory
|
||||
.filter(({ file }) => {
|
||||
if (!file) {
|
||||
return false
|
||||
}
|
||||
return directoryPaths.some((directoryPath) =>
|
||||
path.resolve(file.fileName).includes(directoryPath)
|
||||
)
|
||||
})
|
||||
|
||||
if (!diagnostics.length) {
|
||||
console.log("Type checking passed.")
|
||||
|
||||
// Success
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
console.log("TypeScript diagnostics:")
|
||||
|
||||
const formatHost = {
|
||||
getCanonicalFileName: (fileName) => fileName,
|
||||
getCurrentDirectory: host.getCurrentDirectory,
|
||||
getNewLine: () => ts.sys.newLine,
|
||||
}
|
||||
|
||||
const formattedDiagnostics = ts.formatDiagnosticsWithColorAndContext(
|
||||
diagnostics,
|
||||
formatHost
|
||||
)
|
||||
console.error(formattedDiagnostics)
|
||||
|
||||
// Failure
|
||||
process.exit(1)
|
||||
@@ -6,7 +6,9 @@
|
||||
"main": "dist/hoppscotch-data.cjs",
|
||||
"module": "dist/hoppscotch-data.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [ "dist/*" ],
|
||||
"files": [
|
||||
"dist/*"
|
||||
],
|
||||
"scripts": {
|
||||
"build:code": "vite build",
|
||||
"build:decl": "tsc --project tsconfig.decl.json",
|
||||
@@ -32,14 +34,16 @@
|
||||
},
|
||||
"homepage": "https://github.com/hoppscotch/hoppscotch#readme",
|
||||
"devDependencies": {
|
||||
"@types/lodash": "^4.14.181",
|
||||
"typescript": "^4.6.3",
|
||||
"vite": "^3.2.3"
|
||||
"@types/lodash": "^4.14.200",
|
||||
"typescript": "^5.2.2",
|
||||
"vite": "^4.5.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"fp-ts": "^2.11.10",
|
||||
"io-ts": "^2.2.16",
|
||||
"fp-ts": "^2.16.1",
|
||||
"io-ts": "^2.2.20",
|
||||
"lodash": "^4.17.21",
|
||||
"parser-ts": "^0.6.16"
|
||||
"parser-ts": "^0.7.0",
|
||||
"verzod": "^0.1.1",
|
||||
"zod": "^3.22.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
import { pipe } from "fp-ts/function"
|
||||
import * as E from "fp-ts/Either"
|
||||
import { pipe } from "fp-ts/function"
|
||||
import { InferredEntity, createVersionedEntity } from "verzod"
|
||||
|
||||
export type Environment = {
|
||||
id?: string
|
||||
name: string
|
||||
variables: {
|
||||
key: string
|
||||
value: string
|
||||
}[]
|
||||
}
|
||||
import V0_VERSION from "./v/0"
|
||||
|
||||
export const Environment = createVersionedEntity({
|
||||
latestVersion: 0,
|
||||
versionMap: {
|
||||
0: V0_VERSION
|
||||
},
|
||||
getVersion(x) {
|
||||
return V0_VERSION.schema.safeParse(x).success
|
||||
? 0
|
||||
: null
|
||||
}
|
||||
})
|
||||
|
||||
export type Environment = InferredEntity<typeof Environment>
|
||||
|
||||
const REGEX_ENV_VAR = /<<([^>]*)>>/g // "<<myVariable>>"
|
||||
|
||||
18
packages/hoppscotch-data/src/environment/v/0.ts
Normal file
18
packages/hoppscotch-data/src/environment/v/0.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { z } from "zod"
|
||||
import { defineVersion } from "verzod"
|
||||
|
||||
export const V0_SCHEMA = z.object({
|
||||
id: z.optional(z.string()),
|
||||
name: z.string(),
|
||||
variables: z.array(
|
||||
z.object({
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
export default defineVersion({
|
||||
initial: true,
|
||||
schema: V0_SCHEMA
|
||||
})
|
||||
@@ -1,43 +0,0 @@
|
||||
export type HoppGQLAuthNone = {
|
||||
authType: "none"
|
||||
}
|
||||
|
||||
export type HoppGQLAuthBasic = {
|
||||
authType: "basic"
|
||||
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export type HoppGQLAuthBearer = {
|
||||
authType: "bearer"
|
||||
|
||||
token: string
|
||||
}
|
||||
|
||||
export type HoppGQLAuthOAuth2 = {
|
||||
authType: "oauth-2"
|
||||
|
||||
token: string
|
||||
oidcDiscoveryURL: string
|
||||
authURL: string
|
||||
accessTokenURL: string
|
||||
clientID: string
|
||||
scope: string
|
||||
}
|
||||
|
||||
export type HoppGQLAuthAPIKey = {
|
||||
authType: "api-key"
|
||||
|
||||
key: string
|
||||
value: string
|
||||
addTo: string
|
||||
}
|
||||
|
||||
export type HoppGQLAuth = { authActive: boolean } & (
|
||||
| HoppGQLAuthNone
|
||||
| HoppGQLAuthBasic
|
||||
| HoppGQLAuthBearer
|
||||
| HoppGQLAuthOAuth2
|
||||
| HoppGQLAuthAPIKey
|
||||
)
|
||||
@@ -1,51 +1,75 @@
|
||||
import { HoppGQLAuth } from "./HoppGQLAuth"
|
||||
import { InferredEntity, createVersionedEntity } from "verzod"
|
||||
import { z } from "zod"
|
||||
import V1_VERSION from "./v/1"
|
||||
import V2_VERSION from "./v/2"
|
||||
|
||||
export * from "./HoppGQLAuth"
|
||||
export { GQLHeader } from "./v/1"
|
||||
export {
|
||||
HoppGQLAuth,
|
||||
HoppGQLAuthAPIKey,
|
||||
HoppGQLAuthBasic,
|
||||
HoppGQLAuthBearer,
|
||||
HoppGQLAuthNone,
|
||||
HoppGQLAuthOAuth2,
|
||||
} from "./v/2"
|
||||
|
||||
export const GQL_REQ_SCHEMA_VERSION = 2
|
||||
|
||||
export type GQLHeader = {
|
||||
key: string
|
||||
value: string
|
||||
active: boolean
|
||||
}
|
||||
const versionedObject = z.object({
|
||||
v: z.number(),
|
||||
})
|
||||
|
||||
export type HoppGQLRequest = {
|
||||
id?: string
|
||||
v: number
|
||||
name: string
|
||||
url: string
|
||||
headers: GQLHeader[]
|
||||
query: string
|
||||
variables: string
|
||||
auth: HoppGQLAuth
|
||||
}
|
||||
export const HoppGQLRequest = createVersionedEntity({
|
||||
latestVersion: 2,
|
||||
versionMap: {
|
||||
1: V1_VERSION,
|
||||
2: V2_VERSION,
|
||||
},
|
||||
getVersion(x) {
|
||||
const result = versionedObject.safeParse(x)
|
||||
|
||||
export function translateToGQLRequest(x: any): HoppGQLRequest {
|
||||
if (x.v && x.v === GQL_REQ_SCHEMA_VERSION) return x
|
||||
return result.success ? result.data.v : null
|
||||
},
|
||||
})
|
||||
|
||||
// Old request
|
||||
const name = x.name ?? "Untitled"
|
||||
const url = x.url ?? ""
|
||||
const headers = x.headers ?? []
|
||||
const query = x.query ?? ""
|
||||
const variables = x.variables ?? []
|
||||
const auth = x.auth ?? {
|
||||
authType: "none",
|
||||
authActive: true,
|
||||
export type HoppGQLRequest = InferredEntity<typeof HoppGQLRequest>
|
||||
|
||||
const DEFAULT_QUERY = `
|
||||
query Request {
|
||||
method
|
||||
url
|
||||
headers {
|
||||
key
|
||||
value
|
||||
}
|
||||
}`.trim()
|
||||
|
||||
export function getDefaultGQLRequest(): HoppGQLRequest {
|
||||
return {
|
||||
v: GQL_REQ_SCHEMA_VERSION,
|
||||
name,
|
||||
url,
|
||||
headers,
|
||||
query,
|
||||
variables,
|
||||
auth
|
||||
name: "Untitled",
|
||||
url: "https://echo.hoppscotch.io/graphql",
|
||||
headers: [],
|
||||
variables: `
|
||||
{
|
||||
"id": "1"
|
||||
}`.trim(),
|
||||
query: DEFAULT_QUERY,
|
||||
auth: {
|
||||
authType: "none",
|
||||
authActive: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated This function is deprecated. Use `HoppGQLRequest` instead.
|
||||
*/
|
||||
export function translateToGQLRequest(x: unknown): HoppGQLRequest {
|
||||
const result = HoppGQLRequest.safeParse(x)
|
||||
return result.type === "ok" ? result.value : getDefaultGQLRequest()
|
||||
}
|
||||
|
||||
export function makeGQLRequest(x: Omit<HoppGQLRequest, "v">): HoppGQLRequest {
|
||||
return {
|
||||
v: GQL_REQ_SCHEMA_VERSION,
|
||||
|
||||
24
packages/hoppscotch-data/src/graphql/v/1.ts
Normal file
24
packages/hoppscotch-data/src/graphql/v/1.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { z } from "zod"
|
||||
import { defineVersion } from "verzod"
|
||||
|
||||
export const GQLHeader = z.object({
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
active: z.boolean()
|
||||
})
|
||||
|
||||
export type GQLHeader = z.infer<typeof GQLHeader>
|
||||
|
||||
export const V1_SCHEMA = z.object({
|
||||
v: z.literal(1),
|
||||
name: z.string(),
|
||||
url: z.string(),
|
||||
headers: z.array(GQLHeader),
|
||||
query: z.string(),
|
||||
variables: z.string(),
|
||||
})
|
||||
|
||||
export default defineVersion({
|
||||
initial: true,
|
||||
schema: V1_SCHEMA
|
||||
})
|
||||
91
packages/hoppscotch-data/src/graphql/v/2.ts
Normal file
91
packages/hoppscotch-data/src/graphql/v/2.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { z } from "zod"
|
||||
import { defineVersion } from "verzod"
|
||||
import { GQLHeader, V1_SCHEMA } from "./1"
|
||||
|
||||
export const HoppGQLAuthNone = z.object({
|
||||
authType: z.literal("none")
|
||||
})
|
||||
|
||||
export type HoppGQLAuthNone = z.infer<typeof HoppGQLAuthNone>
|
||||
|
||||
export const HoppGQLAuthBasic = z.object({
|
||||
authType: z.literal("basic"),
|
||||
|
||||
username: z.string(),
|
||||
password: z.string()
|
||||
})
|
||||
|
||||
export type HoppGQLAuthBasic = z.infer<typeof HoppGQLAuthBasic>
|
||||
|
||||
export const HoppGQLAuthBearer = z.object({
|
||||
authType: z.literal("bearer"),
|
||||
|
||||
token: z.string()
|
||||
})
|
||||
|
||||
export type HoppGQLAuthBearer = z.infer<typeof HoppGQLAuthBearer>
|
||||
|
||||
export const HoppGQLAuthOAuth2 = z.object({
|
||||
authType: z.literal("oauth-2"),
|
||||
|
||||
token: z.string(),
|
||||
oidcDiscoveryURL: z.string(),
|
||||
authURL: z.string(),
|
||||
accessTokenURL: z.string(),
|
||||
clientID: z.string(),
|
||||
scope: z.string()
|
||||
})
|
||||
|
||||
export type HoppGQLAuthOAuth2 = z.infer<typeof HoppGQLAuthOAuth2>
|
||||
|
||||
export const HoppGQLAuthAPIKey = z.object({
|
||||
authType: z.literal("api-key"),
|
||||
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
addTo: z.string()
|
||||
})
|
||||
|
||||
export type HoppGQLAuthAPIKey = z.infer<typeof HoppGQLAuthAPIKey>
|
||||
|
||||
export const HoppGQLAuth = z.discriminatedUnion("authType", [
|
||||
HoppGQLAuthNone,
|
||||
HoppGQLAuthBasic,
|
||||
HoppGQLAuthBearer,
|
||||
HoppGQLAuthOAuth2,
|
||||
HoppGQLAuthAPIKey
|
||||
]).and(
|
||||
z.object({
|
||||
authActive: z.boolean()
|
||||
})
|
||||
)
|
||||
|
||||
export type HoppGQLAuth = z.infer<typeof HoppGQLAuth>
|
||||
|
||||
const V2_SCHEMA = z.object({
|
||||
id: z.optional(z.string()),
|
||||
v: z.literal(2),
|
||||
|
||||
name: z.string(),
|
||||
url: z.string(),
|
||||
headers: z.array(GQLHeader),
|
||||
query: z.string(),
|
||||
variables: z.string(),
|
||||
|
||||
auth: HoppGQLAuth
|
||||
})
|
||||
|
||||
export default defineVersion({
|
||||
initial: false,
|
||||
schema: V2_SCHEMA,
|
||||
up(old: z.infer<typeof V1_SCHEMA>) {
|
||||
return <z.infer<typeof V2_SCHEMA>>{
|
||||
...old,
|
||||
v: 2,
|
||||
auth: {
|
||||
authActive: true,
|
||||
authType: "none",
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1,43 +0,0 @@
|
||||
export type HoppRESTAuthNone = {
|
||||
authType: "none"
|
||||
}
|
||||
|
||||
export type HoppRESTAuthBasic = {
|
||||
authType: "basic"
|
||||
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export type HoppRESTAuthBearer = {
|
||||
authType: "bearer"
|
||||
|
||||
token: string
|
||||
}
|
||||
|
||||
export type HoppRESTAuthOAuth2 = {
|
||||
authType: "oauth-2"
|
||||
|
||||
token: string
|
||||
oidcDiscoveryURL: string
|
||||
authURL: string
|
||||
accessTokenURL: string
|
||||
clientID: string
|
||||
scope: string
|
||||
}
|
||||
|
||||
export type HoppRESTAuthAPIKey = {
|
||||
authType: "api-key"
|
||||
|
||||
key: string
|
||||
value: string
|
||||
addTo: string
|
||||
}
|
||||
|
||||
export type HoppRESTAuth = { authActive: boolean } & (
|
||||
| HoppRESTAuthNone
|
||||
| HoppRESTAuthBasic
|
||||
| HoppRESTAuthBearer
|
||||
| HoppRESTAuthOAuth2
|
||||
| HoppRESTAuthAPIKey
|
||||
)
|
||||
@@ -11,3 +11,5 @@ export const knownContentTypes = {
|
||||
}
|
||||
|
||||
export type ValidContentTypes = keyof typeof knownContentTypes
|
||||
|
||||
export const ValidContentTypesList = Object.keys(knownContentTypes) as ValidContentTypes[]
|
||||
|
||||
@@ -1,66 +1,58 @@
|
||||
import cloneDeep from "lodash/cloneDeep"
|
||||
import * as Eq from "fp-ts/Eq"
|
||||
import * as S from "fp-ts/string"
|
||||
import { ValidContentTypes } from "./content-types"
|
||||
import { HoppRESTAuth } from "./HoppRESTAuth"
|
||||
import cloneDeep from "lodash/cloneDeep"
|
||||
import V0_VERSION from "./v/0"
|
||||
import V1_VERSION from "./v/1"
|
||||
import { createVersionedEntity, InferredEntity } from "verzod"
|
||||
import { lodashIsEqualEq, mapThenEq, undefinedEq } from "../utils/eq"
|
||||
import {
|
||||
HoppRESTAuth,
|
||||
HoppRESTReqBody,
|
||||
HoppRESTHeaders,
|
||||
HoppRESTParams,
|
||||
} from "./v/1"
|
||||
import { z } from "zod"
|
||||
|
||||
export * from "./content-types"
|
||||
export * from "./HoppRESTAuth"
|
||||
export {
|
||||
FormDataKeyValue,
|
||||
HoppRESTReqBodyFormData,
|
||||
HoppRESTAuth,
|
||||
HoppRESTAuthAPIKey,
|
||||
HoppRESTAuthBasic,
|
||||
HoppRESTAuthBearer,
|
||||
HoppRESTAuthNone,
|
||||
HoppRESTAuthOAuth2,
|
||||
HoppRESTReqBody,
|
||||
} from "./v/1"
|
||||
|
||||
export const RESTReqSchemaVersion = "1"
|
||||
const versionedObject = z.object({
|
||||
// v is a stringified number
|
||||
v: z.string().regex(/^\d+$/).transform(Number),
|
||||
})
|
||||
|
||||
export type HoppRESTParam = {
|
||||
key: string
|
||||
value: string
|
||||
active: boolean
|
||||
}
|
||||
export const HoppRESTRequest = createVersionedEntity({
|
||||
latestVersion: 1,
|
||||
versionMap: {
|
||||
0: V0_VERSION,
|
||||
1: V1_VERSION,
|
||||
},
|
||||
getVersion(data) {
|
||||
// For V1 onwards we have the v string storing the number
|
||||
const versionCheck = versionedObject.safeParse(data)
|
||||
|
||||
export type HoppRESTHeader = {
|
||||
key: string
|
||||
value: string
|
||||
active: boolean
|
||||
}
|
||||
if (versionCheck.success) return versionCheck.data.v
|
||||
|
||||
export type FormDataKeyValue = {
|
||||
key: string
|
||||
active: boolean
|
||||
} & ({ isFile: true; value: Blob[] } | { isFile: false; value: string })
|
||||
// For V0 we have to check the schema
|
||||
const result = V0_VERSION.schema.safeParse(data)
|
||||
|
||||
export type HoppRESTReqBodyFormData = {
|
||||
contentType: "multipart/form-data"
|
||||
body: FormDataKeyValue[]
|
||||
}
|
||||
return result.success ? 0 : null
|
||||
},
|
||||
})
|
||||
|
||||
export type HoppRESTReqBody =
|
||||
| {
|
||||
contentType: Exclude<ValidContentTypes, "multipart/form-data">
|
||||
body: string
|
||||
}
|
||||
| HoppRESTReqBodyFormData
|
||||
| {
|
||||
contentType: null
|
||||
body: null
|
||||
}
|
||||
export type HoppRESTRequest = InferredEntity<typeof HoppRESTRequest>
|
||||
|
||||
export interface HoppRESTRequest {
|
||||
v: string
|
||||
id?: string // Firebase Firestore ID
|
||||
|
||||
name: string
|
||||
method: string
|
||||
endpoint: string
|
||||
params: HoppRESTParam[]
|
||||
headers: HoppRESTHeader[]
|
||||
preRequestScript: string
|
||||
testScript: string
|
||||
|
||||
auth: HoppRESTAuth
|
||||
|
||||
body: HoppRESTReqBody
|
||||
}
|
||||
|
||||
export const HoppRESTRequestEq = Eq.struct<HoppRESTRequest>({
|
||||
const HoppRESTRequestEq = Eq.struct<HoppRESTRequest>({
|
||||
id: undefinedEq(S.Eq),
|
||||
v: S.Eq,
|
||||
auth: lodashIsEqualEq,
|
||||
@@ -80,6 +72,11 @@ export const HoppRESTRequestEq = Eq.struct<HoppRESTRequest>({
|
||||
testScript: S.Eq,
|
||||
})
|
||||
|
||||
export const RESTReqSchemaVersion = "1"
|
||||
|
||||
export type HoppRESTParam = HoppRESTRequest["params"][number]
|
||||
export type HoppRESTHeader = HoppRESTRequest["headers"][number]
|
||||
|
||||
export const isEqualHoppRESTRequest = HoppRESTRequestEq.equals
|
||||
|
||||
/**
|
||||
@@ -87,6 +84,9 @@ export const isEqualHoppRESTRequest = HoppRESTRequestEq.equals
|
||||
* If we fail to detect certain bits, we just resolve it to the default value
|
||||
* @param x The value to extract REST Request data from
|
||||
* @param defaultReq The default REST Request to source from
|
||||
*
|
||||
* @deprecated Usage of this function is no longer recommended and is only here
|
||||
* for legacy reasons and will be removed
|
||||
*/
|
||||
export function safelyExtractRESTRequest(
|
||||
x: unknown,
|
||||
@@ -94,40 +94,53 @@ export function safelyExtractRESTRequest(
|
||||
): HoppRESTRequest {
|
||||
const req = cloneDeep(defaultReq)
|
||||
|
||||
// TODO: A cleaner way to do this ?
|
||||
if (!!x && typeof x === "object") {
|
||||
if (x.hasOwnProperty("v") && typeof x.v === "string")
|
||||
req.v = x.v
|
||||
if ("id" in x && typeof x.id === "string") req.id = x.id
|
||||
|
||||
if (x.hasOwnProperty("id") && typeof x.id === "string")
|
||||
req.id = x.id
|
||||
if ("name" in x && typeof x.name === "string") req.name = x.name
|
||||
|
||||
if (x.hasOwnProperty("name") && typeof x.name === "string")
|
||||
req.name = x.name
|
||||
if ("method" in x && typeof x.method === "string") req.method = x.method
|
||||
|
||||
if (x.hasOwnProperty("method") && typeof x.method === "string")
|
||||
req.method = x.method
|
||||
|
||||
if (x.hasOwnProperty("endpoint") && typeof x.endpoint === "string")
|
||||
if ("endpoint" in x && typeof x.endpoint === "string")
|
||||
req.endpoint = x.endpoint
|
||||
|
||||
if (x.hasOwnProperty("preRequestScript") && typeof x.preRequestScript === "string")
|
||||
if ("preRequestScript" in x && typeof x.preRequestScript === "string")
|
||||
req.preRequestScript = x.preRequestScript
|
||||
|
||||
if (x.hasOwnProperty("testScript") && typeof x.testScript === "string")
|
||||
if ("testScript" in x && typeof x.testScript === "string")
|
||||
req.testScript = x.testScript
|
||||
|
||||
if (x.hasOwnProperty("body") && typeof x.body === "object" && !!x.body)
|
||||
req.body = x.body as any // TODO: Deep nested checks
|
||||
if ("body" in x) {
|
||||
const result = HoppRESTReqBody.safeParse(x.body)
|
||||
|
||||
if (x.hasOwnProperty("auth") && typeof x.auth === "object" && !!x.auth)
|
||||
req.auth = x.auth as any // TODO: Deep nested checks
|
||||
if (result.success) {
|
||||
req.body = result.data
|
||||
}
|
||||
}
|
||||
|
||||
if (x.hasOwnProperty("params") && Array.isArray(x.params))
|
||||
req.params = x.params // TODO: Deep nested checks
|
||||
if ("auth" in x) {
|
||||
const result = HoppRESTAuth.safeParse(x.auth)
|
||||
|
||||
if (x.hasOwnProperty("headers") && Array.isArray(x.headers))
|
||||
req.headers = x.headers // TODO: Deep nested checks
|
||||
if (result.success) {
|
||||
req.auth = result.data
|
||||
}
|
||||
}
|
||||
|
||||
if ("params" in x) {
|
||||
const result = HoppRESTParams.safeParse(x.params)
|
||||
|
||||
if (result.success) {
|
||||
req.params = result.data
|
||||
}
|
||||
}
|
||||
|
||||
if ("headers" in x) {
|
||||
const result = HoppRESTHeaders.safeParse(x.headers)
|
||||
|
||||
if (result.success) {
|
||||
req.headers = result.data
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return req
|
||||
@@ -137,105 +150,51 @@ export function makeRESTRequest(
|
||||
x: Omit<HoppRESTRequest, "v">
|
||||
): HoppRESTRequest {
|
||||
return {
|
||||
...x,
|
||||
v: RESTReqSchemaVersion,
|
||||
...x,
|
||||
}
|
||||
}
|
||||
|
||||
export function isHoppRESTRequest(x: any): x is HoppRESTRequest {
|
||||
return x && typeof x === "object" && "v" in x
|
||||
}
|
||||
|
||||
function parseRequestBody(x: any): HoppRESTReqBody {
|
||||
if (x.contentType === "application/json") {
|
||||
return {
|
||||
contentType: "application/json",
|
||||
body: x.rawParams,
|
||||
}
|
||||
}
|
||||
|
||||
export function getDefaultRESTRequest(): HoppRESTRequest {
|
||||
return {
|
||||
contentType: "application/json",
|
||||
body: "",
|
||||
}
|
||||
}
|
||||
|
||||
export function translateToNewRequest(x: any): HoppRESTRequest {
|
||||
if (isHoppRESTRequest(x)) {
|
||||
return x
|
||||
} else {
|
||||
// Old format
|
||||
const endpoint: string = `${x?.url ?? ""}${x?.path ?? ""}`
|
||||
|
||||
const headers: HoppRESTHeader[] = x?.headers ?? []
|
||||
|
||||
// Remove old keys from params
|
||||
const params: HoppRESTParam[] = (x?.params ?? []).map(
|
||||
({
|
||||
key,
|
||||
value,
|
||||
active,
|
||||
}: {
|
||||
key: string
|
||||
value: string
|
||||
active: boolean
|
||||
}) => ({
|
||||
key,
|
||||
value,
|
||||
active,
|
||||
})
|
||||
)
|
||||
|
||||
const name = x?.name ?? "Untitled request"
|
||||
const method = x?.method ?? ""
|
||||
|
||||
const preRequestScript = x?.preRequestScript ?? ""
|
||||
const testScript = x?.testScript ?? ""
|
||||
|
||||
const body = parseRequestBody(x)
|
||||
|
||||
const auth = parseOldAuth(x)
|
||||
|
||||
const result: HoppRESTRequest = {
|
||||
name,
|
||||
endpoint,
|
||||
headers,
|
||||
params,
|
||||
method,
|
||||
preRequestScript,
|
||||
testScript,
|
||||
body,
|
||||
auth,
|
||||
v: RESTReqSchemaVersion,
|
||||
}
|
||||
|
||||
if (x.id) result.id = x.id
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
export function parseOldAuth(x: any): HoppRESTAuth {
|
||||
if (!x.auth || x.auth === "None")
|
||||
return {
|
||||
v: "1",
|
||||
endpoint: "https://echo.hoppscotch.io",
|
||||
name: "Untitled",
|
||||
params: [],
|
||||
headers: [],
|
||||
method: "GET",
|
||||
auth: {
|
||||
authType: "none",
|
||||
authActive: true,
|
||||
}
|
||||
|
||||
if (x.auth === "Basic Auth")
|
||||
return {
|
||||
authType: "basic",
|
||||
authActive: true,
|
||||
username: x.httpUser,
|
||||
password: x.httpPassword,
|
||||
}
|
||||
|
||||
if (x.auth === "Bearer Token")
|
||||
return {
|
||||
authType: "bearer",
|
||||
authActive: true,
|
||||
token: x.bearerToken,
|
||||
}
|
||||
|
||||
return { authType: "none", authActive: true }
|
||||
},
|
||||
preRequestScript: "",
|
||||
testScript: "",
|
||||
body: {
|
||||
contentType: null,
|
||||
body: null,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given value is a HoppRESTRequest
|
||||
* @param x The value to check
|
||||
*
|
||||
* @deprecated This function is no longer recommended and is only here for legacy reasons
|
||||
* Use `HoppRESTRequest.is`/`HoppRESTRequest.isLatest` instead.
|
||||
*/
|
||||
export function isHoppRESTRequest(x: unknown): x is HoppRESTRequest {
|
||||
return HoppRESTRequest.isLatest(x)
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely parses a value into a HoppRESTRequest.
|
||||
* @param x The value to check
|
||||
*
|
||||
* @deprecated This function is no longer recommended and is only here for
|
||||
* legacy reasons. Use `HoppRESTRequest.safeParse` instead.
|
||||
*/
|
||||
export function translateToNewRequest(x: unknown): HoppRESTRequest {
|
||||
const result = HoppRESTRequest.safeParse(x)
|
||||
return result.type === "ok" ? result.value : getDefaultRESTRequest()
|
||||
}
|
||||
|
||||
39
packages/hoppscotch-data/src/rest/v/0.ts
Normal file
39
packages/hoppscotch-data/src/rest/v/0.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { defineVersion } from "verzod"
|
||||
import { z } from "zod"
|
||||
|
||||
export const V0_SCHEMA = z.object({
|
||||
id: z.optional(z.string()), // Firebase Firestore ID
|
||||
|
||||
url: z.string(),
|
||||
path: z.string(),
|
||||
headers: z.array(
|
||||
z.object({
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
active: z.boolean()
|
||||
})
|
||||
),
|
||||
params: z.array(
|
||||
z.object({
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
active: z.boolean()
|
||||
})
|
||||
),
|
||||
name: z.string(),
|
||||
method: z.string(),
|
||||
preRequestScript: z.string(),
|
||||
testScript: z.string(),
|
||||
contentType: z.string(),
|
||||
body: z.string(),
|
||||
rawParams: z.optional(z.string()),
|
||||
auth: z.optional(z.string()),
|
||||
httpUser: z.optional(z.string()),
|
||||
httpPassword: z.optional(z.string()),
|
||||
bearerToken: z.optional(z.string()),
|
||||
})
|
||||
|
||||
export default defineVersion({
|
||||
initial: true,
|
||||
schema: V0_SCHEMA
|
||||
})
|
||||
209
packages/hoppscotch-data/src/rest/v/1.ts
Normal file
209
packages/hoppscotch-data/src/rest/v/1.ts
Normal file
@@ -0,0 +1,209 @@
|
||||
import { defineVersion } from "verzod"
|
||||
import { z } from "zod"
|
||||
|
||||
import { V0_SCHEMA } from "./0"
|
||||
|
||||
export const FormDataKeyValue = z.object({
|
||||
key: z.string(),
|
||||
active: z.boolean()
|
||||
}).and(
|
||||
z.union([
|
||||
z.object({
|
||||
isFile: z.literal(true),
|
||||
value: z.array(z.instanceof(Blob))
|
||||
}),
|
||||
z.object({
|
||||
isFile: z.literal(false),
|
||||
value: z.string()
|
||||
})
|
||||
])
|
||||
)
|
||||
|
||||
export type FormDataKeyValue = z.infer<typeof FormDataKeyValue>
|
||||
|
||||
export const HoppRESTReqBodyFormData = z.object({
|
||||
contentType: z.literal("multipart/form-data"),
|
||||
body: z.array(FormDataKeyValue)
|
||||
})
|
||||
|
||||
export type HoppRESTReqBodyFormData = z.infer<typeof HoppRESTReqBodyFormData>
|
||||
|
||||
export const HoppRESTReqBody = z.union([
|
||||
z.object({
|
||||
contentType: z.literal(null),
|
||||
body: z.literal(null)
|
||||
}),
|
||||
z.object({
|
||||
contentType: z.literal("multipart/form-data"),
|
||||
body: FormDataKeyValue
|
||||
}),
|
||||
z.object({
|
||||
contentType: z.union([
|
||||
z.literal("application/json"),
|
||||
z.literal("application/ld+json"),
|
||||
z.literal("application/hal+json"),
|
||||
z.literal("application/vnd.api+json"),
|
||||
z.literal("application/xml"),
|
||||
z.literal("application/x-www-form-urlencoded"),
|
||||
z.literal("text/html"),
|
||||
z.literal("text/plain"),
|
||||
]),
|
||||
body: z.string()
|
||||
})
|
||||
])
|
||||
|
||||
export type HoppRESTReqBody = z.infer<typeof HoppRESTReqBody>
|
||||
|
||||
export const HoppRESTAuthNone = z.object({
|
||||
authType: z.literal("none")
|
||||
})
|
||||
|
||||
export type HoppRESTAuthNone = z.infer<typeof HoppRESTAuthNone>
|
||||
|
||||
export const HoppRESTAuthBasic = z.object({
|
||||
authType: z.literal("basic"),
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
})
|
||||
|
||||
export type HoppRESTAuthBasic = z.infer<typeof HoppRESTAuthBasic>
|
||||
|
||||
export const HoppRESTAuthBearer = z.object({
|
||||
authType: z.literal("bearer"),
|
||||
token: z.string(),
|
||||
})
|
||||
|
||||
export type HoppRESTAuthBearer = z.infer<typeof HoppRESTAuthBearer>
|
||||
|
||||
export const HoppRESTAuthOAuth2 = z.object({
|
||||
authType: z.literal("oauth-2"),
|
||||
token: z.string(),
|
||||
oidcDiscoveryURL: z.string(),
|
||||
authURL: z.string(),
|
||||
accessTokenURL: z.string(),
|
||||
clientID: z.string(),
|
||||
scope: z.string(),
|
||||
})
|
||||
|
||||
export type HoppRESTAuthOAuth2 = z.infer<typeof HoppRESTAuthOAuth2>
|
||||
|
||||
export const HoppRESTAuthAPIKey = z.object({
|
||||
authType: z.literal("api-key"),
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
addTo: z.string(),
|
||||
})
|
||||
|
||||
export type HoppRESTAuthAPIKey = z.infer<typeof HoppRESTAuthAPIKey>
|
||||
|
||||
export const HoppRESTAuth = z.discriminatedUnion("authType", [
|
||||
HoppRESTAuthNone,
|
||||
HoppRESTAuthBasic,
|
||||
HoppRESTAuthBearer,
|
||||
HoppRESTAuthOAuth2,
|
||||
HoppRESTAuthAPIKey
|
||||
]).and(
|
||||
z.object({
|
||||
authActive: z.boolean(),
|
||||
})
|
||||
)
|
||||
|
||||
export type HoppRESTAuth = z.infer<typeof HoppRESTAuth>
|
||||
|
||||
export const HoppRESTParams = z.array(
|
||||
z.object({
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
active: z.boolean()
|
||||
})
|
||||
)
|
||||
|
||||
export type HoppRESTParams = z.infer<typeof HoppRESTParams>
|
||||
|
||||
export const HoppRESTHeaders = z.array(
|
||||
z.object({
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
active: z.boolean()
|
||||
})
|
||||
)
|
||||
|
||||
export type HoppRESTHeaders = z.infer<typeof HoppRESTHeaders>
|
||||
|
||||
const V1_SCHEMA = z.object({
|
||||
v: z.literal("1"),
|
||||
id: z.optional(z.string()), // Firebase Firestore ID
|
||||
|
||||
name: z.string(),
|
||||
method: z.string(),
|
||||
endpoint: z.string(),
|
||||
params: HoppRESTParams,
|
||||
headers: HoppRESTHeaders,
|
||||
preRequestScript: z.string(),
|
||||
testScript: z.string(),
|
||||
|
||||
auth: HoppRESTAuth,
|
||||
|
||||
body: HoppRESTReqBody
|
||||
})
|
||||
|
||||
function parseRequestBody(x: z.infer<typeof V0_SCHEMA>): z.infer<typeof V1_SCHEMA>["body"] {
|
||||
return {
|
||||
contentType: "application/json",
|
||||
body: x.contentType === "application/json" ? x.rawParams ?? "" : "",
|
||||
}
|
||||
}
|
||||
|
||||
export function parseOldAuth(x: z.infer<typeof V0_SCHEMA>): z.infer<typeof V1_SCHEMA>["auth"] {
|
||||
if (!x.auth || x.auth === "None")
|
||||
return {
|
||||
authType: "none",
|
||||
authActive: true,
|
||||
}
|
||||
|
||||
if (x.auth === "Basic Auth")
|
||||
return {
|
||||
authType: "basic",
|
||||
authActive: true,
|
||||
username: x.httpUser ?? "",
|
||||
password: x.httpPassword ?? "",
|
||||
}
|
||||
|
||||
if (x.auth === "Bearer Token")
|
||||
return {
|
||||
authType: "bearer",
|
||||
authActive: true,
|
||||
token: x.bearerToken ?? "",
|
||||
}
|
||||
|
||||
return { authType: "none", authActive: true }
|
||||
}
|
||||
|
||||
export default defineVersion({
|
||||
initial: false,
|
||||
schema: V1_SCHEMA,
|
||||
up(old: z.infer<typeof V0_SCHEMA>) {
|
||||
const { url, path, headers, params, name, method, preRequestScript, testScript } = old
|
||||
|
||||
const endpoint = `${url}${path}`
|
||||
const body = parseRequestBody(old)
|
||||
const auth = parseOldAuth(old)
|
||||
|
||||
const result: z.infer<typeof V1_SCHEMA> = {
|
||||
v: "1",
|
||||
endpoint,
|
||||
headers,
|
||||
params,
|
||||
name,
|
||||
method,
|
||||
preRequestScript,
|
||||
testScript,
|
||||
body,
|
||||
auth,
|
||||
}
|
||||
|
||||
if (old.id) result.id = old.id
|
||||
|
||||
return result
|
||||
},
|
||||
})
|
||||
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "es2017",
|
||||
"module": "esnext",
|
||||
"lib": ["esnext"],
|
||||
"lib": ["esnext", "DOM"],
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
"compilerOptions": {
|
||||
"target": "es2017",
|
||||
"module": "esnext",
|
||||
"lib": ["esnext"],
|
||||
"lib": ["esnext", "DOM"],
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"strictNullChecks": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src/*.ts"]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module.exports = {
|
||||
preset: "ts-jest",
|
||||
testEnvironment: "node",
|
||||
testEnvironment: "jsdom",
|
||||
collectCoverage: true,
|
||||
setupFilesAfterEnv: ["./jest.setup.ts"],
|
||||
}
|
||||
|
||||
5
packages/hoppscotch-selfhost-web/aio.Caddyfile
Normal file
5
packages/hoppscotch-selfhost-web/aio.Caddyfile
Normal file
@@ -0,0 +1,5 @@
|
||||
:80 :3000 {
|
||||
try_files {path} /
|
||||
root * /site
|
||||
file_server
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@hoppscotch/selfhost-web",
|
||||
"private": true,
|
||||
"version": "2023.8.2",
|
||||
"version": "2023.8.3",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev:vite": "vite",
|
||||
|
||||
@@ -38,5 +38,6 @@ createHoppApp("#app", {
|
||||
],
|
||||
platformFeatureFlags: {
|
||||
exportAsGIST: false,
|
||||
hasTelemetry: false,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -151,6 +151,7 @@ export default defineConfig({
|
||||
},
|
||||
}),
|
||||
VitePWA({
|
||||
useCredentials: true,
|
||||
manifest: {
|
||||
name: APP_INFO.name,
|
||||
short_name: APP_INFO.name,
|
||||
@@ -222,6 +223,8 @@ export default defineConfig({
|
||||
/twitter/,
|
||||
/github/,
|
||||
/announcements/,
|
||||
/admin/,
|
||||
/backend/,
|
||||
],
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -98,9 +98,10 @@
|
||||
"load_info_error": "Unable to load team info",
|
||||
"load_list_error": "Unable to Load Teams List",
|
||||
"members": "Number of members",
|
||||
"name": "Team name",
|
||||
"name": "Team Name",
|
||||
"no_members": "No members in this team. Add members to this team to collaborate",
|
||||
"no_pending_invites": "No pending invites",
|
||||
"no_teams": "No teams found",
|
||||
"pending_invites": "Pending invites",
|
||||
"remove": "Remove",
|
||||
"rename": "Rename",
|
||||
@@ -112,6 +113,7 @@
|
||||
"team_members_tab": "Team members",
|
||||
"teams": "Teams",
|
||||
"uid": "UID",
|
||||
"unnamed": "(Unnamed Team)",
|
||||
"valid_name": "Please enter a valid team name",
|
||||
"valid_owner_email": "Please enter a valid owner email"
|
||||
},
|
||||
@@ -125,6 +127,7 @@
|
||||
"created_on": "Created On",
|
||||
"date": "Date",
|
||||
"delete": "Delete",
|
||||
"delete_user": "Delete User",
|
||||
"email": "Email",
|
||||
"email_address": "Email Address",
|
||||
"id": "User ID",
|
||||
@@ -136,6 +139,7 @@
|
||||
"load_info_error": "Unable to load user info",
|
||||
"load_list_error": "Unable to Load Users List",
|
||||
"make_admin": "Make admin",
|
||||
"invite_load_list_error": "Unable to Load Invited Users List",
|
||||
"name": "Name",
|
||||
"no_invite": "No invited users found",
|
||||
"no_users": "No users found",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "hoppscotch-sh-admin",
|
||||
"private": true,
|
||||
"version": "2023.8.2",
|
||||
"version": "2023.8.3",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "pnpm exec npm-run-all -p -l dev:*",
|
||||
|
||||
@@ -1,6 +1,36 @@
|
||||
#!/usr/local/bin/node
|
||||
import { execSync } from "child_process"
|
||||
import { execSync, spawn } from "child_process"
|
||||
import fs from "fs"
|
||||
import process from "process"
|
||||
|
||||
function runChildProcessWithPrefix(command, args, prefix) {
|
||||
const childProcess = spawn(command, args);
|
||||
|
||||
childProcess.stdout.on('data', (data) => {
|
||||
const output = data.toString().trim().split('\n');
|
||||
output.forEach((line) => {
|
||||
console.log(`${prefix} | ${line}`);
|
||||
});
|
||||
});
|
||||
|
||||
childProcess.stderr.on('data', (data) => {
|
||||
const error = data.toString().trim().split('\n');
|
||||
error.forEach((line) => {
|
||||
console.error(`${prefix} | ${line}`);
|
||||
});
|
||||
});
|
||||
|
||||
childProcess.on('close', (code) => {
|
||||
console.log(`${prefix} Child process exited with code ${code}`);
|
||||
});
|
||||
|
||||
childProcess.on('error', (stuff) => {
|
||||
console.log("error")
|
||||
console.log(stuff)
|
||||
})
|
||||
|
||||
return childProcess
|
||||
}
|
||||
|
||||
const envFileContent = Object.entries(process.env)
|
||||
.filter(([env]) => env.startsWith("VITE_"))
|
||||
@@ -16,3 +46,19 @@ fs.writeFileSync("build.env", envFileContent)
|
||||
execSync(`npx import-meta-env -x build.env -e build.env -p "/site/**/*"`)
|
||||
|
||||
fs.rmSync("build.env")
|
||||
|
||||
const caddyFileName = process.env.ENABLE_SUBPATH_BASED_ACCESS === 'true' ? 'sh-admin-subpath-access.Caddyfile' : 'sh-admin-multiport-setup.Caddyfile'
|
||||
const caddyProcess = runChildProcessWithPrefix("caddy", ["run", "--config", `/etc/caddy/${caddyFileName}`, "--adapter", "caddyfile"], "App/Admin Dashboard Caddy")
|
||||
|
||||
caddyProcess.on("exit", (code) => {
|
||||
console.log(`Exiting process because Caddy Server exited with code ${code}`)
|
||||
process.exit(code)
|
||||
})
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
console.log("SIGINT received, exiting...")
|
||||
|
||||
caddyProcess.kill("SIGINT")
|
||||
|
||||
process.exit(0)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
:80 :3100 {
|
||||
try_files {path} /
|
||||
root * /site/sh-admin-multiport-setup
|
||||
file_server
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
:80 :3100 {
|
||||
try_files {path} /admin*
|
||||
root * /site/sh-admin-subpath-access
|
||||
file_server
|
||||
}
|
||||
97
packages/hoppscotch-sh-admin/src/components.d.ts
vendored
97
packages/hoppscotch-sh-admin/src/components.d.ts
vendored
@@ -1,44 +1,71 @@
|
||||
// generated by unplugin-vue-components
|
||||
// We suggest you to commit this file into source control
|
||||
// Read more: https://github.com/vuejs/core/pull/3399
|
||||
import '@vue/runtime-core';
|
||||
import '@vue/runtime-core'
|
||||
|
||||
export {};
|
||||
export {}
|
||||
|
||||
declare module '@vue/runtime-core' {
|
||||
export interface GlobalComponents {
|
||||
AppHeader: typeof import('./components/app/Header.vue')['default'];
|
||||
AppLogin: typeof import('./components/app/Login.vue')['default'];
|
||||
AppLogout: typeof import('./components/app/Logout.vue')['default'];
|
||||
AppModal: typeof import('./components/app/Modal.vue')['default'];
|
||||
AppSidebar: typeof import('./components/app/Sidebar.vue')['default'];
|
||||
AppToast: typeof import('./components/app/Toast.vue')['default'];
|
||||
DashboardMetricsCard: typeof import('./components/dashboard/MetricsCard.vue')['default'];
|
||||
HoppButtonPrimary: typeof import('@hoppscotch/ui')['HoppButtonPrimary'];
|
||||
HoppButtonSecondary: typeof import('@hoppscotch/ui')['HoppButtonSecondary'];
|
||||
HoppSmartAnchor: typeof import('@hoppscotch/ui')['HoppSmartAnchor'];
|
||||
HoppSmartAutoComplete: typeof import('@hoppscotch/ui')['HoppSmartAutoComplete'];
|
||||
HoppSmartConfirmModal: typeof import('@hoppscotch/ui')['HoppSmartConfirmModal'];
|
||||
HoppSmartInput: typeof import('@hoppscotch/ui')['HoppSmartInput'];
|
||||
HoppSmartItem: typeof import('@hoppscotch/ui')['HoppSmartItem'];
|
||||
HoppSmartModal: typeof import('@hoppscotch/ui')['HoppSmartModal'];
|
||||
HoppSmartPicture: typeof import('@hoppscotch/ui')['HoppSmartPicture'];
|
||||
HoppSmartPlaceholder: typeof import('@hoppscotch/ui')['HoppSmartPlaceholder'];
|
||||
HoppSmartSpinner: typeof import('@hoppscotch/ui')['HoppSmartSpinner'];
|
||||
HoppSmartTab: typeof import('@hoppscotch/ui')['HoppSmartTab'];
|
||||
IconLucideArrowLeft: typeof import('~icons/lucide/arrow-left')['default'];
|
||||
IconLucideChevronDown: typeof import('~icons/lucide/chevron-down')['default'];
|
||||
IconLucideHelpCircle: typeof import('~icons/lucide/help-circle')['default'];
|
||||
IconLucideInbox: typeof import('~icons/lucide/inbox')['default'];
|
||||
IconLucideUser: typeof import('~icons/lucide/user')['default'];
|
||||
TeamsAdd: typeof import('./components/teams/Add.vue')['default'];
|
||||
TeamsDetails: typeof import('./components/teams/Details.vue')['default'];
|
||||
TeamsInvite: typeof import('./components/teams/Invite.vue')['default'];
|
||||
TeamsMembers: typeof import('./components/teams/Members.vue')['default'];
|
||||
TeamsPendingInvites: typeof import('./components/teams/PendingInvites.vue')['default'];
|
||||
TeamsTable: typeof import('./components/teams/Table.vue')['default'];
|
||||
Tippy: typeof import('vue-tippy')['Tippy'];
|
||||
UsersInviteModal: typeof import('./components/users/InviteModal.vue')['default'];
|
||||
UsersTable: typeof import('./components/users/Table.vue')['default'];
|
||||
AppHeader: typeof import('./components/app/Header.vue')['default']
|
||||
AppLogin: typeof import('./components/app/Login.vue')['default']
|
||||
AppLogout: typeof import('./components/app/Logout.vue')['default']
|
||||
AppModal: typeof import('./components/app/Modal.vue')['default']
|
||||
AppSidebar: typeof import('./components/app/Sidebar.vue')['default']
|
||||
AppToast: typeof import('./components/app/Toast.vue')['default']
|
||||
ButtonPrimary: typeof import('./../../hoppscotch-ui/src/components/button/Primary.vue')['default']
|
||||
ButtonSecondary: typeof import('./../../hoppscotch-ui/src/components/button/Secondary.vue')['default']
|
||||
DashboardMetricsCard: typeof import('./components/dashboard/MetricsCard.vue')['default']
|
||||
HoppButtonPrimary: typeof import('@hoppscotch/ui')['HoppButtonPrimary']
|
||||
HoppButtonSecondary: typeof import('@hoppscotch/ui')['HoppButtonSecondary']
|
||||
HoppSmartAnchor: typeof import('@hoppscotch/ui')['HoppSmartAnchor']
|
||||
HoppSmartAutoComplete: typeof import('@hoppscotch/ui')['HoppSmartAutoComplete']
|
||||
HoppSmartConfirmModal: typeof import('@hoppscotch/ui')['HoppSmartConfirmModal']
|
||||
HoppSmartInput: typeof import('@hoppscotch/ui')['HoppSmartInput']
|
||||
HoppSmartItem: typeof import('@hoppscotch/ui')['HoppSmartItem']
|
||||
HoppSmartModal: typeof import('@hoppscotch/ui')['HoppSmartModal']
|
||||
HoppSmartPicture: typeof import('@hoppscotch/ui')['HoppSmartPicture']
|
||||
HoppSmartPlaceholder: typeof import('@hoppscotch/ui')['HoppSmartPlaceholder']
|
||||
HoppSmartSpinner: typeof import('@hoppscotch/ui')['HoppSmartSpinner']
|
||||
HoppSmartTab: typeof import('@hoppscotch/ui')['HoppSmartTab']
|
||||
HoppSmartTable: typeof import('@hoppscotch/ui')['HoppSmartTable']
|
||||
IconLucideArrowLeft: typeof import('~icons/lucide/arrow-left')['default']
|
||||
IconLucideChevronDown: typeof import('~icons/lucide/chevron-down')['default']
|
||||
IconLucideHelpCircle: typeof import('~icons/lucide/help-circle')['default']
|
||||
IconLucideInbox: typeof import('~icons/lucide/inbox')['default']
|
||||
SmartAnchor: typeof import('./../../hoppscotch-ui/src/components/smart/Anchor.vue')['default']
|
||||
SmartAutoComplete: typeof import('./../../hoppscotch-ui/src/components/smart/AutoComplete.vue')['default']
|
||||
SmartCheckbox: typeof import('./../../hoppscotch-ui/src/components/smart/Checkbox.vue')['default']
|
||||
SmartConfirmModal: typeof import('./../../hoppscotch-ui/src/components/smart/ConfirmModal.vue')['default']
|
||||
SmartExpand: typeof import('./../../hoppscotch-ui/src/components/smart/Expand.vue')['default']
|
||||
SmartFileChip: typeof import('./../../hoppscotch-ui/src/components/smart/FileChip.vue')['default']
|
||||
SmartInput: typeof import('./../../hoppscotch-ui/src/components/smart/Input.vue')['default']
|
||||
SmartIntersection: typeof import('./../../hoppscotch-ui/src/components/smart/Intersection.vue')['default']
|
||||
SmartItem: typeof import('./../../hoppscotch-ui/src/components/smart/Item.vue')['default']
|
||||
SmartLink: typeof import('./../../hoppscotch-ui/src/components/smart/Link.vue')['default']
|
||||
SmartModal: typeof import('./../../hoppscotch-ui/src/components/smart/Modal.vue')['default']
|
||||
SmartPicture: typeof import('./../../hoppscotch-ui/src/components/smart/Picture.vue')['default']
|
||||
SmartPlaceholder: typeof import('./../../hoppscotch-ui/src/components/smart/Placeholder.vue')['default']
|
||||
SmartProgressRing: typeof import('./../../hoppscotch-ui/src/components/smart/ProgressRing.vue')['default']
|
||||
SmartRadio: typeof import('./../../hoppscotch-ui/src/components/smart/Radio.vue')['default']
|
||||
SmartRadioGroup: typeof import('./../../hoppscotch-ui/src/components/smart/RadioGroup.vue')['default']
|
||||
SmartSlideOver: typeof import('./../../hoppscotch-ui/src/components/smart/SlideOver.vue')['default']
|
||||
SmartSpinner: typeof import('./../../hoppscotch-ui/src/components/smart/Spinner.vue')['default']
|
||||
SmartTab: typeof import('./../../hoppscotch-ui/src/components/smart/Tab.vue')['default']
|
||||
SmartTable: typeof import('./../../hoppscotch-ui/src/components/smart/Table.vue')['default']
|
||||
SmartTabs: typeof import('./../../hoppscotch-ui/src/components/smart/Tabs.vue')['default']
|
||||
SmartToggle: typeof import('./../../hoppscotch-ui/src/components/smart/Toggle.vue')['default']
|
||||
SmartTree: typeof import('./../../hoppscotch-ui/src/components/smart/Tree.vue')['default']
|
||||
SmartTreeBranch: typeof import('./../../hoppscotch-ui/src/components/smart/TreeBranch.vue')['default']
|
||||
SmartWindow: typeof import('./../../hoppscotch-ui/src/components/smart/Window.vue')['default']
|
||||
SmartWindows: typeof import('./../../hoppscotch-ui/src/components/smart/Windows.vue')['default']
|
||||
TeamsAdd: typeof import('./components/teams/Add.vue')['default']
|
||||
TeamsDetails: typeof import('./components/teams/Details.vue')['default']
|
||||
TeamsInvite: typeof import('./components/teams/Invite.vue')['default']
|
||||
TeamsMembers: typeof import('./components/teams/Members.vue')['default']
|
||||
TeamsPendingInvites: typeof import('./components/teams/PendingInvites.vue')['default']
|
||||
Tippy: typeof import('vue-tippy')['Tippy']
|
||||
UsersInviteModal: typeof import('./components/users/InviteModal.vue')['default']
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
<template>
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<tr class="text-secondary border-b border-dividerDark text-sm text-left">
|
||||
<th class="px-3 pb-3">Team ID</th>
|
||||
<th class="px-3 pb-3">Team Name</th>
|
||||
<th class="px-3 pb-3">Number of Members</th>
|
||||
<th class="px-3 pb-3"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody class="divide-y divide-divider">
|
||||
<tr v-if="teamList.length === 0">
|
||||
<div class="py-6 px-3">No teams found ...</div>
|
||||
</tr>
|
||||
<tr
|
||||
v-else
|
||||
v-for="team in teamList"
|
||||
:key="team.id"
|
||||
class="text-secondaryDark hover:bg-divider hover:cursor-pointer rounded-xl"
|
||||
>
|
||||
<td
|
||||
@click="$emit('go-to-team-details', team.id)"
|
||||
class="py-4 px-3 max-w-50"
|
||||
>
|
||||
<div class="flex">
|
||||
<span class="truncate">
|
||||
{{ team.id }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td
|
||||
@click="$emit('go-to-team-details', team.id)"
|
||||
class="py-4 px-3 min-w-80"
|
||||
>
|
||||
<span v-if="team.name" class="flex items-center ml-4 truncate">
|
||||
{{ team.name }}
|
||||
</span>
|
||||
<span v-else class="flex items-center ml-4"> (Unnamed team) </span>
|
||||
</td>
|
||||
|
||||
<td @click="$emit('go-to-team-details', team.id)" class="py-4 px-3">
|
||||
<span class="ml-7">
|
||||
{{ team.members?.length }}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<div class="relative">
|
||||
<tippy interactive trigger="click" theme="popover">
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:icon="IconMoreHorizontal"
|
||||
/>
|
||||
<template #content="{ hide }">
|
||||
<div
|
||||
ref="tippyActions"
|
||||
class="flex flex-col focus:outline-none"
|
||||
tabindex="0"
|
||||
@keyup.escape="hide()"
|
||||
>
|
||||
<HoppSmartItem
|
||||
:icon="IconTrash"
|
||||
:label="'Delete Team'"
|
||||
class="!hover:bg-red-600 w-full"
|
||||
@click="
|
||||
() => {
|
||||
$emit('delete-team', team.id);
|
||||
hide();
|
||||
}
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</tippy>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { TippyComponent } from 'vue-tippy';
|
||||
import { ref } from 'vue';
|
||||
import IconTrash from '~icons/lucide/trash';
|
||||
import IconMoreHorizontal from '~icons/lucide/more-horizontal';
|
||||
import { TeamListQuery } from '~/helpers/backend/graphql';
|
||||
|
||||
// Template refs
|
||||
const tippyActions = ref<TippyComponent | null>(null);
|
||||
|
||||
defineProps<{
|
||||
teamList: TeamListQuery['infra']['allTeams'];
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
(event: 'go-to-team-details', teamID: string): void;
|
||||
(event: 'delete-team', teamID: string): void;
|
||||
}>();
|
||||
</script>
|
||||
@@ -1,162 +0,0 @@
|
||||
<template>
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<tr class="text-secondary border-b border-dividerDark text-sm text-left">
|
||||
<th class="px-3 pb-3">{{ t('users.id') }}</th>
|
||||
<th class="px-3 pb-3">{{ t('users.name') }}</th>
|
||||
<th class="px-3 pb-3">{{ t('users.email') }}</th>
|
||||
<th class="px-3 pb-3">{{ t('users.date') }}</th>
|
||||
<th class="px-3 pb-3"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody class="divide-y divide-divider">
|
||||
<tr
|
||||
v-for="user in usersList"
|
||||
:key="user.uid"
|
||||
class="text-secondaryDark hover:bg-divider hover:cursor-pointer rounded-xl"
|
||||
>
|
||||
<td
|
||||
@click="$emit('goToUserDetails', user.uid)"
|
||||
class="py-2 px-3 max-w-30"
|
||||
>
|
||||
<div class="flex">
|
||||
<span class="truncate">
|
||||
{{ user.uid }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td @click="$emit('goToUserDetails', user.uid)" class="py-2 px-3">
|
||||
<div v-if="user.displayName" class="flex items-center space-x-3">
|
||||
<span>
|
||||
{{ user.displayName }}
|
||||
</span>
|
||||
<span
|
||||
v-if="user.isAdmin"
|
||||
class="text-xs font-medium px-3 py-0.5 rounded-full bg-green-900 text-green-300"
|
||||
>
|
||||
{{ t('users.admin') }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-else class="flex items-center space-x-3">
|
||||
<span> {{ t('users.unnamed') }} </span>
|
||||
<span
|
||||
v-if="user.isAdmin"
|
||||
class="text-xs font-medium px-3 py-0.5 rounded-full bg-green-900 text-green-300"
|
||||
>
|
||||
{{ t('users.admin') }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td @click="$emit('goToUserDetails', user.uid)" class="py-2 px-3">
|
||||
<span>
|
||||
{{ user.email }}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
<td @click="$emit('goToUserDetails', user.uid)" class="py-2 px-3">
|
||||
<div class="flex items-center">
|
||||
<div class="flex flex-col">
|
||||
{{ getCreatedDate(user.createdOn) }}
|
||||
<div class="text-gray-400 text-tiny">
|
||||
{{ getCreatedTime(user.createdOn) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<div class="relative">
|
||||
<span>
|
||||
<tippy interactive trigger="click" theme="popover">
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:icon="IconMoreHorizontal"
|
||||
/>
|
||||
<template #content="{ hide }">
|
||||
<div
|
||||
ref="tippyActions"
|
||||
class="flex flex-col focus:outline-none"
|
||||
tabindex="0"
|
||||
@keyup.escape="hide()"
|
||||
>
|
||||
<HoppSmartItem
|
||||
v-if="!user.isAdmin"
|
||||
:icon="IconUserCheck"
|
||||
:label="'Make Admin'"
|
||||
class="!hover:bg-emerald-600"
|
||||
@click="
|
||||
() => {
|
||||
$emit('makeUserAdmin', user.uid);
|
||||
hide();
|
||||
}
|
||||
"
|
||||
/>
|
||||
<HoppSmartItem
|
||||
v-else
|
||||
:icon="IconUserMinus"
|
||||
:label="'Remove Admin Status'"
|
||||
class="!hover:bg-emerald-600"
|
||||
@click="
|
||||
() => {
|
||||
$emit('makeAdminToUser', user.uid);
|
||||
hide();
|
||||
}
|
||||
"
|
||||
/>
|
||||
<HoppSmartItem
|
||||
v-if="!user.isAdmin"
|
||||
:icon="IconTrash"
|
||||
:label="'Delete User'"
|
||||
class="!hover:bg-red-600"
|
||||
@click="
|
||||
() => {
|
||||
$emit('deleteUser', user.uid);
|
||||
hide();
|
||||
}
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</tippy>
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { format } from 'date-fns';
|
||||
import { ref } from 'vue';
|
||||
import IconTrash from '~icons/lucide/trash';
|
||||
import IconUserMinus from '~icons/lucide/user-minus';
|
||||
import IconUserCheck from '~icons/lucide/user-check';
|
||||
import IconMoreHorizontal from '~icons/lucide/more-horizontal';
|
||||
import { UsersListQuery } from '~/helpers/backend/graphql';
|
||||
import { TippyComponent } from 'vue-tippy';
|
||||
import { useI18n } from '~/composables/i18n';
|
||||
|
||||
const t = useI18n();
|
||||
|
||||
defineProps<{
|
||||
usersList: UsersListQuery['infra']['allUsers'];
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
(event: 'goToUserDetails', uid: string): void;
|
||||
(event: 'makeUserAdmin', uid: string): void;
|
||||
(event: 'makeAdminToUser', uid: string): void;
|
||||
(event: 'deleteUser', uid: string): void;
|
||||
}>();
|
||||
|
||||
// Get Proper Date Formats
|
||||
const getCreatedDate = (date: string) => format(new Date(date), 'dd-MM-yyyy');
|
||||
const getCreatedTime = (date: string) => format(new Date(date), 'hh:mm a');
|
||||
|
||||
// Template refs
|
||||
const tippyActions = ref<TippyComponent | null>(null);
|
||||
</script>
|
||||
@@ -42,7 +42,7 @@ export const isLoadingInitialRoute = readonly(_isLoadingInitialRoute);
|
||||
export default <HoppModule>{
|
||||
onVueAppInit(app) {
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes,
|
||||
});
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
:class="{ 'min-h-screen': statusCode !== 404 }"
|
||||
>
|
||||
<img
|
||||
:src="`/images/youre_lost.svg`"
|
||||
:src="imgUrl"
|
||||
loading="lazy"
|
||||
class="inline-flex flex-col object-contain object-center mb-2 h-46 w-46"
|
||||
:alt="message"
|
||||
@@ -44,6 +44,8 @@ const props = defineProps({
|
||||
},
|
||||
});
|
||||
|
||||
const imgUrl = `${import.meta.env.BASE_URL}images/youre_lost.svg`
|
||||
|
||||
const statusCode = computed(() => props.error?.statusCode ?? 404);
|
||||
|
||||
const message = computed(
|
||||
|
||||
@@ -12,25 +12,90 @@
|
||||
</div>
|
||||
|
||||
<div class="overflow-x-auto">
|
||||
<div
|
||||
v-if="fetching && !error && teamList.length === 0"
|
||||
class="flex justify-center"
|
||||
>
|
||||
<div v-if="fetching" class="flex justify-center">
|
||||
<HoppSmartSpinner />
|
||||
</div>
|
||||
|
||||
<div v-else-if="error">{{ t('teams.load_list_error') }}</div>
|
||||
|
||||
<TeamsTable
|
||||
v-else
|
||||
:teamList="teamList"
|
||||
@goToTeamDetails="goToTeamDetails"
|
||||
@deleteTeam="deleteTeam"
|
||||
class=""
|
||||
/>
|
||||
<HoppSmartTable v-else-if="teamsList.length" :list="teamsList">
|
||||
<template #head>
|
||||
<tr
|
||||
class="text-secondary border-b border-dividerDark text-sm text-left bg-primaryLight"
|
||||
>
|
||||
<th class="px-6 py-2">{{ t('teams.id') }}</th>
|
||||
<th class="px-6 py-3">{{ t('teams.name') }}</th>
|
||||
<th class="px-6 py-2">{{ t('teams.members') }}</th>
|
||||
<!-- Empty Heading for the Action Button -->
|
||||
<th class="px-6 py-2"></th>
|
||||
</tr>
|
||||
</template>
|
||||
<template #body="{ list }">
|
||||
<tr
|
||||
v-for="team in list"
|
||||
:key="team.id"
|
||||
class="text-secondaryDark hover:bg-divider hover:cursor-pointer rounded-xl"
|
||||
@click="goToTeamDetails(team.id)"
|
||||
>
|
||||
<td class="flex py-4 px-7 max-w-50">
|
||||
<span class="truncate">
|
||||
{{ team.id }}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
<td class="py-4 px-7 min-w-80">
|
||||
<span
|
||||
class="flex items-center truncate"
|
||||
:class="{ truncate: team.name }"
|
||||
>
|
||||
{{ team.name ?? t('teams.unnamed') }}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
<td class="py-4 px-7">
|
||||
{{ team.members?.length }}
|
||||
</td>
|
||||
|
||||
<td @click.stop>
|
||||
<div class="relative">
|
||||
<tippy interactive trigger="click" theme="popover">
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:icon="IconMoreHorizontal"
|
||||
/>
|
||||
<template #content="{ hide }">
|
||||
<div
|
||||
ref="tippyActions"
|
||||
class="flex flex-col focus:outline-none"
|
||||
tabindex="0"
|
||||
@keyup.escape="hide()"
|
||||
>
|
||||
<HoppSmartItem
|
||||
:icon="IconTrash"
|
||||
:label="t('teams.delete_team')"
|
||||
class="!hover:bg-red-600 w-full"
|
||||
@click="
|
||||
() => {
|
||||
deleteTeam(team.id);
|
||||
hide();
|
||||
}
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</tippy>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</HoppSmartTable>
|
||||
|
||||
<div v-else class="px-2 text-lg">
|
||||
{{ t('teams.no_teams') }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="hasNextPage && teamList.length >= teamsPerPage"
|
||||
v-if="hasNextPage && teamsList.length >= teamsPerPage"
|
||||
class="flex justify-center my-5 px-3 py-2 cursor-pointer font-semibold rounded-3xl bg-dividerDark hover:bg-divider transition mx-auto w-38 text-secondaryDark"
|
||||
@click="fetchNextTeams"
|
||||
>
|
||||
@@ -66,10 +131,12 @@ import {
|
||||
UsersListDocument,
|
||||
} from '../../helpers/backend/graphql';
|
||||
import { usePagedQuery } from '~/composables/usePagedQuery';
|
||||
import { ref, watch, computed } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useMutation, useQuery } from '@urql/vue';
|
||||
import { useToast } from '~/composables/toast';
|
||||
import IconAddUsers from '~icons/lucide/plus';
|
||||
import IconTrash from '~icons/lucide/trash';
|
||||
import IconMoreHorizontal from '~icons/lucide/more-horizontal';
|
||||
import { useI18n } from '~/composables/i18n';
|
||||
|
||||
const t = useI18n();
|
||||
@@ -96,7 +163,7 @@ const {
|
||||
error,
|
||||
goToNextPage: fetchNextTeams,
|
||||
refetch,
|
||||
list: teamList,
|
||||
list: teamsList,
|
||||
hasNextPage,
|
||||
} = usePagedQuery(
|
||||
TeamListDocument,
|
||||
@@ -143,9 +210,7 @@ const createTeam = async (newTeamName: string, ownerEmail: string) => {
|
||||
|
||||
// Go To Individual Team Details Page
|
||||
const router = useRouter();
|
||||
const goToTeamDetails = (teamId: string) => {
|
||||
router.push('/teams/' + teamId);
|
||||
};
|
||||
const goToTeamDetails = (teamId: string) => router.push('/teams/' + teamId);
|
||||
|
||||
// Reload Teams Page when routed back to the teams page
|
||||
const route = useRoute();
|
||||
@@ -175,7 +240,7 @@ const deleteTeamMutation = async (id: string | null) => {
|
||||
if (result.error) {
|
||||
toast.error(`${t('state.delete_team_failure')}`);
|
||||
} else {
|
||||
teamList.value = teamList.value.filter((team) => team.id !== id);
|
||||
teamsList.value = teamsList.value.filter((team) => team.id !== id);
|
||||
toast.success(`${t('state.delete_team_success')}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -22,27 +22,118 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<div
|
||||
v-if="fetching && !error && usersList.length === 0"
|
||||
class="flex justify-center"
|
||||
>
|
||||
<div v-if="fetching" class="flex justify-center">
|
||||
<HoppSmartSpinner />
|
||||
</div>
|
||||
|
||||
<div v-else-if="error">{{ t('users.load_list_error') }}</div>
|
||||
|
||||
<UsersTable
|
||||
v-else-if="usersList.length >= 1"
|
||||
:usersList="usersList"
|
||||
:fetching="fetching"
|
||||
:error="error"
|
||||
@goToUserDetails="goToUserDetails"
|
||||
@makeUserAdmin="makeUserAdmin"
|
||||
@makeAdminToUser="makeAdminToUser"
|
||||
@deleteUser="deleteUser"
|
||||
/>
|
||||
<HoppSmartTable v-else-if="usersList.length" :list="usersList">
|
||||
<template #head>
|
||||
<tr
|
||||
class="text-secondary border-b border-dividerDark text-sm text-left bg-primaryLight"
|
||||
>
|
||||
<th class="px-6 py-2">{{ t('users.id') }}</th>
|
||||
<th class="px-6 py-2">{{ t('users.name') }}</th>
|
||||
<th class="px-6 py-2">{{ t('users.email') }}</th>
|
||||
<th class="px-6 py-2">{{ t('users.date') }}</th>
|
||||
<!-- Empty header for Action Button -->
|
||||
<th class="px-6 py-2"></th>
|
||||
</tr>
|
||||
</template>
|
||||
|
||||
<div v-else class="flex justify-center">{{ t('users.no_users') }}</div>
|
||||
<template #body="{ list }">
|
||||
<tr
|
||||
v-for="user in list"
|
||||
:key="user.uid"
|
||||
class="text-secondaryDark hover:bg-divider hover:cursor-pointer rounded-xl"
|
||||
@click="goToUserDetails(user.uid)"
|
||||
>
|
||||
<td class="py-2 px-7 max-w-30 truncate">
|
||||
{{ user.uid }}
|
||||
</td>
|
||||
|
||||
<td class="py-2 px-7">
|
||||
<div class="flex items-center space-x-2">
|
||||
<span>
|
||||
{{ user.displayName ?? t('users.unnamed') }}
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-if="user.isAdmin"
|
||||
class="text-xs font-medium px-3 py-0.5 rounded-full bg-green-900 text-green-300"
|
||||
>
|
||||
{{ t('users.admin') }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td class="py-2 px-7">
|
||||
{{ user.email }}
|
||||
</td>
|
||||
|
||||
<td class="py-2 px-7">
|
||||
{{ getCreatedDate(user.createdOn) }}
|
||||
<div class="text-gray-400 text-tiny">
|
||||
{{ getCreatedTime(user.createdOn) }}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td @click.stop>
|
||||
<div class="relative">
|
||||
<tippy interactive trigger="click" theme="popover">
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:icon="IconMoreHorizontal"
|
||||
/>
|
||||
<template #content="{ hide }">
|
||||
<div
|
||||
ref="tippyActions"
|
||||
class="flex flex-col focus:outline-none"
|
||||
tabindex="0"
|
||||
@keyup.escape="hide()"
|
||||
>
|
||||
<HoppSmartItem
|
||||
:icon="user.isAdmin ? IconUserMinus : IconUserCheck"
|
||||
:label="
|
||||
user.isAdmin
|
||||
? t('users.remove_admin_status')
|
||||
: t('users.make_admin')
|
||||
"
|
||||
class="!hover:bg-emerald-600"
|
||||
@click="
|
||||
() => {
|
||||
user.isAdmin
|
||||
? makeAdminToUser(user.uid)
|
||||
: makeUserAdmin(user.uid);
|
||||
hide();
|
||||
}
|
||||
"
|
||||
/>
|
||||
<HoppSmartItem
|
||||
v-if="!user.isAdmin"
|
||||
:icon="IconTrash"
|
||||
:label="t('users.delete_user')"
|
||||
class="!hover:bg-red-600"
|
||||
@click="
|
||||
() => {
|
||||
deleteUser(user.uid);
|
||||
hide();
|
||||
}
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</tippy>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</HoppSmartTable>
|
||||
|
||||
<div v-else-if="usersList.length === 0" class="flex justify-center">
|
||||
{{ t('users.no_users') }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="hasNextPage && usersList.length >= usersPerPage"
|
||||
@@ -82,6 +173,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { format } from 'date-fns';
|
||||
import { ref, watch } from 'vue';
|
||||
import { useMutation } from '@urql/vue';
|
||||
import {
|
||||
@@ -96,8 +188,16 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import { useToast } from '~/composables/toast';
|
||||
import { HoppButtonSecondary } from '@hoppscotch/ui';
|
||||
import IconAddUser from '~icons/lucide/user-plus';
|
||||
import IconTrash from '~icons/lucide/trash';
|
||||
import IconUserMinus from '~icons/lucide/user-minus';
|
||||
import IconUserCheck from '~icons/lucide/user-check';
|
||||
import IconMoreHorizontal from '~icons/lucide/more-horizontal';
|
||||
import { useI18n } from '~/composables/i18n';
|
||||
|
||||
// Get Proper Date Formats
|
||||
const getCreatedDate = (date: string) => format(new Date(date), 'dd-MM-yyyy');
|
||||
const getCreatedTime = (date: string) => format(new Date(date), 'hh:mm a');
|
||||
|
||||
const t = useI18n();
|
||||
|
||||
const toast = useToast();
|
||||
@@ -141,9 +241,7 @@ const sendInvite = async (email: string) => {
|
||||
// Go to Individual User Details Page
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const goToUserDetails = (uid: string) => {
|
||||
router.push('/users/' + uid);
|
||||
};
|
||||
const goToUserDetails = (uid: string) => router.push('/users/' + uid);
|
||||
|
||||
watch(
|
||||
() => route.params.id,
|
||||
|
||||
@@ -12,71 +12,34 @@
|
||||
|
||||
<div class="flex flex-col">
|
||||
<div class="py-2 overflow-x-auto">
|
||||
<div>
|
||||
<div v-if="fetching" class="flex justify-center">
|
||||
<HoppSmartSpinner />
|
||||
</div>
|
||||
<div v-else-if="error || invitedUsers === undefined">
|
||||
<p class="text-xl">{{ t('users.no_invite') }}</p>
|
||||
</div>
|
||||
|
||||
<table v-else class="w-full text-left">
|
||||
<thead>
|
||||
<tr
|
||||
class="text-secondary border-b border-dividerDark text-sm text-left"
|
||||
>
|
||||
<th class="px-3 pb-3">{{ t('users.admin_id') }}</th>
|
||||
<th class="px-3 pb-3">{{ t('users.admin_email') }}</th>
|
||||
<th class="px-3 pb-3">{{ t('users.invitee_email') }}</th>
|
||||
<th class="px-3 pb-3">{{ t('users.invited_on') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-divider">
|
||||
<tr
|
||||
v-if="invitedUsers.length === 0"
|
||||
class="text-secondaryDark py-4"
|
||||
>
|
||||
<div class="py-6 px-3">{{ t('users.no_invite') }}</div>
|
||||
</tr>
|
||||
<tr
|
||||
v-else
|
||||
v-for="(user, index) in invitedUsers"
|
||||
:key="index"
|
||||
class="text-secondaryDark hover:bg-zinc-800 hover:cursor-pointer rounded-xl"
|
||||
>
|
||||
<td class="py-2 px-3 max-w-36">
|
||||
<div class="flex">
|
||||
<span class="truncate">
|
||||
{{ user?.adminUid }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="py-2 px-3">
|
||||
<span class="flex items-center">
|
||||
{{ user?.adminEmail }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-2 px-3 max-w-52">
|
||||
<div class="flex">
|
||||
<span class="truncate">
|
||||
{{ user?.inviteeEmail }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="py-2 px-3">
|
||||
<div class="flex items-center">
|
||||
<div class="flex flex-col">
|
||||
{{ getCreatedDate(user?.invitedOn) }}
|
||||
<div class="text-gray-400 text-xs">
|
||||
{{ getCreatedTime(user?.invitedOn) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-if="fetching" class="flex justify-center">
|
||||
<HoppSmartSpinner />
|
||||
</div>
|
||||
|
||||
<div v-else-if="error" class="text-xl">
|
||||
{{ t('users.invite_load_list_error') }}
|
||||
</div>
|
||||
|
||||
<HoppSmartTable
|
||||
v-else-if="invitedUsers?.length"
|
||||
:list="invitedUsers"
|
||||
:headings="headings"
|
||||
>
|
||||
<template #invitedOn="{ item }">
|
||||
<div v-if="item" class="pr-2 truncate">
|
||||
<span class="truncate">
|
||||
{{ getCreatedDate(item.invitedOn) }}
|
||||
</span>
|
||||
|
||||
<div class="text-gray-400 text-tiny">
|
||||
{{ getCreatedTime(item.invitedOn) }}
|
||||
</div>
|
||||
</div>
|
||||
<span v-else> - </span>
|
||||
</template>
|
||||
</HoppSmartTable>
|
||||
|
||||
<div v-else class="text-lg">{{ t('users.no_invite') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -102,4 +65,12 @@ const getCreatedTime = (date: string) => format(new Date(date), 'hh:mm a');
|
||||
// Get Invited Users
|
||||
const { fetching, error, data } = useQuery({ query: InvitedUsersDocument });
|
||||
const invitedUsers = computed(() => data?.value?.infra.invitedUsers);
|
||||
|
||||
// Table Headings
|
||||
const headings = [
|
||||
{ key: 'adminUid', label: t('users.admin_id') },
|
||||
{ key: 'adminEmail', label: t('users.admin_email') },
|
||||
{ key: 'inviteeEmail', label: t('users.invitee_email') },
|
||||
{ key: 'invitedOn', label: t('users.invited_on') },
|
||||
];
|
||||
</script>
|
||||
|
||||
@@ -21,7 +21,6 @@
|
||||
"@fontsource-variable/material-symbols-rounded": "^5.0.5",
|
||||
"@fontsource-variable/roboto-mono": "^5.0.6",
|
||||
"@hoppscotch/vue-toasted": "^0.1.0",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"@vitejs/plugin-legacy": "^2.3.0",
|
||||
"@vueuse/core": "^8.7.5",
|
||||
"fp-ts": "^2.12.1",
|
||||
@@ -97,4 +96,4 @@
|
||||
"./helpers/treeAdapter.ts": "./src/helpers/treeAdapter.ts"
|
||||
},
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
}
|
||||
69
packages/hoppscotch-ui/src/components/smart/Table.vue
Normal file
69
packages/hoppscotch-ui/src/components/smart/Table.vue
Normal file
@@ -0,0 +1,69 @@
|
||||
<template>
|
||||
<div class="overflow-auto rounded-md border border-dividerDark shadow-md">
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<slot name="head">
|
||||
<tr
|
||||
class="text-secondary border-b border-dividerDark text-sm text-left bg-primaryLight"
|
||||
>
|
||||
<th v-for="th in headings" scope="col" class="px-6 py-3">
|
||||
{{ th.label ?? th.key }}
|
||||
</th>
|
||||
</tr>
|
||||
</slot>
|
||||
</thead>
|
||||
|
||||
<tbody class="divide-y divide-divider">
|
||||
<!-- We are using slot props for future proofing so that in future, we can implement features like filtering -->
|
||||
<slot name="body" :list="list">
|
||||
<tr
|
||||
v-for="(rowData, rowIndex) in list"
|
||||
:key="rowIndex"
|
||||
class="text-secondaryDark hover:bg-divider hover:cursor-pointer rounded-xl"
|
||||
:class="{ 'divide-x divide-divider': showYBorder }"
|
||||
>
|
||||
<td
|
||||
v-for="cellHeading in headings"
|
||||
:key="cellHeading.key"
|
||||
@click="!cellHeading.preventClick && onRowClicked(rowData)"
|
||||
class="max-w-40 pl-6 py-1"
|
||||
>
|
||||
<!-- Dynamic column slot -->
|
||||
<slot :name="cellHeading.key" :item="rowData">
|
||||
<!-- Generic implementation of the column -->
|
||||
<div class="flex flex-col truncate">
|
||||
<span class="truncate">
|
||||
{{ rowData[cellHeading.key] ?? "-" }}
|
||||
</span>
|
||||
</div>
|
||||
</slot>
|
||||
</td>
|
||||
</tr>
|
||||
</slot>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup generic="Item extends Record<string, unknown>">
|
||||
export type CellHeading = {
|
||||
key: string
|
||||
label?: string
|
||||
preventClick?: boolean
|
||||
}
|
||||
|
||||
defineProps<{
|
||||
/** Whether to show the vertical border between columns */
|
||||
showYBorder?: boolean
|
||||
/** The list of items to be displayed in the table */
|
||||
list?: Item[]
|
||||
/** The headings of the table */
|
||||
headings?: CellHeading[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: "onRowClicked", item: Item): void
|
||||
}>()
|
||||
|
||||
const onRowClicked = (item: Item) => emit("onRowClicked", item)
|
||||
</script>
|
||||
@@ -16,6 +16,7 @@ export { default as HoppSmartSlideOver } from "./SlideOver.vue"
|
||||
export { default as HoppSmartSpinner } from "./Spinner.vue"
|
||||
export { default as HoppSmartTab } from "./Tab.vue"
|
||||
export { default as HoppSmartTabs } from "./Tabs.vue"
|
||||
export { default as HoppSmartTable } from "./Table.vue"
|
||||
export { default as HoppSmartToggle } from "./Toggle.vue"
|
||||
export { default as HoppSmartWindow } from "./Window.vue"
|
||||
export { default as HoppSmartWindows } from "./Windows.vue"
|
||||
|
||||
69
packages/hoppscotch-ui/src/stories/Table.story.vue
Normal file
69
packages/hoppscotch-ui/src/stories/Table.story.vue
Normal file
@@ -0,0 +1,69 @@
|
||||
<template>
|
||||
<Story title="Table">
|
||||
<Variant title="General">
|
||||
<HoppSmartTable :list="list" :headings="headings" />
|
||||
</Variant>
|
||||
<Variant title="Custom">
|
||||
<HoppSmartTable>
|
||||
<template #head>
|
||||
<tr
|
||||
class="text-secondary border-b border-dividerDark text-sm text-left bg-primaryLight"
|
||||
>
|
||||
<th
|
||||
v-for="heading in headings"
|
||||
:key="heading.key"
|
||||
scope="col"
|
||||
class="px-6 py-3"
|
||||
>
|
||||
{{ heading.label }}
|
||||
</th>
|
||||
</tr>
|
||||
</template>
|
||||
|
||||
<template #body>
|
||||
<tr
|
||||
v-for="item in list"
|
||||
:key="item.id"
|
||||
class="text-secondaryDark hover:bg-divider hover:cursor-pointer rounded-xl"
|
||||
>
|
||||
<td
|
||||
v-for="cellHeading in headings"
|
||||
:key="cellHeading.key"
|
||||
class="max-w-40 pl-6 py-1"
|
||||
>
|
||||
{{ item[cellHeading.key] ?? "-" }}
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</HoppSmartTable>
|
||||
</Variant>
|
||||
</Story>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { HoppSmartTable } from "../components/smart"
|
||||
import { CellHeading } from "~/components/smart/Table.vue"
|
||||
|
||||
// Table Headings
|
||||
const headings: CellHeading[] = [
|
||||
{ key: "id", label: "ID" },
|
||||
{ key: "name", label: "Name" },
|
||||
{ key: "members", label: "Members" },
|
||||
{ key: "role", label: "Role" },
|
||||
]
|
||||
|
||||
const list: Record<string, string | number>[] = [
|
||||
{
|
||||
id: "123455",
|
||||
name: "Joel",
|
||||
members: 10,
|
||||
role: "Frontend Engineer",
|
||||
},
|
||||
{
|
||||
id: "123456",
|
||||
name: "Anwar",
|
||||
members: 12,
|
||||
role: "Frontend Engineer",
|
||||
},
|
||||
]
|
||||
</script>
|
||||
8237
pnpm-lock.yaml
generated
8237
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -13,16 +13,20 @@ RUN pnpm install -f --offline
|
||||
|
||||
|
||||
FROM base_builder as backend
|
||||
RUN apk add caddy
|
||||
WORKDIR /usr/src/app/packages/hoppscotch-backend
|
||||
RUN pnpm exec prisma generate
|
||||
RUN pnpm run build
|
||||
COPY --from=base_builder /usr/src/app/packages/hoppscotch-backend/backend-subpath.Caddyfile /etc/caddy/backend-subpath.Caddyfile
|
||||
COPY --from=base_builder /usr/src/app/packages/hoppscotch-backend/backend-multiport.Caddyfile /etc/caddy/backend-multiport.Caddyfile
|
||||
# Remove the env file to avoid backend copying it in and using it
|
||||
RUN rm "../../.env"
|
||||
ENV PRODUCTION="true"
|
||||
ENV PORT=3170
|
||||
ENV PORT=8080
|
||||
ENV APP_PORT=${PORT}
|
||||
ENV DB_URL=${DATABASE_URL}
|
||||
CMD ["pnpm", "run", "start:prod"]
|
||||
CMD ["node", "/usr/src/app/packages/hoppscotch-backend/prod_run.mjs"]
|
||||
EXPOSE 80
|
||||
EXPOSE 3170
|
||||
|
||||
FROM base_builder as fe_builder
|
||||
@@ -31,39 +35,51 @@ RUN pnpm run generate
|
||||
|
||||
FROM caddy:2-alpine as app
|
||||
WORKDIR /site
|
||||
COPY --from=fe_builder /usr/src/app/packages/hoppscotch-sh-admin/prod_run.mjs /usr
|
||||
COPY --from=fe_builder /usr/src/app/packages/hoppscotch-selfhost-web/Caddyfile /etc/caddy/Caddyfile
|
||||
COPY --from=fe_builder /usr/src/app/packages/hoppscotch-selfhost-web/prod_run.mjs /usr
|
||||
COPY --from=fe_builder /usr/src/app/packages/hoppscotch-selfhost-web/aio.Caddyfile /etc/caddy/Caddyfile
|
||||
COPY --from=fe_builder /usr/src/app/packages/hoppscotch-selfhost-web/dist/ .
|
||||
RUN apk add nodejs npm
|
||||
RUN npm install -g @import-meta-env/cli
|
||||
EXPOSE 8080
|
||||
EXPOSE 80
|
||||
EXPOSE 3000
|
||||
CMD ["/bin/sh", "-c", "node /usr/prod_run.mjs && caddy run --config /etc/caddy/Caddyfile --adapter caddyfile"]
|
||||
|
||||
FROM base_builder as sh_admin_builder
|
||||
WORKDIR /usr/src/app/packages/hoppscotch-sh-admin
|
||||
# Generate two builds for `sh-admin`, one based on subpath-access and the regular build
|
||||
RUN pnpm run build
|
||||
RUN pnpm run build --outDir dist-subpath-access --base /admin/
|
||||
|
||||
FROM caddy:2-alpine as sh_admin
|
||||
WORKDIR /site
|
||||
COPY --from=sh_admin_builder /usr/src/app/packages/hoppscotch-sh-admin/prod_run.mjs /usr
|
||||
COPY --from=sh_admin_builder /usr/src/app/packages/hoppscotch-sh-admin/Caddyfile /etc/caddy/Caddyfile
|
||||
COPY --from=sh_admin_builder /usr/src/app/packages/hoppscotch-sh-admin/dist/ .
|
||||
COPY --from=sh_admin_builder /usr/src/app/packages/hoppscotch-sh-admin/sh-admin-multiport-setup.Caddyfile /etc/caddy/sh-admin-multiport-setup.Caddyfile
|
||||
COPY --from=sh_admin_builder /usr/src/app/packages/hoppscotch-sh-admin/sh-admin-subpath-access.Caddyfile /etc/caddy/sh-admin-subpath-access.Caddyfile
|
||||
COPY --from=sh_admin_builder /usr/src/app/packages/hoppscotch-sh-admin/dist /site/sh-admin-multiport-setup
|
||||
COPY --from=sh_admin_builder /usr/src/app/packages/hoppscotch-sh-admin/dist-subpath-access /site/sh-admin-subpath-access
|
||||
RUN apk add nodejs npm
|
||||
RUN npm install -g @import-meta-env/cli
|
||||
EXPOSE 8080
|
||||
CMD ["/bin/sh", "-c", "node /usr/prod_run.mjs && caddy run --config /etc/caddy/Caddyfile --adapter caddyfile"]
|
||||
EXPOSE 80
|
||||
EXPOSE 3100
|
||||
CMD ["node","/usr/prod_run.mjs"]
|
||||
|
||||
FROM backend as aio
|
||||
RUN apk add caddy tini
|
||||
RUN npm install -g @import-meta-env/cli
|
||||
COPY --from=fe_builder /usr/src/app/packages/hoppscotch-selfhost-web/dist /site/selfhost-web
|
||||
COPY --from=sh_admin_builder /usr/src/app/packages/hoppscotch-sh-admin/dist /site/sh-admin
|
||||
COPY aio.Caddyfile /etc/caddy/Caddyfile
|
||||
COPY --from=sh_admin_builder /usr/src/app/packages/hoppscotch-sh-admin/dist-subpath-access /site/sh-admin-subpath-access
|
||||
COPY aio-multiport-setup.Caddyfile /etc/caddy/aio-multiport-setup.Caddyfile
|
||||
COPY aio-subpath-access.Caddyfile /etc/caddy/aio-subpath-access.Caddyfile
|
||||
ENTRYPOINT [ "tini", "--" ]
|
||||
RUN apk --no-cache add curl
|
||||
COPY --chmod=755 healthcheck.sh .
|
||||
HEALTHCHECK --interval=2s CMD /bin/sh ./healthcheck.sh
|
||||
CMD ["node", "/usr/src/app/aio_run.mjs"]
|
||||
EXPOSE 3170
|
||||
EXPOSE 8080
|
||||
EXPOSE 3000
|
||||
EXPOSE 3100
|
||||
EXPOSE 80
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user