repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
dogboydog/wanikani-cli
models/base-collection.ts
<reponame>dogboydog/wanikani-cli<filename>models/base-collection.ts /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface BaseCollection */ export interface BaseCollection { /** * * @type {CollectionObjectType} * @memberof BaseCollection */ object: any; /** * * @type {string} * @memberof BaseCollection */ url: any; /** * * @type {BaseCollectionPages} * @memberof BaseCollection */ pages: any; /** * * @type {number} * @memberof BaseCollection */ totalCount: any; /** * * @type {Date} * @memberof BaseCollection */ dataUpdatedAt: any; }
dogboydog/wanikani-cli
models/pronunciation-audio.ts
<filename>models/pronunciation-audio.ts<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface PronunciationAudio */ export interface PronunciationAudio { /** * The location of the audio. * @type {string} * @memberof PronunciationAudio */ url: any; /** * The content type of the audio. Currently the API delivers audio/mpeg and audio/ogg. * @type {string} * @memberof PronunciationAudio */ contentType: any; /** * * @type {PronunciationAudioMetadata} * @memberof PronunciationAudio */ metadata: any; }
dogboydog/wanikani-cli
models/subject-type.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * The type of the associated subject, one of: kanji, radical, or vocabulary. * @export * @enum {string} */ export enum SubjectType { Kanji = 'kanji', Radical = 'radical', Vocabulary = 'vocabulary' }
dogboydog/wanikani-cli
models/base-reading.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface BaseReading */ export interface BaseReading { /** * A singular subject reading. * @type {string} * @memberof BaseReading */ reading: any; /** * Indicates priority in the WaniKani system. * @type {boolean} * @memberof BaseReading */ primary: any; /** * Indicates if the reading is used to evaluate user input for correctness. * @type {boolean} * @memberof BaseReading */ acceptedAnswer: any; }
dogboydog/wanikani-cli
src/cli/imperative.ts
import * as path from "path"; // WIP Imperative version of Brightside import { IImperativeConfig } from "@zowe/imperative"; import { CommonOptions } from "./common-options"; const config: IImperativeConfig = { productDisplayName: 'WaniKani CLI', commandModuleGlobs: [ "list/list.definition!(.d).*s", ], rootCommandDescription: 'Prototype CLI for WaniKani the Japanese language learning site.', defaultHome: '~/.wanikani-cli', envVariablePrefix: 'WANIKANI_CLI', primaryTextColor: 'magenta', logging: { appLogging: { logFile: 'wanikani-cli.log' } }, profiles: [ { type: "wanikani", schema: { type: "object", title: "WaniKani Profile", description: "WaniKani Profile", properties: { token: { type: "string", optionDefinition: CommonOptions.TOKEN_OPTION, secure: true } }, required: ["token"] }, createProfileExamples: [ { options: "myprofile --host sshhost --user ibmuser --password <PASSWORD>", description: "Create a ssh profile called 'ssh111' to connect to z/OS SSH server at host 'zos123' and default port 22" } ] } ] }; module.exports = config;
dogboydog/wanikani-cli
models/base-error.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * Errors with a message will return with the follow response body structure * @export * @interface BaseError */ export interface BaseError { /** * * @type {string} * @memberof BaseError */ error: any; /** * * @type {number} * @memberof BaseError */ code: any; }
dogboydog/wanikani-cli
src/apis/level-progression-api.ts
<filename>src/apis/level-progression-api.ts /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; import { Configuration } from '../../configuration'; // Some imports not used depending on template conditions // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; import { BaseError } from '../../models'; import { LevelProgression } from '../../models'; import { LevelProgressions } from '../../models'; /** * LevelProgressionApi - axios parameter creator * @export */ export const LevelProgressionApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Retrieves a specific level progression by its id. * @summary Get a Specific Level Progression * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getLevelProgression: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling getLevelProgression.'); } const localVarPath = `/level_progressions/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Returns a collection of all level progressions, ordered by ascending created_at, 500 at a time. * @summary Get All Level Progressions * @param {Array&lt;number&gt;} [ids] Only level progressions where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only level_progressions updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getLevelProgressions: async (ids?: Array<number>, updatedAfter?: string, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/level_progressions`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required if (ids) { localVarQueryParameter['ids'] = ids; } if (updatedAfter !== undefined) { localVarQueryParameter['updated_after'] = (updatedAfter as any instanceof Date) ? (updatedAfter as any).toISOString().substr(0,10) : updatedAfter; } const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, } }; /** * LevelProgressionApi - functional programming interface * @export */ export const LevelProgressionApiFp = function(configuration?: Configuration) { return { /** * Retrieves a specific level progression by its id. * @summary Get a Specific Level Progression * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getLevelProgression(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<LevelProgression>> { const localVarAxiosArgs = await LevelProgressionApiAxiosParamCreator(configuration).getLevelProgression(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Returns a collection of all level progressions, ordered by ascending created_at, 500 at a time. * @summary Get All Level Progressions * @param {Array&lt;number&gt;} [ids] Only level progressions where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only level_progressions updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getLevelProgressions(ids?: Array<number>, updatedAfter?: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<LevelProgressions>> { const localVarAxiosArgs = await LevelProgressionApiAxiosParamCreator(configuration).getLevelProgressions(ids, updatedAfter, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * LevelProgressionApi - factory interface * @export */ export const LevelProgressionApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Retrieves a specific level progression by its id. * @summary Get a Specific Level Progression * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getLevelProgression(id: number, options?: any): AxiosPromise<LevelProgression> { return LevelProgressionApiFp(configuration).getLevelProgression(id, options).then((request) => request(axios, basePath)); }, /** * Returns a collection of all level progressions, ordered by ascending created_at, 500 at a time. * @summary Get All Level Progressions * @param {Array&lt;number&gt;} [ids] Only level progressions where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only level_progressions updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getLevelProgressions(ids?: Array<number>, updatedAfter?: string, options?: any): AxiosPromise<LevelProgressions> { return LevelProgressionApiFp(configuration).getLevelProgressions(ids, updatedAfter, options).then((request) => request(axios, basePath)); }, }; }; /** * LevelProgressionApi - object-oriented interface * @export * @class LevelProgressionApi * @extends {BaseAPI} */ export class LevelProgressionApi extends BaseAPI { /** * Retrieves a specific level progression by its id. * @summary Get a Specific Level Progression * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof LevelProgressionApi */ public getLevelProgression(id: number, options?: any) { return LevelProgressionApiFp(this.configuration).getLevelProgression(id, options).then((request) => request(this.axios, this.basePath)); } /** * Returns a collection of all level progressions, ordered by ascending created_at, 500 at a time. * @summary Get All Level Progressions * @param {Array&lt;number&gt;} [ids] Only level progressions where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only level_progressions updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof LevelProgressionApi */ public getLevelProgressions(ids?: Array<number>, updatedAfter?: string, options?: any) { return LevelProgressionApiFp(this.configuration).getLevelProgressions(ids, updatedAfter, options).then((request) => request(this.axios, this.basePath)); } }
dogboydog/wanikani-cli
models/study-material-data.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface StudyMaterialData */ export interface StudyMaterialData { /** * Timestamp when the study material was created. * @type {Date} * @memberof StudyMaterialData */ createdAt: any; /** * Indicates if the associated subject has been hidden, preventing it from appearing in lessons or reviews. * @type {boolean} * @memberof StudyMaterialData */ hidden: any; /** * Free form note related to the meaning(s) of the associated subject. * @type {string} * @memberof StudyMaterialData */ meaningNote: any | null; /** * Synonyms for the meaning of the subject. These are used as additional correct answers during reviews. * @type {Array&lt;string&gt;} * @memberof StudyMaterialData */ meaningSynonyms: any; /** * Free form note related to the reading(s) of the associated subject. * @type {string} * @memberof StudyMaterialData */ readingNote: any | null; /** * Unique identifier of the associated subject. * @type {number} * @memberof StudyMaterialData */ subjectId: any; /** * * @type {SubjectType} * @memberof StudyMaterialData */ subjectType: any; }
dogboydog/wanikani-cli
models/review.ts
<filename>models/review.ts<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseResource} from './base-resource'; /** * * @export * @interface Review */ export interface Review extends BaseResource { /** * * @type {ReviewData} * @memberof Review */ data: any; }
dogboydog/wanikani-cli
src/apis/index.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ export * from "./assignment-api"; export * from "./level-progression-api"; export * from "./reset-api"; export * from "./review-api"; export * from "./review-statistics-api"; export * from "./spaced-repetition-system-api"; export * from "./study-material-api"; export * from "./subject-api"; export * from "./summary-api"; export * from "./user-api"; export * from "./voice-actor-api";
dogboydog/wanikani-cli
models/subject.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseResource} from './base-resource'; /** * * @export * @interface Subject */ export interface Subject extends BaseResource { /** * * @type {RadicalSubject | KanjiSubject | VocabSubject} * @memberof Subject */ data: any; }
dogboydog/wanikani-cli
models/subjects.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseCollection} from './base-collection'; /** * * @export * @interface Subjects */ export interface Subjects extends BaseCollection { /** * * @type {Array&lt;Subject&gt;} * @memberof Subjects */ data: any; }
dogboydog/wanikani-cli
models/radical-subject.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {CommonSubject} from './common-subject'; /** * * @export * @interface RadicalSubject */ export interface RadicalSubject extends CommonSubject { /** * An array of numeric identifiers for the kanji that have the radical as a component. * @type {Array&lt;number&gt;} * @memberof RadicalSubject */ amalgamationSubjectIds: any; /** * Unlike kanji and vocabulary, radicals can have a null value for characters. Not all radicals have a UTF entry, so the radical must be visually represented with an image instead. * @type {string} * @memberof RadicalSubject */ characters: | null; /** * A collection of images of the radical. See table below for the object structure. * @type {Array&lt;RadicalCharacterImage&gt;} * @memberof RadicalSubject */ characterImages: any; }
dogboydog/wanikani-cli
models/meaning.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface Meaning */ export interface Meaning { /** * A singular subject meaning. * @type {string} * @memberof Meaning */ meaning: any; /** * Indicates priority in the WaniKani system. * @type {boolean} * @memberof Meaning */ primary: any; /** * Indicates if the meaning is used to evaluate user input for correctness. * @type {boolean} * @memberof Meaning */ acceptedAnswer: any; }
dogboydog/wanikani-cli
src/apis/review-statistics-api.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; import { Configuration } from '../../configuration'; // Some imports not used depending on template conditions // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; import { BaseError } from '../../models'; import { ReviewStatistic } from '../../models'; import { ReviewStatistics } from '../../models'; import { SubjectType } from '../../models'; /** * ReviewStatisticsApi - axios parameter creator * @export */ export const ReviewStatisticsApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Retrieves a specific review statistic by its id. * @summary Get a Specific Review Statistic * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReviewStatistic: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling getReviewStatistic.'); } const localVarPath = `/review_statistics/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Returns a collection of all review statistics, ordered by ascending created_at, 500 at a time. * @summary Get All Review Statistics * @param {Array&lt;number&gt;} [ids] Only reviews where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only reviews updated after this time are returned. * @param {boolean} [hidden] Return review statistics with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [subjectIds] Only reviews where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only review statistics where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {number} [percentagesGreaterThan] Return review statistics where the percentage_correct is greater than the value. * @param {number} [percentagesLessThan] Return review statistics where the percentage_correct is less than the value. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReviewStatistics: async (ids?: Array<number>, updatedAfter?: string, hidden?: boolean, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, percentagesGreaterThan?: number, percentagesLessThan?: number, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/review_statistics`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required if (ids) { localVarQueryParameter['ids'] = ids; } if (updatedAfter !== undefined) { localVarQueryParameter['updated_after'] = (updatedAfter as any instanceof Date) ? (updatedAfter as any).toISOString().substr(0,10) : updatedAfter; } if (hidden !== undefined) { localVarQueryParameter['hidden'] = hidden; } if (subjectIds) { localVarQueryParameter['subject_ids'] = subjectIds; } if (subjectTypes) { localVarQueryParameter['subject_types'] = subjectTypes; } if (percentagesGreaterThan !== undefined) { localVarQueryParameter['percentages_greater_than'] = percentagesGreaterThan; } if (percentagesLessThan !== undefined) { localVarQueryParameter['percentages_less_than'] = percentagesLessThan; } const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, } }; /** * ReviewStatisticsApi - functional programming interface * @export */ export const ReviewStatisticsApiFp = function(configuration?: Configuration) { return { /** * Retrieves a specific review statistic by its id. * @summary Get a Specific Review Statistic * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getReviewStatistic(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ReviewStatistic>> { const localVarAxiosArgs = await ReviewStatisticsApiAxiosParamCreator(configuration).getReviewStatistic(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Returns a collection of all review statistics, ordered by ascending created_at, 500 at a time. * @summary Get All Review Statistics * @param {Array&lt;number&gt;} [ids] Only reviews where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only reviews updated after this time are returned. * @param {boolean} [hidden] Return review statistics with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [subjectIds] Only reviews where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only review statistics where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {number} [percentagesGreaterThan] Return review statistics where the percentage_correct is greater than the value. * @param {number} [percentagesLessThan] Return review statistics where the percentage_correct is less than the value. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getReviewStatistics(ids?: Array<number>, updatedAfter?: string, hidden?: boolean, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, percentagesGreaterThan?: number, percentagesLessThan?: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ReviewStatistics>> { const localVarAxiosArgs = await ReviewStatisticsApiAxiosParamCreator(configuration).getReviewStatistics(ids, updatedAfter, hidden, subjectIds, subjectTypes, percentagesGreaterThan, percentagesLessThan, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * ReviewStatisticsApi - factory interface * @export */ export const ReviewStatisticsApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Retrieves a specific review statistic by its id. * @summary Get a Specific Review Statistic * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReviewStatistic(id: number, options?: any): AxiosPromise<ReviewStatistic> { return ReviewStatisticsApiFp(configuration).getReviewStatistic(id, options).then((request) => request(axios, basePath)); }, /** * Returns a collection of all review statistics, ordered by ascending created_at, 500 at a time. * @summary Get All Review Statistics * @param {Array&lt;number&gt;} [ids] Only reviews where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only reviews updated after this time are returned. * @param {boolean} [hidden] Return review statistics with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [subjectIds] Only reviews where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only review statistics where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {number} [percentagesGreaterThan] Return review statistics where the percentage_correct is greater than the value. * @param {number} [percentagesLessThan] Return review statistics where the percentage_correct is less than the value. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReviewStatistics(ids?: Array<number>, updatedAfter?: string, hidden?: boolean, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, percentagesGreaterThan?: number, percentagesLessThan?: number, options?: any): AxiosPromise<ReviewStatistics> { return ReviewStatisticsApiFp(configuration).getReviewStatistics(ids, updatedAfter, hidden, subjectIds, subjectTypes, percentagesGreaterThan, percentagesLessThan, options).then((request) => request(axios, basePath)); }, }; }; /** * ReviewStatisticsApi - object-oriented interface * @export * @class ReviewStatisticsApi * @extends {BaseAPI} */ export class ReviewStatisticsApi extends BaseAPI { /** * Retrieves a specific review statistic by its id. * @summary Get a Specific Review Statistic * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ReviewStatisticsApi */ public getReviewStatistic(id: number, options?: any) { return ReviewStatisticsApiFp(this.configuration).getReviewStatistic(id, options).then((request) => request(this.axios, this.basePath)); } /** * Returns a collection of all review statistics, ordered by ascending created_at, 500 at a time. * @summary Get All Review Statistics * @param {Array&lt;number&gt;} [ids] Only reviews where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only reviews updated after this time are returned. * @param {boolean} [hidden] Return review statistics with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [subjectIds] Only reviews where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only review statistics where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {number} [percentagesGreaterThan] Return review statistics where the percentage_correct is greater than the value. * @param {number} [percentagesLessThan] Return review statistics where the percentage_correct is less than the value. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ReviewStatisticsApi */ public getReviewStatistics(ids?: Array<number>, updatedAfter?: string, hidden?: boolean, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, percentagesGreaterThan?: number, percentagesLessThan?: number, options?: any) { return ReviewStatisticsApiFp(this.configuration).getReviewStatistics(ids, updatedAfter, hidden, subjectIds, subjectTypes, percentagesGreaterThan, percentagesLessThan, options).then((request) => request(this.axios, this.basePath)); } }
dogboydog/wanikani-cli
models/level-progression.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseResource} from './base-resource'; /** * * @export * @interface LevelProgression */ export interface LevelProgression extends BaseResource { /** * * @type {LevelProgressionData} * @memberof LevelProgression */ data: any; }
dogboydog/wanikani-cli
models/index.ts
<filename>models/index.ts export * from './assignment'; export * from './assignment-data'; export * from './assignments'; export * from './auxiliary-meaning'; export * from './base-collection'; export * from './base-collection-pages'; export * from './base-error'; export * from './base-reading'; export * from './base-resource'; export * from './collection-object-type'; export * from './common-subject'; export * from './context-sentence'; export * from './create-review'; export * from './create-review-request'; export * from './create-review-response'; export * from './create-review-response-resources-updated'; export * from './image-png-metadata'; export * from './image-svg-metadata'; export * from './kanji-reading'; export * from './kanji-subject'; export * from './level-progression'; export * from './level-progression-data'; export * from './level-progressions'; export * from './meaning'; export * from './pronunciation-audio'; export * from './pronunciation-audio-metadata'; export * from './radical-character-image'; export * from './radical-subject'; export * from './reset'; export * from './reset-data'; export * from './resets'; export * from './resource-object-type'; export * from './review'; export * from './review-data'; export * from './review-statistic'; export * from './review-statistic-data'; export * from './review-statistics'; export * from './reviews'; export * from './spaced-repetition-system'; export * from './spaced-repetition-system-data'; export * from './spaced-repetition-systems'; export * from './stage-attributes'; export * from './start-assignment-request'; export * from './study-material'; export * from './study-material-data'; export * from './study-materials'; export * from './subject'; export * from './subject-type'; export * from './subjects'; export * from './summary'; export * from './summary-data'; export * from './summary-lessons'; export * from './summary-reviews'; export * from './user'; export * from './user-data'; export * from './user-preferences'; export * from './user-subscription'; export * from './vocab-reading'; export * from './vocab-subject'; export * from './voice-actor'; export * from './voice-actor-data'; export * from './voice-actors';
dogboydog/wanikani-cli
models/vocab-reading.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface VocabReading */ export interface VocabReading { }
dogboydog/wanikani-cli
models/level-progression-data.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface LevelProgressionData */ export interface LevelProgressionData { /** * Timestamp when the user abandons the level. This is primary used when the user initiates a reset. * @type {Date} * @memberof LevelProgressionData */ abandonedAt: any | null; /** * Timestamp when the user burns 100% of the assignments belonging to the associated subject's level. * @type {Date} * @memberof LevelProgressionData */ completedAt: any | null; /** * Timestamp when the level progression is created * @type {Date} * @memberof LevelProgressionData */ createdAt: any; /** * The level of the progression, with possible values from 1 to 60. * @type {number} * @memberof LevelProgressionData */ level: any; /** * Timestamp when the user passes at least 90% of the assignments with a type of kanji belonging to the associated subject's level. * @type {Date} * @memberof LevelProgressionData */ passedAt: any | null; /** * Timestamp when the user starts their first lesson of a subject belonging to the level. * @type {Date} * @memberof LevelProgressionData */ startedAt: any | null; /** * Timestamp when the user can access lessons and reviews for the level. * @type {Date} * @memberof LevelProgressionData */ unlockedAt: any | null; }
dogboydog/wanikani-cli
models/pronunciation-audio-metadata.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * Details about the pronunciation audio. See table below for details. * @export * @interface PronunciationAudioMetadata */ export interface PronunciationAudioMetadata { /** * The gender of the voice actor. * @type {string} * @memberof PronunciationAudioMetadata */ gender: any; /** * A unique ID shared between same source pronunciation audio. * @type {number} * @memberof PronunciationAudioMetadata */ sourceId: any; /** * Vocabulary being pronounced in kana. * @type {string} * @memberof PronunciationAudioMetadata */ pronunciation: any; /** * A unique ID belonging to the voice actor. * @type {number} * @memberof PronunciationAudioMetadata */ voiceActorId: any; /** * Humanized name of the voice actor. * @type {string} * @memberof PronunciationAudioMetadata */ voiceActorName: any; /** * Description of the voice. * @type {string} * @memberof PronunciationAudioMetadata */ voiceDescription: any; }
dogboydog/wanikani-cli
models/kanji-subject.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {CommonSubject} from './common-subject'; /** * * @export * @interface KanjiSubject */ export interface KanjiSubject extends CommonSubject { /** * An array of numeric identifiers for the vocabulary that have the kanji as a component. * @type {Array&lt;number&gt;} * @memberof KanjiSubject */ amalgamationSubjectIds: any; /** * An array of numeric identifiers for the radicals that make up this kanji. Note that these are the subjects that must have passed assignments in order to unlock this subject's assignment. * @type {Array&lt;number&gt;} * @memberof KanjiSubject */ componentSubjectIds: any; /** * Meaning hint for the kanji. * @type {string} * @memberof KanjiSubject */ meaningHint: | null; /** * Reading hint for the kanji. * @type {string} * @memberof KanjiSubject */ readingHint: | null; /** * The kanji's reading mnemonic. * @type {string} * @memberof KanjiSubject */ readingMnemonic: any; /** * Selected readings for the kanji. See table below for the object structure. * @type {Array&lt;KanjiReading&gt;} * @memberof KanjiSubject */ readings: any; /** * An array of numeric identifiers for kanji which are visually similar to the kanji in question. * @type {Array&lt;number&gt;} * @memberof KanjiSubject */ visuallySimilarSubjectIds: any; }
dogboydog/wanikani-cli
src/apis/spaced-repetition-system-api.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; import { Configuration } from '../../configuration'; // Some imports not used depending on template conditions // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; import { BaseError } from '../../models'; import { SpacedRepetitionSystem } from '../../models'; import { SpacedRepetitionSystems } from '../../models'; import { SubjectType } from '../../models'; /** * SpacedRepetitionSystemApi - axios parameter creator * @export */ export const SpacedRepetitionSystemApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Retrieves a specific spaced repetition system by its id. * @summary Get a Specific Spaced Repetition System * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getSpacedRepetitionSystem: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling getSpacedRepetitionSystem.'); } const localVarPath = `/spaced_repetition_systems/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Returns a collection of all spaced repetition systems, ordered by ascending created_at, 500 at a time. * @summary Get All Spaced Repetition Systems * @param {boolean} [hidden] Return study materials with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [ids] Only study material records where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only study material records updated after this time are returned. * @param {Array&lt;number&gt;} [subjectIds] Only study material records where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only study material records where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getSpacedRepetitionSystems: async (hidden?: boolean, ids?: Array<number>, updatedAfter?: string, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/spaced_repetition_systems`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required if (hidden !== undefined) { localVarQueryParameter['hidden'] = hidden; } if (ids) { localVarQueryParameter['ids'] = ids; } if (updatedAfter !== undefined) { localVarQueryParameter['updated_after'] = (updatedAfter as any instanceof Date) ? (updatedAfter as any).toISOString().substr(0,10) : updatedAfter; } if (subjectIds) { localVarQueryParameter['subject_ids'] = subjectIds; } if (subjectTypes) { localVarQueryParameter['subject_types'] = subjectTypes; } const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, } }; /** * SpacedRepetitionSystemApi - functional programming interface * @export */ export const SpacedRepetitionSystemApiFp = function(configuration?: Configuration) { return { /** * Retrieves a specific spaced repetition system by its id. * @summary Get a Specific Spaced Repetition System * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getSpacedRepetitionSystem(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<SpacedRepetitionSystem>> { const localVarAxiosArgs = await SpacedRepetitionSystemApiAxiosParamCreator(configuration).getSpacedRepetitionSystem(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Returns a collection of all spaced repetition systems, ordered by ascending created_at, 500 at a time. * @summary Get All Spaced Repetition Systems * @param {boolean} [hidden] Return study materials with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [ids] Only study material records where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only study material records updated after this time are returned. * @param {Array&lt;number&gt;} [subjectIds] Only study material records where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only study material records where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getSpacedRepetitionSystems(hidden?: boolean, ids?: Array<number>, updatedAfter?: string, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<SpacedRepetitionSystems>> { const localVarAxiosArgs = await SpacedRepetitionSystemApiAxiosParamCreator(configuration).getSpacedRepetitionSystems(hidden, ids, updatedAfter, subjectIds, subjectTypes, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * SpacedRepetitionSystemApi - factory interface * @export */ export const SpacedRepetitionSystemApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Retrieves a specific spaced repetition system by its id. * @summary Get a Specific Spaced Repetition System * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getSpacedRepetitionSystem(id: number, options?: any): AxiosPromise<SpacedRepetitionSystem> { return SpacedRepetitionSystemApiFp(configuration).getSpacedRepetitionSystem(id, options).then((request) => request(axios, basePath)); }, /** * Returns a collection of all spaced repetition systems, ordered by ascending created_at, 500 at a time. * @summary Get All Spaced Repetition Systems * @param {boolean} [hidden] Return study materials with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [ids] Only study material records where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only study material records updated after this time are returned. * @param {Array&lt;number&gt;} [subjectIds] Only study material records where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only study material records where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getSpacedRepetitionSystems(hidden?: boolean, ids?: Array<number>, updatedAfter?: string, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, options?: any): AxiosPromise<SpacedRepetitionSystems> { return SpacedRepetitionSystemApiFp(configuration).getSpacedRepetitionSystems(hidden, ids, updatedAfter, subjectIds, subjectTypes, options).then((request) => request(axios, basePath)); }, }; }; /** * SpacedRepetitionSystemApi - object-oriented interface * @export * @class SpacedRepetitionSystemApi * @extends {BaseAPI} */ export class SpacedRepetitionSystemApi extends BaseAPI { /** * Retrieves a specific spaced repetition system by its id. * @summary Get a Specific Spaced Repetition System * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SpacedRepetitionSystemApi */ public getSpacedRepetitionSystem(id: number, options?: any) { return SpacedRepetitionSystemApiFp(this.configuration).getSpacedRepetitionSystem(id, options).then((request) => request(this.axios, this.basePath)); } /** * Returns a collection of all spaced repetition systems, ordered by ascending created_at, 500 at a time. * @summary Get All Spaced Repetition Systems * @param {boolean} [hidden] Return study materials with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [ids] Only study material records where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only study material records updated after this time are returned. * @param {Array&lt;number&gt;} [subjectIds] Only study material records where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only study material records where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SpacedRepetitionSystemApi */ public getSpacedRepetitionSystems(hidden?: boolean, ids?: Array<number>, updatedAfter?: string, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, options?: any) { return SpacedRepetitionSystemApiFp(this.configuration).getSpacedRepetitionSystems(hidden, ids, updatedAfter, subjectIds, subjectTypes, options).then((request) => request(this.axios, this.basePath)); } }
dogboydog/wanikani-cli
src/cli/list/reviews/list-reviews.definition.ts
/* * This program and the accompanying materials are made available under the terms of the * Eclipse Public License v2.0 which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-v20.html * * SPDX-License-Identifier: EPL-2.0 * * Copyright Contributors to the Zowe Project. * */ import { ICommandDefinition } from "@zowe/imperative"; import {CommonOptions} from "../../common-options"; /** * This object defines the top level command group for zosfiles. This is not * something that is intended to be used outside of this npm package. * * @private */ export const ListReviewsDefinition: ICommandDefinition = { name: "reviews", aliases: ["rv"], type: "command", summary: "List reviews for your account", description: "List reviews for your account", profile: { optional: [ 'wanikani'] }, options: [ CommonOptions.TOKEN_OPTION ], outputFormatOptions: true, handler: __dirname + '/list-reviews.handler' };
Igor360/snapshot-hub
server/index.ts
<filename>server/index.ts<gh_stars>0 global['fetch'] = require('node-fetch'); import express from 'express'; import { getAddress } from '@ethersproject/address'; import { spaces } from './helpers/spaces'; import db from './helpers/mysql'; import relayer from './helpers/relayer'; import { pinJson } from './helpers/ipfs'; import { verifySignature, jsonParse, sendError, hashPersonalMessage, formatMessage } from './helpers/utils'; import { addOrUpdateSpace, loadSpace } from './helpers/adapters/mysql'; import writer from './writer'; import gossip from './helpers/gossip'; import pkg from '../package.json'; const router = express.Router(); const network = process.env.NETWORK || 'testnet'; router.get('/', (req, res) => { return res.json({ name: pkg.name, network, version: pkg.version, tag: 'alpha', relayer: relayer.address }); }); router.get('/spaces/:key?', (req, res) => { const { key } = req.params; return res.json(key ? spaces[key] : spaces); }); router.get('/spaces/:key/poke', async (req, res) => { const { key } = req.params; const space = await loadSpace(key); if (space) { await addOrUpdateSpace(key, space); spaces[key] = space; } return res.json(space); }); router.get('/:space/proposals', async (req, res) => { const { space } = req.params; const query = "SELECT * FROM messages WHERE type = 'proposal' AND space = ? ORDER BY timestamp DESC LIMIT 100"; db.queryAsync(query, [space]).then(messages => { res.json( Object.fromEntries(messages.map(message => formatMessage(message))) ); }); }); router.get('/:space/proposal/:id', async (req, res) => { const { space, id } = req.params; const query = ` SELECT v.* FROM votes v LEFT OUTER JOIN votes v2 ON v.voter = v2.voter AND v.proposal = v2.proposal AND ((v.created < v2.created) OR (v.created = v2.created AND v.id < v2.id)) WHERE v2.voter IS NULL AND v.space = ? AND v.proposal = ? ORDER BY created ASC `; db.queryAsync(query, [space, id]).then(messages => { res.json( Object.fromEntries( messages.map(message => { const address = getAddress(message.voter); return [ address, { address, msg: { timestamp: message.created.toString(), payload: { choice: JSON.parse(message.choice), metadata: JSON.parse(message.metadata), proposal: message.proposal } }, authorIpfsHash: message.id } ]; }) ) ); }); }); router.get('/voters', async (req, res) => { const { from = 0, to = 1e24 } = req.query; const spacesArr = req.query.spaces ? (req.query.spaces as string).split(',') : Object.keys(spaces); const query = `SELECT address, timestamp, space FROM messages WHERE type = 'vote' AND timestamp >= ? AND timestamp <= ? AND space IN (?) GROUP BY address ORDER BY timestamp DESC`; const messages = await db.queryAsync(query, [from, to, spacesArr]); res.json(messages); }); router.post('/message', async (req, res) => { if (process.env.MAINTENANCE) return sendError(res, 'update in progress, try later'); const body = req.body; const msg = jsonParse(body.msg); const ts = Date.now() / 1e3; const overTs = (ts + 300).toFixed(); const underTs = (ts - 300).toFixed(); if (!body || !body.address || !body.msg || !body.sig) return sendError(res, 'wrong message body'); if ( Object.keys(msg).length !== 5 || !msg.space || !msg.payload || Object.keys(msg.payload).length === 0 ) return sendError(res, 'wrong signed message'); if (JSON.stringify(body).length > 1e5) return sendError(res, 'too large message'); if (!spaces[msg.space] && msg.type !== 'settings') return sendError(res, 'unknown space'); if ( !msg.timestamp || typeof msg.timestamp !== 'string' || msg.timestamp.length !== 10 || msg.timestamp > overTs || msg.timestamp < underTs ) return sendError(res, 'wrong timestamp'); if (!msg.version || msg.version !== pkg.version) return sendError(res, 'wrong version'); if (!msg.type || !Object.keys(writer).includes(msg.type)) return sendError(res, 'wrong message type'); if ( !(await verifySignature( body.address, body.sig, hashPersonalMessage(body.msg) )) ) return sendError(res, 'wrong signature'); try { await writer[msg.type].verify(body); } catch (e) { return sendError(res, e); } gossip(body, msg.space); const authorIpfsRes = await pinJson(`snapshot/${body.sig}`, { address: body.address, msg: body.msg, sig: body.sig, version: '2' }); const relayerSig = await relayer.signMessage(authorIpfsRes); const relayerIpfsRes = await pinJson(`snapshot/${relayerSig}`, { address: relayer.address, msg: authorIpfsRes, sig: relayerSig, version: '2' }); try { await writer[msg.type].action(body, authorIpfsRes, relayerIpfsRes); } catch (e) { return sendError(res, e); } console.log( `Address "${body.address}"\n`, `Space "${msg.space}"\n`, `Type "${msg.type}"\n`, `IPFS hash "${authorIpfsRes}"` ); return res.json({ ipfsHash: authorIpfsRes, relayer: { address: relayer.address, receipt: relayerIpfsRes } }); }); export default router;
Igor360/snapshot-hub
server/writer/proposal.ts
import snapshot from '@snapshot-labs/snapshot.js'; import { storeProposal } from '../helpers/adapters/mysql'; import { sendMessage } from '../helpers/discord'; import { jsonParse } from '../helpers/utils'; import { spaces } from '../helpers/spaces'; const network = process.env.NETWORK || 'testnet'; export async function verify(body): Promise<any> { const msg = jsonParse(body.msg); const schemaIsValid = snapshot.utils.validateSchema( snapshot.schemas.proposal, msg.payload ); if (schemaIsValid !== true) { console.log('Wrong proposal format', schemaIsValid); return Promise.reject('wrong proposal format'); } const space = spaces[msg.space]; const members = space.members ? space.members.map(address => address.toLowerCase()) : []; const isMember = members.includes(body.address.toLowerCase()); if (space.filters && space.filters.onlyMembers && !isMember) { return Promise.reject('not a member'); } else if (!isMember && space.filters && space.filters.minScore) { try { const scores = await snapshot.utils.getScores( msg.space, space.strategies, space.network, snapshot.utils.getProvider(space.network), [body.address] ); const totalScore: any = scores .map((score: any) => Object.values(score).reduce((a, b: any) => a + b, 0) ) .reduce((a, b: any) => a + b, 0); if (totalScore < space.filters.minScore) return Promise.reject('below min. score'); } catch (e) { console.log( 'Failed to check voting power (proposal)', msg.space, body.address, e ); return Promise.reject('failed to check voting power'); } } } export async function action( body, authorIpfsHash, relayerIpfsHash ): Promise<void> { const msg = jsonParse(body.msg); await storeProposal(msg.space, body, authorIpfsHash, relayerIpfsHash); const networkStr = network === 'testnet' ? 'demo.' : ''; let message = `${msg.space} (${network})\n`; message += `**${msg.payload.name}**\n`; message += `<https://${networkStr}snapshot.org/#/${msg.space}/proposal/${authorIpfsHash}>`; sendMessage(message); }
Igor360/snapshot-hub
server/helpers/ens.ts
import ENS from '@ensdomains/ensjs'; import snapshot from '@snapshot-labs/snapshot.js'; import gateways from '@snapshot-labs/snapshot.js/src/gateways.json'; const gateway = gateways[0]; export async function uriGet( gateway: string, key: string, protocolType = 'ipfs' ) { // key = key.replace( // 'storage.snapshot.page', // 'storageapi.fleek.co/snapshot-team-bucket' // ); // if (key.includes('storageapi.fleek.co')) protocolType = 'https'; // let url = `https://${gateway}/${protocolType}/${key}`; // if (['https', 'http'].includes(protocolType)) // url = `${protocolType}://${key}`; // console.log(url); return { strategies: [ { name: 'erc20-balance-of', params: { symbol: 'PAYB', address: '0x8F1314124158203aC89121458c131dC857F5d520', decimals: 18 } } ], plugins: {}, filters: {minScore: 0, onlyMembers: true}, validation: {name: 'basic', params: {}}, name: 'build_', avatar: '', about: 'Swap paltform', network: '4', twitter: '', symbol: 'PAYB', domain: 'https://ha8mqwcnfna8.corp.merehead.xyz/', members: ['<KEY>'], admins: ['<KEY>'] }; } export async function getSpaceUriFromContentHash(id) { let uri: any = false; const provider = snapshot.utils.getProvider('4'); try { const ensAddress = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e'; const ens = new ENS({ provider, ensAddress }); uri = await ens.name(id).getContent(); uri = uri.value; } catch (e) { console.log('getSpaceUriFromContentHash failed', id, e); } return uri; } export async function getSpaceUriFromTextRecord(id) { let uri: any = false; const provider = snapshot.utils.getProvider('4'); try { const ensAddress = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e'; const ens = new ENS({ provider, ensAddress }); console.log(await ens.name(id)); uri = await ens.name(id).getText('snapshot'); } catch (e) { console.log('getSpaceUriFromTextRecord failed', id, e); } return uri; } export async function getSpaceUri(id) { let uri = await getSpaceUriFromTextRecord(id); if (!uri) uri = await getSpaceUriFromContentHash(id); return uri; } export async function getSpace(id) { let space: any = false; const uri: any = await getSpaceUri(id); if (uri) { try { const [protocolType, key] = uri.split('://'); space = await uriGet(gateway, key, protocolType); } catch (e) { console.log('getSpace failed', id, e); } } return space; }
ulesta/ionic-native
src/@ionic-native/core/ionic-native-plugin.ts
import { checkAvailability } from './decorators/common'; import { get } from './util'; export class IonicNativePlugin { static pluginName: string; static pluginRef: string; static plugin: string; static repo: string; static platforms: string[]; static install: string; /** * Returns a boolean that indicates whether the plugin is installed * @return {boolean} */ static installed(): boolean { return checkAvailability(this.pluginRef) === true; } /** * Returns the original plugin object */ static getPlugin(): any { return get(window, this.pluginRef); } /** * Returns the plugin's name */ static getPluginName(): string { return this.pluginName; } /** * Returns the plugin's reference */ static getPluginRef(): string { return this.pluginRef; } /** * Returns the plugin's install name */ static getPluginInstallName(): string { return this.plugin; } /** * Returns the plugin's supported platforms */ static getSupportedPlatforms(): string[] { return this.platforms || []; } }
ulesta/ionic-native
src/@ionic-native/plugins/photo-viewer/index.ts
import { Injectable } from '@angular/core'; import { Cordova, IonicNativePlugin, Plugin } from '@ionic-native/core'; export interface PhotoViewerOptions { /** * Set to false to disable the share button (Android only). Default: true */ share?: boolean; } /** * @name Photo Viewer * @description This plugin can display your image in full screen with the ability to pan, zoom, and share the image. * @usage * ```typescript * import { PhotoViewer } from '@ionic-native/photo-viewer/ngx'; * * constructor(private photoViewer: PhotoViewer) { } * * ... * * this.photoViewer.show('https://mysite.com/path/to/image.jpg'); * * this.photoViewer.show('https://mysite.com/path/to/image.jpg', 'My image title', {share: false}); * ``` */ @Plugin({ pluginName: 'PhotoViewer', plugin: 'com-sarriaroman-photoviewer', pluginRef: 'PhotoViewer', repo: 'https://github.com/sarriaroman/photoviewer', platforms: ['Android', 'iOS'] }) @Injectable() export class PhotoViewer extends IonicNativePlugin { /** * Shows an image in full screen * @param url {string} URL or path to image * @param title {string} * @param options {PhotoViewerOptions} */ @Cordova({ sync: true }) show(url: string, title?: string, options?: PhotoViewerOptions): void {} }
wiloke1/wil-react-sticky
src/dom.ie.d.ts
<gh_stars>10-100 interface Element { msMatchesSelector: (selectors: string) => boolean; }
wiloke1/wil-react-sticky
dist/offset.d.ts
<reponame>wiloke1/wil-react-sticky<filename>dist/offset.d.ts declare function offset(el: Element): { top: number; left: number; }; export default offset;
wiloke1/wil-react-sticky
src/closest.ts
<gh_stars>10-100 // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest // For browsers that do not support Element.closest(), but carry support for element.matches() (or a prefixed equivalent, meaning IE9+), a polyfill exists: if (typeof Element !== 'undefined') { if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector; } if (!Element.prototype.closest) { Element.prototype.closest = function(s: string) { // eslint-disable-next-line @typescript-eslint/no-this-alias let el: Element = this; do { if (el.matches(s)) return el; // @ts-ignore el = el.parentElement || el.parentNode; } while (el !== null && el.nodeType === 1); return null; }; } }
wiloke1/wil-react-sticky
dist/index.d.ts
<filename>dist/index.d.ts import { PureComponent } from 'react'; import './closest'; interface StickyProps { children: JSX.Element | ((isSticky: boolean) => JSX.Element); offsetTop: number; containerSelectorFocus: string; zIndex: number; stickyEnableRange: number[]; onChange: (isSticky: boolean) => void; } interface StickyState { isEnableSticky: boolean; targetHeight: number; innerPosition: string; containerMeasure: Partial<DOMRect>; isLong: boolean; innerTop: number; } declare type StickyDefaultProps = Pick<StickyProps, 'offsetTop' | 'containerSelectorFocus' | 'zIndex' | 'stickyEnableRange' | 'onChange'>; export default class Sticky extends PureComponent<StickyProps, StickyState> { private $container; private $inner; private prevScrollY; private isPrevSticky; static defaultProps: StickyDefaultProps; state: StickyState; componentDidMount(): void; componentWillUnmount(): void; private getContainerSelectorFocus; private handleWindowResize; private handleWindowScroll; private checkWrapBottom; private handleLong; private getInnerTop; private getInnerOffsetTop; private getContainerOffsetTop; private getContainerSelectorFocusOffsetTop; private getContainerSelectorFocusOffsetBottom; private getInnerPositionTop; private handleLongScrollUp; private setInnerPositionFixedTop; private handleLongScrollDown; private getShortPosition; private handleShort; private getInnerStyle; private getContainerStyle; private checkSticky; private setContainerRef; private setInnerRef; private renderHackGetHeightWhenInnerContentMargin; private renderChildren; render(): JSX.Element; } export {};
wiloke1/wil-react-sticky
src/index.tsx
<filename>src/index.tsx import React, { PureComponent, CSSProperties } from 'react'; import offset from './offset'; import './closest'; interface StickyProps { children: JSX.Element | ((isSticky: boolean) => JSX.Element); offsetTop: number; containerSelectorFocus: string; zIndex: number; stickyEnableRange: number[]; onChange: (isSticky: boolean) => void; } interface StickyState { isEnableSticky: boolean; targetHeight: number; innerPosition: string; containerMeasure: Partial<DOMRect>; isLong: boolean; innerTop: number; } type StickyDefaultProps = Pick< StickyProps, 'offsetTop' | 'containerSelectorFocus' | 'zIndex' | 'stickyEnableRange' | 'onChange' >; export default class Sticky extends PureComponent<StickyProps, StickyState> { private $container!: HTMLElement; private $inner!: HTMLElement; private prevScrollY!: number; private isPrevSticky!: boolean; public static defaultProps: StickyDefaultProps = { offsetTop: 0, containerSelectorFocus: 'body', zIndex: 10, stickyEnableRange: [0, Infinity], onChange: () => {}, }; public state: StickyState = { isEnableSticky: false, targetHeight: Infinity, innerPosition: 'static', containerMeasure: {}, isLong: false, innerTop: 0, }; public componentDidMount() { window.addEventListener('scroll', this.handleWindowScroll); this.handleWindowResize(); window.addEventListener('resize', this.handleWindowResize); } public componentWillUnmount() { window.removeEventListener('scroll', this.handleWindowScroll); window.removeEventListener('resize', this.handleWindowResize); } private getContainerSelectorFocus = () => { const { containerSelectorFocus } = this.props; return this.$container.closest(containerSelectorFocus); }; private handleWindowResize = () => { const { stickyEnableRange } = this.props; const [min, max] = stickyEnableRange; this.setState({ isEnableSticky: window.innerWidth >= min && window.innerWidth <= max, }); }; private handleWindowScroll = async () => { const { onChange } = this.props; const { isEnableSticky } = this.state; const isSticky = this.checkSticky(); const $containerSelectorFocus = this.getContainerSelectorFocus(); const { innerHeight: windowHeight } = window; if (this.$container && this.$inner && isEnableSticky) { const { clientHeight: innerHeight } = this.$inner; const containerMeasure = this.$container.getBoundingClientRect(); const targetHeight = $containerSelectorFocus ? $containerSelectorFocus.clientHeight : Infinity; await this.setState({ containerMeasure: { top: containerMeasure.top, left: containerMeasure.left, width: containerMeasure.width, height: innerHeight, }, targetHeight, isLong: innerHeight > windowHeight, }); if (innerHeight > windowHeight) { this.handleLong(); } else { this.handleShort(); } if (this.isPrevSticky !== isSticky) { onChange(isSticky); } this.isPrevSticky = isSticky; } }; private checkWrapBottom = () => { const { offsetTop } = this.props; const $containerSelectorFocus = this.getContainerSelectorFocus(); const { containerMeasure, isLong } = this.state; const targetHeight = $containerSelectorFocus ? $containerSelectorFocus.clientHeight : Infinity; return ( containerMeasure.top - containerMeasure.height + (isLong ? containerMeasure.height - window.innerHeight + offsetTop : 0) - offsetTop < targetHeight * -1 - (this.getContainerSelectorFocusOffsetTop() - this.getContainerOffsetTop()) ); }; private handleLong = () => { const { scrollY } = window; if (this.prevScrollY > scrollY) { this.handleLongScrollUp(scrollY); } else { this.handleLongScrollDown(scrollY); } this.prevScrollY = scrollY; }; private getInnerTop = () => { const innerMeasure = this.$inner.getBoundingClientRect(); const innerTop = innerMeasure.top || -1; return innerTop; }; private getInnerOffsetTop = () => { return offset(this.$inner).top; }; private getContainerOffsetTop = () => { return offset(this.$container).top; }; private getContainerSelectorFocusOffsetTop = () => { const $containerSelectorFocus = this.getContainerSelectorFocus(); return $containerSelectorFocus ? offset($containerSelectorFocus).top : 0; }; private getContainerSelectorFocusOffsetBottom = () => { const $containerSelectorFocus = this.getContainerSelectorFocus(); return $containerSelectorFocus ? Math.trunc(offset($containerSelectorFocus).top + $containerSelectorFocus.clientHeight) : 0; }; private getInnerPositionTop = () => { if (this.$container && this.$inner) { return this.getInnerOffsetTop() - this.getContainerOffsetTop(); } return 0; }; private handleLongScrollUp = async (scrollY: number) => { const { offsetTop } = this.props; const { containerMeasure, innerPosition } = this.state; const isTop = containerMeasure.top > offsetTop; const innerTop = this.getInnerTop(); if (isTop) { this.setState({ innerPosition: 'static', }); } else { if ( containerMeasure.top <= innerTop && (innerPosition === 'fixedBottom' || (innerPosition === 'absoluteBottom' && scrollY + window.innerHeight <= this.getContainerSelectorFocusOffsetBottom())) ) { await this.setState({ innerPosition: 'absoluteCenter', }); } this.setInnerPositionFixedTop(); } }; private setInnerPositionFixedTop = () => { const { offsetTop } = this.props; const { innerPosition } = this.state; const innerTop = this.getInnerTop(); this.setState({ innerTop: this.getInnerPositionTop(), }); if (innerTop >= offsetTop && innerPosition === 'absoluteCenter') { this.setState({ innerPosition: 'fixedTop', }); } }; private handleLongScrollDown = (scrollY: number) => { const { containerMeasure, innerPosition } = this.state; const isBottom = Math.trunc(scrollY + window.innerHeight) >= Math.trunc(this.getInnerOffsetTop() + containerMeasure.height); const isWrapBottom = this.checkWrapBottom(); if (innerPosition === 'fixedTop') { this.setState({ innerPosition: 'absoluteCenter', }); } if (isWrapBottom) { this.setState({ innerPosition: 'absoluteBottom', }); } else if (isBottom) { this.setState({ innerPosition: 'fixedBottom', innerTop: this.getInnerPositionTop(), }); } }; private getShortPosition = (containerMeasure: StickyState['containerMeasure']) => { const { offsetTop } = this.props; if (containerMeasure.top <= offsetTop) { if (this.checkWrapBottom()) { return 'absoluteBottom'; } return 'fixedTop'; } return 'static'; }; private handleShort = () => { const { containerMeasure } = this.state; this.setState({ innerPosition: this.getShortPosition(containerMeasure), }); }; private getInnerStyle = (): CSSProperties => { const { offsetTop, zIndex } = this.props; const { targetHeight, innerPosition, containerMeasure, isLong, innerTop } = this.state; const topForAbsoluteBottom = targetHeight - containerMeasure.height + (this.getContainerSelectorFocusOffsetTop() - this.getContainerOffsetTop()); if (isLong) { switch (innerPosition) { case 'static': return {}; case 'fixedTop': return { position: 'fixed', top: offsetTop, width: containerMeasure.width, zIndex, }; case 'absoluteCenter': return { position: 'absolute', top: innerTop, width: containerMeasure.width, zIndex, }; case 'absoluteBottom': return { position: 'absolute', top: topForAbsoluteBottom, width: containerMeasure.width, zIndex, }; case 'fixedBottom': return { position: 'fixed', bottom: 0, width: containerMeasure.width, zIndex, }; default: return {}; } } switch (innerPosition) { case 'static': return {}; case 'absoluteBottom': return { position: 'absolute', top: topForAbsoluteBottom, width: containerMeasure.width, zIndex, }; case 'fixedTop': return { position: 'fixed', top: offsetTop, width: containerMeasure.width, zIndex, }; default: return {}; } }; private getContainerStyle = (): CSSProperties => { const { innerPosition, containerMeasure } = this.state; if (innerPosition === 'static') { return { minHeight: containerMeasure.height, }; } return { position: 'relative', minHeight: containerMeasure.height, }; }; private checkSticky = () => { const { innerPosition } = this.state; return innerPosition.search(/fixedTop|fixedBottom/g) !== -1; }; private setContainerRef = (c: HTMLElement) => { this.$container = c; }; private setInnerRef = (c: HTMLElement) => { this.$inner = c; }; private renderHackGetHeightWhenInnerContentMargin = () => { return <div style={{ fontSize: 0, visibility: 'hidden' }}>.</div>; }; private renderChildren = () => { const { children } = this.props; const isSticky = this.checkSticky(); return typeof children === 'function' ? children(isSticky) : children; }; public render() { const { isEnableSticky } = this.state; const containerStyle = isEnableSticky ? this.getContainerStyle() : {}; const innerStyle = isEnableSticky ? this.getInnerStyle() : {}; return ( <div ref={this.setContainerRef} style={containerStyle}> <div ref={this.setInnerRef} style={innerStyle}> {this.renderHackGetHeightWhenInnerContentMargin()} {this.renderChildren()} {this.renderHackGetHeightWhenInnerContentMargin()} </div> </div> ); } }
wiloke1/wil-react-sticky
src/offset.ts
<gh_stars>10-100 function getWindow(el: Document) { return el.nodeType === 9 && el.defaultView; } function offset(el: Element) { const doc = el?.ownerDocument; const docElem = doc.documentElement; const win = getWindow(doc); let box = { top: 0, left: 0 }; if (!doc) { return { top: 0, left: 0, }; } if (typeof el.getBoundingClientRect !== typeof undefined) { box = el.getBoundingClientRect(); } return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft, }; } export default offset;
Subho0710/Swasthify-1
src/app/Hospitals/dashboard/dashboard.component.ts
import { Component, OnInit , OnDestroy} from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { ActivatedRoute,Router } from '@angular/router'; import { Subscription, timer } from 'rxjs'; import { Hospitals } from 'src/app/models/hospitals'; import { HospitalService } from 'src/app/services/hospital.service'; import Swal from 'sweetalert2'; import { SharingService } from 'src/app/services/sharing.service'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; import { Observable } from 'rxjs'; import { map, shareReplay } from 'rxjs/operators'; import { flyInOut, expand } from '../../Utilities/animations/animation'; import { ChatDataTransferService } from 'src/app/services/chat-data-transfer.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.scss'], animations: [ flyInOut(), expand() ] }) export class DashboardComponent implements OnInit { step: any = 1; one: any = "c1"; two: any; three: any; id !: number; time = new Date(); date=Date(); hospitals: Hospitals = new Hospitals(); intervalId:any; subscription: any; light ! : string; constructor(private breakpointObserver: BreakpointObserver,private hospService: HospitalService,private route:Router, private router: ActivatedRoute, private sharingService:SharingService, private chatService : ChatDataTransferService) { } ngOnInit(): void { this.light = this.sharingService.getData(); console.log(this.light); // Using Basic Interval for clock this.intervalId = setInterval(() => { this.time = new Date(); }, 1000); this.id = this.router.snapshot.params['id']; this.hospService.getHospById(this.id).subscribe((data) => { this.hospitals = data; this.chatService.emailId = this.hospitals.emailId; this.chatService.user = this.hospitals.hospitalName; console.log(this.hospitals); }, (Error) => { console.log(Error.error.message); }); } isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset) .pipe( map(result => result.matches), shareReplay() ); ngOnDestroy() { clearInterval(this.intervalId); if (this.subscription) { this.subscription.unsubscribe(); } } updateEntries() { this.hospService.updateDetailsOfHospital(this.id, this.hospitals).subscribe((data) => { this.hospitals = data; console.log(this.hospitals); Swal.fire('Updated Successfully'); }, (Error) => { console.log(Error.error.message); }) } submit() { if (this.step == 1) { this.two = "c1"; } else if (this.step == 2) { this.three = "c1"; } this.step = this.step + 1; } profile(){ this.route.navigate(['/h-profile',this.id]); } previous() { if (this.step == 3) { this.three = "c2"; } else if (this.step == 2) { this.two = "c2"; } this.step = this.step - 1; } }
Subho0710/Swasthify-1
src/app/Hospitals/forget-pas/forget-pas.component.ts
<gh_stars>1-10 import { Component, OnInit } from '@angular/core'; import { FormBuilder,FormGroup,Validators } from '@angular/forms'; import Swal from 'sweetalert2'; import { flyInOut , expand} from '../../Utilities/animations/animation'; import { SharingService } from 'src/app/services/sharing.service'; @Component({ selector: 'app-forget-pas', templateUrl: './forget-pas.component.html', styleUrls: ['./forget-pas.component.scss'], animations: [ flyInOut(), expand() ] }) export class ForgetPasComponent implements OnInit { HForgotForm !: FormGroup; light ! : string; constructor(private fb: FormBuilder, private sharingService:SharingService) { } ngOnInit(): void { this.HForgotForm = this.fb.group({ email: ['',[ Validators.required, Validators.email, Validators.maxLength(40) ]], agree:[false,[ Validators.requiredTrue ]]}); this.light = this.sharingService.getData(); } get email(){ return this.HForgotForm.get('email'); } get agree(){ return this.HForgotForm.get('agree'); } submit(){ console.log(this.HForgotForm.value); Swal.fire({ icon: 'success', title: 'Email Sent', text: 'Please check your inbox', }); this.HForgotForm.reset({ email: '', password: '', }); } }
Subho0710/Swasthify-1
src/app/models/changePass.ts
export class ChangePassword{ currentPassword !: string; newPassword !: string; confirmNewPassword !: string; }
Subho0710/Swasthify-1
src/app/Hospitals/profile-hospital/profile-hospital.component.ts
<reponame>Subho0710/Swasthify-1 import { Hospitals } from './../../models/hospitals'; import { Component, OnInit } from '@angular/core'; import { HospitalService } from 'src/app/services/hospital.service'; import { ActivatedRoute, Router } from '@angular/router'; import { FormBuilder,FormGroup,Validators } from '@angular/forms'; import { flyInOut , expand} from '../../Utilities/animations/animation'; import { ChangePassword } from 'src/app/models/changePass'; import Swal from 'sweetalert2'; @Component({ selector: 'app-profile-hospital', templateUrl: './profile-hospital.component.html', styleUrls: ['./profile-hospital.component.scss'], animations: [ flyInOut(), expand() ] }) export class ProfileHospitalComponent implements OnInit { updatedpass : ChangePassword = new ChangePassword(); id!:number; hospital:Hospitals = new Hospitals(); cpass:boolean = false; // for change password form toggle dpass:boolean = false; // for delete profile toggle email!:any; ChangePassForm !: FormGroup; DeleteForm !: FormGroup; fieldTextType: boolean = false; fieldTextType2: boolean = false; fieldTextType3: boolean = false; fieldTextType4: boolean = false; fieldTextType5: boolean = false; constructor(private fb: FormBuilder,private route:ActivatedRoute,private router:Router,private hospitalservice:HospitalService) { } ngOnInit(): void { this.id = this.route.snapshot.params['id']; this.hospitalservice.getDetailsOfHospital(this.id).subscribe(data =>{ this.hospital = data; }, error =>{ console.log(error); }) function ConfirmedValidator(controlName: string, matchingControlName: string){ return (formGroup: FormGroup) => { const control = formGroup.controls[controlName]; const matchingControl = formGroup.controls[matchingControlName]; if (matchingControl.errors && !matchingControl.errors.confirmedValidator) { return; } if (control.value !== matchingControl.value) { matchingControl.setErrors({ confirmedValidator: true }); } else { matchingControl.setErrors(null); } } } // Change Password Form ---------------------------------------- this.ChangePassForm = this.fb.group({ currentPassword:['',[ Validators.required, Validators.pattern('^(?:(?:(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]))|(?:(?=.*[a-z])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[a-z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))).{8,32}$'), Validators.minLength(8) ]], newPassword:['',[ Validators.required, Validators.pattern('^(?:(?:(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]))|(?:(?=.*[a-z])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[a-z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))).{8,32}$'), Validators.minLength(8) ]], confirmNewPassword:['',[ Validators.required, Validators.pattern('^(?:(?:(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]))|(?:(?=.*[a-z])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[a-z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))).{8,32}$'), Validators.minLength(8), ]] }, { validator: ConfirmedValidator('newPassword', 'confirmNewPassword') }, ); //Delete Form ------------------------------------------------- this.DeleteForm = this.fb.group({ pass:['',[ Validators.required, Validators.pattern('^(?:(?:(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]))|(?:(?=.*[a-z])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[a-z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))).{8,32}$'), Validators.minLength(8) ]], conPass:['',[ Validators.required, Validators.pattern('^(?:(?:(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]))|(?:(?=.*[a-z])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[a-z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))).{8,32}$'), Validators.minLength(8), ]], agree:[false,[ Validators.requiredTrue ]] }, { validator: ConfirmedValidator('pass', 'conPass') } ); } get currentPassword(){ return this.ChangePassForm .get('currentPassword'); } get newPassword(){ return this.ChangePassForm .get('newPassword'); } get confirmNewPassword(){ return this.ChangePassForm .get('confirmNewPassword'); } // Delete FOrm Fields --------------------- get pass(){ return this.DeleteForm.get('pass'); } get conPass(){ return this.DeleteForm.get('conPass'); } get agree(){ return this.DeleteForm.get('agree'); } // Change Password Submit ------------------------------- submit(){ this.hospitalservice.changePassHospital(this.ChangePassForm .value,this.id).subscribe(data=>{ Swal.fire({ icon: 'success', title: 'Password Changed Succesfully', }) }, (Error) =>{ Swal.fire({ icon: 'error', title: 'Oops...Error', text: Error.error.message, }) }); this.ChangePassForm .reset({ currentPassword: '', NewPasswor: '', confirmNewPasswor: '', }); this.router.navigate(['/hospital-login']); } // Delete Patient Submit ----------------------------------- submitDelete(){ this.hospitalservice.deleteHospital(this.id).subscribe(data=>{ Swal.fire({ icon: 'success', title: 'Account Deleted Successfully', }) }, (Error) =>{ Swal.fire({ icon: 'error', title: 'Oops...Error', text: Error.error.message, }) }); this.router.navigate(['/hospital-login']); } // breadcrum route to patient dashboard backroute(){ this.router.navigate(['/hospital-dashboard',this.id]); } // For Change Password Toggle----------------- changePassword(data:any){ if(this.cpass === false){ this.cpass = true; } else{ this.cpass=false; } if(this.dpass){ this.dpass=!this.dpass; } this.email = data; // set email } // For Delete Profile Toggle------------------- DeleteProfile(){ if(this.dpass === false){ this.dpass = true; } else{ this.dpass=false; } if(this.cpass){ this.cpass=!this.cpass; } } // <!-- Switching method --> toggleFieldTextType() { this.fieldTextType = !this.fieldTextType; } toggleFieldTextType2() { this.fieldTextType2 = !this.fieldTextType2; } toggleFieldTextType3() { this.fieldTextType3 = !this.fieldTextType3; } toggleFieldTextType4() { this.fieldTextType4 = !this.fieldTextType4; } toggleFieldTextType5() { this.fieldTextType5 = !this.fieldTextType5; } }
Subho0710/Swasthify-1
src/app/Patients/dashboard-patient/dashboard-patient.component.ts
<reponame>Subho0710/Swasthify-1<filename>src/app/Patients/dashboard-patient/dashboard-patient.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { HospitalDetails } from 'src/app/models/hospital-details'; import { TotalService } from 'src/app/models/total-service'; import { PatientService } from 'src/app/services/patient.service'; import { flyInOut , expand} from '../../Utilities/animations/animation'; import {MatDialog} from '@angular/material/dialog'; import { HospDetailsDialogComponent } from '../hosp-details-dialog/hosp-details-dialog.component'; import { Subscription, timer } from 'rxjs'; import { ActivatedRoute, Router } from '@angular/router'; import { Patients } from 'src/app/models/patients'; import Swal from 'sweetalert2'; import { ChatDataTransferService } from 'src/app/services/chat-data-transfer.service'; @Component({ selector: 'app-dashboard-patient', templateUrl: './dashboard-patient.component.html', styleUrls: ['./dashboard-patient.component.scss'], animations: [ flyInOut(), expand() ] }) export class DashboardPatientComponent implements OnInit { date=Date(); sidenav = ""; sidenavTitle = ""; main_container = "main_container" ; city! : String; hospitalDetails : HospitalDetails[] = []; tempDetails : HospitalDetails[] = []; time = new Date(); id ! : number; patient : Patients = new Patients(); intervalId:any; subscription: any; logoutalert(){ Swal.fire('Thank you...', 'Logout succesfully!', 'success') } toggleNav(){ if(this.sidenav){ this.sidenav = ""; } else{ this.sidenav = "sidenav2"; } if(this.sidenavTitle){ this.sidenavTitle = ""; } else{ this.sidenavTitle = "sidenavTitle2"; } if(this.main_container=="main_container"){ this.main_container = "main_container2"; } else{ this.main_container = "main_container"; } }; totService : TotalService = new TotalService(); constructor(private PatientService : PatientService, public dialog: MatDialog, private route : ActivatedRoute,private router: Router, private chatService : ChatDataTransferService) { } ngOnInit(): void { // Using Basic Interval for clock this.intervalId = setInterval(() => { this.time = new Date(); }, 1000); this.id = this.route.snapshot.params['id']; this.PatientService.getPatient(this.id).subscribe((data) => { this.patient = data; this.chatService.user = this.patient.name; this.chatService.emailId= this.patient.emailId; }, (Error) => {console.log(Error.error.message)} ); this.PatientService.getTotalServices().subscribe((data) => { this.totService = data; }, (Error) => {console.log(Error.error.message)} ); } ngOnDestroy() { clearInterval(this.intervalId); if (this.subscription) { this.subscription.unsubscribe(); } } findHospitalByDefault(data:any){ this.city = data; this.findHospitals(); } findHospitals(){ setTimeout(() => { this.PatientService.getDetailsOfHospitalsByCity(this.city).subscribe((data) => { this.hospitalDetails = data; this.PatientService.getTotalServicesByCity(this.city).subscribe((data) => { this.totService = data; }) }, (Error) => {console.log(Error.error.message)} ); }, 500); } //open daialog of details----- openDialog(id : number) { this.dialog.open(HospDetailsDialogComponent,{ data : id, }); } findIcu(){ let temp : any = []; this.PatientService.getHospitalsByService(this.city).subscribe((data) => { this.tempDetails = data; for(let a of this.tempDetails){ if(a.icuBeds > 0){ temp.push(a); } } }); setTimeout(() => { this.PatientService.getTotalServicesByCity(this.city).subscribe((data) => { this.totService = data; }); },2000); this.hospitalDetails = temp; } findOxygencylinders(){ let temp : any = []; this.PatientService.getHospitalsByService(this.city).subscribe((data) => { this.tempDetails = data; for(let a of this.tempDetails){ if(a.oxygenCylinders > 0){ temp.push(a); } } }); setTimeout(() => { this.PatientService.getTotalServicesByCity(this.city).subscribe((data) => { this.totService = data; }); },2000); this.hospitalDetails = temp; } findVaccines(){ let temp : any = []; this.PatientService.getHospitalsByService(this.city).subscribe((data) => { this.tempDetails = data; for(let a of this.tempDetails){ if(a.vaccine1 > 0 || a.vaccine2 > 0){ temp.push(a); } } }); setTimeout(() => { this.PatientService.getTotalServicesByCity(this.city).subscribe((data) => { this.totService = data; }); },2000); this.hospitalDetails = temp; } findIsolationBeds(){ let temp : any = []; this.PatientService.getHospitalsByService(this.city).subscribe((data) => { this.tempDetails = data; for(let a of this.tempDetails){ if(a.isolationBeds > 0){ temp.push(a); } } }); setTimeout(() => { this.PatientService.getTotalServicesByCity(this.city).subscribe((data) => { this.totService = data; }); },2000); this.hospitalDetails = temp; } profile(){ this.router.navigate(['/p-profile',this.id]); } }
Subho0710/Swasthify-1
src/app/services/patient.service.ts
<filename>src/app/services/patient.service.ts import { ChangePassword } from './../models/changePass'; import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Patients } from '../models/patients'; import { TotalService } from '../models/total-service'; @Injectable({ providedIn: 'root' }) export class PatientService { constructor(private httpClient : HttpClient) { } baseUrl = "https://swasthify-server.herokuapp.com/api/v2/"; // baseUrl = "http://localhost:8080/api/v2/"; //get details public getTotalServices() : Observable<TotalService>{ return this.httpClient.get<TotalService>(this.baseUrl+"all-services") } //get details by city public getTotalServicesByCity(city : String) : Observable<TotalService>{ return this.httpClient.get<TotalService>(this.baseUrl+"all-services/"+city) } //register details public registerPatient(PSForm : any) : Observable<any>{ return this.httpClient.post<any>(this.baseUrl+"register-patient", PSForm); } //sign in public loginPatient(PLoginForm : any) : Observable<any>{ return this.httpClient.post<any>(this.baseUrl+"login-patient", PLoginForm); } //change password public changePassPatient(changePass : ChangePassword,id:number) : Observable<any>{ return this.httpClient.put<any>(this.baseUrl+"patient-details/"+id, changePass); } //get patitent details by id public getPatient(id : number) : Observable<Patients>{ return this.httpClient.get<Patients>(this.baseUrl+"patient-details/"+id); } //Delete patient by id deletePatient(id:number):Observable <any>{ return this.httpClient.delete<any>(this.baseUrl+"patient-details/"+id); } //get all hospitals by city public getDetailsOfHospitalsByCity(city : String) : Observable<any>{ return this.httpClient.get<any>(this.baseUrl+"details/"+city); } //get all hospitals by service public getHospitalsByService(city : String) : Observable<any>{ return this.httpClient.get<any>(this.baseUrl+"all-hospitals/"+city); } }
Subho0710/Swasthify-1
src/app/Hospitals/login/login.component.ts
<reponame>Subho0710/Swasthify-1<filename>src/app/Hospitals/login/login.component.ts<gh_stars>1-10 import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { HospitalService } from 'src/app/services/hospital.service'; import Swal from 'sweetalert2'; import { flyInOut, expand } from '../../Utilities/animations/animation'; import { SharingService } from 'src/app/services/sharing.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], animations: [ flyInOut(), expand() ] }) export class LoginComponent implements OnInit { id !: number; HLoginForm !: FormGroup; err !: String; light !: string; fieldTextType: boolean = false; constructor(private fb: FormBuilder, private hospService: HospitalService, private router: Router, private sharingService: SharingService) { } ngOnInit(): void { this.HLoginForm = this.fb.group({ emailId: ['', [ Validators.required, Validators.email, Validators.maxLength(40) ]], pass: ['', [ Validators.required, Validators.pattern('^(?:(?:(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]))|(?:(?=.*[a-z])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[A-Z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))|(?:(?=.*[0-9])(?=.*[a-z])(?=.*[*.!@$%^&(){}[]:;<>,.?/~_+-=|\]))).{8,32}$'), Validators.minLength(8) ]], }); this.light = this.sharingService.getData(); //console.log("light = "+this.light); } get email() { return this.HLoginForm.get('email'); } get password() { return this.HLoginForm.get('password'); } submit() { this.hospService.signInHospital(this.HLoginForm.value).subscribe((data) => { this.id = data.id; Swal.fire({ icon: 'success', title: 'Login Succesful', }); this.router.navigate(['hospital-dashboard',this.id]); }, (Error) => { this.err = Error.error.message; alert(this.err); Swal.fire({ icon: 'error', title: 'Oops...', text: ('${this.err}'), footer: '<a href>Why do I have this issue?</a>' }) }); this.HLoginForm.reset({ email: '', password: '', }); } // <!-- Switching method --> toggleFieldTextType() { this.fieldTextType = !this.fieldTextType; } }
d8vjork/laravel-json-api
docs/.vuepress/config.ts
import { defineUserConfig } from 'vuepress' import type { DefaultThemeOptions } from 'vuepress' export default defineUserConfig<DefaultThemeOptions>({ base: '/laravel-json-api/', lang: 'en-US', title: 'Laravel JSON:API', description: 'Integrate JSON:API resources on Laravel', plugins: [ [ '@vuepress/search', { searchMaxSuggestions: 10 } ] ], theme: '@vuepress/theme-default', themeConfig: { logo: 'https://skore-public-assets.s3.eu-west-2.amazonaws.com/skore-logo-2x.png', repo: 'skore/laravel-json-api', navbar: [ { text: 'Home', link: '/README.md', }, { text: 'Guide', children: [ { text: 'Installation', link: '/guide/README.md' }, '/guide/usage.md', '/guide/testing.md', '/guide/implementations.md', ], }, { text: 'Comparison', link: '/comparison.md', } ], sidebar: { '/guide/': [ { text: 'Introduction', children: [ { text: 'Installation', link: '/guide/README.md' }, { text: 'Usage', link: '/guide/usage.md' }, { text: 'Testing', link: '/guide/testing.md' }, { text: 'Implementations', link: '/guide/implementations.md' }, ] }, // { // text: 'Upgrading', // link: '/guide/upgrading.md' // }, ], }, }, })
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/components/ServiceQueryBuilder.tsx
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { ServicePureExecutionState, RawLambda, } from '@finos/legend-studio'; import { useApplicationStore, useEditorStore } from '@finos/legend-studio'; import { observer } from 'mobx-react-lite'; import { QueryBuilderState } from '../stores/QueryBuilderState'; export const ServiceQueryBuilder = observer( (props: { executionState: ServicePureExecutionState; isReadOnly: boolean; }) => { const { executionState } = props; const applicationStore = useApplicationStore(); const editorStore = useEditorStore(); const queryBuilderState = editorStore.getEditorExtensionState(QueryBuilderState); const editWithQueryBuilder = async (): Promise<void> => { executionState.setOpeningQueryEditor(true); if (executionState.selectedExecutionConfiguration) { const mapping = executionState.selectedExecutionConfiguration.mapping.value; const runtime = executionState.selectedExecutionConfiguration.runtime; if (!mapping.isStub) { await queryBuilderState.querySetupState.setup( executionState.execution.func, mapping, runtime, async (lambda: RawLambda): Promise<void> => executionState.queryState .updateLamba(lambda) .then(() => editorStore.applicationStore.notifySuccess( `Service '${executionState.execution.owner.name}' execution query is updated`, ), ) .catch(applicationStore.alertIllegalUnhandledError), executionState.queryState.query.isStub, ); executionState.setOpeningQueryEditor(false); return; } } executionState.editorStore.applicationStore.notifyWarning( 'Please specify a mapping and a runtime for the execution to edit with query builder', ); executionState.setOpeningQueryEditor(false); }; return ( <div className="service-query-builder"> <button className="btn--dark service-query-builder__btn" onClick={editWithQueryBuilder} > Edit Query </button> </div> ); }, );
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/stores/QueryBuilderState.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { action, flow, flowResult, observable, makeObservable } from 'mobx'; import type { GeneratorFn } from '@finos/legend-studio-shared'; import { assertErrorThrown, changeEntry, guaranteeNonNullable, guaranteeType, } from '@finos/legend-studio-shared'; import type { QueryBuilderFilterOperator } from './QueryBuilderFilterState'; import { QueryBuilderFilterState } from './QueryBuilderFilterState'; import { QueryBuilderFetchStructureState } from './QueryBuilderFetchStructureState'; import { QueryResultSetModifierState } from './QueryResultSetModifierState'; import { QueryTextEditorMode, QueryTextEditorState, } from './QueryTextEditorState'; import { QueryBuilderSetupState } from './QueryBuilderSetupState'; import { QueryBuilderExplorerState } from './QueryBuilderExplorerState'; import { QueryBuilderResultState } from './QueryBuilderResultState'; import { QueryBuilderLambdaProcessor } from './QueryBuilderLambdaProcessor'; import { QueryBuilderUnsupportedState } from './QueryBuilderUnsupportedState'; import type { EditorStore, LambdaFunction } from '@finos/legend-studio'; import { EditorExtensionState, CompilationError, CORE_LOG_EVENT, extractSourceInformationCoordinates, LambdaFunctionInstanceValue, RawLambda, TYPICAL_MULTIPLICITY_TYPE, } from '@finos/legend-studio'; import { QueryBuilderFilterOperator_Equal, QueryBuilderFilterOperator_NotEqual, } from './filterOperators/QueryBuilderFilterOperator_Equal'; import { QueryBuilderFilterOperator_GreaterThan } from './filterOperators/QueryBuilderFilterOperator_GreaterThan'; import { QueryBuilderFilterOperator_NotStartWith, QueryBuilderFilterOperator_StartWith, } from './filterOperators/QueryBuilderFilterOperator_StartWith'; import { QueryBuilderFilterOperator_GreaterThanEqual } from './filterOperators/QueryBuilderFilterOperator_GreaterThanEqual'; import { QueryBuilderFilterOperator_LessThanEqual } from './filterOperators/QueryBuilderFilterOperator_LessThanEqual'; import { QueryBuilderFilterOperator_LessThan } from './filterOperators/QueryBuilderFilterOperator_LessThan'; import { QueryBuilderFilterOperator_EndWith, QueryBuilderFilterOperator_NotEndWith, } from './filterOperators/QueryBuilderFilterOperator_EndWith'; import { QueryBuilderFilterOperator_Contain, QueryBuilderFilterOperator_NotContain, } from './filterOperators/QueryBuilderFilterOperator_Contain'; import { QueryBuilderFilterOperator_IsEmpty, QueryBuilderFilterOperator_IsNotEmpty, } from './filterOperators/QueryBuilderFilterOperator_IsEmpty'; import { QueryBuilderFilterOperator_In, QueryBuilderFilterOperator_NotIn, } from './filterOperators/QueryBuilderFilterOperator_In'; import { buildLambdaFunction } from './QueryBuilderLambdaBuilder'; export class QueryBuilderState extends EditorExtensionState { editorStore: EditorStore; querySetupState: QueryBuilderSetupState; explorerState: QueryBuilderExplorerState; fetchStructureState: QueryBuilderFetchStructureState; filterState: QueryBuilderFilterState; resultSetModifierState: QueryResultSetModifierState; resultState: QueryBuilderResultState; queryTextEditorState: QueryTextEditorState; queryUnsupportedState: QueryBuilderUnsupportedState; openQueryBuilder = false; filterOperators: QueryBuilderFilterOperator[] = [ new QueryBuilderFilterOperator_Equal(), new QueryBuilderFilterOperator_NotEqual(), new QueryBuilderFilterOperator_LessThan(), new QueryBuilderFilterOperator_LessThanEqual(), new QueryBuilderFilterOperator_GreaterThan(), new QueryBuilderFilterOperator_GreaterThanEqual(), new QueryBuilderFilterOperator_StartWith(), new QueryBuilderFilterOperator_NotStartWith(), new QueryBuilderFilterOperator_Contain(), new QueryBuilderFilterOperator_NotContain(), new QueryBuilderFilterOperator_EndWith(), new QueryBuilderFilterOperator_NotEndWith(), new QueryBuilderFilterOperator_In(), new QueryBuilderFilterOperator_NotIn(), new QueryBuilderFilterOperator_IsEmpty(), new QueryBuilderFilterOperator_IsNotEmpty(), ]; isCompiling = false; constructor(editorStore: EditorStore) { super(); makeObservable(this, { querySetupState: observable, explorerState: observable, fetchStructureState: observable, filterState: observable, resultSetModifierState: observable, resultState: observable, queryTextEditorState: observable, queryUnsupportedState: observable, openQueryBuilder: observable, isCompiling: observable, setOpenQueryBuilder: flow, compileQuery: flow, reset: action, resetData: action, buildStateFromRawLambda: action, saveQuery: action, }); this.editorStore = editorStore; this.querySetupState = new QueryBuilderSetupState(editorStore, this); this.explorerState = new QueryBuilderExplorerState(editorStore, this); this.fetchStructureState = new QueryBuilderFetchStructureState( editorStore, this, ); this.filterState = new QueryBuilderFilterState( editorStore, this, this.filterOperators, ); this.resultSetModifierState = new QueryResultSetModifierState( editorStore, this, ); this.resultState = new QueryBuilderResultState(editorStore, this); this.queryTextEditorState = new QueryTextEditorState(editorStore, this); this.queryUnsupportedState = new QueryBuilderUnsupportedState( editorStore, this, ); } getQuery(options?: { keepSourceInformation: boolean }): RawLambda { return this.isQuerySupported() ? this.buildRawLambdaFromLambdaFunction( buildLambdaFunction(this, { keepSourceInformation: Boolean(options?.keepSourceInformation), }), ) : guaranteeNonNullable(this.queryUnsupportedState.rawLambda); } /** * When opening query builder, we ensure the graph compiles successfully */ *setOpenQueryBuilder( val: boolean, options?: { disableCompile: boolean }, ): GeneratorFn<void> { if (!this.editorStore.isInFormMode) { return; } if (val === this.openQueryBuilder) { return; } if (val) { if (!options?.disableCompile) { this.editorStore.setBlockingAlert({ message: 'Compiling graph before building query...', showLoading: true, }); yield flowResult( this.editorStore.graphState.globalCompileInFormMode({ disableNotificationOnSuccess: true, }), ); this.editorStore.setBlockingAlert(undefined); } if (!this.editorStore.graphState.hasCompilationError) { this.openQueryBuilder = val; } this.editorStore.setBlockGlobalHotkeys(true); this.editorStore.setHotkeys([]); } else { this.openQueryBuilder = val; this.editorStore.setBlockGlobalHotkeys(false); this.editorStore.resetHotkeys(); } } reset(): void { changeEntry( this.editorStore.editorExtensionStates, this.editorStore.getEditorExtensionState(QueryBuilderState), new QueryBuilderState(this.editorStore), ); } resetData(): void { this.explorerState = new QueryBuilderExplorerState(this.editorStore, this); const fetchStructureState = new QueryBuilderFetchStructureState( this.editorStore, this, ); fetchStructureState.setFetchStructureMode( this.fetchStructureState.fetchStructureMode, ); this.fetchStructureState = fetchStructureState; this.filterState = new QueryBuilderFilterState( this.editorStore, this, this.filterOperators, ); this.resultSetModifierState = new QueryResultSetModifierState( this.editorStore, this, ); const resultState = new QueryBuilderResultState(this.editorStore, this); resultState.setPreviewLimit(this.resultState.previewLimit); this.resultState = resultState; this.queryTextEditorState = new QueryTextEditorState( this.editorStore, this, ); this.queryUnsupportedState = new QueryBuilderUnsupportedState( this.editorStore, this, ); this.explorerState.refreshTreeData(); this.fetchStructureState.graphFetchTreeState.init(); } setQuerySetupState(val: QueryBuilderSetupState): void { this.querySetupState = val; } init(rawLambda: RawLambda, options?: { notifyError: boolean }): void { try { this.buildStateFromRawLambda(rawLambda); } catch (error: unknown) { this.querySetupState.setClass(undefined, true); this.resetData(); assertErrorThrown(error); if (options?.notifyError) { this.editorStore.applicationStore.notifyError( `Unable to initialize query builder: ${error.message}`, ); } this.queryUnsupportedState.setLambdaError(error); this.queryUnsupportedState.setRawLambda(rawLambda); } } /** * Process the raw lambda, and build the query builder state. * * @throws error if there is an issue building the compiled lambda or rebuilding the state. * consumers of function should handle the errors. */ buildStateFromRawLambda(rawLambda: RawLambda): void { this.resetData(); if (!rawLambda.isStub) { const valueSpec = this.editorStore.graphState.graphManager.buildValueSpecification( this.editorStore.graphState.graphManager.serializeRawValueSpecification( rawLambda, ), this.editorStore.graphState.graph, ); const compiledValueSpecification = guaranteeType( valueSpec, LambdaFunctionInstanceValue, ); const compiledLambda = guaranteeNonNullable( compiledValueSpecification.values[0], ); compiledLambda.expressionSequence.map((e) => e.accept_ValueSpecificationVisitor( new QueryBuilderLambdaProcessor(this, undefined), ), ); } } buildRawLambdaFromLambdaFunction(lambdaFunction: LambdaFunction): RawLambda { const lambdaFunctionInstanceValue = new LambdaFunctionInstanceValue( this.editorStore.graphState.graph.getTypicalMultiplicity( TYPICAL_MULTIPLICITY_TYPE.ONE, ), undefined, ); lambdaFunctionInstanceValue.values = [lambdaFunction]; return guaranteeType( this.editorStore.graphState.graphManager.buildRawValueSpecification( lambdaFunctionInstanceValue, this.editorStore.graphState.graph, ), RawLambda, ); } async saveQuery(): Promise<void> { const onQuerySave = this.querySetupState.onSave; if (onQuerySave) { try { const rawLambda = this.getQuery(); await onQuerySave(rawLambda); } catch (error: unknown) { assertErrorThrown(error); this.editorStore.applicationStore.notifyError( `Unable to save query: ${error.message}`, ); } } } isQuerySupported(): boolean { return !this.queryUnsupportedState.rawLambda; } clearCompilationError(): void { this.fetchStructureState.projectionState.clearCompilationError(); } *compileQuery(this: QueryBuilderState): GeneratorFn<void> { if (this.openQueryBuilder) { if (!this.queryTextEditorState.mode) { this.isCompiling = true; this.clearCompilationError(); // form mode try { this.queryTextEditorState.setCompilationError(undefined); // NOTE: retain the source information on the lambda in order to be able // to pin-point compilation issue in form mode (yield this.editorStore.graphState.graphManager.getLambdaReturnType( this.getQuery({ keepSourceInformation: true }), this.editorStore.graphState.graph, { keepSourceInformation: true }, )) as string; this.editorStore.applicationStore.notifySuccess( 'Compiled sucessfully', ); } catch (error: unknown) { assertErrorThrown(error); this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.COMPILATION_PROBLEM, error, ); let fallbackToTextModeForDebugging = true; // if compilation failed, we try to reveal the error in form mode, // if even this fail, we will fall back to show it in text mode if (error instanceof CompilationError && error.sourceInformation) { fallbackToTextModeForDebugging = !this.fetchStructureState.projectionState.revealCompilationError( error, ); } // decide if we need to fall back to text mode for debugging if (fallbackToTextModeForDebugging) { this.editorStore.applicationStore.notifyWarning( 'Compilation failed and error cannot be located in form mode. Redirected to text mode for debugging.', ); this.queryTextEditorState.openModal(QueryTextEditorMode.TEXT); // TODO: trigger another compilation to pin-point the issue // since we're using the lambda editor right now, we are a little bit limitted // in terms of the timing to do compilation (since we're using an `useEffect` to // convert the lambda to grammar text), we might as well wait for the refactor // of query builder text-mode // See https://github.com/finos/legend-studio/issues/319 // try { // const code = (yield this.graphManager.graphToPureCode( // this.graph, // )) as string; // this.editorStore.grammarTextEditorState.setGraphGrammarText(code); // } catch (error2: unknown) { // assertErrorThrown(error2); // this.editorStore.applicationStore.notifyWarning( // `Can't enter text mode. Transformation to grammar text failed: ${error2.message}`, // ); // return; // } // this.editorStore.setGraphEditMode(GRAPH_EDITOR_MODE.GRAMMAR_TEXT); // yield this.globalCompileInTextMode({ // ignoreBlocking: true, // suppressCompilationFailureMessage: true, // }); } else { this.editorStore.applicationStore.notifyWarning( `Compilation failed: ${error.message}`, ); } } finally { this.isCompiling = false; } } else if (this.queryTextEditorState.mode === QueryTextEditorMode.TEXT) { this.isCompiling = true; try { this.queryTextEditorState.setCompilationError(undefined); (yield this.editorStore.graphState.graphManager.getLambdaReturnType( this.queryTextEditorState.rawLambdaState.lambda, this.editorStore.graphState.graph, { keepSourceInformation: true }, )) as string; this.editorStore.applicationStore.notifySuccess( 'Compiled sucessfully', ); } catch (error: unknown) { assertErrorThrown(error); if (error instanceof CompilationError) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.COMPILATION_PROBLEM, error, ); this.editorStore.applicationStore.notifyWarning( `Compilaion failed: ${error.message}`, ); const errorElementCoordinates = extractSourceInformationCoordinates( error.sourceInformation, ); if (errorElementCoordinates) { this.queryTextEditorState.setCompilationError(error); } } } finally { this.isCompiling = false; } } } } }
nayanika2/legend-studio
packages/legend-studio/src/stores/ChangeDetectionState.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { IReactionDisposer } from 'mobx'; import { observable, action, reaction, flow, makeObservable } from 'mobx'; import { CORE_LOG_EVENT } from '../utils/Logger'; import type { GeneratorFn } from '@finos/legend-studio-shared'; import { IllegalStateError, shallowStringify, noop, assertErrorThrown, hashObject, } from '@finos/legend-studio-shared'; import type { EditorStore } from './EditorStore'; import type { GraphState } from './GraphState'; import { EntityDiff } from '../models/sdlc/models/comparison/EntityDiff'; import { EntityChangeType } from '../models/sdlc/models/entity/EntityChange'; import type { Entity } from '../models/sdlc/models/entity/Entity'; import type { EntityChangeConflictResolution } from '../models/sdlc/models/entity/EntityChangeConflict'; import { EntityChangeConflict } from '../models/sdlc/models/entity/EntityChangeConflict'; class RevisionChangeDetectionState { editorStore: EditorStore; graphState: GraphState; changes: EntityDiff[] = []; entityHashesIndex = new Map<string, string>(); isBuildingEntityHashesIndex = false; entities: Entity[] = []; setEntityHashesIndex(hashesIndex: Map<string, string>): void { this.entityHashesIndex = hashesIndex; } setIsBuildingEntityHashesIndex(building: boolean): void { this.isBuildingEntityHashesIndex = building; } setEntities(entities: Entity[]): void { this.entities = entities; } constructor(editorStore: EditorStore, graphState: GraphState) { makeObservable(this, { changes: observable.ref, entityHashesIndex: observable.ref, entities: observable.ref, isBuildingEntityHashesIndex: observable, setEntityHashesIndex: action, setIsBuildingEntityHashesIndex: action, setEntities: action, }); this.editorStore = editorStore; this.graphState = graphState; } computeChanges = flow(function* ( this: RevisionChangeDetectionState, quiet?: boolean, ) { const startTime = Date.now(); let changes: EntityDiff[] = []; if (!this.isBuildingEntityHashesIndex) { const originalPaths = new Set(Array.from(this.entityHashesIndex.keys())); if (this.graphState.graph.allOwnElements.length) { yield Promise.all<void>( this.graphState.graph.allOwnElements.map( (element) => new Promise((resolve) => setTimeout(() => { const elementPath = element.path; const originalElementHash = this.entityHashesIndex.get(elementPath); if (!originalElementHash) { changes.push( new EntityDiff( undefined, elementPath, EntityChangeType.CREATE, ), ); } else if (originalElementHash !== element.hashCode) { changes.push( new EntityDiff( elementPath, elementPath, EntityChangeType.MODIFY, ), ); } originalPaths.delete(elementPath); resolve(); }, 0), ), ), ); } changes = changes.concat( Array.from(originalPaths).map( (path) => new EntityDiff(path, undefined, EntityChangeType.DELETE), ), ); } this.changes = changes; if (!quiet) { this.editorStore.applicationStore.logger.info( CORE_LOG_EVENT.GRAPH_CHANGES_DETECTED, Date.now() - startTime, 'ms', ); } }); buildEntityHashesIndex = flow(function* ( this: RevisionChangeDetectionState, entities: Entity[], logEvent: CORE_LOG_EVENT, quiet?: boolean, ) { if (!this.entities.length && !this.entityHashesIndex.size) { return; } const startTime = Date.now(); this.setIsBuildingEntityHashesIndex(true); try { const hashesIndex = (yield this.graphState.graphManager.buildHashesIndex( entities, )) as Map<string, string>; this.setEntityHashesIndex(hashesIndex); this.setIsBuildingEntityHashesIndex(false); if (!quiet) { this.editorStore.applicationStore.logger.info( logEvent, '[ASYNC]', Date.now() - startTime, 'ms', ); } } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.CHANGE_DETECTION_PROBLEM, `Can't build hashes index`, ); this.setEntityHashesIndex(new Map<string, string>()); this.setIsBuildingEntityHashesIndex(false); assertErrorThrown(error); throw new IllegalStateError(error); } finally { this.setIsBuildingEntityHashesIndex(false); } }); } /** * In the SDLC flow of the app, there are several important revision that we want to keep track of. See diagram below: * * (1. PJL) * | * | * (2. CRB) ------- (3. CRH) ------ (4. CRL) * | * | * (5. WSB) ------- (6. WSH) ------ (7. WSL) * | * ... (earlier revisions in the project) * * Annotations: * 1. PJL: Project HEAD revision * 2. CRB: Conflict resolution BASE revision * 3. CRH: Conflict resolution HEAD revision * 4. CRL: Conflict resolution LIVE revision (i.e. local graph state in conflict resolution mode) * 5. WSB: Workspace BASE revision * 6. WSH: Workspace HEAD revision * 7. WSL: Workspace LIVE revision (i.e. local graph state in standard mode) */ export class ChangeDetectionState { editorStore: EditorStore; graphState: GraphState; isChangeDetectionRunning = false; hasChangeDetectionStarted = false; forcedStop = false; changeDetectionReaction?: IReactionDisposer; /** * [1. PJL] Store the entities from project HEAD (i.e. project latest revision) * This can be used to compute changes for a review as well as changes and potential conflicts when updating workspace */ projectLatestRevisionState: RevisionChangeDetectionState; /** * [2. CRB] Store the entities from the BASE revision of workspace with conflict resolution (this is different from the current workspace the user is on) * NOTE: the flow for conflict resolution is briefly like this (assume current user workspace is `w1`): * 1. When the user chooses to update workspace `w1`, the backend will compute changes between `w1` HEAD and `w1` BASE * 2. Create a new conflict resolution branch on top of project HEAD * 3. Apply the changes on this branch. * * So we now have 2 branchs normal `w1` and `w1` in conflict resolution. From the user perspective, they might not need to know this * So in the app, we have to check for the existence of the conflict resolution branch and make it supercede the original `w1` branch * * This branch, thus, will be used to show the users all the changes they have on top of conflict resolution BASE revision * during conflict resolution stage */ conflictResolutionBaseRevisionState: RevisionChangeDetectionState; /** * [3. CRH] Store the entities from the conflict resolution HEAD revision * This is used for computing the live diff, so that when we mark conflicts as resolved and accept conflict resolution * we can compute the entity changes */ conflictResolutionHeadRevisionState: RevisionChangeDetectionState; /** * [5. WSB] Store the entities from workspace BASE revision * This can be used for conflict resolution */ workspaceBaseRevisionState: RevisionChangeDetectionState; /** * [6. WSH] Store the entities from current workspace HEAD revision * This can be used for computing local changes/live diffs (i.e. changes between local graph and workspace HEAD) */ workspaceLatestRevisionState: RevisionChangeDetectionState; aggregatedWorkspaceChanges: EntityDiff[] = []; // review/merge-request changes aggregatedProjectLatestChanges: EntityDiff[] = []; // project latest changes - used for updating workspace potentialWorkspaceUpdateConflicts: EntityChangeConflict[] = []; // potential conflicts when updating workspace (derived from aggregated workspace changes and project latest changes) /** * For conflict resolution, the procedure is split into 2 steps: * 1. The user resolves conflicts (no graph is built at this point) * 2. The user marks all conflicts as resolved and starts building the graph to fix any residual problems * * Ideally, we would like to use the live diff (conflict resolution BASE <-> local graph), but since for step 1 * we do not build the graph, this is not possible, so we have to use the following to store the diff until we move to step 2 */ aggregatedConflictResolutionChanges: EntityDiff[] = []; conflicts: EntityChangeConflict[] = []; // conflicts in conflict resolution mode (derived from aggregated workspace changes and conflict resolution changes) resolutions: EntityChangeConflictResolution[] = []; constructor(editorStore: EditorStore, graphState: GraphState) { makeObservable(this, { isChangeDetectionRunning: observable, hasChangeDetectionStarted: observable, forcedStop: observable, resolutions: observable, projectLatestRevisionState: observable.ref, conflictResolutionBaseRevisionState: observable.ref, conflictResolutionHeadRevisionState: observable.ref, workspaceBaseRevisionState: observable.ref, workspaceLatestRevisionState: observable.ref, aggregatedWorkspaceChanges: observable.ref, aggregatedProjectLatestChanges: observable.ref, potentialWorkspaceUpdateConflicts: observable.ref, aggregatedConflictResolutionChanges: observable.ref, conflicts: observable.ref, setAggregatedProjectLatestChanges: action, setPotentialWorkspaceUpdateConflicts: action, stop: action, start: action, }); this.editorStore = editorStore; this.graphState = graphState; this.workspaceLatestRevisionState = new RevisionChangeDetectionState( editorStore, graphState, ); this.workspaceBaseRevisionState = new RevisionChangeDetectionState( editorStore, graphState, ); this.projectLatestRevisionState = new RevisionChangeDetectionState( editorStore, graphState, ); // conflict resolution this.conflictResolutionHeadRevisionState = new RevisionChangeDetectionState( editorStore, graphState, ); this.conflictResolutionBaseRevisionState = new RevisionChangeDetectionState( editorStore, graphState, ); } setAggregatedProjectLatestChanges(diffs: EntityDiff[]): void { this.aggregatedProjectLatestChanges = diffs; } setPotentialWorkspaceUpdateConflicts( conflicts: EntityChangeConflict[], ): void { this.potentialWorkspaceUpdateConflicts = conflicts; } stop(force = false): void { this.changeDetectionReaction?.(); this.changeDetectionReaction = undefined; this.isChangeDetectionRunning = false; if (force) { this.forcedStop = true; } } /** * The change detection check is not free, although due to the power of mobx's computed, this is really fast * but we want to use a reaction here instead of having changes as a computed getter is that: * 1. We want to debounce the action * 2. We want to control when we would start observing for changes (this is useful since we need to compute the initial * hashes index before this, otherwise users will get false report about the number of changes) * This function might cause the UI to jank the since it involves expensive computation of the all the elements' hashes * for the first time. Currently there is no workaround so we might need to comeback and evaluate this */ start(): void { this.changeDetectionReaction?.(); /** * It seems like the reaction action is not always called in tests, causing fluctuation in * code coverage report for this file. As such, for test, we would want to disable throttling * to avoid timing issue. * * See https://docs.codecov.io/docs/unexpected-coverage-changes * See https://community.codecov.io/t/codecov-reporting-impacted-files-for-unchanged-and-completely-unrelated-file/2635 */ // eslint-disable-next-line no-process-env const throttleDuration = process.env.NODE_ENV === 'test' ? 0 : 1000; /** * For the reaction, the data we observe is the snapshot of the current hashes, note that we can also use the hashCode * of the root package although this might get interesting in the future when we introduce project dependency or * auto-gen elements... * * Whichever form of this, it will have to loop through all elements' and compute the hashCode for the first time * so in subsequent calls this could be fast. This is heavy and the only technique to make this happen is to break * it down into small promises, but this is not possible in mobx as mobx only tracks dependency synchronously. * See https://github.com/danielearwicker/computed-async-mobx#gotchas * See https://github.com/mobxjs/mobx/issues/668 * See https://github.com/mobxjs/mobx/issues/872 * SO, we have 2 options here: * 1. We can let the UI freezes up for a short while, like this: * this.snapshotCurrentHashesIndex(true); * OR * 2. We will use `keepAlive` for elements that we care about for building the hashes index, i.e. class, mapping, diagram, etc. * * NOTE: IMPORTANT: Although we have to note the caveat of `keepAlive` is that it can cause memory leak, which requires us * to dispose them properly, see `disposeComputedHash` in `PackageableElement` */ this.changeDetectionReaction = reaction( // to be safe, rather than just giving the reaction the hash index snapshot to watch, we hash the snapshot content () => hashObject( Array.from(this.snapshotLocalEntityHashesIndex(true).entries()) .sort((a, b) => a[0].localeCompare(b[0])) // sort to ensure this array order does not affect change detection status .map(([key, value]) => `${key}@${value}`), ), () => { this.computeLocalChanges(true).catch(noop()); }, { delay: throttleDuration }, // throttle the call /** * NOTE: this reaction will not be fired immediately so we have to manually call the first local changes computation * See https://mobx.js.org/refguide/reaction.html#options */ ); this.isChangeDetectionRunning = true; this.hasChangeDetectionStarted = true; this.forcedStop = false; } snapshotLocalEntityHashesIndex(quiet?: boolean): Map<string, string> { const startTime = Date.now(); const snapshot = new Map<string, string>(); this.graphState.graph.allOwnElements.forEach((el) => snapshot.set(el.path, el.hashCode), ); if (!quiet) { this.editorStore.applicationStore.logger.info( CORE_LOG_EVENT.GRAPH_HASH_SNAPSHOTED, Date.now() - startTime, 'ms', ); } return snapshot; } private computeAggregatedChangesBetweenStates = async ( fromState: RevisionChangeDetectionState, toState: RevisionChangeDetectionState, quiet?: boolean, ): Promise<EntityDiff[]> => { const startTime = Date.now(); let changes: EntityDiff[] = []; if ( !fromState.isBuildingEntityHashesIndex && !toState.isBuildingEntityHashesIndex ) { const originalPaths = new Set( Array.from(fromState.entityHashesIndex.keys()), ); await Promise.all<void>( Array.from(toState.entityHashesIndex.entries()).map( ([elementPath, hashCode]) => new Promise((resolve) => setTimeout(() => { const originalElementHashCode = fromState.entityHashesIndex.get(elementPath); if (!originalElementHashCode) { changes.push( new EntityDiff( undefined, elementPath, EntityChangeType.CREATE, ), ); } else if (originalElementHashCode !== hashCode) { changes.push( new EntityDiff( elementPath, elementPath, EntityChangeType.MODIFY, ), ); } originalPaths.delete(elementPath); resolve(); }, 0), ), ), ); changes = changes.concat( Array.from(originalPaths).map( (path) => new EntityDiff(path, undefined, EntityChangeType.DELETE), ), ); if (!quiet) { this.editorStore.applicationStore.logger.info( CORE_LOG_EVENT.GRAPH_CHANGES_DETECTED, Date.now() - startTime, 'ms', ); } } return changes; }; computeAggregatedWorkspaceChanges = flow(function* ( this: ChangeDetectionState, quiet?: boolean, ) { this.aggregatedWorkspaceChanges = (yield this.computeAggregatedChangesBetweenStates( this.workspaceBaseRevisionState, this.workspaceLatestRevisionState, quiet, )) as EntityDiff[]; yield Promise.all([ this.computeWorkspaceUpdateConflicts(quiet), this.computeConflictResolutionConflicts(quiet), ]); }); computeAggregatedProjectLatestChanges = flow(function* ( this: ChangeDetectionState, quiet?: boolean, ) { this.aggregatedProjectLatestChanges = (yield this.computeAggregatedChangesBetweenStates( this.workspaceBaseRevisionState, this.projectLatestRevisionState, quiet, )) as EntityDiff[]; yield this.computeWorkspaceUpdateConflicts(quiet); }); computeAggregatedConflictResolutionChanges = flow(function* ( this: ChangeDetectionState, quiet?: boolean, ) { this.aggregatedConflictResolutionChanges = (yield this.computeAggregatedChangesBetweenStates( this.conflictResolutionBaseRevisionState, this.conflictResolutionHeadRevisionState, quiet, )) as EntityDiff[]; }); /** * Workspace update conflicts are computed between 2 sets of changes: * 1. Incoming changes: changes between workspace BASE revision and project LATEST revision * 2. Current changes: changes between worksace BASE revision and workspace HEAD revision */ computeWorkspaceUpdateConflicts = flow(function* ( this: ChangeDetectionState, quiet?: boolean, ) { const startTime = Date.now(); this.potentialWorkspaceUpdateConflicts = (yield this.computeEntityChangeConflicts( this.aggregatedWorkspaceChanges, this.aggregatedProjectLatestChanges, this.workspaceLatestRevisionState.entityHashesIndex, this.projectLatestRevisionState.entityHashesIndex, )) as EntityChangeConflict[]; if (!quiet) { this.editorStore.applicationStore.logger.info( CORE_LOG_EVENT.CHANGE_DETECTION_WORKSPACE_UPDATE_CONFLICTS_COMPUTED, Date.now() - startTime, 'ms', ); } }); /** * Conflict resolution conflicts are computed between 2 sets of changes: * 1. Incoming changes: changes between workspace BASE revision and conflict resolution BASE revision * 2. Current changes: changes between worksace BASE revision and workspace HEAD revision */ computeConflictResolutionConflicts = flow(function* ( this: ChangeDetectionState, quiet?: boolean, ) { const aggregatedUpdateChanges = (yield this.computeAggregatedChangesBetweenStates( this.workspaceBaseRevisionState, this.conflictResolutionBaseRevisionState, quiet, )) as EntityDiff[]; const startTime = Date.now(); this.conflicts = (yield this.computeEntityChangeConflicts( this.aggregatedWorkspaceChanges, aggregatedUpdateChanges, this.workspaceLatestRevisionState.entityHashesIndex, this.conflictResolutionBaseRevisionState.entityHashesIndex, )) as EntityChangeConflict[]; if (!quiet) { this.editorStore.applicationStore.logger.info( CORE_LOG_EVENT.CHANGE_DETECTION_CONFLICT_RESOLUTION_CONFLICTS_COMPUTED, Date.now() - startTime, 'ms', ); } }); /** * This function computes the entity change conflicts between 2 set of entity changes (let's call them incoming changes and current changes). * For a more comprehensive explanation, we take a look at how we can use this to compute potential conflicts during workspace update: * * To compute potential conflicts during workspace update, we must base off the project latest changes [incChg] (worksapce BASE <-> project HEAD) * and the merge request changes [currChng] (workspace BASE <-> workspace HEAD). We have a case table below (`N.A.` means it's impossible cases) * For cases we with `conflict` there might be potential conflicts as the change to the entity appear in both [incChg] and [currChng]. But we must * note that this is `potential` because we cannot be too sure how SDCL server handle merging these during update. * * NOTE: it's important to remember that these are truly potential conflicts, because of git merge mechanism, * it will apply one intermediate commit at a time, this means that if, we have a file A: * * Workspace change: 1. A is deleted; 2. A is created with content `a` * Project latest change: 1. A is modified with content `a` * * These could mean no conflict from our computation but is a conflict when Git tries to merge. * * NOTE: Also, there could be strange case for SVN that a file can be DELETED and CREATED, it's called "replace". * * | [incChg] | | | | * ----------------------------------------------------------- * [currChng] | | CREATE | DELETE | MODIFY | * ----------------------------------------------------------- * | CREATE | conflict | N.A. | N.A. | * ----------------------------------------------------------- * | DELETE | N.A. | none | conflict | * ----------------------------------------------------------- * | MODIFY | N.A. | conflict | conflict | * ----------------------------------------------------------- */ computeEntityChangeConflicts = flow(function* ( this: ChangeDetectionState, currentChanges: EntityDiff[], incomingChanges: EntityDiff[], currentChangeEntityHashesIndex: Map<string, string>, incomingChangeEntityHashesIndex: Map<string, string>, ): GeneratorFn<EntityChangeConflict[]> { const conflicts: EntityChangeConflict[] = []; const currentChangesMap = currentChanges.reduce( (diffMap, currentDiff) => diffMap.set(currentDiff.entityPath, currentDiff), new Map<string, EntityDiff>(), ); const incomingChangesMap = incomingChanges.reduce( (diffMap, currentDiff) => diffMap.set(currentDiff.entityPath, currentDiff), new Map<string, EntityDiff>(), ); yield Promise.all<void>( Array.from(incomingChangesMap.entries()).map( ([entityPath, incomingChange]: [string, EntityDiff]) => new Promise((resolve) => setTimeout(() => { const currentChange = currentChangesMap.get(entityPath); // find the change on the same entity in the set of current changes if (currentChange) { if ( (currentChange.entityChangeType === EntityChangeType.CREATE && incomingChange.entityChangeType === EntityChangeType.CREATE) || (currentChange.entityChangeType === EntityChangeType.MODIFY && incomingChange.entityChangeType === EntityChangeType.MODIFY) ) { // if the two entities are identical, we can guarantee no conflict happens, otherwise, depending on the SDLC server, we might get a conflict. // NOTE: we actually want the potential conflict to be a real conflict in this case because SDLC server while attempting to merge the protocol JSON // might actually mess up the entity, which is very bad if ( currentChangeEntityHashesIndex.get(entityPath) !== incomingChangeEntityHashesIndex.get(entityPath) ) { conflicts.push( new EntityChangeConflict( entityPath, incomingChange, currentChange, ), ); } } else if ( (currentChange.entityChangeType === EntityChangeType.DELETE && incomingChange.entityChangeType === EntityChangeType.MODIFY) || (currentChange.entityChangeType === EntityChangeType.MODIFY && incomingChange.entityChangeType === EntityChangeType.DELETE) ) { conflicts.push( new EntityChangeConflict( entityPath, incomingChange, currentChange, ), ); } else if ( currentChange.entityChangeType === EntityChangeType.DELETE && incomingChange.entityChangeType === EntityChangeType.DELETE ) { // do nothing } else { throw new IllegalStateError( `Detected unfeasible state while computing entity change conflict for entity '${entityPath}', with current change: ${shallowStringify( currentChange, )}, and incoming change: ${shallowStringify( incomingChange, )}`, ); } } resolve(); }, 0), ), ), ); return conflicts; }); /** * NOTE: here we have not dealt with non-entity changes like project dependency for example. * We will have to count that as part of the change in the future. */ computeLocalChanges = flow(function* ( this: ChangeDetectionState, quiet?: boolean, ) { const startTime = Date.now(); yield Promise.all([ this.workspaceLatestRevisionState.computeChanges(quiet), // for local changes detection this.conflictResolutionBaseRevisionState.computeChanges(quiet), // for conflict resolution changes detection ]); if (!quiet) { this.editorStore.applicationStore.logger.info( CORE_LOG_EVENT.GRAPH_CHANGES_DETECTED, Date.now() - startTime, 'ms', ); } }); }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/transformation/pureGraph/from/executionPlan/V1_ExecutionPlanTransformer.ts
<gh_stars>0 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { guaranteeType, UnsupportedOperationError, } from '@finos/legend-studio-shared'; import type { ExecutionPlan } from '../../../../../../../metamodels/pure/model/executionPlan/ExecutionPlan'; import type { ExecutionNode } from '../../../../../../../metamodels/pure/model/executionPlan/nodes/ExecutionNode'; import { RelationalTDSInstantiationExecutionNode } from '../../../../../../../metamodels/pure/model/executionPlan/nodes/RelationalInstantiationExecutionNode'; import { SQLExecutionNode } from '../../../../../../../metamodels/pure/model/executionPlan/nodes/SQLExecutionNode'; import type { SQLResultColumn } from '../../../../../../../metamodels/pure/model/executionPlan/nodes/SQLResultColumn'; import { Real, Binary, Bit, Other, Date, Timestamp, Numeric, Decimal, VarBinary, Char, VarChar, Double, Float, Integer, TinyInt, SmallInt, BigInt, DataType, } from '../../../../../../../metamodels/pure/model/packageableElements/store/relational/model/RelationalDataType'; import type { V1_ExecutionNode } from '../../../../model/executionPlan/nodes/V1_ExecutionNode'; import { V1_RelationalTDSInstantiationExecutionNode } from '../../../../model/executionPlan/nodes/V1_RelationalTDSInstantiationExecutionNode'; import { V1_SQLExecutionNode } from '../../../../model/executionPlan/nodes/V1_SQLExecutionNode'; import { V1_SQLResultColumn } from '../../../../model/executionPlan/nodes/V1_SQLResultColumn'; import type { V1_ExecutionPlan } from '../../../../model/executionPlan/V1_ExecutionPlan'; import type { V1_GraphTransformerContext } from '../V1_GraphTransformerContext'; import type { V1_ResultType } from '../../../../model/executionPlan/results/V1_ResultType'; import type { ResultType } from '../../../../../../../metamodels/pure/model/executionPlan/result/ResultType'; import { V1_DataTypeResultType } from '../../../../model/executionPlan/results/V1_DataTypeResultType'; import { V1_TDSResultType } from '../../../../model/executionPlan/results/V1_TDSResultType'; import { DataTypeResultType } from '../../../../../../../metamodels/pure/model/executionPlan/result/DataTypeResultType'; import { TDSResultType } from '../../../../../../../metamodels/pure/model/executionPlan/result/TDSResultType'; import type { TDSColumn } from '../../../../../../../metamodels/pure/model/executionPlan/result/TDSColumn'; import { V1_TDSColumn } from '../../../../model/executionPlan/results/V1_TDSColumn'; import { CLIENT_VERSION } from '../../../../../../../MetaModelConst'; import { V1_SimpleExecutionPlan } from '../../../../model/executionPlan/V1_SimpleExecutionPlan'; import { V1_Protocol } from '../../../../model/V1_Protocol'; import { V1_transformMultiplicity } from '../V1_CoreTransformerHelper'; import { V1_transformConnection } from '../V1_ConnectionTransformer'; import { V1_DatabaseConnection } from '../../../../model/packageableElements/store/relational/connection/V1_RelationalDatabaseConnection'; const stringifyDataType = (dataType: DataType): string => { if (dataType instanceof Integer) { return 'INTEGER'; } else if (dataType instanceof Float) { return 'FLOAT'; } else if (dataType instanceof Double) { return 'DOUBLE'; } else if (dataType instanceof Real) { return 'REAL'; } else if (dataType instanceof Timestamp) { return 'TIMESTAMP'; } else if (dataType instanceof Date) { return 'DATE'; } else if (dataType instanceof BigInt) { return 'BIGINT'; } else if (dataType instanceof SmallInt) { return 'SMALLINT'; } else if (dataType instanceof TinyInt) { return 'TINYINT'; } else if (dataType instanceof Bit) { return 'BIT'; } else if (dataType instanceof Other) { return 'OTHER'; } else if (dataType instanceof VarChar) { return `VARCHAR(${dataType.size})`; } else if (dataType instanceof Char) { return `CHAR(${dataType.size})`; } else if (dataType instanceof VarBinary) { return `VARBINARY(${dataType.size})`; } else if (dataType instanceof Binary) { return `BINARY(${dataType.size})`; } else if (dataType instanceof Decimal) { return `DECIMAL(${dataType.precision},${dataType.scale})`; } else if (dataType instanceof Numeric) { return `NUMERIC(${dataType.precision},${dataType.scale})`; } throw new UnsupportedOperationError( `Can't stringify relational data type`, dataType, ); }; // ---------------------------------------- Result Type ---------------------------------------- const transformDataTypeResultType = ( metamodel: DataTypeResultType, context: V1_GraphTransformerContext, ): V1_DataTypeResultType => { const protocol = new V1_DataTypeResultType(); protocol.dataType = metamodel.type.valueForSerialization; return protocol; }; const transformTDSColumn = ( metamodel: TDSColumn, context: V1_GraphTransformerContext, ): V1_TDSColumn => { const protocol = new V1_TDSColumn(); protocol.name = metamodel.name; protocol.doc = metamodel.documentation; protocol.type = metamodel.type?.valueForSerialization; protocol.relationalType = metamodel.sourceDataType instanceof DataType ? stringifyDataType(metamodel.sourceDataType) : undefined; return protocol; }; const transformTDSResultType = ( metamodel: TDSResultType, context: V1_GraphTransformerContext, ): V1_TDSResultType => { const protocol = new V1_TDSResultType(); protocol.tdsColumns = metamodel.tdsColumns.map((column) => transformTDSColumn(column, context), ); return protocol; }; const transformResultType = ( metamodel: ResultType, context: V1_GraphTransformerContext, ): V1_ResultType => { if (metamodel instanceof DataTypeResultType) { return transformDataTypeResultType(metamodel, context); } else if (metamodel instanceof TDSResultType) { return transformTDSResultType(metamodel, context); } throw new UnsupportedOperationError( `Can't transform execution node result type`, metamodel, ); }; // ---------------------------------------- Execution Node ---------------------------------------- const transformSQLResultColumn = ( metamodel: SQLResultColumn, ): V1_SQLResultColumn => { const protocol = new V1_SQLResultColumn(); protocol.label = metamodel.label; protocol.dataType = metamodel.dataType ? stringifyDataType(metamodel.dataType) : ''; // this is to make sure to be consistent with the way Pure generates plan protocol return protocol; }; const transformBaseExecutionNode = ( metamodel: ExecutionNode, protocol: V1_ExecutionNode, context: V1_GraphTransformerContext, ): void => { protocol.resultSizeRange = metamodel.resultSizeRange ? V1_transformMultiplicity(metamodel.resultSizeRange) : undefined; protocol.resultType = transformResultType(metamodel.resultType, context); protocol.executionNodes = metamodel.executionNodes.map((node) => V1_transformExecutionNode(node, context), ); }; const transformSQLExecutionNode = ( metamodel: SQLExecutionNode, context: V1_GraphTransformerContext, ): V1_SQLExecutionNode => { const protocol = new V1_SQLExecutionNode(); transformBaseExecutionNode(metamodel, protocol, context); protocol.sqlQuery = metamodel.sqlQuery; protocol.onConnectionCloseCommitQuery = metamodel.onConnectionCloseCommitQuery; protocol.onConnectionCloseRollbackQuery = metamodel.onConnectionCloseRollbackQuery; protocol.connection = guaranteeType( V1_transformConnection(metamodel.connection, true, context), V1_DatabaseConnection, 'SQL execution node connection must be of type database connection', ); protocol.resultColumns = metamodel.resultColumns.map( transformSQLResultColumn, ); return protocol; }; const transformRelationalTDSInstantiationExecutionNode = ( metamodel: RelationalTDSInstantiationExecutionNode, context: V1_GraphTransformerContext, ): V1_RelationalTDSInstantiationExecutionNode => { const protocol = new V1_RelationalTDSInstantiationExecutionNode(); transformBaseExecutionNode(metamodel, protocol, context); return protocol; }; export function V1_transformExecutionNode( metamodel: ExecutionNode, context: V1_GraphTransformerContext, ): V1_ExecutionNode { if (metamodel instanceof SQLExecutionNode) { return transformSQLExecutionNode(metamodel, context); } else if (metamodel instanceof RelationalTDSInstantiationExecutionNode) { return transformRelationalTDSInstantiationExecutionNode(metamodel, context); } throw new UnsupportedOperationError( `Can't transform execution node`, metamodel, ); } // ---------------------------------------- Execution Plan ---------------------------------------- export const V1_transformExecutionPlan = ( metamodel: ExecutionPlan, context: V1_GraphTransformerContext, ): V1_ExecutionPlan => { const protocol = new V1_SimpleExecutionPlan(); protocol.serializer = new V1_Protocol('pure', CLIENT_VERSION.VX_X_X); protocol.authDependent = metamodel.authDependent; protocol.kerberos = metamodel.kerberos; protocol.templateFunctions = metamodel.processingTemplateFunctions; protocol.rootExecutionNode = V1_transformExecutionNode( metamodel.rootExecutionNode, context, ); return protocol; };
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/transformation/pureGraph/to/V1_ProtocolToMetaModelGraphFourthPassBuilder.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { UnsupportedOperationError } from '@finos/legend-studio-shared'; import type { V1_GraphBuilderContext } from './V1_GraphBuilderContext'; import type { V1_PackageableElement, V1_PackageableElementVisitor, } from '../../../model/packageableElements/V1_PackageableElement'; import type { V1_Profile } from '../../../model/packageableElements/domain/V1_Profile'; import type { V1_Enumeration } from '../../../model/packageableElements/domain/V1_Enumeration'; import type { V1_Class } from '../../../model/packageableElements/domain/V1_Class'; import type { V1_ConcreteFunctionDefinition } from '../../../model/packageableElements/function/V1_ConcreteFunctionDefinition'; import type { V1_Association } from '../../../model/packageableElements/domain/V1_Association'; import type { V1_FlatData } from '../../../model/packageableElements/store/flatData/model/V1_FlatData'; import type { V1_Database } from '../../../model/packageableElements/store/relational/model/V1_Database'; import type { V1_Mapping } from '../../../model/packageableElements/mapping/V1_Mapping'; import type { V1_Service } from '../../../model/packageableElements/service/V1_Service'; import type { V1_Diagram } from '../../../model/packageableElements/diagram/V1_Diagram'; import { V1_ProtocolToMetaModelClassMappingSecondPassBuilder } from './V1_ProtocolToMetaModelClassMappingSecondPassBuilder'; import { V1_buildMappingTest, V1_resolveClassMappingRoot, } from './helpers/V1_MappingBuilderHelper'; import type { V1_PackageableRuntime } from '../../../model/packageableElements/runtime/V1_PackageableRuntime'; import type { V1_PackageableConnection } from '../../../model/packageableElements/connection/V1_PackageableConnection'; import type { V1_FileGenerationSpecification } from '../../../model/packageableElements/fileGeneration/V1_FileGenerationSpecification'; import type { V1_GenerationSpecification } from '../../../model/packageableElements/generationSpecification/V1_GenerationSpecification'; import type { V1_Measure } from '../../../model/packageableElements/domain/V1_Measure'; import { V1_buildDatabaseJoin, V1_buildDatabaseFilter, } from './helpers/V1_DatabaseBuilderHelper'; import type { V1_SectionIndex } from '../../../model/packageableElements/section/V1_SectionIndex'; import type { V1_ServiceStore } from '../../../model/packageableElements/store/relational/V1_ServiceStore'; import { V1_buildAssociationMapping } from './helpers/V1_AssociationMappingHelper'; export class V1_ProtocolToMetaModelGraphFourthPassBuilder implements V1_PackageableElementVisitor<void> { context: V1_GraphBuilderContext; constructor(context: V1_GraphBuilderContext) { this.context = context; } visit_PackageableElement(element: V1_PackageableElement): void { this.context.extensions .getExtraBuilderOrThrow(element) .runFourthPass(element, this.context); } visit_Profile(element: V1_Profile): void { throw new UnsupportedOperationError(); } visit_Enumeration(element: V1_Enumeration): void { throw new UnsupportedOperationError(); } visit_Measure(element: V1_Measure): void { throw new UnsupportedOperationError(); } visit_Class(element: V1_Class): void { // TODO?: milestoning (process properties and class) throw new UnsupportedOperationError(); } visit_Association(element: V1_Association): void { // TODO?: milestoning (process properties) throw new UnsupportedOperationError(); } visit_ConcreteFunctionDefinition( element: V1_ConcreteFunctionDefinition, ): void { throw new UnsupportedOperationError(); } visit_FlatData(element: V1_FlatData): void { this.context.graph.getFlatDataStore( this.context.graph.buildPath(element.package, element.name), ); } visit_Database(element: V1_Database): void { const database = this.context.graph.getDatabase( this.context.graph.buildPath(element.package, element.name), ); database.joins = element.joins.map((join) => V1_buildDatabaseJoin(join, this.context, database), ); database.filters = element.filters.map((filter) => V1_buildDatabaseFilter(filter, this.context, database), ); } visit_ServiceStore(element: V1_ServiceStore): void { this.context.graph.getServiceStore( this.context.graph.buildPath(element.package, element.name), ); } visit_Mapping(element: V1_Mapping): void { const path = this.context.graph.buildPath(element.package, element.name); const mapping = this.context.graph.getMapping(path); mapping.associationMappings = element.associationMappings.map( (_associationMapping) => V1_buildAssociationMapping(_associationMapping, mapping, this.context), ); element.classMappings.forEach((classMapping) => classMapping.accept_ClassMappingVisitor( new V1_ProtocolToMetaModelClassMappingSecondPassBuilder( this.context, mapping, ), ), ); mapping.tests = element.tests.map((test) => V1_buildMappingTest(test, this.context), ); // resolve class mappings root V1_resolveClassMappingRoot(mapping); } visit_Service(element: V1_Service): void { throw new UnsupportedOperationError(); } visit_Diagram(element: V1_Diagram): void { throw new UnsupportedOperationError(); } visit_SectionIndex(element: V1_SectionIndex): void { throw new UnsupportedOperationError(); } visit_FileGeneration(element: V1_FileGenerationSpecification): void { throw new UnsupportedOperationError(); } visit_GenerationSpecification(element: V1_GenerationSpecification): void { throw new UnsupportedOperationError(); } visit_PackageableRuntime(element: V1_PackageableRuntime): void { throw new UnsupportedOperationError(); } visit_PackageableConnection(element: V1_PackageableConnection): void { throw new UnsupportedOperationError(); } }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/transformation/pureProtocol/serializationHelpers/V1_DiagramSerializationHelper.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { createModelSchema, list, optional, primitive } from 'serializr'; import { usingConstantValueSchema, usingModelSchema, } from '@finos/legend-studio-shared'; import { V1_ClassView } from '../../../model/packageableElements/diagram/V1_ClassView'; import { V1_Diagram } from '../../../model/packageableElements/diagram/V1_Diagram'; import { V1_Point } from '../../../model/packageableElements/diagram/geometry/V1_Point'; import { V1_Rectangle } from '../../../model/packageableElements/diagram/geometry/V1_Rectangle'; import { V1_propertyPointerModelSchema } from './V1_DomainSerializationHelper'; import { V1_Line } from '../../../model/packageableElements/diagram/geometry/V1_Line'; import { V1_PropertyView } from '../../../model/packageableElements/diagram/V1_PropertyView'; import { V1_GeneralizationView } from '../../../model/packageableElements/diagram/V1_GeneralizationView'; export const V1_DIAGRAM_ELEMENT_PROTOCOL_TYPE = 'diagram'; const pointModelSchema = createModelSchema(V1_Point, { x: primitive(), y: primitive(), }); const recantagleModelSchema = createModelSchema(V1_Rectangle, { height: primitive(), width: primitive(), }); const lineModelSchema = createModelSchema(V1_Line, { points: list(usingModelSchema(pointModelSchema)), }); const classViewModelSchema = createModelSchema(V1_ClassView, { class: primitive(), hideProperties: optional(primitive()), hideStereotypes: optional(primitive()), hideTaggedValues: optional(primitive()), id: primitive(), position: usingModelSchema(pointModelSchema), rectangle: usingModelSchema(recantagleModelSchema), }); const propertyViewModelSchema = createModelSchema(V1_PropertyView, { line: usingModelSchema(lineModelSchema), property: usingModelSchema(V1_propertyPointerModelSchema), sourceView: primitive(), targetView: primitive(), }); const generalizationViewModelSchema = createModelSchema(V1_GeneralizationView, { line: usingModelSchema(lineModelSchema), sourceView: primitive(), targetView: primitive(), }); export const V1_diagramModelSchema = createModelSchema(V1_Diagram, { _type: usingConstantValueSchema(V1_DIAGRAM_ELEMENT_PROTOCOL_TYPE), classViews: list(usingModelSchema(classViewModelSchema)), generalizationViews: list(usingModelSchema(generalizationViewModelSchema)), name: primitive(), package: primitive(), propertyViews: list(usingModelSchema(propertyViewModelSchema)), });
nayanika2/legend-studio
packages/legend-studio-components/src/components/LegendLogo.tsx
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import clsx from 'clsx'; export const LegendLogo: React.FC<{ className: string; }> = (props) => { const { className } = props; return ( <div className={clsx('logo', className)}> <svg stroke="currentColor" fill="currentColor" strokeWidth="0" width="1em" height="1em" viewBox="0 0 215 215" xmlns="https://www.w3.org/2000/svg" > <g transform="matrix(1.0246,0,0,0.999998,1.03751,2.43115)"> <path d="M141.9,86.5L141.9,68.1C141.9,66.5 140.7,65.2 139.1,65.2L66.5,65.2C64.9,65.2 63.7,66.5 63.7,68.1L63.7,86.5C63.7,88.1 64.9,89.4 66.5,89.4L139.1,89.4C140.7,89.4 141.9,88.1 141.9,86.5Z" /> </g> <g transform="matrix(1.0246,0,0,0.999998,1.03751,2.43115)"> <path d="M118.4,116.9L118.4,98.5C118.4,96.9 117.5,95.6 116.4,95.6L65.7,95.6C64.6,95.6 63.7,96.9 63.7,98.5L63.7,116.9C63.7,118.5 64.6,119.8 65.7,119.8L116.5,119.8C117.6,119.8 118.4,118.6 118.4,116.9Z" /> </g> <g transform="matrix(1.0246,0,0,0.999998,1.03751,2.43115)"> <path d="M141.9,147.3L141.9,129C141.9,127.4 140.7,126.1 139.1,126.1L66.5,126.1C64.9,126.1 63.7,127.4 63.7,129L63.7,147.4C63.7,149 64.9,150.3 66.5,150.3L139.1,150.3C140.7,150.3 141.9,149 141.9,147.3Z" /> </g> <g transform="matrix(1.0246,0,0,0.999998,1.03751,2.43115)"> <path d="M205,170.7L152.7,139.1C150,137.4 147.7,138.7 147.7,141.9L147.7,157.9L55.8,157.9L55.8,59.4L67.2,59.4C70.4,59.4 71.7,57.2 70,54.4L38.4,2.1C36.7,-0.6 34.1,-0.6 32.4,2.1L0.7,54.4C-1,57.1 0.3,59.4 3.5,59.4L15.6,59.4L15.6,185.5C15.6,188.5 18,190.9 21,190.9L147.7,190.9L147.7,205.7C147.7,208.9 149.9,210.1 152.7,208.5L205,176.9C207.7,175.1 207.7,172.4 205,170.7Z" /> </g> </svg> </div> ); };
nayanika2/legend-studio
packages/legend-studio/src/stores/__tests__/roundtrip/MappingRoundtripTestData.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // References to resolve in Mapping // - Class mapping - targetClass // - PropertyMapping - Property // - Pure Instance - source class `OPTIONAL` // - Enumeration mapping - targetEnumeration // - Enumeration mapping - sourceType `OPTIONAL` // - Association mapping - targetAssociation // - Association mapping - stores // - MappingTest - inputData - flatdata // - MappingTest - inputData - class export const testMappingRoundtrip = [ { path: 'test::tClass', content: { _type: 'class', name: 'tClass', package: 'test', properties: [ { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'fullName', type: 'String', }, { multiplicity: { lowerBound: 0, }, name: 'name', type: 'String', }, ], }, classifierPath: 'meta::pure::metamodel::type::Class', }, { path: 'test::tEnum', content: { _type: 'Enumeration', name: 'tEnum', package: 'test', values: [ { value: 'b', }, ], }, classifierPath: 'meta::pure::metamodel::type::Enumeration', }, { path: 'test::tMapping1', content: { _type: 'mapping', classMappings: [ { _type: 'operation', class: 'tClass', id: 'tiec', operation: 'STORE_UNION', parameters: ['tiec', 'tiec'], root: true, }, ], enumerationMappings: [], includedMappings: [], name: 'tMapping1', package: 'test', tests: [], }, classifierPath: 'meta::pure::mapping::Mapping', }, { path: 'test::tMapping2', content: { _type: 'mapping', classMappings: [ { _type: 'operation', class: 'tClass', id: 'test_tClass', operation: 'STORE_UNION', parameters: ['test_tClass'], root: true, }, { _type: 'pureInstance', class: 'tClass', id: 'cay', propertyMappings: [ { _type: 'purePropertyMapping', property: { class: 'tClass', property: 'fullName', }, explodeProperty: false, source: '', transform: { _type: 'lambda', body: [ { _type: 'func', function: 'substring', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'fullName', }, { _type: 'integer', multiplicity: { lowerBound: 1, upperBound: 1, }, values: [0], }, { _type: 'func', function: 'indexOf', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'fullName', }, { _type: 'string', multiplicity: { lowerBound: 1, upperBound: 1, }, values: [' '], }, ], }, ], }, ], parameters: [], }, }, { _type: 'purePropertyMapping', property: { class: 'tClass', property: 'fullName', }, source: '', transform: { _type: 'lambda', body: [ { _type: 'func', function: 'substring', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'fullName', }, { _type: 'integer', multiplicity: { lowerBound: 1, upperBound: 1, }, values: [0], }, { _type: 'func', function: 'indexOf', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'fullName', }, { _type: 'string', multiplicity: { lowerBound: 1, upperBound: 1, }, values: [' '], }, ], }, ], }, ], parameters: [], }, }, { _type: 'purePropertyMapping', property: { class: 'tClass', property: 'name', }, source: '', explodeProperty: true, transform: { _type: 'lambda', body: [ { _type: 'func', function: 'substring', parameters: [ { _type: 'property', parameters: [ { _type: 'func', function: 'cast', parameters: [ { _type: 'var', name: 'src', }, { _type: 'packageableElementPtr', fullPath: 'tClass', }, ], }, ], property: 'fullName', }, { _type: 'func', function: 'plus', parameters: [ { _type: 'collection', multiplicity: { lowerBound: 2, upperBound: 2, }, values: [ { _type: 'func', function: 'indexOf', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'fullName', }, { _type: 'string', multiplicity: { lowerBound: 1, upperBound: 1, }, values: [' '], }, ], }, { _type: 'integer', multiplicity: { lowerBound: 1, upperBound: 1, }, values: [1], }, ], }, ], }, { _type: 'func', function: 'length', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'fullName', }, ], }, ], }, ], parameters: [], }, }, ], root: false, srcClass: 'tClass', }, ], enumerationMappings: [ { enumValueMappings: [ { enumValue: 'b', sourceValues: [ { _type: 'enumSourceValue', enumeration: 'test::tEnum', value: 'b', }, ], }, ], enumeration: 'tEnum', id: 'TargetTradeTypeMapping2', }, ], includedMappings: [], name: 'tMapping2', package: 'test', tests: [ { assert: { _type: 'expectedOutputMappingTestAssert', expectedOutput: '{"defects":[],"value":{"name":"oneName 99"},"source":{"defects":[],"value":{"oneName":"oneName 99"},"source":{"number":1,"record":"{\\"oneName\\":\\"oneName 99\\",\\"anotherName\\":\\"anotherName 17\\",\\"oneDate\\":\\"2020-04-13\\",\\"anotherDate\\":\\"2020-02-25\\",\\"oneNumber\\":27,\\"anotherNumber\\":28}"}}}', }, inputData: [ { _type: 'object', data: '{"oneName":"oneName 2","anotherName":"anotherName 16","oneDate":"2020-02-05","anotherDate":"2020-04-13","oneNumber":24,"anotherNumber":29}', inputType: 'JSON', sourceClass: 'tClass', }, { _type: 'object', data: '{"oneName":"oneName 2","anotherName":"anotherName 16","oneDate":"2020-02-05","anotherDate":"2020-04-13","oneNumber":24,"anotherNumber":29}', inputType: 'XML', sourceClass: 'tClass', }, ], name: 'test2', query: { _type: 'lambda', body: [ { _type: 'func', function: 'serialize', parameters: [ { _type: 'func', function: 'graphFetchChecked', parameters: [ { _type: 'func', function: 'getAll', parameters: [ { _type: 'packageableElementPtr', fullPath: 'tClass', }, ], }, { _type: 'rootGraphFetchTree', class: 'tClass', subTrees: [ { _type: 'propertyGraphFetchTree', parameters: [], property: 'name', subTrees: [], }, ], }, ], }, { _type: 'rootGraphFetchTree', class: 'tClass', subTrees: [ { _type: 'propertyGraphFetchTree', parameters: [], property: 'name', subTrees: [], }, ], }, ], }, ], parameters: [], }, }, ], }, classifierPath: 'meta::pure::mapping::Mapping', }, { path: '__internal__::SectionIndex', content: { _type: 'sectionIndex', name: 'SectionIndex', package: '__internal__', sections: [ { _type: 'importAware', imports: [], elements: ['test::tClass', 'test::tEnum'], parserName: 'Pure', }, { _type: 'importAware', imports: ['test'], elements: ['test::tMapping1', 'test::tMapping2'], parserName: 'Mapping', }, ], }, classifierPath: 'meta::pure::metamodel::section::SectionIndex', }, ]; export const testLocalPropertyMapping = [ { path: 'test::Firm', content: { _type: 'class', name: 'Firm', package: 'test', properties: [ { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'id', type: 'Integer', }, { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'legalName', type: 'String', }, ], }, classifierPath: 'meta::pure::metamodel::type::Class', }, { path: 'test::Person', content: { _type: 'class', name: 'Person', package: 'test', properties: [ { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'name', type: 'String', }, ], }, classifierPath: 'meta::pure::metamodel::type::Class', }, { path: 'test::Firm_Person', content: { _type: 'association', name: 'Firm_Person', package: 'test', properties: [ { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'employer', type: 'test::Firm', }, { multiplicity: { lowerBound: 0, }, name: 'employees', type: 'test::Person', }, ], }, classifierPath: 'meta::pure::metamodel::relationship::Association', }, { path: 'test::crossPropertyMappingWithLocalProperties', content: { _type: 'mapping', classMappings: [ { _type: 'pureInstance', class: 'test::Person', id: 'p', propertyMappings: [ { _type: 'purePropertyMapping', explodeProperty: false, localMappingProperty: { multiplicity: { lowerBound: 1, upperBound: 1, }, type: 'Integer', }, property: { class: 'test::Person', property: 'firmId', }, source: '', transform: { _type: 'lambda', body: [ { _type: 'integer', multiplicity: { lowerBound: 1, upperBound: 1, }, values: [1], }, ], parameters: [], }, }, { _type: 'purePropertyMapping', explodeProperty: false, property: { class: 'test::Person', property: 'name', }, source: '', transform: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'name', }, ], parameters: [], }, }, ], root: false, srcClass: 'test::Person', }, ], enumerationMappings: [], includedMappings: [], name: 'crossPropertyMappingWithLocalProperties', package: 'test', tests: [], }, classifierPath: 'meta::pure::mapping::Mapping', }, ]; export const testAggregationAwareMappingRoundtrip = [ { classifierPath: 'meta::pure::metamodel::type::Class', content: { _type: 'class', name: 'FiscalCalendar', package: 'test', properties: [ { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'date', type: 'Date', }, { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'fiscalYear', type: 'Integer', }, { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'fiscalMonth', type: 'Integer', }, { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'fiscalQtr', type: 'Integer', }, ], }, path: 'test::FiscalCalendar', }, { classifierPath: 'meta::pure::metamodel::type::Class', content: { _type: 'class', name: 'Sales', package: 'test', properties: [ { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'id', type: 'Integer', }, { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'salesDate', type: 'test::FiscalCalendar', }, { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'revenue', type: 'Float', }, ], }, path: 'test::Sales', }, { classifierPath: 'meta::pure::metamodel::type::Class', content: { _type: 'class', name: 'Sales_By_Date', package: 'test', properties: [ { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'salesDate', type: 'test::FiscalCalendar', }, { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'netRevenue', type: 'Float', }, ], }, path: 'test::Sales_By_Date', }, { classifierPath: 'meta::pure::mapping::Mapping', content: { _type: 'mapping', classMappings: [ { _type: 'pureInstance', class: 'test::FiscalCalendar', id: 'b', propertyMappings: [ { _type: 'purePropertyMapping', explodeProperty: false, property: { class: 'test::FiscalCalendar', property: 'date', }, source: '', transform: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'date', }, ], parameters: [], }, }, { _type: 'purePropertyMapping', explodeProperty: false, property: { class: 'test::FiscalCalendar', property: 'fiscalYear', }, source: '', transform: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'fiscalYear', }, ], parameters: [], }, }, { _type: 'purePropertyMapping', explodeProperty: false, property: { class: 'test::FiscalCalendar', property: 'fiscalMonth', }, source: '', transform: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'fiscalMonth', }, ], parameters: [], }, }, { _type: 'purePropertyMapping', explodeProperty: false, property: { class: 'test::FiscalCalendar', property: 'fiscalQtr', }, source: '', transform: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'fiscalQtr', }, ], parameters: [], }, }, ], root: false, srcClass: 'test::FiscalCalendar', }, { _type: 'aggregationAware', aggregateSetImplementations: [ { aggregateSpecification: { aggregateValues: [ { aggregateFn: { _type: 'lambda', body: [ { _type: 'func', function: 'sum', parameters: [ { _type: 'var', name: 'mapped', }, ], }, ], parameters: [], }, mapFn: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'this', }, ], property: 'revenue', }, ], parameters: [], }, }, ], canAggregate: true, groupByFunctions: [ { groupByFn: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'this', }, ], property: 'salesDate', }, ], parameters: [], }, }, ], }, index: 0, setImplementation: { _type: 'pureInstance', class: 'test::Sales', id: 'a_Aggregate_0', propertyMappings: [ { _type: 'purePropertyMapping', explodeProperty: false, property: { class: 'test::Sales', property: 'salesDate', }, source: '', target: 'b', transform: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'salesDate', }, ], parameters: [], }, }, { _type: 'purePropertyMapping', explodeProperty: false, property: { class: 'test::Sales', property: 'revenue', }, source: '', transform: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'netRevenue', }, ], parameters: [], }, }, ], root: false, srcClass: 'test::Sales_By_Date', }, }, ], class: 'test::Sales', id: 'a', mainSetImplementation: { _type: 'pureInstance', class: 'test::Sales', id: 'a_Main', propertyMappings: [ { _type: 'purePropertyMapping', explodeProperty: false, property: { class: 'test::Sales', property: 'salesDate', }, source: '', target: 'b', transform: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'salesDate', }, ], parameters: [], }, }, { _type: 'purePropertyMapping', explodeProperty: false, property: { class: 'test::Sales', property: 'revenue', }, source: '', transform: { _type: 'lambda', body: [ { _type: 'property', parameters: [ { _type: 'var', name: 'src', }, ], property: 'revenue', }, ], parameters: [], }, }, ], root: false, srcClass: 'test::Sales', }, propertyMappings: [ { _type: 'AggregationAwarePropertyMapping', property: { class: 'test::Sales', property: 'salesDate', }, source: 'a', target: 'b', }, { _type: 'AggregationAwarePropertyMapping', property: { class: 'test::Sales', property: 'revenue', }, source: 'a', }, ], root: false, }, ], enumerationMappings: [], includedMappings: [], name: 'map', package: 'test', tests: [], }, path: 'test::map', }, { path: '__internal__::SectionIndex', content: { _type: 'sectionIndex', name: 'SectionIndex', package: '__internal__', sections: [ { _type: 'importAware', imports: [], elements: [ 'test::FiscalCalendar', 'test::Sales', 'test::Sales_By_Date', ], parserName: 'Pure', }, { _type: 'importAware', imports: [], elements: ['test::map'], parserName: 'Mapping', }, ], }, classifierPath: 'meta::pure::metamodel::section::SectionIndex', }, ];
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/model/packageableElements/mapping/InferableMappingElementId.ts
<reponame>nayanika2/legend-studio<filename>packages/legend-studio/src/models/metamodels/pure/model/packageableElements/mapping/InferableMappingElementId.ts /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { computed, makeObservable } from 'mobx'; import { fromElementPathToMappingElementId } from '../../../../../MetaModelUtils'; import { InferableValue } from '../../../model/InferableValue'; export abstract class InferableMappingElementIdValue extends InferableValue< string, string | undefined > { protected defaultValue!: string; constructor(value: string, defaultValue: string) { super(value); makeObservable(this, { isDefault: computed, }); this.defaultValue = defaultValue; } get isDefault(): boolean { return this.defaultValue === this.value; } } export class InferableMappingElementIdExplicitValue extends InferableMappingElementIdValue { constructor(value: string, defaultValue: string) { super(value, defaultValue); makeObservable(this, { valueForSerialization: computed, }); } static create( value: string, targetPath: string, ): InferableMappingElementIdExplicitValue { return new InferableMappingElementIdExplicitValue( value, fromElementPathToMappingElementId(targetPath), ); } get valueForSerialization(): string | undefined { // if the current value is the default value, we will use `undefined` // instead of using the default value to reduce the size of the protocol if (this.isDefault) { return undefined; } return this.value; } } export class InferableMappingElementIdImplicitValue extends InferableMappingElementIdValue { private input?: string; constructor(value: string, defaultValue: string, input: string | undefined) { super(value, defaultValue); makeObservable(this, { valueForSerialization: computed, }); this.input = input; } static create( value: string, targetPath: string, input: string | undefined, ): InferableMappingElementIdImplicitValue { return new InferableMappingElementIdImplicitValue( value, fromElementPathToMappingElementId(targetPath), input, ); } get valueForSerialization(): string | undefined { // inferred and the current value is the same as the input if (this.value === this.input) { return this.input; } // inferred and the current value is the default value, we will use `undefined` // as the inference turns `undefined` into default value if (this.isDefault) { return undefined; } return this.value; } }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/model/packageableElements/mapping/V1_PropertyMapping.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { hashArray } from '@finos/legend-studio-shared'; import type { Hashable } from '@finos/legend-studio-shared'; import { CORE_HASH_STRUCTURE } from '../../../../../../MetaModelConst'; import type { V1_EmbeddedRelationalPropertyMapping } from '../../../model/packageableElements/store/relational/mapping/V1_EmbeddedRelationalPropertyMapping'; import type { V1_OtherwiseEmbeddedRelationalPropertyMapping } from '../../../model/packageableElements/store/relational/mapping/V1_OtherwiseEmbeddedRelationalPropertyMapping'; import type { V1_InlineEmbeddedPropertyMapping } from '../../../model/packageableElements/store/relational/mapping/V1_InlineEmbeddedPropertyMapping'; import type { V1_AggregationAwarePropertyMapping } from '../../../model/packageableElements/store/relational/mapping/aggregationAware/V1_AggregationAwarePropertyMapping'; import type { V1_RelationalPropertyMapping } from '../../../model/packageableElements/store/relational/mapping/V1_RelationalPropertyMapping'; import type { V1_LocalMappingPropertyInfo } from './V1_LocalMappingPropertyInfo'; import type { V1_PropertyPointer } from '../../../model/packageableElements/domain/V1_PropertyPointer'; import type { V1_PurePropertyMapping } from '../../../model/packageableElements/store/modelToModel/mapping/V1_PurePropertyMapping'; import type { V1_FlatDataPropertyMapping } from '../../../model/packageableElements/store/flatData/mapping/V1_FlatDataPropertyMapping'; import type { V1_EmbeddedFlatDataPropertyMapping } from '../../../model/packageableElements/store/flatData/mapping/V1_EmbeddedFlatDataPropertyMapping'; import type { V1_XStorePropertyMapping } from './xStore/V1_XStorePropertyMapping'; /* @MARKER: NEW CLASS MAPPING TYPE SUPPORT --- consider adding class mapping type handler here whenever support for a new one is added to the app */ export interface V1_PropertyMappingVisitor<T> { visit_PurePropertyMapping(propertyMapping: V1_PurePropertyMapping): T; visit_FlatDataPropertyMapping(propertyMapping: V1_FlatDataPropertyMapping): T; visit_EmbeddedFlatDataPropertyMapping( propertyMapping: V1_EmbeddedFlatDataPropertyMapping, ): T; visit_RelationalPropertyMapping( propertyMapping: V1_RelationalPropertyMapping, ): T; visit_EmbeddedRelationalPropertyMapping( propertyMapping: V1_EmbeddedRelationalPropertyMapping, ): T; visit_OtherwiseEmbeddedRelationalPropertyMapping( propertyMapping: V1_OtherwiseEmbeddedRelationalPropertyMapping, ): T; visit_InlineEmbeddedPropertyMapping( propertyMapping: V1_InlineEmbeddedPropertyMapping, ): T; visit_AggregationAwarePropertyMapping( propertyMapping: V1_AggregationAwarePropertyMapping, ): T; visit_XStorePropertyMapping(propertyMapping: V1_XStorePropertyMapping): T; } export abstract class V1_PropertyMapping implements Hashable { property!: V1_PropertyPointer; source?: string; // `source` is an information that we actually do not need to care about much as it can derived from the container/holder of the property mapping // NOTE: `target` is required in protocol but that doesn't seem right since the value can be empty string, // also when we convert this to metamodel, we might not be able to identify the class mapping corresponding to the `target` ID // in that case we will handle the logic in Transformer to have `target` as empty, here we use `?:` because the // specification in the current protocol is unreasonable and will be should be changed to optional (String[0..1]) target?: string; localMappingProperty?: V1_LocalMappingPropertyInfo; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.PROPERTY_MAPPING, this.property, this.target ?? '', this.localMappingProperty ?? '', ]); } abstract accept_PropertyMappingVisitor<T>( visitor: V1_PropertyMappingVisitor<T>, ): T; }
nayanika2/legend-studio
packages/legend-studio/src/index.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // application export * from './application/Studio'; export * from './application/PluginManager'; // network export * from './stores/network/Telemetry'; export * from './stores/network/Tracer'; // metamodels export * from './models/metamodels/pure/graph/PureGraphExtension'; export * from './models/metamodels/pure/graph/PureGraphManagerPlugin'; export * from './models/MetaModelUtils'; export { PRIMITIVE_TYPE, CLIENT_VERSION, LAMBDA_START, DEFAULT_SOURCE_PARAMETER_NAME, CORE_ELEMENT_PATH, TYPICAL_MULTIPLICITY_TYPE, MULTIPLICITY_INFINITE, } from './models/MetaModelConst'; export * from './models/metamodels/pure/model/Stubable'; // TODO: to be removed export { BasicModel } from './models/metamodels/pure/graph/BasicModel'; export { PureModel } from './models/metamodels/pure/graph/PureModel'; export * from './models/metamodels/pure/action/EngineError'; export * from './models/metamodels/pure/action/SourceInformationHelper'; export * from './models/metamodels/pure/model/packageableElements/PackageableElement'; export * from './models/metamodels/pure/model/packageableElements/PackageableElementReference'; export { Multiplicity } from './models/metamodels/pure/model/packageableElements/domain/Multiplicity'; export { Type } from './models/metamodels/pure/model/packageableElements/domain/Type'; export { PrimitiveType } from './models/metamodels/pure/model/packageableElements/domain/PrimitiveType'; export { GenericTypeExplicitReference } from './models/metamodels/pure/model/packageableElements/domain/GenericTypeReference'; export { GenericType } from './models/metamodels/pure/model/packageableElements/domain/GenericType'; export { Class, CLASS_PROPERTY_TYPE, getClassPropertyType, } from './models/metamodels/pure/model/packageableElements/domain/Class'; export { Enumeration } from './models/metamodels/pure/model/packageableElements/domain/Enumeration'; export { Enum } from './models/metamodels/pure/model/packageableElements/domain/Enum'; export * from './models/metamodels/pure/model/packageableElements/domain/EnumValueReference'; export type { AbstractProperty } from './models/metamodels/pure/model/packageableElements/domain/AbstractProperty'; export { DerivedProperty } from './models/metamodels/pure/model/packageableElements/domain/DerivedProperty'; export { Property } from './models/metamodels/pure/model/packageableElements/domain/Property'; export { RawLambda } from './models/metamodels/pure/model/rawValueSpecification/RawLambda'; export { UnknownValue } from './models/metamodels/pure/model/valueSpecification/UnknownValue'; export { VariableExpression } from './models/metamodels/pure/model/valueSpecification/VariableExpression'; export { AbstractPropertyExpression, SimpleFunctionExpression, FunctionExpression, } from './models/metamodels/pure/model/valueSpecification/SimpleFunctionExpression'; export { FunctionType, LambdaFunction, LambdaFunctionInstanceValue, } from './models/metamodels/pure/model/valueSpecification/LambdaFunction'; export { AlloySerializationConfigInstanceValue } from './models/metamodels/pure/model/valueSpecification/AlloySerializationConfig'; export { EnumValueInstanceValue, MappingInstanceValue, PairInstanceValue, PureListInstanceValue, RuntimeInstanceValue, InstanceValue, CollectionInstanceValue, PrimitiveInstanceValue, } from './models/metamodels/pure/model/valueSpecification/InstanceValue'; export { ValueSpecification } from './models/metamodels/pure/model/valueSpecification/ValueSpecification'; export type { ValueSpecificationVisitor } from './models/metamodels/pure/model/valueSpecification/ValueSpecification'; export type { RawExecutionPlan } from './models/metamodels/pure/model/executionPlan/ExecutionPlan'; export { ExecutionResult, TdsExecutionResult, } from './models/metamodels/pure/action/execution/ExecutionResult'; export { GraphFetchTree, PropertyGraphFetchTree, RootGraphFetchTree, GraphFetchTreeInstanceValue, PropertyGraphFetchTreeInstanceValue, RootGraphFetchTreeInstanceValue, } from './models/metamodels/pure/model/valueSpecification/GraphFetchTree'; export * from './models/metamodels/pure/model/packageableElements/domain/PropertyReference'; // protocols export * from './models/protocols/pure/PureProtocolProcessorPlugin'; export type { V1_PureModelContextData } from './models/protocols/pure/v1/model/context/V1_PureModelContextData'; export * from './models/protocols/pure/v1/model/packageableElements/V1_PackageableElement'; export * from './models/protocols/pure/v1/transformation/pureGraph/to/V1_GraphBuilderContext'; export * from './models/protocols/pure/v1/transformation/pureGraph/to/V1_ElementBuilder'; export { V1_RawLambda } from './models/protocols/pure/v1/model/rawValueSpecification/V1_RawLambda'; export { V1_ValueSpecification } from './models/protocols/pure/v1/model/valueSpecification/V1_ValueSpecification'; export { V1_ProcessingContext } from './models/protocols/pure/v1/transformation/pureGraph/to/helpers/V1_ProcessingContext'; export * from './models/protocols/pure/v1/transformation/pureGraph/from/V1_GraphTransformerContext'; export { V1_initPackageableElement, V1_transformElementReference, } from './models/protocols/pure/v1/transformation/pureGraph/from/V1_CoreTransformerHelper'; export { V1_RawValueSpecificationTransformer, V1_transformRawLambda, } from './models/protocols/pure/v1/transformation/pureGraph/from/V1_RawValueSpecificationTransformer'; export { V1_rawLambdaModelSchema } from './models/protocols/pure/v1/transformation/pureProtocol/serializationHelpers/V1_RawValueSpecificationSerializationHelper'; export { V1_EngineServerClient } from './models/protocols/pure/v1/engine/V1_EngineServerClient'; export { V1_Engine } from './models/protocols/pure/v1/engine/V1_Engine'; export { V1_pureModelContextDataPropSchema, V1_deserializePureModelContextData as V1_jsonToPureModelContextData, } from './models/protocols/pure/v1/transformation/pureProtocol/V1_PureProtocolSerialization'; export { V1_StereotypePtr } from './models/protocols/pure/v1/model/packageableElements/domain/V1_StereotypePtr'; export { V1_PropertyPointer } from './models/protocols/pure/v1/model/packageableElements/domain/V1_PropertyPointer'; export { V1_propertyPointerModelSchema, V1_stereotypePtrSchema, } from './models/protocols/pure/v1/transformation/pureProtocol/serializationHelpers/V1_DomainSerializationHelper'; export { V1_AppliedFunction } from './models/protocols/pure/v1/model/valueSpecification/application/V1_AppliedFunction'; export { V1_AppliedProperty } from './models/protocols/pure/v1/model/valueSpecification/application/V1_AppliedProperty'; export { V1_Collection } from './models/protocols/pure/v1/model/valueSpecification/raw/V1_Collection'; export { V1_Lambda } from './models/protocols/pure/v1/model/valueSpecification/raw/V1_Lambda'; export { V1_Variable } from './models/protocols/pure/v1/model/valueSpecification/V1_Variable'; export { V1_serializeValueSpecification } from './models/protocols/pure/v1/transformation/pureProtocol/serializationHelpers/V1_ValueSpecificationSerializer'; export { V1_deserializeRawValueSpecification } from './models/protocols/pure/v1/transformation/pureProtocol/serializationHelpers/V1_RawValueSpecificationSerializationHelper'; export { V1_serializeRawValueSpecification } from './models/protocols/pure/v1/transformation/pureProtocol/serializationHelpers/V1_RawValueSpecificationSerializationHelper'; export { V1_ValueSpecificationBuilder } from './models/protocols/pure/v1/transformation/pureGraph/to/helpers/V1_ValueSpecificationBuilderHelper'; // SDLC export { Entity } from './models/sdlc/models/entity/Entity'; export { EntityChangeType } from './models/sdlc/models/entity/EntityChange'; export { Build, BuildStatus } from './models/sdlc/models/build/Build'; export { Project, ProjectType } from './models/sdlc/models/project/Project'; // stores export * from './stores/EditorPlugin'; export * from './stores/ApplicationStore'; export * from './stores/EditorStore'; export * from './stores/EditorConfig'; export * from './stores/editor-state/element-editor-state/ElementEditorState'; export * from './stores/editor-state/UnsupportedElementEditorState'; export { NewElementState, NewElementDriver } from './stores/NewElementState'; export { LambdaEditorState } from './stores/editor-state/element-editor-state/LambdaEditorState'; export type { TransformDropTarget } from './stores/shared/DnDUtil'; export { CORE_DND_TYPE, ElementDragSource, TypeDragSource, } from './stores/shared/DnDUtil'; export { ExplorerTreeRootPackageLabel } from './stores/ExplorerTreeState'; // components export * from './components/shared/TextInputEditor'; export * from './components/shared/AppHeader'; export * from './components/shared/Icon'; // TODO: we might want to move all of these to @finos/legend-studio-components export { AppHeaderMenu } from './components/editor/header/AppHeaderMenu'; export { getElementIcon, getElementTypeIcon } from './components/shared/Icon'; export { TypeTree } from './components/shared/TypeTree'; export { LambdaEditor } from './components/shared/LambdaEditor'; export * from './utils/Logger'; // TODO: to be removed when we move this to @finos/legend-studio-shared // test export * from './const'; export { getTestApplicationConfig, getTestEditorStore, checkBuildingElementsRoundtrip, } from './stores/StoreTestUtils'; export { getMockedApplicationStore, getMockedEditorStore, setUpEditor, setUpEditorWithDefaultSDLCData, } from './components/ComponentTestUtils'; // --------------------------------------------- TO BE MODULARIZED -------------------------------------------------- export * from './DSLMapping_Exports'; export * from './DSLService_Exports'; export * from './DSLGenerationSpecification_Exports'; export * from './StoreFlatData_Exports'; export * from './StoreRelational_Exports';
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/components/QueryBuilder_EditorPlugin.tsx
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import packageJson from '../../package.json'; import type { EditorExtensionState, EditorExtensionStateCreator, EditorStore, LambdaEditorHotkeyConfiguration, LambdaEditorState, PackageableElement, PluginManager, EditorExtensionComponentRendererConfiguration, ExplorerContextMenuItemRendererConfiguration, TEMP__ServiceQueryEditorRendererConfiguration, ServicePureExecutionState, MappingExecutionQueryEditorRendererConfiguration, MappingExecutionState, MappingTestQueryEditorRendererConfiguration, MappingTestState, EditorPluginSetup, } from '@finos/legend-studio'; import { Class, EditorPlugin } from '@finos/legend-studio'; import { MenuContentItem } from '@finos/legend-studio-components'; import { QueryBuilderDialog } from './QueryBuilderDialog'; import { ServiceQueryBuilder } from './ServiceQueryBuilder'; import { MappingExecutionQueryBuilder } from './MappingExecutionQueryBuilder'; import { MappingTestQueryBuilder } from './MappingTestQueryBuilder'; import { QueryBuilderState } from '../stores/QueryBuilderState'; import { flowResult } from 'mobx'; import type { IKeyboardEvent } from 'monaco-editor'; import { KeyCode } from 'monaco-editor'; import { ModuleRegistry as agGrid_ModuleRegistry } from '@ag-grid-community/core'; import { ClientSideRowModelModule } from '@ag-grid-community/client-side-row-model'; export class QueryBuilder_EditorPlugin extends EditorPlugin { constructor() { super(packageJson.name, packageJson.version); } install(pluginManager: PluginManager): void { pluginManager.registerEditorPlugin(this); } override getExtraEditorPluginSetups(): EditorPluginSetup[] { return [ async (pluginManager: PluginManager): Promise<void> => { // Register module extensions for `ag-grid` agGrid_ModuleRegistry.registerModules([ClientSideRowModelModule]); }, ]; } override configure(_configData: object): QueryBuilder_EditorPlugin { return this; } override getExtraEditorExtensionComponentRendererConfigurations(): EditorExtensionComponentRendererConfiguration[] { return [ { key: 'query-builder-dialog', renderer: function QueryBuilderDialogRenderer( editorStore: EditorStore, ): React.ReactNode | undefined { return <QueryBuilderDialog />; }, }, ]; } override getExtraEditorExtensionStateCreators(): EditorExtensionStateCreator[] { return [ (editorStore: EditorStore): EditorExtensionState | undefined => new QueryBuilderState(editorStore), ]; } override getExtraExplorerContextMenuItemRendererConfigurations(): ExplorerContextMenuItemRendererConfiguration[] { return [ { key: 'build-query-context-menu-action', renderer: ( editorStore: EditorStore, element: PackageableElement | undefined, ): React.ReactNode | undefined => { if (element instanceof Class) { const buildQuery = async (): Promise<void> => { const queryBuilderState = editorStore.getEditorExtensionState(QueryBuilderState); await flowResult(queryBuilderState.setOpenQueryBuilder(true)); if (queryBuilderState.openQueryBuilder) { queryBuilderState.querySetupState.setClass(element); queryBuilderState.resetData(); } }; return ( <MenuContentItem onClick={buildQuery}>Execute...</MenuContentItem> ); } return undefined; }, }, ]; } override getExtraLambdaEditorHotkeyConfigurations(): LambdaEditorHotkeyConfiguration[] { return [ { eventMatcher: ( editorStore: EditorStore, event: IKeyboardEvent, ): boolean => editorStore.getEditorExtensionState(QueryBuilderState) .openQueryBuilder && event.keyCode === KeyCode.F9, skipGlobalAction: true, action: ( editorStore: EditorStore, lambdaEditorState: LambdaEditorState, checkParseringError: boolean, ): void => { const queryBuilderState = editorStore.getEditorExtensionState(QueryBuilderState); editorStore.graphState .checkLambdaParsingError( lambdaEditorState, checkParseringError, () => flowResult(queryBuilderState.compileQuery()), ) .catch(editorStore.applicationStore.alertIllegalUnhandledError); }, }, ]; } override getExtraMappingExecutionQueryEditorRendererConfigurations(): MappingExecutionQueryEditorRendererConfiguration[] { return [ { key: 'build-query-context-menu-action', renderer: function MappingExecutionQueryBuilderRenderer( executionState: MappingExecutionState, ): React.ReactNode | undefined { return ( <MappingExecutionQueryBuilder executionState={executionState} /> ); }, }, ]; } override getExtraMappingTestQueryEditorRendererConfigurations(): MappingTestQueryEditorRendererConfiguration[] { return [ { key: 'build-query-context-menu-action', renderer: function MappingTestQueryBuilderRenderer( testState: MappingTestState, isReadOnly: boolean, ): React.ReactNode | undefined { return ( <MappingTestQueryBuilder testState={testState} isReadOnly={isReadOnly} /> ); }, }, ]; } override TEMP__getExtraServiceQueryEditorRendererConfigurations(): TEMP__ServiceQueryEditorRendererConfiguration[] { return [ { key: 'build-query-context-menu-action', renderer: function ServiceQueryBuilderRenderer( executionState: ServicePureExecutionState, isReadOnly: boolean, ): React.ReactNode | undefined { return ( <ServiceQueryBuilder executionState={executionState} isReadOnly={isReadOnly} /> ); }, }, ]; } }
nayanika2/legend-studio
packages/legend-studio/src/stores/editor-state/element-editor-state/FileGenerationEditorState.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { computed, action, observable, makeObservable } from 'mobx'; import { ElementEditorState } from './ElementEditorState'; import { assertType, guaranteeType } from '@finos/legend-studio-shared'; import type { EditorStore } from '../../EditorStore'; import { FileGenerationState } from '../../editor-state/FileGenerationState'; import type { PackageableElement } from '../../../models/metamodels/pure/model/packageableElements/PackageableElement'; import { FileGenerationSpecification } from '../../../models/metamodels/pure/model/packageableElements/fileGeneration/FileGenerationSpecification'; export class FileGenerationEditorState extends ElementEditorState { isGenerating = false; fileGenerationState: FileGenerationState; constructor(editorStore: EditorStore, element: PackageableElement) { super(editorStore, element); makeObservable(this, { isGenerating: observable, fileGenerationState: observable, fileGeneration: computed, reprocess: action, }); this.fileGenerationState = new FileGenerationState( editorStore, this.fileGeneration, ); this.fileGenerationState .generate() .catch(this.editorStore.applicationStore.alertIllegalUnhandledError); assertType( element, FileGenerationSpecification, 'Element inside file generation editor state should be a file generation', ); } get fileGeneration(): FileGenerationSpecification { return guaranteeType( this.element, FileGenerationSpecification, 'Element file generation editor state must be a file generation', ); } reprocess( newElement: FileGenerationSpecification, editorStore: EditorStore, ): FileGenerationEditorState { return new FileGenerationEditorState(editorStore, newElement); } }
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/stores/QueryBuilderPropertyEditorState.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { action, makeAutoObservable } from 'mobx'; import { getNullableFirstElement, guaranteeType, prettyCamelCase, } from '@finos/legend-studio-shared'; import type { AbstractProperty, EditorStore, PureModel, ValueSpecification, } from '@finos/legend-studio'; import { TYPICAL_MULTIPLICITY_TYPE, CollectionInstanceValue, AbstractPropertyExpression, DerivedProperty, Enumeration, EnumValueExplicitReference, EnumValueInstanceValue, InstanceValue, PrimitiveInstanceValue, PRIMITIVE_TYPE, VariableExpression, } from '@finos/legend-studio'; import { generateDefaultValueForPrimitiveType } from './QueryBuilderValueSpecificationBuilderHelper'; export const getPropertyChainName = ( propertyExpression: AbstractPropertyExpression, ): string => { const propertyNameChain = [propertyExpression.func.name]; let currentExpression: ValueSpecification | undefined = propertyExpression; while (currentExpression instanceof AbstractPropertyExpression) { currentExpression = getNullableFirstElement( currentExpression.parametersValues, ); if (currentExpression instanceof AbstractPropertyExpression) { propertyNameChain.unshift(currentExpression.func.name); } } return propertyNameChain.map(prettyCamelCase).join('/'); }; export const getPropertyPath = ( propertyExpression: AbstractPropertyExpression, ): string => { const propertyNameChain = [propertyExpression.func.name]; let currentExpression: ValueSpecification | undefined = propertyExpression; while (currentExpression instanceof AbstractPropertyExpression) { currentExpression = getNullableFirstElement( currentExpression.parametersValues, ); if (currentExpression instanceof AbstractPropertyExpression) { propertyNameChain.unshift(currentExpression.func.name); } } return propertyNameChain.join('.'); }; const fillDerivedPropertyArguments = ( derivedPropertyExpressionState: QueryBuilderDerivedPropertyExpressionState, graph: PureModel, ): void => { const propertyArguments: ValueSpecification[] = derivedPropertyExpressionState.parameterValues; derivedPropertyExpressionState.parameters.forEach((parameter, idx) => { if (idx < derivedPropertyExpressionState.parameterValues.length) { return; } let argument: ValueSpecification | undefined; const genericType = parameter.genericType; if (genericType) { const _type = genericType.value.rawType; if ( ( [ PRIMITIVE_TYPE.STRING, PRIMITIVE_TYPE.BOOLEAN, PRIMITIVE_TYPE.NUMBER, PRIMITIVE_TYPE.FLOAT, PRIMITIVE_TYPE.DECIMAL, PRIMITIVE_TYPE.INTEGER, PRIMITIVE_TYPE.DATE, PRIMITIVE_TYPE.STRICTDATE, PRIMITIVE_TYPE.DATETIME, ] as string[] ).includes(_type.name) ) { const primitiveInstanceValue = new PrimitiveInstanceValue( genericType, parameter.multiplicity, ); primitiveInstanceValue.values = [ generateDefaultValueForPrimitiveType(_type.name as PRIMITIVE_TYPE), ]; argument = primitiveInstanceValue; } else if (_type instanceof Enumeration) { const enumValueInstanceValue = new EnumValueInstanceValue( genericType, parameter.multiplicity, ); if (_type.values.length) { const enumValueRef = EnumValueExplicitReference.create( _type.values[0], ); enumValueInstanceValue.values = [enumValueRef]; } argument = enumValueInstanceValue; } } // for arguments of types we don't support, we will fill them with `[]` // which in Pure is equivalent to `null` in other languages propertyArguments.push( argument ?? new CollectionInstanceValue( graph.getTypicalMultiplicity(TYPICAL_MULTIPLICITY_TYPE.ZERO), ), ); }); derivedPropertyExpressionState.propertyExpression.setParametersValues([ derivedPropertyExpressionState.propertyExpression.parametersValues[0], ...propertyArguments, ]); }; export class QueryBuilderDerivedPropertyExpressionState { editorStore: EditorStore; path: string; title: string; propertyExpression: AbstractPropertyExpression; derivedProperty: DerivedProperty; parameters: VariableExpression[] = []; constructor( editorStore: EditorStore, propertyExpression: AbstractPropertyExpression, ) { this.path = getPropertyPath(propertyExpression); this.title = getPropertyChainName(propertyExpression); this.propertyExpression = propertyExpression; this.editorStore = editorStore; this.derivedProperty = guaranteeType( propertyExpression.func, DerivedProperty, ); // build the parameters of the derived properties if (Array.isArray(this.derivedProperty.parameters)) { this.parameters = this.derivedProperty.parameters.map((parameter) => guaranteeType( this.editorStore.graphState.graphManager.buildValueSpecification( parameter, this.editorStore.graphState.graph, ), VariableExpression, ), ); } fillDerivedPropertyArguments(this, editorStore.graphState.graph); } get property(): AbstractProperty { return this.propertyExpression.func; } get parameterValues(): ValueSpecification[] { return this.propertyExpression.parametersValues.slice(1); } get isValid(): boolean { // TODO: more type matching logic here (take into account multiplicity, type, etc.) return this.parameterValues.every((paramValue) => { if (paramValue instanceof InstanceValue) { const isRequired = paramValue.multiplicity.lowerBound >= 1; // required and no values provided if (isRequired && !paramValue.values.length) { return false; } // more values than allowed if ( paramValue.multiplicity.upperBound && paramValue.values.length > paramValue.multiplicity.upperBound ) { return false; } } return true; }); } } export class QueryBuilderPropertyExpressionState { editorStore: EditorStore; path: string; title: string; propertyExpression: AbstractPropertyExpression; isEditingDerivedPropertyExpression = false; // Since this property is a chain expression, some link of the chain can be // derived property, as such, we need to keep track of the derived properties state in an array derivedPropertyExpressionStates: QueryBuilderDerivedPropertyExpressionState[] = []; /** * If at least one property in the chain is of multiplicity greater than 1, * the property might have multiple values and can cause row explosions. * * In other words, saying `$x.b == 1` is not quite accurate if `$x.b` is multi * is multi. Instead, we should do something like `$x.b->exists($x1 | $x1 == 1)` */ requiresExistsHandling = false; constructor( editorStore: EditorStore, propertyExpression: AbstractPropertyExpression, ) { makeAutoObservable< QueryBuilderPropertyExpressionState, 'initDerivedPropertyExpressionStates' >(this, { editorStore: false, setIsEditingDerivedProperty: action, initDerivedPropertyExpressionStates: action, }); this.editorStore = editorStore; this.propertyExpression = propertyExpression; this.path = getPropertyPath(propertyExpression); this.title = getPropertyChainName(propertyExpression); this.initDerivedPropertyExpressionStates(); } get isValid(): boolean { return this.derivedPropertyExpressionStates.every((e) => e.isValid); } setIsEditingDerivedProperty(val: boolean): void { this.isEditingDerivedPropertyExpression = val; } private initDerivedPropertyExpressionStates(): void { let requiresExistsHandling = false; const result: QueryBuilderDerivedPropertyExpressionState[] = []; let currentExpression: ValueSpecification | undefined = this.propertyExpression; while (currentExpression instanceof AbstractPropertyExpression) { // Check if the property chain can results in column that have multiple values if ( currentExpression.func.multiplicity.upperBound === undefined || currentExpression.func.multiplicity.upperBound > 1 ) { requiresExistsHandling = true; } // Create states to hold derived properties' parameters and arguments for editing if (currentExpression.func instanceof DerivedProperty) { const derivedPropertyExpressionState = new QueryBuilderDerivedPropertyExpressionState( this.editorStore, currentExpression, ); result.push(derivedPropertyExpressionState); } currentExpression = getNullableFirstElement( currentExpression.parametersValues, ); } this.requiresExistsHandling = requiresExistsHandling; this.derivedPropertyExpressionStates = result.reverse(); } }
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/model/packageableElements/domain/Class.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { observable, action, computed, makeObservable, override } from 'mobx'; import { hashArray, uniqBy, IllegalStateError, guaranteeNonNullable, UnsupportedOperationError, addUniqueEntry, deleteEntry, changeEntry, } from '@finos/legend-studio-shared'; import type { Hashable } from '@finos/legend-studio-shared'; import { CORE_HASH_STRUCTURE, CORE_ELEMENT_PATH, } from '../../../../../MetaModelConst'; import { Type } from './Type'; import type { Property } from './Property'; import type { Constraint } from './Constraint'; import type { DerivedProperty } from './DerivedProperty'; import type { AbstractProperty } from './AbstractProperty'; import type { Stubable } from '../../../model/Stubable'; import { isStubArray } from '../../../model/Stubable'; import type { PackageableElementVisitor } from '../../../model/packageableElements/PackageableElement'; import { PrimitiveType } from './PrimitiveType'; import { Enumeration } from './Enumeration'; import { Measure, Unit } from './Measure'; import type { StereotypeReference } from '../../../model/packageableElements/domain/StereotypeReference'; import type { TaggedValue } from '../../../model/packageableElements/domain/TaggedValue'; import type { GenericTypeReference } from './GenericTypeReference'; export class Class extends Type implements Hashable, Stubable { properties: Property[] = []; // derivedPropertiesFromAssociations: DerivedProperty[] = []; propertiesFromAssociations: Property[] = []; derivedProperties: DerivedProperty[] = []; generalizations: GenericTypeReference[] = []; /** * @MARKER MEMORY-SENSITIVE * if this belongs to immutable elements: i.e. in system, project dependency, etc. * we have to make sure to remove of disposed classes from this when we reprocess the graph */ _subClasses: Class[] = []; constraints: Constraint[] = []; stereotypes: StereotypeReference[] = []; taggedValues: TaggedValue[] = []; constructor(name: string) { super(name); makeObservable<Class, 'cleanUpDisposedSubClasses' | '_elementHashCode'>( this, { properties: observable, propertiesFromAssociations: observable, derivedProperties: observable, generalizations: observable, _subClasses: observable, constraints: observable, stereotypes: observable, taggedValues: observable, deleteProperty: action, addProperty: action, deleteDerivedProperty: action, addDerivedProperty: action, addConstraint: action, deleteConstraint: action, changeConstraint: action, addSuperType: action, deleteSuperType: action, addSubClass: action, deleteSubClass: action, deleteTaggedValue: action, addTaggedValue: action, deleteStereotype: action, changeStereotype: action, addStereotype: action, allSuperClasses: computed, allSubClasses: computed({ keepAlive: true }), dispose: override, cleanUpDisposedSubClasses: action, isStub: computed, _elementHashCode: override, }, ); } deleteProperty(val: Property): void { deleteEntry(this.properties, val); } addProperty(val: Property): void { addUniqueEntry(this.properties, val); } deleteDerivedProperty(val: DerivedProperty): void { deleteEntry(this.derivedProperties, val); } addDerivedProperty(val: DerivedProperty): void { addUniqueEntry(this.derivedProperties, val); } addConstraint(val: Constraint): void { addUniqueEntry(this.constraints, val); } deleteConstraint(val: Constraint): void { deleteEntry(this.constraints, val); } changeConstraint(val: Constraint, newVal: Constraint): void { changeEntry(this.constraints, val, newVal); } addSuperType(val: GenericTypeReference): void { addUniqueEntry(this.generalizations, val); } deleteSuperType(val: GenericTypeReference): void { deleteEntry(this.generalizations, val); } addSubClass(val: Class): void { addUniqueEntry(this._subClasses, val); } deleteSubClass(val: Class): void { deleteEntry(this._subClasses, val); } deleteTaggedValue(val: TaggedValue): void { deleteEntry(this.taggedValues, val); } addTaggedValue(val: TaggedValue): void { addUniqueEntry(this.taggedValues, val); } deleteStereotype(val: StereotypeReference): void { deleteEntry(this.stereotypes, val); } changeStereotype( oldVal: StereotypeReference, newVal: StereotypeReference, ): void { changeEntry(this.stereotypes, oldVal, newVal); } addStereotype(val: StereotypeReference): void { addUniqueEntry(this.stereotypes, val); } /** * Get class and its supertypes' properties recursively, duplications and loops are handled (Which should be caught by compiler) */ getAllProperties = (): Property[] => uniqBy( this.allSuperClasses .concat(this) .map((_class) => _class.propertiesFromAssociations.concat(_class.properties), ) .flat(), (p) => p.name, ); getProperty = (name: string): Property => guaranteeNonNullable( this.getAllProperties().find((p) => p.name === name), `Can't find property '${name}' in class '${this.path}'`, ); getAllDerivedProperties = (): DerivedProperty[] => uniqBy( this.allSuperClasses .concat(this) .map((_class) => _class.derivedProperties) .flat(), (p) => p.name, ); getAllOwnedProperties = (): AbstractProperty[] => this.properties .concat(this.propertiesFromAssociations) .concat(this.derivedProperties); getOwnedProperty = (name: string): AbstractProperty => guaranteeNonNullable( this.getAllOwnedProperties().find((p) => p.name === name), `Can't find property '${name}' in class '${this.path}'`, ); // Perhaps we don't need to care about deduping constraints here like for properties getAllConstraints = (): Constraint[] => this.allSuperClasses .concat(this) .map((_class) => _class.constraints) .flat(); isSuperType(type: Type): boolean { return ( type.path === CORE_ELEMENT_PATH.ANY || (type instanceof Class && type.allSuperClasses.includes(this)) ); } isSubType(type: Type): boolean { return ( this.path === CORE_ELEMENT_PATH.ANY || (type instanceof Class && type.allSubClasses.includes(this)) ); } /** * Get all super types of a class, accounted for loop and duplication (which should be caught by compiler) * NOTE: we intentionally leave out `Any` */ get allSuperClasses(): Class[] { const visitedClasses = new Set<Class>(); visitedClasses.add(this); const resolveSuperTypes = (_class: Class): void => { _class.generalizations.forEach((gen) => { const superType = gen.value.getRawType(Class); if (!visitedClasses.has(superType)) { visitedClasses.add(superType); resolveSuperTypes(superType); } }); }; resolveSuperTypes(this); visitedClasses.delete(this); return Array.from(visitedClasses); } /** * Get all sub-classes of a class, accounted for loop and duplication (which should be caught by compiler) * NOTE: we intentionally leave out `Any` * * @MARKER MEMORY-SENSITIVE * When this is an immutable class such as project dependency or system we need to remember to remove the classes from the sub-types array. * And rerun this computation to avoid potenial memory leak */ get allSubClasses(): Class[] { if (this._isDisposed) { throw new IllegalStateError(`Element '${this.path}' is already disposed`); } const visitedClasses = new Set<Class>(); visitedClasses.add(this); const resolveSubClasses = (_class: Class): void => { if (_class._isDisposed) { return; } _class._subClasses.forEach((subClass) => { if (!visitedClasses.has(subClass)) { visitedClasses.add(subClass); resolveSubClasses(subClass); } }); }; resolveSubClasses(this); visitedClasses.delete(this); return Array.from(visitedClasses); } /** * @MARKER MEMORY-SENSITIVE * Since `keepAlive` can cause memory-leak, we need to dispose it manually when we are about to discard the graph * in order to avoid leaking. * See https://mobx.js.org/best/pitfalls.html#computed-values-run-more-often-than-expected * See https://medium.com/terria/when-and-why-does-mobxs-keepalive-cause-a-memory-leak-8c29feb9ff55 */ override dispose(): void { this._subClasses = []; // call this before setting `disposed` flag to avoid triggering errors if something is using this during disposal this._isDisposed = true; // dispose hash computation try { this.hashCode; } catch { /* do nothing */ } // trigger recomputation on `hashCode` so it removes itself from all observables it previously observed // dispose sub-classes analytics this.allSuperClasses.forEach((superClass) => { if (!superClass._isDisposed) { superClass.cleanUpDisposedSubClasses(); } }); try { this.allSubClasses; } catch { /* do nothing */ } // trigger recomputation on `allSubClasses` so it removes itself from all observables it previously observed } protected cleanUpDisposedSubClasses(): void { this._subClasses = this._isDisposed ? [] : this._subClasses.filter((subClass) => !subClass._isDisposed); } static createStub = (): Class => new Class(''); override get isStub(): boolean { return ( super.isStub && isStubArray(this.properties) && isStubArray(this.derivedProperties) && isStubArray(this.constraints) && isStubArray(this.generalizations) && isStubArray(this.stereotypes) && isStubArray(this.taggedValues) ); } protected override get _elementHashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.CLASS, this.path, hashArray(this.properties), hashArray(this.derivedProperties), hashArray( this.generalizations.map( (gen) => gen.ownerReference.valueForSerialization, ), ), hashArray(this.constraints), hashArray(this.stereotypes.map((val) => val.pointerHashCode)), hashArray(this.taggedValues), ]); } accept_PackageableElementVisitor<T>( visitor: PackageableElementVisitor<T>, ): T { return visitor.visit_Class(this); } } export enum CLASS_PROPERTY_TYPE { CLASS = 'CLASS', ENUMERATION = 'ENUMERATION', MEASURE = 'MEASURE', UNIT = 'UNIT', PRIMITIVE = 'PRIMITIVE', } export const getClassPropertyType = (type: Type): CLASS_PROPERTY_TYPE => { if (type instanceof PrimitiveType) { return CLASS_PROPERTY_TYPE.PRIMITIVE; } else if (type instanceof Enumeration) { return CLASS_PROPERTY_TYPE.ENUMERATION; } else if (type instanceof Class) { return CLASS_PROPERTY_TYPE.CLASS; } else if (type instanceof Unit) { return CLASS_PROPERTY_TYPE.UNIT; } else if (type instanceof Measure) { return CLASS_PROPERTY_TYPE.MEASURE; } throw new UnsupportedOperationError(`Can't classify class property`, type); };
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/components/__tests__/QueryBuilder_BuildLambdaFailure.test.tsx
<reponame>nayanika2/legend-studio<gh_stars>0 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <reference types="jest-extended" /> import { getByText } from '@testing-library/react'; import { malformedFilterExpression, errorInGraphLambda, unsupportedFunction, misplacedTakeFunction, unsupportedFunctionWithFullPath, } from './QueryBuilder_FailureTestData'; import ComplexRelationalModel from './QueryBuilder_Model_ComplexRelational.json'; import type { PlainObject } from '@finos/legend-studio-shared'; import { integrationTest, MOBX__enableSpyOrMock, MOBX__disableSpyOrMock, } from '@finos/legend-studio-shared'; import { waitFor } from '@testing-library/dom'; import type { Entity } from '@finos/legend-studio'; import { RawLambda, setUpEditorWithDefaultSDLCData, } from '@finos/legend-studio'; import { QUERY_BUILDER_TEST_ID } from '../../QueryBuilder_Const'; import { QueryBuilderState } from '../../stores/QueryBuilderState'; import { flowResult } from 'mobx'; import { buildQueryBuilderMockedEditorStore } from './QueryBuilder_TestUtils'; const getRawLambda = (jsonRawLambda: { parameters?: object; body?: object; }): RawLambda => new RawLambda(jsonRawLambda.parameters, jsonRawLambda.body); type TestCase = [ string, { entities: PlainObject<Entity>[]; targetClassPath: string; className: string; mappingName: string; runtimeName: string; }, { parameters?: object; body?: object }, string, ]; const relationalCtx = { entities: ComplexRelationalModel, targetClassPath: 'model::pure::tests::model::simple::Person', className: 'Person', mappingName: 'simpleRelationalMapping', runtimeName: 'MyRuntime', }; const cases: TestCase[] = [ [ 'Graph element resolution issue', relationalCtx, errorInGraphLambda, `Can't find type 'model::pure::tests::model::simple::NotFound'`, ], [ 'Unsupported function', relationalCtx, unsupportedFunction, `Can't find expression builder for function 'testUnsupported': no compatible function expression builder available from plugins`, ], [ 'Unsupported function (with full-path)', relationalCtx, unsupportedFunctionWithFullPath, `Can't find expression builder for function 'something::getAll': no compatible function expression builder available from plugins`, ], [ 'Malformed filter()', relationalCtx, malformedFilterExpression, `Can't build filter() expression: filter() expects 1 argument`, ], [ 'Misplaced take()', relationalCtx, misplacedTakeFunction, `Can't process take() expression: only support take() in TDS expression`, ], ]; describe( integrationTest( 'Query builder lambda processer should properly handle failure', ), () => { test.each(cases)( '%s', async (testName, context, lambdaJson, errorMessage) => { const { entities, targetClassPath, className, mappingName, runtimeName, } = context; const mockedEditorStore = buildQueryBuilderMockedEditorStore(); const renderResult = await setUpEditorWithDefaultSDLCData( mockedEditorStore, { entities, }, ); MOBX__enableSpyOrMock(); mockedEditorStore.graphState.globalCompileInFormMode = jest.fn(); MOBX__disableSpyOrMock(); const queryBuilderState = mockedEditorStore.getEditorExtensionState(QueryBuilderState); await flowResult(queryBuilderState.setOpenQueryBuilder(true)); queryBuilderState.querySetupState.setClass( mockedEditorStore.graphState.graph.getClass(targetClassPath), ); queryBuilderState.resetData(); const queryBuilderSetup = await waitFor(() => renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_SETUP), ); // ensure form has updated with respect to the new state await waitFor(() => getByText(queryBuilderSetup, className)); await waitFor(() => getByText(queryBuilderSetup, mappingName)); await waitFor(() => getByText(queryBuilderSetup, runtimeName)); expect(() => queryBuilderState.buildStateFromRawLambda(getRawLambda(lambdaJson)), ).toThrowError(errorMessage); }, ); }, );
nayanika2/legend-studio
packages/legend-studio/src/components/__tests__/SDLCServerConfig.test.tsx
<gh_stars>0 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { App } from '../App'; import { integrationTest, MOBX__enableSpyOrMock, MOBX__disableSpyOrMock, } from '@finos/legend-studio-shared'; import { MemoryRouter, Router } from 'react-router-dom'; import { render } from '@testing-library/react'; import { waitFor } from '@testing-library/dom'; import { getTestApplicationConfig, testApplicationConfigData, testApplicationVersionData, } from '../../stores/StoreTestUtils'; import { getMockedApplicationStore } from '../ComponentTestUtils'; import type { ApplicationStore } from '../../stores/ApplicationStore'; import { PluginManager } from '../../application/PluginManager'; import { ApplicationConfig } from '../../stores/ApplicationConfig'; import { createMemoryHistory } from 'history'; import { generateSetupRoute, URL_PATH_PLACEHOLDER } from '../../stores/Router'; let applicationStore: ApplicationStore; const getTestApplicationConfigWithMultiSDLCServer = ( extraConfigData = {}, ): ApplicationConfig => new ApplicationConfig( { ...testApplicationConfigData, ...extraConfigData, }, testApplicationVersionData, '/studio/', ); const setupMockedApplicationStoreForSuccessfulLoadding = (): void => { applicationStore = getMockedApplicationStore(getTestApplicationConfig()); MOBX__enableSpyOrMock(); jest .spyOn(applicationStore.networkClientManager.sdlcClient, 'isAuthorized') .mockResolvedValueOnce(true); jest .spyOn( applicationStore.networkClientManager.sdlcClient, 'hasAcceptedTermsOfService', ) .mockResolvedValueOnce(['stubUrl']); jest .spyOn(applicationStore.networkClientManager.sdlcClient, 'getProjects') .mockResolvedValue([]); MOBX__disableSpyOrMock(); }; test( integrationTest( 'URL is properly reset with configured SDLC when only one server is specified in the config (legacy SDLC config form)', ), async () => { const config = getTestApplicationConfigWithMultiSDLCServer({ sdlc: { url: 'https://testSdlcUrl1' }, }); setupMockedApplicationStoreForSuccessfulLoadding(); const history = createMemoryHistory({ initialEntries: ['/something/'] }); render( <Router history={history}> <App config={config} pluginManager={PluginManager.create()} /> </Router>, ); await waitFor(() => expect(history.location.pathname).toEqual( generateSetupRoute(URL_PATH_PLACEHOLDER, undefined), ), ); }, ); test( integrationTest( 'SDLC server configuration is required when the SDLC server key in the URL is not recognised', ), async () => { const config = getTestApplicationConfigWithMultiSDLCServer({ sdlc: [ { label: 'Server1', key: 'server1', url: 'https://testSdlcUrl1', }, { label: 'Server2', key: 'server2', url: 'https://testSdlcUrl2', }, ], }); setupMockedApplicationStoreForSuccessfulLoadding(); const { queryByText } = render( <MemoryRouter initialEntries={['/something/']}> <App config={config} pluginManager={PluginManager.create()} /> </MemoryRouter>, ); await waitFor(() => expect(queryByText('SDLC Server')).not.toBeNull()); }, ); test( integrationTest('SDLC server configuration can be done via URL'), async () => { const config = getTestApplicationConfigWithMultiSDLCServer({ sdlc: [ { label: 'Server1', key: 'server1', url: 'https://testSdlcUrl1', }, { label: 'Server2', key: 'server2', url: 'https://testSdlcUrl2', }, { label: 'Server3', key: 'server3', url: 'https://testSdlcUrl2', }, ], }); setupMockedApplicationStoreForSuccessfulLoadding(); const { queryByText } = render( <MemoryRouter initialEntries={['/server1/']}> <App config={config} pluginManager={PluginManager.create()} /> </MemoryRouter>, ); await waitFor(() => expect(queryByText('Next')).not.toBeNull()); }, ); test( integrationTest( 'SDLC server configuration is not required when only one server is specified in the config', ), async () => { const config = getTestApplicationConfigWithMultiSDLCServer({ sdlc: [ { label: 'Server1', key: 'server1', url: 'https://testSdlcUrl1', }, ], }); setupMockedApplicationStoreForSuccessfulLoadding(); const { queryByText } = render( <MemoryRouter initialEntries={['/server1/']}> <App config={config} pluginManager={PluginManager.create()} /> </MemoryRouter>, ); await waitFor(() => expect(queryByText('Next')).not.toBeNull()); }, ); test( integrationTest( 'URL is properly reset with configured SDLC when only one server is specified in the config', ), async () => { const config = getTestApplicationConfigWithMultiSDLCServer({ sdlc: [ { label: 'Server1', key: 'server1', url: 'https://testSdlcUrl1', }, ], }); setupMockedApplicationStoreForSuccessfulLoadding(); const history = createMemoryHistory({ initialEntries: ['/something/'] }); render( <Router history={history}> <App config={config} pluginManager={PluginManager.create()} /> </Router>, ); await waitFor(() => expect(history.location.pathname).toEqual( generateSetupRoute('server1', undefined), ), ); }, ); test( integrationTest( 'URL is properly reset with configured SDLC when only one server is specified in the config (legacy SDLC config form)', ), async () => { const config = getTestApplicationConfigWithMultiSDLCServer({ sdlc: { url: 'https://testSdlcUrl1' }, }); setupMockedApplicationStoreForSuccessfulLoadding(); const history = createMemoryHistory({ initialEntries: ['/something/'] }); render( <Router history={history}> <App config={config} pluginManager={PluginManager.create()} /> </Router>, ); await waitFor(() => expect(history.location.pathname).toEqual( generateSetupRoute(URL_PATH_PLACEHOLDER, undefined), ), ); }, );
nayanika2/legend-studio
packages/legend-studio-shared/src/index.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export * from './utils/CommonUtils'; export * from './utils/AssertionUtils'; export * from './utils/FormatterUtils'; export * from './utils/ErrorUtils'; export * from './utils/NetworkUtils'; export * from './utils/ValidatorUtils'; export * from './utils/HashUtils'; export * from './utils/TestUtils'; export * from './utils/RandomUtils'; export * from './utils/SerializationUtils'; export * from './data-structures/Pair'; export * from './data-structures/Stack'; export * from './states/ActionState'; export * from './plugins/AbstractPluginManager';
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/transformation/pureProtocol/serializationHelpers/V1_ConnectionSerializationHelper.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { alias, createModelSchema, deserialize, custom, serialize, primitive, list, optional, } from 'serializr'; import type { PlainObject } from '@finos/legend-studio-shared'; import { usingConstantValueSchema, IllegalStateError, UnsupportedOperationError, } from '@finos/legend-studio-shared'; import { V1_ModelChainConnection } from '../../../model/packageableElements/store/modelToModel/connection/V1_ModelChainConnection'; import { V1_PackageableConnection } from '../../../model/packageableElements/connection/V1_PackageableConnection'; import type { V1_Connection } from '../../../model/packageableElements/connection/V1_Connection'; import { V1_JsonModelConnection } from '../../../model/packageableElements/store/modelToModel/connection/V1_JsonModelConnection'; import { V1_XmlModelConnection } from '../../../model/packageableElements/store/modelToModel/connection/V1_XmlModelConnection'; import { V1_FlatDataConnection } from '../../../model/packageableElements/store/flatData/connection/V1_FlatDataConnection'; import type { V1_DatabaseConnection } from '../../../model/packageableElements/store/relational/connection/V1_RelationalDatabaseConnection'; import { V1_RelationalDatabaseConnection } from '../../../model/packageableElements/store/relational/connection/V1_RelationalDatabaseConnection'; import type { V1_DatasourceSpecification } from '../../../model/packageableElements/store/relational/connection/V1_DatasourceSpecification'; import { V1_LocalH2DataSourceSpecification, V1_SnowflakeDatasourceSpecification, V1_BigQueryDatasourceSpecification, V1_StaticDatasourceSpecification, V1_EmbeddedH2DatasourceSpecification, V1_RedshiftDatasourceSpecification, } from '../../../model/packageableElements/store/relational/connection/V1_DatasourceSpecification'; import type { V1_AuthenticationStrategy } from '../../../model/packageableElements/store/relational/connection/V1_AuthenticationStrategy'; import { V1_SnowflakePublicAuthenticationStrategy, V1_GCPApplicationDefaultCredentialsAuthenticationStrategy, V1_OAuthAuthenticationStrategy, V1_DefaultH2AuthenticationStrategy, V1_DelegatedKerberosAuthenticationStrategy, V1_TestDatabaseAuthenticationStrategy, V1_UserPasswordAuthenticationStrategy, } from '../../../model/packageableElements/store/relational/connection/V1_AuthenticationStrategy'; import type { PureProtocolProcessorPlugin } from '../../../../PureProtocolProcessorPlugin'; import type { StoreRelational_PureProtocolProcessorPlugin_Extension } from '../../../../StoreRelational_PureProtocolProcessorPlugin_Extension'; import { V1_ConnectionPointer } from '../../../model/packageableElements/connection/V1_ConnectionPointer'; export const V1_PACKAGEABLE_CONNECTION_ELEMENT_PROTOCOL_TYPE = 'connection'; export enum V1_ConnectionType { CONNECTION_POINTER = 'connectionPointer', // MODEL_CONNECTION = 'ModelConnection', MODEL_CHAIN_CONNECTION = 'ModelChainConnection', JSON_MODEL_CONNECTION = 'JsonModelConnection', XML_MODEL_CONNECTION = 'XmlModelConnection', FLAT_DATA_CONNECTION = 'FlatDataConnection', RELATIONAL_DATABASE_CONNECTION = 'RelationalDatabaseConnection', } export const V1_connectionPointerModelSchema = createModelSchema( V1_ConnectionPointer, { _type: usingConstantValueSchema(V1_ConnectionType.CONNECTION_POINTER), connection: primitive(), }, ); export const V1_modelChainConnectionModelSchema = createModelSchema( V1_ModelChainConnection, { _type: usingConstantValueSchema(V1_ConnectionType.MODEL_CHAIN_CONNECTION), store: alias('element', optional(primitive())), // @MARKER: GRAMMAR ROUNDTRIP --- omit this information during protocol transformation as it can be interpreted while building the graph mappings: list(primitive()), }, ); export const V1_jsonModelConnectionModelSchema = createModelSchema( V1_JsonModelConnection, { _type: usingConstantValueSchema(V1_ConnectionType.JSON_MODEL_CONNECTION), class: primitive(), store: alias('element', optional(primitive())), // @MARKER: GRAMMAR ROUNDTRIP --- omit this information during protocol transformation as it can be interpreted while building the graph url: primitive(), }, ); export const V1_xmlModelConnectionModelSchema = createModelSchema( V1_XmlModelConnection, { _type: usingConstantValueSchema(V1_ConnectionType.XML_MODEL_CONNECTION), class: primitive(), store: alias('element', optional(primitive())), // @MARKER: GRAMMAR ROUNDTRIP --- omit this information during protocol transformation as it can be interpreted while building the graph url: primitive(), }, ); export const V1_flatDataConnectionModelSchema = createModelSchema( V1_FlatDataConnection, { _type: usingConstantValueSchema(V1_ConnectionType.FLAT_DATA_CONNECTION), store: alias('element', primitive()), url: primitive(), }, ); // ---------------------------------------- Datasource specification ---------------------------------------- enum V1_DatasourceSpecificationType { STATIC = 'static', H2_EMBEDDED = 'h2Embedded', H2_LOCAL = 'h2Local', SNOWFLAKE = 'snowflake', REDSHIFT = 'redshift', BIGQUERY = 'bigQuery', } const staticDatasourceSpecificationModelSchema = createModelSchema( V1_StaticDatasourceSpecification, { _type: usingConstantValueSchema(V1_DatasourceSpecificationType.STATIC), databaseName: primitive(), host: primitive(), port: primitive(), }, ); const embeddedH2DatasourceSpecificationModelSchema = createModelSchema( V1_EmbeddedH2DatasourceSpecification, { _type: usingConstantValueSchema(V1_DatasourceSpecificationType.H2_EMBEDDED), autoServerMode: primitive(), databaseName: primitive(), directory: primitive(), }, ); const localH2DatasourceSpecificationModelSchema = createModelSchema( V1_LocalH2DataSourceSpecification, { _type: usingConstantValueSchema(V1_DatasourceSpecificationType.H2_LOCAL), testDataSetupCsv: optional(primitive()), testDataSetupSqls: list(primitive()), }, ); const snowflakeDatasourceSpecificationModelSchema = createModelSchema( V1_SnowflakeDatasourceSpecification, { _type: usingConstantValueSchema(V1_DatasourceSpecificationType.SNOWFLAKE), accountName: primitive(), cloudType: primitive(), databaseName: primitive(), quotedIdentifiersIgnoreCase: primitive(), region: primitive(), warehouseName: primitive(), }, ); const redshiftDatasourceSpecificationModelSchema = createModelSchema( V1_RedshiftDatasourceSpecification, { _type: usingConstantValueSchema(V1_DatasourceSpecificationType.REDSHIFT), databaseName: primitive(), endpoint: primitive(), port: primitive(), }, ); const bigqueryDatasourceSpecificationModelSchema = createModelSchema( V1_BigQueryDatasourceSpecification, { _type: usingConstantValueSchema(V1_DatasourceSpecificationType.BIGQUERY), defaultDataset: primitive(), projectId: primitive(), }, ); export const V1_serializeDatasourceSpecification = ( protocol: V1_DatasourceSpecification, plugins: PureProtocolProcessorPlugin[], ): PlainObject<V1_DatasourceSpecification> => { if (protocol instanceof V1_StaticDatasourceSpecification) { return serialize(staticDatasourceSpecificationModelSchema, protocol); } else if (protocol instanceof V1_EmbeddedH2DatasourceSpecification) { return serialize(embeddedH2DatasourceSpecificationModelSchema, protocol); } else if (protocol instanceof V1_SnowflakeDatasourceSpecification) { return serialize(snowflakeDatasourceSpecificationModelSchema, protocol); } else if (protocol instanceof V1_BigQueryDatasourceSpecification) { return serialize(bigqueryDatasourceSpecificationModelSchema, protocol); } else if (protocol instanceof V1_LocalH2DataSourceSpecification) { return serialize(localH2DatasourceSpecificationModelSchema, protocol); } else if (protocol instanceof V1_RedshiftDatasourceSpecification) { return serialize(redshiftDatasourceSpecificationModelSchema, protocol); } const extraConnectionDatasourceSpecificationProtocolSerializers = plugins.flatMap( (plugin) => ( plugin as StoreRelational_PureProtocolProcessorPlugin_Extension ).V1_getExtraConnectionDatasourceSpecificationProtocolSerializers?.() ?? [], ); for (const serializer of extraConnectionDatasourceSpecificationProtocolSerializers) { const json = serializer(protocol); if (json) { return json; } } throw new UnsupportedOperationError( `Can't serialize datasource specification: no compatible serializer available from plugins`, protocol, ); }; export const V1_deserializeDatasourceSpecification = ( json: PlainObject<V1_DatasourceSpecification>, plugins: PureProtocolProcessorPlugin[], ): V1_DatasourceSpecification => { switch (json._type) { case V1_DatasourceSpecificationType.STATIC: return deserialize(staticDatasourceSpecificationModelSchema, json); case V1_DatasourceSpecificationType.H2_EMBEDDED: return deserialize(embeddedH2DatasourceSpecificationModelSchema, json); case V1_DatasourceSpecificationType.SNOWFLAKE: return deserialize(snowflakeDatasourceSpecificationModelSchema, json); case V1_DatasourceSpecificationType.BIGQUERY: return deserialize(bigqueryDatasourceSpecificationModelSchema, json); case V1_DatasourceSpecificationType.H2_LOCAL: return deserialize(localH2DatasourceSpecificationModelSchema, json); case V1_DatasourceSpecificationType.REDSHIFT: return deserialize(redshiftDatasourceSpecificationModelSchema, json); default: { const extraConnectionDatasourceSpecificationProtocolDeserializers = plugins.flatMap( (plugin) => ( plugin as StoreRelational_PureProtocolProcessorPlugin_Extension ).V1_getExtraConnectionDatasourceSpecificationProtocolDeserializers?.() ?? [], ); for (const deserializer of extraConnectionDatasourceSpecificationProtocolDeserializers) { const protocol = deserializer(json); if (protocol) { return protocol; } } throw new UnsupportedOperationError( `Can't deserialize datasource specification of type '${json._type}': no compatible deserializer available from plugins`, ); } } }; // ---------------------------------------- Authentication strategy ---------------------------------------- enum V1_AuthenticationStrategyType { DELEGATED_KERBEROS = 'delegatedKerberos', SNOWFLAKE_PUBLIC = 'snowflakePublic', GCP_APPLICATION_DEFAULT_CREDENTIALS = 'gcpApplicationDefaultCredentials', H2_DEFAULT = 'h2Default', TEST = 'test', OAUTH = 'oauth', USER_PASSWORD = '<PASSWORD>', } const V1_delegatedKerberosAuthenticationStrategyModelSchema = createModelSchema( V1_DelegatedKerberosAuthenticationStrategy, { _type: usingConstantValueSchema( V1_AuthenticationStrategyType.DELEGATED_KERBEROS, ), serverPrincipal: optional(primitive()), }, ); const V1_defaultH2AuthenticationStrategyModelSchema = createModelSchema( V1_DefaultH2AuthenticationStrategy, { _type: usingConstantValueSchema(V1_AuthenticationStrategyType.H2_DEFAULT) }, ); const V1_testDatabaseAuthenticationStrategyModelSchema = createModelSchema( V1_TestDatabaseAuthenticationStrategy, { _type: usingConstantValueSchema(V1_AuthenticationStrategyType.TEST) }, ); const V1_snowflakePublicAuthenticationStrategyModelSchema = createModelSchema( V1_SnowflakePublicAuthenticationStrategy, { _type: usingConstantValueSchema( V1_AuthenticationStrategyType.SNOWFLAKE_PUBLIC, ), privateKeyVaultReference: primitive(), passPhraseVaultReference: primitive(), publicUserName: primitive(), }, ); const V1_userPasswordAuthenticationStrategyModelSchema = createModelSchema( V1_UserPasswordAuthenticationStrategy, { _type: usingConstantValueSchema( V1_AuthenticationStrategyType.USER_PASSWORD, ), userName: primitive(), passwordVaultReference: primitive(), }, ); const V1_GCPApplicationDefaultCredentialsAuthenticationStrategyModelSchema = createModelSchema(V1_GCPApplicationDefaultCredentialsAuthenticationStrategy, { _type: usingConstantValueSchema( V1_AuthenticationStrategyType.GCP_APPLICATION_DEFAULT_CREDENTIALS, ), }); const V1_oAuthAuthenticationStrategyModelSchema = createModelSchema( V1_OAuthAuthenticationStrategy, { _type: usingConstantValueSchema(V1_AuthenticationStrategyType.OAUTH), oauthKey: primitive(), scopeName: primitive(), }, ); export const V1_serializeAuthenticationStrategy = ( protocol: V1_AuthenticationStrategy, plugins: PureProtocolProcessorPlugin[], ): PlainObject<V1_AuthenticationStrategy> => { if (protocol instanceof V1_DelegatedKerberosAuthenticationStrategy) { return serialize( V1_delegatedKerberosAuthenticationStrategyModelSchema, protocol, ); } else if (protocol instanceof V1_DefaultH2AuthenticationStrategy) { return serialize(V1_defaultH2AuthenticationStrategyModelSchema, protocol); } else if (protocol instanceof V1_TestDatabaseAuthenticationStrategy) { return serialize( V1_testDatabaseAuthenticationStrategyModelSchema, protocol, ); } else if (protocol instanceof V1_SnowflakePublicAuthenticationStrategy) { return serialize( V1_snowflakePublicAuthenticationStrategyModelSchema, protocol, ); } else if ( protocol instanceof V1_GCPApplicationDefaultCredentialsAuthenticationStrategy ) { return serialize( V1_GCPApplicationDefaultCredentialsAuthenticationStrategyModelSchema, protocol, ); } else if (protocol instanceof V1_OAuthAuthenticationStrategy) { return serialize(V1_oAuthAuthenticationStrategyModelSchema, protocol); } else if (protocol instanceof V1_UserPasswordAuthenticationStrategy) { return serialize( V1_userPasswordAuthenticationStrategyModelSchema, protocol, ); } const extraConnectionAuthenticationStrategyProtocolSerializers = plugins.flatMap( (plugin) => ( plugin as StoreRelational_PureProtocolProcessorPlugin_Extension ).V1_getExtraConnectionAuthenticationStrategyProtocolSerializers?.() ?? [], ); for (const serializer of extraConnectionAuthenticationStrategyProtocolSerializers) { const json = serializer(protocol); if (json) { return json; } } throw new UnsupportedOperationError( `Can't serialize authentication strategy: no compatible serializer available from plugins`, protocol, ); }; export const V1_deserializeAuthenticationStrategy = ( json: PlainObject<V1_AuthenticationStrategy>, plugins: PureProtocolProcessorPlugin[], ): V1_AuthenticationStrategy => { switch (json._type) { case V1_AuthenticationStrategyType.DELEGATED_KERBEROS: return deserialize( V1_delegatedKerberosAuthenticationStrategyModelSchema, json, ); case V1_AuthenticationStrategyType.H2_DEFAULT: return deserialize(V1_defaultH2AuthenticationStrategyModelSchema, json); case V1_AuthenticationStrategyType.SNOWFLAKE_PUBLIC: return deserialize( V1_snowflakePublicAuthenticationStrategyModelSchema, json, ); case V1_AuthenticationStrategyType.USER_PASSWORD: return deserialize( V1_userPasswordAuthenticationStrategyModelSchema, json, ); case V1_AuthenticationStrategyType.GCP_APPLICATION_DEFAULT_CREDENTIALS: return deserialize( V1_GCPApplicationDefaultCredentialsAuthenticationStrategyModelSchema, json, ); case V1_AuthenticationStrategyType.TEST: return deserialize( V1_testDatabaseAuthenticationStrategyModelSchema, json, ); case V1_AuthenticationStrategyType.OAUTH: return deserialize(V1_oAuthAuthenticationStrategyModelSchema, json); default: { const extraConnectionAuthenticationStrategyProtocolDeserializers = plugins.flatMap( (plugin) => ( plugin as StoreRelational_PureProtocolProcessorPlugin_Extension ).V1_getExtraConnectionAuthenticationStrategyProtocolDeserializers?.() ?? [], ); for (const deserializer of extraConnectionAuthenticationStrategyProtocolDeserializers) { const protocol = deserializer(json); if (protocol) { return protocol; } } throw new UnsupportedOperationError( `Can't deserialize authentication strategy of type '${json._type}': no compatible deserializer available from plugins`, ); } } }; export const V1_serializeConnectionValue = ( protocol: V1_Connection, allowPointer: boolean, ): PlainObject<V1_Connection> => { /* @MARKER: NEW CONNECTION TYPE SUPPORT --- consider adding connection type handler here whenever support for a new one is added to the app */ if (protocol instanceof V1_JsonModelConnection) { return serialize(V1_jsonModelConnectionModelSchema, protocol); } else if (protocol instanceof V1_ModelChainConnection) { return serialize(V1_modelChainConnectionModelSchema, protocol); } else if (protocol instanceof V1_XmlModelConnection) { return serialize(V1_xmlModelConnectionModelSchema, protocol); } else if (protocol instanceof V1_FlatDataConnection) { return serialize(V1_flatDataConnectionModelSchema, protocol); } else if (protocol instanceof V1_RelationalDatabaseConnection) { return serialize(V1_RelationalDatabaseConnection, protocol); } else if (protocol instanceof V1_ConnectionPointer) { if (allowPointer) { return serialize(V1_connectionPointerModelSchema, protocol); } throw new IllegalStateError( `Serializing connection pointer is not allowed here`, ); } throw new UnsupportedOperationError(`Can't serialize connection`, protocol); }; export const V1_deserializeConnectionValue = ( json: PlainObject<V1_Connection>, allowPointer: boolean, ): V1_Connection => { switch (json._type) { /* @MARKER: NEW CONNECTION TYPE SUPPORT --- consider adding connection type handler here whenever support for a new one is added to the app */ case V1_ConnectionType.JSON_MODEL_CONNECTION: return deserialize(V1_jsonModelConnectionModelSchema, json); case V1_ConnectionType.MODEL_CHAIN_CONNECTION: return deserialize(V1_modelChainConnectionModelSchema, json); case V1_ConnectionType.XML_MODEL_CONNECTION: return deserialize(V1_xmlModelConnectionModelSchema, json); case V1_ConnectionType.FLAT_DATA_CONNECTION: return deserialize(V1_flatDataConnectionModelSchema, json); case V1_ConnectionType.RELATIONAL_DATABASE_CONNECTION: return deserialize(V1_RelationalDatabaseConnection, json); case V1_ConnectionType.CONNECTION_POINTER: if (allowPointer) { return deserialize(V1_connectionPointerModelSchema, json); } throw new IllegalStateError( `Deserializing connection pointer is not allowed here`, ); default: throw new UnsupportedOperationError( `Can't deserialize connection of type '${json._type}'`, ); } }; export const V1_serializeDatabaseConnectionValue = ( protocol: V1_DatabaseConnection, ): PlainObject<V1_DatabaseConnection> => { if (protocol instanceof V1_RelationalDatabaseConnection) { return serialize(V1_RelationalDatabaseConnection, protocol); } throw new UnsupportedOperationError( `Can't serialize database connection`, protocol, ); }; export const V1_deserializeDatabaseConnectionValue = ( json: PlainObject<V1_DatabaseConnection>, ): V1_DatabaseConnection => { switch (json._type) { case V1_ConnectionType.RELATIONAL_DATABASE_CONNECTION: return deserialize(V1_RelationalDatabaseConnection, json); default: throw new UnsupportedOperationError( `Can't deserialize database connection of type '${json._type}'`, ); } }; export const V1_packageableConnectionModelSchema = createModelSchema( V1_PackageableConnection, { _type: usingConstantValueSchema( V1_PACKAGEABLE_CONNECTION_ELEMENT_PROTOCOL_TYPE, ), connectionValue: custom( (val) => V1_serializeConnectionValue(val, false), (val) => V1_deserializeConnectionValue(val, false), ), name: primitive(), package: primitive(), }, );
nayanika2/legend-studio
packages/legend-studio/src/stores/editor-state/FileGenerationState.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { EditorStore } from '../EditorStore'; import { observable, action, flow, makeAutoObservable } from 'mobx'; import { CORE_LOG_EVENT } from '../../utils/Logger'; import type { TreeData } from '@finos/legend-studio-components'; import type { GenerationTreeNodeData, GenerationFile, GenerationOutputResult, } from '../shared/FileGenerationTreeUtil'; import { GenerationDirectory, GENERATION_FILE_ROOT_NAME, getGenerationTreeData, openNode, populateDirectoryTreeNodeChildren, buildGenerationDirectory, reprocessOpenNodes, } from '../shared/FileGenerationTreeUtil'; import type { FileGenerationSpecification } from '../../models/metamodels/pure/model/packageableElements/fileGeneration/FileGenerationSpecification'; import { PackageableElement } from '../../models/metamodels/pure/model/packageableElements/PackageableElement'; import { PackageableElementReference, PackageableElementExplicitReference, } from '../../models/metamodels/pure/model/packageableElements/PackageableElementReference'; import type { GenerationOutput } from '../../models/metamodels/pure/action/generation/GenerationOutput'; import { ELEMENT_PATH_DELIMITER } from '../../models/MetaModelConst'; export class FileGenerationState { editorStore: EditorStore; fileGeneration: FileGenerationSpecification; isGenerating = false; root: GenerationDirectory; directoryTreeData?: TreeData<GenerationTreeNodeData>; selectedNode?: GenerationTreeNodeData; filesIndex = new Map<string, GenerationFile>(); constructor( editorStore: EditorStore, fileGeneration: FileGenerationSpecification, ) { makeAutoObservable(this, { editorStore: false, fileGeneration: false, directoryTreeData: observable.ref, selectedNode: observable.ref, resetFileGeneration: action, setIsGeneration: action, setDirectoryTreeData: action, processGenerationResult: action, reprocessNodeTree: action, setSelectedNode: action, onTreeNodeSelect: action, addScopeElement: action, deleteScopeElement: action, }); this.editorStore = editorStore; this.fileGeneration = fileGeneration; this.root = new GenerationDirectory(GENERATION_FILE_ROOT_NAME); } resetFileGeneration(): void { this.fileGeneration.configurationProperties = []; } setIsGeneration(isGenerating: boolean): void { this.isGenerating = isGenerating; } setDirectoryTreeData( directoryTreeData: TreeData<GenerationTreeNodeData>, ): void { this.directoryTreeData = directoryTreeData; } getOrCreateDirectory = (directoryName: string): GenerationDirectory => GenerationDirectory.getOrCreateDirectory(this.root, directoryName, true); generate = flow(function* (this: FileGenerationState) { this.isGenerating = true; try { // avoid wasting a network call when the scope is empty, we can short-circuit this if (!this.fileGeneration.scopeElements.length) { this.selectedNode = undefined; this.processGenerationResult([]); return; } const mode = this.editorStore.graphState.graphGenerationState.getFileGenerationConfiguration( this.fileGeneration.type, ).generationMode; const result = (yield this.editorStore.graphState.graphManager.generateFile( this.fileGeneration, mode, this.editorStore.graphState.graph, )) as GenerationOutput[]; this.processGenerationResult(result); } catch (error: unknown) { this.selectedNode = undefined; this.processGenerationResult([]); this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.GENERATION_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } finally { this.isGenerating = false; } }); processGenerationResult(output: GenerationOutput[]): void { this.root = new GenerationDirectory(GENERATION_FILE_ROOT_NAME); this.filesIndex = new Map<string, GenerationFile>(); const openedNodeIds = this.directoryTreeData ? Array.from(this.directoryTreeData.nodes.values()) .filter((node) => node.isOpen) .map((node) => node.id) : []; const generationResultMap = new Map<string, GenerationOutputResult>(); const rootFolder = this.fileGeneration.generationOutputPath ?? this.fileGeneration.path.split(ELEMENT_PATH_DELIMITER).join('_'); output.forEach((entry) => { entry.cleanFileName(rootFolder); if (generationResultMap.has(entry.fileName)) { this.editorStore.applicationStore.logger.warn( CORE_LOG_EVENT.CODE_GENERATION_PROBLEM, 'Found 2 generation outputs with same path', ); } generationResultMap.set(entry.fileName, { generationOutput: entry, parentId: this.fileGeneration.path, }); }); // take generation outputs and put them into the root directory buildGenerationDirectory(this.root, generationResultMap, this.filesIndex); this.directoryTreeData = getGenerationTreeData(this.root); this.reprocessNodeTree( Array.from(generationResultMap.values()), this.directoryTreeData, openedNodeIds, ); } reprocessNodeTree( generationResult: GenerationOutputResult[], treeData: TreeData<GenerationTreeNodeData>, openedNodeIds: string[], ): void { reprocessOpenNodes(treeData, this.filesIndex, this.root, openedNodeIds); // select the current file node if available, else select the first output const selectedFileNodePath = this.selectedNode?.fileNode.path ?? (generationResult.length === 1 ? generationResult[0].generationOutput.fileName : undefined); if (selectedFileNodePath) { const file = this.filesIndex.get(selectedFileNodePath); if (file) { const node = openNode(file, treeData); if (node) { this.onTreeNodeSelect(node, treeData); } } else { this.selectedNode = undefined; } } this.setDirectoryTreeData({ ...treeData }); } setSelectedNode(node?: GenerationTreeNodeData): void { if (this.selectedNode) { this.selectedNode.isSelected = false; } if (node) { node.isSelected = true; } this.selectedNode = node; } onTreeNodeSelect( node: GenerationTreeNodeData, treeData: TreeData<GenerationTreeNodeData>, ): void { if (node.childrenIds?.length) { node.isOpen = !node.isOpen; if (node.fileNode instanceof GenerationDirectory) { populateDirectoryTreeNodeChildren(node, treeData); } } this.setSelectedNode(node); this.setDirectoryTreeData({ ...treeData }); } getScopeElement = ( element: PackageableElement | string, ): PackageableElementReference<PackageableElement> | string | undefined => this.fileGeneration.scopeElements.find((el) => el instanceof PackageableElementReference ? el.value === element : element === el, ); addScopeElement(element: PackageableElement | string): void { const el = this.getScopeElement(element); if (!el) { this.fileGeneration.addScopeElement( element instanceof PackageableElement ? PackageableElementExplicitReference.create(element) : element, ); } } deleteScopeElement(element: PackageableElement | string): void { const el = this.getScopeElement(element); if (el) { this.fileGeneration.deleteScopeElement(el); } } }
nayanika2/legend-studio
packages/legend-studio/src/models/sdlc/models/entity/EntityChangeConflict.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { observable, computed, makeObservable } from 'mobx'; import type { EntityDiff } from '../comparison/EntityDiff'; import { EntityChangeType } from '../entity/EntityChange'; import { IllegalStateError, shallowStringify, } from '@finos/legend-studio-shared'; import type { Entity } from './Entity'; import { extractEntityNameFromPath } from '../../SDLCUtils'; export class EntityChangeConflictResolution { entityPath: string; resolvedEntity?: Entity; constructor(entityPath: string, resolvedEntity: Entity | undefined) { makeObservable(this, { entityPath: observable, resolvedEntity: observable, }); this.entityPath = entityPath; this.resolvedEntity = resolvedEntity; } } export class EntityChangeConflict { entityPath: string; incomingChangeEntityDiff: EntityDiff; currentChangeEntityDiff: EntityDiff; constructor( entityPath: string, incomingChangeEntityDiff: EntityDiff, currentChangeEntityDiff: EntityDiff, ) { makeObservable(this, { entityPath: observable, incomingChangeEntityDiff: observable, currentChangeEntityDiff: observable, entityName: computed, conflictReason: computed, }); this.entityPath = entityPath; this.incomingChangeEntityDiff = incomingChangeEntityDiff; this.currentChangeEntityDiff = currentChangeEntityDiff; } get entityName(): string { return extractEntityNameFromPath(this.entityPath); } get conflictReason(): string { if ( this.incomingChangeEntityDiff.entityChangeType === EntityChangeType.CREATE && this.currentChangeEntityDiff.entityChangeType === EntityChangeType.CREATE ) { return 'Entity is created in both incoming changes and current changes but the contents are different'; } else if ( this.incomingChangeEntityDiff.entityChangeType === EntityChangeType.MODIFY && this.currentChangeEntityDiff.entityChangeType === EntityChangeType.MODIFY ) { return 'Entity is modified in both incoming changes and current changes but the contents are different'; } else if ( this.incomingChangeEntityDiff.entityChangeType === EntityChangeType.DELETE && this.currentChangeEntityDiff.entityChangeType === EntityChangeType.MODIFY ) { return 'Entity is deleted in incoming changes but modified in current changes'; } else if ( this.incomingChangeEntityDiff.entityChangeType === EntityChangeType.MODIFY && this.currentChangeEntityDiff.entityChangeType === EntityChangeType.DELETE ) { return 'Entity is modified in incoming changes but deleted in current changes'; } throw new IllegalStateError( `Detected unfeasible state while computing entity change conflict for entity '${ this.entityPath }', with current change: ${shallowStringify( this.currentChangeEntityDiff, )}, and incoming change: ${shallowStringify( this.incomingChangeEntityDiff, )}`, ); } }
nayanika2/legend-studio
packages/legend-studio/src/stores/ReviewStore.tsx
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { createContext, useContext } from 'react'; import { useLocalObservable } from 'mobx-react-lite'; import { CORE_LOG_EVENT } from '../utils/Logger'; import { guaranteeNonNullable } from '@finos/legend-studio-shared'; import type { Entity } from '../models/sdlc/models/entity/Entity'; import { flow, makeAutoObservable, action } from 'mobx'; import { Review } from '../models/sdlc/models/review/Review'; import type { EditorStore } from './EditorStore'; import { useEditorStore } from './EditorStore'; import { Project } from '../models/sdlc/models/project/Project'; import { EDITOR_MODE, ACTIVITY_MODE, TAB_SIZE } from './EditorConfig'; import { SDLCServerClient } from '../models/sdlc/SDLCServerClient'; export class ReviewStore { editorStore: EditorStore; currentProjectId?: string; currentProject?: Project; currentReviewId?: string; currentReview?: Review; isFetchingCurrentReview = false; isFetchingComparison = false; isApprovingReview = false; isClosingReview = false; isCommittingReview = false; isReopeningReview = false; constructor(editorStore: EditorStore) { makeAutoObservable(this, { editorStore: false, projectId: false, reviewId: false, review: false, setProjectIdAndReviewId: action, }); this.editorStore = editorStore; this.editorStore.activeActivity = ACTIVITY_MODE.REVIEW; } get projectId(): string { return guaranteeNonNullable(this.currentProjectId, 'Project ID must exist'); } get reviewId(): string { return guaranteeNonNullable(this.currentReviewId, 'Review ID must exist'); } get review(): Review { return guaranteeNonNullable(this.currentReview, 'Review must exist'); } init = flow(function* (this: ReviewStore) { try { // init engine yield this.editorStore.graphState.graphManager.setupEngine( this.editorStore.applicationStore.pluginManager, { env: this.editorStore.applicationStore.config.env, tabSize: TAB_SIZE, clientConfig: { baseUrl: this.editorStore.applicationStore.config.engineServerUrl, enableCompression: true, authenticationUrl: SDLCServerClient.authenticationUrl( this.editorStore.applicationStore.config.sdlcServerUrl, ), }, }, ); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SDLC_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } }); setProjectIdAndReviewId(projectId: string, reviewId: string): void { this.currentProjectId = projectId; this.currentReviewId = reviewId; } fetchReviewComparison = flow(function* (this: ReviewStore) { this.isFetchingComparison = true; try { const [fromEntities, toEntities] = (yield Promise.all([ this.editorStore.applicationStore.networkClientManager.sdlcClient.getReviewFromEntities( this.projectId, this.review.id, ), this.editorStore.applicationStore.networkClientManager.sdlcClient.getReviewToEntities( this.projectId, this.review.id, ), ])) as [Entity[], Entity[]]; this.editorStore.changeDetectionState.workspaceBaseRevisionState.setEntities( fromEntities, ); this.editorStore.changeDetectionState.workspaceLatestRevisionState.setEntities( toEntities, ); yield Promise.all([ this.editorStore.changeDetectionState.workspaceBaseRevisionState.buildEntityHashesIndex( fromEntities, CORE_LOG_EVENT.CHANGE_DETECTION_WORKSPACE_HASHES_INDEX_BUILT, ), this.editorStore.changeDetectionState.workspaceLatestRevisionState.buildEntityHashesIndex( toEntities, CORE_LOG_EVENT.CHANGE_DETECTION_LOCAL_HASHES_INDEX_BUILT, ), ]); yield this.editorStore.changeDetectionState.computeAggregatedWorkspaceChanges(); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SDLC_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } finally { this.isFetchingComparison = false; } }); fetchProject = flow(function* (this: ReviewStore) { try { this.currentProject = Project.serialization.fromJson( yield this.editorStore.applicationStore.networkClientManager.sdlcClient.getProject( this.projectId, ), ); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SDLC_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } }); getReview = flow(function* (this: ReviewStore) { try { this.isFetchingCurrentReview = true; this.currentReview = Review.serialization.fromJson( yield this.editorStore.applicationStore.networkClientManager.sdlcClient.getReview( this.projectId, this.reviewId, ), ); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SDLC_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } finally { this.isFetchingCurrentReview = false; } }); approveReview = flow(function* (this: ReviewStore) { this.isApprovingReview = true; try { this.currentReview = Review.serialization.fromJson( yield this.editorStore.applicationStore.networkClientManager.sdlcClient.approveReview( this.projectId, this.review.id, ), ); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SDLC_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } finally { this.isApprovingReview = false; } }); commitReview = flow(function* (this: ReviewStore) { this.isCommittingReview = true; try { this.currentReview = Review.serialization.fromJson( yield this.editorStore.applicationStore.networkClientManager.sdlcClient.commitReview( this.projectId, this.review.id, { message: `${this.review.title} [review]` }, ), ); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SDLC_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } finally { this.isCommittingReview = false; } }); reOpenReview = flow(function* (this: ReviewStore) { this.isReopeningReview = true; try { this.currentReview = Review.serialization.fromJson( yield this.editorStore.applicationStore.networkClientManager.sdlcClient.reopenReview( this.projectId, this.review.id, ), ); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SDLC_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } finally { this.isReopeningReview = false; } }); closeReview = flow(function* (this: ReviewStore) { this.isClosingReview = true; try { this.currentReview = Review.serialization.fromJson( yield this.editorStore.applicationStore.networkClientManager.sdlcClient.closeReview( this.projectId, this.review.id, ), ); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SDLC_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } finally { this.isClosingReview = false; } }); } const ReviewStoreContext = createContext<ReviewStore | undefined>(undefined); export const ReviewStoreProvider = ({ children, }: { children: React.ReactNode; }): React.ReactElement => { const editorStore = useEditorStore(); editorStore.setMode(EDITOR_MODE.REVIEW); const store = useLocalObservable(() => new ReviewStore(editorStore)); return ( <ReviewStoreContext.Provider value={store}> {children} </ReviewStoreContext.Provider> ); }; export const useReviewStore = (): ReviewStore => guaranteeNonNullable( useContext(ReviewStoreContext), 'useReviewStore() hook must be used inside ReviewStore context provider', );
nayanika2/legend-studio
packages/legend-studio/src/stores/__tests__/roundtrip/GenerationSpecificationTestData.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // References to resolve in GenerationSpecification // - GenerationTreeNode - generation element // - FileGeneration pointer export const testGenerationSpecificationRoundtrip = [ { path: 'test::tMapping', content: { _type: 'mapping', classMappings: [], enumerationMappings: [], includedMappings: [], name: 'tMapping', package: 'test', tests: [], }, classifierPath: 'meta::pure::mapping::Mapping', }, { path: 'test::tFileGen', content: { _type: 'fileGeneration', configurationProperties: [], name: 'tFileGen', package: 'test', scopeElements: [], type: 'avro', }, classifierPath: 'meta::pure::generation::metamodel::GenerationConfiguration', }, { path: 'test::tGenSpec', content: { _type: 'generationSpecification', fileGenerations: [ { path: 'tFileGen', type: 'FILE_GENERATION', }, ], generationNodes: [], name: 'tGenSpec', package: 'test', }, classifierPath: 'meta::pure::generation::metamodel::GenerationSpecification', }, { path: '__internal__::SectionIndex', content: { _type: 'sectionIndex', name: 'SectionIndex', package: '__internal__', sections: [ { _type: 'importAware', imports: [], elements: [], parserName: 'Pure', }, { _type: 'importAware', imports: [], elements: ['test::tFileGen'], parserName: 'FileGeneration', }, { _type: 'importAware', imports: [], elements: ['test::tMapping'], parserName: 'Mapping', }, { _type: 'importAware', imports: ['test'], elements: ['test::tGenSpec'], parserName: 'GenerationSpecification', }, ], }, classifierPath: 'meta::pure::metamodel::section::SectionIndex', }, ];
nayanika2/legend-studio
packages/legend-studio/src/models/sdlc/models/review/Review.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { User } from '../User'; import { SKIP, custom, createModelSchema, primitive, optional, } from 'serializr'; import { SerializationFactory, usingModelSchema, } from '@finos/legend-studio-shared'; export enum ReviewState { OPEN = 'OPEN', COMMITTED = 'COMMITTED', CLOSED = 'CLOSED', UNKNOWN = 'UNKNOWN', } export class Review { id!: string; state!: ReviewState; author!: User; title!: string; projectId!: string; workspaceId!: string; webURL!: string; createdAt!: Date; closedAt?: Date; lastUpdatedAt?: Date; committedAt?: Date; static readonly serialization = new SerializationFactory( createModelSchema(Review, { author: usingModelSchema(User.serialization.schema), closedAt: optional( custom( () => SKIP, (value: string | undefined) => (value ? new Date(value) : undefined), ), ), committedAt: optional( custom( () => SKIP, (value: string | undefined) => (value ? new Date(value) : undefined), ), ), createdAt: custom( () => SKIP, (value: string) => new Date(value), ), id: primitive(), lastUpdatedAt: optional( custom( () => SKIP, (value: string | undefined) => (value ? new Date(value) : undefined), ), ), projectId: primitive(), state: primitive(), title: primitive(), webURL: primitive(), workspaceId: primitive(), }), ); } export interface CreateReviewCommand { workspaceId: string; title: string; description: string; } export interface CommitReviewCommand { message: string; }
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/stores/QueryBuilderFetchStructureState.ts
<filename>packages/legend-studio-preset-query-builder/src/stores/QueryBuilderFetchStructureState.ts /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { action, makeAutoObservable } from 'mobx'; import type { QueryBuilderState } from './QueryBuilderState'; import { QueryBuilderGraphFetchTreeState } from './QueryBuilderGraphFetchTreeState'; import type { EditorStore } from '@finos/legend-studio'; import { QueryBuilderProjectionState } from './QueryBuilderProjectionState'; export enum FETCH_STRUCTURE_MODE { PROJECTION = 'PROJECTION', GRAPH_FETCH = 'GRAPH_FETCH', } export class QueryBuilderFetchStructureState { editorStore: EditorStore; queryBuilderState: QueryBuilderState; fetchStructureMode = FETCH_STRUCTURE_MODE.PROJECTION; projectionState: QueryBuilderProjectionState; graphFetchTreeState: QueryBuilderGraphFetchTreeState; constructor(editorStore: EditorStore, queryBuilderState: QueryBuilderState) { makeAutoObservable(this, { editorStore: false, queryBuilderState: false, setFetchStructureMode: action, }); this.editorStore = editorStore; this.queryBuilderState = queryBuilderState; // TODO: we probably should modularize this a bit better this.projectionState = new QueryBuilderProjectionState( editorStore, queryBuilderState, ); this.graphFetchTreeState = new QueryBuilderGraphFetchTreeState( editorStore, queryBuilderState, ); } setFetchStructureMode(val: FETCH_STRUCTURE_MODE): void { this.fetchStructureMode = val; } isGraphFetchMode(): boolean { return this.fetchStructureMode === FETCH_STRUCTURE_MODE.GRAPH_FETCH; } isProjectionMode(): boolean { return this.fetchStructureMode === FETCH_STRUCTURE_MODE.PROJECTION; } }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/model/packageableElements/mapping/V1_EnumerationMapping.ts
<filename>packages/legend-studio/src/models/protocols/pure/v1/model/packageableElements/mapping/V1_EnumerationMapping.ts<gh_stars>1-10 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { hashArray, getNullableFirstElement, } from '@finos/legend-studio-shared'; import type { Hashable } from '@finos/legend-studio-shared'; import { CORE_HASH_STRUCTURE } from '../../../../../../MetaModelConst'; import type { V1_EnumValueMapping } from '../../../model/packageableElements/mapping/V1_EnumValueMapping'; import { V1_getEnumValueMappingSourceValueType } from '../../../model/packageableElements/mapping/V1_EnumValueMapping'; export class V1_EnumerationMapping implements Hashable { id?: string; enumeration!: string; /** * NOTE: the order is important, during deserialization, we want sourceType to be already available * @deprecated since v1_11_0 * This flag is convenient but after all it's not a good design for protocol because deserializer while processing the source value * might not have access to parent context to know the source type. As such, structured source value is preferred. */ sourceType?: string; enumValueMappings: V1_EnumValueMapping[] = []; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.ENUMERATION_MAPPING, this.id ?? '', this.enumeration, // NOTE: older protocol formats have information about source type so we have to account for those, // otherwise, we don't need to account for the source type in hash computation // If there is no enum value mapping, ignore the source type since it's synthetic and used by the editor this.enumValueMappings.length ? getNullableFirstElement( Array.from( new Set( this.enumValueMappings.flatMap((evm) => evm.sourceValues.map(V1_getEnumValueMappingSourceValueType), ), ).values(), ), ) ?? '' : '', // source type hashArray(this.enumValueMappings), ]); } }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/transformation/pureGraph/from/V1_PostProcessorTransformer.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { PostProcessor } from '../../../../../../metamodels/pure/model/packageableElements/store/relational/connection/postprocessor/PostProcessor'; import { MapperPostProcessor } from '../../../../../../metamodels/pure/model/packageableElements/store/relational/connection/postprocessor/MapperPostProcessor'; import type { Mapper } from '../../../../../../metamodels/pure/model/packageableElements/store/relational/connection/postprocessor/Mapper'; import { V1_MapperPostProcessor } from '../../../model/packageableElements/store/relational/connection/postprocessor/V1_MapperPostProcessor'; import type { V1_PostProcessor } from '../../../model/packageableElements/store/relational/connection/postprocessor/V1_PostProcessor'; import { UnsupportedOperationError } from '@finos/legend-studio-shared'; import { SchemaNameMapper, TableNameMapper, } from '../../../../../../metamodels/pure/model/packageableElements/store/relational/connection/postprocessor/Mapper'; import type { V1_Mapper } from '../../../model/packageableElements/store/relational/connection/postprocessor/V1_Mapper'; import { V1_SchemaNameMapper, V1_TableNameMapper, } from '../../../model/packageableElements/store/relational/connection/postprocessor/V1_Mapper'; import type { StoreRelational_PureProtocolProcessorPlugin_Extension } from '../../../../StoreRelational_PureProtocolProcessorPlugin_Extension'; import type { ViewReference } from '../../../../../../metamodels/pure/model/packageableElements/store/relational/model/ViewReference'; import type { TableReference } from '../../../../../../metamodels/pure/model/packageableElements/store/relational/model/TableReference'; import { V1_TablePtr } from '../../../model/packageableElements/store/relational/model/V1_TablePtr'; import type { V1_GraphTransformerContext } from './V1_GraphTransformerContext'; const V1_transformSchemaNameMapper = ( val: SchemaNameMapper, ): V1_SchemaNameMapper => { const schemaNameMapper = new V1_SchemaNameMapper(); schemaNameMapper.from = val.from; schemaNameMapper.to = val.to; return schemaNameMapper; }; export const V1_transformMapper = (val: Mapper): V1_Mapper => { if (val instanceof SchemaNameMapper) { return V1_transformSchemaNameMapper(val); } else if (val instanceof TableNameMapper) { const tableNameMapper = new V1_TableNameMapper(); tableNameMapper.schema = V1_transformSchemaNameMapper(val.schema); tableNameMapper.from = val.from; tableNameMapper.to = val.to; return tableNameMapper; } throw new UnsupportedOperationError( `Can't transform post-processor mapper`, val, ); }; export const V1_transformRelation = ( val: ViewReference | TableReference, ): V1_TablePtr => { const _table = new V1_TablePtr(); _table.database = val.ownerReference.value.path; _table.schema = val.value.schema.name; _table.table = val.value.name; return _table; }; export const V1_transformPostProcessor = ( postProcessor: PostProcessor, context: V1_GraphTransformerContext, ): V1_PostProcessor => { if (postProcessor instanceof MapperPostProcessor) { const mapperPostProcessor = new V1_MapperPostProcessor(); mapperPostProcessor.mappers = postProcessor.mappers.map(V1_transformMapper); return mapperPostProcessor; } const extraConnectionPostProcessorTransformers = context.plugins.flatMap( (plugin) => ( plugin as StoreRelational_PureProtocolProcessorPlugin_Extension ).V1_getExtraConnectionPostProcessorTransformers?.() ?? [], ); for (const transformer of extraConnectionPostProcessorTransformers) { const postprocessorProtocol = transformer(postProcessor, context); if (postprocessorProtocol) { return postprocessorProtocol; } } throw new UnsupportedOperationError( `Can't transform post-processor: no compatible transformer available from plugins`, postProcessor, ); };
nayanika2/legend-studio
packages/legend-studio-shared/src/utils/__tests__/FormatterUtils.test.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { toSentenceCase, prettyCONSTName, tryToMinifyJSONString, tryToMinifyLosslessJSONString, tryToFormatJSONString, tryToFormatLosslessJSONString, fromGrammarString, toGrammarString, toTitleCase, TITLE_CASE_EXCEPTION_WORDS, } from '../FormatterUtils'; import { unitTest } from '../TestUtils'; test(unitTest('To sentence case'), () => { expect(toSentenceCase('')).toEqual(''); expect(toSentenceCase(undefined)).toEqual(''); expect(toSentenceCase('TOM')).toEqual('TOM'); expect(toSentenceCase('tom')).toEqual('Tom'); // trimming expect(toSentenceCase(' tom ')).toEqual('Tom'); // more than 1 word expect(toSentenceCase('tom tom')).toEqual('Tom tom'); }); test(unitTest('To title case'), () => { expect(toTitleCase('')).toEqual(''); expect(toTitleCase(undefined)).toEqual(''); // first and last words are capitalized expect(toTitleCase('TOM')).toEqual('TOM'); expect(toTitleCase('tom')).toEqual('Tom'); expect(toTitleCase('in out out in')).toEqual('In out out In'); // trimming expect(toTitleCase(' tom is trying ')).toEqual('Tom Is Trying'); // exceptions expect( toTitleCase( `Exception words ${TITLE_CASE_EXCEPTION_WORDS.join(' ')} check`, ), ).toEqual(`Exception Words ${TITLE_CASE_EXCEPTION_WORDS.join(' ')} Check`); }); test(unitTest('Prettify CONST name'), () => { expect(prettyCONSTName('')).toEqual(''); expect(prettyCONSTName(undefined)).toEqual(''); expect(prettyCONSTName('TOM')).toEqual('Tom'); expect(prettyCONSTName('TOM_TOM')).toEqual('<NAME>'); }); test(unitTest('Minify JSON string'), () => { expect(tryToMinifyJSONString('1\n2\n\t123')).toEqual('12123'); expect(tryToMinifyJSONString('{')).toEqual('{'); expect(tryToMinifyJSONString('')).toEqual(''); expect(tryToMinifyJSONString(`{\n\t"doc": "doc"}`)).toEqual('{"doc":"doc"}'); }); test(unitTest('Minify JSON string with decimal'), () => { expect(tryToMinifyLosslessJSONString('1.0')).toEqual('1.0'); expect(tryToMinifyLosslessJSONString('{\n "i": 1.0\n}')).toEqual( '{"i":1.0}', ); }); test(unitTest('Format JSON string'), () => { expect(tryToFormatJSONString('1\n2')).toEqual('1\n2'); expect(tryToFormatJSONString('{')).toEqual('{'); expect(tryToFormatJSONString('')).toEqual(''); expect(tryToFormatJSONString(`{"doc": "doc"}`)).toEqual( '{\n "doc": "doc"\n}', ); }); test(unitTest('Format JSON String with decimal'), () => { expect(tryToFormatLosslessJSONString('1.0')).toEqual('1.0'); expect(tryToFormatLosslessJSONString('{"i":1.0}')).toEqual( '{\n "i": 1.0\n}', ); }); test(unitTest('Convert grammar string to JSON value string'), () => { expect(fromGrammarString('id \r\nid1')).toEqual('id \r\nid1'); expect(fromGrammarString("id 'id1'")).toEqual("id 'id1'"); // NOTE: this case should not happen in PURE as this is an invalid string expect(fromGrammarString("id \\'id1\\'")).toEqual("id 'id1'"); expect(fromGrammarString("id \\\\'id1\\\\'")).toEqual("id \\'id1\\'"); }); test(unitTest('Convert JSON value string to grammar string'), () => { expect(toGrammarString("id 'id1'")).toEqual("id \\'id1\\'"); expect(toGrammarString("id \\'id1\\'")).toEqual("id \\\\'id1\\\\'"); expect(toGrammarString("id \r\nid1'")).toEqual("id \r\nid1\\'"); });
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/components/QueryBuilder.tsx
<filename>packages/legend-studio-preset-query-builder/src/components/QueryBuilder.tsx /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { observer } from 'mobx-react-lite'; import { GlobalHotKeys } from 'react-hotkeys'; import { FaUserSecret, FaRobot, FaSave } from 'react-icons/fa'; import { ReflexContainer, ReflexElement, ReflexSplitter } from 'react-reflex'; import { clsx, HammerIcon } from '@finos/legend-studio-components'; import { QueryBuilderFilterPanel } from './QueryBuilderFilterPanel'; import { QueryBuilderExplorerPanel } from './QueryBuilderExplorerPanel'; import { QueryBuilderSetupPanel } from './QueryBuilderSetupPanel'; import { QueryBuilderResultPanel } from './QueryBuilderResultPanel'; import { QueryBuilderLambdaEditor } from './QueryBuilderLambdaEditor'; import type { QueryBuilderState } from '../stores/QueryBuilderState'; import { QueryTextEditorMode } from '../stores/QueryTextEditorState'; import { QueryBuilderUnsupportedExplorerPanel, QueryBuilderUnsupportedPanel, } from './QueryBuilderUnsupportedPanel'; import { QueryBuilderFetchStructurePanel } from './QueryBuilderFetchStructurePanel'; import { QUERY_BUILDER_TEST_ID } from '../QueryBuilder_Const'; import { HOTKEY, HOTKEY_MAP, useApplicationStore } from '@finos/legend-studio'; import { flowResult } from 'mobx'; import Backdrop from '@material-ui/core/Backdrop'; const QueryBuilderStatusBar = observer( (props: { queryBuilderState: QueryBuilderState }) => { const { queryBuilderState } = props; const applicationStore = useApplicationStore(); const openLambdaEditor = (mode: QueryTextEditorMode): void => queryBuilderState.queryTextEditorState.openModal(mode); const compile = (): Promise<void> => flowResult(queryBuilderState.compileQuery()).catch( applicationStore.alertIllegalUnhandledError, ); return ( <div className="query-builder__status-bar"> <div className="query-builder__status-bar__left"></div> <div className="query-builder__status-bar__right"> <button className={clsx( 'query-builder__status-bar__action query-builder__status-bar__compile-btn', { 'query-builder__status-bar__compile-btn--wiggling': queryBuilderState.isCompiling, }, )} disabled={queryBuilderState.isCompiling} onClick={compile} tabIndex={-1} title="Compile (F9)" > <HammerIcon /> </button> <button className={clsx( 'query-builder__status-bar__action query-builder__status-bar__action__toggler', )} onClick={(): void => openLambdaEditor(QueryTextEditorMode.JSON)} tabIndex={-1} title="View Query JSON" >{`{ }`}</button> <button className={clsx( 'query-builder__status-bar__action query-builder__status-bar__action__toggler', )} onClick={(): void => openLambdaEditor(QueryTextEditorMode.TEXT)} tabIndex={-1} title="View Pure Query" > <FaUserSecret /> </button> </div> </div> ); }, ); const QueryBuilderHeader = observer( (props: { queryBuilderState: QueryBuilderState }) => { const { queryBuilderState } = props; const applicationStore = useApplicationStore(); const promoteToService = (): void => queryBuilderState.resultState.setShowServicePathModal(true); const saveQuery = (): Promise<void> => queryBuilderState .saveQuery() .catch(applicationStore.alertIllegalUnhandledError); const disablePromoteToService = !queryBuilderState.querySetupState.mapping; return ( <div className="query-builder__header"> <div className="query-builder__header__content"> <div className="query-builder__header__title"></div> <div className="query-builder__header__actions"> <div className="query-builder__header__action"> <button className="panel__header__action" onClick={promoteToService} disabled={disablePromoteToService} tabIndex={-1} title="Promote to Service" > <FaRobot /> </button> <button className="panel__header__action" onClick={saveQuery} disabled={!queryBuilderState.querySetupState.onSave} tabIndex={-1} title="Save Query" > <FaSave /> </button> </div> </div> </div> </div> ); }, ); const QueryBuilderUnsupported = observer( (props: { queryBuilderState: QueryBuilderState }) => { const { queryBuilderState } = props; return ( <ReflexContainer orientation="vertical"> <ReflexElement size={450} minSize={0}> <QueryBuilderSetupPanel queryBuilderState={queryBuilderState} /> <QueryBuilderUnsupportedExplorerPanel /> </ReflexElement> <ReflexSplitter /> <ReflexElement minSize={0}> <QueryBuilderUnsupportedPanel queryBuilderState={queryBuilderState} /> </ReflexElement> </ReflexContainer> ); }, ); export const QueryBuilder = observer( (props: { queryBuilderState: QueryBuilderState }) => { const { queryBuilderState } = props; const applicationStore = useApplicationStore(); const isQuerySupported = queryBuilderState.isQuerySupported(); // Hotkeys const keyMap = { [HOTKEY.COMPILE]: [HOTKEY_MAP.COMPILE], }; const handlers = { [HOTKEY.COMPILE]: (event: KeyboardEvent | undefined): void => { event?.preventDefault(); flowResult(queryBuilderState.compileQuery()).catch( applicationStore.alertIllegalUnhandledError, ); }, }; return ( <div data-testid={QUERY_BUILDER_TEST_ID.QUERY_BUILDER} className="query-builder" > <GlobalHotKeys keyMap={keyMap} handlers={handlers}> <QueryBuilderHeader queryBuilderState={queryBuilderState} /> <Backdrop className="backdrop" open={queryBuilderState.editorStore.backdrop} /> <div className="query-builder__content"> <ReflexContainer orientation="horizontal"> <ReflexElement minSize={132}> {isQuerySupported ? ( <ReflexContainer orientation="vertical"> <ReflexElement size={450} minSize={300}> <QueryBuilderSetupPanel queryBuilderState={queryBuilderState} /> <QueryBuilderExplorerPanel queryBuilderState={queryBuilderState} /> </ReflexElement> <ReflexSplitter /> <ReflexElement minSize={300}> <QueryBuilderFetchStructurePanel queryBuilderState={queryBuilderState} /> </ReflexElement> <ReflexSplitter /> <ReflexElement minSize={300}> <QueryBuilderFilterPanel queryBuilderState={queryBuilderState} /> </ReflexElement> </ReflexContainer> ) : ( <QueryBuilderUnsupported queryBuilderState={queryBuilderState} /> )} </ReflexElement> <ReflexSplitter /> <ReflexElement size={300} minSize={28}> <QueryBuilderResultPanel queryBuilderState={queryBuilderState} /> </ReflexElement> </ReflexContainer> </div> <QueryBuilderStatusBar queryBuilderState={queryBuilderState} /> {queryBuilderState.queryTextEditorState.mode && ( <QueryBuilderLambdaEditor queryBuilderState={queryBuilderState} /> )} </GlobalHotKeys> </div> ); }, );
nayanika2/legend-studio
packages/legend-studio/src/stores/__tests__/roundtrip/executionPlan/SimpleRelationalPlanTestData.ts
<gh_stars>0 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const simpleRelationalPlan = { plan: { serializer: { name: 'pure', version: 'vX_X_X', }, templateFunctions: [ '<#function renderCollection collection separator><#return collection?join(separator)></#function>', '<#function collectionSize collection> <#return collection?size?c> </#function>', ], rootExecutionNode: { _type: 'relationalTdsInstantiation', resultType: { tdsColumns: [ { name: 'Legal Name', type: 'String', relationalType: 'VARCHAR(204)', }, { name: 'Employee Size', type: 'Number', }, { name: 'Employees/First Name', type: 'String', relationalType: 'VARCHAR(200)', }, { name: 'Employees/Last Name', type: 'String', relationalType: 'VARCHAR(200)', }, ], _type: 'tds', }, executionNodes: [ { sqlQuery: 'select concat("root".Legal_name, \'_LTD\') as "Legal Name", "firmtable_1".aggCol as "Employee Size", "persontable_1".firstName as "Employees/First Name", "persontable_1".lastName as "Employees/Last Name" from FirmTable as "root" left outer join (select "firmtable_2".id as id, count(*) as aggCol from FirmTable as "firmtable_2" left outer join PersonTable as "persontable_0" on ("persontable_0".firm_id = "firmtable_2".id) group by "firmtable_2".id) as "firmtable_1" on ("root".id = "firmtable_1".id) left outer join PersonTable as "persontable_1" on ("persontable_1".firm_id = "root".id)', resultColumns: [ { label: '"Legal Name"', dataType: '', }, { label: '"Employee Size"', dataType: 'INTEGER', }, { label: '"Employees/First Name"', dataType: 'VARCHAR(200)', }, { label: '"Employees/Last Name"', dataType: 'VARCHAR(200)', }, ], connection: { datasourceSpecification: { testDataSetupSqls: [ "Drop table if exists FirmTable;\nDrop table if exists PersonTable;\nCreate Table FirmTable(id INT, Legal_Name VARCHAR(200));\nCreate Table PersonTable(id INT, firm_id INT, lastName VARCHAR(200), firstName VARCHAR(200));\nInsert into FirmTable (id, Legal_Name) values (1, 'FirmX');\nInsert into PersonTable (id, firm_id, lastName, firstName) values (1, 1, 'John', 'Doe');\n", ], _type: 'h2Local', }, authenticationStrategy: { _type: 'h2Default', }, type: 'H2', _type: 'RelationalDatabaseConnection', element: 'model::Test', }, _type: 'sql', resultType: { dataType: 'meta::pure::metamodel::type::Any', _type: 'dataType', }, }, ], }, authDependent: false, }, entities: [ { path: 'model::IncType', content: { _type: 'Enumeration', name: 'IncType', package: 'model', values: [ { value: 'Corp', }, { value: 'LLC', }, ], }, classifierPath: 'meta::pure::metamodel::type::Enumeration', }, { path: 'model::Firm', content: { _type: 'class', constraints: [ { functionDefinition: { _type: 'lambda', body: [ { _type: 'func', function: 'startsWith', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'this', }, ], property: 'legalName', }, { _type: 'string', multiplicity: { lowerBound: 1, upperBound: 1, }, values: ['_'], }, ], }, ], parameters: [], }, name: 'validName', }, ], name: 'Firm', package: 'model', properties: [ { multiplicity: { lowerBound: 1, }, name: 'employees', type: 'model::Person', }, { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'incType', type: 'model::IncType', }, ], qualifiedProperties: [ { body: [ { _type: 'func', function: 'count', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'this', sourceInformation: { endColumn: 23, endLine: 35, sourceId: '', startColumn: 19, startLine: 35, }, }, ], property: 'employees', sourceInformation: { endColumn: 33, endLine: 35, sourceId: '', startColumn: 25, startLine: 35, }, }, ], sourceInformation: { endColumn: 40, endLine: 35, sourceId: '', startColumn: 36, startLine: 35, }, }, ], name: 'employeeSize', parameters: [], returnMultiplicity: { lowerBound: 1, upperBound: 1, }, returnType: 'Number', }, ], superTypes: ['model::LegalEntity'], }, classifierPath: 'meta::pure::metamodel::type::Class', }, { path: 'model::LegalEntity', content: { _type: 'class', name: 'LegalEntity', package: 'model', properties: [ { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'legalName', type: 'String', }, ], }, classifierPath: 'meta::pure::metamodel::type::Class', }, { path: 'model::Person', content: { _type: 'class', name: 'Person', package: 'model', properties: [ { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'firstName', type: 'String', }, { multiplicity: { lowerBound: 1, upperBound: 1, }, name: 'lastName', type: 'String', }, ], }, classifierPath: 'meta::pure::metamodel::type::Class', }, { path: 'model::Test', content: { _type: 'relational', filters: [], includedStores: [], joins: [ { name: 'FirmPerson', operation: { _type: 'dynaFunc', funcName: 'equal', parameters: [ { _type: 'column', column: 'firm_id', table: { _type: 'Table', database: 'model::Test', mainTableDb: 'model::Test', schema: 'default', table: 'PersonTable', }, tableAlias: 'PersonTable', }, { _type: 'column', column: 'id', table: { _type: 'Table', database: 'model::Test', mainTableDb: 'model::Test', schema: 'default', table: 'FirmTable', }, tableAlias: 'FirmTable', }, ], }, }, ], name: 'Test', package: 'model', schemas: [ { name: 'default', tables: [ { columns: [ { name: 'id', nullable: false, type: { _type: 'Integer', }, }, { name: 'Legal_name', nullable: true, type: { _type: 'Varchar', size: 200, }, }, ], name: 'FirmTable', primaryKey: ['id'], }, { columns: [ { name: 'id', nullable: false, type: { _type: 'Integer', }, }, { name: 'firm_id', nullable: true, type: { _type: 'Integer', }, }, { name: 'firstName', nullable: true, type: { _type: 'Varchar', size: 200, }, }, { name: 'lastName', nullable: true, type: { _type: 'Varchar', size: 200, }, }, ], name: 'PersonTable', primaryKey: ['id'], }, ], views: [], }, ], }, classifierPath: 'meta::relational::metamodel::Database', }, { path: 'model::NewMapping', content: { _type: 'mapping', classMappings: [ { _type: 'relational', class: 'model::Firm', distinct: false, mainTable: { _type: 'Table', database: 'model::Test', mainTableDb: 'model::Test', schema: 'default', table: 'FirmTable', }, primaryKey: [ { _type: 'column', column: 'id', table: { _type: 'Table', database: 'model::Test', mainTableDb: 'model::Test', schema: 'default', table: 'FirmTable', }, tableAlias: 'FirmTable', }, ], propertyMappings: [ { _type: 'relationalPropertyMapping', property: { class: 'model::Firm', property: 'legalName', }, relationalOperation: { _type: 'dynaFunc', funcName: 'concat', parameters: [ { _type: 'column', column: 'Legal_name', table: { _type: 'Table', database: 'model::Test', mainTableDb: 'model::Test', schema: 'default', table: 'FirmTable', }, tableAlias: 'FirmTable', }, { _type: 'literal', value: '_LTD', }, ], }, }, { _type: 'relationalPropertyMapping', property: { class: 'model::Firm', property: 'employees', }, relationalOperation: { _type: 'elemtWithJoins', joins: [ { db: 'model::Test', name: 'FirmPerson', }, ], }, target: 'model_Person', }, ], root: true, }, { _type: 'relational', class: 'model::Person', distinct: false, mainTable: { _type: 'Table', database: 'model::Test', mainTableDb: 'model::Test', schema: 'default', table: 'PersonTable', }, primaryKey: [ { _type: 'column', column: 'id', table: { _type: 'Table', database: 'model::Test', mainTableDb: 'model::Test', schema: 'default', table: 'PersonTable', }, tableAlias: 'PersonTable', }, ], propertyMappings: [ { _type: 'relationalPropertyMapping', property: { class: 'model::Person', property: 'firstName', }, relationalOperation: { _type: 'column', column: 'firstName', table: { _type: 'Table', database: 'model::Test', mainTableDb: 'model::Test', schema: 'default', table: 'PersonTable', }, tableAlias: 'PersonTable', }, }, { _type: 'relationalPropertyMapping', property: { class: 'model::Person', property: 'lastName', }, relationalOperation: { _type: 'column', column: 'lastName', table: { _type: 'Table', database: 'model::Test', mainTableDb: 'model::Test', schema: 'default', table: 'PersonTable', }, tableAlias: 'PersonTable', }, }, ], root: true, }, ], enumerationMappings: [], includedMappings: [], name: 'NewMapping', package: 'model', tests: [], }, classifierPath: 'meta::pure::mapping::Mapping', }, ], };
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/action/SourceInformationHelper.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { assertTrue } from '@finos/legend-studio-shared'; import type { SourceInformation } from './SourceInformation'; const COORDINATE_DELIMITER = '__'; export const extractSourceInformationCoordinates = ( sourceInformation: SourceInformation | undefined, ): string[] | undefined => { if (!sourceInformation) { return undefined; } const coordinates = sourceInformation.sourceId.split(COORDINATE_DELIMITER); assertTrue( coordinates.length > 0, `Can't extract source information coordinates: source ID must be a joined string with delimiter '${COORDINATE_DELIMITER}'`, ); return coordinates; }; export const buildSourceInformationSourceId = (coordinates: string[]): string => coordinates.join(COORDINATE_DELIMITER);
nayanika2/legend-studio
packages/legend-studio/src/models/metadata/MetadataServerClient.ts
<reponame>nayanika2/legend-studio<gh_stars>0 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { AbstractServerClient } from '@finos/legend-studio-network'; import type { PlainObject } from '@finos/legend-studio-shared'; import type { ProjectVersion, ProjectVersionEntities, } from './models/ProjectVersionEntities'; interface MetadataServerClientConfig { serverUrl: string; } export class MetadataServerClient extends AbstractServerClient { constructor(config: MetadataServerClientConfig) { super({ baseUrl: config.serverUrl, }); } private _projects = (): string => `${this.networkClient.baseUrl}/projects`; getDependencyEntities = ( /** * List of (direct) dependencies. */ dependencies: PlainObject<ProjectVersion>[], /** * Flag indicating if transitive dependencies should be returned. */ transitive: boolean, /** * Flag indicating whether to return the root of the dependency tree. */ includeOrigin: boolean, ): Promise<PlainObject<ProjectVersionEntities>[]> => this.post( `${this._projects()}/versions/dependencies`, dependencies, undefined, undefined, { transitive, includeOrigin, versioned: false, // we don't need to add version prefix to entity path }, ); }
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/model/packageableElements/store/flatData/model/FlatData.ts
<gh_stars>0 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { observable, computed, action, makeObservable, override } from 'mobx'; import { guaranteeNonNullable, hashArray, addUniqueEntry, deleteEntry, changeEntry, } from '@finos/legend-studio-shared'; import type { Hashable } from '@finos/legend-studio-shared'; import { CORE_HASH_STRUCTURE } from '../../../../../../../MetaModelConst'; import type { FlatDataSection } from './FlatDataSection'; import { Store } from '../../../../../model/packageableElements/store/Store'; import type { PackageableElementVisitor } from '../../../../../model/packageableElements/PackageableElement'; import type { RootFlatDataRecordType } from './FlatDataDataType'; export class FlatData extends Store implements Hashable { sections: FlatDataSection[] = []; constructor(name: string) { super(name); makeObservable<FlatData, '_elementHashCode'>(this, { sections: observable, deleteSection: action, changeSection: action, addSection: action, recordTypes: computed, _elementHashCode: override, }); } findSection = (sectionName: string): FlatDataSection => guaranteeNonNullable( this.sections.find((section) => section.name === sectionName), `Can't find section '${sectionName}' in flat-data store '${this.path}'`, ); deleteSection(value: FlatDataSection): void { deleteEntry(this.sections, value); } changeSection(value: FlatDataSection, newVal: FlatDataSection): void { changeEntry(this.sections, value, newVal); } addSection(value: FlatDataSection): void { addUniqueEntry(this.sections, value); } get recordTypes(): RootFlatDataRecordType[] { return this.sections.flatMap((section) => section.recordType ? [section.recordType] : [], ); } static createStub = (): FlatData => new FlatData(''); protected override get _elementHashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.FLAT_DATA, this.path, hashArray(this.includes.map((include) => include.valueForSerialization)), hashArray(this.sections), ]); } accept_PackageableElementVisitor<T>( visitor: PackageableElementVisitor<T>, ): T { return visitor.visit_FlatData(this); } }
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/model/packageableElements/domain/Function.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { UnsupportedOperationError } from '@finos/legend-studio-shared'; import type { PackageableElementVisitor } from '../../../model/packageableElements/PackageableElement'; import { PackageableElement } from '../../../model/packageableElements/PackageableElement'; export abstract class Function extends PackageableElement { functionName: string; constructor(name: string) { super(name); this.functionName = name; } } export abstract class FunctionDefinition extends Function {} export class NativeFunctiion extends Function { accept_PackageableElementVisitor<T>( visitor: PackageableElementVisitor<T>, ): T { throw new UnsupportedOperationError(); } } export class LambdaFunction extends FunctionDefinition { accept_PackageableElementVisitor<T>( visitor: PackageableElementVisitor<T>, ): T { throw new UnsupportedOperationError(); } }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/transformation/pureGraph/from/V1_SectionIndexTransformer.ts
<filename>packages/legend-studio/src/models/protocols/pure/v1/transformation/pureGraph/from/V1_SectionIndexTransformer.ts /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { UnsupportedOperationError } from '@finos/legend-studio-shared'; import { DefaultCodeSection, ImportAwareCodeSection, } from '../../../../../../metamodels/pure/model/packageableElements/section/Section'; import type { SectionIndex } from '../../../../../../metamodels/pure/model/packageableElements/section/SectionIndex'; import { V1_DefaultCodeSection, V1_ImportAwareCodeSection, } from '../../../model/packageableElements/section/V1_Section'; import { V1_SectionIndex } from '../../../model/packageableElements/section/V1_SectionIndex'; import { V1_initPackageableElement, V1_transformElementReference, } from './V1_CoreTransformerHelper'; const transformDefaultCodeSectionSchema = ( element: DefaultCodeSection, ): V1_DefaultCodeSection => { const defaultCodeSection = new V1_DefaultCodeSection(); defaultCodeSection.elements = element.elements.map((e) => V1_transformElementReference(e), ); defaultCodeSection.parserName = element.parserName; return defaultCodeSection; }; const transformImportAwareCodeSectionSchema = ( element: ImportAwareCodeSection, ): V1_ImportAwareCodeSection => { const importAware = new V1_ImportAwareCodeSection(); importAware.imports = element.imports.map((e) => V1_transformElementReference(e), ); importAware.elements = element.elements.map((e) => V1_transformElementReference(e), ); importAware.parserName = element.parserName; return importAware; }; export const V1_transformSectionIndex = ( element: SectionIndex, ): V1_SectionIndex => { const _sectionIndex = new V1_SectionIndex(); V1_initPackageableElement(_sectionIndex, element); _sectionIndex.package = '__internal__'; _sectionIndex.sections = element.sections.map((section) => { if (section instanceof ImportAwareCodeSection) { return transformImportAwareCodeSectionSchema(section); } else if (section instanceof DefaultCodeSection) { return transformDefaultCodeSectionSchema(section); } throw new UnsupportedOperationError( `Can't transform section index`, section, ); }); return _sectionIndex; };
nayanika2/legend-studio
packages/legend-studio/src/stores/editor-state/FileGenerationViewerState.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { EditorStore } from '../EditorStore'; import { EditorState } from './EditorState'; import { observable, makeObservable, computed } from 'mobx'; import type { GenerationFile } from '../shared/FileGenerationTreeUtil'; import { EDITOR_LANGUAGE, TAB_SIZE } from '../EditorConfig'; export const getTextContent = ( content: string, format: string | undefined, ): string => { switch (format?.toLowerCase()) { case EDITOR_LANGUAGE.JSON: return JSON.stringify(JSON.parse(content), undefined, TAB_SIZE); default: return content; } }; export const getEditorLanguageFromFormat = ( format?: string, ): EDITOR_LANGUAGE => { switch (format?.toLowerCase()) { case EDITOR_LANGUAGE.JAVA: return EDITOR_LANGUAGE.JAVA; case EDITOR_LANGUAGE.JSON: return EDITOR_LANGUAGE.JSON; default: return EDITOR_LANGUAGE.TEXT; } }; export class FileGenerationViewerState extends EditorState { generatedFile: GenerationFile; constructor(editorStore: EditorStore, generatedFile: GenerationFile) { super(editorStore); makeObservable(this, { generatedFile: observable, headerName: computed, }); this.generatedFile = generatedFile; } get headerName(): string { return this.generatedFile.name; } }
nayanika2/legend-studio
packages/legend-studio/src/stores/editor-state/element-editor-state/connection/DatabaseBuilderState.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { TreeData, TreeNodeData } from '@finos/legend-studio-components'; import type { GeneratorFn } from '@finos/legend-studio-shared'; import { addUniqueEntry, assertNonEmptyString, assertTrue, guaranteeNonNullable, isNonNullable, } from '@finos/legend-studio-shared'; import { observable, action, makeObservable, flow, flowResult } from 'mobx'; import { DatabaseBuilderInput, DatabasePattern, TargetDatabase, } from '../../../../models/metamodels/pure/action/generation/DatabaseBuilderInput'; import { getDbNullableTable } from '../../../../models/metamodels/pure/model/helpers/store/relational/model/DatabaseHelper'; import { PackageableElementExplicitReference } from '../../../../models/metamodels/pure/model/packageableElements/PackageableElementReference'; import type { RelationalDatabaseConnection } from '../../../../models/metamodels/pure/model/packageableElements/store/relational/connection/RelationalDatabaseConnection'; import { Column } from '../../../../models/metamodels/pure/model/packageableElements/store/relational/model/Column'; import { Database } from '../../../../models/metamodels/pure/model/packageableElements/store/relational/model/Database'; import type { Schema } from '../../../../models/metamodels/pure/model/packageableElements/store/relational/model/Schema'; import type { Table } from '../../../../models/metamodels/pure/model/packageableElements/store/relational/model/Table'; import { isValidFullPath, resolvePackagePathAndElementName, } from '../../../../models/MetaModelUtils'; import type { Entity } from '../../../../models/sdlc/models/entity/Entity'; import { CORE_LOG_EVENT } from '../../../../utils/Logger'; import type { EditorStore } from '../../../EditorStore'; export abstract class DatabaseBuilderTreeNodeData implements TreeNodeData { isOpen?: boolean; id: string; label: string; parentId?: string; childrenIds?: string[]; isChecked = false; constructor(id: string, label: string, parentId: string | undefined) { this.id = id; this.label = label; this.parentId = parentId; } } export class SchemaDatabaseBuilderTreeNodeData extends DatabaseBuilderTreeNodeData { schema: Schema; constructor(id: string, parentId: string | undefined, schema: Schema) { super(id, schema.name, parentId); this.schema = schema; } } export class TableDatabaseBuilderTreeNodeData extends DatabaseBuilderTreeNodeData { table: Table; constructor(id: string, parentId: string | undefined, table: Table) { super(id, table.name, parentId); this.table = table; } } export class ColumnDatabaseBuilderTreeNodeData extends DatabaseBuilderTreeNodeData { column: Column; constructor(id: string, parentId: string | undefined, column: Column) { super(id, column.name, parentId); this.column = column; } } export interface DatabaseBuilderTreeData extends TreeData<DatabaseBuilderTreeNodeData> { database: Database; } const WILDCARD = '%'; export class DatabaseBuilderState { editorStore: EditorStore; connection: RelationalDatabaseConnection; showModal = false; databaseGrammarCode = ''; isBuildingDatabase = false; isSavingDatabase = false; targetDatabasePath: string; treeData?: DatabaseBuilderTreeData; constructor( editorStore: EditorStore, connection: RelationalDatabaseConnection, ) { makeObservable(this, { showModal: observable, targetDatabasePath: observable, setTargetDatabasePath: action, setModal: action, setDatabaseGrammarCode: action, setTreeData: action, isBuildingDatabase: observable, databaseGrammarCode: observable, isSavingDatabase: observable, treeData: observable, onNodeSelect: flow, buildDatabaseWithTreeData: flow, fetchSchemaDefinitions: flow, fetchSchemaMetadata: flow, fetchTableMetadata: flow, }); this.connection = connection; this.editorStore = editorStore; this.targetDatabasePath = this.currentDatabase?.path ?? 'store::MyDatabase'; } setModal(val: boolean): void { this.showModal = val; } setTreeData(builderTreeData?: DatabaseBuilderTreeData): void { this.treeData = builderTreeData; } setDatabaseGrammarCode(val: string): void { this.databaseGrammarCode = val; } setTargetDatabasePath(val: string): void { this.targetDatabasePath = val; } // Tree Operations *onNodeSelect( this: DatabaseBuilderState, node: DatabaseBuilderTreeNodeData, treeData: DatabaseBuilderTreeData, ): GeneratorFn<void> { if ( node instanceof SchemaDatabaseBuilderTreeNodeData && !node.childrenIds ) { yield flowResult(this.fetchSchemaMetadata(node, treeData)); } else if ( node instanceof TableDatabaseBuilderTreeNodeData && !node.childrenIds ) { yield flowResult(this.fetchTableMetadata(node, treeData)); } node.isOpen = !node.isOpen; this.setTreeData({ ...treeData }); } getChildNodes( node: DatabaseBuilderTreeNodeData, treeData: DatabaseBuilderTreeData, ): DatabaseBuilderTreeNodeData[] | undefined { return node.childrenIds ?.map((n) => treeData.nodes.get(n)) .filter(isNonNullable); } toggleCheckedNode( node: DatabaseBuilderTreeNodeData, treeData: DatabaseBuilderTreeData, ): void { node.isChecked = !node.isChecked; if (node instanceof SchemaDatabaseBuilderTreeNodeData) { this.getChildNodes(node, treeData)?.forEach((n) => { n.isChecked = node.isChecked; }); } else if (node instanceof TableDatabaseBuilderTreeNodeData) { if (node.parentId) { const parent = treeData.nodes.get(node.parentId); if ( parent && this.getChildNodes(parent, treeData)?.every( (e) => e.isChecked === node.isChecked, ) ) { parent.isChecked = node.isChecked; } } } // TODO: handle ColumnDatabaseBuilderTreeNodeData this.setTreeData({ ...treeData }); } private buildNonEnrichedDbBuilderInput( schema?: string, ): DatabaseBuilderInput { const databaseBuilderInput = new DatabaseBuilderInput(this.connection); const [packagePath, databaseName] = this.getDatabasePackageAndName(); databaseBuilderInput.targetDatabase = new TargetDatabase( packagePath, databaseName, ); databaseBuilderInput.config.maxTables = undefined; databaseBuilderInput.config.enrichTables = Boolean(schema); databaseBuilderInput.config.patterns = [ new DatabasePattern(schema ?? WILDCARD, WILDCARD), ]; return databaseBuilderInput; } *fetchSchemaDefinitions(this: DatabaseBuilderState): GeneratorFn<void> { try { this.isBuildingDatabase = true; const databaseBuilderInput = this.buildNonEnrichedDbBuilderInput(); const database = (yield this.buildDatabaseFromInput( databaseBuilderInput, )) as Database; const rootIds: string[] = []; const nodes = new Map<string, DatabaseBuilderTreeNodeData>(); database.schemas.forEach((dbSchema) => { const schemaId = dbSchema.name; rootIds.push(schemaId); const schemaNode = new SchemaDatabaseBuilderTreeNodeData( schemaId, undefined, dbSchema, ); schemaNode.isChecked = Boolean( this.currentDatabase?.schemas.find( (cSchema) => cSchema.name === dbSchema.name, ), ); nodes.set(schemaId, schemaNode); }); const treeData = { rootIds, nodes, database }; this.setTreeData(treeData); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SERVICE_REGISTRATION_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error, undefined, 3000); } finally { this.isBuildingDatabase = false; } } *fetchSchemaMetadata( this: DatabaseBuilderState, schemaNode: SchemaDatabaseBuilderTreeNodeData, treeData: DatabaseBuilderTreeData, ): GeneratorFn<void> { try { this.isBuildingDatabase = true; const schema = schemaNode.schema; const databaseBuilderInput = this.buildNonEnrichedDbBuilderInput( schema.name, ); const database = (yield this.buildDatabaseFromInput( databaseBuilderInput, )) as Database; const tables = database.getSchema(schema.name).tables; const childrenIds = schemaNode.childrenIds ?? []; schema.tables = tables; tables.forEach((e) => { e.schema = schema; const tableId = `${schema.name}.${e.name}`; const tableNode = new TableDatabaseBuilderTreeNodeData( tableId, schemaNode.id, e, ); tableNode.isChecked = Boolean( this.currentDatabase && getDbNullableTable(e.name, schema.name, this.currentDatabase), ); treeData.nodes.set(tableId, tableNode); addUniqueEntry(childrenIds, tableId); }); schemaNode.childrenIds = childrenIds; this.setTreeData({ ...treeData }); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SERVICE_REGISTRATION_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error, undefined, 3000); } finally { this.isBuildingDatabase = false; } } *fetchTableMetadata( this: DatabaseBuilderState, tableNode: TableDatabaseBuilderTreeNodeData, treeData: DatabaseBuilderTreeData, ): GeneratorFn<void> { try { const databaseBuilderInput = new DatabaseBuilderInput(this.connection); const [packagePath, databaseName] = resolvePackagePathAndElementName( this.targetDatabasePath, ); databaseBuilderInput.targetDatabase = new TargetDatabase( packagePath, databaseName, ); const config = databaseBuilderInput.config; config.maxTables = undefined; config.enrichTables = true; config.enrichColumns = true; config.enrichPrimaryKeys = true; const table = tableNode.table; config.patterns = [new DatabasePattern(table.schema.name, table.name)]; const database = (yield this.buildDatabaseFromInput( databaseBuilderInput, )) as Database; const enrichedTable = database.schemas .find((s) => table.schema.name === s.name) ?.tables.find((t) => t.name === table.name); if (enrichedTable) { this.addColumnsNodeToTableNode(tableNode, enrichedTable, treeData); } } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SERVICE_REGISTRATION_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error, undefined, 3000); } finally { this.isBuildingDatabase = false; } } private addColumnsNodeToTableNode( tableNode: TableDatabaseBuilderTreeNodeData, enrichedTable: Table, treeData: DatabaseBuilderTreeData, ): void { const columns = enrichedTable.columns.filter( (column): column is Column => column instanceof Column, ); tableNode.table.columns = columns; this.removeChildren(tableNode, treeData); const childrenIds: string[] = []; const tableId = tableNode.id; columns.forEach((c) => { const columnId = `${tableId}.${c.name}`; const columnNode = new ColumnDatabaseBuilderTreeNodeData( columnId, tableId, c, ); c.owner = tableNode.table; treeData.nodes.set(columnId, columnNode); addUniqueEntry(childrenIds, columnId); }); tableNode.childrenIds = childrenIds; } private removeChildren( node: DatabaseBuilderTreeNodeData, treeData: DatabaseBuilderTreeData, ): void { const currentChildren = node.childrenIds; if (currentChildren) { currentChildren.forEach((c) => treeData.nodes.delete(c)); node.childrenIds = undefined; } } private getDatabasePackageAndName(): [string, string] { if (this.currentDatabase) { return [ guaranteeNonNullable(this.currentDatabase.package).path, this.currentDatabase.name, ]; } assertNonEmptyString(this.targetDatabasePath, 'Must specify database path'); assertTrue( isValidFullPath(this.targetDatabasePath), 'Invalid database path', ); return resolvePackagePathAndElementName( this.targetDatabasePath, this.targetDatabasePath, ); } *buildDatabaseWithTreeData(this: DatabaseBuilderState): GeneratorFn<void> { try { if (this.treeData) { const dbTreeData = this.treeData; this.isBuildingDatabase = true; const databaseBuilderInput = new DatabaseBuilderInput(this.connection); const [packagePath, databaseName] = this.getDatabasePackageAndName(); databaseBuilderInput.targetDatabase = new TargetDatabase( packagePath, databaseName, ); const config = databaseBuilderInput.config; config.maxTables = undefined; config.enrichTables = true; config.enrichColumns = true; config.enrichPrimaryKeys = true; dbTreeData.rootIds .map((e) => dbTreeData.nodes.get(e)) .filter(isNonNullable) .forEach((schemaNode) => { if (schemaNode instanceof SchemaDatabaseBuilderTreeNodeData) { const tableNodes = this.getChildNodes(schemaNode, dbTreeData); const allChecked = tableNodes?.every((t) => t.isChecked === true); if ( allChecked || (schemaNode.isChecked && !schemaNode.childrenIds) ) { config.patterns.push( new DatabasePattern(schemaNode.schema.name, WILDCARD), ); } else { tableNodes?.forEach((t) => { if ( t instanceof TableDatabaseBuilderTreeNodeData && t.isChecked ) { config.patterns.push( new DatabasePattern(schemaNode.schema.name, t.table.name), ); } }); } } }); const entities = (yield this.editorStore.graphState.graphManager.buildDatabase( databaseBuilderInput, )) as Entity[]; const dbGrammar = (yield this.editorStore.graphState.graphManager.entitiesToPureCode( entities, )) as string; this.setDatabaseGrammarCode(dbGrammar); } } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SERVICE_REGISTRATION_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error, undefined, 3000); } finally { this.isBuildingDatabase = false; } } private getSchemasFromTreeNode(tree: DatabaseBuilderTreeData): Schema[] { return Array.from(tree.nodes.values()) .map((e) => { if (e instanceof SchemaDatabaseBuilderTreeNodeData) { return e.schema; } return undefined; }) .filter(isNonNullable); } private buildDatabaseGrammar = flow(function* ( this: DatabaseBuilderState, grammar: string, ): GeneratorFn<Database> { const entities = (yield this.editorStore.graphState.graphManager.pureCodeToEntities( grammar, )) as Entity[]; const dbGraph = this.editorStore.graphState.createEmptyGraph(); (yield this.editorStore.graphState.graphManager.buildGraph( dbGraph, entities, { quiet: true }, )) as Entity[]; assertTrue( dbGraph.ownDatabases.length === 1, 'Expected one database to be generated from grammar', ); return dbGraph.ownDatabases[0]; }); private buildDatabaseFromInput = flow(function* ( this: DatabaseBuilderState, databaseBuilderInput: DatabaseBuilderInput, ): GeneratorFn<Database> { const entities = (yield this.editorStore.graphState.graphManager.buildDatabase( databaseBuilderInput, )) as Entity[]; const dbGraph = this.editorStore.graphState.createEmptyGraph(); (yield this.editorStore.graphState.graphManager.buildGraph( dbGraph, entities, { quiet: true }, )) as Entity[]; assertTrue( dbGraph.ownDatabases.length === 1, 'Expected one database to be generated from input', ); return dbGraph.ownDatabases[0]; }); createOrUpdateDatabase = flow(function* (this: DatabaseBuilderState) { try { this.isSavingDatabase = true; assertNonEmptyString( this.databaseGrammarCode, 'Database grammar is empty', ); const database = (yield this.buildDatabaseGrammar( this.databaseGrammarCode, )) as Database; let currentDatabase: Database; const isUpdating = Boolean(this.currentDatabase); if (!this.currentDatabase) { const newDatabase = new Database(database.name); this.connection.setStore( PackageableElementExplicitReference.create(newDatabase), ); const PackagePath = guaranteeNonNullable( database.package?.name, 'Database package is missing', ); const databasePackage = this.editorStore.graphState.graph.getOrCreatePackage(PackagePath); databasePackage.addElement(newDatabase); this.editorStore.graphState.graph.addElement(newDatabase); currentDatabase = newDatabase; this.editorStore.explorerTreeState.reprocess(); } else { currentDatabase = this.currentDatabase; } if (this.treeData) { const schemas = this.getSchemasFromTreeNode(this.treeData); this.updateDatabase(currentDatabase, database, schemas); this.editorStore.applicationStore.notifySuccess( `Database successfully '${isUpdating ? 'updated' : 'created'}. ${ !isUpdating ? 'Recompiling...' : '' }`, ); this.fetchSchemaDefinitions(); if (isUpdating) { yield this.editorStore.graphState.globalCompileInFormMode({ message: `Can't compile graph after editing database. Redirecting you to text mode`, }); } } } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.SERVICE_REGISTRATION_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error, undefined, 3000); } finally { this.isSavingDatabase = false; } }); updateDatabase( current: Database, generatedDb: Database, allSchemas: Schema[], ): void { // remove shemas not defined current.schemas = current.schemas.filter((schema) => { if ( allSchemas.find((c) => c.name === schema.name) && !generatedDb.schemas.find((c) => c.name === schema.name) ) { return false; } return true; }); // update existing schemas generatedDb.schemas.forEach((s) => { s.owner = current; const currentSchemaIndex = current.schemas.findIndex( (c) => c.name === s.name, ); if (currentSchemaIndex !== -1) { current.schemas[currentSchemaIndex] = s; } else { current.schemas.push(s); } }); } get currentDatabase(): Database | undefined { const store = this.connection.store.value; if (store instanceof Database && !store.isStub) { return store; } return undefined; } }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/Pure.ts
<gh_stars>1-10 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { Logger } from '../../../utils/Logger'; import type { AbstractPureGraphManager } from '../../metamodels/pure/graph/AbstractPureGraphManager'; import { V1_PureGraphManager } from './v1/V1_PureGraphManager'; import type { PureProtocolProcessorPlugin } from './PureProtocolProcessorPlugin'; import type { PureGraphManagerPlugin } from '../../metamodels/pure/graph/PureGraphManagerPlugin'; export const getGraphManager = ( pureGraphManagerPlugins: PureGraphManagerPlugin[], pureProtocolProcessorPlugins: PureProtocolProcessorPlugin[], logger: Logger, ): AbstractPureGraphManager => // NOTE: until we support more client versions, we always default to return V1 new V1_PureGraphManager( pureGraphManagerPlugins, pureProtocolProcessorPlugins, logger, );
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/components/QueryBuilderPropertyInfoTooltip.tsx
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { TooltipProps } from '@material-ui/core'; import { Tooltip } from '@material-ui/core'; import { StubTransition } from '@finos/legend-studio-components'; import type { AbstractProperty, Multiplicity } from '@finos/legend-studio'; import { DerivedProperty, MULTIPLICITY_INFINITE } from '@finos/legend-studio'; const getMultiplicityDescription = (multiplicity: Multiplicity): string => { if (multiplicity.lowerBound === multiplicity.upperBound) { return `[${multiplicity.lowerBound.toString()}] - Must have exactly ${multiplicity.lowerBound.toString()} value(s)`; } else if ( multiplicity.lowerBound === 0 && multiplicity.upperBound === undefined ) { return `[${MULTIPLICITY_INFINITE}] - May have many values`; } return `[${multiplicity.lowerBound}..${ multiplicity.upperBound ?? MULTIPLICITY_INFINITE }] - ${ multiplicity.upperBound ? `Must have from ${multiplicity.lowerBound} to ${multiplicity.upperBound} value(s)` : `Must have at least ${multiplicity.lowerBound} values(s)` }`; }; export const QueryBuilderPropertyInfoTooltip: React.FC<{ property: AbstractProperty; path: string; isMapped: boolean; children: React.ReactElement; placement: TooltipProps['placement']; }> = (props) => { const { property, path, isMapped, children, placement } = props; return ( <Tooltip arrow={true} placement={placement} classes={{ tooltip: 'query-builder__tooltip', arrow: 'query-builder__tooltip__arrow', tooltipPlacementRight: 'query-builder__tooltip--right', }} TransitionComponent={StubTransition} title={ <div className="query-builder__tooltip__content"> <div className="query-builder__tooltip__item"> <div className="query-builder__tooltip__item__label">Type</div> <div className="query-builder__tooltip__item__value"> {property.genericType.value.rawType.path} </div> </div> <div className="query-builder__tooltip__item"> <div className="query-builder__tooltip__item__label">Path</div> <div className="query-builder__tooltip__item__value">{path}</div> </div> <div className="query-builder__tooltip__item"> <div className="query-builder__tooltip__item__label"> Multiplicity </div> <div className="query-builder__tooltip__item__value"> {getMultiplicityDescription(property.multiplicity)} </div> </div> <div className="query-builder__tooltip__item"> <div className="query-builder__tooltip__item__label"> Derived Property </div> <div className="query-builder__tooltip__item__value"> {property instanceof DerivedProperty ? 'Yes' : 'No'} </div> </div> <div className="query-builder__tooltip__item"> <div className="query-builder__tooltip__item__label">Mapped</div> <div className="query-builder__tooltip__item__value"> {isMapped ? 'Yes' : 'No'} </div> </div> </div> } > {children} </Tooltip> ); };
nayanika2/legend-studio
packages/legend-studio/src/stores/editor-state/GraphGenerationState.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { observable, flow, action, computed, makeObservable } from 'mobx'; import type { Entity } from '../../models/sdlc/models/entity/Entity'; import type { GeneratorFn } from '@finos/legend-studio-shared'; import { assertTrue, assertErrorThrown, guaranteeNonNullable, isNonNullable, } from '@finos/legend-studio-shared'; import { CORE_LOG_EVENT } from '../../utils/Logger'; import type { GenerationTreeNodeData, GenerationOutputResult, } from '../shared/FileGenerationTreeUtil'; import { GenerationDirectory, GENERATION_FILE_ROOT_NAME, GenerationFile, getGenerationTreeData, openNode, populateDirectoryTreeNodeChildren, buildGenerationDirectory, reprocessOpenNodes, } from '../shared/FileGenerationTreeUtil'; import type { TreeData } from '@finos/legend-studio-components'; import type { EditorStore } from '../EditorStore'; import { ExplorerTreeRootPackageLabel } from '../ExplorerTreeState'; import { FileGenerationViewerState } from './FileGenerationViewerState'; import type { EditorState } from './EditorState'; import { ElementEditorState } from './element-editor-state/ElementEditorState'; import { ElementFileGenerationState } from './element-editor-state/ElementFileGenerationState'; import type { GenerationConfigurationDescription } from '../../models/metamodels/pure/action/generation/GenerationConfigurationDescription'; import type { PackageableElement } from '../../models/metamodels/pure/model/packageableElements/PackageableElement'; import { DEFAULT_GENERATION_SPECIFICATION_NAME, GenerationSpecification, } from '../../models/metamodels/pure/model/packageableElements/generationSpecification/GenerationSpecification'; import type { FileGenerationTypeOption } from '../../models/metamodels/pure/model/packageableElements/fileGeneration/FileGenerationSpecification'; import { Class } from '../../models/metamodels/pure/model/packageableElements/domain/Class'; import { Enumeration } from '../../models/metamodels/pure/model/packageableElements/domain/Enumeration'; import type { GenerationOutput } from '../../models/metamodels/pure/action/generation/GenerationOutput'; import type { DSLGenerationSpecification_PureGraphManagerPlugin_Extension } from '../../models/metamodels/pure/graph/DSLGenerationSpecification_PureGraphManagerPlugin_Extension'; import { ELEMENT_PATH_DELIMITER } from '../../models/MetaModelConst'; export class GraphGenerationState { editorStore: EditorStore; isRunningGlobalGenerate = false; generatedEntities = new Map<string, Entity[]>(); isClearingGenerationEntities = false; fileGenerationConfigurations: GenerationConfigurationDescription[] = []; // File generation output rootFileDirectory: GenerationDirectory; filesIndex = new Map<string, GenerationFile>(); selectedNode?: GenerationTreeNodeData; constructor(editorStore: EditorStore) { makeObservable<GraphGenerationState>(this, { isRunningGlobalGenerate: observable, generatedEntities: observable.shallow, isClearingGenerationEntities: observable, fileGenerationConfigurations: observable, rootFileDirectory: observable, filesIndex: observable, selectedNode: observable.ref, fileGenerationConfigurationOptions: computed, supportedFileGenerationConfigurationsForCurrentElement: computed, setFileGenerationConfigurations: action, addMissingGenerationSpecifications: action, processGenerationResult: action, reprocessGenerationFileState: action, reprocessNodeTree: action, onTreeNodeSelect: action, setSelectedNode: action, emptyFileGeneration: action, }); this.editorStore = editorStore; this.rootFileDirectory = new GenerationDirectory(GENERATION_FILE_ROOT_NAME); } get fileGenerationConfigurationOptions(): FileGenerationTypeOption[] { return this.fileGenerationConfigurations .slice() .sort((a, b): number => a.label.localeCompare(b.label)) .map((config) => ({ label: config.label, value: config.key, })); } get supportedFileGenerationConfigurationsForCurrentElement(): GenerationConfigurationDescription[] { if (this.editorStore.currentEditorState instanceof ElementEditorState) { const currentElement = this.editorStore.currentEditorState.element; if ( currentElement instanceof Class || currentElement instanceof Enumeration ) { return this.fileGenerationConfigurations .slice() .sort((a, b): number => a.label.localeCompare(b.label)); } } return []; } setFileGenerationConfigurations( fileGenerationConfigurations: GenerationConfigurationDescription[], ): void { this.fileGenerationConfigurations = fileGenerationConfigurations; } getFileGenerationConfiguration( type: string, ): GenerationConfigurationDescription { return guaranteeNonNullable( this.fileGenerationConfigurations.find((config) => config.key === type), `Can't find configuration description for file generation type '${type}'`, ); } fetchAvailableFileGenerationDescriptions = flow(function* ( this: GraphGenerationState, ) { try { const availableFileGenerationDescriptions = (yield this.editorStore.graphState.graphManager.getAvailableGenerationConfigurationDescriptions()) as unknown as GenerationConfigurationDescription[]; this.setFileGenerationConfigurations(availableFileGenerationDescriptions); this.editorStore.elementGenerationStates = this.fileGenerationConfigurations.map( (config) => new ElementFileGenerationState(this.editorStore, config.key), ); } catch (error: unknown) { this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.GENERATION_PROBLEM, error, ); this.editorStore.applicationStore.notifyError(error); } }); /** * Global generation is tied to the generation specification of the project. Every time a generation element * is added, they will be added to the generation specification */ globalGenerate = flow(function* (this: GraphGenerationState) { if ( this.editorStore.graphState.checkIfApplicationUpdateOperationIsRunning() ) { return; } this.isRunningGlobalGenerate = true; try { yield this.generateModels(); yield this.generateFiles(); } catch (error: unknown) { assertErrorThrown(error); this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.GENERATION_PROBLEM, error, ); this.editorStore.graphState.editorStore.applicationStore.notifyError( `${error.message}`, ); } finally { this.isRunningGlobalGenerate = false; } }); generateModels = flow(function* (this: GraphGenerationState) { try { this.generatedEntities = new Map<string, Entity[]>(); // reset the map of generated entities const generationSpecs = this.editorStore.graphState.graph.ownGenerationSpecifications; if (!generationSpecs.length) { return; } assertTrue( generationSpecs.length === 1, `Can't generate models: only one generation specification permitted to generate`, ); const generationSpec = generationSpecs[0]; const generationNodes = generationSpec.generationNodes; for (let i = 0; i < generationNodes.length; i++) { const node = generationNodes[i]; let generatedEntities: Entity[] = []; try { generatedEntities = (yield this.generateGenerationElement( node.generationElement.value, )) as unknown as Entity[]; } catch (error: unknown) { assertErrorThrown(error); throw new Error( `Can't generate models: failure occured at step ${ i + 1 } with specification '${ node.generationElement.value.path }'. Error: ${error.message}`, ); } this.generatedEntities.set( node.generationElement.value.path, generatedEntities, ); yield this.editorStore.graphState.updateGenerationGraphAndApplication(); } } catch (error: unknown) { assertErrorThrown(error); this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.GENERATION_PROBLEM, error, ); this.editorStore.graphState.editorStore.applicationStore.notifyError( `${error.message}`, ); } }); /** * Generated File Generation * This method does not update graph and application. the files generated */ generateFiles = flow(function* (this: GraphGenerationState) { try { this.emptyFileGeneration(); const generationResultMap = new Map<string, GenerationOutput[]>(); const generationSpecs = this.editorStore.graphState.graph.ownGenerationSpecifications; if (!generationSpecs.length) { return; } assertTrue( generationSpecs.length === 1, `Can't generate models: only one generation specification permitted to generate`, ); const generationSpec = generationSpecs[0]; const fileGenerations = generationSpec.fileGenerations; // we don't need to keep 'fetching' the main model as it won't grow with each file generation for (const fileGeneration of fileGenerations) { let result: GenerationOutput[] = []; try { const mode = this.editorStore.graphState.graphGenerationState.getFileGenerationConfiguration( fileGeneration.value.type, ).generationMode; result = (yield this.editorStore.graphState.graphManager.generateFile( fileGeneration.value, mode, this.editorStore.graphState.graph, )) as GenerationOutput[]; } catch (error: unknown) { assertErrorThrown(error); throw new Error( `Can't generate files using specification '${fileGeneration.value.path}'. Error: ${error.message}`, ); } generationResultMap.set(fileGeneration.value.path, result); } this.processGenerationResult(generationResultMap); } catch (error: unknown) { assertErrorThrown(error); this.editorStore.applicationStore.logger.error( CORE_LOG_EVENT.GENERATION_PROBLEM, error, ); this.editorStore.graphState.editorStore.applicationStore.notifyError( `${error.message}`, ); } }); /** * Used to clear generation entities as well as the generation model */ clearGenerations = flow(function* (this: GraphGenerationState) { this.isClearingGenerationEntities = true; this.generatedEntities = new Map<string, Entity[]>(); this.emptyFileGeneration(); yield this.editorStore.graphState.updateGenerationGraphAndApplication(); this.isClearingGenerationEntities = false; }); /** * Method takes a generation element, defined as a packageable element that generates another model, and returns generated entities */ generateGenerationElement = flow(function* ( this: GraphGenerationState, generationElement: PackageableElement, ): GeneratorFn<Entity[]> { return (yield this.editorStore.graphState.graphManager.generateModel( generationElement, this.editorStore.graphState.graph, )) as Entity[]; }); /** * Method adds generation specification if * 1. no generation specification has been defined in graph * 2. there exists a generation element */ addMissingGenerationSpecifications(): void { if (!this.editorStore.graphState.graph.ownGenerationSpecifications.length) { const modelGenerationElements = this.editorStore.applicationStore.pluginManager .getPureGraphManagerPlugins() .flatMap( (plugin) => ( plugin as DSLGenerationSpecification_PureGraphManagerPlugin_Extension ).getExtraModelGenerationElementGetters?.() ?? [], ) .flatMap((getter) => getter(this.editorStore.graphState.graph)); const fileGenerations = this.editorStore.graphState.graph.ownFileGenerations; if (modelGenerationElements.length || fileGenerations.length) { const generationSpec = new GenerationSpecification( DEFAULT_GENERATION_SPECIFICATION_NAME, ); modelGenerationElements.forEach((e) => generationSpec.addGenerationElement(e), ); fileGenerations.forEach((e) => generationSpec.addFileGeneration(e)); // NOTE: add generation specification at the same package as the first generation element found. // we might want to revisit this decision? const specPackage = guaranteeNonNullable( [...modelGenerationElements, ...fileGenerations][0].package, ); specPackage.addElement(generationSpec); this.editorStore.graphState.graph.addElement(generationSpec); } } } // File Generation Tree processGenerationResult( fileGenerationOutputMap: Map<string, GenerationOutput[]>, ): void { // empty file index and the directory, we keep the open nodes to reprocess them this.emptyFileGeneration(); const directoryTreeData = this.editorStore.graphState.editorStore.explorerTreeState .fileGenerationTreeData; const openedNodeIds = directoryTreeData ? Array.from(directoryTreeData.nodes.values()) .filter((node) => node.isOpen) .map((node) => node.id) : []; // we read the generation outputs and clean const generationResultMap = new Map<string, GenerationOutputResult>(); Array.from(fileGenerationOutputMap.entries()).forEach((entry) => { const fileGeneration = this.editorStore.graphState.graph.getNullableFileGeneration(entry[0]); const rootFolder = fileGeneration?.generationOutputPath ?? fileGeneration?.path.split(ELEMENT_PATH_DELIMITER).join('_'); const generationOutputs = entry[1]; generationOutputs.forEach((genOutput) => { genOutput.cleanFileName(rootFolder); if (generationResultMap.has(genOutput.fileName)) { this.editorStore.applicationStore.logger.warn( CORE_LOG_EVENT.CODE_GENERATION_PROBLEM, `Found 2 generation outputs with same path '${genOutput.fileName}'`, ); } generationResultMap.set(genOutput.fileName, { generationOutput: genOutput, parentId: fileGeneration?.path, }); }); }); // take generation outputs and put them into the root directory buildGenerationDirectory( this.rootFileDirectory, generationResultMap, this.filesIndex, ); this.editorStore.graphState.editorStore.explorerTreeState.setFileGenerationTreeData( getGenerationTreeData( this.rootFileDirectory, ExplorerTreeRootPackageLabel.FILE_GENERATION, ), ); this.editorStore.graphState.editorStore.explorerTreeState.setFileGenerationTreeData( this.reprocessNodeTree( Array.from(generationResultMap.values()), this.editorStore.graphState.editorStore.explorerTreeState.getFileGenerationTreeData(), openedNodeIds, ), ); this.editorStore.openedEditorStates = this.editorStore.openedEditorStates .map((e) => this.reprocessGenerationFileState(e)) .filter(isNonNullable); const currentEditorState = this.editorStore.currentEditorState; if (currentEditorState instanceof FileGenerationViewerState) { this.editorStore.currentEditorState = this.editorStore.openedEditorStates.find( (e) => e instanceof FileGenerationViewerState && e.generatedFile.path === currentEditorState.generatedFile.path, ); } } reprocessGenerationFileState( editorState: EditorState, ): EditorState | undefined { if (editorState instanceof FileGenerationViewerState) { const fileNode = this.filesIndex.get(editorState.generatedFile.path); if (fileNode) { editorState.generatedFile = fileNode; return editorState; } else { return undefined; } } return editorState; } reprocessNodeTree( generationResult: GenerationOutputResult[], treeData: TreeData<GenerationTreeNodeData>, openedNodeIds: string[], ): TreeData<GenerationTreeNodeData> { reprocessOpenNodes( treeData, this.filesIndex, this.rootFileDirectory, openedNodeIds, true, ); const selectedFileNodePath = this.selectedNode?.fileNode.path ?? (generationResult.length === 1 ? generationResult[0].generationOutput.fileName : undefined); if (selectedFileNodePath) { const file = this.filesIndex.get(selectedFileNodePath); if (file) { const node = openNode(file, treeData, true); if (node) { this.onTreeNodeSelect(node, treeData, true); } } else { this.selectedNode = undefined; } } return treeData; } onTreeNodeSelect( node: GenerationTreeNodeData, treeData: TreeData<GenerationTreeNodeData>, reprocess?: boolean, ): void { if (node.childrenIds?.length) { node.isOpen = !node.isOpen; if (node.fileNode instanceof GenerationDirectory) { populateDirectoryTreeNodeChildren(node, treeData); } } if (!reprocess && node.fileNode instanceof GenerationFile) { this.editorStore.openGeneratedFile(node.fileNode); } this.setSelectedNode(node); this.editorStore.graphState.editorStore.explorerTreeState.setFileGenerationTreeData( { ...treeData }, ); } setSelectedNode(node?: GenerationTreeNodeData): void { if (this.selectedNode) { this.selectedNode.isSelected = false; } if (node) { node.isSelected = true; } this.selectedNode = node; } emptyFileGeneration(): void { this.filesIndex = new Map<string, GenerationFile>(); this.rootFileDirectory = new GenerationDirectory(GENERATION_FILE_ROOT_NAME); } }
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/stores/QueryBuilderValueSpecificationBuilderHelper.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { PureModel, ValueSpecification } from '@finos/legend-studio'; import { CORE_ELEMENT_PATH, DATE_FORMAT, FunctionType, LambdaFunction, LambdaFunctionInstanceValue, PRIMITIVE_TYPE, TYPICAL_MULTIPLICITY_TYPE, VariableExpression, } from '@finos/legend-studio'; import { UnsupportedOperationError } from '@finos/legend-studio-shared'; import format from 'date-fns/format'; export const generateDefaultValueForPrimitiveType = ( type: PRIMITIVE_TYPE, ): unknown => { switch (type) { case PRIMITIVE_TYPE.STRING: return ''; case PRIMITIVE_TYPE.BOOLEAN: return false; case PRIMITIVE_TYPE.NUMBER: case PRIMITIVE_TYPE.DECIMAL: case PRIMITIVE_TYPE.FLOAT: case PRIMITIVE_TYPE.INTEGER: return 0; case PRIMITIVE_TYPE.DATE: case PRIMITIVE_TYPE.DATETIME: case PRIMITIVE_TYPE.STRICTDATE: return format(new Date(Date.now()), DATE_FORMAT); default: throw new UnsupportedOperationError( `Can't generate default value for primitive type '${type}'`, ); } }; export const buildGenericLambdaFunctionInstanceValue = ( lambdaParameterName: string, lambdaBodyExpressions: ValueSpecification[], graph: PureModel, ): LambdaFunctionInstanceValue => { const multiplicityOne = graph.getTypicalMultiplicity( TYPICAL_MULTIPLICITY_TYPE.ONE, ); const typeAny = graph.getType(CORE_ELEMENT_PATH.ANY); const aggregateLambda = new LambdaFunctionInstanceValue(multiplicityOne); const colLambdaFunctionType = new FunctionType(typeAny, multiplicityOne); colLambdaFunctionType.parameters.push( new VariableExpression(lambdaParameterName, multiplicityOne), ); const colLambdaFunction = new LambdaFunction(colLambdaFunctionType); colLambdaFunction.expressionSequence = lambdaBodyExpressions; aggregateLambda.values.push(colLambdaFunction); return aggregateLambda; };
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/QueryBuilder_Const.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export enum QUERY_BUILDER_SOURCE_ID_LABEL { QUERY_BUILDER = 'query-builder', PROJECTION = 'projection', } export enum QUERY_BUILDER_TEST_ID { QUERY_BUILDER = 'query__builder', QUERY_BUILDER_SETUP = 'query__builder__setup', QUERY_BUILDER_PROJECTION = 'query__builder__projection', QUERY_BUILDER_GRAPH_FETCH = 'query__builder__graph__fetch', QUERY_BUILDER_FILTER = 'query__builder__filter', } export enum SUPPORTED_FUNCTIONS { AND = 'meta::pure::functions::boolean::and', EXISTS = 'meta::pure::functions::collection::exists', FILTER = 'meta::pure::functions::collection::filter', GET_ALL = 'meta::pure::functions::collection::getAll', NOT = 'meta::pure::functions::boolean::not', OR = 'meta::pure::functions::boolean::or', TAKE = 'meta::pure::functions::collection::take', // graph-fetch GRAPH_FETCH = 'meta::pure::graphFetch::execution::graphFetch', GRAPH_FETCH_CHECKED = 'meta::pure::graphFetch::execution::graphFetchChecked', SERIALIZE = 'meta::pure::graphFetch::execution::serialize', // TDS TDS_ASC = 'meta::pure::tds::asc', TDS_DESC = 'meta::pure::tds::desc', TDS_AGG = 'meta::pure::tds::agg', TDS_DISTINCT = 'meta::pure::tds::distinct', TDS_PROJECT = 'meta::pure::tds::project', TDS_GROUP_BY = 'meta::pure::tds::groupBy', TDS_SORT = 'meta::pure::tds::sort', TDS_TAKE = 'meta::pure::tds::take', // filter CONTAINS = 'meta::pure::functions::string::contains', ENDS_WITH = 'meta::pure::functions::string::endsWith', EQUAL = 'meta::pure::functions::boolean::equal', GREATER_THAN = 'meta::pure::functions::lang::tests::greaterThan', GREATER_THAN_EQUAL = 'meta::pure::functions::lang::tests::greaterThanEqual', IN = 'meta::pure::functions::collection::in', IS_EMPTY = 'meta::pure::functions::collection::isEmpty', LESS_THAN = 'meta::pure::functions::lang::tests::lessThan', LESS_THAN_EQUAL = 'meta::pure::functions::lang::tests::lessThanEqual', STARTS_WITH = 'meta::pure::functions::string::startsWith', // aggregation AVERAGE = 'meta::pure::functions::math::average', COUNT = 'meta::pure::functions::collection::count', JOIN_STRINGS = 'meta::pure::functions::string::joinStrings', DISTINCT = 'meta::pure::functions::collection::distinct', DATE_MAX = 'meta::pure::functions::date::max', DATE_MIN = 'meta::pure::functions::date::min', MAX = 'meta::pure::functions::math::max', MIN = 'meta::pure::functions::math::min', STD_DEV_POPULATION = 'meta::pure::functions::math::stdDevPopulation', STD_DEV_SAMPLE = 'meta::pure::functions::math::stdDevSample', SUM = 'meta::pure::functions::math::sum', UNIQUE_VALUE_ONLY = 'meta::pure::functions::collection::uniqueValueOnly', } export const DEFAULT_LAMBDA_VARIABLE_NAME = 'x';
nayanika2/legend-studio
packages/legend-studio-app/cypress/utils/ElementEditorTester.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { TEST_ID } from '../../src/const'; import { EDITOR_LANGUAGE } from '../../src/stores/EditorConfig'; import { getConfigUrls } from './E2ETestUtil'; import { editor as MonacoEditorAPI } from 'monaco-editor'; import { Clazz, guaranteeType } from '@finos/legend-studio-shared'; import { EndToEndTester } from './EndToEndTester'; import { ElementHelperExtension } from './ElementHelperExtension'; export class ElementEditorTester extends EndToEndTester { // TODO make this an array helperExtension?: ElementHelperExtension; public static create( configFile = 'element-editor.json', ): ElementEditorTester { const elementEditorTest = new ElementEditorTester(); cy.fixture(configFile).then((demoJSON) => { elementEditorTest._projectName = demoJSON.PROJECT_NAME; elementEditorTest._projectId = demoJSON.PROJECT_ID; elementEditorTest._workspace = demoJSON.WORKSPACE; getConfigUrls().then((response) => { elementEditorTest._sdlcServer = response[0]; elementEditorTest._engineServer = response[1]; cy.server(); elementEditorTest.loadRoutes(); }); }); return elementEditorTest; } withHelperExtension( helperExtension: ElementHelperExtension, ): ElementEditorTester { this.helperExtension = helperExtension; return this; } getHelperExtension<T extends ElementHelperExtension>(clazz: Clazz<T>): T { return guaranteeType( this.helperExtension, clazz, `No helper extension found`, ); } buildGraphWithText = ( graphText: string, editorLanguage = EDITOR_LANGUAGE.PURE, ): void => { let editorModels: MonacoEditorAPI.IStandaloneCodeEditor[]; cy.getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT) .get(`[title="${this._domTitles.TOGGLE_TEXT_MODE}"]`) .click() .get(`[data-mode-id="${editorLanguage}"]`) .window() .then((win) => { editorModels = (win as any).monaco.editor.getModels(); }) .then(() => { expect(editorModels.length).to.equal(1); editorModels[0].setValue(graphText); }) .getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT) .get(`[title="${this._domTitles.TOGGLE_TEXT_MODE}"]`) .click(); cy.contains('Open or Search for an Element'); }; getMonacoText = (idx?: number): Cypress.Chainable<string> => { let editorModels: MonacoEditorAPI.IStandaloneCodeEditor[]; return cy .window() .then((win) => { editorModels = (win as any).monaco.editor.getModels(); }) .then(() => { if (!idx) { expect(editorModels.length).to.equal(1); const model = editorModels[0]; return model.getValue(); } return editorModels[idx].getValue(); }); }; addToGraphText = (appendText: string): void => { let editorModels: MonacoEditorAPI.IStandaloneCodeEditor[]; cy.window() .then((win) => { editorModels = (win as any).monaco.editor.getModels(); }) .then(() => { expect(editorModels.length).to.equal(1); const model = editorModels[0]; editorModels[0].setValue(model.getValue() + appendText); }); }; setTextToGraphText = (text: string, child: number = 0): void => { let editorModels: MonacoEditorAPI.IStandaloneCodeEditor[]; cy.window() .then((win) => { editorModels = (win as any).monaco.editor.getModels(); }) .then(() => { editorModels[child].setValue(text); }); }; setDevTools = (): void => { cy.get(`[title="Settings..."]`).click(); cy.contains('Show Developer Tool').click(); cy.contains('Payload compression').parent().children().eq(1).click(); cy.get('[title="Toggle auxiliary panel (Ctrl + `)"]').click(); }; compile = (): void => { cy.getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT) .get('[title="Compile (F9)"]') .click(); cy.wait('@compile').its('status').should('eq', 200); cy.contains('Compiled sucessfully'); }; createReview = (title: string): void => { cy.get('[placeholder="Title"]').focus().clear().type(title); cy.get('[title="Create review"]').click(); cy.wait('@postReview').its('status').should('eq', 200); }; toggleOnHackerMode = (): void => { cy.getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT) .get('[title="Toggle text mode (F8)"]') .click(); cy.wait('@postTransformJsonToGrammar'); }; toggleOffHackerMode = (): void => { cy.getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT) .get('[title="Toggle text mode (F8)"]') .click(); cy.wait('@postTransformGrammarToJson'); }; setUpRoutes = (): void => { cy.route({ method: 'GET', url: `${this.sdlcServer}/projects/${this.projectId}/workspaces`, }).as('getWorkspaces'); cy.route({ method: 'GET', url: `${this.sdlcServer}/projects/${this.projectId}/conflictResolution`, }).as('getConflictResolution'); cy.route({ method: 'POST', url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}`, }).as('postWorkspace'); //same as above but with different alias cy.route({ method: 'GET', url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}/entities`, }).as('getEntities'); cy.route({ method: 'POST', url: `${this.engineServer}/api/pure/v1/schemaGeneration/avro`, }).as('avroGeneration'); cy.route({ method: 'POST', url: `${this.engineServer}/api/pure/v1/schemaGeneration/protobuf`, }).as('protobufGeneration'); cy.route({ method: 'POST', url: `${this.engineServer}/api/pure/v1/compilation/compile`, }).as('compile'); cy.route({ method: 'POST', url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}/entityChanges`, }).as('syncChanges'); cy.route({ method: 'POST', url: `${this.engineServer}/api/pure/v1/execution/execute`, }).as('postExecute'); cy.route({ method: 'POST', url: `${this.engineServer}/api/pure/v1/execution/generatePlan`, }).as('postGeneratePlan'); cy.route({ method: 'POST', url: `${this.engineServer}/api/pure/v1/grammar/transformGrammarToJson`, }).as('transformGrammarToJson'); cy.route({ method: 'POST', url: `${this.sdlcServer}/projects/${this.projectId}/reviews`, }).as('postReview'); cy.route({ method: 'POST', url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}/entityChanges`, }).as('postEntityChanges'); cy.route({ method: 'GET', url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}/inConflictResolutionMode`, }).as('getInConflictResolutionMode'); cy.route({ method: 'POST', url: `${this.engineServer}/api/pure/v1/grammar/transformJsonToGrammar`, }).as('postTransformJsonToGrammar'); cy.route({ method: 'POST', url: `${this.engineServer}/api/pure/v1/grammar/transformGrammarToJson`, }).as('postTransformGrammarToJson'); cy.route({ method: 'GET', url: `${this.sdlcServer}/projects/${this.projectId}`, }).as('getProjectDetails'); cy.route({ method: 'GET', url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}`, }).as('getWorkspace'); }; }
nayanika2/legend-studio
packages/legend-studio/src/components/setup/WorkspaceSelector.tsx
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { useEffect } from 'react'; import { observer } from 'mobx-react-lite'; import { useSetupStore } from '../../stores/SetupStore'; import type { SelectComponent } from '@finos/legend-studio-components'; import { CustomSelectorInput } from '@finos/legend-studio-components'; import type { WorkspaceSelectOption } from '../../models/sdlc/models/workspace/Workspace'; import { FaPlus } from 'react-icons/fa'; import { generateSetupRoute } from '../../stores/Router'; import { useApplicationStore } from '../../stores/ApplicationStore'; import { ACTION_STATE } from '@finos/legend-studio-shared'; export const WorkspaceSelector = observer( ( props: { onChange: (focusNext: boolean) => void; create: () => void; }, ref: React.Ref<SelectComponent>, ) => { const { onChange, create } = props; const setupStore = useSetupStore(); const applicationStore = useApplicationStore(); const currentWorkspaceId = setupStore.currentWorkspaceId; const options = setupStore.currentProjectWorkspaceOptions; const selectedOption = options.find((option) => option.value === currentWorkspaceId) ?? null; const isLoadingOptions = setupStore.loadProjectsState === ACTION_STATE.IN_PROGRESS || setupStore.loadWorkspacesState === ACTION_STATE.IN_PROGRESS; const onSelectionChange = (val: WorkspaceSelectOption | null): void => { if ( (val !== null || selectedOption !== null) && (!val || !selectedOption || val.value !== selectedOption.value) ) { setupStore.setCurrentWorkspaceId(val?.value); onChange(Boolean(selectedOption)); applicationStore.historyApiClient.push( generateSetupRoute( applicationStore.config.sdlcServerKey, setupStore.currentProjectId ?? '', val?.value, ), ); } }; useEffect(() => { if (setupStore.currentProjectWorkspaces && !currentWorkspaceId) { onChange(false); } }, [ setupStore.currentProjectWorkspaces, setupStore.currentProjectId, currentWorkspaceId, onChange, ]); const workspaceSelectorPlacerHold = isLoadingOptions ? 'Loading workspaces' : !setupStore.currentProjectId ? 'In order to select a workspace, a project must be selected' : options.length ? 'Choose an existing workspace' : 'You have no workspaces. Please create one'; return ( <div className="setup-selector"> <button className="setup-selector__action btn--dark" onClick={create} tabIndex={-1} title={'Create a Workspace'} > <FaPlus /> </button> <CustomSelectorInput className="setup-selector__input" allowCreating={false} ref={ref} options={options} disabled={!setupStore.currentProjectId || isLoadingOptions} isLoading={isLoadingOptions} onChange={onSelectionChange} value={selectedOption} placeholder={workspaceSelectorPlacerHold} isClearable={true} escapeClearsValue={true} darkMode={true} /> </div> ); }, { forwardRef: true }, ); WorkspaceSelector.displayName = 'WorkspaceSelector';
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/model/packageableElements/service/ServiceExecution.ts
<filename>packages/legend-studio/src/models/metamodels/pure/model/packageableElements/service/ServiceExecution.ts /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { observable, computed, action, makeObservable } from 'mobx'; import { hashArray, uuid, addUniqueEntry } from '@finos/legend-studio-shared'; import type { Hashable } from '@finos/legend-studio-shared'; import { CORE_HASH_STRUCTURE } from '../../../../../MetaModelConst'; import type { Mapping } from '../../../model/packageableElements/mapping/Mapping'; import type { RawLambda } from '../../../model/rawValueSpecification/RawLambda'; import type { Service } from '../../../model/packageableElements/service/Service'; import type { Runtime } from '../../../model/packageableElements/runtime/Runtime'; import type { ValidationIssue } from '../../../action/validator/ValidationResult'; import { createValidationError } from '../../../action/validator/ValidationResult'; import type { PackageableElementReference } from '../../../model/packageableElements/PackageableElementReference'; export abstract class ServiceExecution implements Hashable { private readonly _$nominalTypeBrand!: 'ServiceExecution'; abstract get hashCode(): string; } export class PureExecution extends ServiceExecution implements Hashable { owner: Service; func: RawLambda; // @MARKER GENERATED MODEL DISCREPANCY --- Studio does not process lambda constructor(func: RawLambda, owner: Service) { super(); makeObservable(this, { func: observable, queryValidationResult: computed, setFunction: action, }); this.func = func; this.owner = owner; } get queryValidationResult(): ValidationIssue | undefined { if (this.func.isStub) { return createValidationError([ 'Service execution function cannot be empty', ]); } // TODO: put this logic back when we properly process lambda - we can't pass the graph manager here to check this // else if (isGetAllLambda(this.func)) { // return createValidationError(['Non-empty graph fetch tree is required']); // } return undefined; } setFunction(value: RawLambda): void { this.func = value; } get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.SERVICE_PURE_EXECUTION, this.func]); } } export class PureSingleExecution extends PureExecution implements Hashable { mapping: PackageableElementReference<Mapping>; runtime: Runtime; constructor( func: RawLambda, owner: Service, mapping: PackageableElementReference<Mapping>, runtime: Runtime, ) { super(func, owner); makeObservable(this, { runtime: observable, setMapping: action, setRuntime: action, mappingValidationResult: computed, hashCode: computed, }); this.mapping = mapping; this.runtime = runtime; } setMapping(value: Mapping): void { this.mapping.setValue(value); } setRuntime(value: Runtime): void { this.runtime = value; } get mappingValidationResult(): ValidationIssue | undefined { return this.mapping.value.isStub ? createValidationError(['Service execution mapping cannot be empty']) : undefined; } override get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.SERVICE_PURE_SINGLE_EXECUTION, super.hashCode, this.mapping.valueForSerialization, this.runtime, ]); } } export class KeyedExecutionParameter implements Hashable { uuid = uuid(); key: string; mapping: PackageableElementReference<Mapping>; runtime: Runtime; constructor( key: string, mapping: PackageableElementReference<Mapping>, runtime: Runtime, ) { makeObservable(this, { key: observable, runtime: observable, mappingValidationResult: computed, setKey: action, setMapping: action, setRuntime: action, hashCode: computed, }); this.key = key; this.mapping = mapping; this.runtime = runtime; } get mappingValidationResult(): ValidationIssue | undefined { return this.mapping.value.isStub ? createValidationError(['Service execution mapping cannot be empty']) : undefined; } setKey(value: string): void { this.key = value; } setMapping(value: Mapping): void { this.mapping.setValue(value); } setRuntime(value: Runtime): void { this.runtime = value; } get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.SERVICE_KEYED_EXECUTION_PARAMETER, this.key, this.mapping.valueForSerialization, this.runtime, ]); } } export class PureMultiExecution extends PureExecution implements Hashable { executionKey: string; executionParameters: KeyedExecutionParameter[] = []; constructor(executionKey: string, func: RawLambda, parentService: Service) { super(func, parentService); makeObservable(this, { executionKey: observable, executionParameters: observable, setExecutionKey: action, addExecutionParameter: action, hashCode: computed, }); this.executionKey = executionKey; } setExecutionKey(value: string): void { this.executionKey = value; } addExecutionParameter(value: KeyedExecutionParameter): void { addUniqueEntry(this.executionParameters, value); } override get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.SERVICE_PURE_MULTI_EXECUTION, super.hashCode, this.executionKey, hashArray(this.executionParameters), ]); } }
nayanika2/legend-studio
packages/legend-studio/src/components/editor/edit-panel/GrammarTextEditor.tsx
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { useEffect, useState, useRef, useCallback } from 'react'; import { observer } from 'mobx-react-lite'; import { editor as monacoEditorAPI, KeyCode } from 'monaco-editor'; import { useEditorStore } from '../../../stores/EditorStore'; import { ContextMenu } from '@finos/legend-studio-components'; import { revealError, setErrorMarkers, disposeEditor, baseTextEditorSettings, disableEditorHotKeys, resetLineNumberGutterWidth, } from '../../../utils/TextEditorUtil'; import { TAB_SIZE, EDITOR_THEME, EDITOR_LANGUAGE, } from '../../../stores/EditorConfig'; import { useResizeDetector } from 'react-resize-detector'; import { FaUserSecret } from 'react-icons/fa'; import { MdMoreHoriz } from 'react-icons/md'; import { useApplicationStore } from '../../../stores/ApplicationStore'; import type { ElementDragSource } from '../../../stores/shared/DnDUtil'; import { CORE_DND_TYPE } from '../../../stores/shared/DnDUtil'; import type { DropTargetMonitor } from 'react-dnd'; import { useDrop } from 'react-dnd'; import type { DSL_EditorPlugin_Extension } from '../../../stores/EditorPlugin'; export const GrammarTextEditorHeaderTabContextMenu = observer( (props: {}, ref: React.Ref<HTMLDivElement>) => { const editorStore = useEditorStore(); const applicationStore = useApplicationStore(); const leaveTextMode = applicationStore.guaranteeSafeAction(() => editorStore.toggleTextMode(), ); return ( <div ref={ref} className="edit-panel__header__tab__context-menu"> <button className="edit-panel__header__tab__context-menu__item" onClick={leaveTextMode} > Leave Text Mode </button> </div> ); }, { forwardRef: true }, ); export const GrammarTextEditor = observer(() => { const [editor, setEditor] = useState< monacoEditorAPI.IStandaloneCodeEditor | undefined >(); const editorStore = useEditorStore(); const applicationStore = useApplicationStore(); const grammarTextEditorState = editorStore.grammarTextEditorState; const currentElementLabelRegexString = grammarTextEditorState.currentElementLabelRegexString; const error = grammarTextEditorState.error; const graphGrammarText = grammarTextEditorState.graphGrammarText; const textEditorRef = useRef<HTMLDivElement>(null); const leaveTextMode = applicationStore.guaranteeSafeAction(() => editorStore.toggleTextMode(), ); const { ref, width, height } = useResizeDetector<HTMLDivElement>(); useEffect(() => { if (width !== undefined && height !== undefined) { editor?.layout({ width, height }); } }, [editor, width, height]); useEffect(() => { if (!editor && textEditorRef.current) { const element = textEditorRef.current; const _editor = monacoEditorAPI.create(element, { ...baseTextEditorSettings, language: EDITOR_LANGUAGE.PURE, theme: EDITOR_THEME.STUDIO, }); _editor.onDidChangeModelContent(() => { grammarTextEditorState.setGraphGrammarText(_editor.getValue()); editorStore.graphState.clearCompilationError(); // we can technically can reset the current element label regex string here // but if we do that on first load, the cursor will not jump to the current element // also, it's better to place that logic in an effect that watches for the regex string }); _editor.onKeyDown((event) => { if (event.keyCode === KeyCode.F9) { event.preventDefault(); event.stopPropagation(); editorStore.graphState .globalCompileInTextMode() .catch(applicationStore.alertIllegalUnhandledError); } else if (event.keyCode === KeyCode.F8) { event.preventDefault(); event.stopPropagation(); editorStore .toggleTextMode() .catch(applicationStore.alertIllegalUnhandledError); } }); disableEditorHotKeys(_editor); _editor.focus(); // focus on the editor initially setEditor(_editor); } }, [editorStore, applicationStore, editor, grammarTextEditorState]); // Drag and Drop const extraDnDTypes = applicationStore.pluginManager .getEditorPlugins() .flatMap( (plugin) => ( plugin as DSL_EditorPlugin_Extension ).getExtraGrammarTextEditorDnDTypes?.() ?? [], ); const handleDrop = useCallback( (item: ElementDragSource, monitor: DropTargetMonitor): void => { if (editor) { editor.trigger('keyboard', 'type', { text: item.data.packageableElement.path, }); } }, [editor], ); const [, dropConnector] = useDrop( () => ({ accept: [ ...extraDnDTypes, CORE_DND_TYPE.PROJECT_EXPLORER_PACKAGE, CORE_DND_TYPE.PROJECT_EXPLORER_CLASS, CORE_DND_TYPE.PROJECT_EXPLORER_ASSOCIATION, CORE_DND_TYPE.PROJECT_EXPLORER_MEASURE, CORE_DND_TYPE.PROJECT_EXPLORER_ENUMERATION, CORE_DND_TYPE.PROJECT_EXPLORER_PROFILE, CORE_DND_TYPE.PROJECT_EXPLORER_FUNCTION, CORE_DND_TYPE.PROJECT_EXPLORER_FLAT_DATA, CORE_DND_TYPE.PROJECT_EXPLORER_DATABASE, CORE_DND_TYPE.PROJECT_EXPLORER_SERVICE_STORE, CORE_DND_TYPE.PROJECT_EXPLORER_MAPPING, CORE_DND_TYPE.PROJECT_EXPLORER_DIAGRAM, CORE_DND_TYPE.PROJECT_EXPLORER_SERVICE, CORE_DND_TYPE.PROJECT_EXPLORER_CONNECTION, CORE_DND_TYPE.PROJECT_EXPLORER_RUNTIME, CORE_DND_TYPE.PROJECT_EXPLORER_FILE_GENERATION, CORE_DND_TYPE.PROJECT_EXPLORER_GENERATION_TREE, ], drop: (item: ElementDragSource, monitor): void => handleDrop(item, monitor), }), [extraDnDTypes, handleDrop], ); dropConnector(textEditorRef); if (editor) { // Set the value of the editor const currentValue = editor.getValue(); if (currentValue !== graphGrammarText) { editor.setValue(graphGrammarText); } resetLineNumberGutterWidth(editor); const editorModel = editor.getModel(); if (editorModel) { editorModel.updateOptions({ tabSize: TAB_SIZE }); if (error?.sourceInformation) { setErrorMarkers(editorModel, error.sourceInformation, error.message); } else { monacoEditorAPI.setModelMarkers(editorModel, 'Error', []); } } // Disable editing if user is in viewer mode editor.updateOptions({ readOnly: editorStore.isInViewerMode }); } /** * Reveal error has to be in an effect like this because, we want to reveal the error. * For this to happen, the editor needs to gain focus. However, if the user clicks on the * exit hackermode button, the editor loses focus, and the blocking modal pops up. This modal * in turn traps the focus and preventing the editor from gaining the focus to reveal the error. * As such we want to dismiss the modal before revealing the error, however, as of the current flow * dismissing the modal is called when we set the parser/compiler error. So if this logic belongs to * the normal rendering logic, and not an effect, it might happen just when the modal is still present * to make sure the modal is dismissed, we should place this logic in an effect to make sure it happens * slightly later, also it's better to have this as part of an effect in response to change in the errors */ useEffect(() => { if (editor) { if (error?.sourceInformation) { revealError(editor, error.sourceInformation); } } }, [editor, error, error?.sourceInformation]); /** * This effect helps to navigate to the currently selected element in the explorer tree * NOTE: this effect is placed after the effect to highlight and move cursor to error, * as even when there are errors, the user should be able to click on the explorer tree * to navigate to the element */ useEffect(() => { if (editor && currentElementLabelRegexString) { const editorModel = editor.getModel(); if (editorModel) { const match = editorModel.findMatches( currentElementLabelRegexString, true, true, true, null, true, ); if (Array.isArray(match) && match.length) { const range = match[0].range; editor.focus(); editor.revealPositionInCenter({ lineNumber: range.startLineNumber, column: range.startColumn, }); editor.setPosition({ column: range.startColumn, lineNumber: range.startLineNumber, }); } } } }, [editor, currentElementLabelRegexString]); // NOTE: dispose the editor to prevent potential memory-leak useEffect( () => (): void => { if (editor) { disposeEditor(editor); } }, [editor], ); return ( <div className="panel edit-panel"> <ContextMenu className="panel__header edit-panel__header" disabled={true}> <div className="edit-panel__header__tabs"> <div className="edit-panel__header__tab edit-panel__header__tab__exit-text-mode"> <button className="edit-panel__header__tab__label edit-panel__header__tab__exit-text-mode__label" disabled={editorStore.graphState.isApplicationLeavingTextMode} onClick={leaveTextMode} tabIndex={-1} title="Click to exit text mode and go back to form mode" > <MdMoreHoriz /> </button> </div> <ContextMenu className="edit-panel__header__tab edit-panel__header__tab__text-mode edit-panel__header__tab--active" content={<GrammarTextEditorHeaderTabContextMenu />} > <div className="edit-panel__header__tab__icon"> <FaUserSecret /> </div> <div className="edit-panel__header__tab__label">Text Mode</div> </ContextMenu> </div> </ContextMenu> <div className="panel__content edit-panel__content"> <div ref={ref} className="text-editor__container"> <div className="text-editor__body" ref={textEditorRef} /> </div> </div> </div> ); });
nayanika2/legend-studio
packages/legend-studio/src/components/editor/edit-panel/mapping-editor/execution-plan-viewer/SqlPlanViewer.tsx
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { observer } from 'mobx-react-lite'; import type { SQLResultColumn } from '../../../../../models/metamodels/pure/model/executionPlan/nodes/SQLResultColumn'; import { TextInputEditor } from '../../../../shared/TextInputEditor'; import { EDITOR_LANGUAGE } from '../../../../../stores/EditorConfig'; import { Real, Binary, Bit, Other, Date, Timestamp, Numeric, Decimal, VarBinary, Char, VarChar, Double, Float, Integer, TinyInt, SmallInt, BigInt, } from '../../../../../models/metamodels/pure/model/packageableElements/store/relational/model/RelationalDataType'; import type { DataType } from '../../../../../models/metamodels/pure/model/packageableElements/store/relational/model/RelationalDataType'; import type { ExecutionPlanState } from '../../../../../stores/ExecutionPlanState'; import { SQL_DISPLAY_TABS } from '../../../../../stores/ExecutionPlanState'; import { prettyCONSTName } from '@finos/legend-studio-shared'; import { clsx } from '@finos/legend-studio-components'; import type { DatabaseConnection } from '../../../../../models/metamodels/pure/model/packageableElements/store/relational/connection/RelationalDatabaseConnection'; import { RelationalDatabaseConnection } from '../../../../../models/metamodels/pure/model/packageableElements/store/relational/connection/RelationalDatabaseConnection'; import { RelationalDatabaseConnectionEditor } from '../../connection-editor/RelationalDatabaseConnectionEditor'; import { format } from 'sql-formatter'; import { RelationalDatabaseConnectionValueState } from '../../../../../stores/editor-state/element-editor-state/connection/ConnectionEditorState'; interface QueryProps { query: string; language: EDITOR_LANGUAGE; wordWrap: 'off' | 'on' | 'wordWrapColumn' | 'bounded' | undefined; } interface resultColumnsProps { resultColumns: SQLResultColumn[]; } const generateDataTypeLabel = (type: DataType | undefined): string => { if (type === undefined) { return `UNDEFINED`; } else if (type instanceof VarChar) { return `VARCHAR`; } else if (type instanceof Char) { return `CHAR`; } else if (type instanceof VarBinary) { return `VARBINARY`; } else if (type instanceof Binary) { return `BINARY`; } else if (type instanceof Bit) { return `BIT`; } else if (type instanceof Numeric) { return `NUMERIC`; } else if (type instanceof Decimal) { return `DECIMAL`; } else if (type instanceof Double) { return `DOUBLE`; } else if (type instanceof Float) { return `FLOAT`; } else if (type instanceof Real) { return `REAL`; } else if (type instanceof Integer) { return `INT`; } else if (type instanceof BigInt) { return `BIGINT`; } else if (type instanceof SmallInt) { return `SMALLINT`; } else if (type instanceof TinyInt) { return `TINYINT`; } else if (type instanceof Date) { return `DATE`; } else if (type instanceof Timestamp) { return `TIMESTAMP`; } else if (type instanceof Other) { return `OTHER`; } else { return `UNDEFINED`; } }; const QueryViewer: React.FC<QueryProps> = ({ query, language, wordWrap }) => ( <div className="mapping-test-editor__query-panel__query"> <TextInputEditor inputValue={query} isReadOnly={true} language={language} showMiniMap={false} extraEditorOptions={{ wordWrap: wordWrap, }} /> </div> ); interface labelprops { label: string; dataType: string; } const ResultColumsDataViewer: React.FC<labelprops> = ({ label, dataType }) => ( <div className="property-basic-editor"> <div className="property-basic-editor__type "> <input className="property-basic-editor__name input-label" disabled={true} value={label} spellCheck={false} /> </div> <div className="property-basic-editor__type"> <input className="property-basic-editor__name input-type" disabled={true} value={dataType} spellCheck={false} /> </div> </div> ); const ResultCoulumsViewer: React.FC<resultColumnsProps> = ({ resultColumns, }) => ( <div> {resultColumns.map((resCol, i) => { const label = resCol.label.match(/(?:"[^"]*"|^[^"]*$)/); if (!(label === null)) { return ( <ResultColumsDataViewer key={resCol.label} label={label[0].replace(/"/g, '')} dataType={generateDataTypeLabel(resCol.dataType)} /> ); } else { return ( <ResultColumsDataViewer key={resCol.label} label={resCol.label} dataType={generateDataTypeLabel(resCol.dataType)} /> ); } })} </div> ); interface sqlprops { query: string; resultCoulumns: SQLResultColumn[]; connection: DatabaseConnection; executionPlanState: ExecutionPlanState; } export const SqlPlanViewer: React.FC<sqlprops> = observer( (props: { query: string; resultCoulumns: SQLResultColumn[]; connection: DatabaseConnection; executionPlanState: ExecutionPlanState; }) => { const { query, resultCoulumns, connection, executionPlanState } = props; const tabs = [ SQL_DISPLAY_TABS.SQL_QUERY, SQL_DISPLAY_TABS.RESULT_COLUMNS, SQL_DISPLAY_TABS.DATABASE_CONNECTION, ]; const changeTab = (tab: SQL_DISPLAY_TABS): (() => void) => (): void => { executionPlanState.setSqlSelectedTab(tab); }; return ( <div className="panel__content"> <div className="panel__main-header edit-panel__header"> <div className="edit-panel__header__tabs"> {tabs.map((tab) => ( <button key={tab} onClick={changeTab(tab)} className={clsx('edit-panel__header__tab', { 'edit-panel__header__tab--active': tab === executionPlanState.sqlSelectedTab, })} > {prettyCONSTName(tab)} </button> ))} </div> </div> {executionPlanState.sqlSelectedTab === SQL_DISPLAY_TABS.SQL_QUERY && ( <QueryViewer query={format(query)} language={EDITOR_LANGUAGE.SQL} wordWrap="on" /> )} {executionPlanState.sqlSelectedTab === SQL_DISPLAY_TABS.RESULT_COLUMNS && ( <div className="table-view"> <ResultCoulumsViewer resultColumns={resultCoulumns} /> </div> )} {executionPlanState.sqlSelectedTab === SQL_DISPLAY_TABS.DATABASE_CONNECTION && connection instanceof RelationalDatabaseConnection && ( <div> <RelationalDatabaseConnectionEditor connectionValueState={ new RelationalDatabaseConnectionValueState( executionPlanState.editorStore, connection, ) } isReadOnly={true} /> </div> )} </div> ); }, );
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/transformation/pureGraph/to/V1_GraphBuilderExtensions.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { GenericClazz } from '@finos/legend-studio-shared'; import { isClassAssignableFrom, isNonNullable, getClass, getSuperClass, UnsupportedOperationError, IllegalStateError, } from '@finos/legend-studio-shared'; import type { PureProtocolProcessorPlugin } from '../../../../PureProtocolProcessorPlugin'; import { V1_PackageableConnection } from '../../../model/packageableElements/connection/V1_PackageableConnection'; import { V1_Diagram } from '../../../model/packageableElements/diagram/V1_Diagram'; import { V1_Association } from '../../../model/packageableElements/domain/V1_Association'; import { V1_Class } from '../../../model/packageableElements/domain/V1_Class'; import { V1_Enumeration } from '../../../model/packageableElements/domain/V1_Enumeration'; import { V1_Measure, V1_Unit, } from '../../../model/packageableElements/domain/V1_Measure'; import { V1_Profile } from '../../../model/packageableElements/domain/V1_Profile'; import { V1_FileGenerationSpecification } from '../../../model/packageableElements/fileGeneration/V1_FileGenerationSpecification'; import { V1_ConcreteFunctionDefinition } from '../../../model/packageableElements/function/V1_ConcreteFunctionDefinition'; import { V1_GenerationSpecification } from '../../../model/packageableElements/generationSpecification/V1_GenerationSpecification'; import { V1_Mapping } from '../../../model/packageableElements/mapping/V1_Mapping'; import { V1_PackageableRuntime } from '../../../model/packageableElements/runtime/V1_PackageableRuntime'; import { V1_SectionIndex } from '../../../model/packageableElements/section/V1_SectionIndex'; import { V1_Service } from '../../../model/packageableElements/service/V1_Service'; import { V1_Store } from '../../../model/packageableElements/store/V1_Store'; import { V1_PackageableElement } from '../../../model/packageableElements/V1_PackageableElement'; import type { V1_ElementBuilder } from './V1_ElementBuilder'; const FORBIDDEN_BUILDER_PROTOCOL_CLASSES = new Set< GenericClazz<V1_PackageableElement> >([ V1_PackageableElement, V1_Class, V1_Association, V1_Enumeration, V1_ConcreteFunctionDefinition, V1_Profile, V1_Measure, V1_Unit, V1_SectionIndex, V1_Store, V1_Mapping, V1_PackageableConnection, V1_PackageableRuntime, V1_Service, V1_Diagram, V1_FileGenerationSpecification, V1_GenerationSpecification, ]); export class V1_GraphBuilderExtensions { plugins: PureProtocolProcessorPlugin[] = []; private extraElementBuildersIndex: Map< GenericClazz<V1_PackageableElement>, V1_ElementBuilder<V1_PackageableElement> >; sortedExtraElementBuilders: V1_ElementBuilder<V1_PackageableElement>[] = []; constructor(graphManagerPlugins: PureProtocolProcessorPlugin[]) { this.plugins = graphManagerPlugins; this.extraElementBuildersIndex = V1_GraphBuilderExtensions.indexElementBuilders(this.plugins); this.sortedExtraElementBuilders = this.getSortedExtraElementBuilders(); } private static indexElementBuilders( graphManagerPlugins: PureProtocolProcessorPlugin[], ): Map< GenericClazz<V1_PackageableElement>, V1_ElementBuilder<V1_PackageableElement> > { const index = new Map< GenericClazz<V1_PackageableElement>, V1_ElementBuilder<V1_PackageableElement> >(); graphManagerPlugins .flatMap((plugin) => plugin.V1_getExtraElementBuilders?.() ?? []) .forEach((builder) => { const _class = builder.getElementProtocolClass(); if (FORBIDDEN_BUILDER_PROTOCOL_CLASSES.has(_class)) { throw new IllegalStateError( `Element builder not allowed for protocol class '${builder.elementClassName}'. Consider removing this builder from plugins`, ); } else if (index.has(_class)) { throw new IllegalStateError( `Conflicting element builders found for protocol class '${builder.elementClassName}'`, ); } index.set(_class, builder); }); return index; } getExtraBuilderOrThrow( element: V1_PackageableElement, ): V1_ElementBuilder<V1_PackageableElement> { const builder = this.getExtraBuilderForProtocolClass( getClass<V1_PackageableElement>(element), ); if (!builder) { throw new UnsupportedOperationError( `Can't find builder for element '${element.path}': no compatible builder available from plugins`, element, ); } return builder; } getExtraBuilderForProtocolClassOrThrow( _class: GenericClazz<V1_PackageableElement>, ): V1_ElementBuilder<V1_PackageableElement> { const builder = this.getExtraBuilderForProtocolClass(_class); if (!builder) { throw new UnsupportedOperationError( `Can't find element builder for the specified protocol class: no compatible builder available from plugins`, ); } return builder; } getExtraBuilderForProtocolClass( _class: GenericClazz<V1_PackageableElement>, ): V1_ElementBuilder<V1_PackageableElement> | undefined { return this.extraElementBuildersIndex.size ? this.getExtraBuilderForProtocolClass_recursive(_class) : undefined; } private getExtraBuilderForProtocolClass_recursive( _class: GenericClazz<V1_PackageableElement>, ): V1_ElementBuilder<V1_PackageableElement> | undefined { const builder = this.extraElementBuildersIndex.get(_class); if (builder) { return builder; } if (FORBIDDEN_BUILDER_PROTOCOL_CLASSES.has(_class)) { return undefined; } // We can ignore interfaces in this search, since V1_PackageableElement is itself a class (not an interface) const superClass = getSuperClass<V1_PackageableElement>(_class); return superClass ? this.getExtraBuilderForProtocolClass_recursive(superClass) : undefined; } /** * Sort element builders in near topological manner. A very subtle detail here is * that if for a builder's prerequisite class there are builders which support * that class or its subclass, those builders will go first as well. * * e.g. If we have: * - class SomeStore extends class Store. * - builder1 supports SomeStore * - builder2 supports SomeElement, and has SomeStore as a prerequisite * Then this sorter makes sure builder2 will be ordered after builder1. * * NOTE: we can consider using topological sorting if that implementation is cleaner. */ private getSortedExtraElementBuilders(): V1_ElementBuilder<V1_PackageableElement>[] { // Collect builder pre-requisites. Those without pre-requisites can go straight into the results list. const results = new Set<V1_ElementBuilder<V1_PackageableElement>>(); const buildersWithPrereqIndex = new Map< V1_ElementBuilder<V1_PackageableElement>, GenericClazz<V1_PackageableElement>[] >(); Array.from(this.extraElementBuildersIndex.values()).forEach((builder) => { const prerequisites = builder.getPrerequisiteElementProtocolClasses(); if (prerequisites.length > 0) { buildersWithPrereqIndex.set(builder, prerequisites); } else { results.add(builder); } }); // If there are builders with pre-requisites, we need to add them to the results list in an appropriate order. if (buildersWithPrereqIndex.size > 0) { const remaining = new Map< V1_ElementBuilder<V1_PackageableElement>, V1_ElementBuilder<V1_PackageableElement>[] >(); // We transform the pre-requisite classes into pre-requisite builders. buildersWithPrereqIndex.forEach((prerequisiteClasses, builder) => { // We only need to be concerned about pre-requisite builders that are not already in the results list, // since the ones already in the results list will go before any which are not already in that list. // We call these `outstanding` pre-requistes const outstandingPrereqs = new Set( // First, scan the list of builders with prerequisite, if among the prerequisite classes // of the current builder, there's another builder that works for that class or its subclass // include that builder as a prerequisite for the current builder. In other words, if a builder // has a prerequisite class, all builders for that class and its subclasses should go first Array.from(buildersWithPrereqIndex.keys()) .filter( (_builder) => _builder !== builder && prerequisiteClasses.some((_class) => isClassAssignableFrom( _class, _builder.getElementProtocolClass(), ), ), ) .concat( // Second, for each prerequisite class, resolve the builder // for that class. The resolution goes up the class hierarchy chain. prerequisiteClasses .map((_class) => this.getExtraBuilderForProtocolClass(_class)) .filter(isNonNullable) .filter( (_builder) => _builder !== _builder && buildersWithPrereqIndex.has(_builder), ), ), ); if (outstandingPrereqs.size > 0) { remaining.set(builder, Array.from(outstandingPrereqs.values())); } else { // If the builder itself does not have any outstanding prerequisites, it can be safely added to the the results list. results.add(builder); } }); // Now we start adding builders with pre-requisites to the results list. If a builder has no pre- // requisites among the other remaining builders, then all of its pre-requisites are already ahead of it // in the results list and so we can add it. // // We repeat this process until either there are no more remaining builders or we are unable to add any // remaining builders to the results list. The latter case indicates some sort of loop among the pre- // requisites, so we cannot put them in a consistent order and we must throw. let remainingCount = remaining.size; while (remainingCount > 0) { remaining.forEach((prereqs, builder) => { if (prereqs.every((prereq) => !remaining.has(prereq))) { // If a builder has no pre-requisites among the remaining builders, we can add it to the // results list and remove it from the remaining builders. results.add(builder); remaining.delete(builder); } }); const newCount = remaining.size; if (newCount === remainingCount) { // This means that all of the remaining builders have a pre-requisite of some other remaining // builders. This implies that there's some sort of loop, and we cannot consistently order the // remaining builders. throw new IllegalStateError( `Can't consistently sort element builders for protocol classes [${Array.from( remaining.keys(), ) .map((builder) => builder.elementClassName) .join( ', ', )}]: this implies presence of loop(s) in the pre-requite chain between these builders`, ); } remainingCount = newCount; } } return Array.from(results.values()); } }
nayanika2/legend-studio
packages/legend-studio/src/models/__tests__/MetaModelUtils.test.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { extractElementNameFromPath, fromElementPathToMappingElementId, matchFunctionName, } from '../MetaModelUtils'; import { unitTest } from '@finos/legend-studio-shared'; test(unitTest('Extract element name in full element path'), () => { expect(extractElementNameFromPath('namePart')).toBe('namePart'); expect(extractElementNameFromPath('p1::p2::p3::namePart')).toBe('namePart'); }); test(unitTest('Matches function name'), () => { expect(matchFunctionName('fnX', 'p1::p2::p3::fnX')).toBe(true); expect(matchFunctionName('fnX', 'fnX')).toBe(true); expect(matchFunctionName('p5::fnX', 'p1::p2::p3::fnX')).toBe(false); expect(matchFunctionName('p3::fnX', 'p1::p2::p3::fnX')).toBe(false); expect(matchFunctionName('fnY', 'fnX')).toBe(false); }); test(unitTest('Converts element path to mapping element default ID'), () => { expect( fromElementPathToMappingElementId( 'meta::pure::mapping::modelToModel::test::shared::dest::Person', ), ).toBe('meta_pure_mapping_modelToModel_test_shared_dest_Person'); expect(fromElementPathToMappingElementId('Person')).toBe('Person'); });
nayanika2/legend-studio
packages/legend-studio-plugin-management/src/components/projectDashboard/ProjectDashboard.tsx
<filename>packages/legend-studio-plugin-management/src/components/projectDashboard/ProjectDashboard.tsx<gh_stars>0 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { useEffect, createContext, useContext } from 'react'; import { observer, useLocalObservable } from 'mobx-react-lite'; import { FaQuestionCircle, FaTimesCircle, FaCheckCircle, FaCircleNotch, FaPauseCircle, FaBan, } from 'react-icons/fa'; import { PanelLoadingIndicator } from '@finos/legend-studio-components'; import type { GeneratorFn, PlainObject } from '@finos/legend-studio-shared'; import { guaranteeNonNullable } from '@finos/legend-studio-shared'; import { flowResult, makeAutoObservable } from 'mobx'; import type { ApplicationStore } from '@finos/legend-studio'; import { Build, BuildStatus, CORE_LOG_EVENT, Project, ProjectType, useApplicationStore, AppHeader, AppHeaderMenu, } from '@finos/legend-studio'; class ProjectDashboardStore { applicationStore: ApplicationStore; projects: Map<string, Project> = new Map<string, Project>(); /** * `undefined` when we are loading the build * `null` when there are no builds available */ currentBuildByProject: Map<string, Build | undefined | null> = new Map< string, Build | undefined | null >(); isFetchingProjects = false; constructor(applicationStore: ApplicationStore) { makeAutoObservable(this, { applicationStore: false, }); this.applicationStore = applicationStore; } *fetchProjects(): GeneratorFn<void> { this.isFetchingProjects = true; try { yield Promise.all([ this.fetchProjectByType(ProjectType.PRODUCTION), this.fetchProjectByType(ProjectType.PROTOTYPE), ]); } catch (error: unknown) { this.applicationStore.logger.error(CORE_LOG_EVENT.SETUP_PROBLEM, error); this.applicationStore.notifyError(error); } finally { this.isFetchingProjects = false; } } *fetchProjectByType(projectType: ProjectType): GeneratorFn<void> { const projects = ( (yield this.applicationStore.networkClientManager.sdlcClient.getProjects( projectType, false, undefined, undefined, )) as PlainObject<Project>[] ).map((project) => Project.serialization.fromJson(project)); projects.forEach((project) => this.projects.set(project.projectId, project), ); projects.forEach((project) => this.currentBuildByProject.set(project.projectId, undefined), ); yield Promise.all( projects.map((project) => this.fetchProjectCurrentBuildStatus(project)), ); } *fetchProjectCurrentBuildStatus(project: Project): GeneratorFn<void> { try { const builds = (yield this.applicationStore.networkClientManager.sdlcClient.getBuilds( project.projectId, undefined, undefined, undefined, 1, )) as PlainObject<Build>[]; this.currentBuildByProject.set( project.projectId, builds.length !== 0 ? Build.serialization.fromJson(builds[0]) : null, ); } catch (error: unknown) { this.applicationStore.logger.error(CORE_LOG_EVENT.SETUP_PROBLEM, error); this.applicationStore.notifyError(error); } } } const ProjectDashboardStoreContext = createContext< ProjectDashboardStore | undefined >(undefined); const ProjectDashboardStoreProvider = ({ children, }: { children: React.ReactNode; }): React.ReactElement => { const applicationStore = useApplicationStore(); const store = useLocalObservable( () => new ProjectDashboardStore(applicationStore), ); return ( <ProjectDashboardStoreContext.Provider value={store}> {children} </ProjectDashboardStoreContext.Provider> ); }; const useProjectDashboardStore = (): ProjectDashboardStore => guaranteeNonNullable( useContext(ProjectDashboardStoreContext), 'useProjectDashboardStore() hook must be used inside ProjectDashboardStoreContext context provider', ); const renderBuildStatus = (data: Build): React.ReactElement => { switch (data.status) { case BuildStatus.PENDING: return ( <div title="Pipeline is suspended" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--suspended" > <FaPauseCircle /> </div> ); case BuildStatus.IN_PROGRESS: return ( <div title="Pipeline is running" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--in-progress" > <FaCircleNotch /> </div> ); case BuildStatus.SUCCEEDED: return ( <div title="Pipeline succeeded" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--succeeded" > <FaCheckCircle /> </div> ); case BuildStatus.FAILED: return ( <div title="Pipeline failed" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--failed" > <FaTimesCircle /> </div> ); case BuildStatus.CANCELED: return ( <div title="Pipeline is canceled" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--canceled" > <FaBan /> </div> ); case BuildStatus.UNKNOWN: default: return ( <div title="Pipeline status is unknown" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--unknown" > <FaQuestionCircle /> </div> ); } }; const renderProjectBuildStatus = ( data: Build | undefined | null, ): React.ReactElement => { if (data === undefined) { return ( <div title="Fetching pipeline information" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--fetching" > <FaCircleNotch /> </div> ); } else if (data === null) { return ( <div title="No pipeline found" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--not-found" > <FaQuestionCircle /> </div> ); } else { return ( <a href={data.webURL} target="_blank" rel="noopener noreferrer"> {renderBuildStatus(data)} </a> ); } }; /** * NOTE: this view is still under construction and likely get replaced in the future */ export const ProjectDashboardInner = observer(() => { const dashboardStore = useProjectDashboardStore(); const applicationStore = useApplicationStore(); const projects = dashboardStore.projects; const productionProjects = Array.from(projects.values()).filter( (project) => project.projectType === ProjectType.PRODUCTION, ); const productionFailures = productionProjects .map((project) => dashboardStore.currentBuildByProject.get(project.projectId), ) .filter( (build) => build instanceof Build && build.status === BuildStatus.FAILED, ); const prototypeProjects = Array.from(projects.values()).filter( (project) => project.projectType === ProjectType.PROTOTYPE, ); const prototypeFailures = prototypeProjects .map((project) => dashboardStore.currentBuildByProject.get(project.projectId), ) .filter( (build) => build instanceof Build && build.status === BuildStatus.FAILED, ); useEffect(() => { flowResult(dashboardStore.fetchProjects()).catch( applicationStore.alertIllegalUnhandledError, ); }, [applicationStore, dashboardStore]); return ( <div className="app__page"> <AppHeader> <AppHeaderMenu /> </AppHeader> <div className="app__content"> <div className="project-dashboard"> <PanelLoadingIndicator isLoading={dashboardStore.isFetchingProjects} /> <div className="project-dashboard__group"> <div className="project-dashboard__group__header"> <div className="project-dashboard__group__header__name"> PROD - Production </div> <div className="project-dashboard__group__header__count"> ({productionProjects.length}) </div> {Boolean(productionFailures.length) && ( <div className="project-dashboard__group__header__failure"> <div title="Pipeline failed" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--failed" > <FaTimesCircle /> </div> <div className="project-dashboard__group__header__failure__count"> {productionFailures.length} </div> </div> )} </div> {productionProjects.map((project) => ( <div key={project.projectId} className="project-dashboard__group__item" > <div className="project-dashboard__group__item__build-status"> {renderProjectBuildStatus( dashboardStore.currentBuildByProject.get(project.projectId), )} </div> <div className="project-dashboard__group__item__name"> {project.name} </div> <div className="project-dashboard__group__item__id"> {project.projectId} </div> </div> ))} </div> <div className="project-dashboard__group"> <div className="project-dashboard__group__header"> <div className="project-dashboard__group__header__name"> UAT - Prototype </div> <div className="project-dashboard__group__header__count"> ({prototypeProjects.length}) </div> {Boolean(prototypeFailures.length) && ( <div className="project-dashboard__group__header__failure"> <div title="Pipeline failed" className="project-dashboard__group__item__build-status__indicator project-dashboard__group__item__build-status__indicator--failed" > <FaTimesCircle /> </div> <div className="project-dashboard__group__header__failure__count"> {prototypeFailures.length} </div> </div> )} </div> {prototypeProjects.map((project) => ( <div key={project.projectId} className="project-dashboard__group__item" > <div className="project-dashboard__group__item__build-status"> {renderProjectBuildStatus( dashboardStore.currentBuildByProject.get(project.projectId), )} </div> <div className="project-dashboard__group__item__name"> {project.name} </div> <div className="project-dashboard__group__item__id"> {project.projectId} </div> </div> ))} </div> </div> </div> </div> ); }); export const ProjectDashboard: React.FC = () => ( <ProjectDashboardStoreProvider> <ProjectDashboardInner /> </ProjectDashboardStoreProvider> );
nayanika2/legend-studio
packages/legend-studio-shared/src/utils/RandomUtils.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import seedrandom from 'seedrandom'; let rng = seedrandom(); /** * This method is exposed to allow setting seeds in test. * NOTE: Disable this during production for security. */ export const setSeed = (seed?: string): void => { // eslint-disable-next-line no-process-env if (process.env.NODE_ENV === 'production') { return; } rng = seedrandom(seed); }; export const getRandomFloat = (): number => rng.quick(); export const getRandomDouble = (): number => rng.double(); export const getRandomSignedInteger = (): number => rng.int32(); export const getRandomPositiveInteger = (max?: number): number => max ? Math.floor(getRandomFloat() * Math.floor(max)) : Math.abs(getRandomSignedInteger()); export const getRandomItemInCollection = <T>(collection: T[]): T => collection[getRandomPositiveInteger(collection.length)]; export const getRandomDate = (start: Date, end: Date): Date => new Date( start.getTime() + Math.floor(getRandomFloat() * (end.getTime() - start.getTime())), );
nayanika2/legend-studio
packages/legend-studio/src/stores/Router.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { generatePath } from 'react-router-dom'; export enum PATH_PARAM_TOKEN { SDLC_SERVER_KEY = 'sdlcServerKey', PROJECT_ID = 'projectId', WORKSPACE_ID = 'workspaceId', REVISION_ID = 'revisionId', VERSION_ID = 'versionId', REVIEW_ID = 'reviewId', ENTITY_PATH = 'entityPath', } export const URL_PATH_PLACEHOLDER = '-'; export const generateRoutePatternWithSDLCServerKey = ( pattern: string, ): string => `/:${PATH_PARAM_TOKEN.SDLC_SERVER_KEY}${pattern}`; export const ROUTE_PATTERN = Object.freeze({ VIEW: generateRoutePatternWithSDLCServerKey( `/view/:${PATH_PARAM_TOKEN.PROJECT_ID}`, ), VIEW_BY_ENTITY: generateRoutePatternWithSDLCServerKey( `/view/:${PATH_PARAM_TOKEN.PROJECT_ID}/entity/:${PATH_PARAM_TOKEN.ENTITY_PATH}`, ), VIEW_BY_REVISION: generateRoutePatternWithSDLCServerKey( `/view/:${PATH_PARAM_TOKEN.PROJECT_ID}/revision/:${PATH_PARAM_TOKEN.REVISION_ID}`, ), VIEW_BY_VERSION: generateRoutePatternWithSDLCServerKey( `/view/:${PATH_PARAM_TOKEN.PROJECT_ID}/version/:${PATH_PARAM_TOKEN.VERSION_ID}`, ), VIEW_BY_REVISION_ENTITY: generateRoutePatternWithSDLCServerKey( `/view/:${PATH_PARAM_TOKEN.PROJECT_ID}/revision/:${PATH_PARAM_TOKEN.REVISION_ID}/entity/:${PATH_PARAM_TOKEN.ENTITY_PATH}`, ), VIEW_BY_VERSION_ENTITY: generateRoutePatternWithSDLCServerKey( `/view/:${PATH_PARAM_TOKEN.PROJECT_ID}/version/:${PATH_PARAM_TOKEN.VERSION_ID}/entity/:${PATH_PARAM_TOKEN.ENTITY_PATH}`, ), REVIEW: generateRoutePatternWithSDLCServerKey( `/review/:${PATH_PARAM_TOKEN.PROJECT_ID}/:${PATH_PARAM_TOKEN.REVIEW_ID}`, ), EDIT: generateRoutePatternWithSDLCServerKey( `/edit/:${PATH_PARAM_TOKEN.PROJECT_ID}/:${PATH_PARAM_TOKEN.WORKSPACE_ID}/`, ), SETUP: generateRoutePatternWithSDLCServerKey( `/setup/:${PATH_PARAM_TOKEN.PROJECT_ID}?/:${PATH_PARAM_TOKEN.WORKSPACE_ID}?`, ), }); export const generateSetupRoute = ( sdlcServerKey: string, projectId: string | undefined, workspaceId?: string, ): string => generatePath(ROUTE_PATTERN.SETUP, { sdlcServerKey, projectId, workspaceId, }); export const generateEditorRoute = ( sdlcServerKey: string, projectId: string, workspaceId: string, ): string => generatePath(ROUTE_PATTERN.EDIT, { sdlcServerKey, projectId, workspaceId, }); export const generateReviewRoute = ( sdlcServerKey: string, projectId: string, reviewId?: string, ): string => generatePath(ROUTE_PATTERN.REVIEW, { sdlcServerKey, projectId, reviewId, }); export const generateViewProjectRoute = ( sdlcServerKey: string, projectId: string, ): string => generatePath(ROUTE_PATTERN.VIEW, { sdlcServerKey, projectId, }); export const generateViewVersionRoute = ( sdlcServerKey: string, projectId: string, versionId: string, ): string => generatePath(ROUTE_PATTERN.VIEW_BY_VERSION, { sdlcServerKey, projectId, versionId, }); export const generateVieweRevisionRoute = ( sdlcServerKey: string, projectId: string, revisionId: string, ): string => generatePath(ROUTE_PATTERN.VIEW_BY_REVISION, { sdlcServerKey, projectId, revisionId, }); export const generateViewEntityRoute = ( sdlcServerKey: string, projectId: string, entityPath: string, ): string => generatePath(ROUTE_PATTERN.VIEW_BY_ENTITY, { sdlcServerKey, projectId, entityPath, }); export interface SDLCServerKeyRouteParams { [PATH_PARAM_TOKEN.SDLC_SERVER_KEY]: string; } export interface ReviewRouteParams { [PATH_PARAM_TOKEN.PROJECT_ID]: string; [PATH_PARAM_TOKEN.REVIEW_ID]: string; } export interface ViewerRouteParams { [PATH_PARAM_TOKEN.PROJECT_ID]: string; [PATH_PARAM_TOKEN.VERSION_ID]?: string; [PATH_PARAM_TOKEN.REVISION_ID]?: string; [PATH_PARAM_TOKEN.ENTITY_PATH]?: string; } export interface EditorRouteParams { [PATH_PARAM_TOKEN.PROJECT_ID]: string; [PATH_PARAM_TOKEN.WORKSPACE_ID]: string; } export interface SetupRouteParams { [PATH_PARAM_TOKEN.PROJECT_ID]?: string; [PATH_PARAM_TOKEN.WORKSPACE_ID]?: string; }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/model/packageableElements/V1_PackageableElement.ts
<gh_stars>1-10 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { CORE_HASH_STRUCTURE, ELEMENT_PATH_DELIMITER, } from '../../../../../MetaModelConst'; import { hashArray } from '@finos/legend-studio-shared'; import type { Hashable } from '@finos/legend-studio-shared'; import type { V1_Profile } from './domain/V1_Profile'; import type { V1_Class } from './domain/V1_Class'; import type { V1_Diagram } from './diagram/V1_Diagram'; import type { V1_Enumeration } from './domain/V1_Enumeration'; import type { V1_FlatData } from './store/flatData/model/V1_FlatData'; import type { V1_Database } from './store/relational/model/V1_Database'; import type { V1_Mapping } from './mapping/V1_Mapping'; import type { V1_Service } from './service/V1_Service'; import type { V1_ConcreteFunctionDefinition } from './function/V1_ConcreteFunctionDefinition'; import type { V1_Association } from './domain/V1_Association'; import type { V1_PackageableRuntime } from './runtime/V1_PackageableRuntime'; import type { V1_PackageableConnection } from './connection/V1_PackageableConnection'; import type { V1_FileGenerationSpecification } from './fileGeneration/V1_FileGenerationSpecification'; import type { V1_GenerationSpecification } from './generationSpecification/V1_GenerationSpecification'; import type { V1_Measure } from './domain/V1_Measure'; import type { V1_SectionIndex } from './section/V1_SectionIndex'; import type { V1_ServiceStore } from './store/relational/V1_ServiceStore'; /* @MARKER: NEW ELEMENT TYPE SUPPORT --- consider adding new element type handler here whenever support for a new element type is added to the app */ export interface V1_PackageableElementVisitor<T> { visit_PackageableElement(element: V1_PackageableElement): T; visit_Profile(element: V1_Profile): T; visit_Enumeration(element: V1_Enumeration): T; visit_Measure(element: V1_Measure): T; visit_Class(element: V1_Class): T; visit_Association(element: V1_Association): T; visit_ConcreteFunctionDefinition(element: V1_ConcreteFunctionDefinition): T; visit_FlatData(element: V1_FlatData): T; visit_Database(element: V1_Database): T; visit_ServiceStore(element: V1_ServiceStore): T; visit_Mapping(element: V1_Mapping): T; visit_Service(element: V1_Service): T; visit_Diagram(element: V1_Diagram): T; visit_PackageableRuntime(element: V1_PackageableRuntime): T; visit_PackageableConnection(element: V1_PackageableConnection): T; visit_FileGeneration(element: V1_FileGenerationSpecification): T; visit_GenerationSpecification(element: V1_GenerationSpecification): T; visit_SectionIndex(element: V1_SectionIndex): T; } export abstract class V1_PackageableElement implements Hashable { package!: string; name!: string; parentSection?: string; get path(): string { return `${this.package}${ELEMENT_PATH_DELIMITER}${this.name}`; } get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.PACKAGEABLE_ELEMENT, this.path]); } abstract accept_PackageableElementVisitor<T>( visitor: V1_PackageableElementVisitor<T>, ): T; } export enum V1_PackageableElementPointerType { STORE = 'STORE', MAPPING = 'MAPPING', FILE_GENERATION = 'FILE_GENERATION', SERVICE = 'SERVICE', } export class V1_PackageableElementPointer implements Hashable { type!: V1_PackageableElementPointerType; path!: string; constructor(type: V1_PackageableElementPointerType, path: string) { this.type = type; this.path = path; } get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.PACKAGEABLE_ELEMENT_POINTER, this.type, this.path, ]); } }
nayanika2/legend-studio
packages/legend-studio/src/components/shared/TypeTree.tsx
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { useState, useEffect } from 'react'; import { isNonNullable, IllegalStateError, assertType, addUniqueEntry, printObject, } from '@finos/legend-studio-shared'; import { FaChevronDown, FaChevronRight } from 'react-icons/fa'; import type { TreeNodeContainerProps, TreeData, } from '@finos/legend-studio-components'; import { clsx, TreeView } from '@finos/legend-studio-components'; import { useDrag } from 'react-dnd'; import { TypeDragSource, CORE_DND_TYPE } from '../../stores/shared/DnDUtil'; import { EnumValueIcon, getClassPropertyIcon } from './Icon'; import type { TypeTreeNodeData } from '../../stores/shared/TreeUtil'; import { DEFAULT_SOURCE_PARAMETER_NAME } from '../../models/MetaModelConst'; import type { Type } from '../../models/metamodels/pure/model/packageableElements/domain/Type'; import { Enumeration } from '../../models/metamodels/pure/model/packageableElements/domain/Enumeration'; import type { Enum } from '../../models/metamodels/pure/model/packageableElements/domain/Enum'; import { Class, CLASS_PROPERTY_TYPE, getClassPropertyType, } from '../../models/metamodels/pure/model/packageableElements/domain/Class'; import type { AbstractProperty } from '../../models/metamodels/pure/model/packageableElements/domain/AbstractProperty'; const getEnumTypeTreeNodeData = ( _enum: Enum, parent: TypeTreeNodeData, ): TypeTreeNodeData => { // NOTE: Enum is not a type assertType( parent.type, Enumeration, 'type of parent node for enum node must be enumeration', ); return { id: `${parent.id}.${_enum.name}`, label: _enum.name, parent: parent.type, dndType: CORE_DND_TYPE.TYPE_TREE_ENUM, }; }; const getPropertyTypeTreeNodeData = ( property: AbstractProperty, parent: TypeTreeNodeData, ): TypeTreeNodeData => { assertType( parent.type, Class, 'type of parent node for class property node must be class', ); const nodeData: TypeTreeNodeData = { id: `${parent.id}.${property.name}`, label: property.name, type: property.genericType.value.rawType, parent: parent.type, dndType: CORE_DND_TYPE.TYPE_TREE_PRIMITIVE, property, }; switch (getClassPropertyType(property.genericType.value.rawType)) { case CLASS_PROPERTY_TYPE.CLASS: nodeData.childrenIds = property.genericType.value .getRawType(Class) .getAllProperties() .map((p) => `${nodeData.id}.${p.name}`); nodeData.dndType = CORE_DND_TYPE.TYPE_TREE_CLASS; break; case CLASS_PROPERTY_TYPE.ENUMERATION: nodeData.childrenIds = property.genericType.value .getRawType(Enumeration) .values.map((p) => `${nodeData.id}.${p.name}`); nodeData.dndType = CORE_DND_TYPE.TYPE_TREE_ENUMERATION; break; default: } return nodeData; }; const getTypeTreeData = (type: Type): TreeData<TypeTreeNodeData> => { const rootIds: string[] = []; const nodes = new Map<string, TypeTreeNodeData>(); if (type instanceof Class) { type .getAllProperties() .concat(type.getAllDerivedProperties()) .sort((a, b) => a.name.localeCompare(b.name)) .sort( (a, b) => (b instanceof Class ? 2 : b instanceof Enumeration ? 1 : 0) - (a instanceof Class ? 2 : a instanceof Enumeration ? 1 : 0), ) .forEach((property) => { const propertyTreeNodeData = getPropertyTypeTreeNodeData(property, { id: `$${DEFAULT_SOURCE_PARAMETER_NAME}`, label: '', parent: type, dndType: CORE_DND_TYPE.TYPE_TREE_CLASS, type: type, }); addUniqueEntry(rootIds, propertyTreeNodeData.id); nodes.set(propertyTreeNodeData.id, propertyTreeNodeData); }); } else if (type instanceof Enumeration) { type.values.forEach((enumValue) => { const propertyTreeNodeData = getEnumTypeTreeNodeData(enumValue, { id: `$${DEFAULT_SOURCE_PARAMETER_NAME}`, label: '', parent: type, dndType: CORE_DND_TYPE.TYPE_TREE_ENUMERATION, type: type, }); addUniqueEntry(rootIds, propertyTreeNodeData.id); nodes.set(propertyTreeNodeData.id, propertyTreeNodeData); }); } else { throw new IllegalStateError( `Can't use type tree with node type other than class and enumeration. Found:\n${printObject( type, )}`, ); } return { rootIds, nodes }; }; const TypeTreeNodeContainer: React.FC< TreeNodeContainerProps<TypeTreeNodeData, { selectedType?: Type }> > = (props) => { const { node, level, stepPaddingInRem, onNodeSelect, innerProps } = props; const { selectedType } = innerProps; const [, dragRef] = useDrag( () => ({ type: node.dndType, item: new TypeDragSource(node) }), [node], ); const isExpandable = Boolean(node.childrenIds?.length); const nodeTypeIcon = node.type ? ( getClassPropertyIcon(node.type) ) : ( <EnumValueIcon /> ); const nodeExpandIcon = isExpandable ? ( node.isOpen ? ( <FaChevronDown /> ) : ( <FaChevronRight /> ) ) : ( <div /> ); const selectNode = (): void => onNodeSelect?.(node); return ( <div className={clsx('tree-view__node__container', { 'type-tree__node__container--highlighted': node.type === selectedType, })} onClick={selectNode} ref={dragRef} style={{ paddingLeft: `${(level - 1) * (stepPaddingInRem ?? 1)}rem`, display: 'flex', }} > <div className="tree-view__node__icon type-tree__node__icon"> <div className="type-tree__expand-icon">{nodeExpandIcon}</div> <div className="type-tree__type-icon">{nodeTypeIcon}</div> </div> <div className="tree-view__node__label type-tree__node__label"> <button tabIndex={-1} title={`${node.id}`}> {node.label} </button> {Boolean(node.type) && ( <div className="type-tree__node__type"> <button className={clsx('type-tree__node__type__label', { 'type-tree__node__type__label--highlighted': node.type === selectedType, })} tabIndex={-1} title={node.type?.path ?? ''} > {node.type?.name ?? 'unknown'} </button> </div> )} </div> </div> ); }; export const TypeTree: React.FC<{ type: Type; selectedType?: Type; }> = (props) => { const { type, selectedType } = props; // NOTE: We only need to compute this once so we use lazy initial state syntax // See https://reactjs.org/docs/hooks-reference.html#lazy-initial-state const [treeData, setTreeData] = useState<TreeData<TypeTreeNodeData>>(() => getTypeTreeData(type), ); const onNodeSelect = (node: TypeTreeNodeData): void => { if (node.childrenIds?.length) { node.isOpen = !node.isOpen; if (node.type instanceof Class) { node.type .getAllProperties() .concat(node.type.getAllDerivedProperties()) .forEach((property) => { const propertyTreeNodeData = getPropertyTypeTreeNodeData( property, node, ); treeData.nodes.set(propertyTreeNodeData.id, propertyTreeNodeData); }); } else if (node.type instanceof Enumeration) { node.type.values.forEach((enumValue) => { const propertyTreeNodeData = getEnumTypeTreeNodeData(enumValue, node); treeData.nodes.set(propertyTreeNodeData.id, propertyTreeNodeData); }); } } setTreeData({ ...treeData }); }; const getChildNodes = (node: TypeTreeNodeData): TypeTreeNodeData[] => { if (!node.childrenIds || !node.type) { return []; } const childrenNodes = node.childrenIds .map((id) => treeData.nodes.get(id)) .filter(isNonNullable) // class comes first then enumeration then primitive .sort((a, b) => a.label.localeCompare(b.label)) .sort( (a, b) => (b.type instanceof Class ? 2 : b.type instanceof Enumeration ? 1 : 0) - (a.type instanceof Class ? 2 : a.type instanceof Enumeration ? 1 : 0), ); return childrenNodes; }; useEffect(() => { setTreeData(() => getTypeTreeData(type)); }, [type]); return ( <TreeView components={{ TreeNodeContainer: TypeTreeNodeContainer, }} treeData={treeData} onNodeSelect={onNodeSelect} getChildNodes={getChildNodes} innerProps={{ selectedType, }} /> ); };
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/model/packageableElements/mapping/MappingInclude.ts
<reponame>nayanika2/legend-studio<filename>packages/legend-studio/src/models/metamodels/pure/model/packageableElements/mapping/MappingInclude.ts /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { observable, action, makeObservable } from 'mobx'; import { hashArray, getNullableFirstElement, addUniqueEntry, } from '@finos/legend-studio-shared'; import { CORE_HASH_STRUCTURE } from '../../../../../MetaModelConst'; import type { PackageableElementReference } from '../../../model/packageableElements/PackageableElementReference'; import type { Mapping } from '../../../model/packageableElements/mapping/Mapping'; import type { SubstituteStore } from './SubstituteStore'; export class MappingInclude { owner: Mapping; included: PackageableElementReference<Mapping>; storeSubstitutions: SubstituteStore[] = []; constructor(owner: Mapping, included: PackageableElementReference<Mapping>) { makeObservable(this, { included: observable, storeSubstitutions: observable, addStoreSubstitution: action, }); this.owner = owner; this.included = included; } addStoreSubstitution(value: SubstituteStore): void { addUniqueEntry(this.storeSubstitutions, value); } get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.MAPPING_INCLUDE, this.included.valueForSerialization, getNullableFirstElement(this.storeSubstitutions)?.original .valueForSerialization ?? '', getNullableFirstElement(this.storeSubstitutions)?.substitute .valueForSerialization ?? '', ]); } }
nayanika2/legend-studio
packages/legend-studio-manual-tests/src/__tests__/roundtrip-grammar/RoundtripGrammar.test.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <reference types="jest-extended" /> // NOTE: mock these methods to make sure we rule out false positive. The grammar parser for any List type field, // will generate empty array, however, in Studio, we avoid that to lessen the size of the serialized graph // to save bandwidth, as such the best action is just to mock these methods so in the scope of this test, Studio // serializers return empty array for these fields just like the parser's jest.mock('@finos/legend-studio-shared', () => ({ ...jest.requireActual('@finos/legend-studio-shared'), /* eslint-disable @typescript-eslint/no-explicit-any */ serializeArray: ( values: any, itemSerializer: (val: any) => any, skipIfEmpty: boolean, ): any[] => Array.isArray(values) ? values.length ? values.map((value) => itemSerializer(value)) : [] : [], deserializeArray: ( values: any, itemDeserializer: (val: any) => any, skipIfEmpty: boolean, ): any[] => (Array.isArray(values) ? values.map(itemDeserializer) : []), /* eslint-enable @typescript-eslint/no-explicit-any */ })); import { resolve, basename } from 'path'; import fs from 'fs'; import axios from 'axios'; import type { V1_PackageableElement } from '@finos/legend-studio'; import { EntityChangeType, getTestEditorStore } from '@finos/legend-studio'; import type { PlainObject } from '@finos/legend-studio-shared'; const engineConfig = JSON.parse( fs.readFileSync(resolve(__dirname, '../../../engine-config.json'), { encoding: 'utf-8', }), ) as object; const ENGINE_SERVER_PORT = (engineConfig as any).server.connector // eslint-disable-line @typescript-eslint/no-explicit-any .port as number; const ENGINE_SERVER_URL = `http://localhost:${ENGINE_SERVER_PORT}/api`; const TEST_CASE_DIR = resolve(__dirname, 'cases'); const EXCLUDED_CASE_FILES: string[] = [ // TODO: remove these when we can properly handle relational mapping `mainTable` and `primaryKey` in transformers. // See https://github.com/finos/legend-studio/issues/295 // See https://github.com/finos/legend-studio/issues/294 'embedded-relational-mapping.pure', 'nested-embedded-relational-mapping.pure', 'relational-mapping-filter.pure', ]; const checkGrammarRoundtrip = async ( file: string, editorStore = getTestEditorStore(), ): Promise<void> => { // parse the grammar const grammarText = fs.readFileSync(file, { encoding: 'utf-8' }); const transformGrammarToJsonResult = await axios.post( `${ENGINE_SERVER_URL}/pure/v1/grammar/transformGrammarToJson`, { code: grammarText, }, {}, ); const entities = editorStore.graphState.graphManager.pureProtocolToEntities( JSON.stringify(transformGrammarToJsonResult.data.modelDataContext), ); await editorStore.graphState.initializeSystem(); await editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, entities, { TEMPORARY__keepSectionIndex: true }, ); const transformedEntities = editorStore.graphState.graph.allOwnElements.map( (element) => editorStore.graphState.graphManager.elementToEntity(element), ); // ensure that transformed entities have all fields ordered alphabetically expect( // received: transformed entity transformedEntities .map((entity) => entity.content) .map(editorStore.graphState.graphManager.pruneSourceInformation), ).toIncludeSameMembers( // expected: protocol JSON parsed from grammar text transformGrammarToJsonResult.data.modelDataContext.elements .map(editorStore.graphState.graphManager.pruneSourceInformation) .filter( (elementProtocol: PlainObject<V1_PackageableElement>) => elementProtocol._type !== 'sectionIndex', ), ); // check hash computation await editorStore.graphState.graph.precomputeHashes( editorStore.applicationStore.logger, ); const protocolHashesIndex = await editorStore.graphState.graphManager.buildHashesIndex(entities); editorStore.changeDetectionState.workspaceLatestRevisionState.setEntityHashesIndex( protocolHashesIndex, ); await editorStore.changeDetectionState.computeLocalChanges(true); // TODO: avoid listing section index as part of change detection for now expect( editorStore.changeDetectionState.workspaceLatestRevisionState.changes.filter( (change) => change.entityChangeType !== EntityChangeType.DELETE || change.oldPath !== '__internal__::SectionIndex', ).length, ).toBe(0); // compose grammar and compare that with original grammar text // NOTE: this is optional test as `grammar text <-> protocol` test should be covered // in engine already. // Here, we do it just so we might be able to detect problem in the grammar roundtrip in engine const transformJsonToGrammarResult = await axios.post( `${ENGINE_SERVER_URL}/pure/v1/grammar/transformJsonToGrammar`, { modelDataContext: { _type: 'data', elements: transformedEntities.map((entity) => entity.content), }, renderStyle: 'STANDARD', }, {}, ); expect(transformJsonToGrammarResult.data.code).toEqual(grammarText); }; const testNameFrom = (fileName: string): string => { const name = basename(fileName, '.pure').split('-').join(' '); return `${name[0].toUpperCase()}${name.substring(1, name.length)}`; }; const cases = fs .readdirSync(TEST_CASE_DIR) .filter((caseName) => !EXCLUDED_CASE_FILES.includes(caseName)) .map((caseName) => resolve(TEST_CASE_DIR, caseName)) .filter((filePath) => fs.statSync(filePath).isFile()) .map((filePath) => [testNameFrom(filePath), filePath]); describe('Protocol JSON parsed from grammar text roundtrip test', () => { test.each(cases)('%s', async (testName, filePath) => { await checkGrammarRoundtrip(filePath); }); });
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/model/packageableElements/store/relational/mapping/V1_EmbeddedRelationalPropertyMapping.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { CORE_HASH_STRUCTURE } from '../../../../../../../../MetaModelConst'; import { hashArray } from '@finos/legend-studio-shared'; import type { Hashable } from '@finos/legend-studio-shared'; import type { V1_RelationalClassMapping } from './V1_RelationalClassMapping'; import type { V1_PropertyMappingVisitor } from '../../../../../model/packageableElements/mapping/V1_PropertyMapping'; import { V1_PropertyMapping } from '../../../../../model/packageableElements/mapping/V1_PropertyMapping'; export class V1_EmbeddedRelationalPropertyMapping extends V1_PropertyMapping implements Hashable { id?: string; classMapping!: V1_RelationalClassMapping; accept_PropertyMappingVisitor<T>(visitor: V1_PropertyMappingVisitor<T>): T { return visitor.visit_EmbeddedRelationalPropertyMapping(this); } override get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.EMBEDDED_REALTIONAL_PROPERTY_MAPPING, super.hashCode, this.classMapping.class ?? '', hashArray(this.classMapping.primaryKey), // skip `root` since we disregard it in embedded property mappings hashArray(this.classMapping.propertyMappings), ]); } }
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/model/packageableElements/store/relational/model/Join.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { computed, observable, makeObservable } from 'mobx'; import type { Hashable, Pair } from '@finos/legend-studio-shared'; import { CORE_HASH_STRUCTURE } from '../../../../../../../MetaModelConst'; import { hashArray } from '@finos/legend-studio-shared'; import type { Operation, TableAlias, } from '../../../../../model/packageableElements/store/relational/model/RelationalOperationElement'; import type { Database } from '../../../../../model/packageableElements/store/relational/model/Database'; export const SELF_JOIN_TABLE_NAME = '{target}'; export const SELF_JOIN_SCHEMA_NAME = 'default'; export const SELF_JOIN_ALIAS_PREFIX = 't_'; export class Join implements Hashable { owner!: Database; name: string; /** * Target is used to show the direction of the join. Since cross table join is symmetrical in nature, * the direction is not required at all, whereas for self-join, the direction really matters */ target?: TableAlias; /** * This is an optimization for looking up tables/views involved in a join. * Normally, it has 2 pairs (A,B) and (B,A) */ aliases: Pair<TableAlias, TableAlias>[] = []; operation: Operation; constructor(name: string, operation: Operation) { makeObservable(this, { name: observable, target: observable, aliases: observable, operation: observable, hashCode: computed, }); this.name = name; this.operation = operation; } get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.DATABASE_JOIN, this.name, this.operation, ]); } }