repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
projectbox99/mean
dev/app/app.module.ts
<filename>dev/app/app.module.ts "use strict"; import { NgModule } from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { FormsModule } from "@angular/forms"; import { HttpModule } from "@angular/http"; // used to create fake backend // import { MockBackend, MockConnection } from "@angular/http/testing"; import { BaseRequestOptions } from "@angular/http"; // import { fakeBackendProvider } from "./Services/fake-backend"; // services import { AuthService } from "./Services/authentication.service"; import { AuthGuard } from "./Services/auth.guard"; import { UserService } from "./Services/users.service"; import { StandingData } from "./Services/standing.data.service"; import { PagerService } from "./Services/pager.service"; import { SearchService } from "./Services/search.service"; import { AboutService } from "./Services/about.service"; // components import { AppLayout } from "./app.layout"; import { HomeComponent } from "./home/home.component"; import { AboutComponent } from "./about/about.component"; import { UserRegistrationComponent } from "./register/register.component"; import { UsersComponent } from "./users/users.component"; import { PageNotFoundComponent } from "./404.component"; // directives import { NavLinkDirective } from "./Directives/nav-link-behavior"; import { routing, appRoutingProviders } from "./app.routes"; import { AdsModule } from "./ads/ads.module"; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, routing, AdsModule ], declarations: [ AppLayout, HomeComponent, AboutComponent, UserRegistrationComponent, UsersComponent, PageNotFoundComponent, NavLinkDirective ], providers: [ appRoutingProviders, AuthGuard, AuthService, UserService, StandingData, PagerService, SearchService, AboutService, // providers used to create fake backend // fakeBackendProvider, // MockBackend, BaseRequestOptions ], bootstrap: [ AppLayout ] }) export class AppModule { }
projectbox99/mean
dev/app/home/home.component.ts
<filename>dev/app/home/home.component.ts "use strict"; import { Router } from "@angular/router"; import { Component, OnInit, Input } from "@angular/core"; import { Observable } from "rxjs/Observable"; import { Subscription } from "rxjs/Subscription"; // services import { User, UserService } from "../Services/users.service"; import { Ad, AdsService } from "../Services/ads.service"; import { AuthService } from "../Services/authentication.service"; import { StandingData, Lists } from "../Services/standing.data.service"; import { PagerService } from "../Services/pager.service"; import { SearchService } from "../Services/search.service"; @Component ({ // selector: "user-list", templateUrl: "home.component.html", styleUrls: [ "home.component.css" ], providers: [ AdsService ] }) export class HomeComponent implements OnInit { private lists: Lists; private ads: Ad[]; private adsCount: number; private loading: boolean; private active: boolean; private error: string; private search: string; private isInSearchResults: boolean; private activeCategory: string; private activeCity: string; private searchAds: Ad[]; private startIdx: number; private count: number; private pager: any = {}; private pagedItems: any[]; private currentPage: number; constructor(private router: Router, private userService: UserService, private adsService: AdsService, private authService: AuthService, private standingData: StandingData, private pagerService: PagerService, private searchService: SearchService) { this.setErrorMsg(""); this.lists = new Lists([], [], []); this.ads = <Ad[]>[]; this.adsCount = 0; this.loadStandingData(); this.searchAds = <Ad[]>[]; this.search = ""; this.isInSearchResults = false; this.activeCategory = ""; this.activeCity = ""; this.startIdx = 0; this.count = 9; this.currentPage = 0; // this.pager = this.pagerService.getPager(this.adsCount || this.count, this.currentPage); // this.getHomeAds(this.startIdx, this.count); } // constructor() public loadStandingData(): void { this.lists = this.standingData.getLists() } // loadStandingData() public getHomeAds(startIdx: number = this.startIdx, count: number = this.count): void { this.adsService.getAds(startIdx, count).subscribe( res => { this.ads = res; this.adsCount = this.adsService.count; this.isInSearchResults = false; this.pager = this.pagerService.getPager(this.adsCount || 0, this.currentPage); this.pagedItems = this.ads; }, error => { this.setErrorMsg("Could not retrieve ads!"); console.error(this.error); } ) } // getHomeAds() private previewAd(id: string): void { if (id) { this.router.navigate([ '/ads/preview', id ]); } } // previewAd() private changeActiveCategory(cat: string): void { if (cat.trim()) { if (cat.trim() !== this.activeCategory) { this.activeCategory = cat.trim(); } else { this.activeCategory = ""; } } } // changeActiveCategory() private changeActiveCity(city: string): void { if (city.trim()) { if (city.trim() !== this.activeCity) { this.activeCity = city.trim(); } else { this.activeCity = ""; } } } // changeActiveCategory() private startSearch(): void { if (this.search.trim()) { console.log(`Entering startSearch()`); this.searchService.searchInAds(this.search.trim(), this.activeCategory, this.activeCity).subscribe( res => { this.searchAds = res; this.adsCount = this.searchService.count; //this.ads = this.searchAds.slice(0, Math.min(this.count - 1, this.adsCount)); console.log(`this.searchAds: ${JSON.stringify(this.searchAds)}`); console.log(`this.adsCount: ${this.adsCount}`); this.pager = this.pagerService.getPager(this.adsCount, 1, this.count); this.displaySeachResults(this.pager.startIndex, this.pager.endIndex); this.isInSearchResults = true; }, error => { this.setErrorMsg("Could not execute search!"); console.error(this.error); } ) } } // startSearch() private displaySeachResults(start: number = this.pager.startIndex, end: number = this.pager.endIndex): void { if (this.searchAds && this.adsCount) { this.pagedItems = this.searchAds.slice(start, end + 1); } else { this.pagedItems = []; } } // displaySeachResults() // private helpers private setErrorMsg(errMsg?: string): void { let msg = errMsg.trim(); if (msg) { this.error = msg; setTimeout(() => this.error = "", 5000 /* ms */); } else this.error = ""; } // setErrorMsg() private setPage(page: number): void { if (page < 1 || page > this.pager.totalPages) { return; } this.pager = this.pagerService.getPager(this.adsCount || this.count, page); // this.pagedItems = this.ads.slice(this.pager.startIndex, this.pager.endIndex + 1); if (this.currentPage !== page) { if (!this.isInSearchResults) { this.getHomeAds(this.pager.startIndex, this.count); } else { this.displaySeachResults(this.pager.startIndex, this.pager.endIndex); } this.currentPage = page; } // this.pager = this.pagerService.getPager(this.dummyItems.length, page); // this.pagedItems = this.dummyItems.slice(this.pager.startIndex, this.pager.endIndex + 1); } // setPage() ngOnInit() { this.loading = false; this.active = true; this.setPage(1); } // ngOnInit() } // class HomeComponent
projectbox99/mean
dev/app/Services/ads.service.ts
<filename>dev/app/Services/ads.service.ts<gh_stars>0 "use strict"; import { Injectable } from "@angular/core"; import { Http, Headers, Response, RequestOptions } from "@angular/http"; import { Observable } from "rxjs/Observable"; export class Ad { constructor( public id: string = "", public title: string = "", public category: string = "", public desc: string = "", public photoMain: string = "", public photos: any[] = [], public city: string = "", public price: number = 0, public owner: string = "", public approved: boolean = false, public dateCreated: Date = new Date, public dateValid: Date = new Date) { } } // class Ad @Injectable() export class AdsService { private adsUrl: string = window.location.protocol + "//" + window.location.hostname + ((window.location.port === "80") ? ("") : (":" + window.location.port)) + "/api/ads"; public count: number; private token: string; constructor(private http: Http) { this.count = 0; this.token = JSON.parse(sessionStorage.getItem("token")); } public getAds(startIndex: number = 0, count: number = 0): Observable<any> { let headers = new Headers({ "Authorization": "Bearer " + this.token }); let options = new RequestOptions({ headers: headers }); let urlToUse: string; if (count) { urlToUse = `${this.adsUrl}/${startIndex}/${count}`; } else { urlToUse = this.adsUrl; console.log(`Using ${this.adsUrl}`); } return this.http.get(urlToUse, options) .map( res => { let data: any = this.extractData(res); this.count = data.count ? <number>data.count : 0; return !count ? data : data.ads; }) .catch(this.handleError); } // getAds() public getMyAds(id: string): Observable<Ad[]> { let headers = new Headers({ "Authorization": "Bearer " + this.token, "Content-Type": "application/json" }); let options = new RequestOptions({ headers: headers }); let body = "{\"user\":\"" + id + "\"}"; return this.http.post(this.adsUrl + "/list", body, options) .map(this.extractData) .catch(this.handleError); } // getMyAds() public getAd(id: string): Observable<Ad> { if (!id) { console.log(`getAd was called with a bad id argument: ${id.toString()}`); return Observable.create(new Ad()); } let headers = new Headers({ "Authorization": "Bearer " + this.token }); let options = new RequestOptions({ headers: headers }); return this.http.get(this.adsUrl + "/" + id, options) .map((response: Response) => { let adData = this.extractData(response); if (adData._id) { adData.id = adData._id; return adData; } else { return Observable.create(new Ad()); } }) .catch(this.handleError); } // getAd() public postAd(ad: Ad): Observable<Ad> { if (!ad) { console.log(`postUser was called with a bad ad id argument: ${JSON.stringify(ad)}`); return Observable.create(new Ad()); } let headers = new Headers({ "Authorization": "Bearer " + this.token, "Content-Type": "application/json" }); let options: RequestOptions = new RequestOptions({ headers: headers }); let body: string = JSON.stringify(ad); console.log(`SERVICE URL: ${this.adsUrl}`); console.log(`SERVICE POST: ${body}`); return this.http.post(this.adsUrl, body, options) // returns Observable<Response> .map(this.extractData) // success .catch(this.handleError); // error } // postAd() public putAd(ad: Ad): Observable<Ad> { if (!ad || !ad.id) { console.log(`putUser was called with a bad ad id argument: ${JSON.stringify(ad)}`); return Observable.create(new Ad()); } let headers = new Headers({ "Authorization": "Bearer " + this.token, "Content-Type": "application/json" }); let options = new RequestOptions({ headers: headers }); let body: string = JSON.stringify(ad); return this.http.put(this.adsUrl + "/" + ad.id, body, options) .map((response: Response) => { let adData = this.extractData(response); if (adData._id) { adData.id = adData._id; console.log(`Service returned: ${JSON.stringify(adData)}`); return adData; } else { return Observable.create(new Ad()); } }) .catch(this.handleError); } // putAd() public deleteAd(id: string): Observable<boolean> { if (!id) { console.log(`deleteAd was called with a bad id argument: ${id.toString()}`); return Observable.create(false); } let headers = new Headers({ "Authorization": "Bearer " + this.token }); let options = new RequestOptions({ headers: headers }); return this.http.delete(this.adsUrl + "/" + id, options) .map((response: Response) => { return this.extractData(response)._id ? true : false; }) .catch((error) => { this.handleError(error).map((errMsg) => console.error("deleteUser Error: " + errMsg)); return Observable.create(false); }); } // deleteAd() private extractData(res: Response) { let body = res.json(); return body.data || {}; } // extractData() private handleError (error: any): Observable<string> { let errMsg = (error.message) ? error.message : (error.status) ? `${error.status} - ${error.statusText}` : "Server Error"; console.error(errMsg); return Observable.throw(errMsg); } // handleError() } // class AdsService
projectbox99/mean
dev/app/Services/standing.data.service.ts
"use strict"; import { Injectable } from "@angular/core"; import { Http, Headers, Response, RequestOptions } from "@angular/http"; import { Observable } from "rxjs/Observable"; import "rxjs/add/operator/map"; import "rxjs/add/operator/catch"; // import { AuthService } from "./authentication.service"; export class Lists { constructor(public categories: string[], public cities: string[], public roles: string[]) { } } // class Lists @Injectable() export class StandingData { public lists: Lists; private token: string; private listsUrl: string = window.location.protocol + "//" + window.location.hostname + ((window.location.port === "80") ? ("") : (":" + window.location.port)) + "/api/lists"; constructor (private http: Http /* private authService: AuthService */) { this.lists = new Lists([], [], []); } public getLists(): Lists { if (this.lists && this.lists.categories && this.lists.categories.length > 0 && this.lists.cities && this.lists.cities.length > 0 && this.lists.roles && this.lists.roles.length > 0) { return Observable.create(this.lists); } else { this.loadStandingData().subscribe( result => this.lists, error => this.lists ); } } // getLists() private loadStandingData(): Observable<boolean> { this.token = JSON.parse(sessionStorage.getItem("token")) || ""; let headers = new Headers({ "Authorization": "Bearer " + this.token }); let options = new RequestOptions({ headers: headers }); return this.http.get(this.listsUrl, options) .map((response: Response) => { let reply = this.extractData(response); if (reply.categories && reply.cities && reply.roles) { this.lists.categories = reply.categories; this.lists.cities = reply.cities; this.lists.roles = reply.roles; return Observable.create(true); } else { return Observable.create(false); } }) .catch((error) => this.handleError(error)); } // loadStandingData() public addCategory(edited: string): Observable<Lists> { if (!edited) { console.log(`addCategory was called with a bad category argument!`); return Observable.create(this.lists); } this.token = JSON.parse(sessionStorage.getItem("token")) || ""; let headers = new Headers({ "Authorization": "Bearer " + this.token, "Content-Type": "application/json" }); let options = new RequestOptions({ headers: headers }); let body: string = JSON.stringify({ category: edited }); console.info(`addCategory calling API with: ${body}`); return this.http.post(this.listsUrl, body, options) .map((response: Response) => { let result = this.extractData(response); this.lists = this.extractData(response); console.info(`standing.data.service.lists set to: ${JSON.stringify(this.lists)}`); return result; }) .catch(this.handleError); } // addCategory() public modifyCategory(picked: string, edited: string): Observable<Lists> { if (!picked) { console.log(`modifyCategory was called with a bad category argument!}`); return Observable.create(this.lists); } if (!edited) { console.log(`modifyCategory was called with a bad modified category argument!`); return Observable.create(this.lists); } this.token = JSON.parse(sessionStorage.getItem("token")) || ""; let headers = new Headers({ "Authorization": "Bearer " + this.token, "Content-Type": "application/json" }); let options = new RequestOptions({ headers: headers }); let body: string = JSON.stringify({ category: picked, modified: edited }); console.info(`modifyCategory calling API with: ${body}`); return this.http.put(this.listsUrl, body, options) .map((response: Response) => { let result = this.extractData(response); if (result && result.categories) { this.lists = result; console.info(`standing.data.service.lists set to: ${this.lists}`); return result; } }) .catch(this.handleError); } // modifyCategory() public removeCategory(edited: string): Observable<Lists> { if (!edited) { console.log(`removeCategory was called with a bad category argument!`); return Observable.create(false); } this.token = JSON.parse(sessionStorage.getItem("token")) || ""; let headers = new Headers({ "Authorization": "Bearer " + this.token }); let options = new RequestOptions({ headers: headers }); console.info(`removeCategory calling API with: ${edited}`); return this.http.delete(this.listsUrl + "/" + edited, options) .map((response: Response) => { let result = this.extractData(response); this.lists = this.extractData(response); console.info(`standing.data.service.lists set to: ${JSON.stringify(this.lists)}`); return result; }) .catch(this.handleError); } // removeCategory() // private helpers private removeCategoryFromLocalCache(category: string): void { if (category) { console.info(`standing.data.service.removeCategoryFromLocalCache(${category}) called.`); let foundAtIndex: number = -1; for (let i = 0; i < this.lists.categories.length && foundAtIndex < 0; ++i) { if (category === this.lists.categories[i]) foundAtIndex = i; } if (foundAtIndex > -1) this.lists.categories.splice(foundAtIndex, 1); console.info(`removeCategoryFromLocalCache -> ${this.lists.categories}`); } } // removeCategoryFromLocalCache() private extractData(res: Response) { let body = res.json(); return body.data || {}; } // extractData() private handleError (error) { let errMsg = (error.message) ? error.message : (error.status) ? `${error.status} - ${error.statusText}` : "Server Error"; console.error("error: " + errMsg); return Observable.throw(errMsg); } // handleError() } // class RegisterService
projectbox99/mean
dev/app/Services/search.service.ts
import { Http, Headers, Response, RequestOptions } from "@angular/http"; import { Observable } from "rxjs/Observable"; import { Subscription } from "rxjs/Subscription"; import { Injectable } from "@angular/core"; import { Ad } from "./ads.service"; import { User } from "./users.service"; import "rxjs/add/operator/map"; import "rxjs/add/operator/catch"; @Injectable() export class SearchService { constructor(private http: Http) { this.token = JSON.parse(sessionStorage.getItem('token')); } private url_Ads: string = window.location.protocol + "//" + window.location.hostname + ((window.location.port === "80") ? ("") : (":" + window.location.port)) + "/api/ads/search"; private token: string; public results: Ad[]; public count: number; public searchInAds(str: string, cat: string = "", city: string = ""): Observable<Ad[]> { if (str) { let headers = new Headers({ "Authorization": "Bearer " + this.token, "Content-Type": "application/json" }); let options = new RequestOptions({ headers: headers }); let body: string = JSON.stringify({ str: str, cat: cat, city: city }); return this.http.post(`${this.url_Ads}`, body, options) .map( res => { let data: any = this.extractData(res); this.count = data.count; return data.ads; }) .catch(this.handleError); } } // searchInAds() // private helpers private extractData(res: Response) { let body = res.json(); return body.data || {}; } // extractData() private handleError (error: any): Observable<string> { let errMsg = (error.message) ? error.message : (error.status) ? `${error.status} - ${error.statusText}` : "Server Error"; console.error(errMsg); return Observable.throw(errMsg); } // handleError() }
logue/vuetify-swatch
vite.config.docs.ts
import { createVuePlugin as Vue } from 'vite-plugin-vue2'; import eslintPlugin from '@modyqyw/vite-plugin-eslint'; import { defineConfig, type UserConfig } from 'vite'; import path from 'path'; // https://vitejs.dev/config/ const config: UserConfig = { base: './', // Resolver resolve: { // https://vitejs.dev/config/#resolve-alias alias: [ // make vue external { find: 'vue', replacement: path.resolve( __dirname, './node_modules/vue/dist/vue.runtime.esm.js' ), }, { find: 'vuetify', replacement: path.resolve(__dirname, './node_modules/vuetify'), }, { // vue @ shortcut fix find: '@/', replacement: `${path.resolve(__dirname, './src')}/`, }, { find: 'src/', replacement: `${path.resolve(__dirname, './src')}/`, }, ], // External dedupe: ['vue', 'vuetify'], }, // https://vitejs.dev/config/#server-options server: { fs: { // Allow serving files from one level up to the project root allow: ['..'], }, }, plugins: [ Vue(), // eslint // https://github.com/ModyQyW/vite-plugin-eslint eslintPlugin(), ], // Build Options // https://vitejs.dev/config/#build-options build: { outDir: 'docs', rollupOptions: { output: { manualChunks: { vue: ['vue', 'vue-demi'], vuetify: ['vuetify/lib', 'vuetify/lib/util/colors'], codemirror: [ '@codemirror/state', '@codemirror/view', '@codemirror/basic-setup', '@codemirror/lang-html', ], }, }, }, target: 'es2021', }, }; // Export vite config export default defineConfig(config);
logue/vuetify-swatch
components.d.ts
// generated by unplugin-vue-components // We suggest you to commit this file into source control // Read more: https://github.com/vuejs/vue-next/pull/3399 import '@vue/runtime-core' declare module '@vue/runtime-core' { export interface GlobalComponents { VBtn: typeof import('vuetify/lib')['VBtn'] VIcon: typeof import('vuetify/lib')['VIcon'] VSheet: typeof import('vuetify/lib')['VSheet'] VSwatches: typeof import('./src/components/VSwatches.vue')['default'] } } export {}
logue/vuetify-swatch
src/index.ts
/** * Vuetify Swatches Component * * @license MIT * @author Logue {@link <EMAIL>} * @copyright 2022 <NAME> {@link https://logue.dev/} All rights reserved. * @see {@link https://github.com/logue/vuetify-swatches} */ import VSwatches from './components/VSwatches.vue'; import { install, isVue2 } from 'vue-demi'; const installVSwatches = isVue2 ? app => { app.component('VSwatches', VSwatches); } : install(); export { VSwatches as default, installVSwatches as install };
logue/vuetify-swatch
dev/serve.ts
import { createApp, isVue3, Vue2 } from 'vue-demi'; import vuetify from './plugins/vuetify'; import Dev from './DemoPage.vue'; if (isVue3) { console.info('ℹ Running as Vue3.'); createApp(Dev).mount('#app'); } else { console.info('ℹ Running as Vue2.'); // @ts-ignore new Vue2({ vuetify, render: h => h(Dev), }).$mount('#app'); }
logue/vuetify-swatch
dev/plugins/vuetify.ts
<filename>dev/plugins/vuetify.ts import { getCurrentInstance } from 'vue-demi'; import Vuetify from 'vuetify/lib'; import Vue from 'vue'; Vue.use(Vuetify); export default new Vuetify(); /** Get vuetify instance (For Composition api) */ export function useVuetify() { /** Get Instance */ const instance = getCurrentInstance(); if (!instance) { throw new Error(`Should be used in setup().`); } // @ts-ignore return instance.proxy.$vuetify; }
logue/vuetify-swatch
src/env.d.ts
/* eslint-disable */ /// <reference types="vite/client" /> declare module '*.vue' { import Vue from 'vue'; export default Vue; } interface ImportMetaEnv { // see https://vitejs.dev/guide/env-and-mode.html#env-files // add .env variables. } interface ImportMeta { readonly env: ImportMetaEnv; }
msolefonte/kafka-restapi-client
src/lib/KafkaRestClient.ts
'use strict'; const request = require('request-promise-native'); import { ApiVersion, AuthenticationCredentials, EmbeddedFormat, ConsumerConfig, KafkaRestClientConfig, Partition, PartitionMetadata, ProduceRequest, SerializationFormat, TopicMetadata } from '../../types/' import { KafkaRestConsumer } from "./KafkaRestConsumer"; export class KafkaRestClient { private readonly apiVersion: ApiVersion; private readonly auth: AuthenticationCredentials; private readonly acceptHeader: string; private readonly contentTypeHeader: string; private readonly embeddedFormat: EmbeddedFormat; private readonly serializationFormat: SerializationFormat; private readonly url: string; constructor(config: KafkaRestClientConfig = {}) { this.apiVersion = config.apiVersion || "v2"; this.auth = config.auth; this.embeddedFormat = config.embeddedFormat || "binary"; this.serializationFormat = config.serializationFormat || "json"; this.url = config.url || "http://localhost:8082"; this.acceptHeader = "application/vnd.kafka." + this.apiVersion + "+" + this.serializationFormat; this.contentTypeHeader = "application/vnd.kafka." + this.embeddedFormat + "." + this.apiVersion + "+" + this.serializationFormat; } // Get a list of Kafka topics. async getTopics(): Promise<string[]> { const requestOptions: any = { uri: this.url + '/topics', headers: { 'Accept': this.acceptHeader }, json: this.serializationFormat === "json" }; if (this.auth) { requestOptions.auth = this.auth; } return request(requestOptions); } // // Get metadata about a specific topic. // async getTopicMetadata(topicName: string): Promise<TopicMetadata> // { // return {} // } // Produce messages to a topic, optionally specifying keys or partitions for the messages. async produceMessages(topicName: string, produceRequest: ProduceRequest, partitionId: number = undefined): Promise<void> { let uri = this.url + '/topics/' + topicName; if(partitionId) { uri += 'partitions/' + partitionId } const requestOptions: any = { uri: uri, method: 'post', headers: { 'Accept': this.acceptHeader, 'Content-Type': this.contentTypeHeader }, body: produceRequest, json: this.serializationFormat === "json" }; if (this.auth) { requestOptions.auth = this.auth; } return request(requestOptions); } // // Get a list of partitions for the topic. // async getPartitions(): Promise<Partition[]> // { // return // } // // // Get metadata about a single partition in the topic. // async getPartitionMetadata(topicName: string, partitionId: number): Promise<PartitionMetadata> // { // return // } // // // produceMessagesToPartition // // // Create a new consumer instance in the consumer group. // async createConsumer(groupName: string, consumerConfig: ConsumerConfig, // idempotent: boolean = false): Promise<KafkaRestConsumer> // { // return // } // // // Destroy the consumer instance. // async deleteConsumer(groupName: string, instanceId: string, // idempotent: boolean = false): Promise<void> // { // // } async getBrokers(): Promise<number[]> { const requestOptions: any = { uri: this.url + '/brokers', headers: { 'Accept': this.acceptHeader }, json: this.serializationFormat === "json" }; if (this.auth) { requestOptions.auth = this.auth; } return request(requestOptions) .then((response: any) => { return response.brokers }) } }
msolefonte/kafka-restapi-client
src/index.ts
'use strict'; export { KafkaRestClient } from './lib/KafkaRestClient'
msolefonte/kafka-restapi-client
types/index.d.ts
<reponame>msolefonte/kafka-restapi-client export type ApiVersion = "v1" | "v2"; export interface AuthenticationCredentials { username: string; password: string; } export interface ConsumerConfig { } export type EmbeddedFormat = "avro" | "binary" | "json"; export interface KafkaRestClientConfig { apiVersion?: ApiVersion; auth?: AuthenticationCredentials; embeddedFormat?: EmbeddedFormat; serializationFormat?: SerializationFormat; url?: string; } export interface Partition { partition: number; leader: number; replicas: Replica[] } export interface PartitionMetadata { } export interface ProduceRequest { records: Record[]; key_schema?: string; key_schema_id?: number; value_schema?: string; value_schema_id?: number; } export interface Record { value: any; key?: any; partition?: any; } export interface Replica { broker: number; leader: boolean; in_sync: boolean; } export type SerializationFormat = "json"; export interface TopicMetadata { }
msolefonte/kafka-restapi-client
src/lib/KafkaRestConsumer.ts
'use strict'; export class KafkaRestConsumer { private readonly url: string; constructor(url: string) { this.url = url ; } /* CONSUMER commitOffsets getOffsets subscribe getSubscriptions deleteSubscription assignPartitions getAssignedPartitions overrideOffsets //Seek to the first offset for each of the given partitions. //Seek to the last offset for each of the given partitions. //Fetch data for the topics or partitions specified using one of the subscribe/assign APIs. destroy */ }
tony-aq/optic
workspaces/local-cli/src/commands/check.ts
<gh_stars>100-1000 import { Command } from '@oclif/command'; export default class Check extends Command { static description = 'verify that Optic can run your tasks and monitor traffic'; static hidden = true; static args = [ { name: 'taskName', }, ]; async run() { const { args } = this.parse(Check); const { taskName } = args; this.log(`Deprecated, going forward use 'api run ${taskName} --verbose' `); } }
tony-aq/optic
workspaces/ui-v2/src/components/SimulatedCommandStore.tsx
import React, { useContext, useEffect, useMemo, useState } from 'react'; import { Provider } from 'react-redux'; import { v4 as uuidv4 } from 'uuid'; import { LinearProgress } from '@material-ui/core'; import { CQRSCommand } from '@useoptic/optic-domain'; import { IForkableSpectacle } from '@useoptic/spectacle'; import { SpectacleStore } from '<src>/contexts/spectacle-provider'; import { createReduxStore, useAppSelector } from '<src>/store'; import { useLastBatchCommitId } from '<src>/hooks/useBatchCommits'; type SimulatedCommandStoreProps = { spectacle: IForkableSpectacle; previewCommands: CQRSCommand[]; children: (batchId: string | undefined) => React.ReactElement; }; type SimulatedCommandContextValue = { previewCommands: CQRSCommand[]; }; export const SimulatedCommandContext = React.createContext<SimulatedCommandContextValue>( { previewCommands: [] } ); export function SimulatedCommandStore(props: SimulatedCommandStoreProps) { const batchId = useLastBatchCommitId(); const value = { previewCommands: props.previewCommands }; const [isProcessing, setIsProcessing] = useState(true); const store = useMemo(() => createReduxStore(), []); const [simulated, setSimulated] = useState<IForkableSpectacle | undefined>( undefined ); const clientSessionId = useAppSelector( (state) => state.metadata.data?.sessionId! ); useEffect(() => { async function task() { const simulated = await props.spectacle.fork(); await simulated.mutate({ query: ` mutation X($commands: [JSON!]!, $batchCommitId: ID!, $commitMessage: String!, $clientId: ID!, $clientSessionId: ID!) { applyCommands(commands: $commands, batchCommitId: $batchCommitId, commitMessage: $commitMessage, clientId: $clientId, clientSessionId: $clientSessionId) { batchCommitId } } `, variables: { commands: props.previewCommands, batchCommitId: uuidv4(), commitMessage: 'proposed changes', clientId: 'simulation-agent', //@TODO: in the future, for features based on the clientId to make sense in the simulated ui, we may need to provide a real id here clientSessionId, }, }); //@ts-ignore simulated.thiscontext = 'simulated'; //@ts-ignore simulated.instanceId = uuidv4(); setSimulated(simulated); setIsProcessing(false); } task(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [JSON.stringify(props.previewCommands)]); if (isProcessing) { return <LinearProgress variant="indeterminate" />; } const spectacleToUse = simulated ? simulated : props.spectacle; return ( <SimulatedCommandContext.Provider value={value}> <SpectacleStore spectacle={spectacleToUse}> <Provider store={store}>{props.children(batchId)}</Provider> </SpectacleStore> </SimulatedCommandContext.Provider> ); } export function useSimulatedCommands() { const { previewCommands } = useContext(SimulatedCommandContext); return previewCommands; }
tony-aq/optic
workspaces/shape-hash/src/protobuf-support.ts
const protobuf = require('protobufjs'); const definition = { nested: { optic_shape_hash: { nested: { FieldDescriptor: { fields: { key: { type: 'string', id: 1, }, hash: { type: 'ShapeDescriptor', id: 2, }, }, }, ShapeDescriptor: { fields: { type: { type: 'PrimitiveType', id: 1, }, fields: { rule: 'repeated', type: 'FieldDescriptor', id: 2, }, items: { rule: 'repeated', type: 'ShapeDescriptor', id: 3, }, rules: { rule: 'repeated', type: 'string', id: 4, }, }, nested: { PrimitiveType: { values: { OBJECT: 0, ARRAY: 1, STRING: 2, NUMBER: 3, BOOLEAN: 4, NULL: 5, }, }, }, }, }, }, }, }; const ShapeHashProto = (() => { const root = protobuf.Root.fromJSON(definition); return root.lookupType('optic_shape_hash.ShapeDescriptor'); })(); export const encodeShapeHash = (payload: any) => { const message = ShapeHashProto.create(payload); return ShapeHashProto.encode(message).finish(); }; export const decodeShapeHash = (payload: any) => { return ShapeHashProto.decode(payload).toJSON(); };
tony-aq/optic
workspaces/graph-lib/src/index.ts
import * as endpoints from './endpoints-graph'; import * as shapes from './shapes-graph'; export { endpoints, shapes };
tony-aq/optic
workspaces/ui-v2/src/utils/encodeQueryParams.ts
<filename>workspaces/ui-v2/src/utils/encodeQueryParams.ts export function encodeQueryParams(params: Record<string, string>): String { return Object.entries(params) .map(([k, v]) => `${k}=${encodeURIComponent(v)}`) .join('&'); }
tony-aq/optic
workspaces/ui-v2/src/errors/invariant.ts
export class InvariantViolationError extends Error {}
tony-aq/optic
workspaces/ui-v2/src/pages/diffs/components/IDiffExampleViewer.tsx
import React, { useCallback, useReducer } from 'react'; import classNames from 'classnames'; import { makeStyles } from '@material-ui/core/styles'; import { SymbolColor, useColor, useShapeViewerStyles } from './SharedStyles'; import _isEqual from 'lodash.isequal'; import _get from 'lodash.get'; import _uniq from 'lodash.uniq'; import CheckCircleIcon from '@material-ui/icons/CheckCircle'; import WarningIcon from '@material-ui/icons/Warning'; import { toCommonJsPath } from '@useoptic/cli-shared/build/diffs/json-trail'; import CheckIcon from '@material-ui/icons/Check'; import { ICopy, ICopyRenderSpan } from './ICopyRender'; import { IChangeType } from '../../../lib/Interfaces'; import { AddedGreen, secondary, ShapeViewerTheme } from '<src>/styles'; /* WARNING: Lots of unconstrained types here from the JS -> Typescript port. We need to come back and remove `:any` once we have this working vertically. Worth the 1-2 hrs to keep this complex component maintainable. +1 */ export type InteractionViewerBody = { noBody?: boolean; asJson?: any; asText?: string; empty?: boolean; }; type InteractionBodyViewerProps = { diff?: any; description?: any; jsonTrails?: any[]; body: InteractionViewerBody; assertion?: ICopy[]; trailsAreCorrect?: boolean; }; export default function InteractionBodyViewerAllJS({ description, jsonTrails = [], body, assertion, trailsAreCorrect = true, }: InteractionBodyViewerProps) { const generalClasses = useShapeViewerStyles(); const [{ rows }, dispatch] = useReducer( updateState, { body, jsonTrails, description }, createInitialState ); const diffDetails = description && { description, assertion, changeType: description.changeType, trailsAreCorrect, // changeDescription: 'changed!', }; return ( <div className={generalClasses.root}> {rows.map((row: IDiffExampleViewerRow, index: number) => { return ( <Row key={row.id} index={index} {...row} diffDetails={row.compliant ? {} : diffDetails} dispatch={dispatch} /> ); })} </div> ); } export function Row(props: any) { const classes = useStyles(); const { collapsed, compliant, diffDetails, indent, index, fieldsHidden, seqIndex, fieldName, fieldValue, type, dispatch, } = props; const onRowClick = useCallback( (e) => { if (!collapsed) return; e.preventDefault(); if (type === 'array_item_collapsed') { dispatch({ type: 'unfold-index', payload: index }); } if (type === 'object_keys_collapsed') { dispatch({ type: 'unfold-fields', payload: index }); } }, [index, type, dispatch, collapsed] ); const indentPadding = ' '.repeat(indent * 2); return ( <div className={classNames(classes.row, { // [generalClasses.isTracked]: !!props.tracked, // important for the compass to work [classes.isCollapsed]: collapsed, [classes.isIncompliant]: !compliant && !collapsed, [classes.isCollapsedIncompliant]: !compliant && collapsed, [classes.requiresAddition]: diffDetails && !diffDetails.trailsAreCorrect && diffDetails.changeType === IChangeType.Added, [classes.requiresUpdate]: diffDetails && !diffDetails.trailsAreCorrect && diffDetails.changeType === IChangeType.Changed, [classes.requiresRemoval]: diffDetails && !diffDetails.trailsAreCorrect && diffDetails.changeType === IChangeType.Removed, [classes.trailsAreCorrect]: diffDetails.trailsAreCorrect, })} > <div className={classes.rowContent} onClick={onRowClick}> {indentPadding} <RowFieldName type={type} name={fieldName} /> <RowSeqIndex type={type} index={seqIndex} /> <RowValue isRoot={indent === 0} type={type} fieldsHidden={fieldsHidden} value={fieldValue} compliant={compliant} changeDescription={diffDetails && diffDetails.changeDescription} /> </div> {!compliant && !collapsed && (diffDetails.trailsAreCorrect ? ( <TrailCheck {...diffDetails} /> ) : ( <DiffAssertion {...diffDetails} /> ))} </div> ); } Row.displayName = 'ShapeViewer/Row'; function RowValue({ type, value, compliant, changeDescription, trailsAreCorrect, isRoot, fieldsHidden, }: any) { const generalClasses = useShapeViewerStyles(); const classes = useStyles(); if (type === 'null') { return ( <span className={classNames( generalClasses.symbols, classes.symbolContent, 'fs-exclude' )} > {'null'} </span> ); } if (type === 'array_open') { return ( <span className={classNames(generalClasses.symbols, classes.symbolContent)} > {'['} </span> ); } if (type === 'array_item_collapsed') { return ( <span className={classes.collapsedSymbol}> {'⋯'} {!compliant ? ( changeDescription || !trailsAreCorrect ? ( <CheckCircleIcon className={classes.collapsedChangeIcon} /> ) : ( <WarningIcon className={classes.collapsedWarning} /> ) ) : ( '' )} </span> ); } if (type === 'object_keys_collapsed') { return ( <span className={classes.collapsedObjectSymbol}> {`...expand ${fieldsHidden} additional fields`} </span> ); } if (type === 'array_close') { return ( <span className={classNames(generalClasses.symbols, classes.symbolContent)} > {']'} </span> ); } if (type === 'object_open') { return ( <span className={classNames(generalClasses.symbols, classes.symbolContent)} > {'{'} </span> ); } if (type === 'object_close') { return ( <span className={classNames(generalClasses.symbols, classes.symbolContent)} > {'}'} </span> ); } if (type === 'string') { const quote = isRoot ? '' : '"'; return ( <span className={classNames(classes.stringContent, 'fs-exclude')}> {quote} {value} {quote} </span> ); } if (type === 'boolean') { return ( <span className="fs-exclude" style={{ color: '#d9ba99', fontWeight: 600 }} > {value ? 'true' : 'false'} </span> ); } if (type === 'number') { return ( <span className="fs-exclude" style={{ color: '#99d9d9', fontWeight: 600 }} > {value} </span> ); } if (type === 'undefined') { return null; } if (type === 'empty') { return ( <span className={classNames(generalClasses.symbols, classes.emptyContent)} > empty </span> ); } throw new Error(`Cannot render RowValue for type '${type}'`); } RowValue.displayName = 'ShapeViewer/RowValue'; function RowFieldName({ type, name }: any) { const classes = useStyles(); const missing = type === 'undefined'; if (!name) return null; return ( <span className={classNames(classes.fieldName, { [classes.isMissing]: type === 'undefined', })} > {name} {!missing && ': '} </span> ); } function RowSeqIndex({ type, index, missing }: any) { const classes = useStyles(); if (!index && index !== 0) return null; return ( <span className={classNames(classes.fieldIndex, { [classes.isMissing]: !!missing, })} > {index}:{' '} </span> ); } function DiffAssertion({ assertion, changeDescription }: any) { const classes = useStyles(); return ( <div className={classes.diffAssertion}> {changeDescription ? ( <> <CheckCircleIcon className={classes.selectectedChangeIcon} /> {/*<span className={classes.changeDescription}>*/} <span> <ICopyRenderSpan variant="subtitle2" copy={assertion} /> {/*{changeDescription.map(({ value }) => value).join(' ')}*/} </span> </> ) : ( <> <WarningIcon className={classes.assertionWarningIcon} /> <ICopyRenderSpan variant="subtitle2" copy={assertion} /> </> )} </div> ); } function TrailCheck({ assertion }: any) { const classes = useStyles(); return ( <div className={classes.diffAssertion}> <div style={{ flex: 1 }} /> <CheckIcon className={classes.correctTrailIcon} /> </div> ); } const useStyles = makeStyles((theme) => ({ row: { display: 'flex', padding: 0, paddingLeft: 4, flexDirection: 'row', alignItems: 'baseline', '&:hover': { backgroundColor: 'rgba(78,165,255,0.27)', }, '&$isCollapsed': { cursor: 'pointer', }, '&$isIncompliant, &$isCollapsedIncompliant:hover': { '&$requiresAddition': { backgroundColor: ShapeViewerTheme.added.background, }, '&$requiresRemoval': { backgroundColor: ShapeViewerTheme.removed.background, }, '&$requiresUpdate': { backgroundColor: ShapeViewerTheme.changed.background, }, }, }, rowContent: { flexGrow: 1, flexShrink: 1, overflow: 'hidden', padding: theme.spacing(0, 5 / 8), lineHeight: '25px', fontSize: 12, fontFamily: "'Source Code Pro', monospace", whiteSpace: 'pre', color: SymbolColor, }, collapsedRowValue: {}, collapsedSymbol: { paddingLeft: theme.spacing(1), paddingRight: theme.spacing(1), paddingTop: 3, color: '#070707', fontSize: 10, backgroundColor: '#ababab', borderRadius: 12, '$isCollapsedIncompliant$requiresAddition &': { backgroundColor: ShapeViewerTheme.added.background, color: ShapeViewerTheme.added.main, }, '$isCollapsedIncompliant$requiresRemoval &': { backgroundColor: ShapeViewerTheme.removed.background, color: ShapeViewerTheme.removed.main, }, '$isCollapsedIncompliant$requiresUpdate &': { backgroundColor: ShapeViewerTheme.changed.background, color: ShapeViewerTheme.changed.main, }, '$trailsAreCorrect &': { backgroundColor: ShapeViewerTheme.added.background, color: ShapeViewerTheme.added.main, }, }, collapsedObjectSymbol: { paddingRight: theme.spacing(1), paddingTop: 3, color: '#8f8f8f', fontSize: 10, borderRadius: 12, '$isCollapsedIncompliant$requiresAddition &': { backgroundColor: ShapeViewerTheme.added.background, color: ShapeViewerTheme.added.main, }, '$isCollapsedIncompliant$requiresRemoval &': { backgroundColor: ShapeViewerTheme.removed.background, color: ShapeViewerTheme.removed.main, }, '$isCollapsedIncompliant$requiresUpdate &': { backgroundColor: ShapeViewerTheme.changed.background, color: ShapeViewerTheme.changed.main, }, '$trailsAreCorrect &': { backgroundColor: ShapeViewerTheme.added.background, color: ShapeViewerTheme.added.main, }, }, collapsedWarning: { width: 10, height: 10, marginLeft: theme.spacing(0.5), color: theme.palette.secondary.main, }, collapsedChangeIcon: { width: 10, height: 10, marginLeft: theme.spacing(0.5), '$requiresAddition &': { color: ShapeViewerTheme.added.main, }, '$requiresRemoval &': { color: ShapeViewerTheme.removed.main, }, '$requiresUpdate &': { color: ShapeViewerTheme.changed.main, }, '$trailsAreCorrect &': { color: ShapeViewerTheme.added.main, }, }, booleanContent: { fontWeight: 600, fontFamily: "'Source Code Pro', monospace", color: useColor.BooleanColor, }, symbolContent: { color: SymbolColor, }, emptyContent: { color: SymbolColor, fontStyle: 'italic', }, numberContent: { fontWeight: 600, fontFamily: "'Source Code Pro', monospace", color: useColor.NumberColor, }, stringContent: { fontWeight: 600, whiteSpace: 'pre-line', wordBreak: 'break-all', overflowWrap: 'break-word', fontFamily: "'Source Code Pro', monospace", color: useColor.StringColor, }, missingContent: { fontWeight: 600, fontFamily: "'Source Code Pro', monospace", fontStyle: 'italic', opacity: 0.8, }, fieldName: { fontWeight: 600, color: '#cfcfcf', fontSize: 12, fontFamily: "'Source Code Pro', monospace", opacity: 1, '&$isMissing': { fontStyle: 'italic', opacity: 0.6, }, }, fieldIndex: { fontWeight: 500, color: '#9cdcfe', fontSize: 12, fontFamily: "'Source Code Pro', monospace", opacity: 1, '&$isMissing': { opacity: 0.4, }, }, diffAssertion: { flexGrow: 0, flexShrink: 0, alignSelf: 'center', minWidth: '35%', maxWidth: '50%', display: 'flex', alignItems: 'center', padding: theme.spacing(0, 2), color: '#f8edf4', fontSize: 14, fontWeight: 800, fontFamily: "'Source Code Pro', monospace", }, assertionWarningIcon: { width: 14, height: 14, marginRight: theme.spacing(1), color: secondary, }, selectectedChangeIcon: { width: 14, height: 14, marginRight: theme.spacing(1), '$requiresAddition &': { color: ShapeViewerTheme.added.main, }, '$requiresRemoval &': { color: ShapeViewerTheme.removed.main, }, '$requiresUpdate &': { color: ShapeViewerTheme.changed.main, }, }, correctTrailIcon: { width: 20, height: 20, marginRight: theme.spacing(1), color: AddedGreen, }, isCollapsed: {}, isMissing: {}, isIncompliant: {}, isCollapsedIncompliant: {}, requiresAddition: {}, requiresUpdate: {}, requiresRemoval: {}, trailsAreCorrect: {}, })); // ShapeViewer view model // ---------------------- // // We're using a reducer model so we can use pure transformation functions to // manage the view model's state. That should especially come in handy when we // want to cover this with tests, but will also help in making it into something // re-usable, using Typescript to implement it, etc. // // TODO: consider moving this to it's own module, partly to enable the usecase // stated above. function createInitialState({ jsonTrails, body }: any) { const diffTrails = jsonTrails.map(toCommonJsPath); if (!body.empty) { const shape = !body.noBody ? body.asJson || body.asText : undefined; const [rows, collapsedTrails] = shapeRows(shape, diffTrails); return { body: shape, rows, collapsedTrails, diffTrails }; } else { const rows = [emptyRow()]; const collapsedTrails = [] as any[]; return { body: undefined, rows, collapsedTrails, diffTrails }; } } function updateState(state: any, action: any) { const index = action.payload; switch (action.type) { case 'unfold-index': return unfoldRows(state, index); case 'unfold-fields': return unfoldObjectRows(state, index); default: throw new Error( `State cannot be updated through action of type '${action.type}'` ); } } function unfoldRows(currentState: any, index: number) { const row = currentState.rows[index]; if (row.type !== 'array_item_collapsed') return currentState; const collapsedShape = _get(currentState.body, row.trail); const rowField = { fieldValue: row.fieldValue, fieldName: row.fieldName, seqIndex: row.seqIndex, trail: [...row.trail], }; const [replacementRows, newCollapsedTrails] = shapeRows( collapsedShape, currentState.diffTrails, [], [], row.indent, rowField ); const updatedRows = [...currentState.rows]; updatedRows.splice(index, 1, ...replacementRows); const updatedCollapsedTrails = currentState.collapsedTrails .filter((trail: any) => !_isEqual(trail, row.trail)) .concat(newCollapsedTrails); return { ...currentState, rows: updatedRows, collapsedTrails: updatedCollapsedTrails, }; } function unfoldObjectRows(currentState: any, index: number) { const row = currentState.rows[index]; if (row.type !== 'object_keys_collapsed') return currentState; const updatedRows = [...currentState.rows]; const startIndex = updatedRows.findIndex( (i) => i.type === 'object_open' && _isEqual(i.trail, row.trail) ); const open = updatedRows[startIndex]; const collapsedShape = _get(currentState.body, open.trail, currentState.body); const rowField = { fieldValue: open.fieldValue, fieldName: open.fieldName, seqIndex: open.seqIndex, trail: [...open.trail], }; const [replacementRows, newCollapsedTrails] = shapeRows( collapsedShape, currentState.diffTrails, [], [], row.indent - 1, rowField, row.trail ); const endIndex = updatedRows.findIndex( (i, index) => i.type === 'object_close' && index > startIndex && _isEqual(i.trail, row.trail) ) + 1; const offset = endIndex - startIndex; updatedRows.splice(startIndex, offset, ...replacementRows); const updatedCollapsedTrails = currentState.collapsedTrails .filter((trail: any) => !_isEqual(trail, row.trail)) .concat(newCollapsedTrails); return { ...currentState, rows: updatedRows, collapsedTrails: updatedCollapsedTrails, }; } // Since we've run into performance issue before traversing entire shapes, we're doing this // the mutative way to prevent a lot of re-alloctions for big bodies. function shapeRows( shape: any, diffTrails: any[] = [], rows: any[] = [], collapsedTrails: any[] = [], indent: number = 0, field: { fieldName: string | undefined; fieldValue: any | undefined; seqIndex: number | undefined; trail: any[]; } = { fieldName: undefined, fieldValue: undefined, seqIndex: undefined, trail: [], }, expandObjectWithTrail?: any ) { const typeString = Object.prototype.toString.call(shape); switch (typeString) { case '[object Object]': // debugger; objectRows( shape, diffTrails, rows, collapsedTrails, indent, field, expandObjectWithTrail ); break; case '[object Array]': // debugger; listRows(shape, diffTrails, rows, collapsedTrails, indent, field); break; default: let type = getFieldType(shape); let row = createRow( { type, ...field, fieldValue: field && field.fieldValue ? field.fieldValue : shape, indent, }, { diffTrails } ); rows.push(createRow(row)); break; } return [rows, collapsedTrails]; } function objectRows( objectShape: any, diffTrails: any[], rows: any[], collapsedTrails: any[], indent: number, field: any, expandObjectWithTrail: any ) { const { trail } = field; rows.push( createRow( { type: 'object_open', fieldName: field.fieldName, seqIndex: field.seqIndex, trail, indent, }, { diffTrails } ) ); const nestedDiffs = diffTrails.filter((diffTrail: any) => trail.every( (trailComponent: any, n: any) => trailComponent === diffTrail[n] ) ); function hasNestedDiff(trail: any) { return nestedDiffs.some((i: any) => _isEqual(i.slice(0, trail.length), trail) ); } const keysWithDiffs = nestedDiffs .filter((nestedDiff: any) => nestedDiff.length === trail.length + 1) .map((diff: any) => diff[diff.length - 1]); const objectKeys = _uniq([...Object.keys(objectShape), ...keysWithDiffs]); const collapseAt = 9; const shouldCollapse = objectKeys.length > collapseAt && !_isEqual(expandObjectWithTrail, trail) && keysWithDiffs.length === 0 && indent !== 0; if (shouldCollapse) { collapsedTrails.push(trail); rows.push( createRow({ type: 'object_keys_collapsed', collapsed: true, indent: indent + 1, fieldsHidden: objectKeys.filter( (key: string) => !(keysWithDiffs.includes(key) || hasNestedDiff([...trail, key])) ).length, trail: trail, }) ); } objectKeys .sort(alphabetizeCaseInsensitve) .forEach((key: string, index: number) => { const fieldName = key; const fieldTrail = [...trail, fieldName]; const value = objectShape[key]; if (shouldCollapse) { if (keysWithDiffs.includes(key) || hasNestedDiff(fieldTrail)) { shapeRows(value, nestedDiffs, rows, collapsedTrails, indent + 1, { fieldName, seqIndex: undefined, fieldValue: value, trail: fieldTrail, }); } else { } } else { shapeRows(value, nestedDiffs, rows, collapsedTrails, indent + 1, { fieldName, seqIndex: undefined, fieldValue: value, trail: fieldTrail, }); } }); rows.push(createRow({ type: 'object_close', indent, trail })); } function alphabetizeCaseInsensitve(A: string, B: string): number { const a = A.toLowerCase ? A.toLowerCase() : A; const b = B.toLowerCase ? B.toLowerCase() : B; if (a > b) { return 1; } else if (b > a) { return -1; } return 0; } function listRows( list: any, diffTrails: any[], rows: any[], collapsedTrails: any[], indent: number, field: any ) { const { trail } = field; rows.push( createRow( { type: 'array_open', indent, fieldName: field.fieldName, seqIndex: field.seqIndex, trail, }, { diffTrails } ) ); const nestedDiffs = diffTrails.filter( (diffTrail) => diffTrail.length > trail.length && trail.every( (trailComponent: any, n: number) => trailComponent === diffTrail[n] ) ); const indexesWithDiffs = list .map((item: any, index: number) => index) .filter((index: number) => { return nestedDiffs.some((diffTrail) => index === diffTrail[trail.length]); }); list.forEach((item: any, index: number) => { let itemTypeString = Object.prototype.toString.call(item); let itemTrail = [...trail, index]; let itemIndent = indent + 1; if ( (itemTypeString !== '[object Object]' && itemTypeString !== '[object Array]') || (indexesWithDiffs.length > 0 && indexesWithDiffs[0] === index) || (indexesWithDiffs.length === 0 && index === 0) ) { shapeRows(item, diffTrails, rows, collapsedTrails, itemIndent, { fieldName: undefined, seqIndex: index, fieldValue: item, trail: itemTrail, }); } else { rows.push( createRow({ type: 'array_item_collapsed', collapsed: true, compliant: !indexesWithDiffs.includes(index), seqIndex: index, indent: itemIndent, trail: itemTrail, }) ); collapsedTrails.push(itemTrail); } }); rows.push(createRow({ type: 'array_close', indent, trail })); } function emptyRow() { return createRow({ type: 'empty', collapsed: false, compliant: true, trail: [], }); } function getFieldType(fieldValue: any): string { if (typeof fieldValue === 'undefined') { return 'undefined'; } const jsTypeString = Object.prototype.toString.call(fieldValue); switch (jsTypeString) { case '[object Null]': return 'null'; case '[object String]': return 'string'; case '[object Boolean]': return 'boolean'; case '[object Number]': return 'number'; default: debugger; throw new Error( `Can not return field type for fieldValue with type string '${jsTypeString}'` ); } } interface IDiffExampleViewerRow { id: string; collapsed: false; compliant: boolean; type: string; trail: any[]; } function createRow(row: any, options: any = {}): IDiffExampleViewerRow { const trail = row && row.trail; const type = row && row.type; if (!trail || !Array.isArray(trail)) new TypeError('trail (array) must be known to create a row'); if (!type) new TypeError('type must be known to create a row'); const id = `${row.trail.join('.') || 'root'}-${row.type}`; const isCompliant = !options.diffTrails || !options.diffTrails.some((diffTrail: any) => _isEqual(diffTrail, trail)); return { id, collapsed: false, compliant: isCompliant, ...row, }; }
tony-aq/optic
workspaces/ui-v2/src/lib/__tests/diff-helpers/trail-parsers.test.ts
<reponame>tony-aq/optic<gh_stars>100-1000 import { ParsedDiff } from '<src>/lib/parse-diff'; import { buildUniverse } from '<src>/lib/__tests/diff-helpers/universes/buildUniverse'; test('accurate spec trail for all diffs', async () => { const { opticContext, currentSpecContext } = await buildUniverse( require('./universes/simple-todo/universe.json') ); const started = await opticContext.capturesService.startDiff( '123', 'example-session' ); await started.onComplete; const result = await opticContext.diffRepository.findById('123'); const diffs = (await result.listDiffs()).diffs; const parsedDiffs = diffs.map( ([diff, interactions, fingerprint]: any) => new ParsedDiff(diff, interactions, fingerprint) ); parsedDiffs.forEach((i: ParsedDiff) => { expect(i).toMatchSnapshot(i.diffHash + '-parsed'); expect(i.location(currentSpecContext)).toMatchSnapshot( i.diffHash + '-parsed-location' ); }); });
tony-aq/optic
workspaces/ui-v2/src/components/loaders/index.ts
export * from './Loaders'; export * from './Errors'; export * from './SpinningOpticLogo';
tony-aq/optic
workspaces/ui-v2/src/pages/diffs/ReviewEndpointDiffPage/DiffLinks.tsx
<reponame>tony-aq/optic import React from 'react'; import { IInterpretation } from '<src>/lib/Interfaces'; import { ICopyRender } from '../components/ICopyRender'; import { makeStyles } from '@material-ui/styles'; import { List, ListItem, ListSubheader } from '@material-ui/core'; export function DiffLinks({ allDiffs, setSelectedDiff, }: { allDiffs: IInterpretation[]; setSelectedDiff: (index: number) => void; }) { const classes = useStyles(); return ( <List> {allDiffs.map((diff, i) => { const { location, diffHash, title } = diff.diffDescription; const isQueryParameter = location.isQueryParameter(); const requestDescriptor = location.getRequestDescriptor(); const responseDescriptor = location.getResponseDescriptor(); return ( <React.Fragment key={diffHash}> <ListSubheader className={classes.locationHeader}> {isQueryParameter ? 'Query Parameters' : requestDescriptor ? `Request Body ${requestDescriptor.contentType}` : responseDescriptor ? `${responseDescriptor.statusCode} Response ${responseDescriptor.contentType}` : 'Unknown location'} </ListSubheader> <ListItem button onClick={() => setSelectedDiff(i)}> <ICopyRender variant="" copy={title} /> </ListItem> </React.Fragment> ); })} </List> ); } const useStyles = makeStyles((theme) => ({ locationHeader: { fontSize: 10, height: 33, }, }));
tony-aq/optic
workspaces/ui-v2/src/contexts/analytics/utils.ts
import { v4 as uuidv4 } from 'uuid'; const LOCAL_STORAGE_CLIENT_AGENT_KEY = 'USER_CLIENT_AGENT'; export const getOrSetAgentFromLocalStorage = (defaultValue: string) => { try { const clientAgent = window.localStorage.getItem( LOCAL_STORAGE_CLIENT_AGENT_KEY ); if (clientAgent) { return clientAgent; } else { const generatedClientAgent = `anonymous_user_${uuidv4()}`; window.localStorage.setItem( LOCAL_STORAGE_CLIENT_AGENT_KEY, generatedClientAgent ); return generatedClientAgent; } } catch (e) { // SecurityError can be thrown if permissions are blocked return defaultValue; } };
tony-aq/optic
workspaces/ui-v2/src/contexts/OpticConfigContext.tsx
import React, { FC } from 'react'; import { useContext } from 'react'; import { IOpticConfigRepository } from '@useoptic/spectacle'; export function useConfigRepository(): { config: IOpticConfigRepository; } { const config = useContext(ConfigRepositoryContext)!; return { config, }; } interface ConfigServiceStoreProps { config: IOpticConfigRepository; } export const ConfigRepositoryContext = React.createContext<IOpticConfigRepository | null>( null ); export const ConfigRepositoryStore: FC<ConfigServiceStoreProps> = (props) => { return ( <ConfigRepositoryContext.Provider value={props.config}> {props.children} </ConfigRepositoryContext.Provider> ); };
tony-aq/optic
workspaces/ui-v2/src/store/selectors/__tests__/shapeSelectors.test.ts
import { RootState } from '<src>/store/root'; import { getShapeRenderer, createFlatList, convertShapeToQueryParameters, } from '../shapeSelectors'; import { getMockReduxStore } from './testHelpers'; let store: RootState; beforeEach(() => { store = getMockReduxStore(); }); describe('getShapeRenderer', () => { test('loading', () => { store.shapes.rootShapes['shape_123'] = { loading: true, }; expect(getShapeRenderer('shape_123')(store)).toEqual({ loading: true, }); }); test('no shape', () => { expect(getShapeRenderer('shape_123')(store)).toEqual({ loading: true, }); }); test('error', () => { store.shapes.rootShapes['shape_123'] = { loading: false, error: new Error('asd'), }; const shapeState = getShapeRenderer('shape_123')(store); expect(shapeState.loading).toBe(false); expect(shapeState.error).toBeTruthy(); }); test('converts shapes to shape renderers', () => { const shapeState = getShapeRenderer('shape_cEkQAVQ3ib')(store); expect(shapeState.loading).toBe(false); expect(shapeState.data).toMatchSnapshot(); }); }); describe('createFlatList', () => { test('converts shape to a contribution list', () => { const shapeState = getShapeRenderer('shape_cEkQAVQ3ib')(store); expect( createFlatList(shapeState.data!, 'path_UOIsxzICu5.GET') ).toMatchSnapshot(); }); }); describe('convertShapeToQueryParameters', () => { test('converts a shape renderer into a query parameter', () => { const shapeState = getShapeRenderer('shape_tNRgroSwLj')(store); expect(convertShapeToQueryParameters(shapeState.data!)).toMatchSnapshot(); }); });
tony-aq/optic
workspaces/ui-v2/src/pages/diffs/AddEndpointsPage/components/index.ts
export * from './AddEndpointDiffHeader'; export * from './BulkLearnModal'; export * from './EndpointNameEditFields'; export * from './UndocumentedUrl';
tony-aq/optic
workspaces/cli-shared/test/tests/ecs.ts
<reponame>tony-aq/optic // Getting the Typescript compiler to find these in cli-shared/typings through // passing it a tsconfig has been successful :( /// <reference types="../../typings/stream-chain/index" /> /// <reference types="../../typings/stream-json/index" /> import Tap from 'tap'; import Path from 'path'; import Fs from 'fs-extra'; import { ecsToHttpInteraction } from '../../build/ingest/ecs-to-sample'; Tap.test('ecs to interactions', async (test) => { const inputDir = Path.join(__dirname, '../fixtures/ecs-examples'); const examples = Fs.readdirSync( Path.join(__dirname, '../fixtures/ecs-examples') ).map((i) => [Path.basename(i, '.json'), require(Path.join(inputDir, i))]); examples.forEach((example) => { const [name, value] = example; test.matchSnapshot(ecsToHttpInteraction(value, name), `ecs-${name}`); }); });
tony-aq/optic
workspaces/local-cli/src/commands/exec.ts
import { Command, flags } from '@oclif/command'; import { LocalCliTaskFlags, LocalTaskSessionWrapper, runCommandFlags, } from '../shared/local-cli-task-runner'; import { cleanupAndExit, loadPathsAndConfig } from '@useoptic/cli-shared'; import { isCommandOnlyTask } from '@useoptic/cli-config'; import { ingestOnlyTaskRunner } from '../shared/ingest-only-task-runner'; export default class Exec extends Command { static description = 'run a command and receives traffic over an ingest-service'; static flags = runCommandFlags; static args = [ { name: 'command', }, ]; async run() { const { args } = this.parse(Exec); const { flags } = this.parse(Exec); const { command } = args; await ingestOnlyTaskRunner(this, command, flags); } }
tony-aq/optic
workspaces/shape-hash/src/test/shape-hash.test.ts
import { toBytes, toJsonExample } from '../json-to-shape-hash'; import { decodeShapeHash } from '../protobuf-support'; const example = { glossary: { title: 'example glossary', GlossDiv: { title: 'S', GlossList: { GlossEntry: { ID: null, SortAs: 'SGML', GlossTerm: 'Standard Generalized Markup Language', Acronym: 'SGML', Abbrev: 'ISO 8879:1986', GlossDef: { para: 'A meta-markup language, used to create markup languages such as DocBook.', GlossSeeAlso: ['GML', 'XML'], }, GlossSee: 'markup', }, }, }, }, }; test('can shape hash a json object', async () => { expect(toBytes(example)).toMatchSnapshot(); expect(toBytes(example).toString('base64')).toMatchSnapshot(); }); test('can decode the hash', async () => { expect(decodeShapeHash(toBytes(example))).toMatchSnapshot(); }); test('can create a sanitized example from the hash', async () => { const hash = toBytes(example).toString('base64'); expect(toJsonExample(hash)).toMatchSnapshot(); }); test('shape hashes of string are secure', async () => { expect(toBytes('123,456,789')).toMatchSnapshot(); }); test('correctly encode "{}"', async () => { expect(toBytes({})).toMatchSnapshot(); });
tony-aq/optic
workspaces/ui-v2/src/pages/docs/DocumentationRootPage/EndpointRow.tsx
<gh_stars>100-1000 import React, { FC, useState } from 'react'; import { useHistory, useRouteMatch } from 'react-router-dom'; import { IconButton, makeStyles, ListItem, Tooltip, darken, } from '@material-ui/core'; import { Delete as DeleteIcon, Undo as UndoIcon } from '@material-ui/icons'; import { RemovedRedBackground } from '<src>/styles'; import { EndpointName } from '<src>/components'; import { IEndpoint } from '<src>/types'; import { getEndpointId } from '<src>/utils'; import { DeleteEndpointConfirmationModal, EndpointNameMiniContribution, } from '../components'; import { useAppSelector, useAppDispatch, selectors, documentationEditActions, } from '<src>/store'; type EndpointRowProps = { endpoint: IEndpoint; }; export const EndpointRow: FC<EndpointRowProps> = ({ endpoint }) => { const history = useHistory(); const match = useRouteMatch(); const classes = useStyles(); const endpointId = getEndpointId({ method: endpoint.method, pathId: endpoint.pathId, }); const dispatch = useAppDispatch(); const isEditing = useAppSelector( (state) => state.documentationEdits.isEditing ); const [deleteModalOpen, setDeleteModalOpen] = useState(false); const isEndpointStagedForDeletion = useAppSelector( selectors.isEndpointRemoved({ method: endpoint.method, pathId: endpoint.pathId, }) ); const removeEndpoint = () => dispatch( documentationEditActions.removeEndpoint({ method: endpoint.method, pathId: endpoint.pathId, }) ); const unremoveEndpoint = () => dispatch( documentationEditActions.unremoveEndpoint({ method: endpoint.method, pathId: endpoint.pathId, }) ); return ( <> {deleteModalOpen && ( <DeleteEndpointConfirmationModal endpoint={endpoint} handleClose={() => setDeleteModalOpen(false)} handleConfirm={() => { removeEndpoint(); setDeleteModalOpen(false); }} /> )} <ListItem button disableRipple disableGutters style={{ display: 'flex' }} className={ isEditing && isEndpointStagedForDeletion ? classes.deleted : '' } onClick={() => !isEndpointStagedForDeletion && history.push( `${match.url}/paths/${endpoint.pathId}/methods/${endpoint.method}` ) } > <div style={{ flex: 1 }}> <EndpointName method={endpoint.method} fullPath={endpoint.fullPath} leftPad={6} /> </div> <div className={classes.contributionsContainer} onClick={(e) => e.stopPropagation()} > <EndpointNameMiniContribution id={endpointId} endpoint={{ method: endpoint.method, pathId: endpoint.pathId, }} defaultText="name for this endpoint" contributionKey="purpose" initialValue={endpoint.purpose} /> {isEditing && ( <div> {isEndpointStagedForDeletion ? ( <Tooltip title="Unstage endpoint deletion"> <IconButton onClick={() => { unremoveEndpoint(); }} > <UndoIcon fontSize="small" /> </IconButton> </Tooltip> ) : ( <Tooltip title="Delete this endpoint"> <IconButton onClick={() => { setDeleteModalOpen(true); }} > <DeleteIcon fontSize="small" /> </IconButton> </Tooltip> )} </div> )} </div> </ListItem> </> ); }; const useStyles = makeStyles((theme) => ({ contributionsContainer: { display: 'flex', flexDirection: 'row', alignItems: 'center', paddingRight: 16, }, deleted: { backgroundColor: RemovedRedBackground, cursor: 'default', '&.Mui-focusVisible, &:hover': { backgroundColor: darken(RemovedRedBackground, 0.2), }, }, }));
tony-aq/optic
workspaces/cli-scripts/src/notify.ts
import notifier from 'node-notifier'; function run(url: string, icon: string) { notifier.notify({ title: 'Observed Unexpected API Behavior', message: 'Click here to review the diff in Optic', icon, timeout: 7000, open: url, wait: true, }); } const [, , url, icon] = process.argv; run(url, icon);
tony-aq/optic
workspaces/ui-v2/src/components/DebugOpticComponent.tsx
<reponame>tony-aq/optic import { FC, useEffect } from 'react'; import { IOpticSpecRepository } from '@useoptic/spectacle/build'; import { useSpecRepository } from '<src>/contexts/SpecRepositoryContext'; declare global { interface Window { __GLOBAL_DIFF_DEBUG_FUNCTION__?: () => any; debugOptic?: () => void; } } const GLOBAL_DIFF_DEBUG_FUNCTION = '__GLOBAL_DIFF_DEBUG_FUNCTION__'; // In the future, we could directly dump the redux store export const useGlobalDiffDebug = (fn: () => any) => { useEffect(() => { window[GLOBAL_DIFF_DEBUG_FUNCTION] = fn; return () => { delete window[GLOBAL_DIFF_DEBUG_FUNCTION]; }; }, [fn]); }; const debugDump = (specService: IOpticSpecRepository) => { return async function () { const events = await specService.listEvents(); const diffDebugFunction = window[GLOBAL_DIFF_DEBUG_FUNCTION]; const diffState = diffDebugFunction ? diffDebugFunction() : false; const diffStateCleaned = JSON.parse(JSON.stringify(diffState)); const output = JSON.stringify( { events, diffState: diffStateCleaned, }, null, 2 ); const blob = new Blob([output], { type: 'application/json' }); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `debug-optic-state-${Math.floor(Date.now() / 1000)}.json`; console.log(link); link.click(); }; }; export const DebugOpticComponent: FC<{}> = () => { const specRepo = useSpecRepository(); useEffect(() => { window.debugOptic = debugDump(specRepo); }, [specRepo]); return null; };
tony-aq/optic
workspaces/cli-shared/src/diffs/trail-values-worker-rust.ts
import { CaptureInteractionIterator } from '../captures/avro/file-system/interaction-iterator'; import fs from 'fs-extra'; import { learnShapeDiffAffordances } from '@useoptic/optic-engine-native'; import { Streams } from '@useoptic/optic-domain'; import { ShapeDiffAffordances } from '@useoptic/optic-domain/build/streams/learning-results/shape-diff-affordances'; import { getDiffOutputPaths } from './interaction-diff-worker-rust'; import path from 'path'; export interface ShapeDiffAffordancesConfig { captureId: string; diffId: string; events: any; captureBaseDirectory: string; } export { ShapeDiffAffordances }; export function getTrailLearnersOutputPaths(values: { captureBaseDirectory: string; captureId: string; }) { const { captureBaseDirectory, captureId } = values; const base = path.join(captureBaseDirectory, captureId, 'trails-learned'); const events = path.join(base, 'events.json'); return { base, events, }; } export class ShapeDiffAffordancesWorker { constructor(private config: ShapeDiffAffordancesConfig) {} async run(): Promise<{ [fingerprint: string]: ShapeDiffAffordances }> { const outputPaths = getTrailLearnersOutputPaths(this.config); await fs.ensureDir(outputPaths.base); await fs.writeJson(outputPaths.events, this.config.events); // diffs const diffResultsPath = getDiffOutputPaths(this.config).diffsStream; const interactionIterator = CaptureInteractionIterator( { captureId: this.config.captureId, captureBaseDirectory: this.config.captureBaseDirectory, }, (a) => true ); const taggedInteractions = (async function* (interactionItems) { for await (let item of interactionItems) { if (!item.hasMoreInteractions) break; if (!item.interaction) continue; let pointer = `${item.interaction.context.batchId}-${item.interaction.context.index}`; yield [item.interaction.value, [pointer]]; } })(interactionIterator); let learningResults = Streams.LearningResults.ShapeDiffAffordances.fromJSONL()( learnShapeDiffAffordances(taggedInteractions, { diffResultsPath, specPath: outputPaths.events, }) ); return await Streams.LearningResults.ShapeDiffAffordances.affordancesByFingerprint()( learningResults ); } }
tony-aq/optic
workspaces/ui-v2/src/utils/endpoint-utilities.ts
export function getEndpointId(endpoint: { pathId: string; method: string }) { const { pathId, method } = endpoint; return `${pathId}.${method.toUpperCase()}`; }
tony-aq/optic
workspaces/ui-v2/src/components/HttpBodySelector.tsx
import React, { useState } from 'react'; import { FormControl, FormControlLabel, makeStyles, Radio, RadioGroup, } from '@material-ui/core'; import { FontFamily } from '<src>/styles'; type HttpBodySelectorProps<T> = { items: T[]; children: (body: T) => React.ReactNode; getDisplayName: (item: T) => string; }; /** * A component that is used to select / handle different items */ export const HttpBodySelector: <T extends {}>( props: HttpBodySelectorProps<T> ) => React.ReactElement = ({ items, children, getDisplayName }) => { const [selectedItem, setSelectedItem] = useState(0); const inBoundsSelected = Math.min(selectedItem, items.length - 1); const classes = useStyles(); return ( <> {items.length === 0 ? ( <>No bodies found</> ) : items.length === 1 ? ( children(items[0]) ) : ( <> <FormControl component="fieldset" className={classes.formGroup}> <RadioGroup value={selectedItem} onChange={(e) => { setSelectedItem(Number(e.target.value)); }} className={classes.radioGroup} > {items.map((item, i) => ( <FormControlLabel classes={{ label: classes.radio, }} key={getDisplayName(item)} value={i} control={<Radio />} label={getDisplayName(item)} /> ))} </RadioGroup> </FormControl> {children(items[inBoundsSelected])} </> )} </> ); }; const useStyles = makeStyles((theme) => ({ formGroup: { marginBottom: theme.spacing(2), }, radioGroup: { display: 'flex', flexDirection: 'row', }, radio: { fontFamily: FontFamily, fontSize: theme.typography.fontSize - 1, }, }));
tony-aq/optic
workspaces/ui-v2/src/pages/docs/components/index.ts
export * from './Contributions'; export * from './DeleteEndpointConfirmationModal'; export * from './DocPageNavigation'; export * from './EditContributionsButton'; export * from './EndpointTOC'; export * from './MarkdownBodyContribution'; export * from './SimulatedBodyPreview'; export * from './ShapeEditor';
tony-aq/optic
workspaces/ui-v2/src/store/selectors/documentationEditSelectors.ts
<reponame>tony-aq/optic import { createSelector } from 'reselect'; import { RootState } from '../root'; import { IContribution } from '<src>/types'; import { getEndpointId } from '<src>/utils'; import { JsonType } from '@useoptic/optic-domain'; export const memoizedGetAllRemovedFields = createSelector< RootState, RootState['shapes'], string[], Set<string> >( (state) => state.shapes, (state) => state.documentationEdits.fields.removed, (shapes, removedFields) => { const allRemovedFields = new Set<string>(); for (const fieldId of removedFields) { allRemovedFields.add(fieldId); const stack = [shapes.fieldMap[fieldId].shapeId]; while (stack.length > 0) { const shapeId = stack.pop()!; const reduxShapes = shapes.shapeMap[shapeId]; for (const shape of reduxShapes) { if (shape.jsonType === JsonType.OBJECT) { for (const field of shape.asObject.fields) { stack.push(field.shapeId); allRemovedFields.add(field.fieldId); } } else if (shape.jsonType === JsonType.ARRAY) { stack.push(shape.asArray.shapeId); } } } } return allRemovedFields; } ); // Valid changes dedupes: // - same contribution value as already set // - a deleted endpoint cannot have other changes export const getValidContributions = (state: RootState): IContribution[] => { const { removedEndpoints, contributions } = state.documentationEdits; const removedEndpointsSet = new Set(removedEndpoints.map(getEndpointId)); const filteredContributions: IContribution[] = []; const removedFields = memoizedGetAllRemovedFields(state); for (const [id, idContributions] of Object.entries(contributions)) { for (const [contributionKey, { value, endpointId }] of Object.entries( idContributions )) { // TODO filter out contributions that have the same initial value const isContributionsForRemovedEndpoint = removedEndpointsSet.has( endpointId ); const isContributionForRemovedField = removedFields.has(id); if ( !isContributionsForRemovedEndpoint && !isContributionForRemovedField ) { filteredContributions.push({ id, contributionKey, value, endpointId, }); } } } return filteredContributions; }; export const getDocumentationEditStagedCount = (state: RootState) => { const { removedEndpoints, fields: { edited: editedFields, removed: removedFields }, } = state.documentationEdits; const validContributions = getValidContributions(state); return ( validContributions.length + removedEndpoints.length + removedFields.length + Object.keys(editedFields).length ); }; export const isEndpointRemoved = ({ pathId, method, }: { pathId: string; method: string; }) => (state: RootState) => { return !!state.documentationEdits.removedEndpoints.find( (endpoint) => endpoint.method === method && endpoint.pathId === pathId ); }; export const isEndpointEditable = ({ pathId, method, }: { pathId: string; method: string; }) => (state: RootState) => { return ( !state.documentationEdits.removedEndpoints.find( (endpoint) => endpoint.method === method && endpoint.pathId === pathId ) && state.documentationEdits.isEditing ); }; export const isFieldRemoved = (fieldId: string) => (state: RootState) => { const memoizedFields = memoizedGetAllRemovedFields(state); return memoizedFields.has(fieldId); }; export const isFieldRemovedRoot = (fieldId: string) => ( state: RootState ): boolean => { return !!state.documentationEdits.fields.removed.find( (removedFieldId) => removedFieldId === fieldId ); }; export const isEndpointFieldEditable = ({ pathId, method, fieldId, }: { pathId: string; method: string; fieldId: string; }) => (state: RootState) => { return ( isEndpointEditable({ pathId, method })(state) && !isFieldRemoved(fieldId)(state) ); };
tony-aq/optic
workspaces/api-checks/src/checks.ts
import { CheckFunction } from './types'; export const requireNotFoundWithGet: CheckFunction = async ({ endpoint }) => { if (!isMethod(endpoint, 'GET')) return; return requireStatusCode(endpoint, 404); }; export function isMethod(endpoint: any, method: string) { return endpoint.method === method; } export function hasStatusCode(endpoint: any, givenStatusCode: number) { return Boolean( endpoint.responses.find(({ statusCode }: { statusCode: number }) => { return statusCode === givenStatusCode; }) ); } export function requireStatusCode(endpoint: any, statusCode: number) { if (!hasStatusCode(endpoint, statusCode)) { return `Endpoint ${endpoint.absolutePathPatternWithParameterNames} ${endpoint.method} does not have a ${statusCode} status code`; } }
tony-aq/optic
workspaces/local-cli/src/commands/debug/capture.ts
import { Command } from '@oclif/command'; import { CaptureInteractionIterator } from '@useoptic/cli-shared/build/captures/avro/file-system/interaction-iterator'; import { getPathsRelativeToConfig, readApiConfig } from '@useoptic/cli-config'; import OS from 'os'; import cli from 'cli-ux'; import path from 'path'; import colors from 'colors'; import fs from 'fs-extra'; import { IgnoreFileHelper } from '@useoptic/cli-config/build/helpers/ignore-file-interface'; import { getOrCreateAnonId } from '@useoptic/cli-config/build/opticrc/optic-rc'; import { getSpecEventsFrom } from '@useoptic/cli-config/build/helpers/read-specification-json'; import { CapturesHelpers } from '@useoptic/cli-server/build/routers/spec-router'; const pJson = require('../../../package.json'); export default class DebugCapture extends Command { static description = 'produce a debug file (with sanitized interactions) that can be shared with Optic maintainers'; static hidden: boolean = true; static args = [ { name: 'captureId', description: 'the captureId, see the address bar /diffs/local/{this-id}', required: false, }, ]; async run() { const { args } = this.parse(DebugCapture); const { captureId } = args; const { capturesPath, configPath, basePath, opticIgnorePath, specStorePath, } = await getPathsRelativeToConfig(); const capturesHelper = new CapturesHelpers(capturesPath); const captures = await capturesHelper.listCaptureIds(); if (!captureId || !captures.includes(captureId)) { if (captures.length === 0) { return this.error('no captures found'); } this.log( colors.red.bold( 'run api debug:capture <captureId> | with one of these IDs:\n\n' ) ); captures.forEach((i) => this.log(i)); return; } cli.action.start('sanitizing json bodies...'); const configJson = await readApiConfig(configPath); const events = await getSpecEventsFrom(specStorePath); const ignoreRules = await new IgnoreFileHelper( opticIgnorePath, configPath ).getCurrentIgnoreRules(); const interactionIterator = CaptureInteractionIterator( { captureId: captureId, captureBaseDirectory: capturesPath, }, (i) => true ); const cleanedInteraction = []; for await (const item of interactionIterator) { if (!item.interaction) { continue; } const { batchId, index } = item.interaction.context; const itemValue = item.interaction.value; cli.action.start( 'sanitizing json bodies...', item.diffedInteractionsCounter.toString() ); //question? do we want to fill in a similar quantity of bytes for non json? itemValue.request.body.value.asJsonString = null; itemValue.request.body.value.asText = null; itemValue.response.body.value.asJsonString = null; itemValue.response.body.value.asText = null; cleanedInteraction.push(itemValue); } const result = { events, configJson, ignoreRules, session: { samples: cleanedInteraction, }, opticVersion: pJson.version, os: { arch: OS.arch(), cpus: OS.cpus(), memory: OS.totalmem(), }, }; cli.action.stop('Done!'); const anonId = await getOrCreateAnonId(); const savePath = path.join( basePath, '../', `debug-optic-${Date.now().toString()}-${anonId}.json` ); fs.writeJson(savePath, result); this.log('saved to: ' + savePath); } }
tony-aq/optic
workspaces/ui-v2/src/components/Button.tsx
<reponame>tony-aq/optic<gh_stars>100-1000 import React, { FC, ComponentProps } from 'react'; import { Button as MuiButton, CircularProgress, makeStyles, } from '@material-ui/core'; type ButtonProps = ComponentProps<typeof MuiButton> & { loading?: boolean; }; export const Button: FC<ButtonProps> = ({ children, loading, ...props }) => { const classes = useStyles(); return ( <MuiButton {...props}> {loading ? ( <CircularProgress className={classes.loading} size={20} /> ) : ( children )} </MuiButton> ); }; const useStyles = makeStyles((theme) => ({ loading: { marginLeft: theme.spacing(1), }, }));
tony-aq/optic
workspaces/ui-v2/src/components/Page/Page.tsx
import React, { FC, useEffect } from 'react'; import { useLocation } from 'react-router-dom'; import classNames from 'classnames'; import { Theme, makeStyles } from '@material-ui/core/styles'; import { FullPageLoader, FullPageError } from '../loaders'; import { TopNavigation } from '../navigation/TopNavigation'; /** * TODO - future enhancements for this components * - Include window.document.title logic here * - Move TopNavigation into `src/components/Page` */ const usePageStyles = makeStyles((theme) => ({ root: { display: 'flex', flexDirection: 'column', height: '100vh', }, })); const usePageBodyStyles = makeStyles<Theme, { padded?: boolean }>((theme) => ({ content: ({ padded = true }) => ({ display: 'flex', flexDirection: 'column', // default to vertical stacking of child elements by default flexGrow: 1, paddingLeft: padded ? theme.spacing(4) : 0, paddingRight: padded ? theme.spacing(4) : 0, }), })); type PageBodyProps = { padded?: boolean; style?: React.CSSProperties; className?: string; loading?: boolean; error?: boolean; }; const PageBody: FC<PageBodyProps> = ({ padded, style, children, className, loading, error, }) => { const classes = usePageBodyStyles({ padded }); return ( <div className={classNames(classes.content, className)} style={style}> {loading ? <FullPageLoader /> : error ? <FullPageError /> : children} </div> ); }; type PageProps = { style?: React.CSSProperties; scrollToTop?: boolean; className?: string; }; export const Page: FC<PageProps> & { Navbar: typeof TopNavigation; Body: typeof PageBody; } = ({ style, children, scrollToTop, className }) => { const classes = usePageStyles(); const { pathname } = useLocation(); useEffect(() => { if (scrollToTop) { window.scrollTo(0, 0); } }, [pathname, scrollToTop]); return ( <div className={classNames(classes.root, className)} style={style}> {children} </div> ); }; Page.Navbar = TopNavigation; Page.Body = PageBody;
tony-aq/optic
workspaces/ui-v2/src/components/loaders/Loaders.tsx
import React from 'react'; import { CenteredColumn } from '../layouts/CenteredColumn'; import { makeStyles } from '@material-ui/styles'; import { Box, Typography } from '@material-ui/core'; import { SpinningOpticLogo } from './SpinningOpticLogo'; interface ILoaderProps { title?: string; } export function FullPageLoader({ title }: ILoaderProps) { const classes = useStyles(); return ( <CenteredColumn maxWidth="md"> <div className={classes.center}> <LoaderWithOpticLogo title={title} /> </div> </CenteredColumn> ); } export function Loader({ title }: ILoaderProps) { const classes = useStyles(); return ( <div className={classes.padded}> <LoaderWithOpticLogo title={title} /> </div> ); } function LoaderWithOpticLogo({ title }: ILoaderProps) { const classes = useStyles(); return ( <Box display="flex"> <SpinningOpticLogo /> <Typography variant="h6" color="textSecondary" className={classes.text}> {title || 'Loading'}... </Typography> </Box> ); } const useStyles = makeStyles((theme) => ({ center: { display: 'flex', alignItems: 'center', justifyContent: 'center', height: 'calc(100vh - 40px)', }, text: { marginLeft: 10, marginTop: -1, fontFamily: 'Ubuntu Mono', }, padded: { padding: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', }, }));
tony-aq/optic
workspaces/ui-v2/src/pages/docs/components/EditContributionsButton.tsx
<reponame>tony-aq/optic import React from 'react'; import { useHistory } from 'react-router-dom'; import { ToggleButton } from '@material-ui/lab'; import { Typography, makeStyles } from '@material-ui/core'; import SaveAltIcon from '@material-ui/icons/SaveAlt'; import EditIcon from '@material-ui/icons/Edit'; import { CommitMessageModal } from '<src>/components'; import { useAnalytics } from '<src>/contexts/analytics'; import { useDocumentationPageLink } from '<src>/components/navigation/Routes'; import { useSpectacleContext } from '<src>/contexts/spectacle-provider'; import { useAppSelector, useAppDispatch, documentationEditActions, selectors, } from '<src>/store'; export function EditContributionsButton() { const classes = useStyles(); const history = useHistory(); const documentationPageRoute = useDocumentationPageLink(); const spectacle = useSpectacleContext(); const analytics = useAnalytics(); const isEditing = useAppSelector( (state) => state.documentationEdits.isEditing ); const specId = useAppSelector( (state) => state.metadata.data?.specificationId! ); const commitModalOpen = useAppSelector( (state) => state.documentationEdits.commitModalOpen ); const pendingCount = useAppSelector( selectors.getDocumentationEditStagedCount ); const removedEndpointsCount = useAppSelector( (state) => state.documentationEdits.removedEndpoints.length ); const dispatch = useAppDispatch(); const setCommitModalOpen = (commitModalOpen: boolean) => { dispatch( documentationEditActions.updateCommitModalState({ commitModalOpen, }) ); }; const setEditing = (isEditing: boolean) => { dispatch( documentationEditActions.updateEditState({ isEditing, }) ); }; const save = (commitMessage: string) => { // If we are on endpoint root page and we just deleted the page, we want to redirect const shouldRedirect = removedEndpointsCount > 0 && history.location.pathname !== documentationPageRoute.path; dispatch( documentationEditActions.saveDocumentationChanges({ spectacle, commitMessage, }) ) .then(() => { analytics.userSavedDocChanges( removedEndpointsCount, pendingCount - removedEndpointsCount, specId ); if (removedEndpointsCount > 0) { analytics.userDeletedEndpoint(); } if (shouldRedirect) { history.push(documentationPageRoute.linkTo()); } }) .catch((e) => { // TODO handle error state console.error(e); }); }; const contents = !isEditing ? ( <> <Typography variant="body2" style={{ textTransform: 'none' }}> Edit </Typography> <EditIcon style={{ marginLeft: 3, height: 14 }} /> </> ) : ( <> <Typography variant="body2" style={{ textTransform: 'none' }}> {pendingCount === 0 ? 'Finish' : `Save (${pendingCount})`} </Typography> <SaveAltIcon color="secondary" style={{ marginLeft: 3, height: 14 }} /> </> ); return ( <> <ToggleButton value="check" selected={isEditing} onClick={() => { isEditing ? pendingCount > 0 ? setCommitModalOpen(true) : setEditing(false) : setEditing(true); }} size="small" className={classes.button} > {contents} </ToggleButton> {commitModalOpen && ( <CommitMessageModal onClose={() => setCommitModalOpen(false)} onSave={async (commitMessage: string) => { save(commitMessage); setCommitModalOpen(false); }} dialogText={`You have ${pendingCount} ${ pendingCount === 1 ? 'change' : 'changes' }.`} /> )} </> ); } const useStyles = makeStyles((theme) => ({ button: { height: 25, paddingRight: 5, }, scroll: { overflow: 'scroll', flex: 1, }, }));
tony-aq/optic
workspaces/spectacle/src/utilities.ts
import { v4 as uuidv4 } from 'uuid'; export interface IdGenerator<T> { nextId(): Iterable<T> } export class UuidV4Generator implements IdGenerator<string> { * nextId() { yield uuidv4() } };
tony-aq/optic
workspaces/ui-v2/src/utils/go-to-anchor.ts
export function goToAnchor(id: string) { return () => { const anchor = document.getElementById(id); if (anchor) { const parent = document.getElementById('right-pane') || window; parent.scrollTo({ top: anchor.offsetTop - 60 }); } }; }
tony-aq/optic
workspaces/ui-v2/src/store/paths/slice.ts
<filename>workspaces/ui-v2/src/store/paths/slice.ts<gh_stars>100-1000 import { createSlice, SerializedError } from '@reduxjs/toolkit'; import { AsyncStatus, IPath } from '<src>/types'; import { fetchPaths } from './thunks'; const initialState: { results: AsyncStatus<IPath[], SerializedError>; } = { results: { loading: true, }, }; const pathsSlice = createSlice({ name: 'paths', initialState, reducers: {}, extraReducers: (builder) => { builder.addCase(fetchPaths.pending, (state) => { state.results = { loading: true, }; }); builder.addCase(fetchPaths.fulfilled, (state, action) => { const results = action.payload; state.results = { loading: false, data: results, }; }); builder.addCase(fetchPaths.rejected, (state, action) => { state.results = { loading: false, error: action.error, }; }); }, }); export const actions = { fetchPaths, }; export const reducer = pathsSlice.reducer;
tony-aq/optic
workspaces/ui-v2/src/store/selectors/__tests__/testHelpers.ts
<reponame>tony-aq/optic import deepCopy from 'deepcopy'; import { RootState } from '<src>/store'; export const getMockReduxStore = (): RootState => deepCopy({ endpoints: { results: { loading: false, data: { endpoints: [ { id: 'path_UOIsxzICu5.GET', pathId: 'path_UOIsxzICu5', method: 'GET', description: '', purpose: 'get api todos', isRemoved: false, fullPath: '/api/todos', pathParameters: [ { id: 'root', name: '', isParameterized: false, description: '', endpointId: 'path_UOIsxzICu5.GET', }, { id: 'path_DuKsKy5MFb', name: 'api', isParameterized: false, description: '', endpointId: 'path_UOIsxzICu5.GET', }, { id: 'path_UOIsxzICu5', name: 'todos', isParameterized: false, description: '', endpointId: 'path_UOIsxzICu5.GET', }, ], query: null, requests: [ { requestId: 'request_gwQEFrHpO0', body: { rootShapeId: 'shape_cEkQAVQ3ib', contentType: 'application/json', }, description: '', endpointId: 'path_UOIsxzICu5.GET', pathId: 'path_UOIsxzICu5', method: 'GET', isRemoved: false, }, ], responsesByStatusCode: { '200': [ { responseId: 'response_Zv48g7lL5e', statusCode: 200, description: '', endpointId: 'path_UOIsxzICu5.GET', pathId: 'path_UOIsxzICu5', method: 'GET', isRemoved: false, body: { rootShapeId: 'shape_0xeeapZ7UZ', contentType: 'application/json', }, }, ], }, }, { id: 'path_xhUZ8irdJO.GET', pathId: 'path_xhUZ8irdJO', method: 'GET', description: 'gets all the completed todos', purpose: 'get completed items on list', isRemoved: false, fullPath: '/api/lists/{listId}/completed', pathParameters: [ { id: 'root', name: '', isParameterized: false, description: '', endpointId: 'path_xhUZ8irdJO.GET', }, { id: 'path_DuKsKy5MFb', name: 'api', isParameterized: false, description: '', endpointId: 'path_xhUZ8irdJO.GET', }, { id: 'path_F22U4m3ddD', name: 'lists', isParameterized: false, description: '', endpointId: 'path_xhUZ8irdJO.GET', }, { id: 'path_AsEexQkVwC', name: 'listId', isParameterized: true, description: '', endpointId: 'path_xhUZ8irdJO.GET', }, { id: 'path_xhUZ8irdJO', name: 'completed', isParameterized: false, description: '', endpointId: 'path_xhUZ8irdJO.GET', }, ], query: { queryParametersId: 'query_LqY12Qc9Mi', rootShapeId: 'shape_tNRgroSwLj', isRemoved: false, description: '', endpointId: 'path_xhUZ8irdJO.GET', pathId: 'path_xhUZ8irdJO', method: 'GET', }, requests: [ { requestId: 'request_SqY61Qc9Mi', body: { rootShapeId: 'shape_Lx1MrhWlFb', contentType: 'application/json', }, description: 'request body param', endpointId: 'path_xhUZ8irdJO.GET', pathId: 'path_xhUZ8irdJO', method: 'GET', isRemoved: false, }, ], responsesByStatusCode: { '200': [ { responseId: 'response_RkkvxIt2RG', statusCode: 200, description: 'response body', endpointId: 'path_xhUZ8irdJO.GET', pathId: 'path_xhUZ8irdJO', method: 'GET', isRemoved: false, body: { rootShapeId: 'shape_ToF242uYVA', contentType: 'application/json', }, }, ], }, }, { id: 'path_wPHNu8BDab.GET', pathId: 'path_wPHNu8BDab', method: 'GET', description: '', purpose: 'get profile of todo author', isRemoved: false, fullPath: '/api/todos/{todoId}/profile', pathParameters: [ { id: 'root', name: '', isParameterized: false, description: '', endpointId: 'path_wPHNu8BDab.GET', }, { id: 'path_DuKsKy5MFb', name: 'api', isParameterized: false, description: '', endpointId: 'path_wPHNu8BDab.GET', }, { id: 'path_UOIsxzICu5', name: 'todos', isParameterized: false, description: '', endpointId: 'path_wPHNu8BDab.GET', }, { id: 'path_it2OyjUysW', name: 'todoId', isParameterized: true, description: '', endpointId: 'path_wPHNu8BDab.GET', }, { id: 'path_wPHNu8BDab', name: 'profile', isParameterized: false, description: '', endpointId: 'path_wPHNu8BDab.GET', }, ], query: null, requests: [ { requestId: 'request_3kjV3YMXdP', body: { rootShapeId: 'shape_FMLvgzBZRK', contentType: 'application/json', }, description: '', endpointId: 'path_wPHNu8BDab.GET', pathId: 'path_wPHNu8BDab', method: 'GET', isRemoved: false, }, ], responsesByStatusCode: { '200': [ { responseId: 'response_dE2gzm1TWj', statusCode: 200, description: '', endpointId: 'path_wPHNu8BDab.GET', pathId: 'path_wPHNu8BDab', method: 'GET', isRemoved: false, body: { rootShapeId: 'shape_atTrTmH6j9', contentType: 'application/json', }, }, ], }, }, ], changes: {}, }, }, }, documentationEdits: { contributions: { field_LRYtHDYkVO: { description: { value: 'hello', endpointId: 'path_UOIsxzICu5.GET', }, }, field_7u9pabP6VJ: { description: { value: 'goodbye', endpointId: 'path_xhUZ8irdJO.GET', }, }, }, removedEndpoints: [], fields: { edited: {}, removed: [], }, commitModalOpen: false, isEditing: false, }, metadata: { loading: false, data: { apiName: 'todos-partial', clientAgent: 'anon_id', specificationId: 'b47d8f6e-d0e4-4814-9db6-add26b96ddd2', sessionId: 'e57695d3-9ea8-4d34-abd7-a34a746b7c02', }, }, diff: { state: { loading: true, }, }, paths: { results: { loading: true, }, }, shapes: { rootShapes: { shape_cEkQAVQ3ib: { loading: false, data: 'shape_cEkQAVQ3ib', }, shape_0xeeapZ7UZ: { loading: false, data: 'shape_0xeeapZ7UZ', }, shape_tNRgroSwLj: { loading: false, data: 'shape_tNRgroSwLj', }, }, shapeMap: { shape_tNRgroSwLj: [ { shapeId: 'shape_tNRgroSwLj', jsonType: 'Object', asObject: { fields: [ { name: 'status', fieldId: 'field_W8dnCvOHU', shapeId: 'shape_ZL8uOU2HQF', contributions: {}, changes: 'added', }, { name: 'author', fieldId: 'field_hnI7P1UdbB', shapeId: 'shape_qQT0krhOKn', contributions: {}, changes: null, }, ], }, }, ], shape_qQT0krhOKn: [ { shapeId: 'shape_qQT0krhOKn', jsonType: 'String', }, ], shape_Lx1MrhWlFb: [ { shapeId: 'shape_Lx1MrhWlFb', jsonType: 'Array', asArray: { shapeId: 'shape_QU1rtECeM2', }, }, ], shape_QU1rtECeM2: [ { shapeId: 'shape_QU1rtECeM2', jsonType: 'Object', asObject: { fields: [ { name: 'task', fieldId: 'field_KqnBpTROYU', shapeId: 'shape_9GDAmGAINi', contributions: { description: 'the task', }, changes: null, }, { name: 'isDone', fieldId: 'field_acS3yeUZo4', shapeId: 'shape_4yRQwm4WOv', contributions: {}, changes: null, }, { name: 'id', fieldId: 'field_ZJ2aPfnDF7', shapeId: 'shape_2mb389jTEL', contributions: {}, changes: null, }, { name: 'dueDate', fieldId: 'field_eHl286agXw', shapeId: 'shape_PTjiKnpFzQ', contributions: {}, changes: null, }, ], }, }, ], shape_9GDAmGAINi: [ { shapeId: 'shape_9GDAmGAINi', jsonType: 'String', }, ], shape_4yRQwm4WOv: [ { shapeId: 'shape_4yRQwm4WOv', jsonType: 'Boolean', }, ], shape_2mb389jTEL: [ { shapeId: 'shape_2mb389jTEL', jsonType: 'String', }, ], shape_PTjiKnpFzQ: [ { shapeId: 'shape_PTjiKnpFzQ', jsonType: 'String', }, ], shape_ToF242uYVA: [ { shapeId: 'shape_ToF242uYVA', jsonType: 'Array', asArray: { shapeId: 'shape_ohd8yFyzEg', }, }, ], shape_ohd8yFyzEg: [ { shapeId: 'shape_ohd8yFyzEg', jsonType: 'Object', asObject: { fields: [ { name: 'task', fieldId: 'field_7u9pabP6VJ', shapeId: 'shape_CgzMTUdLrP', contributions: {}, changes: null, }, { name: 'isDone', fieldId: 'field_WAgxB3TCIX', shapeId: 'shape_eDApTnytqu', contributions: { description: 'is the task done', }, changes: null, }, { name: 'id', fieldId: 'field_I4kC8vgaOM', shapeId: 'shape_z89HIEeyN0', contributions: {}, changes: null, }, { name: 'dueDate', fieldId: 'field_TxVlnhtLaa', shapeId: 'shape_3Xt9wp5UxL', contributions: {}, changes: null, }, ], }, }, ], shape_CgzMTUdLrP: [ { shapeId: 'shape_CgzMTUdLrP', jsonType: 'String', }, ], shape_eDApTnytqu: [ { shapeId: 'shape_eDApTnytqu', jsonType: 'Boolean', }, ], shape_z89HIEeyN0: [ { shapeId: 'shape_z89HIEeyN0', jsonType: 'String', }, ], shape_3Xt9wp5UxL: [ { shapeId: 'shape_3Xt9wp5UxL', jsonType: 'String', }, ], shape_ZL8uOU2HQF: [ { shapeId: 'shape_ZL8uOU2HQF', jsonType: 'String', }, ], shape_cEkQAVQ3ib: [ { shapeId: 'shape_cEkQAVQ3ib', jsonType: 'Array', asArray: { shapeId: 'shape_f7gQgQ8p7G', }, }, ], shape_f7gQgQ8p7G: [ { shapeId: 'shape_f7gQgQ8p7G', jsonType: 'Object', asObject: { fields: [ { name: 'task', fieldId: 'field_LRYtHDYkVO', shapeId: 'shape_tUQxsgursF', contributions: {}, changes: null, }, { name: 'isDone', fieldId: 'field_XM7KRqWOlV', shapeId: 'shape_9cUoBYpjJU', contributions: {}, changes: null, }, { name: 'id', fieldId: 'field_9mczOWgNnu', shapeId: 'shape_R4cTQ1zpOs', contributions: {}, changes: null, }, { name: 'dueDate', fieldId: 'field_5GCvc8KB2p', shapeId: 'shape_owJFnZQJeS', contributions: {}, changes: null, }, ], }, }, ], shape_tUQxsgursF: [ { shapeId: 'shape_tUQxsgursF', jsonType: 'String', }, ], shape_9cUoBYpjJU: [ { shapeId: 'shape_9cUoBYpjJU', jsonType: 'Boolean', }, ], shape_R4cTQ1zpOs: [ { shapeId: 'shape_R4cTQ1zpOs', jsonType: 'String', }, ], shape_owJFnZQJeS: [ { shapeId: 'shape_owJFnZQJeS', jsonType: 'String', }, ], shape_0xeeapZ7UZ: [ { shapeId: 'shape_0xeeapZ7UZ', jsonType: 'Array', asArray: { shapeId: 'shape_Fr2jskGj0G', }, }, ], shape_Fr2jskGj0G: [ { shapeId: 'shape_Fr2jskGj0G', jsonType: 'Object', asObject: { fields: [ { name: 'task', fieldId: 'field_NC2enngiGZ', shapeId: 'shape_iT4Fjb9iYe', contributions: {}, changes: null, }, { name: 'isDone', fieldId: 'field_PPgOBSHq9D', shapeId: 'shape_a1n10Wzc6O', contributions: {}, changes: null, }, { name: 'id', fieldId: 'field_yUzK0XALx0', shapeId: 'shape_UmsvoMDzQ8', contributions: {}, changes: null, }, { name: 'dueDate', fieldId: 'field_cOmYY7RoTV', shapeId: 'shape_FVWIcOgFGF', contributions: {}, changes: null, }, { name: 'nested', fieldId: 'field_p1mYG7RoTV', shapeId: 'shape_1g2scOgFGF', contributions: {}, changes: null, }, ], }, }, ], shape_1g2scOgFGF: [ { shapeId: 'shape_1g2scOgFGF', jsonType: 'Object', asObject: { fields: [ { name: 'inner', fieldId: 'field_y1zK0XALx0', shapeId: 'shape_UmsvoMD123', contributions: {}, changes: null, }, { name: 'polymorphic_array_with_objects', fieldId: 'field_a1zK0XALx0', shapeId: 'shape_qTsqoMD123', contributions: {}, changes: null, }, ], }, }, ], shape_Tsqo312a23: [ { shapeId: 'shape_Tsqo312a23', jsonType: 'Object', asObject: { fields: [ { name: 'ah', fieldId: 'field_qqzK0XALx0', shapeId: 'shape_amsvoMD123', contributions: {}, changes: null, }, ], }, }, ], shape_qTsqoMD123: [ { shapeId: 'shape_qTsqoMD123', jsonType: 'Array', asArray: { shapeId: 'shape_Tsqo312a23', }, }, { shapeId: 'shape_qTsqoMD123', jsonType: 'String', }, ], shape_UmsvoMD123: [ { shapeId: 'shape_UmsvoMD123', jsonType: 'String', }, ], shape_amsvoMD123: [ { shapeId: 'shape_amsvoMD123', jsonType: 'String', }, ], shape_iT4Fjb9iYe: [ { shapeId: 'shape_iT4Fjb9iYe', jsonType: 'String', }, ], shape_a1n10Wzc6O: [ { shapeId: 'shape_a1n10Wzc6O', jsonType: 'Boolean', }, ], shape_UmsvoMDzQ8: [ { shapeId: 'shape_UmsvoMDzQ8', jsonType: 'String', }, ], shape_FVWIcOgFGF: [ { shapeId: 'shape_FVWIcOgFGF', jsonType: 'String', }, ], }, fieldMap: { field_LRYtHDYkVO: { name: 'task', fieldId: 'field_LRYtHDYkVO', shapeId: 'shape_tUQxsgursF', contributions: {}, changes: null, }, field_XM7KRqWOlV: { name: 'isDone', fieldId: 'field_XM7KRqWOlV', shapeId: 'shape_9cUoBYpjJU', contributions: {}, changes: null, }, field_9mczOWgNnu: { name: 'id', fieldId: 'field_9mczOWgNnu', shapeId: 'shape_R4cTQ1zpOs', contributions: {}, changes: null, }, field_5GCvc8KB2p: { name: 'dueDate', fieldId: 'field_5GCvc8KB2p', shapeId: 'shape_owJFnZQJeS', contributions: {}, changes: null, }, field_NC2enngiGZ: { name: 'task', fieldId: 'field_NC2enngiGZ', shapeId: 'shape_iT4Fjb9iYe', contributions: {}, changes: null, }, field_PPgOBSHq9D: { name: 'isDone', fieldId: 'field_PPgOBSHq9D', shapeId: 'shape_a1n10Wzc6O', contributions: {}, changes: null, }, field_yUzK0XALx0: { name: 'id', fieldId: 'field_yUzK0XALx0', shapeId: 'shape_UmsvoMDzQ8', contributions: {}, changes: null, }, field_cOmYY7RoTV: { name: 'dueDate', fieldId: 'field_cOmYY7RoTV', shapeId: 'shape_FVWIcOgFGF', contributions: {}, changes: null, }, field_7u9pabP6VJ: { name: 'task', fieldId: 'field_7u9pabP6VJ', shapeId: 'shape_CgzMTUdLrP', contributions: {}, changes: null, }, field_WAgxB3TCIX: { name: 'isDone', fieldId: 'field_WAgxB3TCIX', shapeId: 'shape_eDApTnytqu', contributions: { description: 'is the task done', }, changes: null, }, field_I4kC8vgaOM: { name: 'id', fieldId: 'field_I4kC8vgaOM', shapeId: 'shape_z89HIEeyN0', contributions: {}, changes: null, }, field_TxVlnhtLaa: { name: 'dueDate', fieldId: 'field_TxVlnhtLaa', shapeId: 'shape_3Xt9wp5UxL', contributions: {}, changes: null, }, field_W8dnCvOHU: { name: 'status', fieldId: 'field_W8dnCvOHU', shapeId: 'shape_ZL8uOU2HQF', contributions: {}, changes: 'added', }, field_hnI7P1UdbB: { name: 'author', fieldId: 'field_hnI7P1UdbB', shapeId: 'shape_qQT0krhOKn', contributions: {}, changes: null, }, field_p1mYG7RoTV: { name: 'nested', fieldId: 'field_p1mYG7RoTV', shapeId: 'shape_1g2scOgFGF', contributions: {}, changes: null, }, field_y1zK0XALx0: { name: 'inner', fieldId: 'field_y1zK0XALx0', shapeId: 'shape_UmsvoMD123', contributions: {}, changes: null, }, }, }, } as RootState);
tony-aq/optic
workspaces/spectacle/test/apply-commands.ts
import Tap from 'tap'; import { InMemoryOpticContextBuilder } from '../src/in-memory'; import { AddPathComponent } from '@useoptic/optic-domain'; import * as opticEngine from '@useoptic/optic-engine-wasm'; import { makeSpectacle } from '../src'; Tap.test(`wasm opticEngine can generate nanoid`, async (test) => { const result = opticEngine.next_nano_id('x'); test.assert(result.startsWith('x')); }); Tap.test('spectacle applyCommands mutation', async (test) => { const opticContext = await InMemoryOpticContextBuilder.fromEvents( opticEngine, [] ); const spectacle = await makeSpectacle(opticContext); const commands = [AddPathComponent('ppp', 'root', 'ppp')]; await spectacle.queryWrapper({ query: ` mutation X($commands: [JSON!]!, $batchCommitId: ID!, $commitMessage: String!, $clientId: ID!, $clientSessionId: ID!) { applyCommands(commands: $commands, batchCommitId: $batchCommitId, commitMessage: $commitMessage, clientId: $clientId, clientSessionId: $clientSessionId) { batchCommitId } } `, variables: { commands: commands, batchCommitId: 'bbb', commitMessage: 'mmm', clientId: 'iii', clientSessionId: 'ccc', }, }); const query = `{ paths { absolutePathPattern absolutePathPatternWithParameterNames isParameterized name pathId } }`; const results = await spectacle.queryWrapper({ query, variables: {} }); test.matchSnapshot(results); });
tony-aq/optic
workspaces/optic-domain/src/streams/index.ts
<reponame>tony-aq/optic export * as Commands from './commands'; export * as DiffResults from './diff-results'; export * as HttpInteractions from './http-interactions'; export * as LearningResults from './learning-results'; export * as SpecEvents from './spec-events'; export * as UndocumentedUrls from './undocumented-urls';
tony-aq/optic
workspaces/ui-v2/src/components/sharing/ShareModal.tsx
<reponame>tony-aq/optic import React, { useCallback, useRef, useState } from 'react'; import { Button, makeStyles, TextField, Typography, CircularProgress, IconButton, Tooltip, } from '@material-ui/core'; import CopyIcon from '@material-ui/icons/FileCopy'; import { useAuth0 } from '@auth0/auth0-react'; import { useAsyncMemo } from 'use-async-memo'; import { ShareTarget } from './ShareButton'; import { useAppSelector } from '<src>/store'; import logoSvg from '<src>/constants/LogoSvg'; import { encodeQueryParams } from '<src>/utils/encodeQueryParams'; import { useAnalytics } from '<src>/contexts/analytics'; const useStyles = makeStyles((theme) => ({ root: { display: 'flex', flexDirection: 'column', marginLeft: theme.spacing(3), marginRight: theme.spacing(3), }, item: { marginBottom: theme.spacing(2), flex: 1, }, logoMarkdownContainer: { overflow: 'scroll', backgroundColor: 'rgba(27, 31, 35, 0.05)', color: 'rgb(36, 41, 46)', padding: theme.spacing(1), }, })); function generateBadgeUrl({ endpointCount }: { endpointCount: number }) { return `https://img.shields.io/static/v1?${encodeQueryParams({ label: 'API Docs', message: `${endpointCount} Endpoints`, style: 'flat', color: 'rgb(43,123,209)', logo: logoSvg, })}`; } function generateBadgeMarkdown({ endpointCount, shareUrl, }: { endpointCount: number; shareUrl: string; }) { return `[![API Docs: ${endpointCount} Endpoints](${generateBadgeUrl({ endpointCount, })})](${shareUrl})`; } export const ShareModal: React.FC<{ share: (intent: ShareTarget) => Promise<string>; }> = (props) => { const styles = useStyles(props); const analytics = useAnalytics(); const { isAuthenticated, isLoading, loginWithPopup } = useAuth0(); const endpointCount = useAppSelector( (state) => state.endpoints.results.data?.endpoints.length || 0 ); const [shareType, _setShareType] = useState<ShareTarget | null>(null); const setShareType = useCallback( (shareType: ShareTarget) => { analytics.userPickedShareTarget(shareType.toString()); _setShareType(shareType); }, [analytics] ); let inputRef = useRef<HTMLInputElement>(); const [copied, setCopied] = useState(false); const copy = useCallback(() => { const input = inputRef.current; if (input) { input.focus(); input.select(); document.execCommand('copy'); setCopied(true); setTimeout(() => setCopied(false), 7500); } }, []); // Call share when authenticated and you set a shareType const shareUrl = useAsyncMemo(async () => { if (isAuthenticated && shareType !== null) { return props.share(shareType); } }, [isAuthenticated, shareType, props.share]); if (shareType === null) { return ( <div className={styles.root}> <div className={styles.item}> <Typography variant="h5" color="textPrimary"> Share Spec With... </Typography> </div> <div className={styles.item}> <Button variant="outlined" size="large" fullWidth onClick={() => setShareType(ShareTarget.TEAM)} > Team </Button> </div> <div className={styles.item}> <Button variant="outlined" size="large" fullWidth onClick={() => setShareType(ShareTarget.CONSUMER)} > External Consumer </Button> </div> {/* <div className={styles.item}> <Button variant="outlined" size="large" fullWidth onClick={() => setShareType(ShareTarget.OTHER)} > Other </Button> </div> */} </div> ); } else if (!isAuthenticated) { return ( <div className={styles.root}> <div className={styles.item}> <Typography variant="h5" color="textPrimary"> Log in to generate an API docs link to share </Typography> </div> <div className={styles.item}> <Button variant="outlined" size="large" fullWidth disabled={isLoading} onClick={loginWithPopup} > {isLoading ? <CircularProgress size={18} /> : 'Log in'} </Button> </div> </div> ); } else { return ( <div className={styles.root}> <div className={styles.item}> <Typography variant="h5" color="textPrimary"> Share{' '} {shareType === ShareTarget.TEAM ? 'with your team' : shareType === ShareTarget.CONSUMER ? 'with your customer' : 'link'} </Typography> </div> {shareUrl ? ( <> <div className={styles.item}> <TextField fullWidth value={shareUrl} inputRef={inputRef} variant="outlined" InputProps={{ style: { fontSize: 14 }, readOnly: true, endAdornment: ( <div style={{ paddingLeft: 10, marginLeft: 4 }}> <IconButton onClick={copy} style={{ backgroundColor: 'transparent' }} > <Tooltip arrow title={copied ? 'Link copied' : 'Copy to clipboard'} > <CopyIcon /> </Tooltip> </IconButton> </div> ), }} /> </div> <div className={styles.item}> <Typography variant="h6" color="textSecondary"> Embed badge </Typography> </div> <div className={styles.item}> <a href={shareUrl}> {' '} <img alt="badge" src={generateBadgeUrl({ endpointCount })} /> </a> <div className={styles.logoMarkdownContainer}> <code style={{ display: 'block' }}> {generateBadgeMarkdown({ endpointCount, shareUrl })} </code> </div> </div> </> ) : ( <div style={{ display: 'flex', justifyContent: 'center' }}> <CircularProgress /> </div> )} </div> ); } };
tony-aq/optic
workspaces/ui-v2/src/components/PathParameters.tsx
<gh_stars>100-1000 import React, { FC, ReactNode } from 'react'; import { Divider, Typography, makeStyles } from '@material-ui/core'; import { JsonType } from '@useoptic/optic-domain'; import { FieldOrParameter } from './FieldOrParameter'; import { IPathParameter, IShapeRenderer } from '<src>/types'; export type PathParametersProps = { parameters: IPathParameter[]; renderField?: (pathParam: IPathParameter, index: number) => ReactNode; }; const defaultFieldRender = (param: IPathParameter): ReactNode => { const alwaysAString: IShapeRenderer = { shapeId: param.id + 'shape', jsonType: JsonType.STRING, }; return ( <FieldOrParameter key={param.id} name={param.name} shapes={[alwaysAString]} depth={0} value={param.description} required /> ); }; export const PathParameters: FC<PathParametersProps> = ({ parameters, renderField = defaultFieldRender, }) => { const classes = useStyles(); return ( <div className={classes.container}> <Typography className={classes.h6}>Path Parameters</Typography> {parameters.length === 0 && ( <> <Divider style={{ marginBottom: 5, backgroundColor: '#e4e8ed', }} /> <Typography className={classes.none}>No path parameters.</Typography> </> )} {parameters.map(renderField)} </div> ); }; const useStyles = makeStyles((theme) => ({ container: { paddingLeft: 10, paddingTop: 10, }, h6: { fontSize: 13, fontFamily: 'Ubuntu, Inter', fontWeight: 500, lineHeight: 1.6, marginBottom: 8, }, none: { color: '#8792a2', fontSize: 12, }, }));
tony-aq/optic
workspaces/cli-config/tests/ignore-files/IgnoreFileInterface.test.ts
<reponame>tony-aq/optic import { IgnoreFileHelper } from '../../src/helpers/ignore-file-interface'; import * as path from 'path'; import fs from 'fs-extra'; test('can parse rules from file, with Optic yml ones included', async () => { const ignoreHelper = new IgnoreFileHelper( path.join(__dirname, 'examples', 'ignore1'), path.join(__dirname, 'examples', 'optic1.yml') ); const rules = await ignoreHelper.getCurrentIgnoreRules(); console.log(rules); expect(rules).toMatchSnapshot(); }); test('can append new rule to file', async () => { const v2 = path.join(__dirname, 'examples', 'ignore2'); await fs.copyFile(path.join(__dirname, 'examples', 'ignore1'), v2); const ignoreHelper = new IgnoreFileHelper( v2, path.join(__dirname, 'examples', 'optic1.yml') ); await ignoreHelper.appendRule('POST /hello-world'); const contents = (await fs.readFile(v2)).toString(); await fs.unlink(v2); expect(contents).toMatchSnapshot(); });
tony-aq/optic
workspaces/ui-v2/src/components/QueryParametersPanel.tsx
import React, { FC } from 'react'; import { makeStyles } from '@material-ui/core'; import classnames from 'classnames'; import { FontFamily, FontFamilyMono, AddedGreenBackground, ChangedYellowBackground, RemovedRedBackground, } from '<src>/styles'; import { QueryParameters } from '<src>/types'; import { ShapeRenderer } from './ShapeRenderer'; import { Panel } from './Panel'; type QueryParametersPanelProps = { parameters: QueryParameters; }; export const QueryParametersPanel: FC<QueryParametersPanelProps> = ({ parameters, }) => { const classes = useStyles(); return ( <Panel header={<span>query string</span>}> {Object.entries(parameters).map(([key, field]) => ( <div className={classnames(classes.queryComponentContainer, [ ...[field.changes === 'added' && classes.added], ...[field.changes === 'updated' && classes.changed], ...[field.changes === 'removed' && classes.removed], ])} key={key} > <div className={classes.queryKey}> {key} {!field.required && ( <span className={classes.attribute}> (optional) </span> )} {field.additionalAttributes && field.additionalAttributes.map((attribute) => ( <span key={attribute} className={classes.attribute}> {' '} ({attribute}){' '} </span> ))} </div> <div className={classes.shapeContainer}> <ShapeRenderer showExamples={false} shapes={field.shapeChoices} /> </div> </div> ))} </Panel> ); }; const useStyles = makeStyles((theme) => ({ queryTooltipContainer: { display: 'flex', alignItems: 'center', }, queryTooltipIcon: { margin: theme.spacing(0, 1), }, queryComponentContainer: { marginBottom: theme.spacing(1), padding: theme.spacing(1), display: 'flex', '&:not(:first-child)': { borderTop: '1px solid #e4e8ed', }, }, queryKey: { fontFamily: FontFamily, fontWeight: 600, fontSize: theme.typography.fontSize - 1, }, shapeContainer: { flexGrow: 1, }, attribute: { fontSize: theme.typography.fontSize - 1, fontFamily: FontFamilyMono, fontWeight: 400, color: '#a3acb9', }, added: { backgroundColor: `${AddedGreenBackground}`, }, changed: { backgroundColor: `${ChangedYellowBackground}`, }, removed: { backgroundColor: `${RemovedRedBackground}`, }, }));
tony-aq/optic
workspaces/ui-v2/src/pages/docs/components/Contributions.tsx
import React from 'react'; import { IShapeRenderer } from '<src>/types'; import Helmet from 'react-helmet'; import { EditableTextField, TextFieldVariant, FieldOrParameter, } from '<src>/components'; import { useAppConfig } from '<src>/contexts/config/AppConfiguration'; import { useAppSelector, useAppDispatch, selectors, documentationEditActions, } from '<src>/store'; import { getEndpointId } from '<src>/utils'; export type DocsFieldOrParameterContributionProps = { shapes: IShapeRenderer[]; id: string; name: string; depth: number; initialValue: string; endpoint: { method: string; pathId: string; }; required: boolean; setSelectedField?: (selectedFieldId: string | null) => void; }; export function DocsFieldOrParameterContribution({ name, id, shapes, depth, initialValue, endpoint, required, ...props }: DocsFieldOrParameterContributionProps & React.HtmlHTMLAttributes<HTMLInputElement>) { const contributionKey = 'description'; const endpointId = getEndpointId(endpoint); const isEditable = useAppSelector( selectors.isEndpointFieldEditable({ ...endpoint, fieldId: id, }) ); const contributionValue = useAppSelector( (state) => state.documentationEdits.contributions[id]?.[contributionKey]?.value ); const value = contributionValue !== undefined ? contributionValue : initialValue; const dispatch = useAppDispatch(); return ( <FieldOrParameter {...props} name={name} shapes={shapes} depth={depth} value={value} setValue={(value) => { if (value === initialValue) { dispatch( documentationEditActions.removeContribution({ id, contributionKey, }) ); } else { dispatch( documentationEditActions.addContribution({ id, contributionKey, value, endpointId, }) ); } }} isEditing={isEditable} required={required} /> ); } type EndpointNameContributionProps = { id: string; contributionKey: string; defaultText: string; requiredError?: string; initialValue: string; endpoint: { method: string; pathId: string; }; }; export function EndpointNameContribution({ id, contributionKey, defaultText, initialValue, endpoint, }: EndpointNameContributionProps) { const endpointId = getEndpointId(endpoint); const appConfig = useAppConfig(); const isEditable = useAppSelector(selectors.isEndpointEditable(endpoint)); const contributionValue = useAppSelector( (state) => state.documentationEdits.contributions[id]?.[contributionKey]?.value ); const dispatch = useAppDispatch(); const value = contributionValue !== undefined ? contributionValue : initialValue; if (!appConfig.allowEditing) { return ( <EditableTextField isEditing={false} setEditing={() => {}} value={initialValue || 'Unnamed Endpoint'} setValue={() => {}} variant={TextFieldVariant.REGULAR} /> ); } return ( <> <Helmet> <title>{value || 'Unnamed Endpoint'}</title> </Helmet> <EditableTextField isEditing={isEditable} setEditing={(value) => dispatch( documentationEditActions.updateEditState({ isEditing: value, }) ) } value={value} setValue={(value) => { if (value === initialValue) { dispatch( documentationEditActions.removeContribution({ id, contributionKey, }) ); } else { } dispatch( documentationEditActions.addContribution({ id, contributionKey, value, endpointId, }) ); }} helperText="Help consumers by naming this endpoint" defaultText={defaultText} variant={TextFieldVariant.REGULAR} /> </> ); } export function EndpointNameMiniContribution({ id, contributionKey, defaultText, initialValue, endpoint, }: EndpointNameContributionProps) { const endpointId = getEndpointId(endpoint); const appConfig = useAppConfig(); const isEditable = useAppSelector(selectors.isEndpointEditable(endpoint)); const contributionValue = useAppSelector( (state) => state.documentationEdits.contributions[id]?.[contributionKey]?.value ); const dispatch = useAppDispatch(); const value = contributionValue !== undefined ? contributionValue : initialValue; if (!appConfig.allowEditing) { return ( <EditableTextField isEditing={false} setEditing={() => {}} value={initialValue || 'Unnamed Endpoint'} setValue={() => {}} variant={TextFieldVariant.SMALL} /> ); } return ( <EditableTextField isEditing={isEditable} setEditing={(value) => dispatch( documentationEditActions.updateEditState({ isEditing: value, }) ) } value={value} setValue={(value) => { if (value === initialValue) { dispatch( documentationEditActions.removeContribution({ id, contributionKey, }) ); } else { dispatch( documentationEditActions.addContribution({ id, contributionKey, value, endpointId, }) ); } }} defaultText={defaultText} variant={TextFieldVariant.SMALL} /> ); }
tony-aq/optic
workspaces/ui-v2/src/pages/diffs/AddEndpointsPage/index.ts
export * from './AddEndpointsPage';
tony-aq/optic
workspaces/ui-v2/src/pages/diffs/contexts/LearnedPendingEndpointContext.tsx
import React, { FC, useContext } from 'react'; import { IPendingEndpoint } from './SharedDiffState'; import { useActor } from '@xstate/react'; import equals from 'lodash.isequal'; import { ILearnedBodies } from '@useoptic/cli-shared/build/diffs/initial-types'; import { CQRSCommand } from '@useoptic/optic-domain'; import { IIgnoreBody, InitialBodiesContext } from './LearnInitialBodiesMachine'; export const LearnedPendingEndpointContext = React.createContext<ILearnedPendingEndpointContextValue | null>( null ); type ILearnedPendingEndpointContextValue = { endpoint: IPendingEndpoint; isLoading: boolean; isReady: boolean; learnedBodies?: ILearnedBodies; ignoredBodies: IIgnoreBody[]; ignoreBody: (ignoreBody: IIgnoreBody) => void; includeBody: (ignoreBody: IIgnoreBody) => void; stageEndpoint: () => void; discardEndpoint: () => void; newEndpointCommands: CQRSCommand[]; stagedCommandsIds: { pathId: string; method: string; }; endpointName: string; changeEndpointName: (name: string) => void; isIgnored: (ignore: IIgnoreBody) => boolean; }; export const ILearnedPendingEndpointStore: FC<{ endpointMachine: any; endpoint: IPendingEndpoint; onEndpointStaged: () => void; onEndpointDiscarded: () => void; }> = ({ endpoint, endpointMachine, children, onEndpointStaged, onEndpointDiscarded, }) => { const [state, send]: any = useActor(endpoint.ref); const context: InitialBodiesContext = state.context; const value: ILearnedPendingEndpointContextValue = { endpoint, isLoading: !state.matches('ready'), isReady: state.matches('ready'), learnedBodies: context.learnedBodies, ignoredBodies: context.ignoredBodies, ignoreBody: (ignoreBody: IIgnoreBody) => { send({ type: 'USER_IGNORED_BODY', ignored: ignoreBody }); }, includeBody: (ignoreBody: IIgnoreBody) => { send({ type: 'USER_INCLUDED_BODY', removeIgnore: ignoreBody }); }, isIgnored: (ignore: IIgnoreBody) => { return !Boolean(context.ignoredBodies.find((i) => equals(i, ignore))); }, stageEndpoint: onEndpointStaged, discardEndpoint: onEndpointDiscarded, newEndpointCommands: context.allCommands, stagedCommandsIds: { pathId: context.pathId, method: endpoint.method, }, endpointName: context.stagedEndpointName, changeEndpointName: (name: string) => { send({ type: 'STAGED_ENDPOINT_NAME_UPDATED', name }); }, }; return ( <LearnedPendingEndpointContext.Provider value={value}> {children} </LearnedPendingEndpointContext.Provider> ); }; export function useLearnedPendingEndpointContext(): ILearnedPendingEndpointContextValue { const value = useContext(LearnedPendingEndpointContext); if (!value) { throw new Error('Could not find LearnedPendingEndpointContext'); } return value; }
tony-aq/optic
workspaces/ui-v2/src/types/changes.ts
export type ChangeType = 'added' | 'updated' | 'removed';
tony-aq/optic
workspaces/cli-shared/src/captures/avro/saas/capture-saver.ts
<reponame>tony-aq/optic import Bottleneck from 'bottleneck'; import { developerDebugLogger, ICaptureSaver, SaasClient, } from '../../../index'; import { serdes } from '../index'; import { IHttpInteraction, IInteractionBatch } from '@useoptic/optic-domain'; export interface ISaasCaptureSaverConfig { orgId: string; agentGroupId: string; agentId: string; captureId: string; launchTokenString: string; baseUrl: string; } class CaptureSaver implements ICaptureSaver { private saasClient: SaasClient; private batcher: Bottleneck.Batcher = new Bottleneck.Batcher({ maxSize: 25, maxTime: 1000, }); private throttler: Bottleneck = new Bottleneck({ maxConcurrent: 10, minTime: 1, }); private batchCount: number = 0; private isStopping = false; constructor(private config: ISaasCaptureSaverConfig) { this.saasClient = new SaasClient(config.baseUrl, config.launchTokenString); } async init() { this.batcher.on('batch', (items: IHttpInteraction[]) => { this.batchCount++; const batchId = this.batchCount.toString(); if (this.isStopping) { developerDebugLogger(`batch ${batchId} came too late`); return; } developerDebugLogger(`scheduled batch ${batchId}`); this.throttler.schedule(() => { developerDebugLogger(`saving batch ${batchId}`); return this.saveBatch(batchId, items) .then(() => { developerDebugLogger(`saved batch ${batchId}`); }) .catch((e) => { developerDebugLogger(`error in batch ${batchId}`); developerDebugLogger(e); }); }); }); } async save(sample: IHttpInteraction) { this.batcher.add(sample); } private async saveBatch(batchId: string, items: IHttpInteraction[]) { const { agentId, agentGroupId, captureId } = this.config; const { uploadUrl } = await this.saasClient.getInteractionsUploadUrl( agentId, batchId ); const input: IInteractionBatch = { groupingIdentifiers: { agentGroupId, captureId, agentId, batchId, }, batchItems: items, }; const bytes = serdes.toBuffer(input); return this.saasClient.uploadInteractions(uploadUrl, bytes); } async cleanup() { this.isStopping = true; developerDebugLogger('waiting for saving to finish...'); try { await this.throttler.stop(); await new Promise<void>((resolve, reject) => { this.throttler.on('idle', resolve); }); } catch (e) { developerDebugLogger(e); } developerDebugLogger('done waiting for saving to finish.'); } } export { CaptureSaver };
tony-aq/optic
workspaces/ui-v2/src/lib/new-regions-interpreter.ts
<reponame>tony-aq/optic<filename>workspaces/ui-v2/src/lib/new-regions-interpreter.ts import * as Sentry from '@sentry/react'; import { CurrentSpecContext, IInterpretation, IPatchChoices, } from './Interfaces'; import { ParsedDiff, DiffLocation } from './parse-diff'; import { ILearnedBodies } from '@useoptic/cli-shared/build/diffs/initial-types'; import { DiffTypes } from '@useoptic/cli-shared/build/diffs/diffs'; import { IOpticDiffService } from '@useoptic/spectacle'; import { CQRSCommand } from '@useoptic/optic-domain'; import { code, plain } from '<src>/pages/diffs/components/ICopyRender'; import { descriptionForNewRegions } from '<src>/lib/diff-description-interpreter'; //only ever take 1 diff at a time export async function newRegionInterpreters( diff: ParsedDiff, opticDiffService: IOpticDiffService, currentSpecContext: CurrentSpecContext ): Promise<IInterpretation | undefined> { if ( diff.isA(DiffTypes.UnmatchedRequestBodyContentType) || diff.isA(DiffTypes.UnmatchedResponseBodyContentType) || diff.isA(DiffTypes.UnmatchedQueryParameters) ) { const location = diff.location(currentSpecContext); const { pathId, method } = location; const learnedBodies = await opticDiffService.learnUndocumentedBodies( pathId, method, [] ); return newContentType(diff, location, learnedBodies); } } // TODO QPB - move IInterpretation generation into ParsedDiff function newContentType( udiff: ParsedDiff, location: DiffLocation, learnedBodies: ILearnedBodies ): IInterpretation { if (udiff.isA(DiffTypes.UnmatchedRequestBodyContentType)) { const requestDescriptor = location.getRequestDescriptor(); const contentType = requestDescriptor ? requestDescriptor.contentType : ''; const learnedRequestBody = learnedBodies.requests.find( (i) => i.contentType === contentType ); if (!learnedRequestBody) { console.error( `Could not learn body for request with content type ${contentType}` ); Sentry.captureEvent({ message: 'No learned request body was found', extra: { learnedBodies, location, udiff, }, }); } const commands = learnedRequestBody ? learnedRequestBody.commands : []; return { previewTabs: [ { assertion: [], interactionPointers: udiff.interactions, invalid: true, jsonTrailsByInteractions: {}, title: `${contentType || 'No Body'} Request`, }, ], diffDescription: descriptionForNewRegions(udiff, location), updateSpecChoices: { includeNewBody: true, isNewRegionDiff: true, shapes: [], copy: [ plain('Document'), code(contentType || 'null'), plain('Request'), ], }, toCommands(choices: IPatchChoices): CQRSCommand[] { if (choices?.includeNewBody) { return commands; } else return []; }, }; } else if (udiff.isA(DiffTypes.UnmatchedResponseBodyContentType)) { const responseDescriptor = location.getResponseDescriptor(); const { contentType, statusCode } = responseDescriptor ? responseDescriptor : { contentType: '', statusCode: 0, }; //learn status code too.... currently missing const learnedResponseBody = learnedBodies.responses.find( (i) => i.contentType === contentType && i.statusCode === statusCode ); if (!learnedResponseBody) { console.error( `Could not learn body for response with status code ${statusCode} content type ${contentType}` ); Sentry.captureEvent({ message: 'No learned response body was found', extra: { learnedBodies, location, udiff, }, }); } const commands = learnedResponseBody ? learnedResponseBody.commands : []; return { previewTabs: [ { assertion: [], interactionPointers: udiff.interactions, invalid: true, jsonTrailsByInteractions: {}, title: `${statusCode} ${contentType} Response`, }, ], diffDescription: descriptionForNewRegions(udiff, location), updateSpecChoices: { includeNewBody: true, isNewRegionDiff: true, shapes: [], copy: [ plain('Document'), code(statusCode.toString()), plain('Response'), ], }, toCommands(choices: IPatchChoices): CQRSCommand[] { if (choices?.includeNewBody) { return commands; } else return []; }, }; } else if (udiff.isA(DiffTypes.UnmatchedQueryParameters)) { const commands = learnedBodies.queryParameters ? learnedBodies.queryParameters.commands : []; if (!learnedBodies.queryParameters) { console.error( `UnmatchedQueryParameters did not have a learnedBody for queryParameters` ); } return { previewTabs: [ { assertion: [], interactionPointers: udiff.interactions, invalid: true, jsonTrailsByInteractions: {}, title: 'Query Parameters', }, ], diffDescription: descriptionForNewRegions(udiff, location), updateSpecChoices: { includeNewBody: true, isNewRegionDiff: true, shapes: [], copy: [plain('Document Query Parameters')], }, toCommands(choices: IPatchChoices): CQRSCommand[] { if (choices?.includeNewBody) { return commands; } else return []; }, }; } throw new Error('new regions must match either a request or a response'); }
tony-aq/optic
workspaces/ui-v2/src/hooks/useBaseUrl.ts
<gh_stars>100-1000 import * as React from 'react'; import { useContext } from 'react'; const BaseUrlContext = React.createContext({ url: '' }); BaseUrlContext.displayName = 'BaseUrlContext'; // only expose the Provider component, but hide the Consumer in favour of hooks export const { Provider } = BaseUrlContext; export function useBaseUrl() { const context = useContext(BaseUrlContext); return context.url; }
tony-aq/optic
workspaces/ui-v2/src/pages/changelogHistory/ChangelogHistory.tsx
<gh_stars>100-1000 import React, { CSSProperties, FC, useEffect, useState } from 'react'; import { Button, makeStyles } from '@material-ui/core'; import ClassNames from 'classnames'; import Color from 'color'; import { CompareArrows as CompareArrowsIcon, Schedule as ScheduleIcon, Subject as SubjectIcon, } from '@material-ui/icons'; import { Link } from 'react-router-dom'; import { Page, useChangelogPages, useDocumentationPageLink, } from '<src>/components'; import { useAnalytics } from '<src>/contexts/analytics'; import { useAppConfig } from '<src>/contexts/config/AppConfiguration'; import { BatchCommit, useBatchCommits } from '<src>/hooks/useBatchCommits'; import { formatTimeAgo } from '<src>/utils'; import { LightBlueBackground, OpticBlueReadable, FontFamily, } from '<src>/styles'; import { ConfirmResetModal } from './components'; export const ChangelogHistory: FC = () => { const appConfig = useAppConfig(); const { loading, batchCommits } = useBatchCommits(); const changelogPage = useChangelogPages(); const documentationPage = useDocumentationPageLink(); const classes = useStyles(); const analytics = useAnalytics(); const [confirmResetModalState, setConfirmResetModalState] = useState< BatchCommit | false >(false); useEffect(() => { analytics.historyPageLoaded(); }, [analytics]); return ( <Page> <Page.Navbar /> <Page.Body padded className={classes.pageBody} loading={loading}> <section className={classes.changelogSection}> <div className={classes.changelogTimeline}> <ScheduleIcon className={classes.changelogIcon} /> </div> <ol className={classes.commitsList}> {batchCommits.map((batchCommit, i) => { const isCurrent = i === 0; return ( <li className={ClassNames(classes.commitsListItem, { [classes.isCurrent]: isCurrent, })} key={batchCommit.batchId} > <div className={classes.commitDetails}> <h4 className={classes.commitMessage}> {batchCommit.commitMessage} </h4> <span className={classes.commitTime}> {formatTimeAgo(new Date(batchCommit.createdAt))} </span> </div> <div className={classes.commitControls}> {isCurrent ? ( <Button className={classes.commitDocsButton} component={Link} to={documentationPage.linkTo()} variant="text" > <SubjectIcon className={classes.commitControlIcon} /> Docs </Button> ) : ( <Button className={classes.commitCompareButton} component={Link} variant="text" to={changelogPage.linkTo(batchCommit.batchId)} > <CompareArrowsIcon className={classes.commitControlIcon} /> Compare </Button> )} {!isCurrent && appConfig.allowEditing && ( <Button className={classes.commitResetButton} variant="outlined" onClick={() => { setConfirmResetModalState(batchCommit); }} > Reset </Button> )} </div> </li> ); })} </ol> </section> </Page.Body> {confirmResetModalState && ( <ConfirmResetModal batchCommit={confirmResetModalState} onClose={() => setConfirmResetModalState(false)} onSave={() => { const numberOfCommitsReset = batchCommits.findIndex( (batchCommit) => batchCommit.batchId === confirmResetModalState.batchId ); analytics.resetToCommit(numberOfCommitsReset); }} /> )} </Page> ); }; const useStyles = makeStyles((theme) => ({ pageBody: { display: 'flex', flexDirection: 'row', justifyContent: 'center', ...theme.mixins.gutters(), }, changelogSection: { display: 'flex', maxWidth: theme.breakpoints.values.md, marginTop: theme.spacing(4), flexGrow: 1, }, changelogTimeline: { borderLeft: `2px solid ${theme.palette.grey[200]}`, paddingRight: theme.spacing(1), flexShrink: 0, }, changelogIcon: { marginLeft: theme.spacing(-1.5) - 1, paddingBottom: theme.spacing(1), background: theme.palette.background.default, boxSizing: 'content-box', fontSize: theme.spacing(3), color: theme.palette.grey[400], }, commitsList: { // this is a reset that re-occurs alot when using semantic ul and ol. probably // worth extracting into a mixin listStyleType: 'none', paddingLeft: 0, marginTop: theme.spacing(3) + theme.spacing(1), // clock height + it's bottom spacing maxWidth: '100%', display: 'flex', flexDirection: 'column', flexGrow: 1, }, commitsListItem: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', background: '#fff', padding: theme.spacing(2), marginBottom: theme.spacing(3), borderRadius: theme.shape.borderRadius, border: `1px solid ${theme.palette.grey[200]}`, color: Color(theme.palette.text.secondary).darken(0.3).hsl().string(), '&$isCurrent': { margin: theme.spacing(0, -0.5, 3), border: `1px solid ${Color(theme.palette.primary.light) .lighten(0.7) .hex()}`, background: Color(LightBlueBackground).lighten(0.03).hex(), fontSize: theme.typography.pxToRem(theme.typography.fontSize + 3), }, }, isCurrent: {}, // state definition, so a classname is generated for it commitDetails: { display: 'flex', flexDirection: 'column', margin: 0, '& h4': {}, }, commitMessage: { margin: 0, }, commitTime: { fontSize: theme.typography.pxToRem(theme.typography.fontSize - 2), }, commitControls: { display: 'flex', flexShrink: 0, flexGrow: 0, flexDirection: 'row-reverse', marginLeft: theme.spacing(1), '& > *:nth-child(n + 2)': { // all but the first child marginRight: theme.spacing(1), }, }, commitCompareButton: { ...button(), }, commitDocsButton: { ...button(), background: '#fff', }, commitResetButton: { ...button('outlined'), }, commitControlIcon: { width: theme.spacing(2), marginRight: theme.spacing(0.5), }, })); function button(variant?: 'outlined'): CSSProperties { return { fontFamily: FontFamily, color: OpticBlueReadable, textTransform: 'none', ...(variant === 'outlined' ? { border: `1px solid ${LightBlueBackground}`, } : { background: LightBlueBackground, }), }; }
tony-aq/optic
workspaces/ui-v2/src/pages/diffs/components/DiffHeader.tsx
import React from 'react'; import { makeStyles } from '@material-ui/styles'; import { Divider, Typography } from '@material-ui/core'; import { SubtleBlueBackground } from '<src>/styles'; export type DiffHeaderProps = { name: any; children?: any; secondary?: any; }; export function DiffHeader({ name, children, secondary }: DiffHeaderProps) { const classes = useStyles(); return ( <> <div className={classes.header}> <div className={classes.topRow}> <Typography color="primary" component="div" className={classes.headerText} > {name} </Typography> <div style={{ flex: 1 }} /> <div>{children}</div> </div> {secondary && <div>{secondary}</div>} </div> <Divider /> </> ); } const useStyles = makeStyles((theme) => ({ header: { padding: 9, backgroundColor: SubtleBlueBackground, }, topRow: { display: 'flex', flexDirection: 'row', alignItems: 'center', }, headerText: { fontWeight: 600, fontSize: 12, paddingLeft: 5, fontFamily: 'Ubuntu', }, bgColor: {}, }));
tony-aq/optic
workspaces/graph-lib/src/shapes-graph/index.ts
import { GraphCommandHandler, mapAppend, NodeListWrapper } from '../shared'; import { BatchCommitData } from '../endpoints-graph'; export type NodeId = string; export enum NodeType { CoreShape = 'CoreShape', Shape = 'Shape', ShapeParameter = 'ShapeParameter', Field = 'Field', BatchCommit = 'BatchCommit', } export type Node = | CoreShapeNode | ShapeNode | ShapeParameterNode | FieldNode | BatchCommitNode; type CoreShapeNode = { id: NodeId; type: NodeType.CoreShape; data: { shapeId: string; descriptor: { kind: string; }; }; }; type ShapeNode = { id: NodeId; type: NodeType.Shape; data: { shapeId: string; }; }; type ShapeParameterNode = { id: NodeId; type: NodeType.ShapeParameter; data: { parameterId: string; }; }; type FieldNode = { id: NodeId; type: NodeType.Field; data: { fieldId: string; descriptor: { name: string; }; }; }; type BatchCommitNode = { id: NodeId; type: NodeType.BatchCommit; data: BatchCommitData; }; export type NodeWrapper = | CoreShapeNodeWrapper | ShapeNodeWrapper | ShapeParameterNodeWrapper | FieldNodeWrapper | BatchCommitNodeWrapper; // Is there a better way of infering / mapping a type to another type? type NodeTypeToNodeWrapper<T extends NodeType> = T extends NodeType.BatchCommit ? BatchCommitNodeWrapper : T extends NodeType.Shape ? ShapeNodeWrapper : T extends NodeType.ShapeParameter ? ShapeParameterNodeWrapper : T extends NodeType.CoreShape ? CoreShapeNodeWrapper : T extends NodeType.Field ? FieldNodeWrapper : NodeWrapper; export enum EdgeType { IsParameterOf = 'IsParameterOf', BelongsTo = 'BelongsTo', IsDescendantOf = 'IsDescendantOf', HasBinding = 'HasBinding', CreatedIn = 'CreatedIn', UpdatedIn = 'UpdatedIn', } export type Edge = | { type: EdgeType.BelongsTo; } | { type: EdgeType.HasBinding; data: { shapeId: string; }; } | { type: EdgeType.IsDescendantOf; } | { type: EdgeType.IsParameterOf; } | { type: EdgeType.CreatedIn; } | { type: EdgeType.UpdatedIn; }; //////////////////////////////////////////////////////////////////////////////// export class GraphIndexer implements GraphCommandHandler<Node, NodeId, Edge> { readonly nodesById: Map<NodeId, Node>; readonly nodesByType: Map<NodeType, Node[]>; readonly outboundNeighbors: Map<NodeId, Map<NodeType, Node[]>>; readonly inboundNeighbors: Map<NodeId, Map<NodeType, Node[]>>; readonly outboundNeighborsByEdgeType: Map<NodeId, Map<EdgeType, Node[]>>; readonly inboundNeighborsByEdgeType: Map<NodeId, Map<EdgeType, Node[]>>; constructor() { this.nodesByType = new Map(); this.nodesById = new Map(); this.outboundNeighbors = new Map(); this.inboundNeighbors = new Map(); this.outboundNeighborsByEdgeType = new Map(); this.inboundNeighborsByEdgeType = new Map(); } addNode(node: Node) { if (this.nodesById.has(node.id)) { throw new Error( `could not add a node with an id that already exists in the graph` ); } this.unsafeAddNode(node); } addEdge(edge: Edge, sourceNodeId: NodeId, targetNodeId: NodeId) { const sourceNode = this.nodesById.get(sourceNodeId); if (!sourceNode) { throw new Error(`expected ${sourceNodeId} to exist`); } const targetNode = this.nodesById.get(targetNodeId); if (!targetNode) { throw new Error(`expected ${targetNodeId} to exist`); } const outboundNeighbors = this.outboundNeighbors.get(sourceNodeId) || new Map(); mapAppend(outboundNeighbors, targetNode.type, targetNode); this.outboundNeighbors.set(sourceNodeId, outboundNeighbors); const outboundNeighborsByEdgeType = this.outboundNeighborsByEdgeType.get(sourceNodeId) || new Map(); mapAppend(outboundNeighborsByEdgeType, edge.type, targetNode); this.outboundNeighborsByEdgeType.set( sourceNodeId, outboundNeighborsByEdgeType ); const inboundNeighbors = this.inboundNeighbors.get(targetNodeId) || new Map(); mapAppend(inboundNeighbors, sourceNode.type, sourceNode); this.inboundNeighbors.set(targetNodeId, inboundNeighbors); const inboundNeighborsByEdgeType = this.inboundNeighborsByEdgeType.get(targetNodeId) || new Map(); mapAppend(inboundNeighborsByEdgeType, edge.type, sourceNode); this.inboundNeighborsByEdgeType.set( targetNodeId, inboundNeighborsByEdgeType ); } unsafeAddNode(node: Node) { this.nodesById.set(node.id, node); mapAppend(this.nodesByType, node.type, node); } } //////////////////////////////////////////////////////////////////////////////// export class CoreShapeNodeWrapper { constructor(public result: Node, private queries: GraphQueries) {} } export class ShapeNodeWrapper { constructor(public result: Node, private queries: GraphQueries) {} coreShape(): NodeWrapper { const coreShapeNode = this.queries.findOutgoingNeighborByEdgeType( this.result.id, EdgeType.IsDescendantOf ); if (!coreShapeNode) { throw new Error(`expected node to have a core shape node`); } return coreShapeNode; } batchCommits() { return this.queries.listOutgoingNeighborsByType( this.result.id, NodeType.BatchCommit ); } } export class ShapeParameterNodeWrapper { constructor(public result: Node, private queries: GraphQueries) {} } export class FieldNodeWrapper { constructor(public result: Node, private queries: GraphQueries) {} batchCommits() { return this.queries.listOutgoingNeighborsByType( this.result.id, NodeType.BatchCommit ); } } export class BatchCommitNodeWrapper { constructor(public result: Node, private queries: GraphQueries) {} } //////////////////////////////////////////////////////////////////////////////// export class GraphQueries { constructor(private index: GraphIndexer) {} findNodeById(id: NodeId): NodeWrapper | null { const node = this.index.nodesById.get(id); if (!node) { return null; } return this.wrap(node); } listNodesByType<T extends NodeType>( type: T ): NodeListWrapper<NodeTypeToNodeWrapper<T>> { return this.wrapList( type, this.index.nodesByType.get(type) || [] ) as NodeListWrapper<NodeTypeToNodeWrapper<T>>; } *descendantsIterator( nodeId: NodeId, seenSet: Set<NodeId> = new Set() ): Generator<Node> { const inboundNeighbors = this.index.inboundNeighbors.get(nodeId); if (!inboundNeighbors) { return; } if (seenSet.has(nodeId)) { return; } seenSet.add(nodeId); for (const neighborsByNodeType of inboundNeighbors.values()) { for (const neighborNode of neighborsByNodeType) { yield neighborNode; yield* this.descendantsIterator(neighborNode.id, seenSet); } } } //@TODO add singular find* variant listIncomingNeighborsByType(id: NodeId, incomingNeighborType: NodeType) { const neighbors = this.index.inboundNeighbors.get(id); if (!neighbors) { return this.wrapList(incomingNeighborType, []); } const neighborsOfType = neighbors.get(incomingNeighborType); return this.wrapList(incomingNeighborType, neighborsOfType || []); } //@TODO add singular find* variant listOutgoingNeighborsByType<T extends NodeType>( id: NodeId, outgoingNeighborType: T ): NodeListWrapper<NodeTypeToNodeWrapper<T>> { debugger; const neighbors = this.index.outboundNeighbors.get(id); if (!neighbors) { return this.wrapList(outgoingNeighborType, []) as NodeListWrapper< NodeTypeToNodeWrapper<T> >; } const neighborsOfType = neighbors.get(outgoingNeighborType); return this.wrapList( outgoingNeighborType, neighborsOfType || [] ) as NodeListWrapper<NodeTypeToNodeWrapper<T>>; } findOutgoingNeighborByEdgeType( id: NodeId, edgeType: EdgeType ): NodeWrapper | null { const neighbors = this.index.outboundNeighborsByEdgeType.get(id); if (!neighbors) { return null; } const neighborsOfType = neighbors.get(edgeType); if (!neighborsOfType) { return null; } return this.wrap(neighborsOfType[0]); } listIncomingNeighborsByEdgeType( id: NodeId, edgeType: EdgeType ): NodeListWrapper<NodeWrapper> { const neighbors = this.index.inboundNeighborsByEdgeType.get(id); if (!neighbors) { return this.wrapList(null, []); } const neighborsOfType = neighbors.get(edgeType); return this.wrapList(null, neighborsOfType || []); } listOutgoingNeighborsByEdgeType( id: NodeId, edgeType: EdgeType ): NodeListWrapper<NodeWrapper> { const neighbors = this.index.outboundNeighborsByEdgeType.get(id); if (!neighbors) { return this.wrapList(null, []); } const neighborsOfType = neighbors.get(edgeType); return this.wrapList(null, neighborsOfType || []); } //@TODO wrap() and wrapList() should be injected? // TODO figure out how to make this generic wrap(node: Node): NodeWrapper { if (node.type === NodeType.CoreShape) { return new CoreShapeNodeWrapper(node, this); } else if (node.type === NodeType.Shape) { return new ShapeNodeWrapper(node, this); } else if (node.type === NodeType.ShapeParameter) { return new ShapeParameterNodeWrapper(node, this); } else if (node.type === NodeType.Field) { return new FieldNodeWrapper(node, this); } else if (node.type === NodeType.BatchCommit) { return new BatchCommitNodeWrapper(node, this); } throw new Error(`unexpected node.type`); } //@TODO move away from null here // TODO figure out how to make this generic wrapList(type: NodeType | null, nodes: Node[]): NodeListWrapper<NodeWrapper> { //@TODO add list helpers (map, etc.) return { results: nodes.map((node) => this.wrap(node)), }; } }
tony-aq/optic
workspaces/cli-server/src/analytics.ts
import os from 'os'; import { newAnalyticsEventBus } from '@useoptic/analytics/lib/eventbus'; import Analytics from 'analytics-node'; import { CliClientContext, TrackingEventBase, } from '@useoptic/analytics/lib/interfaces/TrackingEventBase'; import { AnalyticsEventBus } from '@useoptic/analytics/lib/eventbus'; import { getOrCreateAnonId, getOrCreateSource, } from '@useoptic/cli-config/build/opticrc/optic-rc'; const packageJson = require('../package.json'); const clientId = `local_cli_${packageJson.version}`; const platform = os.platform(); const arch = os.arch(); const release = os.release(); //event bus for tracking events export const analyticsEvents: AnalyticsEventBus = newAnalyticsEventBus( async (batchId: string) => { const clientAgent = await getOrCreateAnonId(); const source = await getOrCreateSource(); const clientContext: CliClientContext = { clientAgent: clientAgent, clientId: clientId, platform: platform, arch: arch, release: release, clientSessionInstanceId: batchId, clientTimestamp: new Date().toISOString(), apiName: '', source, }; return clientContext; } ); export function track(events: TrackingEventBase<any>[]): void { analyticsEvents.emit(...events); } export function trackWithApiName(apiName: string) { return (events: TrackingEventBase<any>[]) => { analyticsEvents.emit( ...events.map((i) => { return { ...i, data: { ...i.data, apiName }, }; }) ); }; } const inDevelopment = process.env.OPTIC_DEVELOPMENT === 'yes'; // segment io sink const token = '<KEY>'; const analytics = new Analytics(token); // Identify user getOrCreateAnonId().then((anonymousId) => analytics.identify({ userId: anonymousId, }) ); analyticsEvents.listen(({ event, context }) => { if (inDevelopment) return; const properties = { uiVariant: 'localCli', ...context, ...event.data, }; analytics.track({ userId: context.clientAgent, event: event.type, properties, }); });
tony-aq/optic
workspaces/ui-v2/src/clients/spectacle.ts
<gh_stars>100-1000 import { CQRSCommand, JsonType } from '@useoptic/optic-domain'; import { IForkableSpectacle } from '@useoptic/spectacle'; export class SpectacleClient { constructor(private spectacle: IForkableSpectacle) {} public fetchRemoveEndpointCommands = async ( pathId: string, method: string ): Promise<CQRSCommand[]> => { type EndpointProjection = { endpoint: { commands: { remove: CQRSCommand[]; }; } | null; }; const results = await this.spectacle.query< EndpointProjection, { pathId: string; method: string; } >({ query: ` query X($pathId: ID!, $method: String!) { endpoint(pathId: $pathId, method: $method) { commands { remove } } }`, variables: { pathId, method, }, }); if (results.errors) { console.error(results.errors); throw new Error(JSON.stringify(results.errors)); } if (!results.data || !results.data.endpoint) { const message = `Could not generate removal commands for endpoint path: ${pathId} and method: ${method}`; console.error(message); throw new Error(message); } return results.data.endpoint.commands.remove; }; public fetchFieldEditCommands = async ( fieldId: string, requestedTypes: JsonType[] ): Promise<CQRSCommand[]> => { type FieldCommands = { field: { commands: { edit: CQRSCommand[]; }; } | null; }; const results = await this.spectacle.query< FieldCommands, { fieldId: string; requestedTypes: JsonType[]; } >({ query: ` query X($fieldId: ID!, $requestedTypes: [JsonType!]!) { field(fieldId: $fieldId) { commands { edit(requestedTypes: $requestedTypes) } } }`, variables: { fieldId, requestedTypes, }, }); if (results.errors) { console.error(results.errors); throw new Error(JSON.stringify(results.errors)); } if (!results.data || !results.data.field) { const message = `Could not generate edit commands for field: ${fieldId}`; console.error(message); throw new Error(message); } return results.data.field.commands.edit; }; public fetchFieldRemoveCommands = async ( fieldId: string ): Promise<CQRSCommand[]> => { type FieldCommands = { field: { commands: { remove: CQRSCommand[]; }; } | null; }; const results = await this.spectacle.query< FieldCommands, { fieldId: string; } >({ query: ` query X($fieldId: ID!) { field(fieldId: $fieldId) { commands { remove } } }`, variables: { fieldId, }, }); if (results.errors) { console.error(results.errors); throw new Error(JSON.stringify(results.errors)); } if (!results.data || !results.data.field) { const message = `Could not generate removal commands for field: ${fieldId}`; console.error(message); throw new Error(message); } return results.data.field.commands.remove; }; }
tony-aq/optic
workspaces/ui-v2/src/pages/changelog/ChangelogListPage.tsx
import React, { FC } from 'react'; import { RouteComponentProps, useHistory, useRouteMatch, } from 'react-router-dom'; import classNames from 'classnames'; import { CenteredColumn, EndpointName, PageLayout } from '<src>/components'; import { Box, List, ListItem, LinearProgress, Typography, } from '@material-ui/core'; import makeStyles from '@material-ui/styles/makeStyles'; import { useChangelogStyles } from '<src>/pages/changelog/components/ChangelogBackground'; import { selectors, useAppSelector } from '<src>/store'; import { IEndpointWithChanges } from '<src>/types'; import { getEndpointId } from '<src>/utils'; import { ChangelogPageAccessoryNavigation, ValidateBatchId, } from './components'; import { useGroupedEndpoints } from '<src>/hooks/useGroupedEndpoints'; export const ChangelogListPage: FC< RouteComponentProps<{ batchId: string; }> > = (props) => { return ( <PageLayout AccessoryNavigation={ChangelogPageAccessoryNavigation}> <ValidateBatchId batchId={props.match.params.batchId}> <ChangelogRootPage {...props} changelogBatchId={props.match.params.batchId} /> </ValidateBatchId> </PageLayout> ); }; export function ChangelogRootPage(props: { changelogBatchId: string }) { const endpointsState = useAppSelector((state) => state.endpoints.results); const endpointChanges = useAppSelector( (state) => state.endpoints.results.data?.changes || {} ); const filteredAndMappedEndpoints = selectors.filterRemovedItemForChangelog( endpointsState.data?.endpoints || [], endpointChanges, (endpoint) => getEndpointId(endpoint) ); const history = useHistory(); const match = useRouteMatch(); const groupedEndpoints = useGroupedEndpoints(filteredAndMappedEndpoints); const tocKeys = Object.keys(groupedEndpoints).sort(); const changelogStyles = useChangelogStyles(); const styles = useStyles(); if (endpointsState.loading) { return <LinearProgress variant="indeterminate" />; } if (tocKeys.length === 0) { return ( <Box display="flex" height="100%" alignItems="center" justifyContent="center" > <Typography variant="h6" style={{ fontFamily: 'Ubuntu Mono', marginBottom: '25%' }} > No endpoints have been documented yet </Typography> </Box> ); } return ( <CenteredColumn maxWidth="md" style={{ marginTop: 35 }}> <List dense> {tocKeys.map((tocKey) => { return ( <div key={tocKey}> <Typography variant="h6" style={{ fontFamily: 'Ubuntu Mono', fontWeight: 600 }} > {tocKey} </Typography> {groupedEndpoints[tocKey].map( (endpoint: IEndpointWithChanges, index: number) => { return ( <ListItem key={index} button disableRipple disableGutters style={{ display: 'flex' }} onClick={() => history.push( `${match.url}/paths/${endpoint.pathId}/methods/${endpoint.method}` ) } className={classNames({ [changelogStyles.added]: endpoint.changes === 'added', [changelogStyles.updated]: endpoint.changes === 'updated', [changelogStyles.removed]: endpoint.changes === 'removed', })} > <div style={{ flex: 1 }}> <EndpointName method={endpoint.method} fullPath={endpoint.fullPath} leftPad={6} /> </div> <div style={{ paddingRight: 15 }}> <Typography className={styles.smallField}> {endpoint.purpose || 'Unnamed Endpoint'} </Typography> </div> </ListItem> ); } )} </div> ); })} </List> </CenteredColumn> ); } const useStyles = makeStyles((theme) => ({ smallField: { fontSize: 12, fontWeight: 400, fontFamily: 'Ubuntu', pointerEvents: 'none', color: '#2a2f45', }, }));
tony-aq/optic
workspaces/api-checks/src/index.ts
<gh_stars>100-1000 export * from './runner'; export * from './spectacle'; export * as checks from './checks'; export * as reports from './reports';
tony-aq/optic
workspaces/ui-v2/src/store/documentationEdit/slice.ts
<filename>workspaces/ui-v2/src/store/documentationEdit/slice.ts /** * There's two places to edit / modify specs - documentation and diffs page, which is * why there's two slices distinct from each other (in the future if we have a single * flow for editing, we could consolidate the two slices) */ import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { saveDocumentationChanges } from './thunks'; // This needs to be exported for typescript to be able to infer typings export type DocumentationEditState = { contributions: Record< string, Record< string, { endpointId: string; value: string; } > >; fields: { edited: Record< string, { isOptional: boolean; isNullable: boolean; } >; removed: string[]; }; removedEndpoints: { pathId: string; method: string; }[]; commitModalOpen: boolean; isEditing: boolean; }; const initialState: DocumentationEditState = { contributions: {}, removedEndpoints: [], fields: { edited: {}, removed: [], }, commitModalOpen: false, isEditing: false, }; const documentationEditSlice = createSlice({ name: 'documentationEdit', initialState, reducers: { addContribution: ( state, action: PayloadAction<{ endpointId: string; id: string; contributionKey: string; value: string; }> ) => { const { id, contributionKey, value, endpointId } = action.payload; if (!state.contributions[id]) { state.contributions[id] = { [contributionKey]: { value, endpointId, }, }; } else { state.contributions[id][contributionKey] = { value, endpointId, }; } }, removeContribution: ( state, action: PayloadAction<{ id: string; contributionKey: string; }> ) => { const { id, contributionKey } = action.payload; if (state.contributions[id]?.[contributionKey]) { delete state.contributions[id][contributionKey]; } }, addFieldEdit: ( state, action: PayloadAction<{ fieldId: string; options: { isOptional: boolean; isNullable: boolean; }; }> ) => { const { fieldId, options } = action.payload; state.fields.edited[fieldId] = options; }, removeFieldEdit: ( state, action: PayloadAction<{ fieldId: string; }> ) => { const { fieldId } = action.payload; if (fieldId in state.fields.edited) { delete state.fields.edited[fieldId]; } }, removeEndpoint: ( state, action: PayloadAction<{ pathId: string; method: string; }> ) => { state.removedEndpoints.push(action.payload); }, unremoveEndpoint: ( state, action: PayloadAction<{ pathId: string; method: string; }> ) => { const { pathId, method } = action.payload; const newRemovedEndpoints = state.removedEndpoints.filter( (endpoint) => !(pathId === endpoint.pathId && method === endpoint.method) ); state.removedEndpoints = newRemovedEndpoints; }, removeField: (state, action: PayloadAction<{ fieldId: string }>) => { // @GOTCHA - selecting a field, and then selecting a parent of this field (e.g. an object that contains this removed field) // will count as a two selected fields. This is still correct, just extra commands state.fields.removed.push(action.payload.fieldId); }, unremoveField: (state, action: PayloadAction<{ fieldId: string }>) => { state.fields.removed = state.fields.removed.filter( (removedFieldId) => removedFieldId !== action.payload.fieldId ); }, updateCommitModalState: ( state, action: PayloadAction<{ commitModalOpen: boolean; }> ) => { const { commitModalOpen } = action.payload; state.commitModalOpen = commitModalOpen; }, updateEditState: ( state, action: PayloadAction<{ isEditing: boolean; }> ) => { const { isEditing } = action.payload; state.isEditing = isEditing; }, }, extraReducers: (builder) => { builder.addCase(saveDocumentationChanges.fulfilled, () => { return initialState; }); }, }); export const actions = { ...documentationEditSlice.actions, saveDocumentationChanges, }; export const reducer = documentationEditSlice.reducer;
tony-aq/optic
workspaces/local-cli/src/commands/run.ts
import { Command, flags } from '@oclif/command'; import { LocalTaskSessionWrapper, runCommandFlags, } from '../shared/local-cli-task-runner'; import { cleanupAndExit, loadPathsAndConfig } from '@useoptic/cli-shared'; import { isCommandOnlyTask } from '@useoptic/cli-config'; import Exec from './exec'; import { ingestOnlyTaskRunner } from '../shared/ingest-only-task-runner'; export default class Run extends Command { static description = 'run tasks from your optic.yml'; static flags = runCommandFlags; static args = [ { name: 'taskName', }, ]; async run() { const { args } = this.parse(Run); const { flags } = this.parse(Run); const { taskName } = args; const { config } = await loadPathsAndConfig(this); const task = config.tasks[taskName]; if (taskName && task && isCommandOnlyTask(task)) { // this is an ingest-only use case await ingestOnlyTaskRunner(this, task.command!, flags); } else { // this is a local proxy use case await LocalTaskSessionWrapper(this, taskName, flags); cleanupAndExit(); } } }
tony-aq/optic
workspaces/local-cli/src/commands/test.ts
<reponame>tony-aq/optic import { Command, flags } from '@oclif/command'; import { LocalTaskSessionWrapper, runCommandFlags, } from '../shared/local-cli-task-runner'; export default class Test extends Command { static description = 'alias for "api run test --ci"'; static flags = runCommandFlags; async run() { const { flags } = this.parse(Test); flags['ci'] = true; await LocalTaskSessionWrapper(this, 'test', flags); } }
tony-aq/optic
workspaces/ui-v2/src/components/layouts/index.ts
export * from './CenteredColumn'; export * from './FullWidth'; export * from './PageLayout'; export * from './TwoColumnFullWidth';
tony-aq/optic
workspaces/ui-v2/src/pages/diffs/AddEndpointsPage/hooks/useCheckboxState.ts
<filename>workspaces/ui-v2/src/pages/diffs/AddEndpointsPage/hooks/useCheckboxState.ts import React from 'react'; import { IUndocumentedUrl } from '<src>/pages/diffs/contexts/SharedDiffState'; export enum CheckboxState { Checked, NotChecked, Indeterminate, } export const useCheckboxState = ( visibleUrls: IUndocumentedUrl[], selectedUrls: Set<string>, setSelectedUrls: React.Dispatch<React.SetStateAction<Set<string>>> ) => { const checkboxState = visibleUrls.every((url) => selectedUrls.has(url.path + url.method) ) ? CheckboxState.Checked : visibleUrls.every((url) => !selectedUrls.has(url.path + url.method)) ? CheckboxState.NotChecked : CheckboxState.Indeterminate; const toggleSelectAllCheckbox = () => { setSelectedUrls((previousState) => { const newState = new Set(previousState); for (const { path, method } of visibleUrls) { if (checkboxState === CheckboxState.NotChecked) { newState.add(path + method); } else { newState.delete(path + method); } } return newState; }); }; return { checkboxState, toggleSelectAllCheckbox, }; };
tony-aq/optic
workspaces/ui-v2/src/styles/theme.ts
import { createMuiTheme } from '@material-ui/core'; import { JsonType } from '@useoptic/optic-domain'; export const primary = '#31366f'; export const secondary = '#ea4a61'; export const UpdatedBlue = '#2b7bd1'; export const UpdatedBlueBackground = 'rgba(43,123,209,0.11)'; export const AddedGreenBackground = 'rgba(0,196,70,0.3)'; export const ChangedYellowBackground = 'rgba(252,171,16,0.3)'; export const RemovedRedBackground = 'rgba(248,51,60,0.3)'; export const AddedGreen = '#17c8a3'; export const AddedDarkGreen = '#1b6d5c'; export const ChangedYellow = '#c8b768'; export const ChangedYellowDark = '#867b46'; export const RemovedRed = '#c86363'; export const OpticBlue = '#1B2958'; export const OpticBlueLightened = '#2a3764'; export const OpticBlueReadable = '#868da4'; export const SubtleBlueBackground = '#F5F6FA'; export const LightBlueBackground = '#edeff6'; export const SubtleGreyBackground = '#eaeaea'; export const GrayText = '#8792a2'; export const methodColors = { OPTIONS: '#686868', GET: '#52e2a3', POST: '#5aaad1', PUT: '#ee7517', PATCH: '#c8a5dc', DELETE: '#cd8d8c', }; export const methodColorsDark: { [key: string]: string | undefined } = { OPTIONS: '#686868', GET: '#276c4e', POST: '#264859', PUT: '#69340a', PATCH: '#796384', DELETE: '#be5353', }; export const jsonTypeColors: Record<JsonType, string> = { [JsonType.STRING]: '#09825d', [JsonType.NUMBER]: '#e56f4a', [JsonType.UNDEFINED]: '#857b79', [JsonType.BOOLEAN]: '#067ab8', [JsonType.NULL]: GrayText, [JsonType.OBJECT]: 'inherit', [JsonType.ARRAY]: 'inherit', }; export const FontFamily = '"Ubuntu", "Roboto", "Helvetica", "Arial", sans-serif'; export const FontFamilyMono = '"Ubuntu Mono", monospace'; export const ShapeViewerTheme = { updated: { main: UpdatedBlue, background: UpdatedBlueBackground }, changed: { main: ChangedYellow, background: ChangedYellowBackground }, added: { main: AddedGreen, background: AddedGreenBackground }, removed: { main: RemovedRed, background: RemovedRedBackground }, }; export const appTheme = createMuiTheme({ palette: { primary: { main: primary }, secondary: { main: secondary }, info: { main: '#323232', }, }, });
tony-aq/optic
workspaces/ui-v2/src/contexts/config/AppConfiguration.tsx
<reponame>tony-aq/optic import React, { ReactNode, useContext } from 'react'; import { InvariantViolationError } from '<src>/errors'; interface IAppConfigurations { allowEditing: boolean; analytics: | { enabled: false } | { enabled: true; segmentToken?: string; sentryUrl?: string; intercomAppId?: string; fullStoryOrgId?: string; }; backendApi: { domain?: string; }; sharing: | { enabled: false } | { enabled: true; specViewerDomain: string; }; } export type OpticAppConfig = { config: IAppConfigurations; }; const AppConfigurationContext = React.createContext<OpticAppConfig | null>( null ); export const AppConfigurationStore = (props: { config: OpticAppConfig; children: ReactNode; }) => { return ( <AppConfigurationContext.Provider value={props.config}> {props.children} </AppConfigurationContext.Provider> ); }; export function useAppConfig() { const value = useContext(AppConfigurationContext); if (!value) { throw new InvariantViolationError( 'useAppConfig could not find AppConfigurationContext' ); } return value.config; }
tony-aq/optic
workspaces/ui-v2/src/hooks/util/useStateWithSideEffect.ts
import { useCallback, useState } from 'react'; export const useStateWithSideEffect = <T>({ initialValue, sideEffect, }: { initialValue: T; sideEffect: (newValue: T) => void; }) => { const [value, setValue] = useState<T>(initialValue); return { value, setValue: useCallback( (value: T) => { sideEffect(value); setValue(value); }, [sideEffect] ), }; };
tony-aq/optic
workspaces/local-cli/src/shared/verbose/verbose.ts
<filename>workspaces/local-cli/src/shared/verbose/verbose.ts import { LocalCliTaskFlags } from '../local-cli-task-runner'; import colors from 'colors'; import { IOpticTaskRunnerConfig } from '@useoptic/cli-config'; import { fromOpticVerbose } from '@useoptic/cli-shared/build/conversation'; import { IHttpInteraction } from '@useoptic/optic-domain'; import waitOn from 'wait-on'; class VerboseLogger { public errors: string[] = []; public failed: boolean = false; public sampleCount: number = 0; constructor(public enabled: boolean) {} log(message: string) { if (this.enabled) { console.log(fromOpticVerbose(message)); } } sample(sample: IHttpInteraction) { this.log( `${colors.grey(`Sample ${this.sampleCount.toString()}`)} ${ sample.request.method } ${sample.request.path} ${colors.bgCyan(`➔`)} ${colors.green( sample.response.statusCode.toString() )} response` ); this.sampleCount = this.sampleCount + 1; } logError(message: string) { if (this.enabled) { this.failed = true; this.errors = [...this.errors, message]; console.log(fromOpticVerbose(`${colors.red(message)}`)); } } } export class RunTaskVerboseLogger extends VerboseLogger { constructor( public enabled: boolean, public taskName: string, public flags: LocalCliTaskFlags, public path: string ) { super(enabled); } logConfigMeaning(taskConfig: IOpticTaskRunnerConfig) { this.log( colors.bgBlue( `${colors.bold(this.taskName)} task is running. Explanation:` ) ); if (taskConfig.command) { waitOn({ resources: [`tcp:${taskConfig.serviceConfig.port}`], delay: 0, tcpTimeout: 500, timeout: 15000, }) .then((e) => { this.log( `✅ Your API just started on the port Optic assigned it using the env variable ${colors.cyan.bold( 'PORT' )} -> ${colors.cyan.bold(taskConfig.serviceConfig.port.toString())}` ); }) .catch((e) => { this.logError( `⚠️ After 15 seconds, Optic never saw your API start on the port it assigns using the ${colors.cyan.bold( 'PORT' )} variable` ); }); this.log(`Running the command "${colors.cyan.bold(taskConfig.command)}"`); this.log( `With an env variable called "${colors.cyan.bold( 'PORT' )}" set to "${colors.cyan.bold( taskConfig.serviceConfig.port.toString() )}"` ); this.log( `Expect the Optic proxy to start on "${colors.cyan.bold( 'localhost:' + taskConfig.proxyConfig.port.toString() )}" and route traffic to your API on "${colors.cyan.bold( 'localhost:' + taskConfig.serviceConfig.port.toString() )}"` ); } else { this.log( `Optic is starting a proxy on ${colors.cyan.bold( `http://localhost:${taskConfig.proxyConfig.port}` )} also on (https)` ); this.log( `The proxy forwards / intercepts traffic to ${colors.cyan.bold( `${taskConfig.serviceConfig.protocol}${taskConfig.serviceConfig.host}:${taskConfig.serviceConfig.port}` )}` ); } } portTaken(port: number) { this.logError( `⚠️ Something is already running on port ${port}. Can not start Optic Proxy there.` ); } commandExitCode(code: number) { this.log(`Command exited with code ${code}`); } results( sampleCount: any, foundDiff: boolean, ctrlC: boolean, exitCode: number | undefined ) { if (ctrlC) { this.log( `Task stopped by user CTRL-C, with ${colors.cyan( this.sampleCount.toString() )} samples in latest capture` ); } else { this.log( `Task exited with code ${exitCode}, with ${colors.cyan( this.sampleCount.toString() )} samples in latest capture` ); } if (this.failed) { this.errors.forEach((i) => this.logError(i)); } if (sampleCount === 0) { this.logError( 'No samples were captured. Make sure your task is set up properly to start your API and the Optic Proxy' ); } } } export class ExecVerboseLogger extends VerboseLogger { constructor(enabled: boolean) { super(enabled); } results(exitCode: number, ctrlC: boolean = false) { if (ctrlC) { this.log( `Task stopped by user CTRL-C, with ${colors.cyan( this.sampleCount.toString() )} samples in latest capture` ); } else { this.log( `Task exited with code ${exitCode}, with ${colors.cyan( this.sampleCount.toString() )} samples in latest capture` ); } } starting(command: string, loggingUrl: string) { this.log( `Starting a local server that receives traffic sent from your SDK/Middleware to ${colors.cyan.bold( loggingUrl )} ` ); this.log(`Running command ${colors.cyan.bold(command)}`); } }
tony-aq/optic
workspaces/ui-v2/src/components/FieldViewer.tsx
<gh_stars>100-1000 import React, { FC } from 'react'; import { makeStyles } from '@material-ui/core'; import * as Theme from '<src>/styles/theme'; import { IFieldDetails } from '<src>/types'; import { ShapeTypeSummary } from './ShapeTypeSummary'; type FieldViewerProps = { fields: IFieldDetails[]; }; export const FieldViewer: FC<FieldViewerProps> = ({ fields }) => { const classes = useStyles(); return ( <div className={classes.container}> {fields.length > 0 && ( <ul className={classes.rowsList}> {fields.map((field) => ( <li key={field.fieldId} className={classes.rowListItem}> <FieldViewerRow field={field} /> </li> ))} </ul> )} </div> ); }; const FieldViewerRow: FC<{ field: IFieldDetails; }> = ({ field }) => { const classes = useStyles(); return ( <div className={classes.fieldRowContainer} style={{ paddingLeft: INDENT_WIDTH * field.depth, }} > <div className={classes.fieldSummary}> <div className={classes.fieldName}>{field.name}</div> <div className={classes.fieldShape}> <ShapeTypeSummary shapes={field.shapes} required={field.required} /> </div> </div> {field.contribution.value !== '' && ( <div className={classes.fieldContribution}> {field.contribution.value} </div> )} </div> ); }; const INDENT_WIDTH = 8 * 3; const useStyles = makeStyles((theme) => ({ container: {}, rowsList: { listStyleType: 'none', paddingLeft: 0, }, rowListItem: {}, row: {}, fieldRowContainer: { borderTop: '1px solid #e4e8ed', padding: theme.spacing(1, 0), }, fieldSummary: { display: 'flex', alignItems: 'center', }, fieldName: { color: '#3c4257', fontFamily: Theme.FontFamily, fontWeight: theme.typography.fontWeightBold, fontSize: theme.typography.fontSize - 1, marginRight: theme.spacing(1), }, fieldShape: { fontFamily: Theme.FontFamilyMono, fontWeight: theme.typography.fontWeightLight, fontSize: theme.typography.fontSize - 2, color: Theme.GrayText, }, fieldContribution: { padding: theme.spacing(1, 0, 0, 1), }, }));
tony-aq/optic
workspaces/ui-v2/src/pages/docs/DocumentationRootPage/index.ts
<reponame>tony-aq/optic<gh_stars>100-1000 export * from './DocumentationRootPage';
tony-aq/optic
workspaces/ui-v2/src/components/ShapeRenderer/ShapePrimitive.tsx
import * as React from 'react'; import makeStyles from '@material-ui/styles/makeStyles'; import { JsonType } from '@useoptic/optic-domain'; import * as Theme from '<src>/styles/theme'; import { useSharedStyles } from './SharedStyles'; import { IShapeRenderer } from '<src>/types'; import classNames from 'classnames'; export const ShapePrimitiveRender = ({ jsonType }: IShapeRenderer) => { const classes = useStyles(); const sharedClasses = useSharedStyles(); if (jsonType === JsonType.STRING) return ( <span className={classNames(sharedClasses.valueFont, classes.stringClass)} > string </span> ); if (jsonType === JsonType.NUMBER) return ( <span className={classNames(sharedClasses.valueFont, classes.numberClass)} > number </span> ); if (jsonType === JsonType.BOOLEAN) return ( <span className={classNames(sharedClasses.valueFont, classes.booleanClass)} > boolean </span> ); if (jsonType === JsonType.NULL) return ( <span className={classNames(sharedClasses.valueFont, classes.nullClass)}> null </span> ); return null; }; export const UnknownPrimitiveRender = ({ props }: any) => { const classes = useStyles(); const sharedClasses = useSharedStyles(); return ( <span className={classNames(sharedClasses.valueFont, classes.stringClass)}> Unknown </span> ); }; const useStyles = makeStyles((theme) => ({ stringClass: { color: Theme.jsonTypeColors[JsonType.STRING], whiteSpace: 'pre-line', }, numberClass: { color: Theme.jsonTypeColors[JsonType.NUMBER], }, unknownClass: { color: Theme.jsonTypeColors[JsonType.UNDEFINED], }, booleanClass: { color: Theme.jsonTypeColors[JsonType.BOOLEAN], fontWeight: 600, }, nullClass: { color: Theme.jsonTypeColors[JsonType.NULL], }, }));
tony-aq/optic
workspaces/ui-v2/src/types/contributions.ts
<gh_stars>100-1000 export interface IContribution { id: string; contributionKey: string; value: string; endpointId: string; }
tony-aq/optic
workspaces/ui-v2/src/store/selectors/__tests__/visibilitySelectors.test.ts
<filename>workspaces/ui-v2/src/store/selectors/__tests__/visibilitySelectors.test.ts import { ChangeType } from '<src>/types'; import { isItemVisible, isItemVisibleForChangelog, filterRemovedItems, filterRemovedItemForChangelog, filterMapOfRemovedItems, filterMapOfRemovedItemsForChangelog, } from '../visibilitySelectors'; describe('visibility selectors without changelog', () => { test('isItemVisible', () => { expect(isItemVisible({ isRemoved: false })).toBe(true); expect(isItemVisible({ isRemoved: true })).toBe(false); }); test('filterRemovedItems', () => { const items = [ { id: 1, isRemoved: false, }, { id: 2, isRemoved: true }, ]; expect(filterRemovedItems(items)).toEqual([ { id: 1, isRemoved: false, }, ]); }); test('filterMapOfRemovedItems', () => { const items = { goodStuff: [ { id: 1, isRemoved: false, }, { id: 2, isRemoved: true }, ], keyShouldNotBeCopied: [{ id: 3, isRemoved: true }], }; expect(filterMapOfRemovedItems(items)).toEqual({ goodStuff: [ { id: 1, isRemoved: false, }, ], }); }); }); describe('visibility selectors with changelog', () => { const getId = <T extends { id: string }>(item: T) => item.id; const changes: Record<string, ChangeType> = { has_changes: 'added', }; test('isItemVisibleForChangelog', () => { expect( isItemVisibleForChangelog( { isRemoved: false, id: 'no_changes' }, changes, getId ) ).toBe(true); expect( isItemVisibleForChangelog( { isRemoved: false, id: 'has_changes' }, changes, getId ) ).toBe(true); expect( isItemVisibleForChangelog( { isRemoved: true, id: 'no_changes' }, changes, getId ) ).toBe(false); expect( isItemVisibleForChangelog( { isRemoved: true, id: 'has_changes' }, changes, getId ) ).toBe(true); }); test('filterRemovedItemsForChangelog', () => { const items = [ { isRemoved: true, id: 'no_changes' }, { isRemoved: true, id: 'has_changes' }, { isRemoved: false, id: '123' }, { isRemoved: false, id: '456' }, ]; expect(filterRemovedItemForChangelog(items, changes, getId)).toEqual([ { isRemoved: true, id: 'has_changes', changes: 'added' }, { isRemoved: false, id: '123', changes: null }, { isRemoved: false, id: '456', changes: null }, ]); }); test('filterMapOfRemovedItemsForChangelog', () => { const items = { goodStuff: [ { isRemoved: true, id: 'no_changes' }, { isRemoved: true, id: 'has_changes' }, { isRemoved: false, id: '123' }, { isRemoved: false, id: '456' }, ], keyShouldNotBeCopied: [{ id: 'bad_id', isRemoved: true }], }; expect(filterMapOfRemovedItemsForChangelog(items, changes, getId)).toEqual({ goodStuff: [ { isRemoved: true, id: 'has_changes', changes: 'added' }, { isRemoved: false, id: '123', changes: null }, { isRemoved: false, id: '456', changes: null }, ], }); }); });
tony-aq/optic
workspaces/ui-v2/src/pages/diffs/components/SharedStyles.tsx
<gh_stars>100-1000 import { makeStyles } from '@material-ui/core/styles'; import { primary } from '<src>/styles'; export const useShapeViewerStyles = makeStyles((theme) => ({ root: { paddingTop: 10, paddingBottom: 10, backgroundColor: '#16203F', position: 'relative', }, nested: { paddingTop: 10, marginTop: 17, paddingBottom: 10, backgroundColor: '#1c274b', }, row: { display: 'flex', padding: 0, paddingLeft: 4, flexDirection: 'row', }, rowWithHover: { cursor: 'pointer', '&:hover': { backgroundColor: 'rgba(78,165,255,0.27) !important', }, '&:hover .descriptionButton': { display: 'inherit !important', }, }, rowCompass: { width: '100%', // set at runtime to match $right position: 'fixed', display: 'flex', justifyContent: 'flex-end', paddingLeft: 8, cursor: 'pointer', animation: '$compassHover 3s ease-in-out infinite', opacity: 0, willChange: 'opacity', transition: '0.1s ease-out opacity', '&$isAbove': { top: theme.spacing(15), opacity: 1, }, '&$isBelow': { bottom: theme.spacing(4), opacity: 1, }, }, '@keyframes compassHover': { '0%': { transform: 'translateY(-2px)', }, '50%': { transform: 'translateY(2px)', }, '100%': { transform: 'translateY(-2px)', }, }, isAbove: {}, isBelow: {}, rowCompassBody: { position: 'relative', padding: theme.spacing(0.8, 1), marginRight: 8, flexShrink: 0, flexGrow: 1, borderRadius: 15, }, rowCompassDirection: { position: 'absolute', left: '50%', marginLeft: -10, width: theme.typography.pxToRem(20), height: theme.typography.pxToRem(20), flexGrow: 0, flexShrink: 0, fill: '#f8edf4', opacity: 0, }, rowCompassDirectionDown: { '$isBelow &': { bottom: -28, opacity: 1, }, }, rowCompassDirectionUp: { '$isAbove &': { top: -28, opacity: 1, }, }, fieldDescription: { flex: 1, alignItems: 'center', paddingRight: 15, display: 'flex', }, stayHighlighted: { backgroundColor: 'rgba(78,165,255,0.27) !important', }, menu: { userSelect: 'none', }, suggestion: { fontStyle: 'italic', color: 'white', flex: 1, textAlign: 'right', paddingRight: 10, }, hiddenItem: { color: '#070707', fontSize: 10, paddingLeft: 7, paddingRight: 7, backgroundColor: '#ababab', borderRadius: 12, }, symbols: { color: '#cfcfcf', fontWeight: 800, fontFamily: "'Source Code Pro', monospace", }, value: { fontWeight: 600, fontFamily: "'Source Code Pro', monospace", }, fieldName: { fontWeight: 600, color: '#cfcfcf', fontSize: 12, fontFamily: "'Source Code Pro', monospace", }, indexMarker: { fontWeight: 500, color: '#9cdcfe', fontSize: 12, fontFamily: "'Source Code Pro', monospace", }, rowContents: { display: 'flex', alignItems: 'baseline', justifyContent: 'center', flexDirection: 'row', }, left: { flexGrow: 1, flexShrink: 1, overflow: 'hidden', display: 'flex', paddingTop: 3, paddingBottom: 3, paddingLeft: 5, }, spacerBorder: { maxWidth: 1, backgroundColor: '#4B5A8C', flexGrow: 0, flexShrink: 0, }, right: { display: 'flex', paddingLeft: 5, paddingTop: 3, paddingBottom: 3, width: '35%', flexGrow: 0, flexShrink: 0, overflow: 'hidden', }, typeName: { display: 'flex', whiteSpace: 'pre', flex: 1, fontWeight: 600, fontFamily: "'Source Code Pro', monospace", }, assertionMet: { display: 'flex', flex: 1, fontWeight: 400, color: '#646464', fontStyle: 'italic', fontFamily: "'Source Code Pro', monospace", }, diffAssertion: { color: '#f8edf4', flex: 1, fontSize: 14, fontWeight: 800, fontFamily: "'Source Code Pro', monospace", }, toolbar: { alignItems: 'flex-start', paddingTop: theme.spacing(1), paddingBottom: theme.spacing(2), }, dash: { fontWeight: 500, marginLeft: -10, color: primary, }, isSticky: {}, })); export const useColor = { StringColor: '#e29f84', NumberColor: '#09885a', BooleanColor: '#E3662E', ObjectColor: '#30B1C4', ListColor: '#c47078', UnknownColor: '#ffc176', modifier: '#d5d4ff', }; export const SymbolColor = '#cfcfcf';
tony-aq/optic
workspaces/ui-v2/src/types/async.ts
<gh_stars>100-1000 export type AsyncStatus<T, E = Error> = | { loading: true; error?: undefined; data?: undefined; } | { loading: false; error: E; data?: undefined; } | { loading: false; error?: undefined; data: T };
tony-aq/optic
workspaces/ui-v2/src/lib/shape-diffs/build-inner-shape.ts
import { CurrentSpecContext, IPatchChoices } from '../Interfaces'; import { Actual } from '../shape-diff-dsl-rust'; import equals from 'lodash.isequal'; import { AddShape, AddShapeParameter, ICoreShapeInnerParameterNames, ICoreShapeKinds, ProviderInShape, SetParameterShape, ShapeProvider, } from '@useoptic/optic-domain'; export function builderInnerShapeFromChoices( choices: IPatchChoices, allowedCoreShapeKindsByShapeId: { [key: string]: ICoreShapeKinds }, actual: Actual, currentSpecContext: CurrentSpecContext ): { rootShapeId: string; commands: any[] } { const targetKinds = new Set([ ...choices.shapes.filter((i) => i.isValid).map((i) => i.coreShapeKind), ]); targetKinds.delete(ICoreShapeKinds.OptionalKind); targetKinds.delete(ICoreShapeKinds.NullableKind); const newCommands = []; const innerShapeIds = Array.from(targetKinds).map((i) => { const foundShapeId = Object.entries(allowedCoreShapeKindsByShapeId).find( ([key, shape]) => shape === i ); if (foundShapeId) { return foundShapeId[0]; } else { const filterToTarget = actual.learnedTrails.affordances.map( (affordance) => { if (equals(affordance.trail, actual.jsonTrail)) { return { ...affordance, wasString: i === ICoreShapeKinds.StringKind, wasNumber: i === ICoreShapeKinds.NumberKind, wasBoolean: i === ICoreShapeKinds.BooleanKind, wasNull: i === ICoreShapeKinds.NullableKind, wasArray: i === ICoreShapeKinds.ListKind, wasObject: i === ICoreShapeKinds.ObjectKind, fieldSet: i === ICoreShapeKinds.ObjectKind ? affordance.fieldSet : [], }; } else { return affordance; } } ); const [commands, newShapeId] = JSON.parse( currentSpecContext.opticEngine.affordances_to_commands( JSON.stringify(filterToTarget), JSON.stringify(actual.jsonTrail), currentSpecContext.idGeneratorStrategy ) ); newCommands.push(...commands); return newShapeId; } }); let rootShapeId = (() => { if (innerShapeIds.length === 1) { return innerShapeIds[0]; } else if (innerShapeIds.length === 0) { const unknownId = currentSpecContext.domainIds.newShapeId(); newCommands.push(AddShape(unknownId, ICoreShapeKinds.UnknownKind)); return unknownId; } else { const oneOfWrapperShape = currentSpecContext.domainIds.newShapeId(); newCommands.push( AddShape(oneOfWrapperShape, ICoreShapeKinds.OneOfKind.toString(), '') ); innerShapeIds.forEach((i) => { const newParamId = currentSpecContext.domainIds.newShapeParameterId(); newCommands.push( ...[ AddShapeParameter(newParamId, oneOfWrapperShape, ''), SetParameterShape( ProviderInShape(oneOfWrapperShape, ShapeProvider(i), newParamId) ), ] ); }); return oneOfWrapperShape; } })(); const shouldMakeNullable = Boolean( choices.shapes.find( (i) => i.coreShapeKind === ICoreShapeKinds.NullableKind && i.isValid ) ); if (shouldMakeNullable) { const wrapperShapeId = currentSpecContext.domainIds.newShapeId(); newCommands.push( ...[ AddShape(wrapperShapeId, ICoreShapeKinds.NullableKind.toString(), ''), SetParameterShape( ProviderInShape( wrapperShapeId, ShapeProvider(rootShapeId), ICoreShapeInnerParameterNames.NullableInner ) ), ] ); rootShapeId = wrapperShapeId; } if (choices.isField && choices.isOptional) { const wrapperShapeId = currentSpecContext.domainIds.newShapeId(); newCommands.push( ...[ AddShape(wrapperShapeId, ICoreShapeKinds.OptionalKind.toString(), ''), SetParameterShape( ProviderInShape( wrapperShapeId, ShapeProvider(rootShapeId), ICoreShapeInnerParameterNames.OptionalInner ) ), ] ); rootShapeId = wrapperShapeId; } return { rootShapeId, commands: newCommands }; }
tony-aq/optic
workspaces/local-cli/src/shared/ingest-only-task-runner.ts
import { Command } from '@oclif/command'; import { LocalCliTaskFlags } from './local-cli-task-runner'; import { cleanupAndExit, developerDebugLogger, loadPathsAndConfig, } from '@useoptic/cli-shared'; import { getSpecEventsFrom } from '@useoptic/cli-config/build/helpers/read-specification-json'; import * as uuid from 'uuid'; import { getCaptureId } from './git/git-context-capture'; import { CaptureSaverWithDiffs } from '@useoptic/cli-shared/build/captures/avro/file-system/capture-saver-with-diffs'; import { Client, SpecServiceClient } from '@useoptic/cli-client'; import { ensureDaemonStarted } from '@useoptic/cli-server'; import { lockFilePath } from './paths'; import { Config } from '../config'; import { EventEmitter } from 'events'; import { IngestTrafficService } from '@useoptic/cli-shared/build/ingest/ingest-traffic-service'; import colors from 'colors'; import { spawnProcessReturnExitCode } from './spawn-process'; import { computeCoverage, printCoverage } from './coverage'; import { ExecVerboseLogger } from './verbose/verbose'; import { IHttpInteraction } from '@useoptic/optic-domain'; export async function ingestOnlyTaskRunner( cli: Command, command: string, flags: LocalCliTaskFlags ) { const { paths, config } = await loadPathsAndConfig(cli); if (flags['ci']) { flags['print-coverage'] = true; flags['pass-exit-code'] = true; flags['collect-diffs'] = true; } const usesTaskSpecificBoundary = flags['ci'] || flags['exit-on-diff']; await getSpecEventsFrom(paths.specStorePath); const captureId = usesTaskSpecificBoundary ? uuid.v4() : await getCaptureId(paths); const daemonState = await ensureDaemonStarted( lockFilePath, Config.apiBaseUrl ); const apiBaseUrl = `http://localhost:${daemonState.port}/api`; developerDebugLogger(`api base url: ${apiBaseUrl}`); const cliClient = new Client(apiBaseUrl); //////////////////////////////////////////////////////////////////////////////// developerDebugLogger('finding matching daemon session'); const cliSession = await cliClient.findSession(paths.cwd, null, captureId); const eventEmitter = new EventEmitter(); const specServiceClient = new SpecServiceClient( cliSession.session.id, eventEmitter, apiBaseUrl ); const persistenceManager = new CaptureSaverWithDiffs( { captureBaseDirectory: paths.capturesPath, captureId, shouldCollectDiffs: true, }, config, specServiceClient ); await persistenceManager.init(); const logger = new ExecVerboseLogger(flags.verbose || false); const collectionService = new IngestTrafficService( persistenceManager, (sample: IHttpInteraction) => logger.sample(sample) ); const loggingUrl = await collectionService.start(); const env: any = { OPTIC_LOGGING_URL: loggingUrl, }; logger.starting(command, loggingUrl); console.log(`Running command: ${colors.grey(command)} `); console.log(`Traffic can be sent to: ${colors.grey(loggingUrl)} `); let exitedByUser = false; async function finish(statusCode: number, ctrlC: boolean = false) { //stop server, no new batches await collectionService.stop(); //await all pending / unsaved traffic await persistenceManager.cleanup(); // mark capture as complete await cliClient.markCaptureAsCompleted(cliSession.session.id, captureId); if (flags['print-coverage']) { const diff_maps = await computeCoverage(paths, captureId); await printCoverage(paths, diff_maps.with_diffs, diff_maps.without_diffs); } // impliment exit on diff logger.results(statusCode, ctrlC); cleanupAndExit(statusCode); } process.on('SIGINT', function () { exitedByUser = true; finish(0, exitedByUser); }); const exitCode = await spawnProcessReturnExitCode(command, env); if (!exitedByUser) { finish(exitCode, false); } }
tony-aq/optic
workspaces/ui-v2/src/contexts/SpecRepositoryContext.tsx
import React, { FC } from 'react'; import { useContext } from 'react'; import { IOpticSpecRepository } from '@useoptic/spectacle'; export function useSpecRepository() { const specRepo = useContext(SpecRepositoryContext)!; if (!specRepo) { throw new Error('Could not find spectacle context'); } return specRepo; } interface SpecRepositoryContextProps { specRepo: IOpticSpecRepository; } export const SpecRepositoryContext = React.createContext<IOpticSpecRepository | null>( null ); export const SpecRepositoryStore: FC<SpecRepositoryContextProps> = (props) => { return ( <SpecRepositoryContext.Provider value={props.specRepo}> {props.children} </SpecRepositoryContext.Provider> ); };
tony-aq/optic
workspaces/spectacle-shared/src/local-cli/client.ts
<gh_stars>100-1000 import { ICapture, IForkableSpectacle, IListDiffsResponse, IListUnrecognizedUrlsResponse, IOpticCapturesService, IOpticConfigRepository, IOpticDiffService, IOpticEngine, IOpticSpecRepository, SpectacleInput, StartDiffResult, } from '@useoptic/spectacle'; import { JsonHttpClient } from '@useoptic/client-utilities'; import { InMemoryOpticContextBuilder, InMemorySpectacle, } from '@useoptic/spectacle/build/in-memory'; import { ILearnedBodies, IAffordanceTrailsDiffHashMap, } from '@useoptic/cli-shared/build/diffs/initial-types'; import { IApiCliConfig } from '@useoptic/cli-config'; import { CQRSCommand, IHttpInteraction } from '@useoptic/optic-domain'; import { EventEmitter } from 'events'; export class LocalCliSpectacle implements IForkableSpectacle { private eventEmitter: EventEmitter; constructor(private baseUrl: string, private opticEngine: IOpticEngine) { this.eventEmitter = new EventEmitter(); } async fork(): Promise<IForkableSpectacle> { const events = await JsonHttpClient.getJson(`${this.baseUrl}/events`); const opticContext = await InMemoryOpticContextBuilder.fromEvents( this.opticEngine, events ); return new InMemorySpectacle(opticContext, []); } mutate: IForkableSpectacle['mutate'] = async (options) => { // send query to local cli-server const response = await JsonHttpClient.postJson( `${this.baseUrl}/spectacle`, options ); this.eventEmitter.emit('update'); return response; }; query: IForkableSpectacle['query'] = (options) => { // send query to local cli-server return JsonHttpClient.postJson(`${this.baseUrl}/spectacle`, options); }; registerUpdateEvent<T extends (...args: any) => any>(fn: T) { this.eventEmitter.on('update', fn); } unregisterUpdateEvent<T extends (...args: any) => any>(fn: T) { this.eventEmitter.off('update', fn); } } export interface LocalCliServices { spectacle: IForkableSpectacle; capturesService: IOpticCapturesService; opticEngine: IOpticEngine; configRepository: IOpticConfigRepository; specRepository: IOpticSpecRepository; } export interface LocalCliCapturesServiceDependencies { baseUrl: string; spectacle: IForkableSpectacle; } export interface LocalCliDiffServiceDependencies { baseUrl: string; spectacle: IForkableSpectacle; diffId: string; captureId: string; } export class LocalCliCapturesService implements IOpticCapturesService { constructor(private dependencies: LocalCliCapturesServiceDependencies) {} async listCaptures(): Promise<ICapture[]> { const response = await JsonHttpClient.getJson( `${this.dependencies.baseUrl}/captures` ); return response.captures; } async loadInteraction( captureId: string, pointer: string ): Promise<IHttpInteraction> { const response = await JsonHttpClient.getJson( `${this.dependencies.baseUrl}/captures/${captureId}/interactions/${pointer}` ); if (!response.interaction) { throw new Error( `Could not find interaction ${pointer} in capture ${captureId}` ); } return response.interaction; } async startDiff(diffId: string, captureId: string): Promise<StartDiffResult> { await this.dependencies.spectacle.query({ query: `mutation X($diffId: ID!, $captureId: ID!){ startDiff(diffId: $diffId, captureId: $captureId) { notificationsUrl } }`, variables: { diffId, captureId, }, }); // This assumes that the onComplete implementation in the cli-server has completed, and that // the fsWriteSink has completed, so that we can read the correct commands const onComplete = Promise.resolve( new LocalCliDiffService({ ...this.dependencies, diffId, captureId }) ); return { onComplete, }; } } export class LocalCliDiffService implements IOpticDiffService { constructor(private dependencies: LocalCliDiffServiceDependencies) {} async learnShapeDiffAffordances(): Promise<IAffordanceTrailsDiffHashMap> { const result = await JsonHttpClient.postJson( `${this.dependencies.baseUrl}/captures/${this.dependencies.captureId}/trail-values`, { diffId: this.dependencies.diffId, } ); //@aidan fixme return result; } async learnUndocumentedBodies( pathId: string, method: string, newPathCommands: CQRSCommand[] ): Promise<ILearnedBodies> { return JsonHttpClient.postJson( `${this.dependencies.baseUrl}/captures/${this.dependencies.captureId}/initial-bodies`, { pathId, method, additionalCommands: newPathCommands } ); } async listDiffs(): Promise<IListDiffsResponse> { const result = await this.dependencies.spectacle.query< { diff: { diffs: IListDiffsResponse; }; }, { diffId: string; } >({ query: `query X($diffId: ID!) { diff(diffId: $diffId) { diffs } }`, variables: { diffId: this.dependencies.diffId, }, }); if (result.errors || !result.data) { const errors = result.errors || 'result.data was unexpectedly falsy'; console.error(errors); throw new Error(JSON.stringify(errors)); } return result.data.diff.diffs; } async listUnrecognizedUrls(): Promise<IListUnrecognizedUrlsResponse> { const result = await this.dependencies.spectacle.query< { diff: { unrecognizedUrls: IListUnrecognizedUrlsResponse; }; }, { diffId: string; } >({ query: `query X($diffId: ID!) { diff(diffId: $diffId) { unrecognizedUrls } }`, variables: { diffId: this.dependencies.diffId, }, }); if (result.errors || !result.data) { const errors = result.errors || 'result.data was unexpectedly falsy'; console.error(errors); throw new Error(JSON.stringify(errors)); } return result.data.diff.unrecognizedUrls; } } export interface LocalCliConfigRepositoryDependencies { baseUrl: string; spectacle: IForkableSpectacle; } export class LocalCliConfigRepository implements IOpticConfigRepository { constructor(private dependencies: LocalCliConfigRepositoryDependencies) {} async addIgnoreRule(rule: string): Promise<void> { await JsonHttpClient.patchJson(`${this.dependencies.baseUrl}/ignores`, { rule, }); } async listIgnoreRules(): Promise<string[]> { throw new Error('unimplemented'); } async getApiName(): Promise<string> { const result = await JsonHttpClient.getJson( `${this.dependencies.baseUrl}/config` ); const config: IApiCliConfig = result.config; return config.name; } } export class UILocalCliSpecRepository implements IOpticSpecRepository { constructor(private dependencies: { baseUrl: string }) {} async listEvents(): Promise<any> { return JsonHttpClient.getJson(`${this.dependencies.baseUrl}/events`); } }
tony-aq/optic
workspaces/ui-v2/src/types/shapes.ts
import { JsonType } from '@useoptic/optic-domain'; import { ChangeType } from './changes'; import { IContribution } from './contributions'; // Types for rendering shapes and fields export interface IFieldRenderer { fieldId: string; name: string; shapeId: string; shapeChoices: IShapeRenderer[]; required: boolean; changes: ChangeType | null; contributions: Record<string, string>; additionalAttributes?: string[]; } // Used to render an objects field details and contributions export interface IFieldDetails { fieldId: string; name: string; contribution: IContribution; shapes: IShapeRenderer[]; depth: number; required: boolean; } // Used to render query parameters export type QueryParameters = Record<string, IFieldRenderer>; export type IShapeRenderer = | { shapeId: string; jsonType: JsonType.OBJECT; asArray?: undefined; asObject: { fields: IFieldRenderer[]; }; } | { shapeId: string; jsonType: JsonType.ARRAY; asArray: IArrayRender; asObject?: undefined; } | { shapeId: string; jsonType: Exclude<JsonType, JsonType.OBJECT | JsonType.ARRAY>; asArray?: undefined; asObject?: undefined; }; export interface IArrayRender { shapeChoices: IShapeRenderer[]; shapeId: string; }
tony-aq/optic
workspaces/ui-v2/src/clients/index.ts
<gh_stars>100-1000 export * from './spectacle';
tony-aq/optic
workspaces/ui-v2/src/pages/docs/index.ts
export * from './DocumentationPages';
tony-aq/optic
workspaces/ui-v2/src/contexts/MetadataLoader.tsx
import React, { FC, useEffect } from 'react'; import { FullPageLoader } from '<src>/components'; import { metadataActions, useAppDispatch, useAppSelector } from '<src>/store'; import { useSpectacleContext } from './spectacle-provider'; import { useConfigRepository } from './OpticConfigContext'; export const MetadataLoader: FC = ({ children }) => { const spectacle = useSpectacleContext(); const { config: configRepository } = useConfigRepository(); const dispatch = useAppDispatch(); const result = useAppSelector((state) => state.metadata); useEffect(() => { dispatch( metadataActions.fetchMetadata({ configRepository, spectacle, }) ); }, [spectacle, configRepository, dispatch]); if (result.loading) { return <FullPageLoader title="loading" />; } if (result.error) { console.error(result.error); return <>error loading app metadata</>; } return <>{children}</>; };
tony-aq/optic
workspaces/local-cli/src/commands/spectacle.ts
<filename>workspaces/local-cli/src/commands/spectacle.ts import { Command } from '@oclif/command'; import { Client } from '@useoptic/cli-client'; import { getPathsRelativeToConfig, IApiCliConfig, readApiConfig, } from '@useoptic/cli-config'; import { IPathMapping } from '@useoptic/cli-config'; import { ensureDaemonStarted } from '@useoptic/cli-server'; import { lockFilePath } from '../shared/paths'; import colors from 'colors'; import openBrowser from 'react-dev-utils/openBrowser'; import { cleanupAndExit, developerDebugLogger, fromOptic, userDebugLogger, } from '@useoptic/cli-shared'; import { Config } from '../config'; export default class Spectacle extends Command { static description = 'open GraphiQL for Spectacle'; async run() { let paths: IPathMapping; let config: IApiCliConfig; try { paths = await getPathsRelativeToConfig(); config = await readApiConfig(paths.configPath); } catch (e) { userDebugLogger(e); this.log( fromOptic( `No optic.yml file found. Add Optic to your API by running ${colors.bold( 'api init' )}` ) ); process.exit(0); } developerDebugLogger(paths); await this.helper(paths.cwd, config); } async helper(basePath: string, config: IApiCliConfig) { const daemonState = await ensureDaemonStarted( lockFilePath, Config.apiBaseUrl ); const apiBaseUrl = `http://localhost:${daemonState.port}/api`; developerDebugLogger(`api base url: ${apiBaseUrl}`); const cliClient = new Client(apiBaseUrl); const cliSession = await cliClient.findSession(basePath, null, null); developerDebugLogger({ cliSession }); const spectacleUrl = `${apiBaseUrl}/specs/${cliSession.session.id}/spectacle`; openBrowser(spectacleUrl); cleanupAndExit(); } }
tony-aq/optic
workspaces/ui-v2/src/hooks/useGroupedEndpoints.ts
<filename>workspaces/ui-v2/src/hooks/useGroupedEndpoints.ts import { useMemo } from 'react'; import groupBy from 'lodash.groupby'; import { IEndpoint } from '<src>/types'; import { findLongestCommonPath } from '<src>/utils'; export const useGroupedEndpoints = <T extends IEndpoint>(endpoints: T[]) => { return useMemo(() => { const commonStart = findLongestCommonPath( endpoints.map((endpoint) => endpoint.pathParameters.map((pathParameter) => pathParameter.name) ) ); const endpointsWithGroups = endpoints.map((endpoint) => ({ ...endpoint, // If there is only one endpoint, split['/'][1] returns undefined since // commonStart.length === endpoint.fullPath.length group: endpoint.fullPath.slice(commonStart.length).split('/')[1] || '', })); return groupBy(endpointsWithGroups, 'group'); }, [endpoints]); };
tony-aq/optic
workspaces/ui-v2/src/components/layouts/PageLayout.tsx
import React, { FC } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { TopNavigation } from '<src>/components/navigation/TopNavigation'; type PageLayoutProps = { AccessoryNavigation?: FC; }; export const PageLayout: FC<PageLayoutProps> = ({ children, AccessoryNavigation, }) => { const classes = useStyles(); return ( <div className={classes.root}> <TopNavigation AccessoryNavigation={AccessoryNavigation} /> <div className={classes.scroll}>{children}</div> </div> ); }; const useStyles = makeStyles((theme) => ({ root: { display: 'flex', flexDirection: 'column', height: '100%', }, scroll: { flex: 1, height: '100%', }, }));
tony-aq/optic
workspaces/cli-shared/src/captures/avro/file-system/capture-saver.ts
<gh_stars>100-1000 import Bottleneck from 'bottleneck'; import fs from 'fs-extra'; import path from 'path'; import avro from 'avsc'; import { developerDebugLogger, ICaptureSaver } from '../../../index'; import { captureFileSuffix } from './index'; import { schema } from '../index'; import { IInteractionBatch, IGroupingIdentifiers, IHttpInteraction, } from '@useoptic/optic-domain'; interface IFileSystemCaptureSaverConfig { captureBaseDirectory: string; captureId: string; } export class CaptureSaver implements ICaptureSaver { private batcher: Bottleneck.Batcher = new Bottleneck.Batcher({ maxSize: 20, maxTime: 500, }); private tracking: Bottleneck = new Bottleneck({ maxConcurrent: 10, minTime: 1, }); private batchCount: number = 0; private interactionsReceivedCount: number = 0; private interactionsSavedCount: number = 0; constructor(private config: IFileSystemCaptureSaverConfig) {} async init() { const { captureId } = this.config; const outputDirectory = path.join( this.config.captureBaseDirectory, captureId ); await fs.ensureDir(outputDirectory); const agentId = ''; const agentGroupId = ''; const entries = fs.readdirSync(outputDirectory); const captureFiles = entries.filter((x) => x.endsWith(captureFileSuffix)); //provide for continuation this.batchCount = captureFiles.length || 0; this.batcher.on('batch', async (items: IHttpInteraction[]) => { const batchId = this.batchCount.toString(); developerDebugLogger( `handling batch id=${batchId} (${items.length} interactions)` ); this.batchCount++; const groupingIdentifiers: IGroupingIdentifiers = { captureId, agentId, agentGroupId, batchId, }; try { const promise: Promise<void> = this.onBatch( groupingIdentifiers, batchId, items, outputDirectory ); await this.tracking.schedule(() => promise); developerDebugLogger( `handled batch id=${batchId} (${items.length} interactions)` ); this.interactionsSavedCount += items.length; } catch (e) { console.error(e); } }); } async onBatch( groupingIdentifiers: IGroupingIdentifiers, batchId: string, items: IHttpInteraction[], outputDirectory: string ) { const outputFile = path.join( outputDirectory, `${batchId}${captureFileSuffix}` ); const output: IInteractionBatch = { groupingIdentifiers, batchItems: items, }; try { const encoder = avro.createFileEncoder(outputFile, schema); await new Promise<void>((resolve, reject) => { encoder.write(output, (err) => { if (err) { return reject(err); } resolve(); }); }); await new Promise<void>((resolve, reject) => { encoder.end(() => { resolve(); }); }); } catch (e) { console.error(e); } } async save(sample: IHttpInteraction) { this.interactionsReceivedCount++; // don't await flush, just enqueue this.batcher.add(sample); } async cleanup() { developerDebugLogger('stopping capture saver'); await new Promise<void>((resolve, reject) => { const poll = () => { const interactionsReceivedCount = this.interactionsReceivedCount; const interactionsSavedCount = this.interactionsSavedCount; developerDebugLogger( 'waiting until interactionsReceivedCount matches interactionsSavedCount...', interactionsReceivedCount, interactionsSavedCount ); if (interactionsSavedCount === interactionsReceivedCount) { developerDebugLogger( 'done waiting until interactionsReceivedCount matches interactionsSavedCount', interactionsReceivedCount, interactionsSavedCount ); resolve(); } else { setTimeout(poll, 50); } }; poll(); }); await this.tracking.stop({ dropWaitingJobs: false }); developerDebugLogger('stopped capture saver'); } }
tony-aq/optic
workspaces/ui-v2/src/pages/docs/DocumentationPages.tsx
import React from 'react'; import { Redirect, Switch, Route } from 'react-router-dom'; import { useDocumentationPageLink, useEndpointPageLink, } from '<src>/components/navigation/Routes'; import { useFetchEndpoints } from '<src>/hooks/useFetchEndpoints'; import { DocumentationRootPageWithDocsNav } from './DocumentationRootPage'; import { EndpointRootPageWithDocsNav } from './EndpointRootPage'; export function DocumentationPages() { const documentationPageLink = useDocumentationPageLink(); const endpointPageLink = useEndpointPageLink(); useFetchEndpoints(); return ( <Switch> <Route exact path={endpointPageLink.path} component={EndpointRootPageWithDocsNav} /> <Route exact path={documentationPageLink.path} component={DocumentationRootPageWithDocsNav} /> <Redirect to={documentationPageLink.path} /> </Switch> ); }
tony-aq/optic
workspaces/ui-v2/src/store/selectors/endpointSelectors.ts
<filename>workspaces/ui-v2/src/store/selectors/endpointSelectors.ts import { IEndpoint, IResponse } from '<src>/types'; import { getEndpointId } from '<src>/utils'; import { RootState } from '../root'; export const getEndpoint = ({ pathId, method, }: { pathId: string; method: string; }) => (state: RootState) => { const endpointId = getEndpointId({ pathId, method }); return state.endpoints.results.data?.endpoints.find( (endpoint) => getEndpointId(endpoint) === endpointId ); }; export const getResponsesInSortedOrder = ( responses: IEndpoint['responsesByStatusCode'] ): [string, IResponse[]][] => { return Object.entries(responses).sort( ([statusCode1], [statusCode2]) => Number(statusCode1) - Number(statusCode2) ); };