text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { expect } from 'chai'; import { describe, it } from 'mocha'; import { expectJSON } from '../../__testUtils__/expectJSON'; import { parse } from '../../language/parser'; import { GraphQLSchema } from '../../type/schema'; import { GraphQLString } from '../../type/scalars'; import { GraphQLNonNull, GraphQLObjectType } from '../../type/definition'; import { buildSchema } from '../../utilities/buildASTSchema'; import type { ExecutionResult } from '../execute'; import { execute, executeSync } from '../execute'; const syncError = new Error('sync'); const syncNonNullError = new Error('syncNonNull'); const promiseError = new Error('promise'); const promiseNonNullError = new Error('promiseNonNull'); const throwingData = { sync() { throw syncError; }, syncNonNull() { throw syncNonNullError; }, promise() { return new Promise(() => { throw promiseError; }); }, promiseNonNull() { return new Promise(() => { throw promiseNonNullError; }); }, syncNest() { return throwingData; }, syncNonNullNest() { return throwingData; }, promiseNest() { return new Promise((resolve) => { resolve(throwingData); }); }, promiseNonNullNest() { return new Promise((resolve) => { resolve(throwingData); }); }, }; const nullingData = { sync() { return null; }, syncNonNull() { return null; }, promise() { return new Promise((resolve) => { resolve(null); }); }, promiseNonNull() { return new Promise((resolve) => { resolve(null); }); }, syncNest() { return nullingData; }, syncNonNullNest() { return nullingData; }, promiseNest() { return new Promise((resolve) => { resolve(nullingData); }); }, promiseNonNullNest() { return new Promise((resolve) => { resolve(nullingData); }); }, }; const schema = buildSchema(` type DataType { sync: String syncNonNull: String! promise: String promiseNonNull: String! syncNest: DataType syncNonNullNest: DataType! promiseNest: DataType promiseNonNullNest: DataType! } schema { query: DataType } `); function executeQuery( query: string, rootValue: unknown, ): ExecutionResult | Promise<ExecutionResult> { return execute({ schema, document: parse(query), rootValue }); } function patch(str: string): string { return str .replace(/\bsync\b/g, 'promise') .replace(/\bsyncNonNull\b/g, 'promiseNonNull'); } // avoids also doing any nests function patchData(data: ExecutionResult): ExecutionResult { return JSON.parse(patch(JSON.stringify(data))); } async function executeSyncAndAsync(query: string, rootValue: unknown) { const syncResult = executeSync({ schema, document: parse(query), rootValue }); const asyncResult = await execute({ schema, document: parse(patch(query)), rootValue, }); expectJSON(asyncResult).toDeepEqual(patchData(syncResult)); return syncResult; } describe('Execute: handles non-nullable types', () => { describe('nulls a nullable field', () => { const query = ` { sync } `; it('that returns null', async () => { const result = await executeSyncAndAsync(query, nullingData); expect(result).to.deep.equal({ data: { sync: null }, }); }); it('that throws', async () => { const result = await executeSyncAndAsync(query, throwingData); expectJSON(result).toDeepEqual({ data: { sync: null }, errors: [ { message: syncError.message, path: ['sync'], locations: [{ line: 3, column: 9 }], }, ], }); }); }); describe('nulls a returned object that contains a non-nullable field', () => { const query = ` { syncNest { syncNonNull, } } `; it('that returns null', async () => { const result = await executeSyncAndAsync(query, nullingData); expectJSON(result).toDeepEqual({ data: { syncNest: null }, errors: [ { message: 'Cannot return null for non-nullable field DataType.syncNonNull.', path: ['syncNest', 'syncNonNull'], locations: [{ line: 4, column: 11 }], }, ], }); }); it('that throws', async () => { const result = await executeSyncAndAsync(query, throwingData); expectJSON(result).toDeepEqual({ data: { syncNest: null }, errors: [ { message: syncNonNullError.message, path: ['syncNest', 'syncNonNull'], locations: [{ line: 4, column: 11 }], }, ], }); }); }); describe('nulls a complex tree of nullable fields, each', () => { const query = ` { syncNest { sync promise syncNest { sync promise } promiseNest { sync promise } } promiseNest { sync promise syncNest { sync promise } promiseNest { sync promise } } } `; const data = { syncNest: { sync: null, promise: null, syncNest: { sync: null, promise: null }, promiseNest: { sync: null, promise: null }, }, promiseNest: { sync: null, promise: null, syncNest: { sync: null, promise: null }, promiseNest: { sync: null, promise: null }, }, }; it('that returns null', async () => { const result = await executeQuery(query, nullingData); expect(result).to.deep.equal({ data }); }); it('that throws', async () => { const result = await executeQuery(query, throwingData); expectJSON(result).toDeepEqual({ data, errors: [ { message: syncError.message, path: ['syncNest', 'sync'], locations: [{ line: 4, column: 11 }], }, { message: syncError.message, path: ['syncNest', 'syncNest', 'sync'], locations: [{ line: 6, column: 22 }], }, { message: syncError.message, path: ['syncNest', 'promiseNest', 'sync'], locations: [{ line: 7, column: 25 }], }, { message: syncError.message, path: ['promiseNest', 'sync'], locations: [{ line: 10, column: 11 }], }, { message: syncError.message, path: ['promiseNest', 'syncNest', 'sync'], locations: [{ line: 12, column: 22 }], }, { message: promiseError.message, path: ['syncNest', 'promise'], locations: [{ line: 5, column: 11 }], }, { message: promiseError.message, path: ['syncNest', 'syncNest', 'promise'], locations: [{ line: 6, column: 27 }], }, { message: syncError.message, path: ['promiseNest', 'promiseNest', 'sync'], locations: [{ line: 13, column: 25 }], }, { message: promiseError.message, path: ['syncNest', 'promiseNest', 'promise'], locations: [{ line: 7, column: 30 }], }, { message: promiseError.message, path: ['promiseNest', 'promise'], locations: [{ line: 11, column: 11 }], }, { message: promiseError.message, path: ['promiseNest', 'syncNest', 'promise'], locations: [{ line: 12, column: 27 }], }, { message: promiseError.message, path: ['promiseNest', 'promiseNest', 'promise'], locations: [{ line: 13, column: 30 }], }, ], }); }); }); describe('nulls the first nullable object after a field in a long chain of non-null fields', () => { const query = ` { syncNest { syncNonNullNest { promiseNonNullNest { syncNonNullNest { promiseNonNullNest { syncNonNull } } } } } promiseNest { syncNonNullNest { promiseNonNullNest { syncNonNullNest { promiseNonNullNest { syncNonNull } } } } } anotherNest: syncNest { syncNonNullNest { promiseNonNullNest { syncNonNullNest { promiseNonNullNest { promiseNonNull } } } } } anotherPromiseNest: promiseNest { syncNonNullNest { promiseNonNullNest { syncNonNullNest { promiseNonNullNest { promiseNonNull } } } } } } `; const data = { syncNest: null, promiseNest: null, anotherNest: null, anotherPromiseNest: null, }; it('that returns null', async () => { const result = await executeQuery(query, nullingData); expectJSON(result).toDeepEqual({ data, errors: [ { message: 'Cannot return null for non-nullable field DataType.syncNonNull.', path: [ 'syncNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNull', ], locations: [{ line: 8, column: 19 }], }, { message: 'Cannot return null for non-nullable field DataType.syncNonNull.', path: [ 'promiseNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNull', ], locations: [{ line: 19, column: 19 }], }, { message: 'Cannot return null for non-nullable field DataType.promiseNonNull.', path: [ 'anotherNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNullNest', 'promiseNonNullNest', 'promiseNonNull', ], locations: [{ line: 30, column: 19 }], }, { message: 'Cannot return null for non-nullable field DataType.promiseNonNull.', path: [ 'anotherPromiseNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNullNest', 'promiseNonNullNest', 'promiseNonNull', ], locations: [{ line: 41, column: 19 }], }, ], }); }); it('that throws', async () => { const result = await executeQuery(query, throwingData); expectJSON(result).toDeepEqual({ data, errors: [ { message: syncNonNullError.message, path: [ 'syncNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNull', ], locations: [{ line: 8, column: 19 }], }, { message: syncNonNullError.message, path: [ 'promiseNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNull', ], locations: [{ line: 19, column: 19 }], }, { message: promiseNonNullError.message, path: [ 'anotherNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNullNest', 'promiseNonNullNest', 'promiseNonNull', ], locations: [{ line: 30, column: 19 }], }, { message: promiseNonNullError.message, path: [ 'anotherPromiseNest', 'syncNonNullNest', 'promiseNonNullNest', 'syncNonNullNest', 'promiseNonNullNest', 'promiseNonNull', ], locations: [{ line: 41, column: 19 }], }, ], }); }); }); describe('nulls the top level if non-nullable field', () => { const query = ` { syncNonNull } `; it('that returns null', async () => { const result = await executeSyncAndAsync(query, nullingData); expectJSON(result).toDeepEqual({ data: null, errors: [ { message: 'Cannot return null for non-nullable field DataType.syncNonNull.', path: ['syncNonNull'], locations: [{ line: 3, column: 9 }], }, ], }); }); it('that throws', async () => { const result = await executeSyncAndAsync(query, throwingData); expectJSON(result).toDeepEqual({ data: null, errors: [ { message: syncNonNullError.message, path: ['syncNonNull'], locations: [{ line: 3, column: 9 }], }, ], }); }); }); describe('Handles non-null argument', () => { const schemaWithNonNullArg = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { withNonNullArg: { type: GraphQLString, args: { cannotBeNull: { type: new GraphQLNonNull(GraphQLString), }, }, resolve: (_, args) => 'Passed: ' + String(args.cannotBeNull), }, }, }), }); it('succeeds when passed non-null literal value', () => { const result = executeSync({ schema: schemaWithNonNullArg, document: parse(` query { withNonNullArg (cannotBeNull: "literal value") } `), }); expect(result).to.deep.equal({ data: { withNonNullArg: 'Passed: literal value', }, }); }); it('succeeds when passed non-null variable value', () => { const result = executeSync({ schema: schemaWithNonNullArg, document: parse(` query ($testVar: String!) { withNonNullArg (cannotBeNull: $testVar) } `), variableValues: { testVar: 'variable value', }, }); expect(result).to.deep.equal({ data: { withNonNullArg: 'Passed: variable value', }, }); }); it('succeeds when missing variable has default value', () => { const result = executeSync({ schema: schemaWithNonNullArg, document: parse(` query ($testVar: String = "default value") { withNonNullArg (cannotBeNull: $testVar) } `), variableValues: { // Intentionally missing variable }, }); expect(result).to.deep.equal({ data: { withNonNullArg: 'Passed: default value', }, }); }); it('field error when missing non-null arg', () => { // Note: validation should identify this issue first (missing args rule) // however execution should still protect against this. const result = executeSync({ schema: schemaWithNonNullArg, document: parse(` query { withNonNullArg } `), }); expectJSON(result).toDeepEqual({ data: { withNonNullArg: null, }, errors: [ { message: 'Argument "cannotBeNull" of required type "String!" was not provided.', locations: [{ line: 3, column: 13 }], path: ['withNonNullArg'], }, ], }); }); it('field error when non-null arg provided null', () => { // Note: validation should identify this issue first (values of correct // type rule) however execution should still protect against this. const result = executeSync({ schema: schemaWithNonNullArg, document: parse(` query { withNonNullArg(cannotBeNull: null) } `), }); expectJSON(result).toDeepEqual({ data: { withNonNullArg: null, }, errors: [ { message: 'Argument "cannotBeNull" of non-null type "String!" must not be null.', locations: [{ line: 3, column: 42 }], path: ['withNonNullArg'], }, ], }); }); it('field error when non-null arg not provided variable value', () => { // Note: validation should identify this issue first (variables in allowed // position rule) however execution should still protect against this. const result = executeSync({ schema: schemaWithNonNullArg, document: parse(` query ($testVar: String) { withNonNullArg(cannotBeNull: $testVar) } `), variableValues: { // Intentionally missing variable }, }); expectJSON(result).toDeepEqual({ data: { withNonNullArg: null, }, errors: [ { message: 'Argument "cannotBeNull" of required type "String!" was provided the variable "$testVar" which was not provided a runtime value.', locations: [{ line: 3, column: 42 }], path: ['withNonNullArg'], }, ], }); }); it('field error when non-null arg provided variable with explicit null value', () => { const result = executeSync({ schema: schemaWithNonNullArg, document: parse(` query ($testVar: String = "default value") { withNonNullArg (cannotBeNull: $testVar) } `), variableValues: { testVar: null, }, }); expectJSON(result).toDeepEqual({ data: { withNonNullArg: null, }, errors: [ { message: 'Argument "cannotBeNull" of non-null type "String!" must not be null.', locations: [{ line: 3, column: 43 }], path: ['withNonNullArg'], }, ], }); }); }); });
the_stack
import { CollectibleBase, CollectionBase, CollectionWithSets, Country, DEFAULT_LANG, DirectusApplication, DirectusCollectibleTemplate, DirectusCollectibleTemplateTranslation, DirectusCollection, DirectusCollectionTranslation, DirectusCountry, DirectusCountryTranslation, DirectusFile, DirectusHomepage, DirectusLanguageTemplate, DirectusPackTemplate, DirectusPackTemplateTranslation, DirectusRarity, DirectusRarityTranslation, DirectusSet, DirectusSetTranslation, DirectusTranslation, HomepageBase, PackBase, PackStatus, PackType, SetBase, SetWithCollection, SortDirection, } from '@algomart/schemas' import { CMSCacheApplicationModel, CMSCacheCollectibleTemplateModel, CMSCacheCollectionModel, CMSCacheHomepageModel, CMSCacheLanguageModel, CMSCachePackTemplateModel, CMSCacheSetModel, } from '@algomart/shared/models' import { invariant, isAfterNow, isNowBetweenDates, isStringArray, } from '@algomart/shared/utils' import { URL } from 'node:url' import Objection, { QueryBuilder, Transaction } from 'objection' import pino from 'pino' export interface ItemsResponse<T> { data: T[] meta?: { filter_count?: number total_count?: number } } export interface ItemByIdResponse<T> { data: T } export enum ItemFilterType { lte = '_lte', gte = '_gte', gt = '_gt', lt = '_lt', eq = '_eq', in = '_in', nin = '_nin', } export type ItemFilter<T extends Objection.Model = Objection.Model> = { [key in ItemFilterType]?: | string | string[] | number | number[] | boolean | boolean[] | Date | Date[] | Objection.QueryBuilder<T> } export interface ItemFilters { [key: string]: ItemFilter } export interface ItemSort { field: string order: SortDirection } export interface ItemQuery { search?: string sort?: ItemSort[] filter?: ItemFilters limit?: number offset?: number page?: number deep?: ItemFilters totalCount?: boolean } function getDirectusTranslation<TItem extends DirectusTranslation>( translations: TItem[] & DirectusTranslation[], invariantLabel: string, language = DEFAULT_LANG ): TItem { invariant( typeof translations != 'number' && translations?.length > 0, `no translations found: ${invariantLabel}` ) const translation = translations.find( (translation) => translation.languages_code === language ) || translations[0] invariant( translation !== undefined && typeof translation !== 'number', invariantLabel ) return translation as TItem } // #endregion // #region Mappers export type GetFileURL = (file: DirectusFile) => string export function toHomepageBase( homepage: DirectusHomepage, getFileURL: GetFileURL, language = DEFAULT_LANG ): HomepageBase { return { featuredPackTemplateId: typeof homepage.featured_pack === 'string' ? homepage.featured_pack : homepage.featured_pack?.id, upcomingPackTemplateIds: (homepage.upcoming_packs ?? []).map( (pack) => toPackBase(pack, getFileURL, language).templateId ), notableCollectibleTemplateIds: (homepage.notable_collectibles ?? []).map( (collectible) => toCollectibleBase(collectible, getFileURL, language).templateId ), } } export function toSetBase(set: DirectusSet, language = DEFAULT_LANG): SetBase { const { id, slug, translations, nft_templates } = set const { name } = getDirectusTranslation<DirectusSetTranslation>( translations as DirectusSetTranslation[], `set ${id} has no translations`, language ) const collectibleTemplateIds = isStringArray(nft_templates) ? nft_templates : nft_templates.map((t) => t.id) return { id, slug, name, collectibleTemplateIds, } } export function toCollectionBase( collection: DirectusCollection, getFileURL: GetFileURL, language: string ): CollectionBase { const { id, slug, translations, reward_image, nft_templates, collection_image, } = collection const translation = getDirectusTranslation<DirectusCollectionTranslation>( translations as DirectusCollectionTranslation[], `collection ${id} has no translations`, language ) const collectibleTemplateIds = isStringArray(nft_templates) ? nft_templates : nft_templates.map((t) => t.id) const { name, description, metadata, reward_complete, reward_prompt } = translation return { id, slug, name, description: description ?? undefined, metadata: metadata ?? undefined, collectibleTemplateIds, image: getFileURL(collection_image), reward: reward_complete && reward_prompt && reward_image ? { complete: reward_complete, prompt: reward_prompt, image: getFileURL(reward_image), } : undefined, } } export function toSetWithCollection( set: DirectusSet, getFileURL: GetFileURL, language = DEFAULT_LANG ): SetWithCollection { const base = toSetBase(set, language) invariant(typeof set.collection !== 'string', 'collection must be an object') return { ...base, collection: toCollectionBase(set.collection, getFileURL, language), } } export function toCollectionWithSets( collection: DirectusCollection, getFileURL: GetFileURL, language = DEFAULT_LANG ): CollectionWithSets { const base = toCollectionBase(collection, getFileURL, language) invariant(!isStringArray(collection.sets), 'sets must be an array of objects') return { ...base, sets: collection.sets.map((set) => toSetBase(set, language)), } } export function toCollectibleBase( template: DirectusCollectibleTemplate, getFileURL: GetFileURL, language = DEFAULT_LANG ): CollectibleBase { const translation = getDirectusTranslation<DirectusCollectibleTemplateTranslation>( template.translations as DirectusCollectibleTemplateTranslation[], `collectible ${template.id} has no translations`, language ) const rarity = template.rarity as DirectusRarity const rarityTranslation = rarity ? getDirectusTranslation<DirectusRarityTranslation>( rarity?.translations as DirectusRarityTranslation[], 'expected rarity to include translations', language ) : undefined let collectionId = typeof template.collection === 'string' ? template.collection : template.collection?.id if ( collectionId === undefined && template.set && typeof template.set !== 'string' ) { collectionId = typeof template.set.collection === 'string' ? template.set.collection : template.set.collection?.id } const setId = typeof template.set === 'string' ? template.set : template.set?.id return { body: translation.body ?? undefined, subtitle: translation.subtitle ?? undefined, title: translation.title, image: getFileURL(template.preview_image), previewVideo: template.preview_video ? getFileURL(template.preview_video) : undefined, previewAudio: template.preview_audio ? getFileURL(template.preview_audio) : undefined, assetFile: template.asset_file ? getFileURL(template.asset_file) : undefined, collectionId, setId, templateId: template.id, totalEditions: template.total_editions, uniqueCode: template.unique_code, rarity: rarity ? { code: rarity.code, color: rarity.color, name: rarityTranslation?.name, } : undefined, } } export function toStatus(template: DirectusPackTemplate) { if (template.type === PackType.Auction) { // Disable auction if either date parameter is not provided if (!template.released_at || !template.auction_until) { return PackStatus.Expired } const startDate = new Date(template.released_at) const endDate = new Date(template.auction_until) if (isAfterNow(startDate)) return PackStatus.Upcoming if (isNowBetweenDates(startDate, endDate)) return PackStatus.Active if (isAfterNow(endDate)) return PackStatus.Expired // If we get here, something was misconfigured return PackStatus.Expired } return PackStatus.Active } export function toCountryBase( country: DirectusCountry, language: string ): Country { const translation = getDirectusTranslation<DirectusCountryTranslation>( country.countries_code.translations as DirectusCountryTranslation[], `country ${country.countries_code} has no translations`, language ) return { code: country.countries_code.code, name: translation.title, } } export function toPackBase( template: DirectusPackTemplate, getFileURL: GetFileURL, language = DEFAULT_LANG ): PackBase { const translation = getDirectusTranslation<DirectusPackTemplateTranslation>( template.translations as DirectusPackTemplateTranslation[], `pack ${template.id} has no translations`, language ) return { // TODO: Need to load the additional images from Directus to populate additionalImages: [], allowBidExpiration: template.allow_bid_expiration, auctionUntil: template.auction_until ?? undefined, body: translation.body ?? undefined, collectibleTemplateIds: template.nft_templates.map( (nft_template) => nft_template.id ), collectibleTemplates: template.nft_templates.map((nft_template) => toCollectibleBase(nft_template, getFileURL, language) ), config: { collectibleDistribution: template.nft_distribution, collectibleOrder: template.nft_order, collectiblesPerPack: template.nfts_per_pack, }, image: getFileURL(template.pack_image), onePackPerCustomer: template.one_pack_per_customer, nftsPerPack: template.nfts_per_pack, price: template.price || 0, releasedAt: template.released_at ?? undefined, slug: template.slug, status: toStatus(template), subtitle: translation.subtitle ?? undefined, templateId: template.id, title: translation.title, type: template.type, } } // #endregion export interface CMSCacheAdapterOptions { cmsUrl: string gcpCdnUrl: string } export class CMSCacheAdapter { logger: pino.Logger<unknown> constructor( private readonly options: CMSCacheAdapterOptions, logger: pino.Logger<unknown> ) { this.logger = logger.child({ context: this.constructor.name }) } async findApplication(trx?: Transaction) { const queryResult = await CMSCacheApplicationModel.query(trx) .select('content') .first() const result: DirectusApplication = queryResult.content as unknown as DirectusApplication return result } async findAllCountries(language = DEFAULT_LANG, trx?: Transaction) { const application = await this.findApplication(trx) return application.countries.map((country) => { return toCountryBase(country, language) }) } async findAllPacksAuctionCompletion( startDate: Date, language = DEFAULT_LANG, trx?: Transaction ) { const queryResult = await CMSCachePackTemplateModel.query(trx) .where('type', PackType.Auction) .where('auctionUntil', '>', startDate) .select('content') .orderBy('releasedAt', 'desc') const data = queryResult.map( (result: CMSCachePackTemplateModel): DirectusPackTemplate => result.content as unknown as DirectusPackTemplate ) return data.map((template) => toPackBase(template, this.getFileURL.bind(this), language) ) } async findAllPacks( { language = DEFAULT_LANG, page = 1, pageSize = 10, filter = {}, sort = [ { field: 'releasedAt', order: SortDirection.Descending, }, ], }: { language?: string page?: number pageSize?: number filter?: ItemFilters sort?: ItemSort[] }, trx?: Transaction ) { const response = await this.findPackTemplates( { page, limit: pageSize, sort, filter, totalCount: true, }, trx ) invariant( typeof response.meta?.total_count === 'number', 'total_count missing from response' ) return { packs: response.data.map((template) => toPackBase(template, this.getFileURL.bind(this), language) ), total: response.meta.total_count, } } async findPacksByTemplateIds( templateIds: string[], language = DEFAULT_LANG, trx?: Transaction ) { const queryResult = await CMSCachePackTemplateModel.query(trx) .whereIn('id', templateIds) .select('content') const data = queryResult.map( (result: CMSCachePackTemplateModel): PackBase => { const packTemplate = result.content as unknown as DirectusPackTemplate return toPackBase(packTemplate, this.getFileURL.bind(this), language) } ) return data } async findPackBySlug( slug: string, language = DEFAULT_LANG, trx?: Transaction ) { const queryResult = await CMSCachePackTemplateModel.query(trx) .findOne('slug', slug) .select('content') const packTemplate = queryResult.content as unknown as DirectusPackTemplate return toPackBase(packTemplate, this.getFileURL.bind(this), language) } async findPackByTemplateId( templateId: string, language = DEFAULT_LANG, trx?: Transaction ) { const queryResult = await CMSCachePackTemplateModel.query(trx) .findOne('id', templateId) .select('content') const packTemplate = queryResult.content as unknown as DirectusPackTemplate return toPackBase(packTemplate, this.getFileURL.bind(this), language) } async findPacksPendingGeneration(language = DEFAULT_LANG, trx?: Transaction) { const queryResult = await CMSCachePackTemplateModel.query(trx) .leftJoin('Pack', 'Pack.templateId', 'CmsCachePackTemplates.id') .whereNull('Pack.templateId') .distinctOn('CmsCachePackTemplates.id') .select('content') const data = queryResult.map( (result: CMSCachePackTemplateModel): PackBase => { const packTemplate = result.content as unknown as DirectusPackTemplate return toPackBase(packTemplate, this.getFileURL.bind(this), language) } ) return data } async findAllCollectibles( language = DEFAULT_LANG, filter: ItemFilters = {}, limit = -1, trx?: Transaction ) { const response = await this.findCollectibleTemplates( { filter, limit, }, trx ) invariant( typeof response.meta?.filter_count === 'number', 'filter_count missing from response' ) return { collectibles: response.data.map((template) => toCollectibleBase(template, this.getFileURL.bind(this), language) ), total: response.meta.filter_count, } } async findCollectiblesByTemplateIds( templateIds: string[], language = DEFAULT_LANG, trx?: Transaction ): Promise<CollectibleBase[]> { const queryResult = await CMSCacheCollectibleTemplateModel.query(trx) .whereIn('id', templateIds) .select('content') const data = queryResult.map( (result: CMSCacheCollectibleTemplateModel): CollectibleBase => { const collectibleTemplate = result.content as unknown as DirectusCollectibleTemplate return toCollectibleBase( collectibleTemplate, this.getFileURL.bind(this), language ) } ) return data } async findCollectibleByTemplateId( templateId: string, language = DEFAULT_LANG, trx?: Transaction ) { const queryResult = await CMSCacheCollectibleTemplateModel.query(trx) .findOne('id', templateId) .select('content') const collectibleTemplate = queryResult.content as unknown as DirectusCollectibleTemplate return toCollectibleBase( collectibleTemplate, this.getFileURL.bind(this), language ) } async findAllCollections(language = DEFAULT_LANG, trx?: Transaction) { const response = await this.findCollections(undefined, trx) invariant( typeof response.meta?.filter_count === 'number', 'filter_count missing from response' ) return { collections: response.data.map((c) => toCollectionWithSets(c, this.getFileURL.bind(this), language) ), total: response.meta.filter_count, } } async findCollectionBySlug( slug: string, language = DEFAULT_LANG, trx?: Transaction ) { const result = await CMSCacheCollectionModel.query(trx).findOne( 'slug', slug ) if (result) { const collection: DirectusCollection = result.content as unknown as DirectusCollection return toCollectionWithSets( collection, this.getFileURL.bind(this), language ) } return null } async findSetBySlug( slug: string, language = DEFAULT_LANG, trx?: Transaction ) { const result = await CMSCacheSetModel.query(trx).findOne('slug', slug) if (result) { const set: DirectusSet = result.content as unknown as DirectusSet return toSetWithCollection(set, this.getFileURL.bind(this), language) } return null } async findHomepage(language: string = DEFAULT_LANG, trx?: Transaction) { const queryResult = await CMSCacheHomepageModel.query(trx) .select('content') .first() const result: DirectusHomepage = queryResult.content as unknown as DirectusHomepage return toHomepageBase(result, this.getFileURL.bind(this), language) } async getLanguages(trx?: Transaction) { const queryResult = await CMSCacheLanguageModel.query(trx) return queryResult .map((directusLanguageTemplate: DirectusLanguageTemplate) => ({ languages_code: directusLanguageTemplate.code, label: directusLanguageTemplate.name, sort: directusLanguageTemplate.sort, })) .sort(({ sort: a }, { sort: b }) => { if (a < b) { return -1 } if (a > b) { return 1 } return 0 }) } private async findPackTemplates(query: ItemQuery = {}, trx?: Transaction) { const queryBuild = CMSCachePackTemplateModel.query(trx) .orWhere('releasedAt', null) .orWhere('releasedAt', '<', new Date()) const { total, results } = await this.cacheQueryBuilder(query, queryBuild) const data = results.map( (result: CMSCachePackTemplateModel): DirectusPackTemplate => result.content as unknown as DirectusPackTemplate ) const result: ItemsResponse<DirectusPackTemplate> = { data, meta: { filter_count: data.length, total_count: total, }, } return result } private async findCollectibleTemplates( query: ItemQuery = {}, trx?: Transaction ) { const queryBuild = CMSCacheCollectibleTemplateModel.query(trx) const { total, results } = await this.cacheQueryBuilder(query, queryBuild) const data = results.map( (result: CMSCacheCollectibleTemplateModel): DirectusCollectibleTemplate => result.content as unknown as DirectusCollectibleTemplate ) const result: ItemsResponse<DirectusCollectibleTemplate> = { data, meta: { filter_count: data.length, total_count: total, }, } return result } private async findCollections(query: ItemQuery = {}, trx?: Transaction) { const queryBuild = CMSCacheCollectionModel.query(trx) const { total, results } = await this.cacheQueryBuilder(query, queryBuild) const data = results.map( (result: CMSCacheCollectionModel): DirectusCollection => result.content as unknown as DirectusCollection ) const result: ItemsResponse<DirectusCollection> = { data, meta: { filter_count: data.length, total_count: total, }, } return result } private cacheQueryBuilder( query: ItemQuery, queryBuild: Objection.QueryBuilder< | CMSCachePackTemplateModel | CMSCacheCollectibleTemplateModel | CMSCacheCollectionModel | CMSCacheSetModel, | CMSCachePackTemplateModel[] | CMSCacheCollectibleTemplateModel[] | CMSCacheCollectionModel[] | CMSCacheSetModel[] > ) { queryBuild = queryBuild.select('content') // For each column defined in the filter, loop through and convert to query if (query.filter) { for (const column of Object.keys(query.filter)) { const filters = query.filter[column] for (const filterKey of Object.keys(filters)) { const filter = filters[filterKey] switch (filterKey) { case ItemFilterType.in: queryBuild = column !== 'status' ? queryBuild.whereIn(column, filter) : queryBuild.where((builder) => { this.inStatusFilter(builder, filter) }) break case ItemFilterType.nin: queryBuild = queryBuild.whereNotIn(column, filter) break case ItemFilterType.eq: queryBuild = queryBuild.where(column, filter) break case ItemFilterType.gt: queryBuild = column !== 'reserveMet' ? queryBuild.where((builder) => { builder.orWhere(column, null).orWhere(column, '>', filter) }) : queryBuild.where((builder) => this.gtReserveMetWhere(builder) ) break case ItemFilterType.lt: queryBuild = queryBuild.where((builder) => { builder.orWhere(column, null).orWhere(column, '<', filter) }) break case ItemFilterType.gte: queryBuild = queryBuild.where((builder) => { builder.orWhere(column, null).orWhere(column, '>=', filter) }) break case ItemFilterType.lte: queryBuild = queryBuild.where((builder) => { builder.orWhere(column, null).orWhere(column, '<=', filter) }) break default: break } } } } for (let i = 0; i < query.sort?.length; i++) { const sort = query.sort[i] queryBuild = queryBuild.orderBy(sort.field, sort.order) } const page = query.page - 1 || 0 const pageSize = query.limit != -1 ? query.limit || 10 : Number.MAX_SAFE_INTEGER return queryBuild.page(page, pageSize) } private inStatusFilter<M extends Objection.Model>( queryBuild: QueryBuilder<M>, statuses: PackStatus[] ) { return queryBuild.where((builder) => { builder .orWhereIn('type', [PackType.Free, PackType.Purchase, PackType.Redeem]) .orWhere((subBuilder) => this.auctionUpcomingWhere(subBuilder, statuses) ) .orWhere((subBuilder) => this.auctionActiveWhere(subBuilder, statuses)) .orWhere((subBuilder) => this.auctionExpiredWhere(subBuilder, statuses)) }) } private auctionUpcomingWhere<M extends Objection.Model>( builder: QueryBuilder<M>, statuses: PackStatus[] ) { return statuses.includes(PackStatus.Upcoming) ? builder.where('releasedAt', '>', new Date()) : builder } private auctionActiveWhere<M extends Objection.Model>( builder: QueryBuilder<M>, statuses: PackStatus[] ) { return statuses.includes(PackStatus.Active) ? builder .where('releasedAt', '<', new Date()) .where('auctionUntil', '>', new Date()) : builder } private auctionExpiredWhere<M extends Objection.Model>( builder: QueryBuilder<M>, statuses: PackStatus[] ) { return statuses.includes(PackStatus.Expired) ? builder.where('auctionUntil', '<', new Date()) : builder } private gtReserveMetWhere<M extends Objection.Model>( builder: QueryBuilder<M> ) { return builder .orWhereIn('type', [PackType.Free, PackType.Purchase, PackType.Redeem]) .orWhere((subBuilder) => { subBuilder .where('type', PackType.Auction) .withGraphFetched('pack.activeBid') .where('activeBid' > 'price') }) } private getFileURL(file: DirectusFile | null) { if (file === null) { return null } if (file.storage == 'gcp' && this.options.gcpCdnUrl !== undefined) { return new URL(`${this.options.gcpCdnUrl}/${file.filename_disk}`).href } return new URL(`/assets/${file.id}`, this.options.cmsUrl).href } }
the_stack
import fetch from "node-fetch"; import { HandlerDataResponse, ICookieMap, IExposeFragment, IFileResourceAsset, IFragment, IFragmentBFF, IFragmentContentResponse, IFragmentHandler } from "./types"; import { CONTENT_ENCODING_TYPES, FRAGMENT_RENDER_MODES } from "./enums"; import * as querystring from "querystring"; import { DEBUG_QUERY_NAME, DEFAULT_CONTENT_TIMEOUT, PREVIEW_PARTIAL_QUERY_NAME, RENDER_MODE_QUERY_NAME } from "./config"; import url from "url"; import path from "path"; import { container, TYPES } from "./base"; import { Logger } from "./logger"; import { decompress } from "iltorb"; // TODO: remove this import * as express from 'express'; import { HttpClient } from "./client"; import { ERROR_CODES, PuzzleError } from "./errors"; import { CookieVersionMatcher } from "./cookie-version-matcher"; import { AssetManager } from "./asset-manager"; const logger = container.get(TYPES.Logger) as Logger; const httpClient = container.get(TYPES.Client) as HttpClient; export class Fragment { name: string; constructor(config: IFragment) { this.name = config.name; } } export class FragmentBFF extends Fragment { config: IFragmentBFF; versionMatcher?: CookieVersionMatcher; private handler: { [version: string]: IFragmentHandler } = {}; constructor(config: IFragmentBFF) { super({ name: config.name }); this.config = config; if (this.config.versionMatcher) { this.versionMatcher = new CookieVersionMatcher(this.config.versionMatcher); } this.prepareHandlers(); } /** * Renders fragment: data -> content * @param {object} req * @param {string} version * @returns {Promise<HandlerDataResponse>} */ async render(req: express.Request, version: string, res: express.Response): Promise<HandlerDataResponse> { const handler = this.handler[version] || this.handler[this.config.version]; const clearedRequest = this.clearRequest(req); const clearedResponse = this.clearResponse(res); if (handler) { if (handler.data) { let dataResponse; try { dataResponse = await handler.data(clearedRequest, clearedResponse); } catch (e) { logger.error(`Failed to fetch data for fragment ${this.config.name}`, { url: req.url, query: req.query, params: req.params, headers: req.headers, error: e }); return { $status: 500 }; } if (dataResponse.data) { const renderedPartials = handler.content(dataResponse.data); delete dataResponse.data; return { ...renderedPartials, ...dataResponse }; } else { return dataResponse; } } else { throw new Error(`Failed to find data handler for fragment. Fragment: ${this.config.name}, Version: ${version || this.config.version}`); } } else { throw new Error(`Failed to find fragment version. Fragment: ${this.config.name}, Version: ${version || this.config.version}`); } } /** * Renders placeholder * @param {object} req * @param {string} version * @returns {string} */ placeholder(req: object, version?: string) { const fragmentVersion = (version && this.config.versions[version]) ? version : this.config.version; const handler = this.handler[fragmentVersion]; if (handler) { return handler.placeholder(); } else { throw new Error(`Failed to find fragment version. Fragment: ${this.config.name}, Version: ${version || this.config.version}`); } } /** * Renders error * @param {object} req * @param {string} version * @returns {string} */ errorPage(req: object, version?: string) { const fragmentVersion = (version && this.config.versions[version]) ? version : this.config.version; const handler = this.handler[fragmentVersion]; if (handler) { return handler.error(); } else { throw new Error(`Failed to find fragment version. Fragment: ${this.config.name}, Version: ${version || this.config.version}`); } } private clearResponse(res: express.Response) { return res && res.locals ? res.locals : {}; } /** * Purifies req.path, req.query from Puzzle elements. * @param req * @returns {*} */ private clearRequest(req: express.Request) { const clearedReq = Object.assign({}, req); if (req.query) { delete clearedReq.query[RENDER_MODE_QUERY_NAME]; delete clearedReq.query[PREVIEW_PARTIAL_QUERY_NAME]; delete clearedReq.query[DEBUG_QUERY_NAME]; } if (req.path) { clearedReq.path = req.path.replace(`/${this.name}`, ''); } return clearedReq; } /** * Check module type */ private checkModuleType(fragmentModule: IFragmentHandler | Function): IFragmentHandler { if (typeof fragmentModule === "function") return fragmentModule(container); return fragmentModule; } /** * Resolve handlers based on configuration */ private prepareHandlers() { Object.keys(this.config.versions).forEach(version => { const configurationHandler = this.config.versions[version].handler; if (configurationHandler) { this.handler[version] = configurationHandler; } else { const module = require(path.join(process.cwd(), this.config.folderPath || `/src/fragments/`, this.config.name, version)); this.handler[version] = this.checkModuleType(module); } }); } } export class FragmentStorefront extends Fragment { get attributes(): { [p: string]: string } { return this._attributes; } set attributes(value: { [p: string]: string }) { delete value.primary; delete value['client-async']; delete value['client-async-force']; delete value['on-demand']; delete value['critical-css']; delete value.name; delete value.from; delete value.primary; delete value.shouldwait; delete value.partial; this._attributes = value; } config: IExposeFragment | undefined; primary = false; shouldWait = false; asyncDecentralized = false; static = false; clientAsync = false; clientAsyncForce = false; criticalCss = false; onDemand = false; from: string; gatewayPath!: string; fragmentUrl: string | undefined; assetUrl: string | undefined; private _attributes: { [p: string]: string }; private versionMatcher?: CookieVersionMatcher; private cachedErrorPage: string | undefined; private gatewayName: string; constructor(name: string, from: string, attributes?: { [name: string]: string }) { super({ name }); this._attributes = attributes || {}; this.from = from; } /** * Updates fragment configuration * @param {IExposeFragment} config * @param {string} gatewayUrl * @param gatewayName * @param {string | undefined} assetUrl */ update(config: IExposeFragment, gatewayUrl: string, gatewayName: string, assetUrl?: string | undefined) { if (assetUrl) { this.assetUrl = url.resolve(assetUrl.endsWith('/') ? assetUrl : `${assetUrl}/`, this.name); } this.fragmentUrl = url.resolve(gatewayUrl.endsWith('/') ? gatewayUrl : `${gatewayUrl}/`, this.name); const hostname = url.parse(gatewayUrl).hostname; if (hostname) { this.gatewayPath = hostname; } this.gatewayName = gatewayName; this.config = config; if (this.config && this.config.versionMatcher) { this.versionMatcher = new CookieVersionMatcher(this.config.versionMatcher); } if (this.config && this.config.render.error && !this.cachedErrorPage) { this.getErrorPage(); } } detectVersion(cookie: ICookieMap, preCompile = false): string { if (!this.config) return '0'; const cookieKey = this.config.testCookie; const cookieVersion = cookie[cookieKey]; if (cookieVersion) { return cookieVersion; } if (!preCompile && this.versionMatcher) { const version = this.versionMatcher.match(cookie); if (version) return version; } return this.config.version; } /** * Returns fragment placeholder as promise, fetches from gateway * @returns {Promise<string>} */ async getPlaceholder(): Promise<string> { logger.info(`Trying to get placeholder of fragment: ${this.name}`); if (!this.config) { logger.error(`No config provided for fragment: ${this.name}`); return ''; } if (!this.config.render.placeholder) { logger.error('Placeholder is not enabled for fragment'); return ''; } return fetch(`${this.fragmentUrl}/placeholder`, { headers: { gateway: this.gatewayName } }) .then(res => res.text()) .then(html => { try{ const placeholderContent = JSON.parse(html); logger.info(`Received placeholder contents: ${placeholderContent} of fragment: ${this.name}`); return placeholderContent }catch(e) { logger.info(`Received placeholder contents of fragment: ${this.name} as string`); return html } }) .catch(err => { logger.error(`Failed to fetch placeholder for fragment: ${this.fragmentUrl}/placeholder`, { error: err }); return ''; }); } /** * Returns fragment error as promise, fetches from gateway * @returns { Promise<string> } */ async getErrorPage(): Promise<string> { logger.info(`Trying to get error page of fragment: ${this.name}`); if (!this.config || !this.config.render.error) { logger.warn('Error page is not enabled for fragment'); return ''; } if (this.cachedErrorPage) { return this.cachedErrorPage; } return fetch(`${this.fragmentUrl}/error`, { headers: { gateway: this.gatewayName } }) .then(res => res.json()) .then(html => { this.cachedErrorPage = html; return html; }) .catch(err => { logger.error(`Failed to fetch error page for fragment: ${this.fragmentUrl}/error`, { error: err }); return ''; }); } /** * Fetches fragment content as promise, fetches from gateway * Returns { * html: { * Partials * }, * status: gateway status response code * } * @param attribs * @param req * @returns {Promise<IFragmentContentResponse>} */ // @nrSegmentAsync("fragment.getContent", true) async getContent(attribs: any = {}, req?: express.Request): Promise<IFragmentContentResponse> { logger.info(`Trying to get contents of fragment: ${this.name}`); if (!this.config) { logger.error(`No config provided for fragment: ${this.name}`); return { status: 500, html: {}, headers: {}, cookies: {}, model: {} }; } let query = { ...attribs, __renderMode: FRAGMENT_RENDER_MODES.STREAM }; let parsedRequest; const requestConfiguration: any = { timeout: this.config.render.timeout || DEFAULT_CONTENT_TIMEOUT, }; if (req) { if (req.url) { parsedRequest = url.parse(req.url) as { pathname: string }; query = { ...query, ...req.query, }; } if (req.headers) { requestConfiguration.headers = req.headers; delete requestConfiguration.headers.host; requestConfiguration.headers['originalurl'] = req.url; requestConfiguration.headers['originalpath'] = req.path; } } requestConfiguration.headers = { ...requestConfiguration.headers, gateway: this.gatewayName } || { gateway: this.gatewayName }; delete query.from; delete query.name; delete query.partial; delete query.primary; delete query.shouldwait; const routeRequest = req && parsedRequest ? `${parsedRequest.pathname.replace('/' + this.name, '')}?${querystring.stringify(query)}` : `/?${querystring.stringify(query)}`; return httpClient.get(`${this.fragmentUrl}${routeRequest}`, this.name, { json: true, gzip: true, ...requestConfiguration }).then(res => { logger.info(`Received fragment contents of ${this.name} with status code ${res.response.statusCode}`); return { status: res.data.$status || res.response.statusCode, headers: res.data.$headers || {}, cookies: res.data.$cookies || {}, html: res.data, model: res.data.$model || {} }; }).catch(async (err) => { const puzzleError = new PuzzleError(ERROR_CODES.FAILED_TO_GET_FRAGMENT_CONTENT, this.name, `${this.fragmentUrl}${routeRequest}`); logger.error(puzzleError.toString(), { name: this.name, url: `${this.fragmentUrl}${routeRequest}`, error: err }); const errorPage = await this.getErrorPage(); return { status: errorPage ? 200 : 500, html: errorPage ? errorPage : {}, headers: {}, cookies: {}, model: {} }; }); } /** * Returns asset content * @param {string} name * @param targetVersion * @returns {Promise<string>} */ async getAsset(name: string, targetVersion: string) { logger.info(`Trying to get asset: ${name}`); if (!this.config) { logger.error(`No config provided for fragment: ${this.name}`); return null; } let fragmentVersion: { assets: IFileResourceAsset[] } = this.config; if (targetVersion !== this.config.version && this.config.passiveVersions && this.config.passiveVersions[targetVersion]) { fragmentVersion = this.config.passiveVersions[targetVersion]; } const asset = fragmentVersion.assets.find(asset => asset.name === name); if (!asset) { logger.error(`Asset not declared in fragments asset list: ${name}`); return null; } const link = (asset.link || `${this.fragmentUrl}/static/${asset.fileName}`) + `?__version=${targetVersion}`; return await AssetManager.getAsset(link, this.gatewayName); } /** * Returns asset path * @param {string} name * @returns {string} */ getAssetPath(name: string) { if (!this.config) { logger.error(`No config provided for fragment: ${this.name}`); return null; } const asset = this.config.assets.find(asset => asset.name === name); if (!asset) { logger.error(`Asset not declared in fragments asset list: ${name}`); return null; } return asset.link || `${this.assetUrl || this.fragmentUrl}/static/${asset.fileName}`; } }
the_stack
import Log from '../../../Utils/Logger'; class ExpGolomb { Tag: string data: Uint8Array bytesAvailable: number word: number bitsAvailable: number constructor(data: Uint8Array) { this.Tag = 'ExpGolomb'; this.data = data; // the number of bytes left to examine in this.data this.bytesAvailable = data.byteLength; // the current word being examined this.word = 0; // :uint // the number of bits left to examine in the current word this.bitsAvailable = 0; // :uint } // ():void loadWord(): void { const { data } = this; const { bytesAvailable } = this; const position = data.byteLength - bytesAvailable; const workingBytes = new Uint8Array(4); const availableBytes = Math.min(4, bytesAvailable); if(availableBytes === 0) { throw new Error('no bytes available'); } workingBytes.set(data.subarray(position, position + availableBytes)); this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed this.bitsAvailable = availableBytes * 8; this.bytesAvailable -= availableBytes; } // (count:int):void skipBits(count: number): void { let skipBytes; // :int if(this.bitsAvailable > count) { this.word <<= count; this.bitsAvailable -= count; } else { count -= this.bitsAvailable; skipBytes = count >> 3; count -= skipBytes >> 3; this.bytesAvailable -= skipBytes; this.loadWord(); this.word <<= count; this.bitsAvailable -= count; } } // (size:int):uint readBits(size: number): number { let bits = Math.min(this.bitsAvailable, size); // :uint const valu = this.word >>> (32 - bits); // :uint if(size > 32) { Log.error(this.Tag, 'Cannot read more than 32 bits at a time'); } this.bitsAvailable -= bits; if(this.bitsAvailable > 0) { this.word <<= bits; } else if(this.bytesAvailable > 0) { this.loadWord(); } bits = size - bits; if(bits > 0 && this.bitsAvailable) { return (valu << bits) | this.readBits(bits); } return valu; } // ():uint skipLZ(): number { let leadingZeroCount; // :uint for(leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) { if((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) { // the first bit of working word is 1 this.word <<= leadingZeroCount; this.bitsAvailable -= leadingZeroCount; return leadingZeroCount; } } // we exhausted word and still have not found a 1 this.loadWord(); return leadingZeroCount + this.skipLZ(); } // ():void skipUEG(): void { this.skipBits(1 + this.skipLZ()); } // ():void skipEG(): void { this.skipBits(1 + this.skipLZ()); } // ():uint readUEG(): number { const clz = this.skipLZ(); // :uint return this.readBits(clz + 1) - 1; } // ():int readEG(): number { const valu = this.readUEG(); // :int if(0x01 & valu) { // the number is odd if the low order bit is set return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2 } return -1 * (valu >>> 1); // divide by two then make it negative } // Some convenience functions // :Boolean readBoolean(): boolean { return this.readBits(1) === 1; } // ():int readUByte(): number { return this.readBits(8); } // ():int readUShort(): number { return this.readBits(16); } // ():int readUInt(): number { return this.readBits(32); } /** * Advance the ExpGolomb decoder past a scaling list. The scaling * list is optionally transmitted as part of a sequence parameter * set and is not relevant to transmuxing. * @param count {number} the number of entries in this scaling list * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1 */ skipScalingList(count: number): void { let lastScale = 8; let nextScale = 8; let j; let deltaScale; for(j = 0; j < count; j++) { if(nextScale !== 0) { deltaScale = this.readEG(); nextScale = (lastScale + deltaScale + 256) % 256; } lastScale = nextScale === 0 ? lastScale : nextScale; } } /** * Read a sequence parameter set and return some interesting video * properties. A sequence parameter set is the H264 metadata that * describes the properties of upcoming video frames. * @param data {Uint8Array} the bytes of a sequence parameter set * @return {object} an object with configuration parsed from the * sequence parameter set, including the dimensions of the * associated video frames. */ readSPS() { let frameCropLeftOffset = 0; let frameCropRightOffset = 0; let frameCropTopOffset = 0; let frameCropBottomOffset = 0; let numRefFramesInPicOrderCntCycle; let scalingListCount; let i; const readUByte = this.readUByte.bind(this); const readBits = this.readBits.bind(this); const readUEG = this.readUEG.bind(this); const readBoolean = this.readBoolean.bind(this); const skipBits = this.skipBits.bind(this); const skipEG = this.skipEG.bind(this); const skipUEG = this.skipUEG.bind(this); const skipScalingList = this.skipScalingList.bind(this); readUByte(); const profileIdc = readUByte(); // profile_idc const profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5) skipBits(3); // reserved_zero_3bits u(3), const levelIdc = readUByte(); // level_idc u(8) skipUEG(); // seq_parameter_set_id // some profiles have more optional data we don't need if( profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128 ) { const chromaFormatIdc = readUEG(); if(chromaFormatIdc === 3) { skipBits(1); } // separate_colour_plane_flag skipUEG(); // bit_depth_luma_minus8 skipUEG(); // bit_depth_chroma_minus8 skipBits(1); // qpprime_y_zero_transform_bypass_flag if(readBoolean()) { // seq_scaling_matrix_present_flag scalingListCount = chromaFormatIdc !== 3 ? 8 : 12; for(i = 0; i < scalingListCount; i++) { if(readBoolean()) { // seq_scaling_list_present_flag[ i ] if(i < 6) { skipScalingList(16); } else { skipScalingList(64); } } } } } skipUEG(); // log2_max_frame_num_minus4 const picOrderCntType = readUEG(); if(picOrderCntType === 0) { readUEG(); // log2_max_pic_order_cnt_lsb_minus4 } else if(picOrderCntType === 1) { skipBits(1); // delta_pic_order_always_zero_flag skipEG(); // offset_for_non_ref_pic skipEG(); // offset_for_top_to_bottom_field numRefFramesInPicOrderCntCycle = readUEG(); for(i = 0; i < numRefFramesInPicOrderCntCycle; i++) { skipEG(); } // offset_for_ref_frame[ i ] } skipUEG(); // max_num_ref_frames skipBits(1); // gaps_in_frame_num_value_allowed_flag const picWidthInMbsMinus1 = readUEG(); const picHeightInMapUnitsMinus1 = readUEG(); const frameMbsOnlyFlag = readBits(1); if(frameMbsOnlyFlag === 0) { skipBits(1); } // mb_adaptive_frame_field_flag skipBits(1); // direct_8x8_inference_flag if(readBoolean()) { // frame_cropping_flag frameCropLeftOffset = readUEG(); frameCropRightOffset = readUEG(); frameCropTopOffset = readUEG(); frameCropBottomOffset = readUEG(); } let pixelRatio = [1, 1]; if(readBoolean()) { // vui_parameters_present_flag if(readBoolean()) { // aspect_ratio_info_present_flag const aspectRatioIdc = readUByte(); switch(aspectRatioIdc) { case 1: pixelRatio = [1, 1]; break; case 2: pixelRatio = [12, 11]; break; case 3: pixelRatio = [10, 11]; break; case 4: pixelRatio = [16, 11]; break; case 5: pixelRatio = [40, 33]; break; case 6: pixelRatio = [24, 11]; break; case 7: pixelRatio = [20, 11]; break; case 8: pixelRatio = [32, 11]; break; case 9: pixelRatio = [80, 33]; break; case 10: pixelRatio = [18, 11]; break; case 11: pixelRatio = [15, 11]; break; case 12: pixelRatio = [64, 33]; break; case 13: pixelRatio = [160, 99]; break; case 14: pixelRatio = [4, 3]; break; case 15: pixelRatio = [3, 2]; break; case 16: pixelRatio = [2, 1]; break; case 255: { pixelRatio = [ (readUByte() << 8) | readUByte(), (readUByte() << 8) | readUByte() ]; break; } default: pixelRatio = [1, 1]; break; } } } return { width: Math.ceil( (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2 ), height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset), pixelRatio }; } readSliceType(): number { // skip NALu type this.readUByte(); // discard first_mb_in_slice this.readUEG(); // return slice_type return this.readUEG(); } } export default ExpGolomb;
the_stack
import { assert } from "@fluidframework/common-utils"; import { randomId, TokenList, TagName } from "@fluid-example/flow-util-lib"; import { LazyLoadedDataObject, LazyLoadedDataObjectFactory } from "@fluidframework/data-object-base"; import { IFluidHandle } from "@fluidframework/core-interfaces"; import { createInsertSegmentOp, createRemoveRangeOp, IMergeTreeRemoveMsg, ISegment, LocalReference, Marker, MergeTreeDeltaType, PropertySet, ReferencePosition, ReferenceType, reservedMarkerIdKey, reservedRangeLabelsKey, reservedTileLabelsKey, TextSegment, } from "@fluidframework/merge-tree"; import { IFluidDataStoreContext, IFluidDataStoreFactory } from "@fluidframework/runtime-definitions"; import { SharedString, SharedStringSegment, SequenceMaintenanceEvent, SequenceDeltaEvent, } from "@fluidframework/sequence"; import { ISharedDirectory, SharedDirectory } from "@fluidframework/map"; import { IFluidHTMLOptions } from "@fluidframework/view-interfaces"; import { IEvent } from "@fluidframework/common-definitions"; import { clamp, emptyArray } from "../util"; import { IHTMLAttributes } from "../util/attr"; import { documentType } from "../package"; import { debug } from "./debug"; import { SegmentSpan } from "./segmentspan"; export const enum DocSegmentKind { text = "text", paragraph = "<p>", lineBreak = "<br>", beginTags = "<t>", inclusion = "<?>", endTags = "</>", // Special case for LocalReference to end of document. (See comments on 'endOfTextSegment'). endOfText = "eot", } const tilesAndRanges = new Set([DocSegmentKind.paragraph, DocSegmentKind.lineBreak, DocSegmentKind.beginTags, DocSegmentKind.inclusion]); const enum Workaround { checkpoint = "*" } export const enum DocTile { paragraph = DocSegmentKind.paragraph, checkpoint = Workaround.checkpoint, } export const getDocSegmentKind = (segment: ISegment): DocSegmentKind => { // Special case for LocalReference to end of document. (See comments on 'endOfTextSegment'). if (segment === endOfTextSegment) { return DocSegmentKind.endOfText; } if (TextSegment.is(segment)) { return DocSegmentKind.text; } else if (Marker.is(segment)) { const markerType = segment.refType; switch (markerType) { case ReferenceType.Tile: case ReferenceType.Tile | ReferenceType.NestBegin: const kind = (segment.hasRangeLabels() ? segment.getRangeLabels()[0] : segment.getTileLabels()[0]) as DocSegmentKind; assert(tilesAndRanges.has(kind), `Unknown tile/range label.`); return kind; default: assert(markerType === (ReferenceType.Tile | ReferenceType.NestEnd), "unexpected marker type"); // Ensure that 'nestEnd' range label matches the 'beginTags' range label (otherwise it // will not close the range.) assert(segment.getRangeLabels()[0] === DocSegmentKind.beginTags, `Unknown refType '${markerType}'.`); return DocSegmentKind.endTags; } } }; const empty = Object.freeze({}); export const getCss = (segment: ISegment): Readonly<{ style?: string, classList?: string }> => segment.properties || empty; // eslint-disable-next-line @typescript-eslint/no-unsafe-return export const getComponentOptions = (segment: ISegment): IFluidHTMLOptions | undefined => (segment.properties && segment.properties.componentOptions) || empty; type LeafAction = (position: number, segment: ISegment, startOffset: number, endOffset: number) => boolean; /** * Used by 'FlowDocument.visitRange'. Uses the otherwise unused 'accum' object to pass the * leaf action callback, allowing us to simplify the the callback signature and while (maybe) * avoiding unnecessary allocation to wrap the given 'callback'. */ const accumAsLeafAction = ( segment: ISegment, position: number, refSeq: number, clientId: number, startOffset: number, endOffset: number, accum?: LeafAction, ) => (accum)(position, segment, startOffset, endOffset); // TODO: We need the ability to create LocalReferences to the end of the document. Our // workaround creates a LocalReference with an 'undefined' segment that is never // inserted into the MergeTree. We then special case this segment in localRefToPosition, // addLocalRef, removeLocalRef, etc. // // Note, we use 'undefined' for our sentinel value to also workaround the case where // the user deletes the entire sequence. (The SlideOnRemove references end up pointing // to undefined segments.) // // See: https://github.com/microsoft/FluidFramework/issues/86 const endOfTextSegment = undefined as unknown as SharedStringSegment; export interface IFlowDocumentEvents extends IEvent { (event: "sequenceDelta", listener: (event: SequenceDeltaEvent, target: SharedString) => void); (event: "maintenance", listener: (event: SequenceMaintenanceEvent, target: SharedString) => void); } export class FlowDocument extends LazyLoadedDataObject<ISharedDirectory, IFlowDocumentEvents> { private static readonly factory = new LazyLoadedDataObjectFactory<FlowDocument>( documentType, FlowDocument, /* root: */ SharedDirectory.getFactory(), [SharedString.getFactory()]); public static getFactory(): IFluidDataStoreFactory { return FlowDocument.factory; } public static async create(parentContext: IFluidDataStoreContext, props?: any) { return FlowDocument.factory.create(parentContext, props); } private get sharedString() { return this.maybeSharedString; } public get length() { return this.sharedString.getLength(); } private static readonly paragraphProperties = Object.freeze({ [reservedTileLabelsKey]: [DocSegmentKind.paragraph, DocTile.checkpoint], tag: TagName.p }); private static readonly lineBreakProperties = Object.freeze({ [reservedTileLabelsKey]: [DocSegmentKind.lineBreak, DocTile.checkpoint] }); private static readonly inclusionProperties = Object.freeze({ [reservedTileLabelsKey]: [DocSegmentKind.inclusion, DocTile.checkpoint] }); private static readonly tagsProperties = Object.freeze({ [reservedTileLabelsKey]: [DocSegmentKind.inclusion, DocTile.checkpoint], [reservedRangeLabelsKey]: [DocSegmentKind.beginTags], }); private maybeSharedString?: SharedString; public create() { // For 'findTile(..)', we must enable tracking of left/rightmost tiles: Object.assign(this.runtime, { options: { ...(this.runtime.options || {}), blockUpdateMarkers: true } }); this.maybeSharedString = SharedString.create(this.runtime, "text"); this.root.set("text", this.maybeSharedString.handle); if (this.maybeSharedString !== undefined) { this.forwardEvent(this.maybeSharedString, "sequenceDelta", "maintenance"); } } public async load() { // For 'findTile(..)', we must enable tracking of left/rightmost tiles: Object.assign(this.runtime, { options: { ...(this.runtime.options || {}), blockUpdateMarkers: true } }); const handle = await this.root.wait<IFluidHandle<SharedString>>("text"); this.maybeSharedString = await handle.get(); if (this.maybeSharedString !== undefined) { this.forwardEvent(this.maybeSharedString, "sequenceDelta", "maintenance"); } } public async getComponentFromMarker(marker: Marker) { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return marker.properties.handle.get(); } public getSegmentAndOffset(position: number) { // Special case for LocalReference to end of document. (See comments on 'endOfTextSegment'). return position === this.length ? { segment: endOfTextSegment, offset: 0 } : this.sharedString.getContainingSegment(position); } public getPosition(segment: ISegment) { // Special case for LocalReference to end of document. (See comments on 'endOfTextSegment'). return segment === endOfTextSegment ? this.length : this.sharedString.getPosition(segment); } public addLocalRef(position: number) { // Special case for LocalReference to end of document. (See comments on 'endOfTextSegment'). if (position >= this.length) { return this.sharedString.createPositionReference(endOfTextSegment, 0, ReferenceType.Transient); } const { segment, offset } = this.getSegmentAndOffset(position); const localRef = this.sharedString.createPositionReference(segment, offset, ReferenceType.SlideOnRemove); return localRef; } public removeLocalRef(localRef: LocalReference) { const segment = localRef.getSegment(); // Special case for LocalReference to end of document. (See comments on 'endOfTextSegment'). if (segment !== endOfTextSegment) { this.sharedString.removeLocalReference(localRef); } } public localRefToPosition(localRef: LocalReference) { // Special case for LocalReference to end of document. (See comments on 'endOfTextSegment'). if (localRef.getSegment() === endOfTextSegment) { return this.length; } return localRef.toPosition(); } public insertText(position: number, text: string) { debug(`insertText(${position},"${text}")`); this.sharedString.insertText(position, text); } public replaceWithText(start: number, end: number, text: string) { debug(`replaceWithText(${start}, ${end}, "${text}")`); this.sharedString.replaceText(start, end, text); } public remove(start: number, end: number) { let _start = start; debug(`remove(${_start},${end})`); const ops: IMergeTreeRemoveMsg[] = []; this.visitRange((position: number, segment: ISegment) => { switch (getDocSegmentKind(segment)) { case DocSegmentKind.beginTags: { // Removing a start tag implicitly removes its matching end tag. // Check if the end tag is already included in the range being removed. const endTag = this.getEnd(segment as Marker); const endPos = this.getPosition(endTag); // Note: The end tag must appear after the position of the current start tag. console.assert(position < endPos); if (!(endPos < end)) { // If not, add the end tag removal to the group op. debug(` also remove end tag '</${endTag.properties.tag}>' at ${endPos}.`); ops.push(createRemoveRangeOp(endPos, endPos + 1)); } break; } case DocSegmentKind.endTags: { // The end tag should be preserved unless the start tag is also included in // the removed range. Check if range being removed includes the start tag. const startTag = this.getStart(segment as Marker); const startPos = this.getPosition(startTag); // Note: The start tag must appear before the position of the current end tag. console.assert(startPos < position); if (!(_start <= startPos)) { // If not, remove any positions up to, but excluding the current segment // and adjust the pending removal range to just after this marker. debug(` exclude end tag '</${segment.properties.tag}>' at ${position}.`); // If the preserved end tag is at the beginning of the removal range, no remove op // is necessary. Just skip over it. if (_start !== position) { ops.push(createRemoveRangeOp(_start, position)); } _start = position + 1; } break; } default: break; } return true; }, _start, end); // If there is a non-empty span remaining, generate its remove op now. if (_start !== end) { ops.push(createRemoveRangeOp(_start, end)); } // Perform removals in descending order, otherwise earlier deletions will shift the positions // of later ops. Because each effected interval is non-overlapping, a simple sort suffices. ops.sort((left, right) => right.pos1 - left.pos1); this.sharedString.groupOperation({ ops, type: MergeTreeDeltaType.GROUP, }); } public insertParagraph(position: number, tag?: TagName) { debug(`insertParagraph(${position})`); this.sharedString.insertMarker(position, ReferenceType.Tile, Object.freeze({ ...FlowDocument.paragraphProperties, tag })); } public insertLineBreak(position: number) { debug(`insertLineBreak(${position})`); this.sharedString.insertMarker(position, ReferenceType.Tile, FlowDocument.lineBreakProperties); } // eslint-disable-next-line @typescript-eslint/ban-types public insertComponent(position: number, handle: IFluidHandle, view: string, componentOptions: object, style?: string, classList?: string[]) { this.sharedString.insertMarker(position, ReferenceType.Tile, Object.freeze({ ...FlowDocument.inclusionProperties, componentOptions, handle, style, classList: classList && classList.join(" "), view, })); } public setFormat(position: number, tag: TagName) { const { start } = this.findParagraph(position); // If inside an existing paragraph marker, update it with the new formatting tag. if (start < this.length) { const pgSeg = this.getSegmentAndOffset(start).segment; if (getDocSegmentKind(pgSeg) === DocSegmentKind.paragraph) { pgSeg.properties.tag = tag; this.annotate(start, start + 1, { tag }); return; } } // Otherwise, insert a new paragraph marker. this.insertParagraph(start, tag); } public insertTags(tags: TagName[], start: number, end = start) { const ops = []; const id = randomId(); const endMarker = new Marker(ReferenceType.Tile | ReferenceType.NestEnd); endMarker.properties = Object.freeze({ ...FlowDocument.tagsProperties, [reservedMarkerIdKey]: `end-${id}` }); ops.push(createInsertSegmentOp(end, endMarker)); const beginMarker = new Marker(ReferenceType.Tile | ReferenceType.NestBegin); beginMarker.properties = Object.freeze({ ...FlowDocument.tagsProperties, tags, [reservedMarkerIdKey]: `begin-${id}` }); ops.push(createInsertSegmentOp(start, beginMarker)); // Note: Insert the endMarker prior to the beginMarker to avoid needing to compensate for the // change in positions. this.sharedString.groupOperation({ ops, type: MergeTreeDeltaType.GROUP, }); } public getTags(position: number): Readonly<Marker[]> { const tags = this.sharedString.getStackContext(position, [DocSegmentKind.beginTags])[DocSegmentKind.beginTags]; // eslint-disable-next-line @typescript-eslint/no-unsafe-return return (tags && tags.items) || emptyArray; } public getStart(marker: Marker) { return this.getOppositeMarker(marker, /* "end".length = */ 3, "begin"); } public getEnd(marker: Marker) { return this.getOppositeMarker(marker, /* "begin".length = */ 5, "end"); } public annotate(start: number, end: number, props: PropertySet) { this.sharedString.annotateRange(start, end, props); } public setCssStyle(start: number, end: number, style: string) { this.sharedString.annotateRange(start, end, { style }); } public addCssClass(start: number, end: number, ...classNames: string[]) { if (classNames.length > 0) { const newClasses = classNames.join(" "); this.updateCssClassList(start, end, (classList) => TokenList.set(classList, newClasses)); } } public removeCssClass(start: number, end: number, ...classNames: string[]) { this.updateCssClassList(start, end, (classList) => classNames.reduce( (updatedList, className) => TokenList.unset(updatedList, className), classList)); } public toggleCssClass(start: number, end: number, ...classNames: string[]) { // Pre-visit the range to see if any of the new styles have already been set. // If so, change the add to a removal by setting the map value to 'undefined'. const toAdd = classNames.slice(0); const toRemove = new Set<string>(); this.updateCssClassList(start, end, (classList) => { TokenList.computeToggle(classList, toAdd, toRemove); return classList; }); this.removeCssClass(start, end, ...toRemove); this.addCssClass(start, end, ...toAdd); } public setAttr(start: number, end: number, attr: IHTMLAttributes) { this.sharedString.annotateRange(start, end, { attr }); } public findTile(position: number, tileType: DocTile, preceding: boolean): { tile: ReferencePosition, pos: number } { return this.sharedString.findTile(position, tileType as unknown as string, preceding); } public findParagraph(position: number) { const maybeStart = this.findTile(position, DocTile.paragraph, /* preceding: */ true); const start = maybeStart ? maybeStart.pos : 0; const maybeEnd = this.findTile(position, DocTile.paragraph, /* preceding: */ false); const end = maybeEnd ? maybeEnd.pos + 1 : this.length; return { start, end }; } public visitRange(callback: LeafAction, start = 0, end = this.length) { const _end = clamp(0, end, this.length); const _start = clamp(0, start, end); // Early exit if passed an empty or invalid range (e.g., NaN). if (!(_start < _end)) { return; } // Note: We pass the leaf callback action as the accumulator, and then use the 'accumAsLeafAction' // actions to invoke the accum for each leaf. (Paranoid micro-optimization that attempts to // avoid allocation while simplifying the 'LeafAction' signature.) this.sharedString.walkSegments(accumAsLeafAction, _start, _end, callback); } public getText(start?: number, end?: number): string { return this.sharedString.getText(start, end); } public toString() { const s: string[] = []; this.visitRange((position, segment) => { let _segment = segment; const kind = getDocSegmentKind(_segment); switch (kind) { case DocSegmentKind.text: s.push((_segment as TextSegment).text); break; case DocSegmentKind.beginTags: for (const tag of _segment.properties.tags) { s.push(`<${tag}>`); } break; case DocSegmentKind.endTags: _segment = this.getStart(_segment as Marker); const tags = _segment.properties.tags.slice().reverse(); for (const tag of tags) { s.push(`</${tag}>`); } break; default: s.push(kind); } return true; }); return s.join(""); } private getOppositeMarker(marker: Marker, oldPrefixLength: number, newPrefix: string) { return this.sharedString.getMarkerFromId(`${newPrefix}${marker.getId().slice(oldPrefixLength)}`); } private updateCssClassList(start: number, end: number, callback: (classList: string) => string) { const updates: { span: SegmentSpan, classList: string }[] = []; this.visitRange((position, segment, startOffset, endOffset) => { const oldList = getCss(segment).classList; const newList = callback(oldList); if (newList !== oldList) { updates.push({ classList: newList, span: new SegmentSpan(position, segment, startOffset, endOffset), }); } return true; }, start, end); for (const { span, classList } of updates) { this.annotate(span.startPosition, span.endPosition, { classList }); } } }
the_stack
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; import { join as joinPaths, resolve } from 'path'; import { deleteFolderRecursive, JovoUserConfigFile, Preset, UserConfig } from '../src'; const testPath: string = resolve(joinPaths('test', 'tmpTestFolderUserConfig')); const configDirectory: string = joinPaths(testPath, '.jovo'); jest.mock('os', () => ({ ...Object.assign({}, jest.requireActual('os')), homedir() { return resolve(joinPaths('test', 'tmpTestFolderUserConfig')); }, })); afterEach(() => { jest.restoreAllMocks(); }); describe('new UserConfig()', () => { test('should create a new config', () => { jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValue({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [], }, }); const config: UserConfig = new UserConfig(); expect(config['config']).toBeDefined(); expect(config['config']).toHaveProperty('webhook'); expect(config['config'].webhook).toHaveProperty('uuid'); expect(config['config'].webhook.uuid).toMatch('test'); }); test("should create a new default preset if it doesn't exist", () => { const mockedSavePreset: jest.SpyInstance = jest .spyOn(UserConfig.prototype, 'savePreset') .mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValue({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [], }, }); new UserConfig(); expect(mockedSavePreset).toBeCalledTimes(1); expect(mockedSavePreset).toBeCalledWith<Preset[]>({ name: 'default', platforms: [], locales: ['en'], projectName: 'helloworld', language: 'typescript', }); }); }); describe('UserConfig.getPath()', () => { test('should return .jovo/config', () => { expect(UserConfig.getPath()).toMatch(joinPaths('.jovo', 'config')); }); }); describe('get()', () => { test('should return config', () => { jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValueOnce({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [], }, }); mkdirSync(configDirectory, { recursive: true }); writeFileSync(joinPaths(configDirectory, 'config'), JSON.stringify({ webhook: 'test' })); const config: UserConfig = new UserConfig(); const configContent: JovoUserConfigFile = config.get(); expect(configContent).toBeDefined(); expect(configContent).toHaveProperty('webhook'); expect(config['config'].webhook).toHaveProperty('uuid'); expect(config['config'].webhook.uuid).toMatch('test'); deleteFolderRecursive(testPath); }); test('should create a new config, if it cannot be found', () => { jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValueOnce({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [], }, }); const mockedCreate: jest.SpyInstance = jest // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore .spyOn(UserConfig.prototype, 'create') .mockReturnThis(); const config: UserConfig = new UserConfig(); config.get(); expect(mockedCreate).toHaveBeenCalled(); }); test('should throw an error if something went wrong while parsing the config', () => { jest.spyOn(UserConfig.prototype, 'get').mockReturnValueOnce({ webhook: { uuid: '', }, cli: { plugins: [], presets: [], }, }); jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); mkdirSync(configDirectory, { recursive: true }); writeFileSync(joinPaths(configDirectory, 'config'), '{'); const config: UserConfig = new UserConfig(); expect(config.get.bind(config)).toThrow(`Error while trying to parse ${UserConfig.getPath()}.`); deleteFolderRecursive(testPath); }); }); describe('save()', () => { beforeEach(() => { mkdirSync(testPath, { recursive: true }); }); afterEach(() => { deleteFolderRecursive(testPath); }); test('should create .jovo/ folder if it does not exist', () => { expect(existsSync(joinPaths(configDirectory))).toBeFalsy(); jest .spyOn(UserConfig.prototype, 'get') .mockReturnValue({ webhook: { uuid: '' }, cli: { plugins: [], presets: [] } }); jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); const config: UserConfig = new UserConfig(); config.save({ webhook: { uuid: '', }, cli: { plugins: [], presets: [], }, }); expect(existsSync(joinPaths(configDirectory))).toBeTruthy(); }); test('should save the new config', () => { jest .spyOn(UserConfig.prototype, 'get') .mockReturnValue({ webhook: { uuid: '' }, cli: { plugins: [], presets: [] } }); jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); const config: UserConfig = new UserConfig(); const configFile: JovoUserConfigFile = { webhook: { uuid: 'saved', }, cli: { plugins: [], presets: [], }, }; config.save(configFile); expect(existsSync(joinPaths(configDirectory, 'config'))).toBeTruthy(); expect(config['config']).toHaveProperty('webhook'); expect(config['config'].webhook).toHaveProperty('uuid'); expect(config['config'].webhook.uuid).toMatch('saved'); const savedConfigFile: JovoUserConfigFile = JSON.parse( readFileSync(joinPaths(configDirectory, 'config'), 'utf-8'), ); expect(savedConfigFile).toStrictEqual(config['config']); }); }); describe('getParameter()', () => { test('should return webhook uuid', () => { jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValue({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [], }, }); const config: UserConfig = new UserConfig(); expect(config.getParameter('webhook.uuid')).toBeDefined(); // expect(config.getParameter('webhook.uuid')).toMatch( // /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}/, // ); expect(config.getParameter('webhook.uuid')).toMatch('test'); }); test('should return undefined for a nonexisting property', () => { jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValue({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [], }, }); const config: UserConfig = new UserConfig(); expect(config.getParameter('invalid')).toBeUndefined(); }); }); describe('getPresets()', () => { test('should return presets', () => { jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValue({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [ { name: 'presetName', projectName: '', locales: [], platforms: [], language: 'typescript', }, ], }, }); const config: UserConfig = new UserConfig(); const presets: Preset[] = config.getPresets(); expect(presets).toBeDefined(); expect(presets).toHaveLength(1); expect(presets[0]).toHaveProperty('name'); expect(presets[0].name).toMatch('presetName'); }); }); describe('getWebhookUuid()', () => { test('should return webhook uuid', () => { jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValue({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [], }, }); const config: UserConfig = new UserConfig(); const webhookUuid: string = config.getWebhookUuid(); expect(webhookUuid).toBeDefined(); expect(webhookUuid).toMatch('test'); }); }); describe('getPreset()', () => { test('should return correct preset', () => { jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValue({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [ { name: 'presetName', projectName: '', locales: [], platforms: [], language: 'typescript', }, ], }, }); const config: UserConfig = new UserConfig(); const preset: Preset = config.getPreset('presetName'); expect(preset).toBeDefined(); }); test('should fail if preset does not exist', () => { jest.spyOn(UserConfig.prototype, 'savePreset').mockReturnThis(); jest.spyOn(UserConfig.prototype, 'get').mockReturnValue({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [], }, }); const config: UserConfig = new UserConfig(); expect(config.getPreset.bind(config, 'test')).toThrow('Could not find preset test.'); }); }); describe('savePreset()', () => { // TODO: Mock promptForOVerwrite and test for overwriting presets. test('should save preset', async () => { jest.spyOn(UserConfig.prototype, 'get').mockReturnValue({ webhook: { uuid: 'test', }, cli: { plugins: [], presets: [ { name: 'default', language: 'typescript', platforms: [], projectName: '', locales: [], }, ], }, }); jest.spyOn(UserConfig.prototype, 'save').mockReturnThis(); const config: UserConfig = new UserConfig(); const preset: Preset = { name: 'test', projectName: '', platforms: [], locales: [], language: 'typescript', }; await config.savePreset(preset); expect(config['config'].cli.presets).toHaveLength(2); expect(config['config'].cli.presets[0].name).toMatch('default'); expect(config['config'].cli.presets[1].name).toMatch('test'); }); });
the_stack
import * as t from "@babel/types"; import { IInferType, IIdentifier, ITypeExpression, ITypeIfStatement, IStringTypeLiteral, IStringType, INeverType, ITypeReference, ITypeCallExpression, INumberTypeLiteral, ITupleType, INumberType, IConditionalTypeExpression, ITemplateTypeLiteral, ITypeFile, ITypeFunctionDeclaration, IUnionType, IKeyOfType, IIndexType, IArrayType, IFunctionType, IMappedTypeExpression, ITypeForInStatement, IIntersectionType, ITypeObjectProperty, IAnyType, IReadonlyArray, IOperatorType, IReadonlyTuple, IRestType, IObjectTypeLiteral, ITypeArrowFunctionExpression, ITypeExpressionParam, IParamList, IBigIntType, IImportDeclaration, ITypeVariableDeclaration, IParenthesizedType, ICallSignature, IFunctionTypeParam, IConstructSignature, IContextType } from "../parser"; export function TSFile(ast: ITypeFile): t.File { const body = ast.body.map(each => { switch (each.kind) { case "TypeVariableDeclaration": return TSTypeAliasDeclaration(each); case "TypeFunctionDeclaration": return TSTypeAliasDeclarationWithParams(each); case "ImportDeclaration": return importDeclaration(each); default: assertNever(each); } }); const file = t.file(t.program(body)); return file; } export function importDeclaration(ast: IImportDeclaration): t.ImportDeclaration { const specifiers = ast.specifiers.map(each => t.importSpecifier(Identifier(each.imported), Identifier(each.imported))); return t.importDeclaration(specifiers, t.stringLiteral(ast.source)); } export type ITypeType = ITypeExpression | IRestType | ITypeArrowFunctionExpression; export function TSTypeAliasDeclarationWithParams(ast: ITypeFunctionDeclaration): t.TSTypeAliasDeclaration | t.ExportNamedDeclaration { const _type = TSTypeAliasDeclaration(ast); const type = t.isExportNamedDeclaration(_type) ? _type.declaration as t.TSTypeAliasDeclaration : _type; type.typeParameters = tsTypeParameterDeclaration(ast.declarator.initializer.params); return _type; } export function TSTypeAliasDeclaration(ast: ITypeFunctionDeclaration | ITypeVariableDeclaration): t.TSTypeAliasDeclaration | t.ExportNamedDeclaration { const declarator = ast.declarator; const declaraion = t.tsTypeAliasDeclaration(Identifier(declarator.name), null, TSType(declarator.initializer)); if (ast.export) { return t.exportNamedDeclaration(declaraion); } else { return declaraion; } } function tsConditionalType(ast: ITypeIfStatement): t.TSConditionalType { const { condition, consequent, alternate } = ast; const falseType = alternate.kind === "TypeIfStatement" ? tsConditionalType(alternate) : TSType(alternate.argument); const type = t.tsConditionalType(TSType(condition.checkType), TSType(condition.extendsType), TSType(consequent.argument), falseType); return type; } function tsConstrucSignature(ast: ITypeObjectProperty) { const name = ast.name as IConstructSignature; const params = tsFunctionParams(name.params); return t.tsConstructSignatureDeclaration(null, params, t.tsTypeAnnotation(TSType(ast.value))); } function tsCallSignature(ast: ITypeObjectProperty) { const name = ast.name as ICallSignature; const params = tsFunctionParams(name.params); return t.tsCallSignatureDeclaration(null, params, t.tsTypeAnnotation(TSType(ast.value))); } function tsPropertySignature(ast: ITypeObjectProperty) { const key = Identifier(ast.name as IIdentifier); const value = TSType(ast.value); if (/\s/g.test(key.name)) { key.name = `"${key.name}"`; } const prop = t.tsPropertySignature(key, t.tsTypeAnnotation(value)); return { ...prop, readonly: ast.readonly, optional: ast.optional } as t.TSPropertySignature; } function tsTypeLiteral(ast: IObjectTypeLiteral) { const props = ast.props.map(each => { switch (each.kind) { case "TypeObjectProperty": { switch (each.name.kind) { case "Identifier": return tsPropertySignature(each); case "StringLiteral": return tsPropertySignature({ ...each, name: { kind: "Identifier", name: each.name.value } }); case "CallSignature": return tsCallSignature(each); case "ConstructSignature": return tsConstrucSignature(each); } } case "TypeSpreadProperty": { if (each.param.kind === "TypeReference") { const type = TSType(each.param) as t.TSTypeReference; return type; } else if (each.param.kind === "TypeCallExpression") { const typeName = Identifier(each.param.callee.typeName); const params = each.param.params.map(each => { if (each.kind === "TypeReference") { return TSType(each); } throw new Error(`unkonwn param: ${JSON.stringify(each, null, 4)}`); }) const typeReference = t.tsTypeReference(typeName, t.tsTypeParameterInstantiation(params)); return typeReference; } } } }); const isSpread = ast.props.some(prop => prop.kind === "TypeSpreadProperty"); if (isSpread) { const tsTypeProps = props.map(each => { if (t.isTSPropertySignature(each)) { return t.tsTypeLiteral([each]); } else { return each; } }); const assigned = assignObjects(tsTypeProps as t.TSTypeLiteral[]); return assigned; } else { return t.tsTypeLiteral(props as t.TSPropertySignature[]); } } function assignObjects(objects: t.TSType[]) { const name = t.identifier(TypeLibFunction.Object.Assign); const params = t.tsTypeParameterInstantiation([t.tsTypeLiteral([]), t.tsTupleType(objects)]); const assigned = t.tsTypeReference(name, params); return assigned; } /** * eg. * `a` * `${a}` * `${a}${b}` * `${a}b${c}` * `${a}b${c}d` * `a${b}c${d}e` */ function templateLiteral(ast: ITemplateTypeLiteral): t.TemplateLiteral { const { items } = ast; const quasis: t.TemplateElement[] = []; const expressions: t.TSType[] = []; items.forEach((each, index) => { if (each.kind === "TemplateElement") { quasis.push(t.templateElement({ raw: each.value })); } else if (each.kind === "TemplateExpression") { if (quasis.length === expressions.length) { quasis.push(t.templateElement({ raw: "" })); } expressions.push(TSType(each.expression)); if (index === items.length - 1) { quasis.push(t.templateElement({ raw: "" }, true)); } } }); return t.templateLiteral(quasis, expressions); } function tsIndexedAccessType(head: ITypeExpression, members: ITypeExpression[]): t.TSIndexedAccessType { const indexType = TSType(members[members.length - 1]); if (members.length === 1) { const type = t.tsIndexedAccessType(TSType(head), indexType); return type; } else { const rest = members.slice(0, members.length - 1); const objectType = tsIndexedAccessType(head, rest); return t.tsIndexedAccessType(objectType, indexType); } } function tsIndexType(ast: IIndexType): t.TSIndexedAccessType { return tsIndexedAccessType(ast.head, ast.members); } function _tsArrayType(elementType: t.TSType, dimension: number) { if (dimension === 1) { return t.tsArrayType(elementType); } else { return t.tsArrayType(_tsArrayType(elementType, dimension - 1)); } } function tsArrayType(ast: IArrayType): t.TSArrayType { return _tsArrayType(TSType(ast.elementType), ast.dimension); } function tsFunctionType(ast: IFunctionType): t.TSFunctionType | t.TSConstructorType { const params = tsFunctionParams(ast.params); const typeParams = ast.typeParams ? tsTypeParameterDeclaration(ast.typeParams) : null; const args = [typeParams, params, t.tsTypeAnnotation(TSType(ast.returnType))] as const; const type = ast.isConstructor ? t.tsConstructorType(...args) : t.tsFunctionType(...args); return type; } function tsFunctionParams(params: IFunctionTypeParam[]) { return params.map(each => { const identifier = Identifier(each.name); const param = each.rest ? t.restElement(identifier) : identifier; param.typeAnnotation = t.tsTypeAnnotation(TSType(each.type)); if (each.optional) { param["optional"] = true } return param; }); } function tsTypeParameterDeclaration(params: IParamList): t.TSTypeParameterDeclaration { return t.tsTypeParameterDeclaration(params.map(param => tsTypeParameter(param))); } function tsTypeParameter(ast: ITypeExpressionParam): t.TSTypeParameter { const constraint = ast.constraint ? TSType(ast.constraint) : null; const _default = ast.default ? TSType(ast.default) : null; const tsParam = t.tSTypeParameter(constraint, _default, (ast as ITypeReference).typeName.name) return tsParam; } function resolveMappedTypeAsClause(as: ITypeObjectProperty, key: IIdentifier) { if (as.value.kind === "TypeReference" && as.value.typeName.name === key.name) { return null; } return TSType(as.value); } function tsMappedType(ast: ITypeForInStatement): t.TSMappedType { const { as, key, keys, value } = ast; const typeParam = t.tsTypeParameter(TSType(keys), null, key.name); const nameType = resolveMappedTypeAsClause(as, key); const type = t.tsMappedType(typeParam, TSType(value), nameType); return { ...type, readonly: as.readonly, optional: as.optional } as t.TSMappedType; } function tsTypeOperator(ast: IOperatorType, operator: string): t.TSTypeOperator { return { ...t.tsTypeOperator(TSType(ast.operand)), operator } /** TODO: use t.tsTypeOperator to create it? */ } type Kind<T extends ITypeType> = T["kind"]; type TypeInTS<T extends ITypeType> = /** */ Kind<T> extends Kind<IStringTypeLiteral> ? t.TSLiteralType : Kind<T> extends Kind<INumberTypeLiteral> ? t.TSLiteralType : Kind<T> extends Kind<ITemplateTypeLiteral> ? t.TemplateLiteral : Kind<T> extends Kind<IContextType> ? t.TSTupleType : /** */ Kind<T> extends Kind<IStringType> ? t.TSStringKeyword : Kind<T> extends Kind<INeverType> ? t.TSNeverKeyword : Kind<T> extends Kind<IAnyType> ? t.TSAnyKeyword : Kind<T> extends Kind<INumberType> ? t.TSNumberKeyword : Kind<T> extends Kind<IBigIntType> ? t.TSBigIntKeyword : Kind<T> extends Kind<IObjectTypeLiteral> ? t.TSTypeLiteral : Kind<T> extends Kind<ITupleType> ? t.TSTupleType : Kind<T> extends Kind<IArrayType> ? t.TSArrayType : /** */ Kind<T> extends Kind<ITypeReference> ? t.TSTypeReference : Kind<T> extends Kind<IInferType> ? t.TSInferType : Kind<T> extends Kind<IUnionType> ? t.TSUnionType : Kind<T> extends Kind<IIntersectionType> ? t.TSIntersectionType : Kind<T> extends Kind<IKeyOfType> ? t.TSTypeOperator : Kind<T> extends Kind<IReadonlyArray> ? t.TSTypeOperator : Kind<T> extends Kind<IReadonlyTuple> ? t.TSTypeOperator : Kind<T> extends Kind<IIndexType> ? t.TSIndexedAccessType : Kind<T> extends Kind<IFunctionType> ? t.TSFunctionType : Kind<T> extends Kind<IParenthesizedType> ? t.TSParenthesizedType : Kind<T> extends Kind<IConditionalTypeExpression> ? t.TSConditionalType : Kind<T> extends Kind<IMappedTypeExpression> ? t.TSMappedType : Kind<T> extends Kind<ITypeCallExpression> ? t.TSConditionalType : t.TSType; export function TSType(ast: ITypeType): TypeInTS<typeof ast> { switch (ast.kind) { /** */ case "StringTypeLiteral": return t.tsLiteralType({ ...t.stringLiteral(ast.value), extra: { raw: `"${ast.value}"`, rawValue: ast.value } } as t.StringLiteral); case "NumberTypeLiteral": return t.tsLiteralType(t.numericLiteral(ast.value)); case "BooleanTypeLiteral": return t.tsLiteralType(t.booleanLiteral(ast.value)); case "TemplateTypeLiteral": return { type: "TSLiteralType", literal: templateLiteral(ast) } as any as t.TSLiteralType; /** TODO: use t.tsLiteralType to create it */ case "ContextType": return t.tsTupleType([ t.tsLiteralType(t.stringLiteral(ast.body.context)), t.tsLiteralType(t.stringLiteral(ast.body.source)), ]); /** */ case "StringType": return t.tsStringKeyword(); case "NeverType": return t.tsNeverKeyword(); case "AnyType": return t.tsAnyKeyword(); case "ObjectType": return t.tsObjectKeyword(); case "VoidType": return t.tsVoidKeyword(); case "NumberType": return t.tsNumberKeyword(); case "BigIntType": return t.tsBigIntKeyword(); case "ObjectTypeLiteral": return tsTypeLiteral(ast); case "TupleType": return t.tsTupleType(ast.items.map(item => TSType(item))); case "ArrayType": return tsArrayType(ast); /** */ case "TypeReference": return t.tsTypeReference(Identifier(ast.typeName)); case "InferType": return t.tsInferType(t.tSTypeParameter(null, null, ast.typeName.name)); case "TypeArrowFunctionExpression": return TSType(ast.body); case "TypeCallExpression": { const type = TSType(ast.callee) as TypeInTS<typeof ast.callee>; const params = ast.params.map(param => TSType(param)); type.typeParameters = t.tsTypeParameterInstantiation(params); return type; } case "ConditionalTypeExpression": return tsConditionalType(ast.body); case "MappedTypeExpression": return tsMappedType(ast.body); case "UnionType": return t.tsParenthesizedType(t.tsUnionType(ast.types.map(each => TSType(each)))); case "IntersectionType": return t.tsParenthesizedType(t.tsIntersectionType(ast.types.map(each => TSType(each)))); case "KeyOfType": return tsTypeOperator(ast, "keyof"); case "ReadonlyArray": return tsTypeOperator(ast, "readonly"); case "ReadonlyTuple": return tsTypeOperator(ast, "readonly"); case "IndexType": return tsIndexType(ast); case "FunctionType": return tsFunctionType(ast); case "ParenthesizedType": return t.tsParenthesizedType(TSType(ast.param)); case "RestType": return t.tsRestType(TSType(ast.param)); default: return assertNever(ast); } } function Identifier(ast: IIdentifier): t.Identifier { return t.identifier(ast.name); } function assertNever(ast: never): never { throw new Error("Unexpected ast: " + JSON.stringify(ast, null, 4)); } const TypeLibFunction = { Object: { Assign: "object$assign", } }
the_stack
import Pluralize from 'pluralize' import { snakeCase, camelCase, pascalCase } from 'change-case' import { Config, FieldContract, FieldProperty, SerializedField, FieldHookFunction, AuthorizeFunction, SanitizationRules, DataPayload } from '@tensei/common' export class Field implements FieldContract { public showHideField = { /** * * If this is true, the field will be shown on the * index page * */ showOnIndex: true, /** * * If this is true, the field will be updatable. It will * show up on the update page * */ showOnUpdate: true, /** * * If this is true, the field will show up on the detail page */ showOnDetail: true, /** * * If this is true, the field will be shown on the creation * form */ showOnCreation: true } public graphqlType = '' public showHideFieldFromApi = { hideOnCreateApi: false, hideOnUpdateApi: false, hideOnDeleteApi: false, hideOnFetchApi: false } public component = { form: '', index: '', detail: '' } public showOnPanel: boolean = false public sidebar: boolean = false formComponent(component: string) { this.component.form = component return this } indexComponent(component: string) { this.component.index = component return this } detailComponent(component: string) { this.component.detail = component return this } public property: FieldProperty = { name: '', type: 'string', primary: false // nullable: true } public relatedProperty: FieldProperty = {} public tenseiConfig: Config | null = null public authorizeCallbacks: { authorizedToSee: AuthorizeFunction authorizedToCreate: AuthorizeFunction authorizedToUpdate: AuthorizeFunction authorizedToDelete: AuthorizeFunction } = { authorizedToSee: request => true, authorizedToCreate: request => true, authorizedToUpdate: request => true, authorizedToDelete: request => true } public onFieldUpdate: any = null public hooks: { beforeCreate: FieldHookFunction beforeUpdate: FieldHookFunction afterCreate: FieldHookFunction afterUpdate: FieldHookFunction onUpdate: FieldHookFunction } = { beforeCreate: payload => { return payload }, beforeUpdate: payload => { return payload }, onUpdate: payload => { return payload }, afterCreate: payload => { return payload }, afterUpdate: payload => { return payload } } public afterConfigSet() { if (this.tenseiConfig?.databaseConfig?.type === 'sqlite') { this.nullable() } } public onUpdate<T extends FieldContract>(this: T, onUpdate: () => any): T { this.property.onUpdate = onUpdate return this } public required<T extends FieldContract>(this: T): T { this.validationRules = [...this.validationRules, 'required'] return this } public requiredOnCreate<T extends FieldContract>(this: T): T { this.creationValidationRules = [...this.creationValidationRules, 'required'] return this } public requiredOnUpdate<T extends FieldContract>(this: T): T { this.updateValidationRules = [...this.updateValidationRules, 'required'] return this } /** * * The name of the field. Will be used to display table columns, * field labels etc */ public name: string /** * * Define validation rules to be used to validate * this field on forms */ public validationRules: Array<string> = [] /** * * Validation rules for fields that are in array format */ public arrayValidationRules: Array<string> = [] /** * * Rules for sanitizing data for a field */ public sanitizeRules: Array<SanitizationRules> = [] /** * * Define validation rules to be used to validate * this field on creation forms */ public creationValidationRules: Array<string> = [] /** * * Define validation rules to be used to validate * this field on update forms */ public updateValidationRules: Array<string> = [] /** * * This is a set of all html attributes to be passed * to this component * */ public attributes: {} = {} /** * * This value set to true will hide this field completely * from all query results. */ public isHidden: boolean = false public isRelationshipField: boolean = false /** * * The database field associated with this field. * By default, this will be the camel case * version of the name * */ public databaseField: string public camelCaseName: string public camelCaseNamePlural: string public pascalCaseName: string public snakeCaseName: string public snakeCaseNamePlural: string public capsDatabasefieldName: string /** * * The */ public helpText: string = '' public isNullable: boolean = true public isUnique: boolean = false /** * * Adds database sorting by this field. Will show up * on the index page, on the table headers. * */ public isSortable: boolean = false /** * Adds database filtering by this field. Will show up * on the index page, on the table headers. * * Will also expose filtering on the frontend for this * field. * */ public isFilterable: boolean = true public isSearchable: boolean = false /** * * Set the default value of this * field * */ public defaultValue: any = null /** * Instantiate a new field. Requires the name, * and optionally the corresponding database * field. This field if not provided will * default to the camel case version of * the name. */ public constructor(name: string, databaseField?: string) { this.name = name this.databaseField = databaseField || camelCase(this.name) this.property.name = this.databaseField this.relatedProperty.name = this.databaseField this.camelCaseName = camelCase(name) this.pascalCaseName = pascalCase(name) this.snakeCaseName = snakeCase(name) this.snakeCaseNamePlural = snakeCase(name) this.camelCaseNamePlural = Pluralize(this.camelCaseName) this.capsDatabasefieldName = this.databaseField.toUpperCase() } /** * * Show this field on the index page */ public showOnIndex() { this.showHideField = { ...this.showHideField, showOnIndex: true } return this } /** * * Show this field on the detail page */ public showOnDetail() { this.showHideField = { ...this.showHideField, showOnDetail: true } return this } /** * * Show this field on the creation page */ public showOnCreate() { this.showHideField = { ...this.showHideField, showOnCreation: true } return this } /** * * Show this field on the update page */ public showOnUpdate() { this.showHideField = { ...this.showHideField, showOnUpdate: true } return this } /** * * Hide this field on the index page */ public hideOnIndex() { this.showHideField = { ...this.showHideField, showOnIndex: false } return this } public type(type: string) { this.graphqlType = type return this } public serializer(serializeFn: (value: any) => any) { this.property.serializer = serializeFn return this } /** * * Hide this field from the detail page */ public hideOnDetail() { this.showHideField = { ...this.showHideField, showOnDetail: false } return this } /** * * Hide this field from the create form */ public hideOnCreate() { this.showHideField = { ...this.showHideField, showOnCreation: false } return this } /** * * Hide this field from the update form */ public hideOnUpdate() { this.showHideField = { ...this.showHideField, showOnUpdate: false } return this } /** * * Hide this field everywhere, except the index page */ public onlyOnIndex() { this.showHideField = { ...this.showHideField, showOnIndex: true, showOnUpdate: false, showOnCreation: false, showOnDetail: false } return this } /** * * Hide this field everuwhere, except the * create and update forms */ public onlyOnForms() { this.showHideField = { ...this.showHideField, showOnIndex: false, showOnUpdate: true, showOnCreation: true, showOnDetail: false } return this } /** * * Show this field only on the detail and, * index pages. hidden on create and * update forms. */ public exceptOnForms() { this.showHideField = { ...this.showHideField, showOnIndex: true, showOnUpdate: false, showOnCreation: false, showOnDetail: true } return this } public hideOnApi() { this.showHideFieldFromApi.hideOnCreateApi = true this.showHideFieldFromApi.hideOnFetchApi = true this.showHideFieldFromApi.hideOnDeleteApi = true this.showHideFieldFromApi.hideOnUpdateApi = true return this } public hideOnCreateApi() { this.showHideFieldFromApi.hideOnCreateApi = true return this } public hideOnUpdateApi() { this.showHideFieldFromApi.hideOnUpdateApi = true return this } public hideOnDeleteApi() { this.showHideFieldFromApi.hideOnDeleteApi = true return this } public hideOnFetchApi() { this.showHideFieldFromApi.hideOnFetchApi = true return this } /** * * Make this field sortable * */ public sortable<T extends FieldContract>(this: T): T { this.isSortable = true return this } /** * * Make this field filterable * */ public filterable<T extends FieldContract>(this: T): T { this.isFilterable = true return this } /** * * Turn off filtering for this field. * */ public notFilterable<T extends FieldContract>(this: T): T { this.isFilterable = false return this } /** * * Make this field searchable. will also index * this field in the database. * * This method optionally takes in the name of the index. * */ public searchable<T extends FieldContract>( this: T, index: string | boolean = true ): T { this.isSearchable = true this.property.index = index return this } public onCreate<T extends FieldContract>(this: T, onCreate: () => any): T { this.property.onCreate = onCreate return this } /** * * Make this field unique * */ public unique<T extends FieldContract>(this: T) { this.property.unique = true return this } /** * * Make this field unsigned * */ public unsigned<T extends FieldContract>(this: T) { this.property.unsigned = true return this } public shadow() { this.property.persist = false return this } /** * Make this field a primary field * */ public primary<T extends FieldContract>(this: T) { this.property.primary = true return this } /** * * Make this field signed * */ public signed<T extends FieldContract>(this: T) { this.property.unsigned = false return this } public notUnique<T extends FieldContract>(this: T): T { this.property.unique = false return this } public dockToSidebarOnForms() { this.sidebar = true return this } public removeFromSidebarOnForms() { this.sidebar = true return this } /** * * Make this field nullable * */ public notNullable<T extends FieldContract>(this: T): T { if (this.tenseiConfig?.orm?.config.get('type') === 'sqlite') { return this } this.isNullable = false this.property.nullable = false this.relatedProperty.nullable = false return this } public virtual<T extends FieldContract>( this: T, compute: (value: any) => any ): T { this.property.persist = false this.property.getter = true this.property.type = 'method' this.property.virtualGetter = compute this.hideOnCreateApi() this.hideOnUpdateApi() this.hideOnIndex() this.hideOnUpdate() this.hideOnCreate() this.nullable() return this } /** * * Make this field nullable * */ public nullable<T extends FieldContract>(this: T): T { this.isNullable = true this.property.nullable = true this.relatedProperty.nullable = true return this } public getValueFromPayload(payload: DataPayload, request: Express.Request) { return payload[this.databaseField] } /** * * Define the description. This would be a help text * that provides more information to the user * about this field on forms. */ public description<T extends FieldContract>(this: T, description: string): T { this.helpText = description return this } /** * * Set the default value for this field. * Will save to the database as default. * */ public default<T extends FieldContract>(this: T, value: any): T { this.property.default = value return this } /** * * Set the default value for this field. * Will show up on create forms as * default * */ public defaultFormValue<T extends FieldContract>(this: T, value: any): T { this.defaultValue = value return this } /** * * Set the default value for this field. * Will show up on create forms as * default * */ public defaultRaw<T extends FieldContract>(this: T, value: string): T { this.property.defaultRaw = value return this } /** * * Set html attributes for this component */ public htmlAttributes<T extends FieldContract>(this: T, attributes: {}): T { this.attributes = attributes return this } /** * * Set validation rules. These rules will be applied on both create * and update * * @param this */ public rules<T extends FieldContract>(this: T, ...rules: Array<string>): T { this.validationRules = Array.from( new Set([...this.validationRules, ...rules]) ) return this } /** * * Set validation rules. These rules will be applied on both create * and update * * @param this */ public arrayRules<T extends FieldContract>( this: T, ...rules: Array<string> ): T { this.arrayValidationRules = Array.from( new Set([...this.arrayValidationRules, ...rules]) ) return this } /** * Define a sanitization rule to be used when saving data for this field. * * @param this * @param sanitize string */ public sanitize<T extends FieldContract>( this: T, sanitizeRule: SanitizationRules ): T { this.sanitizeRule = sanitizeRule return this } /** * Set the validation rules to be used when * creating this field to the database */ public creationRules<T extends FieldContract>( this: T, ...rules: Array<string> ): T { this.creationValidationRules = Array.from( new Set([...this.creationValidationRules, ...rules]) ) return this } /** * Set the validation rules to be used when updating * this field */ public updateRules<T extends FieldContract>( this: T, ...rules: Array<string> ): T { this.updateValidationRules = Array.from( new Set([...this.updateValidationRules, ...rules]) ) return this } /** * Set this field to be a hidden field. It won't show up * in query results. */ public hidden<T extends FieldContract>(this: T): T { this.property.hidden = true this.hideOnApi() this.hideOnCreate() this.hideOnDetail() this.hideOnIndex() this.hideOnUpdate() return this } public canSee(authorizeFunction: AuthorizeFunction) { this.authorizeCallbacks['authorizedToSee'] = authorizeFunction return this } public canCreate(authorizeFunction: AuthorizeFunction) { this.authorizeCallbacks['authorizedToCreate'] = authorizeFunction return this } public canUpdate(authorizeFunction: AuthorizeFunction) { this.authorizeCallbacks['authorizedToUpdate'] = authorizeFunction return this } public canDelete(authorizeFunction: AuthorizeFunction) { this.authorizeCallbacks['authorizedToDelete'] = authorizeFunction return this } public isHiddenOnApi() { return ( Object.values(this.showHideFieldFromApi).filter(shown => shown).length === 0 || !!this.property.hidden ) } /** * * Serializes the field for data to be sent * to the frontend * */ public serialize(): SerializedField { return { ...this.showHideField, name: this.name, sidebar: this.sidebar, hidden: this.isHidden, isUnique: this.isUnique, component: this.component, description: this.helpText, isNullable: this.isNullable, isFilterable: this.isFilterable, isSortable: this.isSortable, attributes: this.attributes, rules: this.validationRules, showOnPanel: this.showOnPanel, inputName: this.databaseField, isSearchable: this.isSearchable, defaultValue: this.defaultValue, fieldName: this.constructor.name, snakeCaseName: this.snakeCaseName, databaseField: this.databaseField, camelCaseName: camelCase(this.name), pascalCaseName: this.pascalCaseName, updateRules: this.updateValidationRules, isVirtual: this.property.persist === false, creationRules: this.creationValidationRules, camelCaseNamePlural: this.camelCaseNamePlural, isRelationshipField: this.isRelationshipField, snakeCaseNamePlural: this.snakeCaseNamePlural, capsDatabasefieldName: this.capsDatabasefieldName } } } export default Field
the_stack
* @author Richard <richardo2016@gmail.com> * */ /// <reference path="Buffer.d.ts" /> /// <reference path="BufferedStream.d.ts" /> /// <reference path="Chain.d.ts" /> /// <reference path="Cipher.d.ts" /> /// <reference path="Condition.d.ts" /> /// <reference path="DbConnection.d.ts" /> /// <reference path="DgramSocket.d.ts" /> /// <reference path="Digest.d.ts" /> /// <reference path="Event.d.ts" /> /// <reference path="EventEmitter.d.ts" /> /// <reference path="EventInfo.d.ts" /> /// <reference path="Fiber.d.ts" /> /// <reference path="File.d.ts" /> /// <reference path="Handler.d.ts" /> /// <reference path="HandlerEx.d.ts" /> /// <reference path="HeapGraphEdge.d.ts" /> /// <reference path="HeapGraphNode.d.ts" /> /// <reference path="HeapSnapshot.d.ts" /> /// <reference path="HttpClient.d.ts" /> /// <reference path="HttpCollection.d.ts" /> /// <reference path="HttpCookie.d.ts" /> /// <reference path="HttpHandler.d.ts" /> /// <reference path="HttpMessage.d.ts" /> /// <reference path="HttpRequest.d.ts" /> /// <reference path="HttpResponse.d.ts" /> /// <reference path="HttpServer.d.ts" /> /// <reference path="HttpUploadData.d.ts" /> /// <reference path="HttpsServer.d.ts" /> /// <reference path="Image.d.ts" /> /// <reference path="Int64.d.ts" /> /// <reference path="LevelDB.d.ts" /> /// <reference path="Lock.d.ts" /> /// <reference path="LruCache.d.ts" /> /// <reference path="MSSQL.d.ts" /> /// <reference path="MemoryStream.d.ts" /> /// <reference path="Message.d.ts" /> /// <reference path="MongoCollection.d.ts" /> /// <reference path="MongoCursor.d.ts" /> /// <reference path="MongoDB.d.ts" /> /// <reference path="MongoID.d.ts" /> /// <reference path="MySQL.d.ts" /> /// <reference path="PKey.d.ts" /> /// <reference path="Redis.d.ts" /> /// <reference path="RedisHash.d.ts" /> /// <reference path="RedisList.d.ts" /> /// <reference path="RedisSet.d.ts" /> /// <reference path="RedisSortedSet.d.ts" /> /// <reference path="Routing.d.ts" /> /// <reference path="SQLite.d.ts" /> /// <reference path="SandBox.d.ts" /> /// <reference path="SeekableStream.d.ts" /> /// <reference path="Semaphore.d.ts" /> /// <reference path="Service.d.ts" /> /// <reference path="Smtp.d.ts" /> /// <reference path="Socket.d.ts" /> /// <reference path="SslHandler.d.ts" /> /// <reference path="SslServer.d.ts" /> /// <reference path="SslSocket.d.ts" /> /// <reference path="Stat.d.ts" /> /// <reference path="Stats.d.ts" /> /// <reference path="Stream.d.ts" /> /// <reference path="StringDecoder.d.ts" /> /// <reference path="SubProcess.d.ts" /> /// <reference path="TcpServer.d.ts" /> /// <reference path="Timer.d.ts" /> /// <reference path="UrlObject.d.ts" /> /// <reference path="WebSocket.d.ts" /> /// <reference path="WebSocketMessage.d.ts" /> /// <reference path="WebView.d.ts" /> /// <reference path="Worker.d.ts" /> /// <reference path="X509Cert.d.ts" /> /// <reference path="X509Crl.d.ts" /> /// <reference path="X509Req.d.ts" /> /// <reference path="XmlAttr.d.ts" /> /// <reference path="XmlCDATASection.d.ts" /> /// <reference path="XmlCharacterData.d.ts" /> /// <reference path="XmlComment.d.ts" /> /// <reference path="XmlDocument.d.ts" /> /// <reference path="XmlDocumentType.d.ts" /> /// <reference path="XmlElement.d.ts" /> /// <reference path="XmlNamedNodeMap.d.ts" /> /// <reference path="XmlNode.d.ts" /> /// <reference path="XmlNodeList.d.ts" /> /// <reference path="XmlProcessingInstruction.d.ts" /> /// <reference path="XmlText.d.ts" /> /// <reference path="ZipFile.d.ts" /> /// <reference path="ZmqSocket.d.ts" /> /// <reference path="object.d.ts" /> /** module Or Internal Object */ /** * @brief zlib 压缩解压模块 * @detail 使用方法:,```JavaScript,var zlib = require('zlib');,``` */ declare module "zlib" { module zlib { /** * * @brief deflate 压缩级别,设定不压缩 * * */ export const NO_COMPRESSION = 0; /** * * @brief deflate 压缩级别,设定最快压缩 * * */ export const BEST_SPEED = 1; /** * * @brief deflate 压缩级别,设定最高压缩 * * */ export const BEST_COMPRESSION = 9; /** * * @brief deflate 压缩级别,设定缺省设置 * * */ export const DEFAULT_COMPRESSION = -1; /** * * @brief 创建一个 deflate 流对象 * @param to 用于存储处理结果的流 * @return 返回封装过的流对象 * * */ export function createDeflate(to: Class_Stream): Class_Stream; /** * * @brief 创建一个 deflateRaw 流对象 * @param to 用于存储处理结果的流 * @return 返回封装过的流对象 * * */ export function createDeflateRaw(to: Class_Stream): Class_Stream; /** * * @brief 创建一个 gunzip 流对象 * @param to 用于存储处理结果的流 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * @return 返回封装过的流对象 * * */ export function createGunzip(to: Class_Stream, maxSize?: number/** = -1*/): Class_Stream; /** * * @brief 创建一个 gzip 流对象 * @param to 用于存储处理结果的流 * @return 返回封装过的流对象 * * */ export function createGzip(to: Class_Stream): Class_Stream; /** * * @brief 创建一个 inflate 流对象 * @param to 用于存储处理结果的流 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * @return 返回封装过的流对象 * * */ export function createInflate(to: Class_Stream, maxSize?: number/** = -1*/): Class_Stream; /** * * @brief 创建一个 inflateRaw 流对象 * @param to 用于存储处理结果的流 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * @return 返回封装过的流对象 * * */ export function createInflateRaw(to: Class_Stream, maxSize?: number/** = -1*/): Class_Stream; /** * * @brief 使用 deflate 算法压缩数据(zlib格式) * @param data 给定要压缩的数据 * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION * @return 返回压缩后的二进制数据 * * * @async */ export function deflate(data: Class_Buffer, level?: number/** = undefined*/): Class_Buffer; /** * * @brief 使用 deflate 算法压缩数据到流对象中(zlib格式) * @param data 给定要压缩的数据 * @param stm 指定存储压缩数据的流 * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION * * * @async */ export function deflateTo(data: Class_Buffer, stm: Class_Stream, level?: number/** = undefined*/): void; /** * * @brief 使用 deflate 算法压缩源流中的数据到流对象中(zlib格式) * @param src 给定要压缩的数据所在的流 * @param stm 指定存储压缩数据的流 * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION * * * @async */ export function deflateTo(src: Class_Stream, stm: Class_Stream, level?: number/** = undefined*/): void; /** * * @brief 解压缩 deflate 算法压缩的数据(zlib格式) * @param data 给定压缩后的数据 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * @return 返回解压缩后的二进制数据 * * * @async */ export function inflate(data: Class_Buffer, maxSize?: number/** = -1*/): Class_Buffer; /** * * @brief 解压缩 deflate 算法压缩的数据到流对象中(zlib格式) * @param data 给定要解压缩的数据 * @param stm 指定存储解压缩数据的流 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * * * @async */ export function inflateTo(data: Class_Buffer, stm: Class_Stream, maxSize?: number/** = -1*/): void; /** * * @brief 解压缩源流中 deflate 算法压缩的数据到流对象中(zlib格式) * @param src 给定要解压缩的数据所在的流 * @param stm 指定存储解压缩数据的流 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * * * @async */ export function inflateTo(src: Class_Stream, stm: Class_Stream, maxSize?: number/** = -1*/): void; /** * * @brief 使用 gzip 算法压缩数据 * @param data 给定要压缩的数据 * @return 返回压缩后的二进制数据 * * * @async */ export function gzip(data: Class_Buffer): Class_Buffer; /** * * @brief 使用 gzip 算法压缩数据到流对象中 * @param data 给定要压缩的数据 * @param stm 指定存储压缩数据的流 * * * @async */ export function gzipTo(data: Class_Buffer, stm: Class_Stream): void; /** * * @brief 使用 gzip 算法压缩源流中的数据到流对象中 * @param src 给定要压缩的数据所在的流 * @param stm 指定存储压缩数据的流 * * * @async */ export function gzipTo(src: Class_Stream, stm: Class_Stream): void; /** * * @brief 解压缩 gzip 算法压缩的数据 * @param data 给定压缩后的数据 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * @return 返回解压缩后的二进制数据 * * * @async */ export function gunzip(data: Class_Buffer, maxSize?: number/** = -1*/): Class_Buffer; /** * * @brief 解压缩 gzip 算法压缩的数据到流对象中 * @param data 给定要解压缩的数据 * @param stm 指定存储解压缩数据的流 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * * * @async */ export function gunzipTo(data: Class_Buffer, stm: Class_Stream, maxSize?: number/** = -1*/): void; /** * * @brief 解压缩源流中 gzip 算法压缩的数据到流对象中 * @param src 给定要解压缩的数据所在的流 * @param stm 指定存储解压缩数据的流 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * * * @async */ export function gunzipTo(src: Class_Stream, stm: Class_Stream, maxSize?: number/** = -1*/): void; /** * * @brief 使用 deflate 算法压缩数据(deflateRaw) * @param data 给定要压缩的数据 * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION * @return 返回压缩后的二进制数据 * * * @async */ export function deflateRaw(data: Class_Buffer, level?: number/** = undefined*/): Class_Buffer; /** * * @brief 使用 deflate 算法压缩数据到流对象中(deflateRaw) * @param data 给定要压缩的数据 * @param stm 指定存储压缩数据的流 * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION * * * @async */ export function deflateRawTo(data: Class_Buffer, stm: Class_Stream, level?: number/** = undefined*/): void; /** * * @brief 使用 deflate 算法压缩源流中的数据到流对象中(deflateRaw) * @param src 给定要压缩的数据所在的流 * @param stm 指定存储压缩数据的流 * @param level 指定压缩级别,缺省为 DEFAULT_COMPRESSION * * * @async */ export function deflateRawTo(src: Class_Stream, stm: Class_Stream, level?: number/** = undefined*/): void; /** * * @brief 解压缩 deflate 算法压缩的数据(inflateRaw) * @param data 给定压缩后的数据 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * @return 返回解压缩后的二进制数据 * * * @async */ export function inflateRaw(data: Class_Buffer, maxSize?: number/** = -1*/): Class_Buffer; /** * * @brief 解压缩 deflate 算法压缩的数据到流对象中(inflateRaw) * @param data 给定要解压缩的数据 * @param stm 指定存储解压缩数据的流 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * * * @async */ export function inflateRawTo(data: Class_Buffer, stm: Class_Stream, maxSize?: number/** = -1*/): void; /** * * @brief 解压缩源流中 deflate 算法压缩的数据到流对象中(inflateRaw) * @param src 给定要解压缩的数据所在的流 * @param stm 指定存储解压缩数据的流 * @param maxSize 指定解压缩尺寸限制,缺省为 -1,不限制 * * * @async */ export function inflateRawTo(src: Class_Stream, stm: Class_Stream, maxSize?: number/** = -1*/): void; } /** end of `module zlib` */ export = zlib } /** endof `module Or Internal Object` */
the_stack
import { Camera, FFMpegInput, MotionSensor, ScryptedDevice, ScryptedDeviceType, ScryptedInterface, ScryptedMimeTypes, VideoCamera, AudioSensor, Intercom, MediaStreamOptions, ObjectsDetected, VideoCameraConfiguration, OnOff } from '@scrypted/sdk' import { addSupportedType, bindCharacteristic, DummyDevice, HomeKitSession } from '../common' import { AudioStreamingCodec, AudioStreamingCodecType, AudioStreamingSamplerate, CameraController, CameraStreamingDelegate, CameraStreamingOptions, Characteristic, VideoCodecType, H264Level, H264Profile, PrepareStreamCallback, PrepareStreamRequest, PrepareStreamResponse, SRTPCryptoSuites, StartStreamRequest, StreamingRequest, StreamRequestCallback, StreamRequestTypes } from '../hap'; import { makeAccessory } from './common'; import sdk from '@scrypted/sdk'; import child_process from 'child_process'; import { ChildProcess } from 'child_process'; import dgram, { SocketType } from 'dgram'; import { once } from 'events'; import debounce from 'lodash/debounce'; import { CameraRecordingDelegate } from '../hap'; import { ffmpegLogInitialOutput } from '@scrypted/common/src/media-helpers'; import { RtpDemuxer } from '../rtp/rtp-demuxer'; import { HomeKitRtpSink, startRtpSink } from '../rtp/rtp-ffmpeg-input'; import { handleFragmentsRequests, iframeIntervalSeconds } from './camera/camera-recording'; import { createSnapshotHandler } from './camera/camera-snapshot'; import { evalRequest } from './camera/camera-transcode'; import { AudioRecordingCodec, AudioRecordingCodecType, AudioRecordingSamplerate, CameraRecordingOptions, RecordingManagement, OccupancySensor, CharacteristicEventTypes, DataStreamConnection, Service, WithUUID } from '../hap'; import { defaultObjectDetectionContactSensorTimeout } from '../camera-mixin'; import os from 'os'; const { log, mediaManager, deviceManager, systemManager } = sdk; async function getPort(socketType?: SocketType): Promise<{ socket: dgram.Socket, port: number }> { const socket = dgram.createSocket(socketType || 'udp4'); while (true) { const port = Math.round(10000 + Math.random() * 30000); socket.bind(port); await once(socket, 'listening'); return { socket, port }; } } const numberPrebufferSegments = 1; const v4Regex = /^[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}$/ const v4v6Regex = /^::ffff:[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}$/; addSupportedType({ type: ScryptedDeviceType.Camera, probe(device: DummyDevice) { return device.interfaces.includes(ScryptedInterface.VideoCamera); }, async getAccessory(device: ScryptedDevice & VideoCamera & VideoCameraConfiguration & Camera & MotionSensor & AudioSensor & Intercom & OnOff, homekitSession: HomeKitSession) { const console = deviceManager.getMixinConsole(device.id, undefined); interface Session { prepareRequest: PrepareStreamRequest; startRequest: StartStreamRequest; videossrc: number; audiossrc: number; cp: ChildProcess; videoReturn: dgram.Socket; audioReturn: dgram.Socket; demuxer?: RtpDemuxer; rtpSink?: HomeKitRtpSink; } const sessions = new Map<string, Session>(); const twoWayAudio = device.interfaces?.includes(ScryptedInterface.Intercom); function killSession(sessionID: string) { const session = sessions.get(sessionID); if (!session) return; console.log('streaming session killed'); sessions.delete(sessionID); session.cp?.kill('SIGKILL'); session.videoReturn?.close(); session.audioReturn?.close(); session.rtpSink?.destroy(); if (twoWayAudio) device.stopIntercom(); } const delegate: CameraStreamingDelegate = { handleSnapshotRequest: createSnapshotHandler(device, homekitSession), async prepareStream(request: PrepareStreamRequest, callback: PrepareStreamCallback) { const videossrc = CameraController.generateSynchronisationSource(); const audiossrc = CameraController.generateSynchronisationSource(); const socketType = request.addressVersion === 'ipv6' ? 'udp6' : 'udp4'; const { socket: videoReturn, port: videoPort } = await getPort(socketType); const { socket: audioReturn, port: audioPort } = await getPort(socketType); const session: Session = { prepareRequest: request, startRequest: null, videossrc, audiossrc, cp: null, videoReturn, audioReturn, } sessions.set(request.sessionID, session); const response: PrepareStreamResponse = { video: { srtp_key: request.video.srtp_key, srtp_salt: request.video.srtp_salt, port: videoPort, ssrc: videossrc, }, audio: { srtp_key: request.audio.srtp_key, srtp_salt: request.audio.srtp_salt, port: audioPort, ssrc: audiossrc, } } // plugin scope or device scope? const addressOverride = localStorage.getItem('addressOverride'); if (addressOverride) { console.log('using address override', addressOverride); response.addressOverride = addressOverride; } else { // HAP-NodeJS has weird default address determination behavior. Ideally it should use // the same IP address as the incoming socket, because that is by definition reachable. // But it seems to rechoose a matching address based on the interface. This guessing // can be error prone if that interface offers multiple addresses, some of which // may not be reachable. // Return the incoming address, assuming the sanity checks pass. Otherwise, fall through // to the HAP-NodeJS implementation. let check: string; if (request.addressVersion === 'ipv4') { const localAddress = request.connection.localAddress; if (v4Regex.exec(localAddress)) { check = localAddress; } else if (v4v6Regex.exec(localAddress)) { // if this is a v4 over v6 address, parse it out. check = localAddress.substring('::ffff:'.length); } } else if (request.addressVersion === 'ipv6' && !v4Regex.exec(request.connection.localAddress)) { check = request.connection.localAddress; } // sanity check this address. if (check) { const infos = os.networkInterfaces()[request.connection.networkInterface]; if (infos && infos.find(info => info.address === check)) { response.addressOverride = check; } } } callback(null, response); }, async handleStreamRequest(request: StreamingRequest, callback: StreamRequestCallback) { console.log('streaming request', request); if (request.type === StreamRequestTypes.STOP) { killSession(request.sessionID); callback(); return; } const session = sessions.get(request.sessionID); if (!session) { callback(new Error('unknown session')); return; } callback(); let selectedStream: MediaStreamOptions; const isHomeKitHub = homekitSession.isHomeKitHub(session.prepareRequest?.targetAddress); const streamingChannel = isHomeKitHub ? storage.getItem('streamingChannelHub') : storage.getItem('streamingChannel'); if (streamingChannel) { const msos = await device.getVideoStreamOptions(); selectedStream = msos.find(mso => mso.name === streamingChannel); } console.log('isHomeKitHub', isHomeKitHub, 'selected stream', selectedStream?.name || 'Default/undefined'); const tryReconfigureBitrate = () => { if (!isHomeKitHub) return; if (!device.interfaces.includes(ScryptedInterface.VideoCameraConfiguration)) return; const dynamicBitrate = storage.getItem('dynamicBitrate') === 'true'; if (!dynamicBitrate) return; const reconfigured: MediaStreamOptions = Object.assign({ video: { }, }, selectedStream || {}); const bitrate = 10000000;//request.video.max_bit_rate * 1000; reconfigured.video.bitrate = bitrate; device.setVideoStreamOptions(reconfigured); console.log('reconfigure selected stream', selectedStream); } if (request.type === StreamRequestTypes.RECONFIGURE) { tryReconfigureBitrate(); return; } else { session.startRequest = request as StartStreamRequest; } tryReconfigureBitrate(); // watch for data to verify other side is alive. session.videoReturn.on('data', () => debounce(() => { controller.forceStopStreamingSession(request.sessionID); killSession(request.sessionID); }, 60000)); const videomtu = request.video.mtu; // 400 seems fine? no idea what to use here. this is the mtu for sending audio to homekit. // from my observation of talkback packets, the max packet size is ~370, so // I'm just guessing that HomeKit wants something similar for the audio it receives. // going higher causes choppiness. going lower may cause other issues. let audiomtu = 400; try { console.log('fetching video stream'); const media = await device.getVideoStream(selectedStream); const ffmpegInput = JSON.parse((await mediaManager.convertMediaObjectToBuffer(media, ScryptedMimeTypes.FFmpegInput)).toString()) as FFMpegInput; const videoKey = Buffer.concat([session.prepareRequest.video.srtp_key, session.prepareRequest.video.srtp_salt]); const audioKey = Buffer.concat([session.prepareRequest.audio.srtp_key, session.prepareRequest.audio.srtp_salt]); const noAudio = ffmpegInput.mediaStreamOptions && ffmpegInput.mediaStreamOptions.audio === null; const args: string[] = [ '-hide_banner', ]; const transcodeStreaming = isHomeKitHub ? storage.getItem('transcodeStreamingHub') === 'true' : storage.getItem('transcodeStreaming') === 'true'; if (transcodeStreaming) { // decoder arguments const videoDecoderArguments = storage.getItem('videoDecoderArguments') || ''; if (videoDecoderArguments) { args.push(...evalRequest(videoDecoderArguments, request)); } } // ffmpeg input for decoder args.push(...ffmpegInput.inputArguments); if (!noAudio) { // create a dummy audio track if none actually exists. // this track will only be used if no audio track is available. // this prevents homekit erroring out if the audio track is actually missing. // https://stackoverflow.com/questions/37862432/ffmpeg-output-silent-audio-track-if-source-has-no-audio-or-audio-is-shorter-th args.push('-f', 'lavfi', '-i', 'anullsrc=cl=1', '-shortest'); } // video encoding args.push( "-an", '-sn', '-dn', ); if (transcodeStreaming) { const h264EncoderArguments = storage.getItem('h264EncoderArguments') || ''; const videoCodec = h264EncoderArguments ? evalRequest(h264EncoderArguments, request) : [ "-vcodec", "libx264", // '-preset', 'ultrafast', '-tune', 'zerolatency', '-pix_fmt', 'yuvj420p', // '-color_range', 'mpeg', "-bf", "0", // "-profile:v", profileToFfmpeg(request.video.profile), // '-level:v', levelToFfmpeg(request.video.level), "-b:v", request.video.max_bit_rate.toString() + "k", "-bufsize", (2 * request.video.max_bit_rate).toString() + "k", "-maxrate", request.video.max_bit_rate.toString() + "k", "-filter:v", "fps=" + request.video.fps.toString(), ]; args.push( ...videoCodec, ) } else { args.push( "-vcodec", "copy", ); } args.push( "-payload_type", (request as StartStreamRequest).video.pt.toString(), "-ssrc", session.videossrc.toString(), "-f", "rtp", "-srtp_out_suite", session.prepareRequest.video.srtpCryptoSuite === SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80 ? "AES_CM_128_HMAC_SHA1_80" : "AES_CM_256_HMAC_SHA1_80", "-srtp_out_params", videoKey.toString('base64'), `srtp://${session.prepareRequest.targetAddress}:${session.prepareRequest.video.port}?rtcpport=${session.prepareRequest.video.port}&pkt_size=${videomtu}` ) if (!noAudio) { // audio encoding const audioCodec = (request as StartStreamRequest).audio.codec; args.push( "-vn", '-sn', '-dn', ); // homekit live streaming seems extremely picky about aac output. // so currently always transcode audio. if (false && !transcodeStreaming) { args.push( "-acodec", "copy", ); } else if (audioCodec === AudioStreamingCodecType.OPUS || audioCodec === AudioStreamingCodecType.AAC_ELD) { args.push( '-acodec', ...(audioCodec === AudioStreamingCodecType.OPUS ? [ 'libopus', '-application', 'lowdelay', '-frame_duration', (request as StartStreamRequest).audio.packet_time.toString(), ] : ['libfdk_aac', '-profile:a', 'aac_eld']), '-flags', '+global_header', '-ar', `${(request as StartStreamRequest).audio.sample_rate}k`, '-b:a', `${(request as StartStreamRequest).audio.max_bit_rate}k`, "-bufsize", `${(request as StartStreamRequest).audio.max_bit_rate * 4}`, '-ac', `${(request as StartStreamRequest).audio.channel}`, "-payload_type", (request as StartStreamRequest).audio.pt.toString(), "-ssrc", session.audiossrc.toString(), "-srtp_out_suite", session.prepareRequest.audio.srtpCryptoSuite === SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80 ? "AES_CM_128_HMAC_SHA1_80" : "AES_CM_256_HMAC_SHA1_80", "-srtp_out_params", audioKey.toString('base64'), // not sure this works. // '-fflags', '+flush_packets', '-flush_packets', '1', "-f", "rtp", `srtp://${session.prepareRequest.targetAddress}:${session.prepareRequest.audio.port}?rtcpport=${session.prepareRequest.audio.port}&pkt_size=${audiomtu}` ) } else { console.warn(device.name, 'unknown audio codec, audio will not be streamed.', request); } } if (!sessions.has(request.sessionID)) { console.log('session ended before streaming could start. bailing.'); return; } console.log('ffmpeg args', args); const cp = child_process.spawn(await mediaManager.getFFmpegPath(), args); ffmpegLogInitialOutput(console, cp); session.cp = cp; // audio talkback if (twoWayAudio) { session.demuxer = new RtpDemuxer(console, session.audioReturn); const socketType = session.prepareRequest.addressVersion === 'ipv6' ? 'udp6' : 'udp4'; session.rtpSink = await startRtpSink(socketType, session.prepareRequest.targetAddress, audioKey, (request as StartStreamRequest).audio.sample_rate, console); session.demuxer.on('rtp', (buffer: Buffer) => { session.audioReturn.send(buffer, session.rtpSink.rtpPort); }); session.demuxer.on('rtcp', (buffer: Buffer) => { session.rtpSink.heartbeat(session.audioReturn, buffer); }); const mo = mediaManager.createFFmpegMediaObject(session.rtpSink.ffmpegInput); device.startIntercom(mo); } } catch (e) { console.error('streaming error', e); } }, }; const codecs: AudioStreamingCodec[] = []; // multiple audio options can be provided but lets stick with AAC ELD 24k, // that's what the talkback ffmpeg session in rtp-ffmpeg-input.ts will use. for (const type of [AudioStreamingCodecType.OPUS, AudioStreamingCodecType.AAC_ELD]) { for (const samplerate of [AudioStreamingSamplerate.KHZ_8, AudioStreamingSamplerate.KHZ_16, AudioStreamingSamplerate.KHZ_24]) { codecs.push({ type, samplerate, bitrate: 0, audioChannels: 1, }); } } // const msos = await device.getVideoStreamOptions(); // const nativeResolutions: Resolution[] = []; // if (msos) { // for (const mso of msos) { // if (!mso.video) // continue; // const { width, height } = mso.video; // if (!width || !height) // continue; // nativeResolutions.push( // [width, height, mso.video.fps || 30] // ); // } // } // function ensureHasWidthResolution(resolutions: Resolution[], width: number, defaultHeight: number) { // if (resolutions.find(res => res[0] === width)) // return; // const topVideo = msos?.[0]?.video; // if (!topVideo || !topVideo?.width || !topVideo?.height) { // resolutions.unshift([width, defaultHeight, 30]); // return; // } // resolutions.unshift( // [ // width, // fitHeightToWidth(topVideo.width, topVideo.height, width), // topVideo.fps || 30, // ]); // } // const streamingResolutions = [...nativeResolutions]; // // needed for apple watch // ensureHasWidthResolution(streamingResolutions, 320, 240); // // i think these are required by homekit? // ensureHasWidthResolution(streamingResolutions, 1280, 720); // ensureHasWidthResolution(streamingResolutions, 1920, 1080); const storage = deviceManager.getMixinStorage(device.id, undefined); const h265Support = storage.getItem('h265Support') === 'true'; const codecType = h265Support ? VideoCodecType.H265 : VideoCodecType.H264 const streamingOptions: CameraStreamingOptions = { video: { codec: { type: VideoCodecType.H264, levels: [H264Level.LEVEL3_1, H264Level.LEVEL3_2, H264Level.LEVEL4_0], profiles: [H264Profile.MAIN], }, resolutions: [ // 3840x2160@30 (4k). [3840, 2160, 30], // 1920x1080@30 (1080p). [1920, 1080, 30], // 1280x720@30 (720p). [1280, 720, 30], // 320x240@15 (Apple Watch). [320, 240, 15], ] }, audio: { codecs, twoWayAudio, }, supportedCryptoSuites: [ // not supported by ffmpeg // SRTPCryptoSuites.AES_CM_256_HMAC_SHA1_80, SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, SRTPCryptoSuites.NONE, ] } let recordingDelegate: CameraRecordingDelegate | undefined; let recordingOptions: CameraRecordingOptions | undefined; const accessory = makeAccessory(device); const detectAudio = storage.getItem('detectAudio') === 'true'; const needAudioMotionService = device.interfaces.includes(ScryptedInterface.AudioSensor) && detectAudio; const linkedMotionSensor = storage.getItem('linkedMotionSensor'); const storageKeySelectedRecordingConfiguration = 'selectedRecordingConfiguration'; if (linkedMotionSensor || device.interfaces.includes(ScryptedInterface.MotionSensor) || needAudioMotionService) { recordingDelegate = { handleFragmentsRequests(connection: DataStreamConnection): AsyncGenerator<Buffer, void, unknown> { homekitSession.detectedHomeKitHub(connection.remoteAddress); const configuration = RecordingManagement.parseSelectedConfiguration(storage.getItem(storageKeySelectedRecordingConfiguration)) return handleFragmentsRequests(device, configuration, console) } }; const recordingCodecs: AudioRecordingCodec[] = []; const samplerate: AudioRecordingSamplerate[] = []; for (const sr of [AudioRecordingSamplerate.KHZ_32]) { samplerate.push(sr); } for (const type of [AudioRecordingCodecType.AAC_LC]) { const entry: AudioRecordingCodec = { type, bitrateMode: 0, samplerate, audioChannels: 1, } recordingCodecs.push(entry); } // const recordingResolutions = [...nativeResolutions]; // ensureHasWidthResolution(recordingResolutions, 1280, 720); // ensureHasWidthResolution(recordingResolutions, 1920, 1080); recordingOptions = { motionService: true, prebufferLength: numberPrebufferSegments * iframeIntervalSeconds * 1000, eventTriggerOptions: 0x01, mediaContainerConfigurations: [ { type: 0, fragmentLength: iframeIntervalSeconds * 1000, } ], video: { codec: { type: codecType, levels: [H264Level.LEVEL3_1, H264Level.LEVEL3_2, H264Level.LEVEL4_0], profiles: [H264Profile.BASELINE, H264Profile.MAIN, H264Profile.HIGH], }, resolutions: [ [1280, 720, 30], [1920, 1080, 30], ], }, audio: { codecs: recordingCodecs, }, }; } const controller = new CameraController({ cameraStreamCount: 8, delegate, streamingOptions, recording: { options: recordingOptions, delegate: recordingDelegate, } }); accessory.configureController(controller); if (controller.motionService) { const motionDevice = systemManager.getDeviceById<MotionSensor & AudioSensor>(linkedMotionSensor) || device; if (!motionDevice) { return; } const motionDetected = needAudioMotionService ? () => !!motionDevice.audioDetected || !!motionDevice.motionDetected : () => !!motionDevice.motionDetected; const { motionService } = controller; bindCharacteristic(motionDevice, ScryptedInterface.MotionSensor, motionService, Characteristic.MotionDetected, () => motionDetected(), true) const { recordingManagement } = controller; const persistBooleanCharacteristic = (service: Service, characteristic: WithUUID<{ new(): Characteristic }>) => { const property = `characteristic-v2-${characteristic.UUID}` service.getCharacteristic(characteristic) .on(CharacteristicEventTypes.GET, callback => callback(null, storage.getItem(property) === 'true' ? 1 : 0)) .on(CharacteristicEventTypes.SET, (value, callback) => { callback(); storage.setItem(property, (!!value).toString()); }); } persistBooleanCharacteristic(recordingManagement.getService(), Characteristic.Active); persistBooleanCharacteristic(recordingManagement.getService(), Characteristic.RecordingAudioActive); persistBooleanCharacteristic(controller.cameraOperatingModeService, Characteristic.EventSnapshotsActive); persistBooleanCharacteristic(controller.cameraOperatingModeService, Characteristic.HomeKitCameraActive); persistBooleanCharacteristic(controller.cameraOperatingModeService, Characteristic.PeriodicSnapshotsActive); if (!device.interfaces.includes(ScryptedInterface.OnOff)) { persistBooleanCharacteristic(controller.cameraOperatingModeService, Characteristic.CameraOperatingModeIndicator); } else { const indicator = controller.cameraOperatingModeService.getCharacteristic(Characteristic.CameraOperatingModeIndicator); bindCharacteristic(device, ScryptedInterface.OnOff, controller.cameraOperatingModeService, Characteristic.CameraOperatingModeIndicator, () => device.on ? 1 : 0); indicator.on(CharacteristicEventTypes.SET, (value, callback) => { callback(); if (value) device.turnOn(); else device.turnOff(); }) } recordingManagement.getService().getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration) .on(CharacteristicEventTypes.GET, callback => { callback(null, storage.getItem(storageKeySelectedRecordingConfiguration) || ''); }) .on(CharacteristicEventTypes.SET, (value, callback) => { // prepare recording here if necessary. storage.setItem(storageKeySelectedRecordingConfiguration, value.toString()); callback(); }); } if (device.interfaces.includes(ScryptedInterface.ObjectDetector)) { const objectDetectionContactSensorsValue = storage.getItem('objectDetectionContactSensors'); const objectDetectionContactSensors: string[] = []; try { objectDetectionContactSensors.push(...JSON.parse(objectDetectionContactSensorsValue)); } catch (e) { } for (const ojs of new Set(objectDetectionContactSensors)) { const sensor = new OccupancySensor(`${device.name}: ` + ojs, ojs); accessory.addService(sensor); let contactState = Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED; let timeout: NodeJS.Timeout; const resetSensorTimeout = () => { clearTimeout(timeout); timeout = setTimeout(() => { contactState = Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED; sensor.updateCharacteristic(Characteristic.OccupancyDetected, contactState); }, (parseInt(storage.getItem('objectDetectionContactSensorTimeout')) || defaultObjectDetectionContactSensorTimeout) * 1000) } bindCharacteristic(device, ScryptedInterface.ObjectDetector, sensor, Characteristic.OccupancyDetected, (source, details, data) => { if (!source) return contactState; const ed: ObjectsDetected = data; if (!ed.detections) return contactState; const objects = ed.detections.map(d => d.className); if (objects.includes(ojs)) { contactState = Characteristic.OccupancyDetected.OCCUPANCY_DETECTED; resetSensorTimeout(); } return contactState; }, true); } } return accessory; } });
the_stack
const CLASSES = { /** * app is the container of the app. */ app: "coral coral-stream", /** * guidlines represents the box containing the guidlines. */ guidelines: { container: "coral coral-guidelines", content: "coral coral-guidelines-content", }, /** * guidlines represents the box containing the guidlines. */ announcement: "coral coral-announcement", /** * closedSitewide represents the box containing the message when comments * are closed sitewide. */ closedSitewide: "coral coral-closedSitewide", /** * sortMenu contains the dropdown to sort the comments. */ sortMenu: "coral coral-sortMenu", /** * counter to show e.g. the amount of comments. */ counter: "coral coral-counter", /** * commentForm is the border div around the RTE. */ commentForm: "coral coral-commentForm", /** * rte represents the rich-text-editor */ rte: { $root: "coral coral-rte", content: "coral coral-rte-content", placeholder: "coral coral-rte-placeholder", toolbar: "coral coral-rte-toolbar", container: "coral coral-rte-container", }, /** * tabBar is all the components in the top tab bar selector. */ tabBar: { /** * $root represents the container for the tab buttons. */ $root: "coral coral-tabBar", /** * comments is the button for the "Comments" tab. */ comments: "coral coral-tabBar-tab coral-tabBar-comments", /** * myProfile is the button for the "My Profile" tab. */ myProfile: "coral coral-tabBar-tab coral-tabBar-myProfile", discussions: "coral coral-tabBar-tab coral-tabBar-discussions", /** * configure is the button for the "Configure" tab. */ configure: "coral coral-tabBar-tab coral-tabBar-configure", activeTab: "coral-tabBar-tab-active", }, /** * tabBarComments is all the components in the comments secondary tab bar selector. */ tabBarComments: { /** * $root represents the container for the tab buttons. */ $root: "coral coral-tabBarSecondary coral-tabBarComments", /** * allComments is the button for the "All Comments" tab. */ allComments: "coral coral-tabBarSecondary-tab coral-tabBarComments-allComments", /** * featured is the button for the "Featured Comments" tab. */ featured: "coral coral-tabBarSecondary-tab coral-tabBarComments-featured", /** * featuredTooltip is the tooltip next to the featured tab. */ featuredTooltip: "coral coral-tabBarComments-featuredTooltip", activeTab: "coral-tabBarSecondary-tab-active", }, /** * tabBarMyProfile is all the components in the my profile secondary tab bar selector. */ tabBarMyProfile: { /** * $root represents the container for the tab buttons. */ $root: "coral coral-tabBarSecondary coral-tabBarMyProfile", /** * myComments is the button for the "My Comments" tab. */ myComments: "coral coral-tabBarSecondary-tab coral-tabBarMyProfile-myComments", /** * preferences is the button for the "Preferences" tab. */ preferences: "coral coral-tabBarSecondary-tab coral-tabBarMyProfile-preferences", /** * notifications is the button for the "Notifications" tab. */ notifications: "coral coral-tabBarSecondary-tab coral-tabBarMyProfile-notifications", active: "coral-tabBarSecondary-tab-active", /** * settings is the button for the "Settings" tab. */ settings: "coral coral-tabBarSecondary-tab coral-tabBarMyProfile-settings", }, /** * createComment is the comment creation box where a user can write a comment. */ createComment: { /** * $root represents the container for the new comments box. */ $root: "coral coral-createComment", /** * message is the box containing the messages configured in the story. */ message: "coral coral-createComment-message", /** * closed is the box containing the message when the story is closed. */ closed: "coral coral-createComment-closed", /** * submit is the button for submitting a new comment. */ submit: "coral coral-createComment-submit", /** * signIn is the button for submitting a new comment and signing in. */ signIn: "coral coral-createComment-signIn", /** * inReview is the message notifying the user that the posted comment is * in review. */ inReview: "coral coral-createComment-inReview", /** * rejected is the message notifying the user that the posted comment is * rejected. */ rejected: "coral coral-createComment-rejected", /** * dismissButton is the button to dismiss the in review message. */ dismissButton: "coral coral-createComment-dismissButton", /** * cancel is the button for cancelling the post. */ cancel: "coral coral-createComment-cancel", }, /** * replyComment is the comment creation box where a user can write a reply on * a specific comment. */ createReplyComment: { /** * $root represents the container for the new reply box. */ $root: "coral coral-createReplyComment", /** * inReview is the message notifying the user that the posted comment is * in review. */ inReview: "coral coral-createReplyComment-inReview", /** * submit is the button for submitting a new reply. */ submit: "coral coral-createReplyComment-submit", /** * cancel is the button for cancelling the reply. */ cancel: "coral coral-createReplyComment-cancel", /** * dimiss is the button to dismiss the message after submit. */ dismiss: "coral coral-createReplyComment-dismiss", /** * replyTo shows the author of the parent comment. */ replyTo: { $root: "coral coral-createReplyComment-replyTo", text: "coral coral-createReplyComment-replyToText", username: "coral coral-createReplyComment-replyToUsername", }, }, /** * editComment is the comment edit box where a user can edit his comment. */ editComment: { /** * $root represents the container for the edit box. */ $root: "coral coral-editComment", /** * inReview is the message notifying the user that the edited comment is * in review. */ inReview: "coral coral-editComment-inReview", /** * remainingTime is the message telling the user the remaining time. */ remainingTime: "coral coral-editComment-remainingTime", /** * expiredTime appears when the comment can no longer be edited. */ expiredTime: "coral coral-editComment-expiredTime", /** * submit is the button for submitting the edit. */ submit: "coral coral-editComment-submit", /** * close is the button for closing the edit after it expired. */ close: "coral coral-editComment-close", /** * cancel is the button for cancelling the edit. */ cancel: "coral coral-editComment-cancel", /** * dimiss is the button to dismiss the message after submit. */ dismiss: "coral coral-editComment-dismiss", }, /** * comment is the visual representation of a Comment. */ comment: { /** * $root represents the container containing a given Comment. */ $root: "coral coral-comment", /** * highlight is attached to the comment container if the single * conversation view is shown for this comment. */ highlight: "coral coral-comment-highlight", notSeen: "coral-comment-notSeen", focus: "coral-comment-focus", /** * reacted signifies the number of reactions of the comment. * The no of reactions is appended: e.g. `coral-reacted-1`. */ reacted: "coral coral-reacted", /** * collapseToggle is the button to collapse and expand the display of a comment. */ collapseToggle: { $root: "coral coral-comment-collapse-toggle", icon: "coral coral-comment-collapse-toggle-icon", indent: "coral coral-comment-collapse-toggle-indent", collapsed: "coral coral-comment-collapse-toggle-collapsed", }, /** * topBar is the uppper bar of the comment. */ topBar: { /** * $root represents the container of the top bar. */ $root: "coral coral-comment-topBar", /** * username is the text display for any given Username in the system. */ username: "coral coral-username coral-comment-username", /** * timestamp is the text that contains the time since the comment was * published. */ timestamp: "coral coral-timestamp coral-comment-timestamp", /** * edited is the text that indicated that a comment was edited. */ edited: "coral coral-comment-edited", /** * userTag can be used to target a tag associated with a User. */ userTag: "coral coral-userTag coral-comment-userTag", /** * userBadge can be used to target a badge associated with a User. */ userBadge: "coral coral-userBadge coral-comment-userBadge", /** * commentTag can be used to target a tag associated with a Comment. */ commentTag: "coral coral-commentTag coral-comment-commentTag", featuredTag: "coral coral-commentTag coral-comment-commentTag coral-featuredTag coral-comment-featuredTag", /** * caretButton can be used to target the caret that opens the moderation dropdown. */ caretButton: "coral coral-comment-caret", /** * editButton can be used to target the edit button. */ editButton: "coral coral-comment-editButton", }, /** * content is the html text body of the comment. */ content: "coral coral-content coral-comment-content", /** * readMoreOfConversation is the link that continues the * thread of the conversation on a deeper level. */ readMoreOfConversation: "coral coral-comment-readMoreOfConveration", /** * inReplyTo shows the author of the parent comment. */ inReplyTo: { $root: "coral coral-comment-inReplyTo", text: "coral coral-comment-inReplyToText", username: "coral coral-comment-inReplyToUsername", }, /** * actionBar is the lower bar of the comment. */ actionBar: { /** * $root represents the container of action bar. */ $root: "coral coral-comment-actionBar", /** * reactButton is the reaction button. */ reactButton: "coral coral-reactButton coral-comment-reactButton", /** * reactedButton is the class added to the reaction button * when the viewer has already reacted to the comment. */ reactedButton: "coral-reactedButton coral-comment-reactedButton", /** * replyButton is button that triggers the reply form. */ replyButton: "coral coral-comment-replyButton", /** * shareButton is the button that will show the permalink popover. */ shareButton: "coral coral-comment-shareButton", /** * reportButton is the button that triggers the report feature. */ reportButton: "coral coral-reportButton coral-comment-reportButton", /** * reportedButton is added to report button when the viewer * has already reported the comment. */ reportedButton: "coral-reportedButton coral-comment-reportedButton", }, /** * indentation classes for the different levels. */ indent: [ "coral coral-indent coral-indent-0", "coral coral-indent coral-indent-1", "coral coral-indent coral-indent-2", "coral coral-indent coral-indent-3", "coral coral-indent coral-indent-4", "coral coral-indent coral-indent-5", "coral coral-indent coral-indent-6", ], }, /** * moderationRejectedTombstone is shown to the moderator when a comment got rejected. */ moderationRejectedTombstone: { $root: "coral coral-moderationRejectedTombstone", goToModerateButton: "coral coral-moderationRejectedTombstone-goToModerateButton", }, /** * rejectedTombstone is shown when a comment has been rejected. */ rejectedTombstone: "coral coral-rejectedTombstone", /** * deletedTombstone is shown when a comment has been deleted. */ deletedTombstone: "coral coral-deletedTombstone", /** * ignoredTombstown is shown when a comment got ignored. */ ignoredTombstone: "coral coral-ignoredTombstone", /** * replyList represents the list of replies to a comment. */ replyList: { /** * showAllButton is the button to show all replies. */ showAllButton: "coral coral-replyList-showAllButton", /** * showAllButton is the button to show incoming live replies. */ showMoreReplies: "coral coral-replyList-showMoreButton", }, /** * comment is the visual representation of a featured comment. */ featuredComment: { /** * $root represents the container containing a featured comment. */ $root: "coral coral-featuredComment", /** * authorBar is the uppper bar of the comment. */ authorBar: { $root: "coral coral-featuredComment-authorBar", /** * username is the text display for any given Username in the system. */ username: "coral coral-username coral-comment-username", /** * timestamp is the text that contains the time since the comment was * published. */ timestamp: "coral coral-timestamp coral-comment-timestamp", /** * userTag can be used to target a tag associated with a User. */ userTag: "coral coral-userTag coral-comment-userTag", }, /** * content is the html text body of the featured comment. */ content: "coral coral-content coral-featuredComment-content", /** * actionBar is the lower bar of the featured comment. */ actionBar: { /** * $root represents the container of action bar. */ $root: "coral coral-featuredComment-actionBar", /** * replies indicates the amount of replies this comment has. */ replies: "coral coral-featuredComment-replies", /** * replies indicates the amount of replies this comment has. */ repliesDivider: "coral coral-featuredComment-replies-divider", /** * reactButton is the reaction button. */ reactButton: "coral coral-reactButton coral-featuredComment-reactButton", /** * reactedButton is the class added to the reaction button * when the viewer has already reacted to the comment. */ reactedButton: "coral-reactedButton coral-featuredComment-reactedButton", /** * goToConversation is the link that leads to the whole conversation. */ goToConversation: "coral coral-featuredComment-goToConversationButton", }, }, /** * streamFooter is the links that appear at the bottom of the comments stream */ streamFooter: { /** * root is the container for all of the links */ $root: "coral coral-streamFooter", /** * profileLink is the "profile and replies" link */ profileLink: "coral coral-streamFooter-link coral-streamFooter-profileLink", /** * discussionsLink is the "more discussions" link */ discussionsLink: "coral coral-streamFooter-link coral-streamFooter-discussionsLink", /** * commentsTopLink is the "top of comments" link */ commentsTopLink: "coral coral-streamFooter-link coral-streamFooter-commentsTopLink", /** * articleTopLink is the "top of comments" link */ articleTopLink: "coral coral-streamFooter-link coral-streamFooter-articleTopLink", }, /** * userPopover is the popover that appears when clicking on the username. */ userPopover: { /** * $root is the container of the user popover. */ $root: "coral coral-userPopover", /** * username that is rendeed inside the user popover. */ username: "coral coral-username coral-userPopover-username", /** * ignoreButton that will trigger the ignore user popover. */ ignoreButton: "coral coral-userPopover-ignoreButton", }, /** * ignoreUserPopover is the popover that allow the * viewer to ignore a user. */ ignoreUserPopover: { /** * $root is the container of the ignore user popover. */ $root: "coral coral-ignoreUserPopover", cancelButton: "coral coral-ignoreUserPopover-cancelButton", ignoreButton: "coral coral-ignoreUserPopover-ignoreButton", }, /** * sharePopover is the popover that shows the permalink of the comment. */ sharePopover: { $root: "coral coral-sharePopover", copyButton: "coral coral-sharePopover-copyButotn coral-sharePopover-copyButton", }, /** * reportPopover is the popover that appears when the viewer clicks on the * report button. */ reportPopover: { $root: "coral coral-reportPopover", closeButton: "coral coral-reportPopover-closeButton", cancelButton: "coral coral-reportPopover-cancelButton", submitButton: "coral coral-reportPopover-submitButton", copyButton: "coral coral-reportPopover-copyButton", }, /** * moderationDropdown is the dropdown that appears when clicking on the * caret as a priviledged user (at least moderator). */ moderationDropdown: { $root: "coral coral-moderationDropdown", approveButton: "coral coral-dropdownButton coral-moderationDropdown-approveButton", approvedButton: "coral coral-dropdownButton coral-moderationDropdown-approveedButton", rejectButton: "coral coral-dropdownButton coral-moderationDropdown-rejectButton", rejectedButton: "coral coral-dropdownButton coral-moderationDropdown-rejectedButton", featureButton: "coral coral-dropdownButton coral-moderationDropdown-featureButton", unfeatureButton: "coral coral-dropdownButton coral-moderationDropdown-unfeatureButton", banUserButton: "coral coral-dropdownButton coral-moderationDropdown-banUserButton", bannedButton: "coral coral-dropdownButton coral-moderationDropdown-bannedButton", goToModerateButton: "coral coral-dropdownButton coral-moderationDropdown-goToModerateButton", }, /** * banUserPopover is the popover that allows the viewer to ban users. */ banUserPopover: { $root: "coral coral-banUserPopover", cancelButton: "coral coral-banUserPopover-cancelButton", banButton: "coral coral-banUserPopover-banButton", }, /** * viewerBox is the box that indicates which user is logged in and * provides login, signout or register functionality. */ viewerBox: { $root: "coral coral-viewerBox", logoutButton: "coral coral-viewerBox-logoutButton", signInButton: "coral coral-viewerBox-signInButton", registerButton: "coral coral-viewerBox-registerButton", username: "coral coral-viewerBox-username", }, /** * comments tab pane is the default tab pane. */ commentsTabPane: { /** * $root is the container for the comments tab pane. */ $root: "coral coral-comments", /** * authenticated will indicate that the user is logged in. */ authenticated: "coral coral-authenticated", /** * unauthenticated will indicate that the user hasn't logged in yet. */ unauthenticated: "coral coral-unauthenticated", }, /** * allCommentsTabPane is the tab pane that shows all comments. */ allCommentsTabPane: { $root: "coral coral-allComments", /** * loadMoreButton is the button to paginate. */ loadMoreButton: "coral coral-loadMoreButton coral-allComments-loadMoreButton", /** * viewNewButton is the button that reveals newer comments. */ viewNewButton: "coral coral-allComments-viewNewButton", }, /** * featuredCommentsTabPane is the tab pane that shows featured comments. */ featuredCommentsTabPane: { $root: "coral coral-featuredComments", loadMoreButton: "coral coral-loadMoreButton coral-featuredComments-loadMoreButton", }, /** * permalinkView is the tab pane that shows the conversation of a comment. */ permalinkView: { /** * $root is the container for the permalink tab pane. */ $root: "coral coral-permalink", /** * authenticated will be applied to the container when the user is logged in. */ authenticated: "coral-authenticated", /** * unauthenticated will be applied to the container when the user has not logged in yet. */ unauthenticated: "coral-unauthenticated", /** * viewFullDiscussionButton is the button that leads to the full comment stream. */ viewFullDiscussionButton: "coral coral-permalink-viewFullDiscussionButton", }, /** * conversationThread shows the thread of comments that lead to the permalinked comment. */ conversationThread: { $root: "coral coral-conversationThread", /** * rootParent is the root comment that is shown in the thread before it has been * expanded. */ rootParent: { $root: "coral coral-rootParent", username: "coral coral-username coral-rootParent-username", timestamp: "coral coral-timestamp coral-rootParent-timestamp", userTag: "coral coral-userTag coral-rootParent-userTag", }, /** * showMore is the button that reveals all comments between root parent and highlighted comment. */ showMore: "coral coral-conversationThread-showMore", /** * highlighted is the comment that is targeted by the permalink. */ hightlighted: "coral coral-conversationThread-highlighted", }, /** * myProfileTabPane is the tab pane that shows the profile of the viewer. */ myProfileTabPane: { $root: "coral coral-myProfile", }, discussionsTabPane: { $root: "coral coral-discussions", }, /** * myUsername is the username part of my profile. */ myUsername: { title: "coral coral-myUsername-title", username: "coral coral-myUsername", editButton: "coral coral-myUsername-editButton", change: "coral coral-myUsername-change", tooSoon: "coral-myUsername-tooSoon", form: { $root: "coral coral-changeMyUsername", heading: "coral coral-changeMyUsername-heading", description: "coral coral-changeMyUsername-description", label: "coral coral-changeMyUsername-label", username: "coral coral-changeMyUsername-username", cancelButton: "coral coral-changeMyUsername-cancelButton", saveButton: "coral coral-changeMyUsername-saveButton", closeButton: "coral coral-changeMyUsername-closeButton", footer: "coral coral-changeMyUsername-footer", errorMessage: "coral coral-changeMyUsername-errorMessage coral-changeMyEmail-errorMessage", successMessage: "coral coral-changeMyUsername-successMessage", successCallOut: "coral coral-changeMyUsername-successCallOut", }, }, /** * myUsername is the email part of my profile. */ myEmail: { email: "coral coral-myEmail", title: "coral coral-myEmail-title", unverified: "coral coral-myEmail-unverified", editButton: "coral coral-myEmail-editButton", form: { $root: "coral coral-changeMyEmail", header: "coral coral-changeMyEmail-header", footer: "coral coral-changeMyEmail-footer", currentEmail: "coral coral-myEmail-currentEmail", desc: "coral coral-changeMyEmail-desc", cancelButton: "coral coral-changeMyEmail-cancelButton", saveButton: "coral coral-changeMyEmail-saveButton", errorMessage: "coral coral-changeMyEmail-errorMessage", }, }, /** * myUsername is the verify email part of my profile. */ verifyEmail: { $root: "coral coral-verifyEmail", container: "coral coral-verifyEmail-container", content: "coral coral-verifyEmail-content", title: "coral coral-verifyEmail-title", resendButton: "coral coral-verifyEmail-resendButton", resentMessage: "coral coral-verifyEmail-resentMessage", }, /** * myCommentsTabPane is the tab pane that shows viewers comments. */ myCommentsTabPane: { $root: "coral coral-myComments", loadMoreButton: "coral coral-loadMoreButton coral-myComments-loadMoreButton", }, /** * myComment is the comment that shows up in the viewers comment history. */ myComment: { $root: "coral coral-myComment", story: "coral coral-myComment-story", timestamp: "coral coral-myComment-timestamp", content: "coral coral-myComment-content", replies: "coral coral-myComment-replies", reactions: "coral coral-myComment-reactions", viewConversationButton: "coral coral-myComment-viewConversationButton", commentOn: "coral coral-myComment-commentOn", }, /** * notificationsTabPane is the tab pane that shows notifications settings. */ notificationsTabPane: { $root: "coral coral-notifications", }, preferencesTabPane: { $root: "coral coral-preferences", }, /** * accountTabPane is the tab pane that shows account settings. */ accountTabPane: { $root: "coral coral-account", }, /** * ignoredCommenters is ignored commenters settings. */ ignoredCommenters: { $root: "coral coral-ignoredCommenters", list: "coral coral-ignoredCommenters-list", manageButton: "coral coral-ignoredComments-manageButton", username: "coral coral-ignoredCommenters-username", stopIgnoreButton: "coral coral-ignoredCommenters-stopIgnoreButton", }, /** * myPassword allows the viewer to change password in settings. */ myPassword: { $root: "coral coral-myPassword", title: "coral coral-myPassword-title", editButton: "coral coral-myPassword-editButton", form: { $root: "coral coral-changePassword", footer: "coral coral-changePassword-footer", cancelButton: "coral coral-changePassword-cancelButton", forgotButton: "coral coral-changePassword-forgotButton", changeButton: "coral coral-changePassword-changeButton", successMessageContainer: "coral coral-changePassword-successContainer", successMessage: "coral coral-changePassword-successMessage", errorMessage: "coral coral-changePassword-errorMessage", }, }, /** * downloadCommentHistory allows the viewer to download the comment * history in settings. */ downloadCommentHistory: { $root: "coral coral-downloadCommentHistory", requestButton: "coral coral-downloadCommentHistory-requestButton", recentRequest: "coral coral-downloadCommentHistory-recentRequest", requestLater: "coral coral-downloadCommentHistory-requestLater", requestError: "coral coral-downloadCommentHistory-requestError", }, /** * deleteMyAccount allows the viewer to delete their account. */ deleteMyAccount: { $root: "coral coral-deleteMyAccount", title: "coral coral-deleteMyAccount-title", section: "coral coral-deleteMyAccount-section", content: "coral coral-deleteMyAccount-content", requestButton: "coral coral-deleteMyAccount-requestButton", cancelRequestButton: "coral coral-deleteMyAccount-cancelRequestButton", }, /** * pendingAccountDeletion is the message box informing the viewer * about a pending account deletion. */ pendingAccountDeletion: { $root: "coral coral-pendingAccountDeletion", container: "coral coral-pendingAccountDeletion-container", cancelRequestButton: "coral coral-pendingAccountDeletion-cancelRequestButton", icon: "coral coral-pendingAccountDeletion-cancelRequestIcon", }, /** * deleteMyAccount allows the viewer to delete their account. */ deleteMyAccountModal: { $root: "coral coral-deleteMyAccountModal", header: "coral coral-deleteMyAccountModal-header", headerText: "coral coral-deleteMyAccountModal-headerText", subHeaderText: "coral coral-deleteMyAccountModal-subHeaderText", body: "coral coral-deleteMyAccountModal-body", sectionContent: "coral coral-deleteMyAccountModal-sectionContent", sectionHeader: "coral coral-deleteMyAccountModal-sectionHeader", cancelButton: "coral coral-deleteMyAccountModal-cancelButton", proceedButton: "coral coral-deleteMyAccountModal-proceedButton", doneButton: "coral coral-deleteMyAccountModal-doneButton", stepBar: "coral coral-deleteMyAccountModal-stepBar", deleteMyAccountButton: "coral coral-deleteMyAccount-deleteMyAccountButton", }, /** * configureTabPane is the tab pane that lets priviledged users to * change settings of the stream. */ configureTabPane: { $root: "coral coral-configure", }, /** * configureMessageBox is the message box section in the stream configure. */ configureMessageBox: { $root: "coral coral-configureMessageBox", messageBox: "coral coral-configureMessageBox-messageBox", option: "coral coral-configureMessageBox-option", }, /** * configureCommentStream allows priviledged users to adjust settings of * the stream. */ configureCommentStream: { $root: "coral coral-configureCommentStream", applyButton: "coral coral-configureCommentStream-applyButton", errorMessage: "coral coral-configureCommentStream-errorMessage", successMessage: "coral coral-configureCommentStream-successMessage", }, /** * closeCommentStream allows priviledged users to close the stream. */ closeCommentStream: { $root: "coral coral-closeCommentStream", closeButton: "coral coral-closeCommentStream-closeButton", }, /** * openCommentStream allows priviledged users to open the stream. */ openCommentStream: { $root: "coral coral-openCommentStream", openButton: "coral coral-openCommentStream-openButton", }, emailNotifications: { $root: "coral coral-emailNotifications", updateButton: "coral coral-emailNotifications-updateButton", }, mediaPreferences: { updateButton: "coral coral-mediaPreferences-updateButton", }, /** * spinner is the loading indicator. */ spinner: "coral-spinner", /** * validation message that shows up on form errors. */ validationMessage: "coral-validation-message", login: { signIn: { noAccount: "coral coral-login-signIn-noAccount", }, signUp: { alreadyHaveAccount: "coral coral-login-signUp-alreadyHaveAccount", }, signInWithEmail: { forgotPassword: "coral coral-login-signInWithEmail-forgotPassword", }, bar: "coral coral-login-bar", title: "coral coral-login-title", header: "coral coral-login-header", subBar: "coral coral-login-subBar", orSeparator: "coral coral-login-orSeparator", description: "coral coral-login-description", field: "coral coral-login-field", errorContainer: "coral coral-login-errorContainer", error: "coral coral-login-error", facebookButton: "coral coral-login-facebookButton", googleButton: "coral coral-login-googleButton", oidcButton: "coral coral-login-oidcButton", }, moderateStream: "coral coral-general-moderateStreamLink", discussions: { $root: "coral coral-discussions", mostActiveDiscussions: "coral coral-mostActiveDiscussions", myOngoingDiscussions: "coral coral-myOngoingDiscussions", header: "coral coral-discussions-header", subHeader: "coral coral-discussions-subHeader", discussionsList: "coral coral-discussions-list", story: { $root: "coral coral-discussions-story", header: "coral coral-discussions-story-header", commentsCount: "coral coral-discussions-story-commentsCount", commentsCountIcon: "coral coral-discussions-story-commentsCountIcon", date: "coral coral-discussions-story-date", siteName: "coral coral-discussions-story-siteName", }, viewHistoryButton: "coral coral-discussions-viewHistoryButton", }, ratingsAndReview: { noReviews: "coral coral-ratingsReview-noReviewsYet", ratingsFilter: "coral coral-ratingsReview-filter", stars: { rating: "coral coral-ratingsReview-rating", readonly: "coral coral-ratingsReview-rating-readonly", icon: "coral coral-ratingsReview-icon", }, input: { title: "coral coral-ratingsReview-input-title", }, }, mobileToolbar: "coral coral-mobileToolbar", }; export default CLASSES;
the_stack
import Conditions from '../../../../../resources/conditions'; import NetRegexes from '../../../../../resources/netregexes'; import Outputs from '../../../../../resources/outputs'; import { Responses } from '../../../../../resources/responses'; import ZoneId from '../../../../../resources/zone_id'; import { RaidbossData } from '../../../../../types/data'; import { TriggerSet } from '../../../../../types/trigger'; export interface Data extends RaidbossData { moonIsOut?: boolean; moonlitCount?: number; moonshadowedCount?: number; } // Tsukuyomi Extreme const triggerSet: TriggerSet<Data> = { zoneId: ZoneId.TheMinstrelsBalladTsukuyomisPain, timelineFile: 'tsukuyomi-ex.txt', triggers: [ { id: 'TsukuyomiEx Nightfall Gun', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '2BBC', source: 'Tsukuyomi', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '2BBC', source: 'Tsukuyomi', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '2BBC', source: 'Tsukuyomi', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '2BBC', source: 'ツクヨミ', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '2BBC', source: '月读', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '2BBC', source: '츠쿠요미', capture: false }), response: Responses.stackMarker(), }, { id: 'TsukuyomiEx Nightfall Spear', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '2BBD', source: 'Tsukuyomi', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '2BBD', source: 'Tsukuyomi', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '2BBD', source: 'Tsukuyomi', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '2BBD', source: 'ツクヨミ', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '2BBD', source: '月读', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '2BBD', source: '츠쿠요미', capture: false }), response: Responses.spread(), }, { id: 'TsukuyomiEx Torment', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: ['2BBB', '2EB2'], source: 'Tsukuyomi' }), netRegexDe: NetRegexes.startsUsing({ id: ['2BBB', '2EB2'], source: 'Tsukuyomi' }), netRegexFr: NetRegexes.startsUsing({ id: ['2BBB', '2EB2'], source: 'Tsukuyomi' }), netRegexJa: NetRegexes.startsUsing({ id: ['2BBB', '2EB2'], source: 'ツクヨミ' }), netRegexCn: NetRegexes.startsUsing({ id: ['2BBB', '2EB2'], source: '月读' }), netRegexKo: NetRegexes.startsUsing({ id: ['2BBB', '2EB2'], source: '츠쿠요미' }), alarmText: (data, matches, output) => { if (matches.target === data.me || data.role !== 'tank') return; return output.tankSwap!(); }, alertText: (data, matches, output) => { if (matches.target === data.me) return output.tankBusterOnYou!(); if (data.role === 'healer') return output.busterOn!({ player: data.ShortName(matches.target) }); }, infoText: (data, matches, output) => { if (matches.target === data.me || data.role === 'tank' || data.role === 'healer') return; return output.getOutOfFront!(); }, outputStrings: { getOutOfFront: { en: 'Get out of front', de: 'Weg von vorn', fr: 'Éloignez-vous de l\'avant', ja: '正面から離れる', cn: '远离正面', ko: '정면 피하기', }, tankBusterOnYou: Outputs.tankBusterOnYou, busterOn: Outputs.tankBusterOnPlayer, tankSwap: Outputs.tankSwap, }, }, { id: 'TsukuyomiEx Full Moon', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ target: 'Tsukuyomi', effectId: '5FF', capture: false }), netRegexDe: NetRegexes.gainsEffect({ target: 'Tsukuyomi', effectId: '5FF', capture: false }), netRegexFr: NetRegexes.gainsEffect({ target: 'Tsukuyomi', effectId: '5FF', capture: false }), netRegexJa: NetRegexes.gainsEffect({ target: 'ツクヨミ', effectId: '5FF', capture: false }), netRegexCn: NetRegexes.gainsEffect({ target: '月读', effectId: '5FF', capture: false }), netRegexKo: NetRegexes.gainsEffect({ target: '츠쿠요미', effectId: '5FF', capture: false }), run: (data) => data.moonIsOut = true, }, { id: 'TsukuyomiEx New Moon', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ target: 'Tsukuyomi', effectId: '600', capture: false }), netRegexDe: NetRegexes.gainsEffect({ target: 'Tsukuyomi', effectId: '600', capture: false }), netRegexFr: NetRegexes.gainsEffect({ target: 'Tsukuyomi', effectId: '600', capture: false }), netRegexJa: NetRegexes.gainsEffect({ target: 'ツクヨミ', effectId: '600', capture: false }), netRegexCn: NetRegexes.gainsEffect({ target: '月读', effectId: '600', capture: false }), netRegexKo: NetRegexes.gainsEffect({ target: '츠쿠요미', effectId: '600', capture: false }), run: (data) => data.moonIsOut = false, }, { id: 'TsukuyomiEx Dark Blade', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '2BDA', source: 'Tsukuyomi', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '2BDA', source: 'Tsukuyomi', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '2BDA', source: 'Tsukuyomi', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '2BDA', source: 'ツクヨミ', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '2BDA', source: '月读', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '2BDA', source: '츠쿠요미', capture: false }), infoText: (data, _matches, output) => { if (data.moonIsOut) return output.leftAndOut!(); return output.leftAndIn!(); }, outputStrings: { leftAndOut: { en: 'Left + Out', de: 'Links + Raus', fr: 'À gauche + Extérieur', ja: '左へ + 外へ', cn: '左边 + 远离', ko: '왼쪽 + 밖', }, leftAndIn: { en: 'Left + In', de: 'Links + Rein', fr: 'À gauche + Intérieur', ja: '左へ + 中へ', cn: '左边 + 靠近', ko: '왼쪽 + 안', }, }, }, { id: 'TsukuyomiEx Bright Blade', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '2BDB', source: 'Tsukuyomi', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '2BDB', source: 'Tsukuyomi', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '2BDB', source: 'Tsukuyomi', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '2BDB', source: 'ツクヨミ', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '2BDB', source: '月读', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '2BDB', source: '츠쿠요미', capture: false }), infoText: (data, _matches, output) => { if (data.moonIsOut) return output.rightAndOut!(); return output.rightAndIn!(); }, outputStrings: { rightAndOut: { en: 'Right + Out', de: 'Rechts + Raus', fr: 'À droite + Extérieur', ja: '右へ + 外へ', cn: '右边 + 远离', ko: '오른쪽 + 밖', }, rightAndIn: { en: 'Right + In', de: 'Rechts + Rein', fr: 'À droite + Intérieur', ja: '右へ + 中へ', cn: '右边 + 靠近', ko: '오른쪽 + 안', }, }, }, { id: 'TsukuyomiEx Meteor Marker', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '0083' }), condition: Conditions.targetIsYou(), response: Responses.meteorOnYou(), }, { id: 'TsukuyomiEx Lunacy', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '003E', capture: false }), response: Responses.stackMarker(), }, { id: 'TsukuyomiEx Hagetsu', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '0017' }), condition: Conditions.targetIsYou(), response: Responses.spread(), }, { id: 'TsukuyomiEx Dance of the Dead', type: 'GameLog', // There's no "starts using" here. She pushes at 35% to this ability. // This happens after 2nd meteors naturally, but if dps is good // then this could push unexpectedly earlier (or paired with buster). netRegex: NetRegexes.dialog({ line: '[^:]*:No\. No\.\.\. Not yet\. Not\. Yet\..*?', capture: false }), netRegexDe: NetRegexes.dialog({ line: '[^:]*:Meine Rache \.\.\. Ich will\.\.\. meine Rache\.\.\..*?', capture: false }), netRegexFr: NetRegexes.dialog({ line: '[^:]*:Non\, je ne peux pas\.\.\. échouer\.\.\..*?', capture: false }), netRegexJa: NetRegexes.dialog({ line: '[^:]*:嗚呼、まだ、あたしは…………。.*?', capture: false }), netRegexCn: NetRegexes.dialog({ line: '[^:]*:我不能输.*我还没有.*.*?', capture: false }), netRegexKo: NetRegexes.dialog({ line: '[^:]*:아아, 나는 아직……\..*?', capture: false }), response: Responses.aoe(), }, { id: 'TsukuyomiEx Supreme Selenomancy', type: 'Ability', netRegex: NetRegexes.ability({ source: 'Tsukuyomi', id: '2EB0', capture: false }), netRegexDe: NetRegexes.ability({ source: 'Tsukuyomi', id: '2EB0', capture: false }), netRegexFr: NetRegexes.ability({ source: 'Tsukuyomi', id: '2EB0', capture: false }), netRegexJa: NetRegexes.ability({ source: 'ツクヨミ', id: '2EB0', capture: false }), netRegexCn: NetRegexes.ability({ source: '月读', id: '2EB0', capture: false }), netRegexKo: NetRegexes.ability({ source: '츠쿠요미', id: '2EB0', capture: false }), suppressSeconds: 5, run: (data) => { delete data.moonlitCount; delete data.moonshadowedCount; }, }, { id: 'TsukuyomiEx Moonlit Debuff Logic', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: '602' }), condition: Conditions.targetIsYou(), preRun: (data) => { // init at 3 so we can start at 4 stacks to give the initial instruction to move if (typeof data.moonlitCount === 'undefined') data.moonlitCount = 3; data.moonlitCount += 1; data.moonshadowedCount = 0; // dead/reset? if (data.moonlitCount > 4) data.moonlitCount = 0; }, }, { id: 'TsukuyomiEx Moonlit Debuff', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: '602' }), condition: (data, matches) => { if (matches.target !== data.me) return false; return data.moonlitCount !== undefined && data.moonlitCount >= 4; }, infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Move to Black!', de: 'In\'s schwarze laufen!', fr: 'Allez en zone noire !', ja: '新月に!', cn: '踩黑色!', ko: '검정색으로 이동!', }, }, }, { id: 'TsukuyomiEx Moonshadowed Debuff Logic', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: '603' }), condition: Conditions.targetIsYou(), preRun: (data) => { // init at 3 so we can start at 4 stacks to give the initial instruction to move if (typeof data.moonshadowedCount === 'undefined') data.moonshadowedCount = 3; data.moonshadowedCount += 1; data.moonlitCount = 0; // dead/reset? if (data.moonshadowedCount > 4) data.moonshadowedCount = 0; }, }, { id: 'TsukuyomiEx Moonshadowed Debuff', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: '603' }), condition: (data, matches) => { if (matches.target !== data.me) return false; return data.moonlitCount !== undefined && data.moonlitCount >= 4; }, infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Move to White!', de: 'In\'s weiße laufen!', fr: 'Allez en zone blanche !', ja: '満月に!', cn: '踩白色!', ko: '흰색으로 이동!', }, }, }, ], timelineReplace: [ { 'locale': 'en', 'replaceText': { 'Bright Blade/Dark Blade': 'Bright/Dark Blade', 'Waning Grudge/Waxing Grudge': 'Waning/Waxing Grudge', 'Lead Of The Underworld/Steel Of The Underworld': 'Lead/Steel Of The Underworld', }, }, { 'locale': 'de', 'replaceSync': { 'Dancing Fan': 'tanzend(?:e|er|es|en) Fächer', 'Moondust': 'Mondfragment', 'Moonlight': 'Mondlicht', 'No\. No\.\.\. Not yet\. Not\. Yet\.': 'Meine Rache ... Ich will... meine Rache...', 'Specter(?! )': 'Schemen', 'Specter Of Asahi': 'Asahi', 'Specter Of Gosetsu': 'Gosetsu', 'Specter Of The Patriarch': 'Yotsuyus Ziehvater', 'Specter Of Zenos': 'Zenos', 'Specter of Zenos': 'Zenos', 'Tsukuyomi': 'Tsukuyomi', }, 'replaceText': { '\\(gun': '(Pistole', 'spear\\)': 'Speer)', 'Antitwilight': 'Schönheit der Nacht', 'Bright Blade': 'Helle Klinge', 'Concentrativity': 'Konzentriertheit', 'Crater': 'Krater', 'Dance Of The Dead': 'Tanz der Toten', 'Dark Blade': 'Dunkle Klinge', 'Dispersivity': 'Dispersivität', 'Empire adds': 'Soldaten Adds', 'Hagetsu': 'Hagetsu', 'Homeland adds': 'Domaner Adds', 'Lead Of The Underworld': 'Blei der Unterwelt', 'Lunacy': 'Mondscheinblüte', 'Lunar Halo': 'Flammender Mond', 'Lunar Rays': 'Mondschimmer', 'Midnight Rain': 'Mitternachtsregen', 'Moonbeam': 'Mondstrahl', 'Moonfall': 'Mondfall', 'Nightbloom': 'Monddämmerung', 'Perilune': 'Zenit des Mondes', 'Reprimand': 'Maßregelung', 'Steel Of The Underworld': 'Stahl der Unterwelt', 'Supreme Selenomancy': 'Hohe Mondprophezeiung', 'Torment Unto Death': 'Todesqualen', 'Tsuki-No-Kakera': 'Mondsplitter', 'Tsuki-No-Maiogi': 'Mondfächer', 'Unmoving Troika': 'Unbewegte Troika', 'Waning Grudge': 'Schwindender Groll', 'Waxing Grudge': 'Wachsender Groll', 'Zashiki-Asobi': 'Zashiki-Asobi', }, }, { 'locale': 'fr', 'replaceSync': { 'Dancing Fan': 'maiôgi', 'Moondust': 'fragment de lune', 'Moonlight': 'Clair de lune', 'No\. No\.\.\. Not yet\. Not\. Yet\.': 'Non, je ne peux pas... échouer...', 'Specter(?! )': 'spector', 'Specter Of Asahi': 'apparition d\'Asahi', 'Specter Of Gosetsu': 'apparition de Gosetsu', 'Specter Of The Patriarch': 'spectre du parâtre', 'Specter Of Zenos': 'spectre de Zenos', 'Tsukuyomi': 'Tsukuyomi', 'Specter of Zenos': 'spectre de Zenos', }, 'replaceText': { '\\?': ' ?', '\\(E->W\\)': '(E->O)', '\\(SW->NW\\)': '(SO->NO)', '\\(gun\\)': '(fusil)', '\\(gun/spear\\)': '(fusil/lance)', '\\(spear\\)': '(lance)', 'Antitwilight': 'Belle-de-nuit', 'Bright Blade/Dark Blade': 'Lame blafarde/ténébreuse', 'Concentrativity': 'Kenki concentré', 'Crater': 'Explosion de fragment lunaire', 'Dance Of The Dead': 'Danse des morts', 'Dispersivity': 'Onde Kenki', 'Empire adds': 'Adds Impériaux', 'Hagetsu': 'Pulvérisation lunaire', 'Homeland adds': 'Adds Domiens', 'Lead Of The Underworld(?!/)': 'Tir de l\'au-delà', 'Lead Of The Underworld/Steel Of The Underworld': 'Tir/Pointes de l\'au-delà', 'Lunacy': 'Efflorescence au clair de lune', 'Lunar Halo': 'Flamboiement lunaire', 'Lunar Rays': 'Rayons lunaires', 'Midnight Rain': 'Bruine nocturne', 'Moonbeam': 'Faisceau lunaire', 'Moonfall': 'Impact de fragment lunaire', 'Nightbloom': 'Lis araignée', 'Nightfall': 'Jeune nuit', 'Perilune': 'Zénith lunaire', 'Reprimand': 'Correction', '(?<!/)Steel Of The Underworld': 'Pointes de l\'au-delà', 'Supreme Selenomancy': 'Sélénomancie suprême', 'Torment Unto Death': 'Brimade meurtrière', 'Tsuki-No-Kakera': 'Fragments lunaires', 'Tsuki-No-Maiogi': 'Maiôgi lunaire', 'Unmoving Troika': 'Troïka immobile', 'Waning Grudge/Waxing Grudge': 'Rancœur blafarde/ténébreuse', 'Zashiki-Asobi': 'Zashiki asobi', }, }, { 'locale': 'ja', 'missingTranslations': true, 'replaceSync': { 'Dancing Fan': '舞扇', 'Moondust': '月の欠片', 'Moonlight': '月光', 'No\. No\.\.\. Not yet\. Not\. Yet\.': '嗚呼、まだ、あたしは…………。', 'Specter(?! )': 'スペクター', 'Specter Of Asahi': 'アサヒの幻影', 'Specter Of Gosetsu': 'ゴウセツの幻影', 'Specter Of The Patriarch': '養父の幻影', 'Specter Of Zenos': 'ゼノスの幻影', 'Tsukuyomi': 'ツクヨミ', 'Specter of Zenos': 'ゼノスの幻影', }, 'replaceText': { 'Antitwilight': '月下美人', 'Bright Blade': '月刀左近', 'Concentrativity': '圧縮剣気', 'Crater': '氷輪', 'Dance Of The Dead': '黄泉の舞', 'Dark Blade': '月刀右近', 'Dispersivity': '剣気波動', 'Empire adds': '雑魚: 帝国軍', 'Hagetsu': '破月', 'Homeland adds': '雑魚: 幻影', 'Lead Of The Underworld': '黄泉の銃弾', 'Lunacy': '月下繚乱', 'Lunar Halo': '百月光', 'Lunar Rays': '残月', 'Midnight Rain': '月時雨', 'Moonbeam': '月光流転', 'Moonfall': '月片落下', 'Nightbloom': '月下彼岸花', 'Perilune': '月天心', 'Reprimand': '折檻', 'Steel Of The Underworld': '黄泉の穂先', 'Supreme Selenomancy': '極の月読', 'Torment Unto Death': 'なぶり殺し', 'Tsuki-No-Kakera': '月の欠片', 'Tsuki-No-Maiogi': '月の舞扇', 'Unmoving Troika': '不動三段', 'Waning Grudge': '黒き怨念', 'Waxing Grudge': '白き怨念', 'Zashiki-Asobi': '座敷遊び', }, }, { 'locale': 'cn', 'replaceSync': { 'Dancing Fan': '舞扇', 'Moondust': '月之碎片', 'Moonlight': '月光', 'No\. No\.\.\. Not yet\. Not\. Yet\.': '我不能输.*我还没有.*', 'Specter(?! )': '妖影', 'Specter Of Asahi': '朝阳的幻影', 'Specter Of Gosetsu': '豪雪的幻影', 'Specter Of The Patriarch': '养父的幻影', 'Specter Of Zenos': '芝诺斯的幻影', 'Tsukuyomi': '月读', 'Specter of Zenos': '芝诺斯的幻影', }, 'replaceText': { '\\(gun': '(枪', 'spear\\)': '长矛)', 'Antitwilight': '月下美人', 'Bright Blade': '月刀左斩', 'Concentrativity': '压缩剑气', 'Crater': '冰轮', 'Dance Of The Dead': '黄泉之舞', 'Dark Blade': '月刀右斩', 'Dispersivity': '剑气波动', 'Empire adds': '帝国幻影', 'Hagetsu': '破月', 'Homeland adds': '家人幻影', 'Lead Of The Underworld': '黄泉之弹', 'Lunacy': '月下缭乱', 'Lunar Halo': '百月光', 'Lunar Rays': '残月', 'Midnight Rain': '月时雨', 'Moonbeam': '月光流转', 'Moonfall': '碎片散落', 'Nightbloom': '月下彼岸花', 'Perilune': '月天心', 'Reprimand': '责难', 'Steel Of The Underworld': '黄泉之枪', 'Supreme Selenomancy': '极月读', 'Torment Unto Death': '折磨', 'Tsuki-No-Kakera': '月之碎片', 'Tsuki-No-Maiogi': '月下舞扇', 'Unmoving Troika': '不动三段', 'Waning Grudge': '漆黑怨念', 'Waxing Grudge': '纯白怨念', 'Zashiki-Asobi': '宴会游乐', }, }, { 'locale': 'ko', 'replaceSync': { 'Dancing Fan': '춤추는 부채', 'Moondust': '달조각', 'Moonlight': '월광', 'No\. No\.\.\. Not yet\. Not\. Yet\.': '아아, 나는 아직…….', 'Specter(?! )': '그림자요괴', 'Specter Of Asahi': '아사히의 환영', 'Specter Of Gosetsu': '고우세츠의 환영', 'Specter Of The Patriarch': '양아버지의 환영', 'Specter Of Zenos': '제노스의 환영', 'Tsukuyomi': '츠쿠요미', 'Specter of Zenos': '제노스의 환영', }, 'replaceText': { 'Antitwilight': '월하미인', 'Bright Blade': '하현달 베기', 'Concentrativity': '압축 검기', 'Crater': '빙륜', 'Dance Of The Dead': '황천의 춤', 'Dark Blade': '상현달 베기', 'Dispersivity': '검기 파동', 'Empire adds': '제국군 쫄', 'Hagetsu': '파월', 'Homeland adds': '도마 쫄', 'Lead Of The Underworld': '황천의 총탄', 'Lunacy': '월하요란', 'Lunar Halo': '백월광', 'Lunar Rays': '잔월', 'Midnight Rain': '달의 눈물', 'Moonbeam': '달빛 윤회', 'Moonfall': '달조각 낙하', 'Nightbloom': '달빛 저승꽃', 'Perilune': '중천의 달', 'Reprimand': '절함', 'Steel Of The Underworld': '황천의 창끝', 'Supreme Selenomancy': '궁극의 달읽기', 'Torment Unto Death': '고문살인', 'Tsuki-No-Kakera': '달조각', 'Tsuki-No-Maiogi': '춤추는 달 부채', 'Unmoving Troika': '부동삼단', 'Waning Grudge': '검은 원념', 'Waxing Grudge': '하얀 원념', 'Zashiki-Asobi': '유흥', 'gun': '총', 'spear': '창', }, }, ], }; export default triggerSet;
the_stack
import { ProductName } from "@microsoft/teamsfx-api"; import * as uuid from "uuid"; import * as vscode from "vscode"; import { endLocalDebugSession, getLocalDebugSessionId, getLocalTeamsAppId, getNpmInstallLogInfo, } from "./commonUtils"; import { ext } from "../extensionVariables"; import { ExtTelemetry } from "../telemetry/extTelemetry"; import { TelemetryEvent, TelemetryProperty } from "../telemetry/extTelemetryEvents"; import { Correlator, getHashedEnv, isValidProject } from "@microsoft/teamsfx-core"; import * as path from "path"; import { errorDetail, issueLink, issueTemplate } from "./constants"; import * as StringResources from "../resources/Strings.json"; import * as util from "util"; import VsCodeLogInstance from "../commonlib/log"; import { globalStateGet, globalStateUpdate } from "@microsoft/teamsfx-core"; import * as constants from "../debug/constants"; import { ExtensionSurvey } from "../utils/survey"; import { TreatmentVariableValue } from "../exp/treatmentVariables"; import { TeamsfxDebugConfiguration } from "./teamsfxDebugProvider"; interface IRunningTeamsfxTask { source: string; name: string; scope: vscode.WorkspaceFolder | vscode.TaskScope; } const allRunningTeamsfxTasks: Map<IRunningTeamsfxTask, number> = new Map< IRunningTeamsfxTask, number >(); const allRunningDebugSessions: Set<string> = new Set<string>(); const activeNpmInstallTasks = new Set<string>(); /** * This EventEmitter is used to track all running tasks called by `runTask`. * Each task executed by `runTask` will have an internal task id. * Event emitters use this id to identify each tracked task, and `runTask` matches this id * to determine whether a task is terminated or not. */ let taskEndEventEmitter: vscode.EventEmitter<{ id: string; exitCode?: number }>; let taskStartEventEmitter: vscode.EventEmitter<string>; const trackedTasks = new Set<string>(); function isNpmInstallTask(task: vscode.Task): boolean { if (task) { return task.name.trim().toLocaleLowerCase().endsWith("npm install"); } return false; } function isTeamsfxTask(task: vscode.Task): boolean { // teamsfx: xxx start / xxx watch // teamsfx: dev / watch if (task) { if ( task.source === ProductName && (task.name.trim().toLocaleLowerCase().endsWith("start") || task.name.trim().toLocaleLowerCase().endsWith("watch")) ) { // provided by toolkit return true; } if (task.definition && task.definition.type === ProductName) { // defined by launch.json const command = task.definition.command as string; return ( command !== undefined && (command.trim().toLocaleLowerCase().endsWith("start") || command.trim().toLocaleLowerCase().endsWith("watch") || command.trim().toLowerCase() === "dev" || command.trim().toLowerCase() === "watch") ); } } return false; } function displayTerminal(taskName: string): boolean { const terminal = vscode.window.terminals.find((t) => t.name === taskName); if (terminal !== undefined && terminal !== vscode.window.activeTerminal) { terminal.show(true); return true; } return false; } export async function runTask(task: vscode.Task): Promise<number | undefined> { if (task.definition.teamsfxTaskId === undefined) { task.definition.teamsfxTaskId = uuid.v4(); } const taskId = task.definition.teamsfxTaskId; let started = false; return new Promise<number | undefined>((resolve, reject) => { // corner case but need to handle - somehow the task does not start const startTimer = setTimeout(() => { if (!started) { reject(new Error("Task start timeout")); } }, 30000); const startListener = taskStartEventEmitter.event((result) => { if (taskId === result) { clearTimeout(startTimer); started = true; startListener.dispose(); } }); vscode.tasks.executeTask(task); const endListener = taskEndEventEmitter.event((result) => { if (taskId === result.id) { endListener.dispose(); resolve(result.exitCode); } }); }); } // TODO: move to local debug prerequisites checker async function checkCustomizedPort(component: string, componentRoot: string, checklist: RegExp[]) { /* const devScript = await loadTeamsFxDevScript(componentRoot); if (devScript) { let showWarning = false; for (const check of checklist) { if (!check.test(devScript)) { showWarning = true; break; } } if (showWarning) { VsCodeLogInstance.info(`Customized port detected in ${component}.`); if (!globalStateGet(constants.PortWarningStateKeys.DoNotShowAgain, false)) { const doNotShowAgain = "Don't Show Again"; const editPackageJson = "Edit package.json"; const learnMore = "Learn More"; vscode.window .showWarningMessage( util.format( StringResources.vsc.localDebug.portWarning, component, path.join(componentRoot, "package.json") ), doNotShowAgain, editPackageJson, learnMore ) .then(async (selected) => { if (selected === doNotShowAgain) { await globalStateUpdate(constants.PortWarningStateKeys.DoNotShowAgain, true); } else if (selected === editPackageJson) { vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(path.join(componentRoot, "package.json")) ); } else if (selected === learnMore) { vscode.commands.executeCommand( "vscode.open", vscode.Uri.parse(constants.localDebugHelpDoc) ); } }); } } } */ } function onDidStartTaskHandler(event: vscode.TaskStartEvent): void { const taskId = event.execution.task?.definition?.teamsfxTaskId; if (taskId !== undefined) { trackedTasks.add(taskId); taskStartEventEmitter.fire(taskId as string); } } function onDidEndTaskHandler(event: vscode.TaskEndEvent): void { const taskId = event.execution.task?.definition?.teamsfxTaskId; if (taskId !== undefined && trackedTasks.has(taskId as string)) { trackedTasks.delete(taskId as string); taskEndEventEmitter.fire({ id: taskId as string, exitCode: undefined }); } } async function onDidStartTaskProcessHandler(event: vscode.TaskProcessStartEvent): Promise<void> { if (ext.workspaceUri && isValidProject(ext.workspaceUri.fsPath)) { const task = event.execution.task; if (task.scope !== undefined && isTeamsfxTask(task)) { allRunningTeamsfxTasks.set( { source: task.source, name: task.name, scope: task.scope }, event.processId ); } else if (isNpmInstallTask(task)) { try { ExtTelemetry.sendTelemetryEvent(TelemetryEvent.DebugNpmInstallStart, { [TelemetryProperty.DebugNpmInstallName]: task.name, }); if (TreatmentVariableValue.isEmbeddedSurvey) { // Survey triggering point const survey = ExtensionSurvey.getInstance(); survey.activate(); } } catch { // ignore telemetry error } activeNpmInstallTasks.add(task.name); } } } async function onDidEndTaskProcessHandler(event: vscode.TaskProcessEndEvent): Promise<void> { const timestamp = new Date(); const task = event.execution.task; const activeTerminal = vscode.window.activeTerminal; const taskId = task?.definition?.teamsfxTaskId; if (taskId !== undefined) { trackedTasks.delete(taskId as string); taskEndEventEmitter.fire({ id: taskId as string, exitCode: event.exitCode }); } if (task.scope !== undefined && isTeamsfxTask(task)) { allRunningTeamsfxTasks.delete({ source: task.source, name: task.name, scope: task.scope }); } else if (isNpmInstallTask(task)) { try { activeNpmInstallTasks.delete(task.name); if (activeTerminal?.name === task.name && event.exitCode === 0) { // when the task in active terminal is ended successfully. for (const hiddenTaskName of activeNpmInstallTasks) { // display the first hidden terminal. if (displayTerminal(hiddenTaskName)) { return; } } } else if (activeTerminal?.name !== task.name && event.exitCode !== 0) { // when the task in hidden terminal failed to execute. displayTerminal(task.name); } const cwdOption = (task.execution as vscode.ShellExecution).options?.cwd; let cwd: string | undefined; if (cwdOption !== undefined) { cwd = path.join(ext.workspaceUri.fsPath, cwdOption?.replace("${workspaceFolder}/", "")); } const npmInstallLogInfo = await getNpmInstallLogInfo(); let validNpmInstallLogInfo = false; if ( cwd !== undefined && npmInstallLogInfo?.cwd !== undefined && path.relative(npmInstallLogInfo.cwd, cwd).length === 0 && event.exitCode !== undefined && npmInstallLogInfo.exitCode === event.exitCode ) { const timeDiff = timestamp.getTime() - npmInstallLogInfo.timestamp.getTime(); if (timeDiff >= 0 && timeDiff <= 20000) { validNpmInstallLogInfo = true; } } const properties: { [key: string]: string } = { [TelemetryProperty.DebugNpmInstallName]: task.name, [TelemetryProperty.DebugNpmInstallExitCode]: event.exitCode + "", // "undefined" or number value }; if (validNpmInstallLogInfo) { properties[TelemetryProperty.DebugNpmInstallNodeVersion] = npmInstallLogInfo?.nodeVersion + ""; // "undefined" or string value properties[TelemetryProperty.DebugNpmInstallNpmVersion] = npmInstallLogInfo?.npmVersion + ""; // "undefined" or string value properties[TelemetryProperty.DebugNpmInstallErrorMessage] = npmInstallLogInfo?.errorMessage?.join("\n") + ""; // "undefined" or string value } ExtTelemetry.sendTelemetryEvent(TelemetryEvent.DebugNpmInstall, properties); if (cwd !== undefined && event.exitCode !== undefined && event.exitCode !== 0) { let url = `${issueLink}title=new+bug+report: Task '${task.name}' failed&body=${issueTemplate}`; if (validNpmInstallLogInfo) { url = `${url}${errorDetail}${JSON.stringify(npmInstallLogInfo, undefined, 4)}`; } const issue = { title: StringResources.vsc.handlers.reportIssue, run: async (): Promise<void> => { vscode.commands.executeCommand("vscode.open", vscode.Uri.parse(url)); }, }; vscode.window .showErrorMessage( util.format( StringResources.vsc.localDebug.npmInstallFailedHintMessage, task.name, task.name ), issue ) .then(async (button) => { await button?.run(); }); await VsCodeLogInstance.error( util.format( StringResources.vsc.localDebug.npmInstallFailedHintMessage, task.name, task.name ) ); terminateAllRunningTeamsfxTasks(); } } catch { // ignore any error } } } async function onDidStartDebugSessionHandler(event: vscode.DebugSession): Promise<void> { if (ext.workspaceUri && isValidProject(ext.workspaceUri.fsPath)) { const debugConfig = event.configuration as TeamsfxDebugConfiguration; if ( debugConfig && debugConfig.name && (debugConfig.url || debugConfig.port) && // it's from launch.json !debugConfig.postRestartTask ) { // and not a restart one // send f5 event telemetry try { const localAppId = (await getLocalTeamsAppId()) as string; const isLocal = (debugConfig.url as string) && localAppId && (debugConfig.url as string).includes(localAppId); let appId = ""; let env = ""; if (isLocal) { appId = localAppId; } else { if (debugConfig.teamsfxAppId) { appId = debugConfig.teamsfxAppId; } if (debugConfig.teamsfxEnv) { env = getHashedEnv(event.configuration.env); } } ExtTelemetry.sendTelemetryEvent(TelemetryEvent.DebugStart, { [TelemetryProperty.DebugSessionId]: event.id, [TelemetryProperty.DebugType]: debugConfig.type, [TelemetryProperty.DebugRequest]: debugConfig.request, [TelemetryProperty.DebugPort]: debugConfig.port + "", [TelemetryProperty.DebugRemote]: isLocal ? "false" : "true", [TelemetryProperty.DebugAppId]: appId, [TelemetryProperty.Env]: env, }); if ( debugConfig.request === "launch" && isLocal && !globalStateGet(constants.SideloadingHintStateKeys.DoNotShowAgain, false) ) { vscode.window .showInformationMessage( StringResources.vsc.localDebug.sideloadingHintMessage, StringResources.vsc.localDebug.sideloadingHintDoNotShowAgain, StringResources.vsc.localDebug.openFAQ ) .then(async (selected) => { if (selected === StringResources.vsc.localDebug.sideloadingHintDoNotShowAgain) { await globalStateUpdate(constants.SideloadingHintStateKeys.DoNotShowAgain, true); } else if (selected === StringResources.vsc.localDebug.openFAQ) { vscode.commands.executeCommand( "vscode.open", vscode.Uri.parse(constants.localDebugFAQUrl) ); } ExtTelemetry.sendTelemetryEvent(TelemetryEvent.DebugFAQ, { [TelemetryProperty.DebugFAQSelection]: selected + "", [TelemetryProperty.DebugAppId]: localAppId, }); }); } } catch { // ignore telemetry error } allRunningDebugSessions.add(event.id); } } } export function terminateAllRunningTeamsfxTasks(): void { for (const task of allRunningTeamsfxTasks) { try { process.kill(task[1], "SIGTERM"); } catch (e) { // ignore and keep killing others } } allRunningTeamsfxTasks.clear(); } function onDidTerminateDebugSessionHandler(event: vscode.DebugSession): void { if (allRunningDebugSessions.has(event.id)) { // a valid debug session // send stop-debug event telemetry try { ExtTelemetry.sendTelemetryEvent(TelemetryEvent.DebugStop, { [TelemetryProperty.DebugSessionId]: event.id, }); } catch { // ignore telemetry error } const extConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("fx-extension"); if (extConfig.get<boolean>("stopTeamsToolkitTasksPostDebug", true)) { terminateAllRunningTeamsfxTasks(); } allRunningDebugSessions.delete(event.id); if (allRunningDebugSessions.size == 0) { endLocalDebugSession(); } allRunningTeamsfxTasks.clear(); } } export function registerTeamsfxTaskAndDebugEvents(): void { taskEndEventEmitter = new vscode.EventEmitter<{ id: string; exitCode?: number }>(); taskStartEventEmitter = new vscode.EventEmitter<string>(); ext.context.subscriptions.push({ dispose() { taskEndEventEmitter.dispose(); taskStartEventEmitter.dispose(); trackedTasks.clear(); }, }); ext.context.subscriptions.push(vscode.tasks.onDidStartTask(onDidStartTaskHandler)); ext.context.subscriptions.push(vscode.tasks.onDidEndTask(onDidEndTaskHandler)); ext.context.subscriptions.push( vscode.tasks.onDidStartTaskProcess((event: vscode.TaskProcessStartEvent) => Correlator.runWithId(getLocalDebugSessionId(), onDidStartTaskProcessHandler, event) ) ); ext.context.subscriptions.push( vscode.tasks.onDidEndTaskProcess((event: vscode.TaskProcessEndEvent) => Correlator.runWithId(getLocalDebugSessionId(), onDidEndTaskProcessHandler, event) ) ); // debug session handler use correlation-id from event.configuration.teamsfxCorrelationId // to minimize concurrent debug session affecting correlation-id ext.context.subscriptions.push( vscode.debug.onDidStartDebugSession((event: vscode.DebugSession) => Correlator.runWithId( // fallback to retrieve correlation id from the global variable. event.configuration.teamsfxCorrelationId || getLocalDebugSessionId(), onDidStartDebugSessionHandler, event ) ) ); ext.context.subscriptions.push( vscode.debug.onDidTerminateDebugSession((event: vscode.DebugSession) => Correlator.runWithId( event.configuration.teamsfxCorrelationId || getLocalDebugSessionId(), onDidTerminateDebugSessionHandler, event ) ) ); }
the_stack
import { debounceTime, distinctUntilChanged, finalize, map, switchMap, takeUntil, withLatestFrom } from 'rxjs/operators'; import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router, ParamMap } from '@angular/router'; import { Subject, Observable } from 'rxjs'; import * as moment from 'moment/moment'; import { StatsService, SuggestionsService, ReportDataService, ReportQueryService, ReportQuery, ReportingSummaryStatus } from '../shared/reporting'; import { LayoutFacadeService, Sidebar } from 'app/entities/layout/layout.facade'; import { saveAs } from 'file-saver'; import { Chicklet, ReportingFilterTypes } from 'app/types/types'; import { DateTime } from 'app/helpers/datetime/datetime'; import { pickBy } from 'lodash/fp'; import { FilterC } from './types'; @Component({ templateUrl: './reporting.component.html', styleUrls: ['./reporting.component.scss'], providers: [SuggestionsService] }) export class ReportingComponent implements OnInit, OnDestroy { allowedURLFilterTypes = [ ReportingFilterTypes.CHEF_SERVER, ReportingFilterTypes.CHEF_TAGS, ReportingFilterTypes.CONTROL_ID, ReportingFilterTypes.CONTROL_NAME, ReportingFilterTypes.CONTROL_TAG_KEY, ReportingFilterTypes.ENVIRONMENT, ReportingFilterTypes.INSPEC_VERSION, ReportingFilterTypes.JOB_ID, ReportingFilterTypes.NODE_ID, ReportingFilterTypes.NODE_NAME, ReportingFilterTypes.ORGANIZATION, ReportingFilterTypes.PLATFORM_WITH_VERSION, ReportingFilterTypes.POLICY_GROUP, ReportingFilterTypes.POLICY_NAME, ReportingFilterTypes.PROFILE_ID, ReportingFilterTypes.PROFILE_WITH_VERSION, ReportingFilterTypes.PROFILE_NAME, ReportingFilterTypes.RECIPE, ReportingFilterTypes.ROLE ]; // Query search bar availableFilterTypes = [ { 'name': 'chef_server', 'title': 'Chef Infra Server', 'description': '', 'placeholder': 'Chef Infra Server' }, { 'name': 'organization', 'title': 'Chef Organization', 'description': 'Add the organization to filter this report to a specific organization', 'placeholder': 'Chef Organization' }, { 'name': 'chef_tags', 'title': 'Chef Tag', 'description': '', 'placeholder': 'Chef Tag' }, { 'name': 'control_tag_key', 'title': 'Control Tag', 'description': '', 'placeholder': 'Control Tag' }, { 'name': 'control', 'title': 'Controls', 'description': 'Add the title to filter this report against a control', 'placeholder': 'Title' }, { 'name': 'environment', 'title': 'Environment', 'description': 'Add the environment name to filter this report to a specific environment', 'placeholder': 'Environment' }, { 'name': 'inspec_version', 'title': 'InSpec Version', 'description': '', 'placeholder': 'InSpec Version' }, { 'name': 'node', 'title': 'Node Name', 'description': 'Add the node name to filter this report against a specific node', 'placeholder': 'Node Name' }, { 'name': 'platform_with_version', 'title': 'Platform', 'description': 'Add the name to filter this report to a specific platform', 'placeholder': 'Name' }, { 'name': 'policy_group', 'title': 'Policy Group', 'description': '', 'placeholder': 'Policy Group' }, { 'name': 'policy_name', 'title': 'Policy Name', 'description': '', 'placeholder': 'Policy Name' }, { 'name': 'profile_with_version', 'title': 'Profile', 'description': 'Add the name or ID to filter this report against a profile', 'placeholder': 'Name or ID' }, { 'name': 'recipe', 'title': 'Recipe', 'description': 'Add the recipe to filter this report to a specific recipe', 'placeholder': 'Recipe' }, { 'name': 'role', 'title': 'Role', 'description': 'Add the role to filter this report to a specific role', 'placeholder': 'Role' } ]; private NO_VALUE = 'no value'; private noValuesControlTagFilter = { id: '', score: 1, text: this.NO_VALUE, title: 'no value', version: '' }; availableFilterValues = []; defaultFilterInputPlaceholder = 'Filter by...'; inputSelectedFilter: {}; removeSelectedFilter: {}; downloadOptsVisible = false; shareOptsVisible = false; downloadList: Array<string> = []; downloadStatusVisible = false; downloadInProgress = false; downloadFailed = false; endDate$: Observable<Date>; filters$: Observable<FilterC[]>; ChefDateTime = DateTime.CHEF_DATE_TIME; showSummary = false; private suggestionSearchTerms = new Subject< { 'type': string, 'text': string, 'type_key': string }>(); // Used to notify all subscriptions to unsubscribe // http://stackoverflow.com/a/41177163/319074 private isDestroyed: Subject<boolean> = new Subject<boolean>(); constructor( private router: Router, private statsService: StatsService, private suggestionsService: SuggestionsService, public reportQuery: ReportQueryService, public reportData: ReportDataService, private route: ActivatedRoute, private layoutFacade: LayoutFacadeService ) { } private getAllUrlParameters(): Observable<Chicklet[]> { return this.route.queryParamMap.pipe(map((params: ParamMap) => { return params.keys.reduce((list, key) => { const paramValues = params.getAll(key); return list.concat(paramValues.map(value => ({type: key, text: value}))); }, []); })); } ngOnInit() { this.layoutFacade.showSidebar(Sidebar.Compliance); const allUrlParameters$ = this.getAllUrlParameters(); this.endDate$ = this.reportQuery.state.pipe(map((reportQuery: ReportQuery) => this.convertMomentToDate(reportQuery.endDate))); allUrlParameters$.pipe(takeUntil(this.isDestroyed)).subscribe( allUrlParameters => this.applyParamFilters(allUrlParameters)); this.reportQuery.state.pipe( takeUntil(this.isDestroyed)) .subscribe(reportQuery => { this.reportData.nodesListParams.page = 1; this.reportData.profilesListParams.page = 1; this.getData(reportQuery); }); this.suggestionSearchTerms.pipe( // wait 1/2 second after each keystroke before considering the term debounceTime(500), // ignore new term if same as previous term distinctUntilChanged(), // include currently selected report filters withLatestFrom(this.reportQuery.state), // switch to new search observable each time the term changes switchMap(([terms, reportQuery]) => { const { type, text } = terms; return this.getSuggestions(type, text, reportQuery); }), takeUntil(this.isDestroyed) ).subscribe(suggestions => this.availableFilterValues = suggestions.filter(e => e.text)); this.filters$ = this.reportQuery.state.pipe(map((reportQuery: ReportQuery) => reportQuery.filters.filter((filter) => filter.value.text !== undefined).map(filter => { filter.value.id = filter.value.text; if (['profile_id', 'node_id', 'control_id'].indexOf(filter.type.name) >= 0) { const name = this.reportQuery.getFilterTitle(filter.type.name, filter.value.id); if (name !== undefined) { filter.value.text = name; } } return filter; }))); } ngOnDestroy() { this.isDestroyed.next(true); this.isDestroyed.complete(); } toggleDownloadDropdown() { this.downloadOptsVisible = !this.downloadOptsVisible; } toggleShareDropdown() { this.shareOptsVisible = !this.shareOptsVisible; } hideShareDropdown() { this.shareOptsVisible = false; } get shareUrl() { return window.location.href; } hideDownloadDropdown() { this.downloadOptsVisible = false; } onDownloadOptPressed(format) { this.downloadOptsVisible = false; const reportQuery = this.reportQuery.getReportQuery(); const filename = `${reportQuery.endDate.format('YYYY-M-D')}.${format}`; const onComplete = () => this.downloadInProgress = false; const onError = _e => this.downloadFailed = true; const types = { 'json': 'application/json', 'csv': 'text/csv' }; const onNext = data => { const type = types[format]; const blob = new Blob([data], { type }); saveAs(blob, filename); this.hideDownloadStatus(); }; this.downloadList = [filename]; this.showDownloadStatus(); this.statsService.downloadReport(format, reportQuery).pipe( finalize(onComplete)) .subscribe(onNext, onError); } showDownloadStatus() { this.downloadStatusVisible = true; this.downloadInProgress = true; this.downloadFailed = false; } hideDownloadStatus() { this.downloadStatusVisible = false; this.downloadInProgress = false; this.downloadFailed = false; } onEndDateChanged(event) { const queryParams = {...this.route.snapshot.queryParams}; const endDate = moment.utc(event.detail); queryParams['end_time'] = moment(endDate).format('YYYY-MM-DD'); this.router.navigate([], {queryParams}); } onLast24Selected() { const queryParams = {...this.route.snapshot.queryParams}; delete queryParams['end_time']; this.router.navigate([], {queryParams}); } onSuggestValues(event) { const { type, text } = event.detail; this.suggestionSearchTerms.next( { 'type': type, 'text': text, type_key: this.suggestionsService.selectedControlTagKey}); } onFilterAdded(event) { const {type, value} = event.detail; let filterValue = value.text; let typeName = type.name; if (type.name === 'profile_with_version') { if ( value.id ) { typeName = 'profile_id'; filterValue = value.id; this.reportQuery.setFilterTitle(typeName, value.id, value.title); } else { typeName = 'profile_with_version'; } } else if (type.name === 'node') { if ( value.id ) { typeName = 'node_id'; filterValue = value.id; this.reportQuery.setFilterTitle(typeName, value.id, value.title); } else { typeName = 'node_name'; } } else if (type.name === 'control') { if ( value.id ) { typeName = 'control_id'; filterValue = value.id; this.reportQuery.setFilterTitle(typeName, value.id, value.title); } else { typeName = 'control_name'; } } else if (this.isTypeControlTag(type.name)) { if (value.title === 'no value') { typeName = type.name; filterValue = value.id; this.reportQuery.setFilterTitle(typeName, value.id, value.title); } } const {queryParamMap} = this.route.snapshot; const queryParams = {...this.route.snapshot.queryParams}; const existingValues = queryParamMap.getAll(typeName).filter( v => v !== filterValue).concat(filterValue); queryParams[typeName] = existingValues; this.router.navigate([], {queryParams}); } onFilterRemoved(event) { const {type, value} = event.detail; const {queryParamMap} = this.route.snapshot; const queryParams = {...this.route.snapshot.queryParams}; const values = queryParamMap.getAll(type.name).filter(v => v !== value.id); if (values.length === 0) { delete queryParams[type.name]; } else { queryParams[type.name] = values; } this.router.navigate([], {queryParams}); } onFiltersClear(_event) { const queryParams = {...this.route.snapshot.queryParams}; const filteredParams = pickBy((_value, key: ReportingFilterTypes) => // We 'control_tag...' filter because this is a second level filter and will not // clear properly when included. (!key.includes('control_tag') && this.allowedURLFilterTypes.indexOf(key) < 0), queryParams); this.router.navigate([], {queryParams: filteredParams}); } getData(reportQuery: ReportQuery) { this.reportData.getReportingSummary(reportQuery); } toggleSummary() { this.showSummary = !this.showSummary; } getIcon(status: ReportingSummaryStatus): string { switch (status) { case 'failed': return 'report_problem'; case 'passed': return 'check_circle'; case 'waived': return 'check_circle'; case 'skipped': return 'help'; case 'unknown': return 'help'; } } formatSummaryPhrase(status: ReportingSummaryStatus): string { switch (status) { case 'failed': return 'Not Compliant'; case 'passed': return 'Compliant'; case 'waived': return 'Compliant'; case 'skipped': return 'Skipped'; case 'unknown': return 'Unknown'; } } formatDuration(duration) { return moment.duration(duration).humanize(); } formatDate(timestamp) { return moment.utc(timestamp).format('MMMM Do[,] YYYY'); } getSuggestions(type: string, text: string, reportQuery: ReportQuery) { return this.suggestionsService.getSuggestions(type.replace('_id', ''), text, reportQuery).pipe( map(data => { // Adding the option of 'no value' only to the control tag third level suggestions if (type === 'control_tag_value') { data.unshift(this.noValuesControlTagFilter); } return data.map(item => Object.assign(item, { title: item.text })); }), takeUntil(this.isDestroyed) ); } applyParamFilters(urlFilters: Chicklet[]) { const reportQuery = this.reportQuery.getReportQuery(); reportQuery.filters = urlFilters.filter( (urlParm: Chicklet) => this.isTypeControlTag(urlParm.type) || this.allowedURLFilterTypes.indexOf(urlParm.type as ReportingFilterTypes) >= 0) .map((urlParm: Chicklet) => { return { type: { name: urlParm.type }, value: { text: urlParm.text } }; }); reportQuery.interval = this.getDateInterval(urlFilters); reportQuery.endDate = this.getEndDate(urlFilters); reportQuery.startDate = this.reportQuery.findTimeIntervalStartDate( reportQuery.interval, reportQuery.endDate); reportQuery.last24h = this.isLast24h(urlFilters); this.reportQuery.setState(reportQuery); } isTypeControlTag(type: string) { return type.search('control_tag:') !== -1; } getEndDate(urlFilters: Chicklet[]): moment.Moment { const foundFilter = urlFilters.find( (filter: Chicklet) => filter.type === 'end_time'); if (foundFilter !== undefined) { const endDate = moment.utc(foundFilter.text + 'GMT+00:00', 'YYYY-MM-DDZ'); if (endDate.isValid()) { return endDate.utc().startOf('day').add(12, 'hours'); } else { const queryParams = {...this.route.snapshot.queryParams}; delete queryParams['end_time']; this.router.navigate([], {queryParams}); } } return moment().utc().startOf('day').add(12, 'hours'); } getDateInterval(urlFilters: Chicklet[]): number { const foundFilter = urlFilters.find( (filter: Chicklet) => filter.type === 'date_interval'); if (foundFilter === undefined) { return 0; } else { const dateInterval = parseInt(foundFilter.text, 10); if ( !isNaN(dateInterval) && dateInterval >= 0 && dateInterval < this.reportQuery.intervals.length ) { return dateInterval; } else { const queryParams = {...this.route.snapshot.queryParams}; delete queryParams['date_interval']; this.router.navigate([], {queryParams}); } } return 0; } convertMomentToDate(m: moment.Moment): Date { return new Date(Date.UTC(m.year(), m.month(), m.date())); } isLast24h(urlFilters: Chicklet[]): boolean { return !urlFilters.some((filter: Chicklet) => filter.type === 'end_time'); } }
the_stack
import * as assert from 'assert'; import {describe, it, afterEach, beforeEach} from 'mocha'; import * as sinon from 'sinon'; import {AwsRequestSigner} from '../src/auth/awsrequestsigner'; import {GaxiosOptions} from 'gaxios'; /** Defines the interface to facilitate testing of AWS request signing. */ interface AwsRequestSignerTest { // Test description. description: string; // The mock time when the signature is generated. referenceDate: Date; // AWS request signer instance. instance: AwsRequestSigner; // The raw input request. originalRequest: GaxiosOptions; // The expected signed output request. getSignedRequest: () => GaxiosOptions; } describe('AwsRequestSigner', () => { let clock: sinon.SinonFakeTimers; // Load AWS credentials from a sample security_credentials response. // eslint-disable-next-line @typescript-eslint/no-var-requires const awsSecurityCredentials = require('../../test/fixtures/aws-security-credentials-fake.json'); const accessKeyId = awsSecurityCredentials.AccessKeyId; const secretAccessKey = awsSecurityCredentials.SecretAccessKey; const token = awsSecurityCredentials.Token; beforeEach(() => { clock = sinon.useFakeTimers(0); }); afterEach(() => { if (clock) { clock.restore(); } }); describe('getRequestOptions()', () => { const awsError = new Error('Error retrieving AWS security credentials'); // Successful AWS credentials retrieval. // In this case, temporary credentials are returned. const getCredentials = async () => { return { accessKeyId, secretAccessKey, token, }; }; // Successful AWS credentials retrieval. // In this case, permanent credentials are returned (no session token). const getCredentialsWithoutToken = async () => { return { accessKeyId, secretAccessKey, }; }; // Failing AWS credentials retrieval. const getCredentialsUnsuccessful = async () => { throw awsError; }; // Sample request parameters. const requestParams = { KeySchema: [ { KeyType: 'HASH', AttributeName: 'Id', }, ], TableName: 'TestTable', AttributeDefinitions: [ { AttributeName: 'Id', AttributeType: 'S', }, ], ProvisionedThroughput: { WriteCapacityUnits: 5, ReadCapacityUnits: 5, }, }; // List of various requests and their expected signatures. // Examples source: // https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html const getRequestOptionsTests: AwsRequestSignerTest[] = [ { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.sreq description: 'signed GET request (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'GET', url: 'https://host.foo.com', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }, getSignedRequest: () => { const signature = 'b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470'; return { url: 'https://host.foo.com', method: 'GET', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.sreq description: 'signed GET request with relative path (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'GET', url: 'https://host.foo.com/foo/bar/../..', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }, getSignedRequest: () => { const signature = 'b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470'; return { url: 'https://host.foo.com/foo/bar/../..', method: 'GET', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.sreq description: 'signed GET request with /./ path (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'GET', url: 'https://host.foo.com/./', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }, getSignedRequest: () => { const signature = 'b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470'; return { url: 'https://host.foo.com/./', method: 'GET', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.sreq description: 'signed GET request with pointless dot path (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'GET', url: 'https://host.foo.com/./foo', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }, getSignedRequest: () => { const signature = '910e4d6c9abafaf87898e1eb4c929135782ea25bb0279703146455745391e63a'; return { url: 'https://host.foo.com/./foo', method: 'GET', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.sreq description: 'signed GET request with utf8 path (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'GET', url: 'https://host.foo.com/%E1%88%B4', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }, getSignedRequest: () => { const signature = '8d6634c189aa8c75c2e51e106b6b5121bed103fdb351f7d7d4381c738823af74'; return { url: 'https://host.foo.com/%E1%88%B4', method: 'GET', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.sreq description: 'signed GET request with uplicate query key (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'GET', url: 'https://host.foo.com/?foo=Zoo&foo=aha', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }, getSignedRequest: () => { const signature = 'be7148d34ebccdc6423b19085378aa0bee970bdc61d144bd1a8c48c33079ab09'; return { url: 'https://host.foo.com/?foo=Zoo&foo=aha', method: 'GET', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-ut8-query.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-ut8-query.sreq description: 'signed GET request with utf8 query (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'GET', url: 'https://host.foo.com/?ሴ=bar', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }, getSignedRequest: () => { const signature = '6fb359e9a05394cc7074e0feb42573a2601abc0c869a953e8c5c12e4e01f1a8c'; return { url: 'https://host.foo.com/?ሴ=bar', method: 'GET', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.sreq description: 'signed POST request with sorted headers (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'POST', url: 'https://host.foo.com/', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', ZOO: 'zoobar', }, }, getSignedRequest: () => { const signature = 'b7a95a52518abbca0964a999a880429ab734f35ebbf1235bd79a5de87756dc4a'; return { url: 'https://host.foo.com/', method: 'POST', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host;zoo, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', ZOO: 'zoobar', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.sreq description: 'signed POST request with upper case header value from ' + 'AWS Python test harness', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'POST', url: 'https://host.foo.com/', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', zoo: 'ZOOBAR', }, }, getSignedRequest: () => { const signature = '273313af9d0c265c531e11db70bbd653f3ba074c1009239e8559d3987039cad7'; return { url: 'https://host.foo.com/', method: 'POST', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host;zoo, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', zoo: 'ZOOBAR', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.sreq description: 'signed POST request with header and no body (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'POST', url: 'https://host.foo.com', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', p: 'phfft', }, }, getSignedRequest: () => { const signature = 'debf546796015d6f6ded8626f5ce98597c33b47b9164cf6b17b4642036fcb592'; return { url: 'https://host.foo.com', method: 'POST', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host;p, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', p: 'phfft', }, }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.sreq description: 'signed POST request with body and no header (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'POST', url: 'https://host.foo.com', headers: { 'Content-Type': 'application/x-www-form-urlencoded', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, body: 'foo=bar', }, getSignedRequest: () => { const signature = '5a15b22cf462f047318703b92e6f4f38884e4a7ab7b1d6426ca46a8bd1c26cbc'; return { url: 'https://host.foo.com', method: 'POST', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + 'aws4_request, SignedHeaders=content-type;date;host, ' + `Signature=${signature}`, host: 'host.foo.com', 'Content-Type': 'application/x-www-form-urlencoded', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, body: 'foo=bar', }; }, }, { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.sreq description: 'signed POST request with querystring (AWS botocore tests)', referenceDate: new Date('2011-09-09T23:36:00.000Z'), instance: new AwsRequestSigner(async () => { return { accessKeyId: 'AKIDEXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', }; }, 'us-east-1'), originalRequest: { method: 'POST', url: 'https://host.foo.com/?foo=bar', headers: { date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }, getSignedRequest: () => { const signature = 'b6e3b79003ce0743a491606ba1035a804593b0efb1e20a11cba83f8c25a57a92'; return { url: 'https://host.foo.com/?foo=bar', method: 'POST', headers: { Authorization: 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/' + `aws4_request, SignedHeaders=date;host, Signature=${signature}`, host: 'host.foo.com', date: 'Mon, 09 Sep 2011 23:36:00 GMT', }, }; }, }, { description: 'signed GET request', referenceDate: new Date('2020-08-11T06:55:22.345Z'), instance: new AwsRequestSigner(getCredentials, 'us-east-2'), originalRequest: { url: 'https://ec2.us-east-2.amazonaws.com?' + 'Action=DescribeRegions&Version=2013-10-15', }, getSignedRequest: () => { const amzDate = '20200811T065522Z'; const dateStamp = '20200811'; const signature = '631ea80cddfaa545fdadb120dc92c9f18166e38a5c47b50fab9fce476e022855'; return { url: 'https://ec2.us-east-2.amazonaws.com?' + 'Action=DescribeRegions&Version=2013-10-15', method: 'GET', headers: { Authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/` + `${dateStamp}/us-east-2/ec2/aws4_request, SignedHeaders=host;` + `x-amz-date;x-amz-security-token, Signature=${signature}`, host: 'ec2.us-east-2.amazonaws.com', 'x-amz-date': amzDate, 'x-amz-security-token': token, }, }; }, }, { description: 'signed POST request', referenceDate: new Date('2020-08-11T06:55:22.345Z'), instance: new AwsRequestSigner(getCredentials, 'us-east-2'), originalRequest: { url: 'https://sts.us-east-2.amazonaws.com' + '?Action=GetCallerIdentity&Version=2011-06-15', method: 'POST', }, getSignedRequest: () => { const amzDate = '20200811T065522Z'; const dateStamp = '20200811'; const signature = '73452984e4a880ffdc5c392355733ec3f5ba310d5e0609a89244440cadfe7a7a'; return { url: 'https://sts.us-east-2.amazonaws.com' + '?Action=GetCallerIdentity&Version=2011-06-15', method: 'POST', headers: { 'x-amz-date': amzDate, Authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/` + `${dateStamp}/us-east-2/sts/aws4_request, SignedHeaders=host;` + `x-amz-date;x-amz-security-token, Signature=${signature}`, host: 'sts.us-east-2.amazonaws.com', 'x-amz-security-token': token, }, }; }, }, { description: 'signed request when AWS credentials have no token', referenceDate: new Date('2020-08-11T06:55:22.345Z'), instance: new AwsRequestSigner(getCredentialsWithoutToken, 'us-east-2'), originalRequest: { url: 'https://sts.us-east-2.amazonaws.com' + '?Action=GetCallerIdentity&Version=2011-06-15', method: 'POST', }, getSignedRequest: () => { const amzDate = '20200811T065522Z'; const dateStamp = '20200811'; const signature = 'd095ba304919cd0d5570ba8a3787884ee78b860f268ed040ba23831d55536d56'; return { url: 'https://sts.us-east-2.amazonaws.com' + '?Action=GetCallerIdentity&Version=2011-06-15', method: 'POST', headers: { 'x-amz-date': amzDate, Authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/` + `${dateStamp}/us-east-2/sts/aws4_request, SignedHeaders=host;` + `x-amz-date, Signature=${signature}`, host: 'sts.us-east-2.amazonaws.com', }, }; }, }, { description: 'signed POST request with additional headers/body', referenceDate: new Date('2020-08-11T06:55:22.345Z'), instance: new AwsRequestSigner(getCredentials, 'us-east-2'), originalRequest: { url: 'https://dynamodb.us-east-2.amazonaws.com/', method: 'POST', headers: { 'Content-Type': 'application/x-amz-json-1.0', 'x-amz-target': 'DynamoDB_20120810.CreateTable', }, body: JSON.stringify(requestParams), }, getSignedRequest: () => { const amzDate = '20200811T065522Z'; const dateStamp = '20200811'; const signature = 'fdaa5b9cc9c86b80fe61eaf504141c0b3523780349120f2bd8145448456e0385'; return { url: 'https://dynamodb.us-east-2.amazonaws.com/', method: 'POST', headers: { Authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/` + `${dateStamp}/us-east-2/dynamodb/aws4_request, SignedHeaders=` + 'content-type;host;x-amz-date;x-amz-security-token;x-amz-target' + `, Signature=${signature}`, 'Content-Type': 'application/x-amz-json-1.0', host: 'dynamodb.us-east-2.amazonaws.com', 'x-amz-date': amzDate, 'x-amz-security-token': token, 'x-amz-target': 'DynamoDB_20120810.CreateTable', }, body: JSON.stringify(requestParams), }; }, }, { description: 'signed POST request with additional headers/data', referenceDate: new Date('2020-08-11T06:55:22.345Z'), instance: new AwsRequestSigner(getCredentials, 'us-east-2'), originalRequest: { url: 'https://dynamodb.us-east-2.amazonaws.com/', method: 'POST', headers: { 'Content-Type': 'application/x-amz-json-1.0', 'x-amz-target': 'DynamoDB_20120810.CreateTable', }, data: requestParams, }, getSignedRequest: () => { const amzDate = '20200811T065522Z'; const dateStamp = '20200811'; const signature = 'fdaa5b9cc9c86b80fe61eaf504141c0b3523780349120f2bd8145448456e0385'; return { url: 'https://dynamodb.us-east-2.amazonaws.com/', method: 'POST', headers: { Authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/` + `${dateStamp}/us-east-2/dynamodb/aws4_request, SignedHeaders=` + 'content-type;host;x-amz-date;x-amz-security-token;x-amz-target' + `, Signature=${signature}`, 'Content-Type': 'application/x-amz-json-1.0', host: 'dynamodb.us-east-2.amazonaws.com', 'x-amz-date': amzDate, 'x-amz-security-token': token, 'x-amz-target': 'DynamoDB_20120810.CreateTable', }, body: JSON.stringify(requestParams), }; }, }, ]; getRequestOptionsTests.forEach(test => { it(`should resolve with the expected ${test.description}`, async () => { clock.tick(test.referenceDate.getTime()); const actualSignedRequest = await test.instance.getRequestOptions( test.originalRequest ); assert.deepStrictEqual(actualSignedRequest, test.getSignedRequest()); }); }); it('should reject with underlying getCredentials error', async () => { const awsRequestSigner = new AwsRequestSigner( getCredentialsUnsuccessful, 'us-east-2' ); const options: GaxiosOptions = { url: 'https://sts.us-east-2.amazonaws.com' + '?Action=GetCallerIdentity&Version=2011-06-15', method: 'POST', }; await assert.rejects( awsRequestSigner.getRequestOptions(options), awsError ); }); it('should reject when no URL is available', async () => { const invalidOptionsError = new Error( '"url" is required in "amzOptions"' ); const awsRequestSigner = new AwsRequestSigner( getCredentials, 'us-east-2' ); await assert.rejects( awsRequestSigner.getRequestOptions({}), invalidOptionsError ); }); }); });
the_stack
import { setImmediate } from "../../deps.ts"; import { Route } from "./route.ts"; import { Layer } from "./layer.ts"; import { merge } from "../utils/merge.ts"; import { parseUrl } from "../utils/parseUrl.ts"; import { methods } from "../methods.ts"; import type { NextFunction, OpineRequest, OpineResponse, Router as IRouter, RouterConstructor, } from "../types.ts"; const objectRegExp = /^\[object (\S+)\]$/; const setPrototypeOf = Object.setPrototypeOf; /** * Initialize a new `Router` with the given `options`. * * @param {object} options * @return {Router} which is an callable function * @public */ export const Router: RouterConstructor = function (options: any = {}): any { function router( req: OpineRequest, res: OpineResponse, next: NextFunction, ): void { (router as any).handle(req, res, next); } setPrototypeOf(router, Router); router.params = {}; router._params = [] as any[]; router.caseSensitive = options.caseSensitive; router.mergeParams = options.mergeParams; router.strict = options.strict; router.stack = [] as any[]; return router as IRouter; } as any; /** * Map the given param placeholder `name`(s) to the given callback. * * Parameter mapping is used to provide pre-conditions to routes * which use normalized placeholders. For example a _:user_id_ parameter * could automatically load a user's information from the database without * any additional code, * * The callback uses the same signature as middleware, the only difference * being that the value of the placeholder is passed, in this case the _id_ * of the user. Once the `next()` function is invoked, just like middleware * it will continue on to execute the route, or subsequent parameter functions. * * Just like in middleware, you must either respond to the request or call next * to avoid stalling the request. * * app.param('user_id', function(req, res, next, id){ * User.find(id, function(err, user){ * if (err) { * return next(err); * } else if (!user) { * return next(new Error('failed to load user')); * } * req.user = user; * next(); * }); * }); * * @param {String} name * @param {Function} fn * @return {app} for chaining * @public */ Router.param = function param(name, fn) { // apply param functions var params = this._params; var len = params.length; var ret; // ensure param `name` is a string if (typeof name !== "string") { throw new Error( "invalid param() call for " + name + ", value must be a string", ); } for (var i = 0; i < len; ++i) { if (ret = params[i](name, fn)) { fn = ret; } } // ensure we end up with a // middleware function if ("function" !== typeof fn) { throw new Error("invalid param() call for " + name + ", got " + fn); } (this.params[name] = this.params[name] || []).push(fn); return this; }; /** * Dispatch a req, res into the router. * @private */ Router.handle = function handle( req: OpineRequest, res: OpineResponse, out: NextFunction = () => {}, ) { const self: any = this; let idx = 0; let protohost = getProtohost(req.url) || ""; let removed = ""; let slashAdded = false; let paramcalled = {}; // store options for OPTIONS request // only used if OPTIONS request let options: any[] = []; // middleware and routes let stack = self.stack; // manage inter-router variables let parentParams = req.params; let parentUrl = req.baseUrl || ""; let done = (restore as any)(out, req, "baseUrl", "next", "params"); // setup next layer req.next = next; // for options requests, respond with a default if nothing else responds if (req.method === "OPTIONS") { done = wrap(done, function (old: any, err?: any): void { if (err || options.length === 0) { return old(err); } sendOptionsResponse(res, options, old); }); } // setup basic req values req.baseUrl = parentUrl; req.originalUrl = req.originalUrl || req.url; next(); function next(err?: any) { let layerError = err === "route" ? null : err; // remove added slash if (slashAdded) { req.url = req.url.substr(1); slashAdded = false; } // restore altered req.url if (removed.length !== 0) { req.baseUrl = parentUrl; req.url = protohost + removed + req.url.substr(protohost.length); removed = ""; } // signal to exit router if (layerError === "router") { setImmediate(done, null); return; } // no more matching layers if (idx >= stack.length) { setImmediate(done, layerError); return; } // get pathname of request let path = (parseUrl(req) || {}).pathname; if (path == null) { return done(layerError); } // find next matching layer let layer: any; let match: any; let route: any; while (match !== true && idx < stack.length) { layer = stack[idx++]; match = matchLayer(layer, path); route = layer.route; if (typeof match !== "boolean") { // hold on to layerError layerError = layerError || match; } if (match !== true) { continue; } if (!route) { // process non-route handlers normally continue; } if (layerError) { // routes do not match with a pending error match = false; continue; } let method = req.method; let has_method = route._handles_method(method); // build up automatic options response if (!has_method && method === "OPTIONS") { appendMethods(options, route._options()); } // don't even bother matching route if (!has_method && method !== "HEAD") { match = false; continue; } } // no match if (match !== true) { return done(layerError); } // store route for dispatch on change if (route) { req.route = route; } // Capture one-time layer values req.params = self.mergeParams ? mergeParams(layer.params, parentParams) : layer.params; let layerPath = layer.path; // this should be done for the layer self.process_params( layer, paramcalled, req, res, function (err?: any) { if (err) { return next(layerError || err); } if (route) { return layer.handle_request(req, res, next); } trim_prefix(layer, layerError, layerPath, path); }, ); } function trim_prefix( layer: any, layerError: any, layerPath: any, path: any, ) { if (layerPath.length !== 0) { // Validate path breaks on a path separator let c = path[layerPath.length]; if (c && c !== "/" && c !== ".") { return next(layerError); } // Trim off the part of the url that matches the route // middleware (.use stuff) needs to have the path stripped removed = layerPath; req.url = protohost + req.url.substr(protohost.length + removed.length); // Ensure leading slash if (!protohost && req.url[0] !== "/") { req.url = "/" + req.url; slashAdded = true; } // Setup base URL (no trailing slash) req.baseUrl = parentUrl + (removed[removed.length - 1] === "/" ? removed.substring(0, removed.length - 1) : removed); } if (layerError) { layer.handle_error(layerError, req, res, next); } else { layer.handle_request(req, res, next); } } }; /** * Process any parameters for the layer. * @private */ Router.process_params = function process_params( layer: any, called: any, req: OpineRequest, res: OpineResponse, done: NextFunction, ) { let params = this.params; // captured parameters from the layer, keys and values let keys = layer.keys; // fast track if (!keys || keys.length === 0) { return done(); } let i = 0; let name; let paramIndex = 0; let key: any; let paramVal: any; let paramCallbacks: any; let paramCalled: any; // process params in order // param callbacks can be async function param(err?: any): any { if (err) { return done(err); } if (i >= keys.length) { return done(); } paramIndex = 0; key = keys[i++]; name = key.name; paramVal = req.params[name]; paramCallbacks = params[name]; paramCalled = called[name]; if (paramVal === undefined || !paramCallbacks) { return param(); } // param previously called with same value or error occurred if ( paramCalled && (paramCalled.match === paramVal || (paramCalled.error && paramCalled.error !== "route")) ) { // restore value req.params[name] = paramCalled.value; // next param return param(paramCalled.error); } called[name] = paramCalled = { error: null, match: paramVal, value: paramVal, }; paramCallback(); } // single param callbacks function paramCallback(err?: any) { let fn = paramCallbacks[paramIndex++]; // store updated value paramCalled.value = req.params[key.name]; if (err) { // store error paramCalled.error = err; param(err); return; } if (!fn) return param(); try { fn(req, res, paramCallback, paramVal, key.name); } catch (e) { paramCallback(e); } } param(); }; /** * Use the given middleware function, with optional path, defaulting to "/". * * Use (like `.all`) will run for any http METHOD, but it will not add * handlers for those methods so OPTIONS requests will not consider `.use` * functions even if they could respond. * * The other difference is that _route_ path is stripped and not visible * to the handler function. The main effect of this feature is that mounted * handlers can operate without any code changes regardless of the "prefix" * pathname. * * @public */ Router.use = function use(fn: any) { let offset = 0; let path = "/"; // default path to '/' // disambiguate router.use([fn]) if (typeof fn !== "function") { let arg: any = fn; while (Array.isArray(arg) && arg.length !== 0) { arg = arg[0]; } // first arg is the path if (typeof arg !== "function") { offset = 1; path = fn; } } let callbacks = Array.prototype.slice.call(arguments, offset).flat(1); if (callbacks.length === 0) { throw new TypeError("Router.use() requires a middleware function"); } for (let i = 0; i < callbacks.length; i++) { let fn = callbacks[i]; if (typeof fn !== "function") { throw new TypeError( "Router.use() requires a middleware function but got a " + gettype(fn), ); } let layer = new (Layer as any)(path, { sensitive: this.caseSensitive, strict: false, end: false, }, fn); layer.route = undefined; this.stack.push(layer); } return this; }; /** * Create a new Route for the given path. * * Each route contains a separate middleware stack and VERB handlers. * * See the Route api documentation for details on adding handlers * and middleware to routes. * * @param {String} path * @return {Route} * @public */ Router.route = function route(path: string) { let route = new Route(path); let layer = new Layer(path, { sensitive: this.caseSensitive, strict: this.strict, end: true, }, route.dispatch.bind(route)); layer.route = route; this.stack.push(layer); return route; }; // create Router#VERB functions methods.concat("all").forEach(function (method) { (Router as any)[method] = function (path: string) { let route = this.route(path); route[method].apply(route, Array.prototype.slice.call(arguments, 1)); return this; }; }); // append methods to a list of methods function appendMethods(list: any, addition: any) { for (let i = 0; i < addition.length; i++) { let method = addition[i]; if (list.indexOf(method) === -1) { list.push(method); } } } // Get get protocol + host for a URL function getProtohost(url: string) { if (typeof url !== "string" || url.length === 0 || url[0] === "/") { return undefined; } let searchIndex = url.indexOf("?"); let pathLength = searchIndex !== -1 ? searchIndex : url.length; let fqdnIndex = url.substr(0, pathLength).indexOf("://"); return fqdnIndex !== -1 ? url.substr(0, url.indexOf("/", 3 + fqdnIndex)) : undefined; } // get type for error message function gettype(obj: any) { let type = typeof obj; if (type !== "object") { return type; } // inspect [[Class]] for objects return Object.prototype.toString.call(obj) .replace(objectRegExp, "$1"); } /** * Match path to a layer. * * @param {Layer} layer * @param {string} path * @private */ function matchLayer(layer: any, path: string) { try { return layer.match(path); } catch (err) { return err; } } // merge params with parent params function mergeParams(params: any, parent: any) { if (typeof parent !== "object" || !parent) { return params; } // make copy of parent for base let obj = merge({}, parent); // simple non-numeric merging if (!(0 in params) || !(0 in parent)) { return merge(obj, params); } let i = 0; let o = 0; // determine numeric gaps while (i in params) { i++; } while (o in parent) { o++; } // offset numeric indices in params before merge for (i--; i >= 0; i--) { params[i + o] = params[i]; // create holes for the merge when necessary if (i < o) { delete params[i]; } } return merge(obj, params); } // restore obj props after function function restore(fn: Function, obj: any) { let props = new Array(arguments.length - 2); let vals = new Array(arguments.length - 2); for (let i = 0; i < props.length; i++) { props[i] = arguments[i + 2]; vals[i] = obj[props[i]]; } return function (this: any) { // restore vals for (let i = 0; i < props.length; i++) { obj[props[i]] = vals[i]; } return fn.apply(this, arguments); }; } // send an OPTIONS response function sendOptionsResponse( res: OpineResponse, options: any, next: NextFunction, ) { try { let body = options.join(","); res.set("Allow", body); res.send(body); } catch (err) { next(err); } } // wrap a function function wrap(old: any, fn: any) { return function proxy(this: any) { let args = new Array(arguments.length + 1); args[0] = old; for (let i = 0, len = arguments.length; i < len; i++) { args[i + 1] = arguments[i]; } fn.apply(this, args); }; }
the_stack
'use strict'; import { HoverProvider, TextDocument, Position, CancellationToken, Hover, MarkdownString, ExtensionContext, window, TextEditor, Range, TextEditorDecorationType, Location } from 'vscode'; import { SymbolUtils, VariableInfo, SymbolInfo } from './SymbolUtils'; import { CodePddlWorkspace } from '../workspace/CodePddlWorkspace'; import { ModelHierarchy, VariableReferenceInfo, VariableReferenceKind, VariableEffectReferenceInfo } from 'pddl-workspace'; import { PDDL } from 'pddl-workspace'; import { DomainInfo } from 'pddl-workspace'; import { Variable } from 'pddl-workspace'; import { toPosition, toURI } from '../utils'; import { isPddl } from '../workspace/workspaceUtils'; import { parser } from 'pddl-workspace'; import { PddlWorkspace } from 'pddl-workspace'; export class ModelHierarchyProvider implements HoverProvider { private symbolUtils: SymbolUtils; private dirtyEditors = new Set<TextEditor>(); private timeout: NodeJS.Timer | undefined = undefined; private decorations = new Map<TextEditor, TextEditorDecorationType[]>(); constructor(context: ExtensionContext, private readonly pddlWorkspace: CodePddlWorkspace) { this.symbolUtils = new SymbolUtils(pddlWorkspace); window.onDidChangeActiveTextEditor(editor => this.scheduleDecoration(editor), null, context.subscriptions); pddlWorkspace.pddlWorkspace.on(PddlWorkspace.UPDATED, updatedFile => { if (updatedFile instanceof DomainInfo) { window.visibleTextEditors .filter(editor => editor.document.uri.toString() === updatedFile.fileUri.toString()) .forEach(editor => this.scheduleDecoration(editor)); } }); window.visibleTextEditors.forEach(editor => this.scheduleDecoration(editor)); } scheduleDecoration(editor: TextEditor | undefined): void { if (editor && editor.visibleRanges.length && isPddl(editor.document)) { this.triggerDecorationRefresh(editor); } } private triggerDecorationRefresh(editor: TextEditor): void { this.dirtyEditors.add(editor); if (this.timeout) { clearTimeout(this.timeout); this.timeout = undefined; } this.timeout = setTimeout(() => this.refreshDirtyEditors(), 1000); } private refreshDirtyEditors(): void { const currentlyDirtyEditors = new Set<TextEditor>(this.dirtyEditors); this.dirtyEditors.clear(); currentlyDirtyEditors .forEach(editor => this.updateDecoration(editor)); } private updateDecoration(editor: TextEditor): void { if (editor.visibleRanges.length === 0) { return; } const fileInfo = this.pddlWorkspace.pddlWorkspace.getFileInfo(toURI(editor.document.uri)); if (fileInfo instanceof DomainInfo) { const domainInfo = fileInfo as DomainInfo; const allVariables = domainInfo.getFunctions().concat(domainInfo.getPredicates()); //todo: add derived variables this.decorations.get(editor)?.forEach(d => d.dispose()); this.decorations.delete(editor); const decorations = allVariables.map(v => this.decorateVariable(v, editor, domainInfo)) .filter(dec => !!dec) .map(dec => dec!); this.decorations.set(editor, decorations); } } decorateVariable(variable: Variable, editor: TextEditor, domainInfo: DomainInfo): TextEditorDecorationType | undefined { const symbolInfo = this.symbolUtils.getSymbolInfo(editor.document, toPosition(variable.getLocation().start).translate({ characterDelta: 1 })); if (symbolInfo instanceof VariableInfo) { const references = this.symbolUtils.findSymbolReferences(editor.document, symbolInfo, false); const pddlFileInfo = this.pddlWorkspace.getFileInfo(editor.document); if (!pddlFileInfo) { return undefined; } if (references !== undefined && domainInfo !== undefined) { const referenceInfos = this.getReferences(references, domainInfo, symbolInfo, editor.document); const readCount = referenceInfos .filter(ri => [VariableReferenceKind.READ, VariableReferenceKind.READ_OR_WRITE].includes(ri.kind)) .length; const writeReferences = referenceInfos .filter(ri => [VariableReferenceKind.WRITE, VariableReferenceKind.READ_OR_WRITE].includes(ri.kind)); const writeEffectReferences = writeReferences .filter(ri => (ri instanceof VariableEffectReferenceInfo)) .map(ri => ri as VariableEffectReferenceInfo); const increaseCount = writeEffectReferences.filter(ri => ri.effect instanceof parser.IncreaseEffect).length; const decreaseCount = writeEffectReferences.filter(ri => ri.effect instanceof parser.DecreaseEffect).length; const scaleUpCount = writeEffectReferences.filter(ri => ri.effect instanceof parser.ScaleUpEffect).length; const scaleDownCount = writeEffectReferences.filter(ri => ri.effect instanceof parser.ScaleDownEffect).length; const assignCount = writeEffectReferences.filter(ri => ri.effect instanceof parser.AssignEffect).length; const makeTrueCount = writeEffectReferences.filter(ri => ri.effect instanceof parser.MakeTrueEffect).length; const makeFalseCount = writeEffectReferences.filter(ri => ri.effect instanceof parser.MakeFalseEffect).length; const decorationText: string[] = []; const hoverText: string[] = []; if (readCount) { decorationText.push(`${readCount}👁`); hoverText.push(`${readCount}x read`); } if (increaseCount) { decorationText.push(`${increaseCount}↗`); hoverText.push(`${increaseCount}x increased`); } if (decreaseCount) { decorationText.push(`${decreaseCount}↘`); hoverText.push(`${decreaseCount}x decreased`); } if (scaleUpCount) { decorationText.push(`${scaleUpCount}⤴`); hoverText.push(`${scaleUpCount}x scaled up`); } if (scaleDownCount) { decorationText.push(`${scaleDownCount}⤵`); hoverText.push(`${scaleDownCount}x scaled down`); } if (assignCount) { decorationText.push(`${assignCount}≔`); hoverText.push(`${assignCount}x assigned`); } if (makeTrueCount) { decorationText.push(`${makeTrueCount}☑`);// ⊨ hoverText.push(`${makeTrueCount}x made true`); } if (makeFalseCount) { decorationText.push(`${makeFalseCount}☒`);// ⊭ hoverText.push(`${makeFalseCount}x made false`); } const rest = referenceInfos.length - readCount - increaseCount - decreaseCount - scaleUpCount - scaleDownCount - assignCount - makeTrueCount - makeFalseCount; if (rest) { decorationText.push(`${rest}?`); hoverText.push(`${rest}x unrecognized`); } return this.decorate(editor, decorationText.join(' '), hoverText.join('\n\n'), symbolInfo.location.range); } } return undefined; } decorate(editor: TextEditor, decorationText: string, hoverText: string, range: Range): TextEditorDecorationType { const decorationType = window.createTextEditorDecorationType({ after: { contentText: decorationText, textDecoration: "; color: gray; margin-left: 10px" //font-size: 10px; ; opacity: 0.5 } }); editor.setDecorations(decorationType, [{ range: range, hoverMessage: hoverText }]); return decorationType; } async provideHover(document: TextDocument, position: Position, token: CancellationToken): Promise<Hover | undefined> { if (token.isCancellationRequested) { return undefined; } await this.symbolUtils.assertFileParsed(document); const symbolInfo = this.symbolUtils.getSymbolInfo(document, position); if (symbolInfo instanceof VariableInfo) { const references = this.symbolUtils.findSymbolReferences(document, symbolInfo, false); const pddlFileInfo = this.pddlWorkspace.getFileInfo(document); if (!pddlFileInfo) { return undefined; } const domainInfo = this.pddlWorkspace.pddlWorkspace.asDomain(pddlFileInfo); if (references !== undefined && domainInfo !== undefined) { const referenceInfos = this.getReferences(references, domainInfo, symbolInfo, document); const documentation = this.createReferenceDocumentation(referenceInfos); return new Hover(documentation, symbolInfo.hover.range); } else { return undefined; } } else { return undefined; } } private getReferences(references: Location[], domainInfo: DomainInfo, symbolInfo: SymbolInfo, document: TextDocument): VariableReferenceInfo[] { return references .filter(r => r.uri.toString() === domainInfo.fileUri.toString()) // limit this to the domain file only .map(r => new ModelHierarchy(domainInfo).getReferenceInfo((symbolInfo as VariableInfo).variable, document.offsetAt(r.range.start) + 1)); } private createReferenceDocumentation(referenceInfos: VariableReferenceInfo[]): MarkdownString { const documentation = new MarkdownString(`**References**\n`); this.addAccessKindDocumentation(documentation, referenceInfos, 'Read', VariableReferenceKind.READ); this.addAccessKindDocumentation(documentation, referenceInfos, 'Write', VariableReferenceKind.WRITE); this.addAccessKindDocumentation(documentation, referenceInfos, 'Read or write', VariableReferenceKind.READ_OR_WRITE); this.addAccessKindDocumentation(documentation, referenceInfos, 'Unrecognized', VariableReferenceKind.UNRECOGNIZED); if (referenceInfos.length === 0) { documentation.appendText('\nNo references.'); } return documentation; } private addAccessKindDocumentation(documentation: MarkdownString, referenceInfos: VariableReferenceInfo[], label: string, kind: VariableReferenceKind): void { const accessReferences = referenceInfos.filter(ri => ri.kind === kind); if (accessReferences.length > 0) { documentation.appendText('\n' + label + ' access:\n'); this.createAccessKindDocumentation(accessReferences, documentation); } } private createAccessKindDocumentation(referenceInfos: VariableReferenceInfo[], documentation: MarkdownString): void { referenceInfos.forEach(ri => documentation.appendMarkdown(`\n- \`${ri.structure.getNameOrEmpty()}\` ${ri.getTimeQualifier()} ${ri.part}`).appendCodeblock(ri.relevantCode ?? '', PDDL)); } }
the_stack
import {ApiResult, ErrorResponse, SuccessResponse} from "helpers/api_request_builder"; import m from "mithril"; import {Pipeline, PipelineGroups} from "models/internal_pipeline_structure/pipeline_structure"; import data from "models/new-environments/spec/test_data"; import {Origin, OriginType} from "models/origin"; import {PipelineConfig} from "models/pipeline_configs/pipeline_config"; import {ModalState} from "views/components/modal"; import {ModalManager} from "views/components/modal/modal_manager"; import { ApiService, ClonePipelineConfigModal, CreatePipelineGroupModal, DeletePipelineGroupModal, ExtractTemplateModal, MoveConfirmModal } from "views/pages/admin_pipelines/modals"; import {TestHelper} from "views/pages/spec/test_helper"; describe("CreatePipelineGroupModal", () => { let modal: CreatePipelineGroupModal; let callback: (groupName: string) => void; let modalTestHelper: TestHelper; beforeEach(() => { callback = jasmine.createSpy("callback"); modal = new CreatePipelineGroupModal(callback); modal.render(); m.redraw.sync(); modalTestHelper = new TestHelper().forModal(); }); afterEach(() => { ModalManager.closeAll(); }); it("should render modal", () => { expect(modal).toContainTitle("Create new pipeline group"); expect(modal).toContainButtons(["Create"]); modalTestHelper.oninput(modalTestHelper.byTestId("form-field-input-pipeline-group-name"), "new-pipeline-group"); modalTestHelper.clickButtonOnActiveModal(`[data-test-id="button-create"]`); expect(callback).toHaveBeenCalledWith("new-pipeline-group"); }); }); describe("ClonePipelineConfigModal", () => { const successCallback: (newPipelineName: string) => void = jasmine.createSpy("successCallback"); afterEach(() => { ModalManager.closeAll(); }); function spyForPipelineGet(pipelineName: string, modal: ClonePipelineConfigModal) { spyOn(PipelineConfig, "get").and.callFake(() => { return new Promise<ApiResult<string>>((resolve) => { const pipelineConfig = new PipelineConfig(pipelineName); pipelineConfig.origin(new Origin(OriginType.GoCD)); modal.modalState = ModalState.OK; resolve(ApiResult.success(JSON.stringify(pipelineConfig.toPutApiPayload()), 200, new Map())); }); }); } it("should render modal", () => { const dummyService = new class implements ApiService { performOperation(onSuccess: (data: SuccessResponse<string>) => void, onError: (message: ErrorResponse) => void, data?: { [key: string]: any }): Promise<void> { onSuccess({body: "some msg"}); expect(Object.keys(data!)).toEqual(['group', 'pipeline']); expect(data!.group).toEqual('new-pipeline-group'); return Promise.resolve(); } }(); const modal = new ClonePipelineConfigModal(new Pipeline("blah"), successCallback, dummyService); spyForPipelineGet("blah", modal); modal.render(); m.redraw.sync(); const modalTestHelper = new TestHelper().forModal(); expect(modal).toContainTitle(`Clone pipeline - blah`); expect(modal).toContainButtons(["Cancel", "Clone"]); modalTestHelper.oninput(modalTestHelper.byTestId("form-field-input-new-pipeline-name"), "new-pipeline-name"); modalTestHelper.oninput(modalTestHelper.byTestId("form-field-input-pipeline-group-name"), "new-pipeline-group"); modalTestHelper.clickButtonOnActiveModal(`[data-test-id="button-clone"]`); expect(successCallback).toHaveBeenCalledWith("new-pipeline-name"); }); it('should render error message if clone operation fails', () => { const dummyService = new class implements ApiService { performOperation(onSuccess: (data: SuccessResponse<string>) => void, onError: (message: ErrorResponse) => void): Promise<void> { onError({message: "some msg", body: '{"message": "some major error"}'}); return Promise.reject(); } }(); const modal = new ClonePipelineConfigModal(new Pipeline("blah"), successCallback, dummyService); spyForPipelineGet("blah", modal); modal.render(); m.redraw.sync(); const modalTestHelper = new TestHelper().forModal(); expect(modalTestHelper.byTestId('flash-message-alert')).not.toBeInDOM(); modalTestHelper.oninput(modalTestHelper.byTestId("form-field-input-new-pipeline-name"), "new-pipeline-name"); modalTestHelper.oninput(modalTestHelper.byTestId("form-field-input-pipeline-group-name"), "new-pipeline-group"); modalTestHelper.clickButtonOnActiveModal(`[data-test-id="button-clone"]`); expect(modalTestHelper.byTestId('flash-message-alert')).toBeInDOM(); expect(modal).toContainError("some major error"); }); }); describe("MoveConfirmModal", () => { const callback: (msg: m.Children) => void = jasmine.createSpy("callback"); const pipelineGroupsJSON = data.pipeline_groups_json(); const pipelineGroups = PipelineGroups.fromJSON(pipelineGroupsJSON.groups); afterEach(() => { ModalManager.closeAll(); }); function spyForPipelineGet(modal: MoveConfirmModal) { spyOn(PipelineConfig, "get").and.callFake(() => { return new Promise<ApiResult<string>>((resolve) => { const pipelineConfig = new PipelineConfig(pipelineGroups[0].pipelines()[0].name()); pipelineConfig.origin(new Origin(OriginType.GoCD)); modal.modalState = ModalState.OK; resolve(ApiResult.success(JSON.stringify(pipelineConfig.toPutApiPayload()), 200, new Map())); }); }); } it("should render modal", () => { const dummyService = new class implements ApiService { performOperation(onSuccess: (data: SuccessResponse<string>) => void, onError: (message: ErrorResponse) => void): Promise<void> { onSuccess({body: "some msg"}); return Promise.resolve(); } }(); const modal = new MoveConfirmModal(pipelineGroups, pipelineGroups[0], pipelineGroups[0].pipelines()[0], callback, dummyService); spyForPipelineGet(modal); modal.render(); m.redraw.sync(); const modalTestHelper = new TestHelper().forModal(); expect(modal).toContainTitle(`Move pipeline ${pipelineGroups[0].pipelines()[0].name()}`); expect(modal).toContainButtons(["Cancel", "Move"]); const targetPipelineGroup = pipelineGroupsJSON.groups[1].name; expect(modalTestHelper.textAll("option")).toEqual([targetPipelineGroup]); modalTestHelper.onchange(modalTestHelper.byTestId("move-pipeline-group-selection"), targetPipelineGroup); modalTestHelper.clickButtonOnActiveModal(`button[data-test-id="button-move"]`); expect(callback).toHaveBeenCalled(); }); it("should render error if move operation fails", () => { const dummyService = new class implements ApiService { performOperation(onSuccess: (data: SuccessResponse<string>) => void, onError: (message: ErrorResponse) => void): Promise<void> { onError({message: "some msg", body: '{"message": "some major error"}'}); return Promise.resolve(); } }(); const modal = new MoveConfirmModal(pipelineGroups, pipelineGroups[0], pipelineGroups[0].pipelines()[0], callback, dummyService); spyForPipelineGet(modal); modal.render(); m.redraw.sync(); const modalTestHelper = new TestHelper().forModal(); expect(modal).toContainTitle(`Move pipeline ${pipelineGroups[0].pipelines()[0].name()}`); expect(modal).toContainButtons(["Cancel", "Move"]); const targetPipelineGroup = pipelineGroupsJSON.groups[1].name; expect(modalTestHelper.textAll("option")).toEqual([targetPipelineGroup]); modalTestHelper.onchange(modalTestHelper.byTestId("move-pipeline-group-selection"), targetPipelineGroup); modalTestHelper.clickButtonOnActiveModal(`button[data-test-id="button-move"]`); expect(modalTestHelper.byTestId('flash-message-alert')).toBeInDOM(); expect(modal).toContainError("some major error"); }); }); describe("ExtractTemplateModal", () => { let modal: ExtractTemplateModal; let callback: (templateName: string) => void; let modalTestHelper: TestHelper; beforeEach(() => { callback = jasmine.createSpy("callback"); modal = new ExtractTemplateModal("foo", callback); modal.render(); m.redraw.sync(); modalTestHelper = new TestHelper().forModal(); }); afterEach(() => { ModalManager.closeAll(); }); it("should render modal", () => { expect(modal).toContainTitle(`Extract template from pipeline foo`); expect(modal).toContainButtons(["Extract template"]); modalTestHelper.oninput(modalTestHelper.byTestId("form-field-input-new-template-name"), "new-template"); modalTestHelper.clickButtonOnActiveModal(`[data-test-id="button-extract-template"]`); expect(callback).toHaveBeenCalledWith("new-template"); }); }); describe('DeletePipelinGroupModalSpec', () => { let modal: DeletePipelineGroupModal; const successCallBack: (msg: m.Children) => void = jasmine.createSpy("successCallBack"); afterEach(() => { ModalManager.closeAll(); }); it('should render modal', () => { const dummyService = new class implements ApiService { performOperation(onSuccess: (data: SuccessResponse<string>) => void, onError: (message: ErrorResponse) => void): Promise<void> { onSuccess({body: "some msg"}); return Promise.resolve(); } }(); modal = new DeletePipelineGroupModal("pipeline-grp-name", successCallBack, dummyService); modal.render(); m.redraw.sync(); const modalTestHelper: TestHelper = new TestHelper().forModal(); expect(modal).toContainTitle("Are you sure?"); expect(modal).toContainButtons(["No", "Yes Delete"]); modalTestHelper.clickButtonOnActiveModal(`[data-test-id="button-delete"]`); expect(successCallBack).toHaveBeenCalled(); }); it('should render error message if an error occurs', () => { const dummyService = new class implements ApiService { performOperation(onSuccess: (data: SuccessResponse<string>) => void, onError: (message: ErrorResponse) => void): Promise<void> { onError({message: 'some error', body: '{"message": "some major error"}'}); return Promise.reject(); } }(); modal = new DeletePipelineGroupModal("pipeline-grp-name", successCallBack, dummyService); modal.render(); m.redraw.sync(); const modalTestHelper: TestHelper = new TestHelper().forModal(); modalTestHelper.clickButtonOnActiveModal(`[data-test-id="button-delete"]`); expect(modal).toContainError("some major error"); expect(modal).toContainButtons(["OK"]); }); });
the_stack
import { CancellationToken } from 'vs/base/common/cancellation'; import { FuzzyScore } from 'vs/base/common/filters'; import { Iterable } from 'vs/base/common/iterator'; import { IDisposable, RefCountedDisposable } from 'vs/base/common/lifecycle'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { EditorOption, FindComputedEditorOptionValueById } from 'vs/editor/common/config/editorOptions'; import { ISingleEditOperation } from 'vs/editor/common/core/editOperation'; import { IPosition, Position } from 'vs/editor/common/core/position'; import { IRange, Range } from 'vs/editor/common/core/range'; import { IWordAtPosition } from 'vs/editor/common/core/wordHelper'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { Command, CompletionItemProvider, CompletionTriggerKind, InlineCompletion, InlineCompletionContext, InlineCompletions, InlineCompletionsProvider } from 'vs/editor/common/languages'; import { ITextModel } from 'vs/editor/common/model'; import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures'; import { CompletionItemInsertTextRule } from 'vs/editor/common/standalone/standaloneEnums'; import { CompletionModel, LineContext } from 'vs/editor/contrib/suggest/browser/completionModel'; import { CompletionItem, CompletionItemModel, CompletionOptions, provideSuggestionItems, QuickSuggestionsOptions } from 'vs/editor/contrib/suggest/browser/suggest'; import { ISuggestMemoryService } from 'vs/editor/contrib/suggest/browser/suggestMemory'; import { WordDistance } from 'vs/editor/contrib/suggest/browser/wordDistance'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; class SuggestInlineCompletion implements InlineCompletion { constructor( readonly range: IRange, readonly insertText: string | { snippet: string }, readonly filterText: string, readonly additionalTextEdits: ISingleEditOperation[] | undefined, readonly command: Command | undefined, readonly completion: CompletionItem, ) { } } class InlineCompletionResults extends RefCountedDisposable implements InlineCompletions<SuggestInlineCompletion> { constructor( readonly model: ITextModel, readonly line: number, readonly word: IWordAtPosition, readonly completionModel: CompletionModel, completions: CompletionItemModel, @ISuggestMemoryService private readonly _suggestMemoryService: ISuggestMemoryService, ) { super(completions.disposable); } canBeReused(model: ITextModel, line: number, word: IWordAtPosition) { return this.model === model // same model && this.line === line && this.word.word.length > 0 && this.word.startColumn === word.startColumn && this.word.endColumn < word.endColumn // same word && this.completionModel.incomplete.size === 0; // no incomplete results } get items(): SuggestInlineCompletion[] { const result: SuggestInlineCompletion[] = []; // Split items by preselected index. This ensures the memory-selected item shows first and that better/worst // ranked items are before/after const { items } = this.completionModel; const selectedIndex = this._suggestMemoryService.select(this.model, { lineNumber: this.line, column: this.word.endColumn + this.completionModel.lineContext.characterCountDelta }, items); const first = Iterable.slice(items, selectedIndex); const second = Iterable.slice(items, 0, selectedIndex); let resolveCount = 5; for (const item of Iterable.concat(first, second)) { if (item.score === FuzzyScore.Default) { // skip items that have no overlap continue; } const range = new Range( item.editStart.lineNumber, item.editStart.column, item.editInsertEnd.lineNumber, item.editInsertEnd.column + this.completionModel.lineContext.characterCountDelta // end PLUS character delta ); const insertText = item.completion.insertTextRules && (item.completion.insertTextRules & CompletionItemInsertTextRule.InsertAsSnippet) ? { snippet: item.completion.insertText } : item.completion.insertText; result.push(new SuggestInlineCompletion( range, insertText, item.filterTextLow ?? item.labelLow, item.completion.additionalTextEdits, item.completion.command, item )); // resolve the first N suggestions eagerly if (resolveCount-- >= 0) { item.resolve(CancellationToken.None); } } return result; } } export class SuggestInlineCompletions implements InlineCompletionsProvider<InlineCompletionResults> { private _lastResult?: InlineCompletionResults; constructor( private readonly _getEditorOption: <T extends EditorOption>(id: T, model: ITextModel) => FindComputedEditorOptionValueById<T>, @ILanguageFeaturesService private readonly _languageFeatureService: ILanguageFeaturesService, @IClipboardService private readonly _clipboardService: IClipboardService, @ISuggestMemoryService private readonly _suggestMemoryService: ISuggestMemoryService, ) { } async provideInlineCompletions(model: ITextModel, position: Position, context: InlineCompletionContext, token: CancellationToken): Promise<InlineCompletionResults | undefined> { if (context.selectedSuggestionInfo) { return; } const config = this._getEditorOption(EditorOption.quickSuggestions, model); if (QuickSuggestionsOptions.isAllOff(config)) { // quick suggest is off (for this model/language) return; } model.tokenization.tokenizeIfCheap(position.lineNumber); const lineTokens = model.tokenization.getLineTokens(position.lineNumber); const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(position.column - 1 - 1, 0))); if (QuickSuggestionsOptions.valueFor(config, tokenType) !== 'inline') { // quick suggest is off (for this token) return undefined; } // We consider non-empty leading words and trigger characters. The latter only // when no word is being typed (word characters superseed trigger characters) let wordInfo = model.getWordAtPosition(position); let triggerCharacterInfo: { ch: string; providers: Set<CompletionItemProvider> } | undefined; if (!wordInfo?.word) { triggerCharacterInfo = this._getTriggerCharacterInfo(model, position); } if (!wordInfo?.word && !triggerCharacterInfo) { // not at word, not a trigger character return; } // ensure that we have word information and that we are at the end of a word // otherwise we stop because we don't want to do quick suggestions inside words if (!wordInfo) { wordInfo = model.getWordUntilPosition(position); } if (wordInfo.endColumn !== position.column) { return; } let result: InlineCompletionResults; const leadingLineContents = model.getValueInRange(new Range(position.lineNumber, 1, position.lineNumber, position.column)); if (!triggerCharacterInfo && this._lastResult?.canBeReused(model, position.lineNumber, wordInfo)) { // reuse a previous result iff possible, only a refilter is needed // TODO@jrieken this can be improved further and only incomplete results can be updated // console.log(`REUSE with ${wordInfo.word}`); const newLineContext = new LineContext(leadingLineContents, position.column - this._lastResult.word.endColumn); this._lastResult.completionModel.lineContext = newLineContext; this._lastResult.acquire(); result = this._lastResult; } else { // refesh model is required const completions = await provideSuggestionItems( this._languageFeatureService.completionProvider, model, position, new CompletionOptions(undefined, undefined, triggerCharacterInfo?.providers), triggerCharacterInfo && { triggerKind: CompletionTriggerKind.TriggerCharacter, triggerCharacter: triggerCharacterInfo.ch }, token ); let clipboardText: string | undefined; if (completions.needsClipboard) { clipboardText = await this._clipboardService.readText(); } const completionModel = new CompletionModel( completions.items, position.column, new LineContext(leadingLineContents, 0), WordDistance.None, this._getEditorOption(EditorOption.suggest, model), this._getEditorOption(EditorOption.snippetSuggestions, model), { boostFullMatch: false, firstMatchCanBeWeak: false }, clipboardText ); result = new InlineCompletionResults(model, position.lineNumber, wordInfo, completionModel, completions, this._suggestMemoryService); } this._lastResult = result; return result; } handleItemDidShow(_completions: InlineCompletionResults, item: SuggestInlineCompletion): void { item.completion.resolve(CancellationToken.None); } freeInlineCompletions(result: InlineCompletionResults): void { result.release(); } private _getTriggerCharacterInfo(model: ITextModel, position: IPosition) { const ch = model.getValueInRange(Range.fromPositions({ lineNumber: position.lineNumber, column: position.column - 1 }, position)); const providers = new Set<CompletionItemProvider>(); for (const provider of this._languageFeatureService.completionProvider.all(model)) { if (provider.triggerCharacters?.includes(ch)) { providers.add(provider); } } if (providers.size === 0) { return undefined; } return { providers, ch }; } } class EditorContribution implements IEditorContribution { private static _counter = 0; private static _disposable: IDisposable | undefined; constructor( _editor: ICodeEditor, @ILanguageFeaturesService languageFeatureService: ILanguageFeaturesService, @ICodeEditorService editorService: ICodeEditorService, @IInstantiationService instaService: IInstantiationService, ) { // HACK - way to contribute something only once if (++EditorContribution._counter === 1) { const provider = instaService.createInstance( SuggestInlineCompletions, (id, model) => { // HACK - reuse the editor options world outside from a "normal" contribution const editor = editorService.listCodeEditors().find(editor => editor.getModel() === model) ?? _editor; return editor.getOption(id); }, ); EditorContribution._disposable = languageFeatureService.inlineCompletionsProvider.register('*', provider); } } dispose(): void { if (--EditorContribution._counter === 0) { EditorContribution._disposable?.dispose(); EditorContribution._disposable = undefined; } } } registerEditorContribution('suggest.inlineCompletionsProvider', EditorContribution);
the_stack
import { PdfFontStyle } from './enum'; import { IPdfWrapper } from './../../../interfaces/i-pdf-wrapper'; import { IPdfPrimitive } from './../../../interfaces/i-pdf-primitives'; import { IPdfCache } from './../../../interfaces/i-pdf-cache'; import { SizeF } from './../../drawing/pdf-drawing'; import { PdfStringFormat } from './pdf-string-format'; import { PdfStringLayouter, PdfStringLayoutResult } from './string-layouter'; import { PdfFontMetrics } from './pdf-font-metrics'; import { StringTokenizer } from './string-tokenizer'; /** * Defines a particular format for text, including font face, size, and style attributes. * @private */ export abstract class PdfFont implements IPdfWrapper, IPdfCache { //Constants /** * `Multiplier` of the symbol width. * @default 0.001 * @private */ public static readonly charSizeMultiplier : number = 0.001; /** * `Synchronization` object. * @private */ protected static syncObject : Object = new Object(); //Fields /** * `Size` of the font. * @private */ private fontSize : number; /** * `Style` of the font. * @private */ private fontStyle : PdfFontStyle = PdfFontStyle.Regular; /** * `Metrics` of the font. * @private */ private fontMetrics : PdfFontMetrics; /** * PDf `primitive` of the font. * @private */ private pdfFontInternals : IPdfPrimitive; //Constructors /** * Initializes a new instance of the `PdfFont` class. * @private */ protected constructor(size : number) /** * Initializes a new instance of the `PdfFont` class. * @private */ protected constructor(size : number, style : PdfFontStyle) protected constructor(size ?: number, style ?: PdfFontStyle) { if (typeof size === 'number' && typeof style === 'undefined') { this.fontSize = size; } else { this.fontSize = size; this.setStyle(style); } } //Properties /** * Gets the face name of this Font. * @private */ public get name() : string { return this.metrics.name; } /** * Gets the size of this font. * @private */ public get size() : number { return this.fontSize; } /** * Gets the height of the font in points. * @private */ public get height() : number { return this.metrics.getHeight(null); } /** * Gets the style information for this font. * @private */ public get style() : PdfFontStyle { return this.fontStyle; } public set style(value : PdfFontStyle) { this.fontStyle = value; } /** * Gets a value indicating whether this `PdfFont` is `bold`. * @private */ public get bold() : boolean { return ((this.style & PdfFontStyle.Bold) > 0); } /** * Gets a value indicating whether this `PdfFont` has the `italic` style applied. * @private */ public get italic() : boolean { return ((this.style & PdfFontStyle.Italic) > 0); } /** * Gets a value indicating whether this `PdfFont` is `strikeout`. * @private */ public get strikeout() : boolean { return ((this.style & PdfFontStyle.Strikeout) > 0); } /** * Gets a value indicating whether this `PdfFont` is `underline`. * @private */ public get underline() : boolean { return ((this.style & PdfFontStyle.Underline) > 0); } /** * Gets or sets the `metrics` for this font. * @private */ public get metrics() : PdfFontMetrics { return this.fontMetrics; } public set metrics(value : PdfFontMetrics) { this.fontMetrics = value; } // /** // * Gets and Sets the font `internals`. // * @private // */ // public get fontInternal() : IPdfPrimitive { // return this.pdfFontInternals; // } // public set fontInternal(value : IPdfPrimitive) { // this.pdfFontInternals = value; // } //IPdfWrapper Members /** * Gets the `element` representing the font. * @private */ public get element() : IPdfPrimitive { return this.pdfFontInternals; } /* tslint:disable */ //Public methods /** * `Measures` a string by using this font. * @private */ public measureString(text : string) : SizeF /** * `Measures` a string by using this font. * @private */ public measureString(text : string, format : PdfStringFormat) : SizeF /** * `Measures` a string by using this font. * @private */ public measureString(text : string, format : PdfStringFormat, charactersFitted : number, linesFilled : number) : SizeF /** * `Measures` a string by using this font. * @private */ public measureString(text : string, width : number) : SizeF /** * `Measures` a string by using this font. * @private */ public measureString(text : string, width : number, format : PdfStringFormat) : SizeF /** * `Measures` a string by using this font. * @private */ public measureString(text : string, width : number, format : PdfStringFormat, charactersFitted : number, linesFilled : number) : SizeF /** * `Measures` a string by using this font. * @private */ public measureString(text : string, layoutArea : SizeF) : SizeF /** * `Measures` a string by using this font. * @private */ public measureString(text : string, layoutArea : SizeF, format : PdfStringFormat) : SizeF /** * `Measures` a string by using this font. * @private */ public measureString(text : string, layoutArea : SizeF, format : PdfStringFormat, charactersFitted : number, linesFilled : number) : SizeF public measureString(text : string, arg2 ?: PdfStringFormat|number|SizeF, arg3 ?: number|PdfStringFormat, arg4 ?: number, arg5 ?: number) : SizeF { if (typeof text === 'string' && typeof arg2 === 'undefined') { return this.measureString(text, null); } else if (typeof text === 'string' && (arg2 instanceof PdfStringFormat || arg2 == null) && typeof arg3 === 'undefined' && typeof arg4 === 'undefined') { let temparg2 : PdfStringFormat = arg2 as PdfStringFormat; let charactersFitted : number = 0; let linesFilled : number = 0; return this.measureString(text, temparg2, charactersFitted, linesFilled); } else if (typeof text === 'string' && (arg2 instanceof PdfStringFormat || arg2 == null) && typeof arg3 === 'number' && typeof arg4 === 'number') { let temparg2 : PdfStringFormat = arg2 as PdfStringFormat; return this.measureString(text, 0, temparg2, arg3, arg4); // } else if (typeof text === 'string' && typeof arg2 === 'number' && typeof arg3 === 'undefined') { // return this.measureString(text, arg2, null); // } else if (typeof text === 'string' && typeof arg2 === 'number' && (arg3 instanceof PdfStringFormat || arg3 == null) && typeof arg4 === 'undefined' && typeof arg5 === 'undefined') { // let temparg3 : PdfStringFormat = arg3 as PdfStringFormat; // let charactersFitted : number = 0; // let linesFilled : number = 0; // return this.measureString(text, arg2, temparg3, charactersFitted, linesFilled); } else if (typeof text === 'string' && typeof arg2 === 'number' && (arg3 instanceof PdfStringFormat || arg3 == null) && typeof arg4 === 'number' && typeof arg5 === 'number') { let layoutArea : SizeF = new SizeF(arg2, 0); let temparg3 : PdfStringFormat = arg3 as PdfStringFormat; return this.measureString(text, layoutArea, temparg3, arg4, arg5); // } else if (typeof text === 'string' && arg2 instanceof SizeF && typeof arg3 === 'undefined') { // return this.measureString(text, arg2, null); // } else if (typeof text === 'string' && arg2 instanceof SizeF && (arg3 instanceof PdfStringFormat || arg3 == null) && typeof arg4 === 'undefined' && typeof arg5 === 'undefined') { // let temparg3 : PdfStringFormat = arg3 as PdfStringFormat; // let charactersFitted : number = 0; // let linesFilled : number = 0; // return this.measureString(text, arg2, temparg3, charactersFitted, linesFilled); } else { if (text == null) { throw Error(`ArgumentNullException("text")`); } let temparg2 : SizeF = arg2 as SizeF; let temparg3 : PdfStringFormat = arg3 as PdfStringFormat; let layouter : PdfStringLayouter = new PdfStringLayouter(); let result : PdfStringLayoutResult = layouter.layout(text, this, temparg3, temparg2, false, new SizeF(0, 0)); // arg4 = (result.Remainder == null) ? text.length : text.length - result.Remainder.length; arg4 = text.length; arg5 = (result.empty) ? 0 : result.lines.length; return result.actualSize; } } /* tslint:enable */ //IPdfCache Members /** * `Checks` whether the object is similar to another object. * @private */ public equalsTo(obj : IPdfCache) : boolean { let result : boolean = this.equalsToFont(obj as PdfFont); return result; } /** * Returns `internals` of the object. * @private */ public getInternals() : IPdfPrimitive { return this.pdfFontInternals; } /** * Sets `internals` to the object. * @private */ public setInternals(internals : IPdfPrimitive) : void { if (internals == null) { throw new Error('ArgumentNullException:internals'); } this.pdfFontInternals = internals; } // //Implementation /** * `Checks` whether fonts are equals. * @private */ protected abstract equalsToFont(font : PdfFont) : boolean; /** * Returns `width` of the line. * @private */ public abstract getLineWidth(line : string, format : PdfStringFormat) : number; /** * Sets the `style` of the font. * @private */ protected setStyle(style : PdfFontStyle) : void { this.fontStyle = style; } /** * Applies `settings` to the default line width. * @private */ protected applyFormatSettings(line : string, format : PdfStringFormat, width : number) : number { // if (line == null) { // throw new Error(`ArgumentNullException:line`); // } let realWidth : number = width; if (format != null && width > 0) { // Space among characters is not default. if (format.characterSpacing !== 0) { realWidth += (line.length - 1) * format.characterSpacing; } // Space among words is not default. if (format.wordSpacing !== 0) { let symbols : string[] = StringTokenizer.spaces; let whitespacesCount : number = StringTokenizer.getCharsCount(line, symbols); realWidth += whitespacesCount * format.wordSpacing; } } return realWidth; } }
the_stack
import * as React from 'react'; import { Button, Icon, Input } from 'antd'; import { Wrapper, Segment } from 'components'; import { DataGrid } from 'axui-datagrid'; import { IDataGrid } from 'axui-datagrid/common/@types'; import styled from 'styled-components'; // import { debounce } from 'axui-datagrid/utils'; import { arrayTypedData } from './data/arrayTypedData'; const DatagridContainer = styled.div` border: 1px solid #ccc; .ant-input { height: 23px; padding: 2px 5px; } .ant-select { height: 23px; } .ant-select-selection--single { height: 23px; } .ant-select-selection__rendered { line-height: 23px; } .ant-input-number { height: 23px; } .ant-input-number-input { height: 23px; } `; interface IProps {} interface IState { width: number; height: number; scrollTop: number; scrollLeft: number; columns: IDataGrid.IColumn[]; data: IDataGrid.IData; selection: IDataGrid.ISelection; sortInfos: IDataGrid.ISortInfo[]; } class MultiEdit extends React.Component<IProps, IState> { dataGridContainerRef: React.RefObject<HTMLDivElement>; scrollTop: number = 0; scrollContentContainerHeight: number = 0; scrollContentHeight: number = 0; bodyTrHeight: number = 24; selectedIndexes: number[] = []; debouncedOnScroll: any; constructor(props: any) { super(props); const editor: IDataGrid.cellEditorFunction = ({ value, li, item, update, cancel, blur, focus, keyAction, }) => { return ( <Input style={{ width: '100%' }} autoFocus defaultValue={value.v} onBlur={e => { cancel(); }} onKeyDown={e => { if (e.which === 9) { e.preventDefault(); keyAction( 'EDIT_NEXT', value.v !== e.currentTarget.value ? { ...value, changed: e.currentTarget.value } : undefined, { e }, ); } else if (e.which === 27) { e.preventDefault(); cancel(); } else if (e.which === 13) { e.preventDefault(); if (value.v !== e.currentTarget.value) { update({ ...value, changed: e.currentTarget.value }); } else { blur(); } } }} /> ); }; const formatter: IDataGrid.formatterFunction = ({ value, item }) => { return value ? value.v : ''; }; const columns: IDataGrid.ICol[] = [ { key: '0', label: 'column 0', editor: { activeType: 'dblclick', render: editor }, formatter: ({ value }) => value.v, }, { key: '1', label: 'column 1', editor: { activeType: 'dblclick', render: editor }, formatter: ({ value }) => value.v, }, { key: '2', label: 'column 2', editor: { activeType: 'dblclick', render: editor }, formatter, }, { key: '3', label: 'column 3', editor: { activeType: 'dblclick', render: editor }, formatter, }, { key: '4', label: 'column 4', editor: { activeType: 'dblclick', render: editor }, formatter, }, { key: '5', label: 'column 5', editor: { activeType: 'dblclick', render: editor }, formatter, }, { key: '6', label: 'column 6', editor: { activeType: 'dblclick', render: editor }, formatter, }, { key: '7', label: 'column 7', editor: { activeType: 'dblclick', render: editor }, formatter, }, { key: '8', label: 'column 8', editor: { activeType: 'dblclick', render: editor }, formatter, }, { key: '9', label: 'column 9', editor: { activeType: 'dblclick', render: editor }, formatter, }, ]; const selection: IDataGrid.ISelection = { rows: [], cols: [], focusedRow: -1, focusedCol: -1, isEditing: false, }; this.state = { width: 300, height: 300, scrollTop: 0, scrollLeft: 0, columns, data: arrayTypedData, selection, sortInfos: [], }; this.dataGridContainerRef = React.createRef(); } addItem = () => { const { data } = this.state; const dataLength = Object.keys(data).length; const newItem: IDataGrid.IData = { [dataLength]: { type: 'C', value: [ { v: 'J' }, { v: 'A' }, { v: 'N' }, { v: 'G' }, { v: 'S' }, { v: 'E' }, { v: 'O' }, { v: 'W' }, { v: 'O' }, { v: 'O' }, ], }, }; // 그리드의 스크롤을 변경하기 위한 스크롤 포지션 구하기 const scrollTop = this.scrollContentContainerHeight < this.scrollContentHeight ? -this.scrollContentHeight : 0; this.setState({ data: { ...data, ...newItem }, scrollTop, selection: { rows: [dataLength], cols: [0], focusedRow: dataLength, focusedCol: 0, isEditing: true, }, }); }; removeItem = () => { const { selection, data } = this.state; if (selection.rows && selection.rows.length) { const dataLength = Object.keys(data).length; selection.rows.forEach(li => { if (data instanceof Map) { const item = data.get(li); if (item) { if (item.type === 'C') { data.delete(li); } else { item.type = 'D'; } for (let i = li; i < dataLength - 1; i++) { const nextItem = data.get(i + 1); if (nextItem) { data.set(i, nextItem); data.delete(i + 1); } } } } else { const item = data[li]; if (item) { if (item.type === 'C') { delete data[li]; } else { item.type = 'D'; } for (let i = li; i < dataLength - 1; i++) { data[i] = data[i + 1]; delete data[i + 1]; } } } }); this.setState({ data: { ...data } }); } }; onEditItem = (param: IDataGrid.IonEditParam) => { try { const { li, col: { key: colKey = '' } = {}, value } = param; const { data } = this.state; const originalItemType = data[li].type; if (originalItemType === 'C') { const editDataItem: IDataGrid.IDataItem = { ...data[li] }; editDataItem.value[colKey] = { v: value.changed }; this.setState({ data: { ...data, [li]: editDataItem }, }); } else { const editDataItem: IDataGrid.IDataItem = { type: 'U', value: data[li].value, changed: { ...data[li].changed, [colKey]: { v: value.changed } }, }; this.setState({ data: { ...data, [li]: editDataItem }, }); } } catch (e) { console.log(e); } }; onScroll = (param: IDataGrid.IonScrollFunctionParam) => { // console.log('onScroll', param); const { scrollTop, scrollLeft } = param; this.setState({ scrollTop, scrollLeft, }); }; onChangeScrollSize = (param: IDataGrid.IonChangeScrollSizeFunctionParam) => { // console.log('onChangeScrollSize', param); this.scrollContentContainerHeight = param.scrollContentContainerHeight || 0; this.scrollContentHeight = param.scrollContentHeight || 0; this.bodyTrHeight = param.bodyTrHeight || 0; }; onChangeSelection = (param: IDataGrid.IonChangeSelectionParam) => { // console.log('onChangeSelection', param); this.setState({ selection: param }); }; onChangeColumns = (param: IDataGrid.IonChangeColumnParam) => { console.log(param); const { columns } = this.state; const { colGroup = [] } = param; colGroup.forEach(col => { columns[col.colIndex || 0].width = col.width; }); this.setState({ columns }); }; getDataGridContainerRect = (e?: Event) => { if (this.dataGridContainerRef.current) { const { width, } = this.dataGridContainerRef.current.getBoundingClientRect(); this.setState({ width }); } }; onSort = (param: IDataGrid.IonSortParam) => { const { data } = this.state; const { sortInfos } = param; const getValueByKey = function(_item: any, _key: string) { return _item.value[_key].v || ''; }; const newData = Object.values(data) .sort((a, b) => { for (let i = 0; i < sortInfos.length; i++) { let aValue = getValueByKey(a, sortInfos[i].key!); let bValue = getValueByKey(b, sortInfos[i].key!); if (typeof aValue !== typeof bValue) { aValue = '' + aValue; bValue = '' + bValue; } if (aValue < bValue) { return sortInfos[i].orderBy === 'asc' ? -1 : 1; } else if (aValue > bValue) { return sortInfos[i].orderBy === 'asc' ? 1 : -1; } } return 0; }) .reduce((obj, item, idx) => { // convert array to object obj[idx] = item; return obj; }, {}); // console.log(newData); this.setState({ sortInfos, data: newData }); }; componentDidMount() { this.getDataGridContainerRect(); window.addEventListener('resize', this.getDataGridContainerRect, false); } componentWillUnmount() { window.removeEventListener('resize', this.getDataGridContainerRect); } render() { const { width, height, columns, data, scrollTop, scrollLeft, selection, sortInfos, } = this.state; return ( <Wrapper> <Segment padded> <h1>Multi Edit</h1> <div ref={this.dataGridContainerRef}> <DatagridContainer> <DataGrid style={{ fontSize: '12px' }} width={width - 2} height={height - 2} columns={columns} data={data} dataLength={Object.keys(data).length} options={{}} onScroll={this.onScroll} scrollTop={scrollTop} scrollLeft={scrollLeft} onChangeScrollSize={this.onChangeScrollSize} selection={selection} onChangeSelection={this.onChangeSelection} onChangeColumns={this.onChangeColumns} sortInfos={sortInfos} onSort={this.onSort} onEdit={this.onEditItem} /> </DatagridContainer> </div> <div style={{ height: 10 }} /> <Button size="small" onClick={this.addItem}> <Icon type="plus" /> Add item </Button> <Button size="small" onClick={this.removeItem}> <Icon type="minus" /> Remove item </Button> <Button size="small" onClick={() => {}}> Save </Button> <div> <h4>width</h4> <Input value={width} readOnly /> </div> <div> <h4>height</h4> <Input value={height} readOnly /> </div> <div> <h4>scrollTop</h4> <Input value={scrollTop} readOnly /> </div> <div> <h4>selection</h4> <textarea style={{ width: '100%', height: 100 }} value={JSON.stringify(selection)} readOnly /> </div> <div> <h4>columns</h4> <textarea style={{ width: '100%', height: 100 }} value={JSON.stringify(columns)} readOnly /> </div> <div> <h4>data</h4> <textarea style={{ width: '100%', height: 200 }} value={JSON.stringify(data).replace(/},"/g, '},\n"')} readOnly /> </div> </Segment> </Wrapper> ); } } export default MultiEdit;
the_stack
import { createMemoryFs } from '@file-services/memory'; import type { IFileSystem } from '@file-services/types'; import { expect } from 'chai'; import { waitFor } from 'promise-assist'; import { DirectoryProcessService } from '@stylable/cli'; function createSpy<T extends (...args: any[]) => any>(fn?: T) { const spy = (...args: any[]) => { spy.calls.push(args); spy.callCount++; return fn?.(...args); }; spy.calls = [] as unknown[][]; spy.callCount = 0; spy.resetHistory = () => { spy.calls.length = 0; spy.callCount = 0; }; return spy; } const project1 = { '0.template.js': ` const ATemplate = use('./a.template.js'); output(\`0(\${ATemplate}\`); `, 'a.template.js': ` const BTemplate = use('./b.template.js'); const CTemplate = use('./c.template.js'); output(\`A(\${BTemplate},\${CTemplate})\`); `, 'b.template.js': ` const CTemplate = use('./c.template.js'); output(\`B(\${CTemplate})\`); `, 'c.template.js': ` output('C()'); `, }; describe('DirectoryWatchService', () => { describe('Empty project', () => { let fs: IFileSystem; beforeEach(() => { fs = createMemoryFs({ dist: {} }); }); it('should watch added files', async () => { const watcher = new DirectoryProcessService(fs, { watchMode: true, fileFilter: isTemplateFile, processFiles(watcher, affectedFiles) { for (const filePath of affectedFiles) { const { deps, value } = evalTemplate(fs, filePath); writeTemplateOutputToDist(fs, filePath, value); for (const dep of deps) { watcher.registerInvalidateOnChange(dep, filePath); } } }, }); await watcher.init('/'); fs.writeFileSync('/0.template.js', `output('0()')`); await waitFor(() => { // Init file and emit change on new file expect(fs.readFileSync('/dist/0.txt', 'utf8')).to.equal('0()'); }); fs.writeFileSync( '/0.template.js', ` const ATemplate = use('./a.template.js'); output(\`0(\${ATemplate})\`); ` ); await waitFor(() => { expectInvalidationMap(watcher, { '/0.template.js': [], '/a.template.js': ['/0.template.js'], }); }); fs.writeFileSync( '/a.template.js', ` output('A()'); ` ); await waitFor(() => { expect(fs.readFileSync('/dist/a.txt', 'utf8')).to.equal('A()'); expect(fs.readFileSync('/dist/0.txt', 'utf8')).to.equal('0(A())'); }); }); it('should handle directory added after watch started', async () => { const changeSpy = createSpy(); const watcher = new DirectoryProcessService(fs, { watchMode: true, fileFilter: isTemplateFile, processFiles(watcher, affectedFiles, _, changeOrigin) { for (const filePath of affectedFiles) { const { deps, value } = evalTemplate(fs, filePath); writeTemplateOutputToDist(fs, filePath, value); for (const dep of deps) { watcher.registerInvalidateOnChange(dep, filePath); } } changeSpy({ changedFiles: Array.from(affectedFiles), changeOriginPath: changeOrigin?.path, }); }, }); await watcher.init('/'); // Nothing happened expect(changeSpy.callCount, 'not been called').to.equal(0); fs.ensureDirectorySync('test'); // Add file to new added dir fs.writeFileSync('/test/0.template.js', 'output(`0()`)'); await waitFor(() => { expect(changeSpy.callCount, 'called once').to.equal(1); expect(fs.readFileSync('/dist/test/0.txt', 'utf8')).to.equal('0()'); expectInvalidationMap(watcher, { '/test/0.template.js': [], }); }); }); it('should handle delete files', async () => { new DirectoryProcessService(fs, { watchMode: true, fileFilter: isTemplateFile, processFiles(watcher, affectedFiles) { for (const filePath of affectedFiles) { const { deps, value } = evalTemplate(fs, filePath); writeTemplateOutputToDist(fs, filePath, value); for (const dep of deps) { watcher.registerInvalidateOnChange(dep, filePath); } } }, }); fs.writeFileSync('0.template.js', 'output(`0()`)'); await waitFor(() => { expect(fs.readFileSync('/dist/0.txt', 'utf8')).to.equal('0()'); }); fs.unlinkSync('0.template.js'); await waitFor(() => { expect(fs.readFileSync('/dist/0.txt', 'utf8')).to.equal('0()'); }); }); it('should handle delete dirs', async () => { const watcher = new DirectoryProcessService(fs, { watchMode: true, fileFilter: isTemplateFile, processFiles(watcher, affectedFiles) { for (const filePath of affectedFiles) { const { deps, value } = evalTemplate(fs, filePath); writeTemplateOutputToDist(fs, filePath, value); for (const dep of deps) { watcher.registerInvalidateOnChange(dep, filePath); } } }, }); fs.ensureDirectorySync('/test'); fs.writeFileSync('test/0.template.js', 'output(`0()`)'); fs.writeFileSync('test/a.template.js', 'output(`A()`)'); await waitFor(() => { expect(fs.readFileSync('/dist/test/0.txt', 'utf8')).to.equal('0()'); expect(fs.readFileSync('/dist/test/a.txt', 'utf8')).to.equal('A()'); }); fs.removeSync('test'); await waitFor(() => { expectInvalidationMap(watcher, {}); }); }); }); describe('Basic watcher init/change API (project1)', () => { let fs: IFileSystem; beforeEach(() => { fs = createMemoryFs(project1); }); it('should report affectedFiles and no changeOrigin when watch started', async () => { const changeSpy = createSpy(); const watcher = new DirectoryProcessService(fs, { watchMode: true, fileFilter: isTemplateFile, processFiles(_watcher, affectedFiles, _, changeOrigin) { changeSpy({ affectedFiles: Array.from(affectedFiles), changeOriginPath: changeOrigin?.path, }); }, }); await watcher.init('/'); expect(changeSpy.callCount, 'called once').to.equal(1); expect(changeSpy.calls[0], 'called with').to.eql([ { affectedFiles: [ '/0.template.js', '/a.template.js', '/b.template.js', '/c.template.js', ], changeOriginPath: undefined, }, ]); }); it('should allow hooks to fill in the invalidationMap', async () => { const watcher = new DirectoryProcessService(fs, { watchMode: true, fileFilter: isTemplateFile, processFiles(watcher, affectedFiles) { for (const filePath of affectedFiles) { const { deps } = evalTemplate(fs, filePath); for (const depFilePath of deps) { watcher.registerInvalidateOnChange(depFilePath, filePath); } } }, }); await watcher.init('/'); expectInvalidationMap(watcher, { '/0.template.js': [], '/a.template.js': ['/0.template.js'], '/b.template.js': ['/0.template.js', '/a.template.js'], '/c.template.js': ['/0.template.js', '/a.template.js', '/b.template.js'], }); }); it('should report change for all files affected by the changeOrigin', async () => { const changeSpy = createSpy(); const watcher = new DirectoryProcessService(fs, { watchMode: true, fileFilter: isTemplateFile, processFiles(watcher, affectedFiles, _, changeOrigin) { for (const filePath of affectedFiles) { const { deps } = evalTemplate(fs, filePath); for (const dep of deps) { watcher.registerInvalidateOnChange(dep, filePath); } } changeSpy({ affectedFiles: Array.from(affectedFiles), changeOriginPath: changeOrigin?.path, }); }, }); await watcher.init('/'); changeSpy.resetHistory(); await fs.promises.writeFile('/c.template.js', `output('C($)');`); await waitFor(() => { expect(changeSpy.callCount, 'called once').to.equal(1); expect(changeSpy.calls[0], 'called with').to.eql([ { changeOriginPath: '/c.template.js', affectedFiles: [ '/c.template.js', '/0.template.js', '/a.template.js', '/b.template.js', ], }, ]); }); changeSpy.resetHistory(); await fs.promises.writeFile( '/b.template.js', ` /* changed */ const CTemplate = use('./c.template.js'); output(\`B(\${CTemplate})\`); ` ); await waitFor(() => { expect(changeSpy.callCount, 'called once').to.equal(1); expect(changeSpy.calls[0], 'called with').to.eql([ { changeOriginPath: '/b.template.js', affectedFiles: ['/b.template.js', '/0.template.js', '/a.template.js'], }, ]); }); changeSpy.resetHistory(); await fs.promises.writeFile( '/0.template.js', ` /* changed */ const ATemplate = use('./a.template.js'); output(\`0(\${ATemplate}\`); ` ); await waitFor(() => { expect(changeSpy.callCount, 'called once').to.equal(1); expect(changeSpy.calls[0], 'called with').to.eql([ { changeOriginPath: '/0.template.js', affectedFiles: ['/0.template.js'], }, ]); }); }); }); }); function evalTemplate(fs: IFileSystem, filePath: string) { let templateCode = ''; let value = ''; const errors = new Set<string>(); try { templateCode = fs.readFileSync(filePath, 'utf8'); } catch (e) { errors.add((e as Error)?.message); } const deps = new Set<string>(); const output = (_value: string) => { value = _value; }; const use = (filePath: string) => { const resolvedPath = fs.resolve(filePath); const res = evalTemplate(fs, resolvedPath); deps.add(resolvedPath); for (const d of res.deps) { deps.add(d); } for (const e of res.errors) { errors.add(e); } return res.value; }; // eslint-disable-next-line @typescript-eslint/no-implied-eval const compiled = new Function('use', 'output', templateCode); compiled(use, output); return { value, deps, errors }; } function isTemplateFile(filePath: string): boolean { return filePath.endsWith('.template.js'); } function writeTemplateOutputToDist(fs: IFileSystem, filePath: string, value: string) { const outDir = fs.join('dist', fs.dirname(filePath)); fs.ensureDirectorySync(outDir); fs.writeFileSync(fs.join(outDir, fs.basename(filePath, '.template.js') + '.txt'), value); } function expectInvalidationMap( watcher: DirectoryProcessService, expected: Record<string, string[]> ) { const acutal: Record<string, string[]> = {}; for (const [key, invalidationSet] of watcher.invalidationMap) { acutal[key] = Array.from(invalidationSet); } expect(acutal).to.eql(expected); }
the_stack
import * as ethers from 'ethers' import { AbstractContract, expect, BigNumber, RevertError } from './utils' import * as utils from './utils' import { ERC1155MetaMintBurnMock, ERC1155ReceiverMock, ERC1155OperatorMock } from 'src/gen/typechain' // init test wallets from package.json mnemonic import { web3 } from 'hardhat' const { wallet: ownerWallet, provider: ownerProvider, signer: ownerSigner } = utils.createTestWallet(web3, 0) const { wallet: receiverWallet, provider: receiverProvider, signer: receiverSigner } = utils.createTestWallet(web3, 2) const { wallet: operatorWallet, provider: operatorProvider, signer: operatorSigner } = utils.createTestWallet(web3, 4) describe('ERC1155', () => { const MAXVAL = BigNumber.from(2) .pow(256) .sub(1) // 2**256 - 1 const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' const NAME = "MyERC1155" const METADATA_URI = "https://example.com/" let ownerAddress: string let receiverAddress: string let operatorAddress: string let erc1155Abstract: AbstractContract let operatorAbstract: AbstractContract let erc1155Contract: ERC1155MetaMintBurnMock let operatorERC1155Contract: ERC1155MetaMintBurnMock // load contract abi and deploy to test server before(async () => { ownerAddress = await ownerWallet.getAddress() receiverAddress = await receiverWallet.getAddress() operatorAddress = await operatorWallet.getAddress() erc1155Abstract = await AbstractContract.fromArtifactName('ERC1155MetaMintBurnMock') operatorAbstract = await AbstractContract.fromArtifactName('ERC1155OperatorMock') }) // deploy before each test, to reset state of contract beforeEach(async () => { erc1155Contract = (await erc1155Abstract.deploy(ownerWallet, [NAME, METADATA_URI])) as ERC1155MetaMintBurnMock operatorERC1155Contract = (await erc1155Contract.connect(operatorSigner)) as ERC1155MetaMintBurnMock }) describe('Getter functions', () => { beforeEach(async () => { await erc1155Contract.mintMock(ownerAddress, 5, 256, []) await erc1155Contract.mintMock(receiverAddress, 66, 133, []) }) it('balanceOf() should return types balance for queried address', async () => { const balance5 = await erc1155Contract.balanceOf(ownerAddress, 5) expect(balance5).to.be.eql(BigNumber.from(256)) const balance16 = await erc1155Contract.balanceOf(ownerAddress, 16) expect(balance16).to.be.eql(BigNumber.from(0)) }) it('balanceOfBatch() should return types balance for queried addresses', async () => { const balances = await erc1155Contract.balanceOfBatch([ownerAddress, receiverAddress], [5, 66]) expect(balances[0]).to.be.eql(BigNumber.from(256)) expect(balances[1]).to.be.eql(BigNumber.from(133)) const balancesNull = await erc1155Contract.balanceOfBatch([ownerAddress, receiverAddress], [1337, 1337]) expect(balancesNull[0]).to.be.eql(BigNumber.from(0)) expect(balancesNull[1]).to.be.eql(BigNumber.from(0)) }) it('supportsInterface(0x4e2312e0) on receiver should return true', async () => { const abstract = await AbstractContract.fromArtifactName('ERC1155ReceiverMock') const receiverContract = (await abstract.deploy(ownerWallet)) as ERC1155ReceiverMock const returnedValue = await receiverContract.supportsInterface('0x4e2312e0') await expect(returnedValue).to.be.equal(true) }) it('supportsInterface(0x01ffc9a7) on receiver should return true', async () => { const abstract = await AbstractContract.fromArtifactName('ERC1155ReceiverMock') const receiverContract = (await abstract.deploy(ownerWallet)) as ERC1155ReceiverMock const returnedValue = await receiverContract.supportsInterface('0x01ffc9a7') await expect(returnedValue).to.be.equal(true) }) it('supportsInterface(0x4e2312ee) on receiver should return false', async () => { const abstract = await AbstractContract.fromArtifactName('ERC1155ReceiverMock') const receiverContract = (await abstract.deploy(ownerWallet)) as ERC1155ReceiverMock const returnedValue = await receiverContract.supportsInterface('0x4e2312ee') await expect(returnedValue).to.be.equal(false) }) }) describe('safeTransferFrom() function', () => { let receiverContract: ERC1155ReceiverMock let operatorContract: ERC1155OperatorMock beforeEach(async () => { const abstract = await AbstractContract.fromArtifactName('ERC1155ReceiverMock') receiverContract = (await abstract.deploy(ownerWallet)) as ERC1155ReceiverMock operatorContract = (await operatorAbstract.deploy(operatorWallet)) as ERC1155OperatorMock await erc1155Contract.mintMock(ownerAddress, 0, 256, []) }) it('should be able to transfer if sufficient balance', async () => { const tx = erc1155Contract.safeTransferFrom(ownerAddress, receiverAddress, 0, 1, []) await expect(tx).to.be.fulfilled }) it('should REVERT if insufficient balance', async () => { const tx = erc1155Contract.safeTransferFrom(ownerAddress, receiverAddress, 0, 257, []) await expect(tx).to.be.rejectedWith(RevertError('SafeMath#sub: UNDERFLOW')) }) it('should REVERT if sending to 0x0', async () => { const tx = erc1155Contract.safeTransferFrom(ownerAddress, ZERO_ADDRESS, 0, 1, []) await expect(tx).to.be.rejectedWith(RevertError('ERC1155#safeTransferFrom: INVALID_RECIPIENT')) }) it('should REVERT if operator not approved', async () => { const tx = operatorERC1155Contract.safeTransferFrom(ownerAddress, receiverAddress, 0, 1, []) await expect(tx).to.be.rejectedWith(RevertError('ERC1155#safeTransferFrom: INVALID_OPERATOR')) }) it('should be able to transfer via operator if operator is approved', async () => { // owner first gives operatorWallet address approval permission await erc1155Contract.setApprovalForAll(operatorAddress, true) // operator performs a transfer const tx = operatorERC1155Contract.safeTransferFrom(ownerAddress, receiverAddress, 0, 1, []) await expect(tx).to.be.fulfilled }) it('should REVERT if transfer leads to overflow', async () => { await erc1155Contract.mintMock(receiverAddress, 0, MAXVAL, []) const tx = erc1155Contract.safeTransferFrom(ownerAddress, receiverAddress, 0, 1, []) expect(tx).to.be.rejectedWith(RevertError('SafeMath#add: OVERFLOW')) }) it('should REVERT when sending to non-receiver contract', async () => { const tx = erc1155Contract.safeTransferFrom(ownerAddress, erc1155Contract.address, 0, 1, []) await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnMock: INVALID_METHOD')) }) it('should REVERT if invalid response from receiver contract', async () => { await receiverContract.setShouldReject(true) const tx = erc1155Contract.safeTransferFrom(ownerAddress, receiverContract.address, 0, 1, []) await expect(tx).to.be.rejectedWith(RevertError('ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE')) }) it('should pass if valid response from receiver contract', async () => { const tx = erc1155Contract.safeTransferFrom(ownerAddress, receiverContract.address, 0, 1, []) await expect(tx).to.be.fulfilled }) it('should pass if data is not null to receiver contract', async () => { const data = ethers.utils.toUtf8Bytes('Hello from the other side') // NOTE: typechain generates the wrong type for `bytes` type at this time // see https://github.com/ethereum-ts/TypeChain/issues/123 // @ts-ignore const tx = erc1155Contract.safeTransferFrom(ownerAddress, receiverContract.address, 0, 1, data) await expect(tx).to.be.fulfilled }) it('should have balances updated before onERC1155Received is called', async () => { const fromPreBalance = await erc1155Contract.balanceOf(ownerAddress, 0) const toPreBalance = await erc1155Contract.balanceOf(receiverContract.address, 0) // Get event filter to get internal tx event const filterFromReceiverContract = receiverContract.filters.TransferSingleReceiver(null, null, null, null) await erc1155Contract.safeTransferFrom(ownerAddress, receiverContract.address, 0, 1, []) // Get logs from internal transaction event // @ts-ignore (https://github.com/ethers-io/ethers.js/issues/204#issuecomment-427059031) filterFromReceiverContract.fromBlock = 0 const logs = await ownerProvider.getLogs(filterFromReceiverContract) const args = receiverContract.interface.decodeEventLog( receiverContract.interface.events['TransferSingleReceiver(address,address,uint256,uint256)'], logs[0].data, logs[0].topics ) expect(args._from).to.be.eql(ownerAddress) expect(args._to).to.be.eql(receiverContract.address) expect(args._fromBalance).to.be.eql(fromPreBalance.sub(1)) expect(args._toBalance).to.be.eql(toPreBalance.add(1)) }) it('should have TransferSingle event emitted before onERC1155Received is called', async () => { // Get event filter to get internal tx event const tx = await erc1155Contract.safeTransferFrom(ownerAddress, receiverContract.address, 0, 1, []) const receipt = await tx.wait(1) const firstEventTopic = receipt.logs![0].topics[0] const secondEventTopic = receipt.logs![1].topics[0] expect(firstEventTopic).to.be.equal( erc1155Contract.interface.getEventTopic( erc1155Contract.interface.events['TransferSingle(address,address,address,uint256,uint256)'] ) ) expect(secondEventTopic).to.be.equal( receiverContract.interface.getEventTopic( receiverContract.interface.events['TransferSingleReceiver(address,address,uint256,uint256)'] ) ) }) context('When successful transfer', () => { let tx: ethers.ContractTransaction beforeEach(async () => { tx = await erc1155Contract.safeTransferFrom(ownerAddress, receiverAddress, 0, 1, []) }) it('should correctly update balance of sender', async () => { const balance = await erc1155Contract.balanceOf(ownerAddress, 0) expect(balance).to.be.eql(BigNumber.from(255)) }) it('should correctly update balance of receiver', async () => { const balance = await erc1155Contract.balanceOf(receiverAddress, 0) expect(balance).to.be.eql(BigNumber.from(1)) }) describe('TransferSingle event', async () => { let filterFromOperatorContract: ethers.ethers.EventFilter it('should emit TransferSingle event', async () => { const receipt = await tx.wait(1) const ev = receipt.events!.pop()! expect(ev.event).to.be.eql('TransferSingle') }) it('should have `msg.sender` as `_operator` field, not _from', async () => { await erc1155Contract.setApprovalForAll(operatorAddress, true) tx = await operatorERC1155Contract.safeTransferFrom(ownerAddress, receiverAddress, 0, 1, []) const receipt = await tx.wait(1) const ev = receipt.events!.pop()! const args = ev.args! as any expect(args._operator).to.be.eql(operatorAddress) }) it('should have `msg.sender` as `_operator` field, not tx.origin', async () => { // Get event filter to get internal tx event filterFromOperatorContract = erc1155Contract.filters.TransferSingle(operatorContract.address, null, null, null, null) // Set approval to operator contract await erc1155Contract.setApprovalForAll(operatorContract.address, true) // Execute transfer from operator contract // @ts-ignore (https://github.com/ethereum-ts/TypeChain/issues/118) await operatorContract.safeTransferFrom( erc1155Contract.address, ownerAddress, receiverAddress, 0, 1, [], { gasLimit: 1000000 } // INCORRECT GAS ESTIMATION ) // Get logs from internal transaction event // @ts-ignore (https://github.com/ethers-io/ethers.js/issues/204#issuecomment-427059031) filterFromOperatorContract.fromBlock = 0 const logs = await operatorProvider.getLogs(filterFromOperatorContract) const args = erc1155Contract.interface.decodeEventLog( erc1155Contract.interface.events['TransferSingle(address,address,address,uint256,uint256)'], logs[0].data, logs[0].topics ) // operator arg should be equal to msg.sender, not tx.origin expect(args._operator).to.be.eql(operatorContract.address) }) }) }) }) describe('safeBatchTransferFrom() function', () => { let types: any[], values: any[] const nTokenTypes = 30 //560 const nTokensPerType = 10 let receiverContract: ERC1155ReceiverMock beforeEach(async () => { ;(types = []), (values = []) // Minting enough values for transfer for each types for (let i = 0; i < nTokenTypes; i++) { types.push(i) values.push(nTokensPerType) } await erc1155Contract.batchMintMock(ownerAddress, types, values, []) const abstract = await AbstractContract.fromArtifactName('ERC1155ReceiverMock') receiverContract = (await abstract.deploy(ownerWallet)) as ERC1155ReceiverMock }) it('should be able to transfer tokens if sufficient balances', async () => { const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, types, values, []) await expect(tx).to.be.fulfilled }) it('should PASS if arrays are empty', async () => { const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, [], [], []) await expect(tx).to.be.fulfilled }) it('should REVERT if insufficient balance', async () => { const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, [0], [11], []) await expect(tx).to.be.rejectedWith(RevertError('SafeMath#sub: UNDERFLOW')) }) it('should REVERT if single insufficient balance', async () => { const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, [0, 15, 30], [1, 9, 11], []) await expect(tx).to.be.rejectedWith(RevertError('SafeMath#sub: UNDERFLOW')) }) it('should REVERT if operator not approved', async () => { const tx = operatorERC1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, types, values, []) expect(tx).to.be.rejectedWith(RevertError('ERC1155#safeBatchTransferFrom: INVALID_OPERATOR')) }) it('should REVERT if length of ids and values are not equal', async () => { const tx1 = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, [0, 15, 30, 0], [1, 9, 10], []) await expect(tx1).to.be.rejectedWith(RevertError('ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH')) const tx2 = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, [0, 15, 30], [1, 9, 10, 0], []) await expect(tx2).to.be.rejectedWith(RevertError('ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH')) }) it('should REVERT if sending to 0x0', async () => { const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, ZERO_ADDRESS, types, values, []) await expect(tx).to.be.rejectedWith(RevertError('ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT')) }) it('should be able to transfer via operator if operator is approved', async () => { await erc1155Contract.setApprovalForAll(operatorAddress, true) const tx = operatorERC1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, types, values, []) await expect(tx).to.be.fulfilled }) it('should REVERT if transfer leads to overflow', async () => { await erc1155Contract.mintMock(receiverAddress, 5, MAXVAL, []) const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, [5], [1], []) await expect(tx).to.be.rejectedWith(RevertError('SafeMath#add: OVERFLOW')) }) it('should update balances of sender and receiver', async () => { await erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, types, values, []) let balanceFrom: ethers.BigNumber let balanceTo: ethers.BigNumber for (let i = 0; i < types.length; i++) { balanceFrom = await erc1155Contract.balanceOf(ownerAddress, types[i]) balanceTo = await erc1155Contract.balanceOf(receiverAddress, types[i]) expect(balanceFrom).to.be.eql(BigNumber.from(0)) expect(balanceTo).to.be.eql(BigNumber.from(values[i])) } }) it('should REVERT when sending to non-receiver contract', async () => { const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, erc1155Contract.address, types, values, [], { gasLimit: 2000000 }) await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnMock: INVALID_METHOD')) }) it('should REVERT if invalid response from receiver contract', async () => { await receiverContract.setShouldReject(true) const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverContract.address, types, values, [], { gasLimit: 2000000 }) await expect(tx).to.be.rejectedWith(RevertError('ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE')) }) it('should pass if valid response from receiver contract', async () => { const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverContract.address, types, values, [], { gasLimit: 2000000 }) await expect(tx).to.be.fulfilled }) it('should pass if data is not null from receiver contract', async () => { const data = ethers.utils.toUtf8Bytes('Hello from the other side') // TODO: remove ts-ignore when contract declaration is fixed // @ts-ignore const tx = erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverContract.address, types, values, data, { gasLimit: 2000000 }) await expect(tx).to.be.fulfilled }) it('should have balances updated before onERC1155BatchReceived is called', async () => { const fromAddresses = Array(types.length).fill(ownerAddress) const toAddresses = Array(types.length).fill(receiverContract.address) const fromPreBalances = await erc1155Contract.balanceOfBatch(fromAddresses, types) const toPreBalances = await erc1155Contract.balanceOfBatch(toAddresses, types) // Get event filter to get internal tx event const filterFromReceiverContract = receiverContract.filters.TransferBatchReceiver(null, null, null, null) await erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverContract.address, types, values, [], { gasLimit: 2000000 }) // Get logs from internal transaction event // @ts-ignore (https://github.com/ethers-io/ethers.js/issues/204#issuecomment-427059031) filterFromReceiverContract.fromBlock = 0 const logs = await ownerProvider.getLogs(filterFromReceiverContract) const args = receiverContract.interface.decodeEventLog( receiverContract.interface.events['TransferBatchReceiver(address,address,uint256[],uint256[])'], logs[0].data, logs[0].topics ) expect(args._from).to.be.eql(ownerAddress) expect(args._to).to.be.eql(receiverContract.address) for (let i = 0; i < types.length; i++) { expect(args._fromBalances[i]).to.be.eql(fromPreBalances[i].sub(values[i])) expect(args._toBalances[i]).to.be.eql(toPreBalances[i].add(values[i])) } }) it('should have TransferBatch event emitted before onERC1155BatchReceived is called', async () => { // Get event filter to get internal tx event const tx = await erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverContract.address, types, values, [], { gasLimit: 2000000 }) const receipt = await tx.wait(1) const firstEventTopic = receipt.logs![0].topics[0] const secondEventTopic = receipt.logs![1].topics[0] expect(firstEventTopic).to.be.equal( erc1155Contract.interface.getEventTopic( erc1155Contract.interface.events['TransferBatch(address,address,address,uint256[],uint256[])'] ) ) expect(secondEventTopic).to.be.equal( receiverContract.interface.getEventTopic( receiverContract.interface.events['TransferBatchReceiver(address,address,uint256[],uint256[])'] ) ) }) describe('TransferBatch event', async () => { let tx: ethers.ContractTransaction let filterFromOperatorContract: ethers.ethers.EventFilter let operatorContract: ERC1155OperatorMock beforeEach(async () => { operatorContract = (await operatorAbstract.deploy(operatorWallet)) as ERC1155OperatorMock }) it('should emit 1 TransferBatch events of N transfers', async () => { const tx = await erc1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, types, values, []) const receipt = await tx.wait(1) const ev = receipt.events!.pop()! expect(ev.event).to.be.eql('TransferBatch') const args = ev.args! as any expect(args._ids.length).to.be.eql(types.length) }) it('should have `msg.sender` as `_operator` field, not _from', async () => { await erc1155Contract.setApprovalForAll(operatorAddress, true) tx = await operatorERC1155Contract.safeBatchTransferFrom(ownerAddress, receiverAddress, types, values, []) const receipt = await tx.wait(1) const ev = receipt.events!.pop()! const args = ev.args! as any expect(args._operator).to.be.eql(operatorAddress) }) it('should have `msg.sender` as `_operator` field, not tx.origin', async () => { // Get event filter to get internal tx event filterFromOperatorContract = erc1155Contract.filters.TransferBatch(operatorContract.address, null, null, null, null) // Set approval to operator contract await erc1155Contract.setApprovalForAll(operatorContract.address, true) // Execute transfer from operator contract // @ts-ignore (https://github.com/ethereum-ts/TypeChain/issues/118) await operatorContract.safeBatchTransferFrom( erc1155Contract.address, ownerAddress, receiverAddress, types, values, [], { gasLimit: 2000000 } // INCORRECT GAS ESTIMATION ) // Get logs from internal transaction event // @ts-ignore (https://github.com/ethers-io/ethers.js/issues/204#issuecomment-427059031) filterFromOperatorContract.fromBlock = 0 const logs = await operatorProvider.getLogs(filterFromOperatorContract) const args = erc1155Contract.interface.decodeEventLog( erc1155Contract.interface.events['TransferBatch(address,address,address,uint256[],uint256[])'], logs[0].data, logs[0].topics ) // operator arg should be equal to msg.sender, not tx.origin expect(args._operator).to.be.eql(operatorContract.address) }) }) }) describe('setApprovalForAll() function', () => { it('should emit an ApprovalForAll event', async () => { const tx = await erc1155Contract.setApprovalForAll(operatorAddress, true) const receipt = await tx.wait(1) expect(receipt.events![0].event).to.be.eql('ApprovalForAll') }) it('should set the operator status to _status argument', async () => { const tx = erc1155Contract.setApprovalForAll(operatorAddress, true) await expect(tx).to.be.fulfilled const status = await erc1155Contract.isApprovedForAll(ownerAddress, operatorAddress) expect(status).to.be.eql(true) }) context('When the operator was already an operator', () => { beforeEach(async () => { await erc1155Contract.setApprovalForAll(operatorAddress, true) }) it('should leave the operator status to set to true again', async () => { const tx = erc1155Contract.setApprovalForAll(operatorAddress, true) await expect(tx).to.be.fulfilled const status = await erc1155Contract.isApprovedForAll(ownerAddress, operatorAddress) expect(status).to.be.eql(true) }) it('should allow the operator status to be set to false', async () => { const tx = erc1155Contract.setApprovalForAll(operatorAddress, false) await expect(tx).to.be.fulfilled const status = await erc1155Contract.isApprovedForAll(operatorAddress, ownerAddress) expect(status).to.be.eql(false) }) }) }) describe('Supports ERC165', () => { describe('supportsInterface()', () => { it('should return true for 0x01ffc9a7 (IERC165)', async () => { const support = await erc1155Contract.supportsInterface('0x01ffc9a7') expect(support).to.be.eql(true) }) it('should return true for 0xd9b67a26 (IERC1155)', async () => { const support = await erc1155Contract.supportsInterface('0xd9b67a26') expect(support).to.be.eql(true) }) }) }) })
the_stack
import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; // import { p } from '@angular/core/src/render3'; import { flatMap } from 'rxjs/operators'; import { LegacyWalletV1, ImplicitAccount, OriginatedAccount, LegacyWalletV2, Activity, LegacyWalletV3, EmbeddedTorusWallet, HdWallet, } from './../../src/app/services/wallet/wallet'; import { viewClassName } from '@angular/compiler'; /** * Kukai Extensible Mocking Tools */ export class Tools { /** * Generate Random Number * @param min * @param max * @param multiplier * @param fixed */ generateRandomNumber( min: number, max: number, multiplier: number = 1, fixed: number = 0 ): number { min = min * multiplier; max = max * multiplier; if (fixed) { return Number((Math.random() * (max - min) + min).toFixed(fixed)); } else { return Math.floor(Math.random() * (max - min)) + min; } } /** * Generate Random String * @param length */ generateRandomString(length: number, prefix: string = '') { let randString: string = prefix; const len: number = length - prefix.length; const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; // generate string for remaining non-prefix length for (let i = 0; i <= len; i++) { randString += charSet[Math.floor(Math.random() * charSet.length)]; } return randString; } /** * Generate Random Date * @param start * @param end * @returns new Date() * Example: generateRandomDate('1999-01-01', '2017-12-07') */ generateRandomDate(start, end): number { //new Date('2011-04-11T10:20:30Z') start = new Date(start); end = new Date(end); return start.getTime() + Math.random() * (end.getTime() - start.getTime()); } /** * Balance Generator * @summary Randomly generate realistic balance * @returns number */ generateBalance(xtzrate: number = 0.510272): number { // generate common transaction amount, use multiplier to adjust const balance = this.generateRandomNumber(1000, 7500, 1000000); return balance; } /** * Return Empty Balance */ getEmptyBalance(): number { return null; } /** * Date Difference in Days * @param a * @param b */ dateDiffInDays(a: Date, b: Date) { const _MS_PER_DAY = 1000 * 60 * 60 * 24; // Discard the time and time-zone information. const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()); const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()); if (a === b) { console.log('they are the same'); return 0; } else { return Math.floor((utc2 - utc1) / _MS_PER_DAY); } } printAccounts(implicitAccounts: ImplicitAccount[]): void { let string = '\n+--------------------------------------+\n'; for (const impAcc of implicitAccounts) { let pkh = impAcc.pkh; let balance = (impAcc.balanceXTZ / 1000000).toFixed(2); let delegate = impAcc.delegate; let numberOfActivites = impAcc.state; string += '\x1b[36m'; //set blue string += ' public key hash: ' + pkh + '\n'; string += '\x1b[32m'; string += ' delegate: ' + delegate + '\n'; string += ' balance: ' + balance + '\n'; string += ' counter: ' + numberOfActivites + ''; string += '\x1b[0m'; string += '\n+--------------------------------------+\n'; for (const origAcc of impAcc.originatedAccounts) { pkh = origAcc.address; balance = (origAcc.balanceXTZ / 1000000).toFixed(2); delegate = origAcc.delegate; numberOfActivites = origAcc.state; string += '\x1b[36m'; //set blue string += ' public key hash: ' + pkh + '\n'; string += '\x1b[32m'; string += ' delegate: ' + delegate + '\n'; string += ' balance: ' + balance + '\n'; string += ' counter: ' + numberOfActivites + ''; string += '\x1b[0m'; string += '\n+--------------------------------------+\n'; } } console.log(string); } /** @param activities hash: string; block: string; source: string; destination: string; amount: number; fee: number; timestamp: null|Date; type: string; */ printActivities(activities: Activity[]): void { let string = '\n+--------------------------------------+\n'; for (let i = 0; i < activities.length; i++) { const hash = activities[i].hash; const block = activities[i].block; const source = activities[i].source; const destination = activities[i].destination; const amount = activities[i].amount; const fee = activities[i].fee; const timestamp = activities[i].timestamp; const type = activities[i].type; string += '\x1b[36m'; //set blue string += ' hash: ' + hash + '\n'; string += '\x1b[32m'; string += ' block: ' + block + '\n'; string += ' source: ' + source + '\n'; string += ' destination: ' + destination + '\n'; string += ' amount: ' + amount + '\n'; string += ' fee: ' + fee + '\n'; string += ' timestamp: ' + timestamp + '\n'; string += ' type: ' + type + '\n'; string += '\x1b[0m'; string += '\n+--------------------------------------+\n'; } console.log(string); } } /** * Kukai OperationMocking Library */ export class OperationTools extends Tools { getOp(data: any, pkh: string): any { const ops: any[] = []; for (let index = 0; index < data.type.operations.length; index++) { let type = 'Unknown'; if (data.type.operations[index].kind !== 'reveal') { type = data.type.operations[index].kind; let destination = ''; let source = ''; let amount = 0; let fee = 0; if (type === 'activation') { source = data.type.operations[index].pkh.tz; } else { source = data.type.source.tz; if (type === 'transaction') { destination = data.type.operations[index].destination.tz; amount = data.type.operations[index].amount; if (destination !== pkh) { amount = amount * -1; } fee = data.type.fee; } else if (type === 'origination') { destination = data.type.operations[index].tz1.tz; amount = data.type.operations[index].balance; if (destination !== pkh) { amount = amount * -1; } fee = data.type.fee; } else if (type === 'delegation') { destination = data.type.operations[index].delegate; fee = data.type.fee; } } const op: any = { hash: data.hash, block: data.block_hash, source: source, destination: destination, amount: amount, fee: fee, timestamp: null, type: type, }; ops.push(op); } } return ops; } getOperations() { // tslint:disable-next-line:max-line-length return [ { hash: 'oojyMokq8spYaDECQP9s43aCnMHGocdbYbPKvddaieQAZCS7H3s', block_hash: 'BKmiYRBy7ZbLxZcN34JvKurMYt3s9RcAbcVVF6mTfE5Uo6G4Jtt', network_hash: 'NetXdQprcVkpaWU', type: { kind: 'manager', source: { tz: 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt' }, operations: [ { kind: 'transaction', src: { tz: 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt' }, amount: '889162032500', destination: { tz: 'KT1VyvPxmo7GpSozfzen8UQLWBRwKjiF9JNa' }, internal: false, burn: 0, counter: 1389, fee: 2000, gas_limit: '10200', storage_limit: '0', op_level: 225011, timestamp: '2018-12-12T21:54:12Z', }, ], }, }, { hash: 'oo3LbVP5U4kzrAHKRSow6amejMkXHfwUuJ1wiuW1cwGJ5CKYBrd', block_hash: 'BLZisMgE9cb7nf1yaEHB3QfU53uavjmJyC11DVto5gKmS6zrYe9', network_hash: 'NetXdQprcVkpaWU', type: { kind: 'manager', source: { tz: 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt' }, operations: [ { kind: 'transaction', src: { tz: 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt' }, amount: '26478863095', destination: { tz: 'KT1HmGvNKp8GXgVk6YckUL1LY9h9itDTNXuA' }, internal: false, burn: 0, counter: 1388, fee: 2000, gas_limit: '10200', storage_limit: '0', op_level: 225010, timestamp: '2018-12-12T21:53:12Z', }, ], }, }, { hash: 'ooYri4TZk4wukWs8sWWFVVXZyxTiro1xbX5aZP1PfCKWqbLWcLx', block_hash: 'BLtLNKqse6ceRkHC3jnS8z6bo7i7hw2RJJXxVsyacciebcJHYWA', network_hash: 'NetXdQprcVkpaWU', type: { kind: 'manager', source: { tz: 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt' }, operations: [ { kind: 'transaction', src: { tz: 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt' }, amount: '15991842036', destination: { tz: 'KT1AcH3YscoUcJKqvqdcYCBeZwAennd2NEeN' }, internal: false, burn: 0, counter: 1387, fee: 2000, gas_limit: '10200', storage_limit: '0', op_level: 225009, timestamp: '2018-12-12T21:52:12Z', }, ], }, }, ]; } } /** * Kukai Activity Mocking Library */ export class ActivityTools extends OperationTools { /** * Generate Multiple Activities * @param number * @param source * @param type */ generateActivities(number: number, source: string, type: string): Activity[] { // initialize empty Activity array const activities: Activity[] = []; // generate unique hashes for { number } of activities for (let i = 0; i < number; i++) { // generated hashes let ophash: string; let blockhash: string; // boolean checks it is unique let ophash_verified = false; let blockhash_verified = false; // check to exit condition let unique: boolean; // generate a unique operation hash while (!ophash_verified) { unique = true; ophash = this.generateOperationHash(); // check against existing ophash set for (let x = 0; x < activities.length; x++) { if (ophash === activities[x].hash) { unique = false; } } // verify if property is not used in set if (unique) { ophash_verified = true; } } // generate unique block hash while (!blockhash_verified) { unique = true; blockhash = this.generateBlockHash(); // check against existing blockhash set for (let x = 0; x < activities.length; x++) { if (blockhash === activities[x].block) { unique = false; } } // verify if property is not used in set if (unique) { blockhash_verified = true; } } activities.push(this.generateActivity(ophash, blockhash, source, type)); } return activities; } /** * Generate Activity * @param operationhash * @param blockhash * @param source * @param type */ generateActivity( operationhash: string, blockhash: string, source: string, type: string ): Activity { // generate a mock activity const activity: Activity = { hash: operationhash, block: blockhash, source: { address: source }, status: 1, destination: { address: this.generateDestination() }, amount: this.generateAmount().toString(), fee: this.generateFee().toString(), timestamp: this.generateDate(), type: type, }; return activity; } /** * Generate Operation Hash */ generateOperationHash(): string { return this.generateRandomString(51, 'oo'); } /** * Generate Block Hash */ generateBlockHash(): string { return this.generateRandomString(51, 'BL'); } /** * Generate Destination Address * @summary Returns random entry from alphanet account map * @returns string */ generateDestination(): string { const implicitAddresses = [ 'tz1eSeLtoZwbi6hCbepRcsoQiLzTaeAMK59J', 'tz1PvVPHCtyvwrpLKoCFBXbiPh3DwmiFFKnQ', 'tz1hgWvYdzLECdrq5zndGHwCGnUCJq1KFe3r', 'tz1Vrs3r11Tu9fZvu4mHFcuNt9FK9QuCw83X', 'tz1isdcry1fivqoXbFArYjP7nhFU1watadyC', 'tz1SjiQ2fApoJB6VWxMa6nha3GwCPw4266AZ', 'tz1YsbingXMmDqaXiTSccV8CgavdATeXeNF1', 'tz2L2HuhaaSnf6ShEDdhTEAr5jGPWPNwpvcB', 'tz1bsHJBTfGBbPvG48rN6ryiHDzBustQ9gtZ', 'tz1bhk6jHswCTggueGfYCNfuQ5pneRMzaPbm', 'tz1hhFd3KyjWAwAR718GVfTHUtCND6LZdLjC', 'tz1XD4TuLXVjtpaE14B3ZJ2cjfp4Kzbpdqs1', 'tz1VAckrTCDiJcYALzjdW56NTVDmxrgJyrVn', 'tz1ciwpCgVCcJ7eWgqhzJe4yKQqPH1Yj3NTM', 'tz1YZvSSCi6fjgtTxTDAvKuSvdBHQw2dbXZu', 'tz1N2huAR4LaZyac7cCR7ZNaJCkEDhuTmetU', 'tz1fX1eDSwSCC2SEyCAVyFbrgpGkLBpjDSFR', 'tz1QYqcPtcYLTcH7Bz2BNy7B4N6eWgAX93CC', 'tz1ZL6qHzJz3NTXHApWJRXoByFxL6R38KvFb', ]; return implicitAddresses[this.generateRandomNumber(0, 19)]; } /** * Amount Generator * @summary Randomly generate realistic transaction operation amount * @returns number */ generateAmount(): number { // generate common transaction amount, use multiplier to adjust return this.generateRandomNumber(1000, 7500, 1000000); } /** * Fee Generator * @summary Randomly generate realistic operation fee amount * @returns number fixed (4) */ generateFee(): number { // generate realistic fee amount between 0.0025-0.0035 XTZ return this.generateRandomNumber(0.0025, 0.0035, 1, 4); } /** * Timestamp Generator * @summary Returns random datetime between two dates * @retuns Date */ generateDate(): number { return this.generateRandomDate( '2018-07-01T00:00:00Z', '2019-01-04T00:00:00Z' ); } } /** * Kukai Account Mocking Library */ export class AccountTools extends ActivityTools { generateAccount( pkh: string, pk: string, xtzrate: number = 0.510272, balance: number = this.getEmptyBalance() ): ImplicitAccount { return <ImplicitAccount> { pkh: pkh, pk: pk, delegate: this.generateRandomDelegate(), balanceXTZ: this.generateBalance(xtzrate), balanceUSD: 0, state: '5', activities: this.generateActivities(5, pkh, 'transaction'), originatedAccounts: [] }; } generateAccounts(pkh: string[], pk: string[], activities: Activity[][] = []): ImplicitAccount[] { const accounts: ImplicitAccount[] = []; for (let i = 0; i < pkh.length; i++) { accounts.push( this.generateAccount(pkh[i], pk[i], 0.510272, this.generateBalance()) ); } return accounts; } generateRandomDelegate(): string { const x = this.generateRandomNumber(0, 5); const delegates = [ '', 'tz1eEnQhbwf6trb8Q8mPb2RaPkNk2rN7BKi8', 'tz1abTjX2tjtMdaq5VCzkDtBnMSCFPW2oRPa', 'tz1NortRftucvAkD1J58L32EhSVrQEWJCEnB', 'tz1bHzftcTKZMTZgLLtnrXydCm6UEqf4ivca', 'tz1LLNkQK4UQV6QcFShiXJ2vT2ELw449MzAA', ]; return delegates[x]; } } /** * Kukai Wallet Mocking Library */ export class WalletTools extends AccountTools { // @todo move to pipe, network service, etc. getTickerRate(symbol: string, basepair: string): number { if (symbol === 'xtz' && basepair === 'usd') { return 0.510272; } } // @todo move to pipe, network service, etc. getUSDRate(symbol: string, qty: number): number { if (symbol === 'xtz') { const conversion = qty / 1000000; return conversion * this.getTickerRate('xtz', 'usd'); } } getWalletBalance(implicitAccounts: ImplicitAccount[]): any { let totalbalance = 0; if (implicitAccounts.length) { for (let i = 0; i < implicitAccounts.length; i++) { const balance = implicitAccounts[i].balanceXTZ; if (balance != null) { totalbalance += balance; } } return { balanceXTZ: totalbalance, balanceUSD: this.getUSDRate('xtz', totalbalance), }; } else { return this.getEmptyBalance(); } } /** * Generate Wallet * @param seed * @param type * @param accountpkhs * @param xtzrate * @param balance */ // tslint:disable-next-line:max-line-length generateWalletV1( seed: string = '224e6376f4b25825f8110b896c81b74895451d8c19ba09ee3a2552a2550fcf88', implicitAccount: any = { pk: 'edpktuKnjXvtFnpEjz85Fm8712wV2xvd2SjsLPk1v6dDQZa8ZqgaWf', pkh: 'tz1U2R9zKaKW6EjngeLU4LPitck5koJHT5Xb', }, originatedAccounts: string[] = [ 'KT1EyxYE9TWEVSvUktBMErqKfNxGEomTdoaf', 'KT1TZeMxMUHeLM4SvbcsvdpAG2KRHUYV7fiT', ], xtzrate: number = 0.510272, balance: number = 100 ): LegacyWalletV1 { const v1wallet = new LegacyWalletV1('U2R9zKaKW6EjngeL', seed); v1wallet.XTZrate = xtzrate; v1wallet.implicitAccounts.push( new ImplicitAccount(implicitAccount.pkh, implicitAccount.pk) ); v1wallet.implicitAccounts[0].balanceXTZ = balance; for (const origAcc of originatedAccounts) { v1wallet.implicitAccounts[0].originatedAccounts.push( new OriginatedAccount(origAcc, implicitAccount.pkh, implicitAccount.pk) ); v1wallet.implicitAccounts[0].originatedAccounts[ v1wallet.implicitAccounts[0].originatedAccounts.length - 1 ].balanceXTZ = balance; } const { balanceXTZ, balanceUSD } = this.getWalletBalance( v1wallet.implicitAccounts ); v1wallet.totalBalanceXTZ = balanceXTZ; v1wallet.totalBalanceUSD = balanceUSD; return v1wallet; } generateWalletEmbedded(): EmbeddedTorusWallet { const keyPair = { sk: 'spsk1VfCfhixtzGvUSKDre6jwyGbXFm6aoeLGnxeVLCouueZmkgtJF', pk: 'sppk7cZsZeBApsFgYEdWuSwj92YCWkJxMmBfkN3FeKRmEB7Lk5pmDrT', pkh: 'tz2WKg52VqnYXH52TZbSVjT4hcc8YGVKi7Pd' }; const userInfo = { typeOfLogin: 'google', verifierId: 'mock.user@gmail.com', name: 'Mock User' }; const wallet = new EmbeddedTorusWallet(userInfo.typeOfLogin, userInfo.verifierId, userInfo.name, 'https://test.com', keyPair.sk, '1'); wallet.XTZrate = 4.01; wallet.implicitAccounts.push( new ImplicitAccount(keyPair.pkh, keyPair.pk) ); wallet.implicitAccounts[0].balanceXTZ = 234324.234; return wallet; } /** * Generate Wallet v2 * @param seed * @param type * @param accountpkhs * @param xtzrate * @param balance * * @todo create actual password encrypted wallet */ // tslint:disable-next-line:max-line-length generateWalletV2( seed: string = '3f5ec27d8efc83a8c6ca6ba22b0e4f179cfe2381f12fda4672f571a07d4b89e2==508e35d6b94f018eeec18d12a9337341', implicitAccount: any = { pk: 'edpku7vd7gzLzeTwdo21VC97Vp23rTjpyAZxdXTWNWi66puhPuBRLe, pkh: tz1NUXpLwA9Jj5hXHZanYCV1pMNycxXx6zAf', }, originatedAccounts: string[] = [ 'KT18e6uHg65SZUF2Gkh8GU2RRDaHm3VGfLhF', 'KT1LmKuo4GwJeRLtrZcdX2sSQyHAPZUHSb9T', ], xtzrate: number = 0.510272, balance: number = 100 ): LegacyWalletV2 { const v2wallet = new LegacyWalletV2( 'ce7738762322795aca89a178a5db915e', seed ); v2wallet.XTZrate = xtzrate; v2wallet.implicitAccounts.push( new ImplicitAccount(implicitAccount.pkh, implicitAccount.pk) ); v2wallet.implicitAccounts[0].balanceXTZ = balance; for (const origAcc of originatedAccounts) { v2wallet.implicitAccounts[0].originatedAccounts.push( new OriginatedAccount(origAcc, implicitAccount.pkh, implicitAccount.pk) ); v2wallet.implicitAccounts[0].originatedAccounts[ v2wallet.implicitAccounts[0].originatedAccounts.length - 1 ].balanceXTZ = balance; } const { balanceXTZ, balanceUSD } = this.getWalletBalance( v2wallet.implicitAccounts ); v2wallet.totalBalanceXTZ = balanceXTZ; v2wallet.totalBalanceUSD = balanceUSD; return v2wallet; } // icon salute dinner depend radio announce urge hello danger join long toe ridge clever toast opera spot rib outside explain mixture eyebrow brother share generateHdWallet( iv: string = 'aff0bfd4ccdab8ae3e35eeab9e7af782', encryptedSeed: string = '90f57ef8f82e9acfa11a44e02aefaa8444596c3a8d2aa2aeaecfbb51187484a0354bf8a6c009bb4836716dc030d790978948044454dd85e6e2f2fb6284ac2c50==a533b34b90fcf71742a0d6abc9eaed15', encryptedEntropy: string = '8178b31d4c23c4e07f2fdc024966a76ca7630c4607018847a3aec315a765e17b==5d0c16c5f2207409f67f259110b9ca93', implicitAccounts: any = [{ pk: 'edpkvXyJHwuFRkngpcPyYWndZhAqf72owWrMnkkNsBoBkS54V4GJrM', pkh: 'tz1TogVQurVUhTFY1d62QJGmkMdEadM9MNpu', }, { pk: 'edpkvaNoKcTrQ8jBVHkVUzwZnLAaZT98ALxucqcfmkPAWGXuRVM9Db', pkh: 'tz1dXCZTs4pRTVvoXJXNRUmrYqtCde4fdP8N' }], xtzrate: number = 0.510272, balance: number = 100 ): HdWallet { const hdWallet = new HdWallet( iv, encryptedSeed, encryptedEntropy ); hdWallet.XTZrate = xtzrate; for (const impAcc of implicitAccounts) { hdWallet.implicitAccounts.push( new ImplicitAccount(impAcc.pkh, impAcc.pk) ); hdWallet.implicitAccounts[hdWallet.implicitAccounts.length - 1].balanceXTZ = balance; } const { balanceXTZ, balanceUSD } = this.getWalletBalance( hdWallet.implicitAccounts ); hdWallet.totalBalanceXTZ = balanceXTZ; hdWallet.totalBalanceUSD = balanceUSD; return hdWallet; } }
the_stack
import 'reflect-metadata'; import * as Decrators from '../../../../src/decorators/validates'; import * as Validators from '../../../../src/validate/validators'; describe('validate decrators', () => { it('should patch passed rule with @Passed', () => { const options = {}; class Example { @Decrators.Passed() example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.passed, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch accepted rule with @Accepted', () => { const options = {}; class Example { @Decrators.Accepted(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.accepted, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch is rule with @Is', () => { const options = {}; class Example { @Decrators.Is('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.is, args: ['test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch required rule with @Required', () => { const options = {}; class Example { @Decrators.Required(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.required, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch equals rule with @Equals', () => { const options = {}; class Example { @Decrators.Equals('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.equals, args: ['test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsEmpty rule with @IsEmpty', () => { const options = {}; class Example { @Decrators.IsEmpty(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isEmpty, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsNotEmpty rule with @IsNotEmpty', () => { const options = {}; class Example { @Decrators.IsNotEmpty(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isNotEmpty, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsDivisibleBy rule with @IsDivisibleBy', () => { const options = {}; class Example { @Decrators.IsDivisibleBy(1, options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isDivisibleBy, args: [1], options: { message: expect.any(String), ...options, }, }, ]); }); // ============================================================ // ============================================================ // ============================================================ // ============================================================ // ============================================================ // ============================================================ // ============================================================ // ============================================================ // ============================================================ // ============================================================ it('should patch IsPositive rule with @IsPositive', () => { const options = {}; class Example { @Decrators.IsPositive(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isPositive, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsNegative rule with @IsNegative', () => { const options = {}; class Example { @Decrators.IsNegative(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isNegative, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch Min rule with @Min', () => { const options = {}; class Example { @Decrators.Min(1, options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.min, args: [1], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch Max rule with @Max', () => { const options = {}; class Example { @Decrators.Max(1, options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.max, args: [1], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch AfterDate rule with @AfterDate', () => { const options = {}; class Example { @Decrators.AfterDate(1, options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.afterDate, args: [1], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch BeforeDate rule with @BeforeDate', () => { const options = {}; class Example { @Decrators.BeforeDate(1, options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.beforeDate, args: [1], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsBoolean rule with @IsBoolean', () => { const options = {}; class Example { @Decrators.IsBoolean(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isBoolean, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsDate rule with @IsDate', () => { const options = {}; class Example { @Decrators.IsDate(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isDate, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsString rule with @IsString', () => { const options = {}; class Example { @Decrators.IsString(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isString, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsNumber rule with @IsNumber', () => { const options = {}; class Example { @Decrators.IsNumber(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isNumber, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsArray rule with @IsArray', () => { const options = {}; class Example { @Decrators.IsArray(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isArray, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsError rule with @IsError', () => { const options = {}; class Example { @Decrators.IsError(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isError, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsFunction rule with @IsFunction', () => { const options = {}; class Example { @Decrators.IsFunction(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isFunction, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsBuffer rule with @IsBuffer', () => { const options = {}; class Example { @Decrators.IsBuffer(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isBuffer, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsObject rule with @IsObject', () => { const options = {}; class Example { @Decrators.IsObject(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isObject, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsRegExp rule with @IsRegExp', () => { const options = {}; class Example { @Decrators.IsRegExp(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isRegExp, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsSymbol rule with @IsSymbol', () => { const options = {}; class Example { @Decrators.IsSymbol(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isSymbol, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsNullOrUndefined rule with @IsNullOrUndefined', () => { const options = {}; class Example { @Decrators.IsNullOrUndefined(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isNullOrUndefined, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsNull rule with @IsNull', () => { const options = {}; class Example { @Decrators.IsNull(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isNull, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsUndefined rule with @IsUndefined', () => { const options = {}; class Example { @Decrators.IsUndefined(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isUndefined, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsDateString rule with @IsDateString', () => { const options = {}; class Example { @Decrators.IsDateString(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isDateString, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsBooleanString rule with @IsBooleanString', () => { const options = {}; class Example { @Decrators.IsBooleanString(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isBooleanString, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsNumberString rule with @IsNumberString', () => { const options = {}; class Example { @Decrators.IsNumberString(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isNumberString, args: [options], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch Contains rule with @Contains', () => { const options = {}; class Example { @Decrators.Contains('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.contains, args: ['test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch NotContains rule with @NotContains', () => { const options = {}; class Example { @Decrators.NotContains('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.notContains, args: ['test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsAlpha rule with @IsAlpha', () => { const options = {}; class Example { @Decrators.IsAlpha('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isAlpha, args: ['test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsAlphanumeric rule with @IsAlphanumeric', () => { const options = {}; class Example { @Decrators.IsAlphanumeric('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isAlphanumeric, args: ['test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsAscii rule with @IsAscii', () => { const options = {}; class Example { @Decrators.IsAscii(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isAscii, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsBase64 rule with @IsBase64', () => { const options = {}; class Example { @Decrators.IsBase64(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isBase64, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsByteLength rule with @IsByteLength', () => { const options = {}; class Example { @Decrators.IsByteLength('test', 'test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isByteLength, args: ['test', 'test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsCreditCard rule with @IsCreditCard', () => { const options = {}; class Example { @Decrators.IsCreditCard(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isCreditCard, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsCurrency rule with @IsCurrency', () => { const options = {}; class Example { @Decrators.IsCurrency(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isCurrency, args: [options], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsEmail rule with @IsEmail', () => { const options = {}; class Example { @Decrators.IsEmail(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isEmail, args: [options], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsFQDN rule with @IsFQDN', () => { const options = {}; class Example { @Decrators.IsFQDN(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isFQDN, args: [options], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsFullWidth rule with @IsFullWidth', () => { const options = {}; class Example { @Decrators.IsFullWidth(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isFullWidth, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsHalfWidth rule with @IsHalfWidth', () => { const options = {}; class Example { @Decrators.IsHalfWidth(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isHalfWidth, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsHexColor rule with @IsHexColor', () => { const options = {}; class Example { @Decrators.IsHexColor(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isHexColor, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsHexadecimal rule with @IsHexadecimal', () => { const options = {}; class Example { @Decrators.IsHexadecimal(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isHexadecimal, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsIP rule with @IsIP', () => { const options = {}; class Example { @Decrators.IsIP('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isIP, args: ['test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsISBN rule with @IsISBN', () => { const options = {}; class Example { @Decrators.IsISBN('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isISBN, args: ['test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsISSN rule with @IsISSN', () => { const options = {}; class Example { @Decrators.IsISSN(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isISSN, args: [options], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsISIN rule with @IsISIN', () => { const options = {}; class Example { @Decrators.IsISIN(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isISIN, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsISO8601 rule with @IsISO8601', () => { const options = {}; class Example { @Decrators.IsISO8601(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isISO8601, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsJSON rule with @IsJSON', () => { const options = {}; class Example { @Decrators.IsJSON(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isJSON, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsLowercase rule with @IsLowercase', () => { const options = {}; class Example { @Decrators.IsLowercase(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isLowercase, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsMobilePhone rule with @IsMobilePhone', () => { const options = {}; class Example { @Decrators.IsMobilePhone('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isMobilePhone, args: ['test', options], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsMongoId rule with @IsMongoId', () => { const options = {}; class Example { @Decrators.IsMongoId(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isMongoId, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsMultibyte rule with @IsMultibyte', () => { const options = {}; class Example { @Decrators.IsMultibyte(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isMultibyte, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsSurrogatePair rule with @IsSurrogatePair', () => { const options = {}; class Example { @Decrators.IsSurrogatePair(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isSurrogatePair, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsURL rule with @IsURL', () => { const options = {}; class Example { @Decrators.IsURL(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isURL, args: [options], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsUUID rule with @IsUUID', () => { const options = {}; class Example { @Decrators.IsUUID('test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isUUID, args: ['test'], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch IsUppercase rule with @IsUppercase', () => { const options = {}; class Example { @Decrators.IsUppercase(options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.isUppercase, args: [], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch Length rule with @Length', () => { const options = {}; class Example { @Decrators.Length(1, 10, options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.length, args: [1, 10], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch MinLength rule with @MinLength', () => { const options = {}; class Example { @Decrators.MinLength(1, options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.minLength, args: [1], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch MaxLength rule with @MaxLength', () => { const options = {}; class Example { @Decrators.MaxLength(1, options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.maxLength, args: [1], options: { message: expect.any(String), ...options, }, }, ]); }); it('should patch Matches rule with @Matches', () => { const options = {}; class Example { @Decrators.Matches('test', 'test', options) example: any; } expect(Reflect.getMetadata('rules', Example)).toEqual([ { field: 'example', handler: Validators.matches, args: ['test', 'test', options], options: { message: expect.any(String), ...options, }, }, ]); }); });
the_stack
import { TransitionItem, StateChanges, ValueContextType, Values, InterpolatorContext, InterpolatorContextType, } from "../Types"; import { getStyleInfo } from "../../Styles/getStyleInfo"; import { useLog } from "../../Hooks"; import { UseLoggerFunction, LoggerLevel, fluidException } from "../../Types"; import { ConfigAnimationType, ConfigWhenStyleType, ConfigWhenInterpolationType, SafeStateConfigType, isConfigWhenStyle, isConfigStyleInterpolation, isConfigPropInterpolation, getResolvedStateName, isConfigWhenValueInterplation, isConfigWhenFactory, ConfigWhenFactoryType, } from "../../Configuration"; import { getAnimationOnEnd } from "../../Animation/Builder/getAnimationOnEnd"; import { useContext, useRef } from "react"; import { removeInterpolation } from "../../Animation/Runner/addInterpolation"; import { Dimensions } from "react-native"; import { InterpolationInfo } from "../Types"; import { unregisterRunningInterpolation } from "../../Animation/Runner/interpolationStorage"; export const useWhenConfig = ( transitionItem: TransitionItem, styleContext: ValueContextType, propContext: ValueContextType, stateChanges: StateChanges, configuration: SafeStateConfigType, animationType?: ConfigAnimationType, ) => { const logger = useLog(transitionItem.label, "cwhen"); const interpolatorContext = useContext(InterpolatorContext); const runningInterpolationsRef = useRef<InterpolationInfo[]>([]); const configs = configuration.when; const added = configs.filter( o => stateChanges.added.find(s => s.name === getResolvedStateName(o.state)) !== undefined, ); const changed = configs.filter( o => stateChanges.changed.find( s => s.name === getResolvedStateName(o.state), ) !== undefined, ); const removed = configs.filter( o => stateChanges.removed.find( s => s.name === getResolvedStateName(o.state), ) !== undefined, ); // Sort order? const allActiveConfigs = [...removed, ...added, ...changed]; if (allActiveConfigs.length === 0) { return; } // Now we are ready to process the active when elements. // Lets loop through and find the unique ones const uniqueConfigs = allActiveConfigs.filter( (v, i, a) => a.indexOf(v) === i, ); // console.log( // transitionItem.label, // uniqueConfigs // .map( // cf => // getResolvedStateName(cf.state) + // " (" + // (removed.indexOf(cf) > -1 ? "removed" : "added") + // ")", // ) // .join(", "), // ); uniqueConfigs.forEach(cf => { const isRemoved = removed.indexOf(cf) > -1; if (isConfigWhenStyle(cf)) { // When with style registerWhenStyle(logger, cf, styleContext, isRemoved, animationType); } else if (isConfigWhenFactory(cf)) { // When with factory registerWhenWithFactory( transitionItem, cf, logger, styleContext, propContext, runningInterpolationsRef.current, interpolatorContext, isRemoved, animationType, ); } else { // When with interpolation registerWhenInterpolations( transitionItem, logger, cf, styleContext, propContext, isRemoved, runningInterpolationsRef.current, interpolatorContext, animationType, ); } }); }; const registerWhenInterpolations = ( transitionItem: TransitionItem, logger: UseLoggerFunction, when: ConfigWhenInterpolationType, styleContext: ValueContextType, propContext: ValueContextType, isRemoved: boolean, runningInterpolations: InterpolationInfo[], interpolatorContext: InterpolatorContextType | null, animationType?: ConfigAnimationType, ) => { // No need to do anything if we don't have any interpolations const interpolations = when.interpolation instanceof Array ? when.interpolation : [when.interpolation]; if (interpolations.length === 0) { return; } if (__DEV__) { logger( () => "Register when(" + getResolvedStateName(when.state) + ") interpolation for " + Object.keys(interpolations).join(", "), LoggerLevel.Verbose, ); } let onBegin = when.onBegin; const onEnd = getAnimationOnEnd( Object.keys(interpolations).length, when.onEnd, ); interpolations.forEach(interpolation => { if (!isRemoved) { // Let us create the animation if (isConfigWhenValueInterplation(interpolation)) { if (!interpolatorContext) { throw fluidException( "A when config element refers to a value but is not " + "contained in a parent fluid view.", ); } const interpolator = interpolatorContext.getInterpolator( interpolation.value.ownerLabel, interpolation.value.valueName, ); if (!interpolator) { throw fluidException( "Could not find interpolator with name " + interpolation.value.valueName + " in component with label " + interpolation.value.ownerLabel, ); } const interpolationInfo = styleContext.addInterpolation( interpolator, interpolation.styleKey, interpolation.inputRange, interpolation.outputRange, interpolation.extrapolate, interpolation.extrapolateLeft, interpolation.extrapolateRight, ); if (interpolationInfo) { runningInterpolations.push(interpolationInfo); } } else if (isConfigStyleInterpolation(interpolation)) { // console.log( // transitionItem.label, // "Adding", // interpolation.styleKey, // "[" + interpolation.outputRange.join(", ") + "]", // ); const interpolationInfo = styleContext.addAnimation( interpolation.styleKey, interpolation.inputRange, interpolation.outputRange, interpolation.animation || when.animation || animationType, onBegin, onEnd, interpolation.extrapolate, interpolation.extrapolateLeft, interpolation.extrapolateRight, when.loop, when.flip, when.yoyo, ); if (interpolationInfo) { runningInterpolations.push(interpolationInfo); } } else if (isConfigPropInterpolation(interpolation)) { const interpolationInfo = propContext.addAnimation( interpolation.propName, interpolation.inputRange, interpolation.outputRange, interpolation.animation || when.animation || animationType, onBegin, onEnd, interpolation.extrapolate, interpolation.extrapolateLeft, interpolation.extrapolateRight, when.loop, when.flip, when.yoyo, ); if (interpolationInfo) { runningInterpolations.push(interpolationInfo); } } } else { // Removed if (isConfigWhenValueInterplation(interpolation)) { removeInterpolation(transitionItem.id, interpolation.styleKey); } // NO need to stop these I think, we'll just let them finish by themselves. else if (isConfigStyleInterpolation(interpolation)) { // console.log( // transitionItem.label, // "Adding", // interpolation.styleKey, // "[" + interpolation.outputRange.join(", ") + "]", // ); removePossibleInterpolation( transitionItem.id, interpolation.styleKey, runningInterpolations, ); } else if (isConfigPropInterpolation(interpolation)) { removePossibleInterpolation( transitionItem.id, interpolation.propName, runningInterpolations, ); } } }); }; const removePossibleInterpolation = ( id: number, key: string, runningInterpolations: InterpolationInfo[], ) => { const index = runningInterpolations.findIndex(p => p.key === key); if (index > -1) { unregisterRunningInterpolation(id, key, runningInterpolations[index].id); runningInterpolations.splice(index, 1); } }; const registerWhenWithFactory = ( transitionItem: TransitionItem, when: ConfigWhenFactoryType, logger: UseLoggerFunction, styleContext: ValueContextType, propContext: ValueContextType, runningInterpolations: InterpolationInfo[], interpolatorContext: InterpolatorContextType | null, isRemoved: boolean, animationType?: ConfigAnimationType, ) => { const screenSize = Dimensions.get("screen"); // Register custom interpolation const factoryResults = when.whenFactory({ screenSize, metrics: transitionItem.metrics(), state: getResolvedStateName(when.state), stateValue: typeof when.state !== "string" ? when.state.value : undefined, }); let interpolations = factoryResults.interpolation instanceof Array ? factoryResults.interpolation : [factoryResults.interpolation]; registerWhenInterpolations( transitionItem, logger, { ...when, interpolation: interpolations, animation: animationType, } as ConfigWhenInterpolationType, styleContext, propContext, isRemoved, runningInterpolations, interpolatorContext, animationType, ); }; const registerWhenStyle = ( logger: UseLoggerFunction, when: ConfigWhenStyleType, styleContext: ValueContextType, isRemoved: boolean, animationType?: ConfigAnimationType, ) => { // Find all values that needs interpolation const { styleKeys: nextStyleKeys, styleValues: nextStyleValues, } = getStyleInfo(when.style); const interpolations: Values = {}; // Find all values that needs interpolation nextStyleKeys.forEach(key => { if (nextStyleValues[key] !== styleContext.nextValues[key]) { interpolations[key] = nextStyleValues[key]; } }); if (Object.keys(interpolations).length === 0) return; if (__DEV__) { logger( () => "Register when(" + getResolvedStateName(when.state) + ") style change for " + Object.keys(interpolations).join(", "), LoggerLevel.Verbose, ); } let onBegin = when.onBegin; const onEnd = getAnimationOnEnd( Object.keys(interpolations).length, when.onEnd, ); // Register interpolations Object.keys(interpolations).forEach(key => { const outputRange = isRemoved ? [ interpolations[key], styleContext.descriptors[key] ? styleContext.descriptors[key].defaultValue : undefined, ] : [undefined, interpolations[key]]; // Let us create the animation styleContext.addAnimation( key, undefined, outputRange, when.animation || animationType || styleContext.descriptors[key].defaultAnimation, onBegin, onEnd, styleContext.descriptors[key].extrapolate, undefined, undefined, when.loop, when.flip, when.yoyo, ); }); };
the_stack
import '../../../test/common-test-setup-karma'; import './gr-repo-detail-list.js'; import {GrRepoDetailList} from './gr-repo-detail-list'; import {page} from '../../../utils/page-wrapper-utils'; import { addListenerForTest, mockPromise, queryAll, queryAndAssert, stubRestApi, } from '../../../test/test-utils'; import {RepoDetailView} from '../../core/gr-navigation/gr-navigation'; import { BranchInfo, EmailAddress, GitRef, GroupId, GroupName, ProjectAccessGroups, ProjectAccessInfoMap, RepoName, TagInfo, Timestamp, TimezoneOffset, } from '../../../types/common'; import {GerritView} from '../../../services/router/router-model'; import {GrButton} from '../../shared/gr-button/gr-button'; import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions'; import {PageErrorEvent} from '../../../types/events'; import {GrOverlay} from '../../shared/gr-overlay/gr-overlay'; import {GrDialog} from '../../shared/gr-dialog/gr-dialog'; import {GrListView} from '../../shared/gr-list-view/gr-list-view'; import {SHOWN_ITEMS_COUNT} from '../../../constants/constants'; const basicFixture = fixtureFromElement('gr-repo-detail-list'); function branchGenerator(counter: number) { return { ref: `refs/heads/test${counter}` as GitRef, revision: '9c9d08a438e55e52f33b608415e6dddd9b18550d', web_links: [ { name: 'diffusion', url: `https://git.example.org/branch/test;refs/heads/test${counter}`, }, ], }; } function createBranchesList(n: number) { const branches = []; for (let i = 0; i < n; ++i) { branches.push(branchGenerator(i)); } return branches; } function tagGenerator(counter: number) { return { ref: `refs/tags/test${counter}` as GitRef, revision: '9c9d08a438e55e52f33b608415e6dddd9b18550d', can_delete: false, web_links: [ { name: 'diffusion', url: `https://git.example.org/tag/test;refs/tags/test${counter}`, }, ], message: 'Annotated tag', tagger: { name: 'Test User', email: 'test.user@gmail.com' as EmailAddress, date: '2017-09-19 14:54:00.000000000' as Timestamp, tz: 540 as TimezoneOffset, }, }; } function createTagsList(n: number) { const tags = []; for (let i = 0; i < n; ++i) { tags.push(tagGenerator(i)); } return tags; } suite('gr-repo-detail-list', () => { suite('Branches', () => { let element: GrRepoDetailList; let branches: BranchInfo[]; setup(async () => { element = basicFixture.instantiate(); await element.updateComplete; element.detailType = RepoDetailView.BRANCHES; sinon.stub(page, 'show'); }); suite('list of repo branches', () => { setup(async () => { branches = [ { ref: 'HEAD' as GitRef, revision: 'master', }, ].concat(createBranchesList(25)); stubRestApi('getRepoBranches').returns(Promise.resolve(branches)); element.params = { view: GerritView.REPO, repo: 'test' as RepoName, detail: RepoDetailView.BRANCHES, }; await element.paramsChanged(); await element.updateComplete; }); test('test for branch in the list', () => { assert.equal(element.items![3].ref, 'refs/heads/test2'); }); test('test for web links in the branches list', () => { assert.equal( element.items![3].web_links![0].url, 'https://git.example.org/branch/test;refs/heads/test2' ); }); test('test for refs/heads/ being striped from ref', () => { assert.equal( element.stripRefs(element.items![3].ref, element.detailType), 'test2' ); }); test('items', () => { assert.equal(queryAll<HTMLTableElement>(element, '.table').length, 25); }); test('Edit HEAD button not admin', async () => { sinon.stub(element, 'getLoggedIn').returns(Promise.resolve(true)); stubRestApi('getRepoAccess').returns( Promise.resolve({ test: { revision: 'xxxx', local: { 'refs/*': { permissions: { owner: {rules: {xxx: {action: 'ALLOW', force: false}}}, }, }, }, owner_of: ['refs/*'] as GitRef[], groups: { xxxx: { id: 'xxxx' as GroupId, url: 'test', name: 'test' as GroupName, }, } as ProjectAccessGroups, config_web_links: [{name: 'gitiles', url: 'test'}], }, } as ProjectAccessInfoMap) ); await element.determineIfOwner('test' as RepoName); assert.equal(element.isOwner, false); assert.equal( getComputedStyle( queryAndAssert<HTMLSpanElement>(element, '.revisionNoEditing') ).display, 'inline' ); assert.equal( getComputedStyle( queryAndAssert<HTMLSpanElement>(element, '.revisionEdit') ).display, 'none' ); }); test('Edit HEAD button admin', async () => { const saveBtn = queryAndAssert<GrButton>(element, '.saveBtn'); const cancelBtn = queryAndAssert<GrButton>(element, '.cancelBtn'); const editBtn = queryAndAssert<GrButton>(element, '.editBtn'); const revisionNoEditing = queryAndAssert<HTMLSpanElement>( element, '.revisionNoEditing' ); const revisionWithEditing = queryAndAssert<HTMLSpanElement>( element, '.revisionWithEditing' ); sinon.stub(element, 'getLoggedIn').returns(Promise.resolve(true)); stubRestApi('getRepoAccess').returns( Promise.resolve({ test: { revision: 'xxxx', local: { 'refs/*': { permissions: { owner: {rules: {xxx: {action: 'ALLOW', force: false}}}, }, }, }, is_owner: true, owner_of: ['refs/*'] as GitRef[], groups: { xxxx: { id: 'xxxx' as GroupId, url: 'test', name: 'test' as GroupName, }, } as ProjectAccessGroups, config_web_links: [{name: 'gitiles', url: 'test'}], }, } as ProjectAccessInfoMap) ); const handleSaveRevisionStub = sinon.stub( element, 'handleSaveRevision' ); await element.determineIfOwner('test' as RepoName); assert.equal(element.isOwner, true); // The revision container for non-editing enabled row is not visible. assert.equal(getComputedStyle(revisionNoEditing).display, 'none'); // The revision container for editing enabled row is visible. assert.notEqual( getComputedStyle( queryAndAssert<HTMLSpanElement>(element, '.revisionEdit') ).display, 'none' ); // The revision and edit button are visible. assert.notEqual(getComputedStyle(revisionWithEditing).display, 'none'); assert.notEqual(getComputedStyle(editBtn).display, 'none'); // The input, cancel, and save buttons are not visible. const hiddenElements = queryAll<HTMLTableElement>( element, '.canEdit .editItem' ); for (const item of hiddenElements) { assert.equal(getComputedStyle(item).display, 'none'); } MockInteractions.tap(editBtn); await element.updateComplete; // The revision and edit button are not visible. assert.equal(getComputedStyle(revisionWithEditing).display, 'none'); assert.equal(getComputedStyle(editBtn).display, 'none'); // The input, cancel, and save buttons are not visible. for (const item of hiddenElements) { assert.notEqual(getComputedStyle(item).display, 'none'); } // The revised ref was set correctly assert.equal(element.revisedRef, 'master' as GitRef); assert.isFalse(saveBtn.disabled); // Delete the ref. element.revisedRef = '' as GitRef; await element.updateComplete; assert.isTrue(saveBtn.disabled); // Change the ref to something else element.revisedRef = 'newRef' as GitRef; element.repo = 'test' as RepoName; await element.updateComplete; assert.isFalse(saveBtn.disabled); // Save button calls handleSave. since this is stubbed, the edit // section remains open. MockInteractions.tap(saveBtn); assert.isTrue(handleSaveRevisionStub.called); // When cancel is tapped, the edit secion closes. MockInteractions.tap(cancelBtn); await element.updateComplete; // The revision and edit button are visible. assert.notEqual(getComputedStyle(revisionWithEditing).display, 'none'); assert.notEqual(getComputedStyle(editBtn).display, 'none'); // The input, cancel, and save buttons are not visible. for (const item of hiddenElements) { assert.equal(getComputedStyle(item).display, 'none'); } }); test('handleSaveRevision with invalid rev', async () => { element.isEditing = true; stubRestApi('setRepoHead').returns( Promise.resolve({ status: 400, } as Response) ); await element.setRepoHead('test' as RepoName, 'newRef' as GitRef, 1); assert.isTrue(element.isEditing); }); test('handleSaveRevision with valid rev', async () => { element.isEditing = true; stubRestApi('setRepoHead').returns( Promise.resolve({ status: 200, } as Response) ); await element.setRepoHead('test' as RepoName, 'newRef' as GitRef, 1); assert.isFalse(element.isEditing); }); test('test computeItemName', () => { assert.deepEqual( element.computeItemName(RepoDetailView.BRANCHES), 'Branch' ); assert.deepEqual(element.computeItemName(RepoDetailView.TAGS), 'Tag'); }); }); suite('list with less then 25 branches', () => { setup(async () => { branches = createBranchesList(25); stubRestApi('getRepoBranches').returns(Promise.resolve(branches)); element.params = { view: GerritView.REPO, repo: 'test' as RepoName, detail: RepoDetailView.BRANCHES, }; await element.paramsChanged(); await element.updateComplete; }); test('items', () => { assert.equal(queryAll<HTMLTableElement>(element, '.table').length, 25); }); }); suite('filter', () => { test('paramsChanged', async () => { const stub = stubRestApi('getRepoBranches').returns( Promise.resolve(branches) ); element.params = { view: GerritView.REPO, repo: 'test' as RepoName, detail: RepoDetailView.BRANCHES, filter: 'test', offset: 25, }; await element.paramsChanged(); assert.equal(stub.lastCall.args[0], 'test'); assert.equal(stub.lastCall.args[1], 'test'); assert.equal(stub.lastCall.args[2], 25); assert.equal(stub.lastCall.args[3], 25); }); }); suite('404', () => { test('fires page-error', async () => { const response = {status: 404} as Response; stubRestApi('getRepoBranches').callsFake( (_filter, _repo, _reposBranchesPerPage, _opt_offset, errFn) => { if (errFn !== undefined) { errFn(response); } return Promise.resolve([]); } ); const promise = mockPromise(); addListenerForTest(document, 'page-error', e => { assert.deepEqual((e as PageErrorEvent).detail.response, response); promise.resolve(); }); element.params = { view: GerritView.REPO, repo: 'test' as RepoName, detail: RepoDetailView.BRANCHES, filter: 'test', offset: 25, }; element.paramsChanged(); await promise; }); }); }); suite('Tags', () => { let element: GrRepoDetailList; let tags: TagInfo[]; setup(async () => { element = basicFixture.instantiate(); await element.updateComplete; element.detailType = RepoDetailView.TAGS; sinon.stub(page, 'show'); }); suite('list of repo tags', () => { setup(async () => { tags = createTagsList(26); stubRestApi('getRepoTags').returns(Promise.resolve(tags)); element.params = { view: GerritView.REPO, repo: 'test' as RepoName, detail: RepoDetailView.TAGS, }; await element.paramsChanged(); await element.updateComplete; }); test('test for tag in the list', async () => { assert.equal(element.items![2].ref, 'refs/tags/test2'); }); test('test for tag message in the list', async () => { assert.equal((element.items as TagInfo[])![2].message, 'Annotated tag'); }); test('test for tagger in the tag list', async () => { const tagger = { name: 'Test User', email: 'test.user@gmail.com' as EmailAddress, date: '2017-09-19 14:54:00.000000000' as Timestamp, tz: 540 as TimezoneOffset, }; assert.deepEqual((element.items as TagInfo[])![2].tagger, tagger); }); test('test for web links in the tags list', async () => { assert.equal( element.items![2].web_links![0].url, 'https://git.example.org/tag/test;refs/tags/test2' ); }); test('test for refs/tags/ being striped from ref', async () => { assert.equal( element.stripRefs(element.items![2].ref, element.detailType), 'test2' ); }); test('items', () => { assert.equal(element.items!.slice(0, SHOWN_ITEMS_COUNT)!.length, 25); }); }); suite('list with less then 25 tags', () => { setup(async () => { tags = createTagsList(25); stubRestApi('getRepoTags').returns(Promise.resolve(tags)); element.params = { view: GerritView.REPO, repo: 'test' as RepoName, detail: RepoDetailView.TAGS, }; await element.paramsChanged(); await element.updateComplete; }); test('items', () => { assert.equal(element.items!.slice(0, SHOWN_ITEMS_COUNT)!.length, 25); }); }); suite('filter', () => { test('paramsChanged', async () => { const stub = stubRestApi('getRepoTags').returns(Promise.resolve(tags)); element.params = { view: GerritView.REPO, repo: 'test' as RepoName, detail: RepoDetailView.TAGS, filter: 'test', offset: 25, }; await element.paramsChanged(); assert.equal(stub.lastCall.args[0], 'test'); assert.equal(stub.lastCall.args[1], 'test'); assert.equal(stub.lastCall.args[2], 25); assert.equal(stub.lastCall.args[3], 25); }); }); suite('create new', () => { test('handleCreateClicked called when create-click fired', () => { const handleCreateClickedStub = sinon.stub( element, 'handleCreateClicked' ); queryAndAssert<GrListView>(element, 'gr-list-view').dispatchEvent( new CustomEvent('create-clicked', { composed: true, bubbles: true, }) ); assert.isTrue(handleCreateClickedStub.called); }); test('handleCreateClicked opens modal', () => { queryAndAssert<GrOverlay>(element, '#createOverlay'); const openStub = sinon.stub( queryAndAssert<GrOverlay>(element, '#createOverlay'), 'open' ); element.handleCreateClicked(); assert.isTrue(openStub.called); }); test('handleCreateItem called when confirm fired', () => { const handleCreateItemStub = sinon.stub(element, 'handleCreateItem'); queryAndAssert<GrDialog>(element, '#createDialog').dispatchEvent( new CustomEvent('confirm', { composed: true, bubbles: true, }) ); assert.isTrue(handleCreateItemStub.called); }); test('handleCloseCreate called when cancel fired', () => { const handleCloseCreateStub = sinon.stub(element, 'handleCloseCreate'); queryAndAssert<GrDialog>(element, '#createDialog').dispatchEvent( new CustomEvent('cancel', { composed: true, bubbles: true, }) ); assert.isTrue(handleCloseCreateStub.called); }); }); suite('404', () => { test('fires page-error', async () => { const response = {status: 404} as Response; stubRestApi('getRepoTags').callsFake( (_filter, _repo, _reposTagsPerPage, _opt_offset, errFn) => { if (errFn !== undefined) { errFn(response); } return Promise.resolve([]); } ); const promise = mockPromise(); addListenerForTest(document, 'page-error', e => { assert.deepEqual((e as PageErrorEvent).detail.response, response); promise.resolve(); }); element.params = { view: GerritView.REPO, repo: 'test' as RepoName, detail: RepoDetailView.TAGS, filter: 'test', offset: 25, }; element.paramsChanged(); await promise; }); }); test('computeItemName', () => { assert.equal(element.computeItemName(RepoDetailView.BRANCHES), 'Branch'); assert.equal(element.computeItemName(RepoDetailView.TAGS), 'Tag'); }); }); });
the_stack
import { FabricEnvironmentManager, ConnectedState } from '../../../extension/fabric/environments/FabricEnvironmentManager'; import * as chai from 'chai'; import * as sinon from 'sinon'; import { FabricEnvironmentRegistryEntry, IFabricEnvironmentConnection, EnvironmentType } from 'ibm-blockchain-platform-common'; import { FabricEnvironmentConnection } from 'ibm-blockchain-platform-environment-v1'; import { TestUtil } from '../../TestUtil'; import { TimerUtil } from '../../../extension/util/TimerUtil'; import { ExtensionCommands } from '../../../ExtensionCommands'; const should: Chai.Should = chai.should(); // tslint:disable: no-unused-expression describe('FabricEnvironmentManager', () => { const environmentManager: FabricEnvironmentManager = FabricEnvironmentManager.instance(); let mockEnvironmentConnection: sinon.SinonStubbedInstance<FabricEnvironmentConnection>; let sandbox: sinon.SinonSandbox; let registryEntry: FabricEnvironmentRegistryEntry; beforeEach(async () => { sandbox = sinon.createSandbox(); mockEnvironmentConnection = sandbox.createStubInstance(FabricEnvironmentConnection); environmentManager['connection'] = null; registryEntry = new FabricEnvironmentRegistryEntry(); registryEntry.name = 'myConnection'; registryEntry.managedRuntime = false; }); before(async () => { await TestUtil.setupTests(sandbox); }); afterEach(async () => { sandbox.restore(); environmentManager['connection'] = null; }); describe('#getConnection', () => { it('should get the connection', () => { environmentManager['connection'] = ((mockEnvironmentConnection as any) as IFabricEnvironmentConnection); environmentManager.getConnection().should.equal(mockEnvironmentConnection); }); }); describe('#getEnvironmentRegistryEntry', () => { it('should get the registry entry', () => { environmentManager['environmentRegistryEntry'] = registryEntry; environmentManager.getEnvironmentRegistryEntry().should.equal(registryEntry); }); }); describe('#connect', () => { it('should store the connection and emit an event', () => { const listenerStub: sinon.SinonStub = sandbox.stub(); const startEnivronmentRefreshStub: sinon.SinonStub = sandbox.stub(FabricEnvironmentManager.instance(), 'startEnvironmentRefresh'); environmentManager.once('connected', listenerStub); environmentManager.connect((mockEnvironmentConnection as any) as IFabricEnvironmentConnection, registryEntry, ConnectedState.CONNECTED); environmentManager.getConnection().should.equal(mockEnvironmentConnection); environmentManager.getEnvironmentRegistryEntry().should.equal(registryEntry); environmentManager.getState().should.equal(ConnectedState.CONNECTED); listenerStub.should.have.been.calledOnceWithExactly(); startEnivronmentRefreshStub.should.have.been.calledOnce; }); it('should not start environment refresh if requested', () => { const listenerStub: sinon.SinonStub = sandbox.stub(); const startEnivronmentRefreshStub: sinon.SinonStub = sandbox.stub(FabricEnvironmentManager.instance(), 'startEnvironmentRefresh'); environmentManager.once('connected', listenerStub); environmentManager.connect((mockEnvironmentConnection as any) as IFabricEnvironmentConnection, registryEntry, ConnectedState.CONNECTED, false); environmentManager.getConnection().should.equal(mockEnvironmentConnection); environmentManager.getEnvironmentRegistryEntry().should.equal(registryEntry); environmentManager.getState().should.equal(ConnectedState.CONNECTED); listenerStub.should.have.been.calledOnceWithExactly(); startEnivronmentRefreshStub.should.have.not.been.called; }); }); describe('#disconnect', () => { it('should clear the connection and emit an event', () => { const stopEnivronmentRefreshStub: sinon.SinonStub = sandbox.stub(FabricEnvironmentManager.instance(), 'stopEnvironmentRefresh'); const listenerStub: sinon.SinonStub = sandbox.stub(); environmentManager['connection'] = mockEnvironmentConnection; environmentManager['environmentRegistryEntry'] = registryEntry; environmentManager['state'] = ConnectedState.CONNECTED; environmentManager.once('disconnected', listenerStub); environmentManager.disconnect(); should.equal(environmentManager.getConnection(), null); should.equal(environmentManager.getEnvironmentRegistryEntry(), null); environmentManager.getState().should.equal(ConnectedState.DISCONNECTED); mockEnvironmentConnection.disconnect.should.have.been.called; listenerStub.should.have.been.calledOnceWithExactly(); stopEnivronmentRefreshStub.should.have.been.calledOnce; }); it('should handle no connectionn and emit an event', () => { const stopEnivronmentRefreshStub: sinon.SinonStub = sandbox.stub(FabricEnvironmentManager.instance(), 'stopEnvironmentRefresh'); const listenerStub: sinon.SinonStub = sandbox.stub(); environmentManager.once('disconnected', listenerStub); environmentManager.disconnect(); should.equal(environmentManager.getConnection(), null); should.equal(environmentManager.getEnvironmentRegistryEntry(), null); environmentManager.getState().should.equal(ConnectedState.DISCONNECTED); listenerStub.should.have.been.calledOnceWithExactly(); stopEnivronmentRefreshStub.should.have.been.calledOnce; }); }); describe('#getState', () => { it('should get that state', () => { environmentManager['state'] = ConnectedState.CONNECTED; const result: ConnectedState = environmentManager.getState(); result.should.equal(ConnectedState.CONNECTED); }); }); describe('#setState', () => { it('should set new state', () => { environmentManager['state'] = ConnectedState.CONNECTING; environmentManager.setState(ConnectedState.CONNECTED); const result: ConnectedState = environmentManager.getState(); result.should.equal(ConnectedState.CONNECTED); }); }); describe('#startEnvironmentRefresh', () => { let setIntervalStub: sinon.SinonStub; let cancelIntervalStub: sinon.SinonStub; beforeEach(() => { setIntervalStub = sandbox.stub(TimerUtil, 'setInterval').returns({ name: 'timeout' }); cancelIntervalStub = sandbox.stub(TimerUtil, 'cancelInterval'); }); it('should start the auto refresh interval', () => { const entry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({ name: 'myFabric', environmentType: EnvironmentType.OPS_TOOLS_ENVIRONMENT }); environmentManager['state'] = ConnectedState.CONNECTING; environmentManager['environmentRegistryEntry'] = entry; environmentManager['timeoutObject'] = undefined; environmentManager.startEnvironmentRefresh(); setIntervalStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, [entry, false], 10000); cancelIntervalStub.should.not.have.been.called; }); it('should start the auto refresh interval and cancel the old one if set', () => { const entry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({ name: 'myFabric', environmentType: EnvironmentType.OPS_TOOLS_ENVIRONMENT }); environmentManager['state'] = ConnectedState.CONNECTING; environmentManager['environmentRegistryEntry'] = entry; environmentManager['timeoutObject'] = { name: 'timeout' } as any; environmentManager.startEnvironmentRefresh(); setIntervalStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, [entry, false], 10000); cancelIntervalStub.should.have.been.calledWith({ name: 'timeout' }); }); it('should not start the auto refresh interval if not ops tools', () => { const entry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({ name: 'myFabric', environmentType: EnvironmentType.ENVIRONMENT }); environmentManager['state'] = ConnectedState.CONNECTING; environmentManager['environmentRegistryEntry'] = entry; environmentManager.startEnvironmentRefresh(); setIntervalStub.should.not.have.been.called; cancelIntervalStub.should.have.been.called; }); it('should not start the auto refresh interval if state is not connecting or connected', () => { const entry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({ name: 'myFabric', environmentType: EnvironmentType.OPS_TOOLS_ENVIRONMENT }); environmentManager['state'] = ConnectedState.DISCONNECTED; environmentManager['environmentRegistryEntry'] = entry; environmentManager.startEnvironmentRefresh(); setIntervalStub.should.not.have.been.called; cancelIntervalStub.should.have.been.called; }); }); describe('#stopEnvironmentRefresh', () => { let cancelIntervalStub: sinon.SinonStub; beforeEach(() => { cancelIntervalStub = sandbox.stub(TimerUtil, 'cancelInterval'); }); it('should cancel interval', () => { environmentManager['timeoutObject'] = { name: 'timeout' } as any; environmentManager.stopEnvironmentRefresh(); cancelIntervalStub.should.have.been.called; }); it('should not cancel interval if timeout object not set', () => { environmentManager['timeoutObject'] = undefined; environmentManager.stopEnvironmentRefresh(); cancelIntervalStub.should.not.have.been.called; }); }); });
the_stack
namespace pxsim.codal.music { export enum WaveShape { Sine = 0, Sawtooth = 1, Triangle = 2, Square = 3, Noise = 4 } export enum InterpolationEffect { None = 0, Linear = 1, Curve = 2, ExponentialRising = 5, ExponentialFalling = 6, ArpeggioRisingMajor = 8, ArpeggioRisingMinor = 10, ArpeggioRisingDiminished = 12, ArpeggioRisingChromatic = 14, ArpeggioRisingWholeTone = 16, ArpeggioFallingMajor = 9, ArpeggioFallingMinor = 11, ArpeggioFallingDiminished = 13, ArpeggioFallingChromatic = 15, ArpeggioFallingWholeTone = 17, Logarithmic = 18 } export enum Effect { None = 0, Vibrato = 1, Tremolo = 2, Warble = 3 } export class Sound { src: string; constructor() { this.src = "000000000000000000000000000000000000000000000000000000000000000000000000" } get wave(): WaveShape { return this.getValue(0, 1); } set wave(value: WaveShape) { this.setValue(0, constrain(value, 0, 4), 1); } get volume() { return this.getValue(1, 4); } set volume(value: number) { this.setValue(1, constrain(value, 0, 1023), 4); } get frequency() { return this.getValue(5, 4); } set frequency(value: number) { this.setValue(5, value, 4); } get duration() { return this.getValue(9, 4); } set duration(value: number) { this.setValue(9, value, 4); } get shape(): InterpolationEffect { return this.getValue(13, 2); } set shape(value: InterpolationEffect) { this.setValue(13, value, 2); } get endFrequency() { return this.getValue(18, 4); } set endFrequency(value: number) { this.setValue(18, value, 4); } get endVolume() { return this.getValue(26, 4); } set endVolume(value: number) { this.setValue(26, constrain(value, 0, 1023), 4); } get steps() { return this.getValue(30, 4); } set steps(value: number) { this.setValue(30, value, 4); } get fx(): Effect { return this.getValue(34, 2); } set fx(value: Effect) { this.setValue(34, constrain(value, 0, 3), 2); } get fxParam() { return this.getValue(36, 4); } set fxParam(value: number) { this.setValue(36, value, 4); } get fxnSteps() { return this.getValue(40, 4); } set fxnSteps(value: number) { this.setValue(40, value, 4); } get frequencyRandomness() { return this.getValue(44, 4); } set frequencyRandomness(value: number) { this.setValue(44, value, 4); } get endFrequencyRandomness() { return this.getValue(48, 4); } set endFrequencyRandomness(value: number) { this.setValue(48, value, 4); } get volumeRandomness() { return this.getValue(52, 4); } set volumeRandomness(value: number) { this.setValue(52, value, 4); } get endVolumeRandomness() { return this.getValue(56, 4); } set endVolumeRandomness(value: number) { this.setValue(56, value, 4); } get durationRandomness() { return this.getValue(60, 4); } set durationRandomness(value: number) { this.setValue(60, value, 4); } get fxParamRandomness() { return this.getValue(64, 4); } set fxParamRandomness(value: number) { this.setValue(64, value, 4); } get fxnStepsRandomness() { return this.getValue(68, 4); } set fxnStepsRandomness(value: number) { this.setValue(68, value, 4); } copy() { const result = new Sound(); result.src = this.src.slice(0); return result; } protected setValue(offset: number, value: number, length: number) { value = constrain(value | 0, 0, Math.pow(10, length) - 1); this.src = this.src.substr(0, offset) + formatNumber(value, length) + this.src.substr(offset + length); } protected getValue(offset: number, length: number) { return parseInt(this.src.substr(offset, length)); } } function formatNumber(num: number, length: number) { let result = num + ""; while (result.length < length) result = "0" + result; return result; } interface PendingSound { notes: string; onFinished: () => void; onCancelled: () => void; } let playing = false; let soundQueue: PendingSound[]; let cancellationToken = { cancelled: false }; export function __playSoundExpression(notes: string, waitTillDone: boolean): void { if (!soundQueue) soundQueue = []; const cb = getResume(); const soundPromise = new Promise<void>((resolve, reject) => { soundQueue.push({ notes, onFinished: resolve, onCancelled: reject }); }) if (!playing) { playNextSoundAsync(); } if (!waitTillDone) cb(); else soundPromise.then(cb); } async function playNextSoundAsync() { if (soundQueue.length) { playing = true; const sound = soundQueue.shift(); let currentToken = cancellationToken; try { await playSoundExpressionAsync(sound.notes, () => currentToken.cancelled); if (currentToken.cancelled) { sound.onCancelled(); } else { sound.onFinished(); } } catch { sound.onCancelled(); } playNextSoundAsync(); } else { playing = false; } } export function clearSoundQueue() { soundQueue = []; cancellationToken.cancelled = true; cancellationToken = { cancelled: false }; } export function playSoundExpressionAsync(notes: string, isCancelled?: () => boolean, onPull?: (freq: number, volume: number) => void) { const synth = new SoundEmojiSynthesizer(0); const soundEffects = parseSoundEffects(notes); synth.play(soundEffects); let cancelled = false; return Promise.race([ delayAsync(synth.totalDuration()) .then(() => { // If safari didn't allow the sound to play for some reason, // it will get delayed until the user does something that // unmutes it. make sure we cancel it so that it doesn't // play long after it was supposed to cancelled = true }), AudioContextManager.playPCMBufferStreamAsync(() => { if (!synth.effect) return undefined; const buff = synth.pull(); if (onPull) onPull(synth.frequency, synth.volume) const arr = new Float32Array(buff.length); for (let i = 0; i < buff.length; i++) { // Buffer is (0, 1023) we need to map it to (-1, 1) arr[i] = ((buff[i] - 512) / 512); } return arr; }, synth.sampleRate, 0.03, () => cancelled || (isCancelled && isCancelled())) ]); } export function __stopSoundExpressions() { clearSoundQueue(); AudioContextManager.stopAll(); } /** * Adapted from lancaster-university/codal-microbit-v2 * https://github.com/lancaster-university/codal-microbit-v2/blob/master/source/SoundExpressions.cpp */ function parseSoundEffects(notes: string) { // https://github.com/lancaster-university/codal-microbit-v2/blob/master/source/SoundExpressions.cpp#L57 // 72 characters of sound data comma separated const charsPerEffect = 72; const effectCount = Math.floor((notes.length + 1) / (charsPerEffect + 1)); const expectedLength = effectCount * (charsPerEffect + 1) - 1; if (notes.length != expectedLength) { return []; } const soundEffects: SoundEffect[] = []; for (let i = 0; i < effectCount; ++i) { const start = i * charsPerEffect + i; if (start > 0 && notes[start - 1] != ',') { return []; } const effect = blankSoundEffect(); if (!parseSoundExpression(notes.substr(start), effect)) { return []; } soundEffects.push(effect); } return soundEffects; } export interface TonePrint { tonePrint: (arg: number[], position: number) => number; parameter: number[]; } export interface ToneEffect { effect: (synth: SoundEmojiSynthesizer, context: ToneEffect) => void; step: number; steps: number; parameter: number[]; parameter_p: Progression[]; } export interface SoundEffect { frequency: number; volume: number; duration: number; tone: TonePrint; effects: ToneEffect[]; } export function parseSoundExpression(soundChars: string, fx: SoundEffect) { // https://github.com/lancaster-university/codal-microbit-v2/blob/master/source/SoundExpressions.cpp#L115 // Encoded as a sequence of zero padded decimal strings. // This encoding is worth reconsidering if we can! // The ADSR effect (and perhaps others in future) has two parameters which cannot be expressed. // 72 chars total // [0] 0-4 wave let wave = parseInt(soundChars.substr(0, 1)); // [1] 0000-1023 volume let effectVolume = parseInt(soundChars.substr(1, 4)); // [5] 0000-9999 frequency let frequency = parseInt(soundChars.substr(5, 4)); // [9] 0000-9999 duration let duration = parseInt(soundChars.substr(9, 4)); // [13] 00 shape (specific known values) let shape = parseInt(soundChars.substr(13, 2)); // [15] XXX unused/bug. This was startFrequency but we use frequency above. // [18] 0000-9999 end frequency let endFrequency = parseInt(soundChars.substr(18, 4)); // [22] XXXX unused. This was start volume but we use volume above. // [26] 0000-1023 end volume let endVolume = parseInt(soundChars.substr(26, 4)); // [30] 0000-9999 steps let steps = parseInt(soundChars.substr(30, 4)); // [34] 00-03 fx choice let fxChoice = parseInt(soundChars.substr(34, 2)); // [36] 0000-9999 fxParam let fxParam = parseInt(soundChars.substr(36, 4)); // [40] 0000-9999 fxnSteps let fxnSteps = parseInt(soundChars.substr(40, 4)); // Details that encoded randomness to be applied when frame is used: // Can the randomness cause any parameters to go out of range? // [44] 0000-9999 frequency random frequency = applyRandom(frequency, parseInt(soundChars.substr(44, 4))); // [48] 0000-9999 end frequency random endFrequency = applyRandom(endFrequency, parseInt(soundChars.substr(48, 4))); // [52] 0000-9999 volume random effectVolume = applyRandom(effectVolume, parseInt(soundChars.substr(52, 4))); // [56] 0000-9999 end volume random endVolume = applyRandom(endVolume, parseInt(soundChars.substr(56, 4))); // [60] 0000-9999 duration random duration = applyRandom(duration, parseInt(soundChars.substr(60, 4))); // [64] 0000-9999 fxParamRandom fxParam = applyRandom(fxParam, parseInt(soundChars.substr(64, 4))); // [68] 0000-9999 fxnStepsRandom fxnSteps = applyRandom(fxnSteps, parseInt(soundChars.substr(68, 4))); if (frequency == -1 || endFrequency == -1 || effectVolume == -1 || endVolume == -1 || duration == -1 || fxParam == -1 || fxnSteps == -1) { return false; } let volumeScaleFactor = 1; switch(wave) { case 0: fx.tone.tonePrint = Synthesizer.SineTone; break; case 1: fx.tone.tonePrint = Synthesizer.SawtoothTone; break; case 2: fx.tone.tonePrint = Synthesizer.TriangleTone; break; case 3: fx.tone.tonePrint = Synthesizer.SquareWaveTone; break; case 4: fx.tone.tonePrint = Synthesizer.NoiseTone; break; } fx.frequency = frequency; fx.duration = duration; fx.effects[0].steps = steps; switch(shape) { case 0: fx.effects[0].effect = SoundSynthesizerEffects.noInterpolation; break; case 1: fx.effects[0].effect = SoundSynthesizerEffects.linearInterpolation; fx.effects[0].parameter[0] = endFrequency; break; case 2: fx.effects[0].effect = SoundSynthesizerEffects.curveInterpolation; fx.effects[0].parameter[0] = endFrequency; break; case 5: fx.effects[0].effect = SoundSynthesizerEffects.exponentialRisingInterpolation; fx.effects[0].parameter[0] = endFrequency; break; case 6: fx.effects[0].effect = SoundSynthesizerEffects.exponentialFallingInterpolation; fx.effects[0].parameter[0] = endFrequency; break; case 8: // various ascending scales - see next switch case 10: case 12: case 14: case 16: fx.effects[0].effect = SoundSynthesizerEffects.appregrioAscending; break; case 9: // various descending scales - see next switch case 11: case 13: case 15: case 17: fx.effects[0].effect = SoundSynthesizerEffects.appregrioDescending; break; case 18: fx.effects[0].effect = SoundSynthesizerEffects.logarithmicInterpolation; fx.effects[0].parameter[0] = endFrequency; break; } // Scale switch(shape) { case 8: case 9: fx.effects[0].parameter_p[0] = MusicalProgressions.majorScale; break; case 10: case 11: fx.effects[0].parameter_p[0] = MusicalProgressions.minorScale; break; case 12: case 13: fx.effects[0].parameter_p[0] = MusicalProgressions.diminished; break; case 14: case 15: fx.effects[0].parameter_p[0] = MusicalProgressions.chromatic; break; case 16: case 17: fx.effects[0].parameter_p[0] = MusicalProgressions.wholeTone; break; } // Volume envelope let effectVolumeFloat = CLAMP(0, effectVolume, 1023) / 1023.0; let endVolumeFloat = CLAMP(0, endVolume, 1023) / 1023.0; fx.volume = volumeScaleFactor * effectVolumeFloat; fx.effects[1].effect = SoundSynthesizerEffects.volumeRampEffect; fx.effects[1].steps = 36; fx.effects[1].parameter[0] = volumeScaleFactor * endVolumeFloat; // Vibrato effect // Steps need to be spread across duration evenly. let normalizedFxnSteps = Math.round(fx.duration / 10000 * fxnSteps); switch(fxChoice) { case 1: fx.effects[2].steps = normalizedFxnSteps; fx.effects[2].effect = SoundSynthesizerEffects.frequencyVibratoEffect; fx.effects[2].parameter[0] = fxParam; break; case 2: fx.effects[2].steps = normalizedFxnSteps; fx.effects[2].effect = SoundSynthesizerEffects.volumeVibratoEffect; fx.effects[2].parameter[0] = fxParam; break; case 3: fx.effects[2].steps = normalizedFxnSteps; fx.effects[2].effect = SoundSynthesizerEffects.warbleInterpolation; fx.effects[2].parameter[0] = fxParam; break; } return true; } function random(max: number) { return Math.floor(Math.random() * max); } function CLAMP(min: number, value: number, max: number) { return Math.min(max, Math.max(min, value)); } function applyRandom(value: number, rand: number) { if (value < 0 || rand < 0) { return -1; } const delta = random(rand * 2 + 1) - rand; return Math.abs(value + delta); } function blankSoundEffect() { const res: SoundEffect = { frequency: 0, volume: 1, duration: 0, tone: { tonePrint: undefined, parameter: [0] }, effects: [] }; for(let i = 0; i < EMOJI_SYNTHESIZER_TONE_EFFECTS; i++) { res.effects.push({ effect: undefined, step: 0, steps: 0, parameter: [], parameter_p: [] }); } return res; } function delayAsync(millis: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, millis)); } function constrain(val: number, min: number, max: number) { return Math.min(Math.max(val, min), max); } }
the_stack
import { ElementRef, OnDestroy, QueryList, Renderer2 } from '@angular/core'; import { AbstractControl, FormGroup } from '@angular/forms'; import * as Ro from '@nakedobjects/restful-objects'; import { LoggerService, Pane } from '@nakedobjects/services'; import { ChoiceViewModel, DialogViewModel, DomainObjectViewModel, DragAndDropService, FieldViewModel, IDraggableViewModel, ParameterViewModel, PropertyViewModel } from '@nakedobjects/view-models'; import { Dictionary } from 'lodash'; import every from 'lodash-es/every'; import find from 'lodash-es/find'; import keys from 'lodash-es/keys'; import mapValues from 'lodash-es/mapValues'; import omit from 'lodash-es/omit'; import { BehaviorSubject, SubscriptionLike as ISubscription } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { AutoCompleteComponent } from '../auto-complete/auto-complete.component'; import { DatePickerFacadeComponent } from '../date-picker-facade/date-picker-facade.component'; import { accept, dropOn, focus, paste, safeUnsubscribe } from '../helpers-components'; import { TimePickerFacadeComponent } from '../time-picker-facade/time-picker-facade.component'; import { CdkDrag, CdkDropList, CdkDragDrop } from '@angular/cdk/drag-drop'; export abstract class FieldComponent implements OnDestroy { protected constructor( private readonly loggerService: LoggerService, private readonly renderer: Renderer2, protected readonly dragAndDrop: DragAndDropService ) { } set formGroup(fm: FormGroup) { this.formGrp = fm; this.formGrp.valueChanges.pipe(debounceTime(200)).subscribe(data => this.onValueChanged()); this.onValueChanged(); // (re)set validation messages now } get formGroup() { return this.formGrp; } get message() { return this.model.getMessage(); } get isBoolean() { return this.model.returnType === 'boolean'; } get subject() { if (!this.bSubject) { const initialValue = this.control.value; this.bSubject = new BehaviorSubject(initialValue); this.sub = this.control.valueChanges.subscribe((data) => { this.bSubject.next(data); }); } return this.bSubject; } private formGrp: FormGroup; private vmParent: DialogViewModel | DomainObjectViewModel; private model: ParameterViewModel | PropertyViewModel; private isConditionalChoices: boolean; private isAutoComplete: boolean; private bSubject: BehaviorSubject<any>; private sub: ISubscription; private lastArgs: Dictionary<Ro.Value>; control: AbstractControl; currentOptions: ChoiceViewModel[] = []; pArgs: Dictionary<Ro.Value>; paneId: Pane; canDrop = false; dragOver = false; abstract checkboxList: QueryList<ElementRef>; abstract focusList: QueryList<ElementRef | DatePickerFacadeComponent | TimePickerFacadeComponent | AutoCompleteComponent>; protected init(vmParent: DialogViewModel | DomainObjectViewModel, vm: ParameterViewModel | PropertyViewModel, control: AbstractControl) { this.vmParent = vmParent; this.model = vm; this.control = control; this.paneId = this.model.onPaneId; this.isConditionalChoices = (this.model.entryType === Ro.EntryType.ConditionalChoices || this.model.entryType === Ro.EntryType.MultipleConditionalChoices); this.isAutoComplete = this.model.entryType === Ro.EntryType.AutoComplete; if (this.isConditionalChoices) { this.pArgs = omit(this.model.promptArguments, 'x-ro-nof-members') as Dictionary<Ro.Value>; this.populateDropdown(); } } get accept() { const _this = this; return (cdkDrag: CdkDrag<IDraggableViewModel>, cdkDropList: CdkDropList) => { return accept(_this.model, _this, cdkDrag.data); }; } drop(event: CdkDragDrop<CdkDrag<IDraggableViewModel>>) { const cdkDrag: CdkDrag<IDraggableViewModel> = event.item; if (event.isPointerOverContainer) { dropOn(cdkDrag.data, this.model, this); } this.canDrop = false; this.dragOver = false; } exit() { this.canDrop = false; this.dragOver = false; } enter() { this.dragOver = true; } private isDomainObjectViewModel(object: any): object is DomainObjectViewModel { return object && 'properties' in object; } private mapValues(args: Dictionary<Ro.Value>, parmsOrProps: { argId: string, getValue: () => Ro.Value }[]) { return mapValues(this.pArgs, (v, n) => { const pop = find(parmsOrProps, p => p.argId === n); return pop!.getValue(); }); } private populateArguments() { const dialog = this.vmParent as DialogViewModel; const object = this.vmParent as DomainObjectViewModel; if (!dialog && !object) { this.loggerService.throw('FieldComponent:populateArguments Expect dialog or object'); } let parmsOrProps: { argId: string, getValue: () => Ro.Value }[]; if (this.isDomainObjectViewModel(object)) { parmsOrProps = object.properties; } else { parmsOrProps = dialog.parameters; } return this.mapValues(this.pArgs, parmsOrProps); } private argsChanged(newArgs: Dictionary<Ro.Value>) { const same = this.lastArgs && keys(this.lastArgs).length === keys(newArgs).length && every(this.lastArgs, (v, k) => newArgs[k].toValueString() === v.toValueString()); this.lastArgs = newArgs; return !same; } private populateDropdown() { const nArgs = this.populateArguments(); if (this.argsChanged(nArgs)) { const prompts = this.model.conditionalChoices(nArgs); prompts. then((cvms: ChoiceViewModel[]) => { // if unchanged return if (cvms.length === this.currentOptions.length && every(cvms, (c, i) => c.equals(this.currentOptions[i]))) { return; } this.model.choices = cvms; this.currentOptions = cvms; if (this.isConditionalChoices) { // need to reset control to find the selected options if (this.model.entryType === Ro.EntryType.MultipleConditionalChoices) { this.control.reset(this.model.selectedMultiChoices); } else { this.control.reset(this.model.selectedChoice); } } }). catch(() => { // error clear everything this.model.selectedChoice = null; this.currentOptions = []; }); } } private onChange() { if (this.isConditionalChoices) { this.populateDropdown(); } else if (this.isAutoComplete) { this.populateAutoComplete(); } else if (this.isBoolean) { this.populateBoolean(); } } private onValueChanged() { if (this.model) { this.onChange(); } } private populateAutoComplete() { const input = this.control.value; if (input instanceof ChoiceViewModel) { return; } if (input && input.length > 0 && input.length >= this.model.minLength) { this.model.prompt(input) .then((cvms: ChoiceViewModel[]) => { if (cvms.length === this.currentOptions.length && every(cvms, (c, i) => c.equals(this.currentOptions[i]))) { return; } this.model.choices = cvms; this.currentOptions = cvms; this.model.selectedChoice = null; }) .catch(() => { this.model.choices = []; this.currentOptions = []; this.model.selectedChoice = null; }); } else { this.model.choices = []; this.currentOptions = []; this.model.selectedChoice = null; } } protected populateBoolean() { // editable booleans only if (this.isBoolean && this.control) { const input = this.control.value; const element = this.checkboxList.first.nativeElement; if (input == null) { this.renderer.setProperty(element, 'indeterminate', true); this.renderer.setProperty(element, 'checked', null); } else { this.renderer.setProperty(element, 'indeterminate', false); this.renderer.setProperty(element, 'checked', !!input); } } } private select(item: ChoiceViewModel) { this.model.choices = []; this.model.selectedChoice = item; this.control.reset(item); } fileUpload(evt: Event) { const file: File = (evt.target as HTMLInputElement)!.files![0]; const fileReader = new FileReader(); fileReader.onloadend = () => { const link = new Ro.Link({ href: fileReader.result as string, type: file.type, title: file.name }); this.control.reset(link); this.model.file = link; }; fileReader.readAsDataURL(file); } paste(event: KeyboardEvent) { paste(event, this.model, this, () => this.dragAndDrop.getCopyViewModel(), () => this.dragAndDrop.setCopyViewModel(null)); } clear() { if (this.model.isEditable) { this.control.reset(''); this.model.clear(); } } private filterEnter(event: KeyboardEvent) { const enterKeyCode = 13; if (event && event.keyCode === enterKeyCode) { event.preventDefault(); } } protected handleKeyEvents(event: KeyboardEvent, isMultiline: boolean) { this.paste(event); // catch and filter enters or they will submit form - ok for multiline if (!isMultiline) { this.filterEnter(event); } } private triStateClick = (currentValue: any) => { switch (currentValue) { case false: return true; case true: return null; default: // null return false; } } protected handleClick(event: Event) { if (this.isBoolean && this.model.optional) { const currentValue = this.control.value; setTimeout(() => this.control.setValue(this.triStateClick(currentValue))); event.preventDefault(); } } focus() { const first = this.focusList && this.focusList.first; if (first instanceof ElementRef) { return focus(first); } return first && first.focus(); } ngOnDestroy() { safeUnsubscribe(this.sub); } }
the_stack
import LoginPage from "../support/pages/LoginPage"; import Masthead from "../support/pages/admin_console/Masthead"; import ListingPage from "../support/pages/admin_console/ListingPage"; import SidebarPage from "../support/pages/admin_console/SidebarPage"; import CreateClientPage from "../support/pages/admin_console/manage/clients/CreateClientPage"; import ModalUtils from "../support/util/ModalUtils"; import AdvancedTab from "../support/pages/admin_console/manage/clients/AdvancedTab"; import AdminClient from "../support/util/AdminClient"; import InitialAccessTokenTab from "../support/pages/admin_console/manage/clients/InitialAccessTokenTab"; import { keycloakBefore } from "../support/util/keycloak_before"; import RoleMappingTab from "../support/pages/admin_console/manage/RoleMappingTab"; import KeysTab from "../support/pages/admin_console/manage/clients/KeysTab"; import ClientScopesTab from "../support/pages/admin_console/manage/clients/ClientScopesTab"; let itemId = "client_crud"; const loginPage = new LoginPage(); const masthead = new Masthead(); const sidebarPage = new SidebarPage(); const listingPage = new ListingPage(); const createClientPage = new CreateClientPage(); const modalUtils = new ModalUtils(); describe("Clients test", () => { describe("Client details - Client scopes subtab", () => { const clientScopesTab = new ClientScopesTab(); const client = new AdminClient(); const clientId = "client-scopes-subtab-test"; const clientScopeName = "client-scope-test"; const clientScope = { name: clientScopeName, description: "", protocol: "openid-connect", attributes: { "include.in.token.scope": "true", "display.on.consent.screen": "true", "gui.order": "1", "consent.screen.text": "", }, }; before(async () => { client.createClient({ clientId, protocol: "openid-connect", publicClient: false, }); for (let i = 0; i < 5; i++) { clientScope.name = clientScopeName + i; await client.createClientScope(clientScope); await client.addDefaultClientScopeInClient( clientScopeName + i, clientId ); } }); beforeEach(() => { keycloakBefore(); loginPage.logIn(); sidebarPage.goToClients(); cy.intercept("/auth/admin/realms/master/clients/*").as("fetchClient"); listingPage.searchItem(clientId).goToItemDetails(clientId); cy.wait("@fetchClient"); clientScopesTab.goToTab(); }); after(async () => { client.deleteClient(clientId); for (let i = 0; i < 5; i++) { await client.deleteClientScope(clientScopeName + i); } }); it("should show items on next page are more than 11", () => { listingPage.showNextPageTableItems(); cy.get(listingPage.tableRowItem).its("length").should("be.gt", 1); }); }); describe("Client creation", () => { beforeEach(() => { keycloakBefore(); loginPage.logIn(); sidebarPage.goToClients(); }); it("should fail creating client", () => { listingPage.goToCreateItem(); createClientPage.continue().checkClientIdRequiredMessage(); createClientPage .fillClientData("") .selectClientType("openid-connect") .continue() .checkClientIdRequiredMessage(); createClientPage.fillClientData("account").continue().continue(); // The error should inform about duplicated name/id masthead.checkNotificationMessage( "Could not create client: 'Client account already exists'" ); }); it("Client CRUD test", () => { itemId += "_" + (Math.random() + 1).toString(36).substring(7); // Create listingPage.itemExist(itemId, false).goToCreateItem(); createClientPage .selectClientType("openid-connect") .fillClientData(itemId) .continue() .continue(); masthead.checkNotificationMessage("Client created successfully"); sidebarPage.goToClients(); listingPage.searchItem(itemId).itemExist(itemId); // Delete listingPage.deleteItem(itemId); modalUtils.checkModalTitle(`Delete ${itemId} ?`).confirmModal(); masthead.checkNotificationMessage("The client has been deleted"); listingPage.itemExist(itemId, false); }); it("Initial access token", () => { const initialAccessTokenTab = new InitialAccessTokenTab(); initialAccessTokenTab.goToInitialAccessTokenTab().shouldBeEmpty(); initialAccessTokenTab.createNewToken(1, 1).save(); modalUtils.checkModalTitle("Initial access token details").closeModal(); initialAccessTokenTab.shouldNotBeEmpty(); initialAccessTokenTab.getFistId((id) => { listingPage.deleteItem(id); modalUtils .checkModalTitle("Delete initial access token?") .confirmModal(); masthead.checkNotificationMessage( "initial access token created successfully" ); }); }); }); describe("Advanced tab test", () => { const advancedTab = new AdvancedTab(); let client: string; beforeEach(() => { keycloakBefore(); loginPage.logIn(); sidebarPage.goToClients(); client = "client_" + (Math.random() + 1).toString(36).substring(7); listingPage.goToCreateItem(); createClientPage .selectClientType("openid-connect") .fillClientData(client) .continue() .continue(); advancedTab.goToTab(); }); afterEach(() => { new AdminClient().deleteClient(client); }); it("Clustering", () => { advancedTab.expandClusterNode(); advancedTab .clickRegisterNodeManually() .fillHost("localhost") .clickSaveHost(); advancedTab.checkTestClusterAvailability(true); }); it("Fine grain OpenID connect configuration", () => { const algorithm = "ES384"; advancedTab .selectAccessTokenSignatureAlgorithm(algorithm) .clickSaveFineGrain(); advancedTab .selectAccessTokenSignatureAlgorithm("HS384") .clickRevertFineGrain(); advancedTab.checkAccessTokenSignatureAlgorithm(algorithm); }); }); describe("Service account tab test", () => { const serviceAccountTab = new RoleMappingTab(); const serviceAccountName = "service-account-client"; beforeEach(() => { keycloakBefore(); loginPage.logIn(); sidebarPage.goToClients(); }); before(async () => { await new AdminClient().createClient({ protocol: "openid-connect", clientId: serviceAccountName, publicClient: false, authorizationServicesEnabled: true, serviceAccountsEnabled: true, standardFlowEnabled: true, }); }); after(() => { new AdminClient().deleteClient(serviceAccountName); }); it("list", () => { listingPage .searchItem(serviceAccountName) .goToItemDetails(serviceAccountName); serviceAccountTab .goToServiceAccountTab() .checkRoles(["manage-account", "offline_access", "uma_authorization"]); }); /* this test causes the test(s) that follow it to fail - it should be rewritten it("assign", () => { listingPage.goToItemDetails(serviceAccountName); serviceAccountTab .goToServiceAccountTab() .clickAssignRole(false) .selectRow("create-realm") .clickAssign(); masthead.checkNotificationMessage("Role mapping updated"); }); */ }); describe("Mapping tab", () => { const mappingClient = "mapping-client"; beforeEach(() => { keycloakBefore(); loginPage.logIn(); sidebarPage.goToClients(); listingPage.searchItem(mappingClient).goToItemDetails(mappingClient); }); before(() => { new AdminClient().createClient({ protocol: "openid-connect", clientId: mappingClient, publicClient: false, }); }); after(() => { new AdminClient().deleteClient(mappingClient); }); it("add mapping to openid client", () => { cy.get("#pf-tab-mappers-mappers").click(); cy.findByText("Add predefined mapper").click(); cy.get("table input").first().click(); cy.findByTestId("modalConfirm").click(); masthead.checkNotificationMessage("Mapping successfully created"); }); }); describe("Keys tab test", () => { const keysName = "keys-client"; beforeEach(() => { keycloakBefore(); loginPage.logIn(); sidebarPage.goToClients(); listingPage.searchItem(keysName).goToItemDetails(keysName); }); before(() => { new AdminClient().createClient({ protocol: "openid-connect", clientId: keysName, publicClient: false, }); }); after(() => { new AdminClient().deleteClient(keysName); }); it("change use JWKS Url", () => { const keysTab = new KeysTab(); keysTab.goToTab().checkSaveDisabled(); keysTab.toggleUseJwksUrl().checkSaveDisabled(false); }); it("generate new keys", () => { const keysTab = new KeysTab(); keysTab.goToTab().clickGenerate(); keysTab.fillGenerateModal("keyname", "123", "1234").clickConfirm(); masthead.checkNotificationMessage( "New key pair and certificate generated successfully" ); }); }); describe("Realm client", () => { const clientName = "master-realm"; beforeEach(() => { keycloakBefore(); loginPage.logIn(); sidebarPage.goToClients(); listingPage.searchItem(clientName).goToItemDetails(clientName); }); it("displays the correct tabs", () => { cy.findByTestId("client-tabs") .find("#pf-tab-settings-settings") .should("exist"); cy.findByTestId("client-tabs") .find("#pf-tab-roles-roles") .should("exist"); cy.findByTestId("client-tabs") .find("#pf-tab-advanced-advanced") .should("exist"); cy.findByTestId("client-tabs").find("li").should("have.length", 3); }); it("hides the delete action", () => { cy.findByTestId("action-dropdown").click(); cy.findByTestId("delete-client").should("not.exist"); }); }); describe("Bearer only", () => { const clientId = "bearer-only"; before(() => { new AdminClient().createClient({ clientId, protocol: "openid-connect", publicClient: false, bearerOnly: true, }); }); after(() => { new AdminClient().deleteClient(clientId); }); beforeEach(() => { keycloakBefore(); loginPage.logIn(); sidebarPage.goToClients(); cy.intercept("/auth/admin/realms/master/clients/*").as("fetchClient"); listingPage.searchItem(clientId).goToItemDetails(clientId); cy.wait("@fetchClient"); }); it("shows an explainer text for bearer only clients", () => { cy.findByTestId("bearer-only-explainer-label").trigger("mouseenter"); cy.findByTestId("bearer-only-explainer-tooltip").should("exist"); }); it("hides the capability config section", () => { cy.findByTestId("capability-config-form").should("not.exist"); cy.findByTestId("jump-link-capability-config").should("not.exist"); }); }); });
the_stack
import { h, defineComponent, ref, computed, Transition, onBeforeUnmount, getCurrentInstance, VNode } from 'vue' import VcIcon from '../icon' import { Spinner as VcSpinner } from '../spinner' import { Ripple } from '@vue-cesium/directives' import useBtn, { useBtnProps } from './use-btn' import { hMergeSlot, hDir } from '@vue-cesium/utils/private/render' import { stop, prevent, stopAndPrevent, listenOpts } from '@vue-cesium/utils/private/event' import { getTouchTarget } from '@vue-cesium/utils/private/touch' import { isKeyCode } from '@vue-cesium/utils/private/key-composition' const { passiveCapture } = listenOpts let touchTarget: HTMLElement | null, keyboardTarget: HTMLElement | null, mouseTarget: HTMLElement | null export default defineComponent({ name: 'VcBtn', props: { ...useBtnProps, percentage: { type: Number, default: 0 }, darkPercentage: Boolean }, emits: ['click', 'keydown', 'touchstart', 'mousedown', 'keyup'], setup(props, { slots, emit }) { const proxy = getCurrentInstance()?.proxy const { classes, style, innerClasses, attributes, isActionable } = useBtn(props) const rootRef = ref<HTMLElement | null>(null) const blurTargetRef = ref<HTMLElement | null>(null) let localTouchTargetEl: HTMLElement | null = null, avoidMouseRipple, mouseTimer const hasLabel = computed(() => props.label !== void 0 && props.label !== null && props.label !== '') const ripple = computed(() => props.ripple === false ? false : { // keyCodes: isLink.value === true ? [ 13, 32 ] : [ 13 ], keyCodes: 13, ...(props.ripple === true ? {} : props.ripple) } ) const percentageStyle = computed(() => { const val = Math.max(0, Math.min(100, props.percentage)) return val > 0 ? { transition: 'transform 0.6s', transform: `translateX(${val - 100}%)` } : {} }) const onEvents = computed(() => { if (props.loading === true) { return { onMousedown: onLoadingEvt, onTouchstart: onLoadingEvt, onClick: onLoadingEvt, onKeydown: onLoadingEvt, onKeyup: onLoadingEvt } } else if (isActionable.value === true) { return { onClick, onKeydown, onMousedown, onTouchstart } } return {} }) const directives = computed(() => { // if props.disable !== true && props.ripple !== false return [[Ripple, ripple.value, void 0, { center: props.round }]] }) const nodeProps = computed(() => ({ ref: rootRef, class: 'vc-btn vc-btn-item non-selectable no-outline ' + classes.value, style: style.value, ...attributes.value, ...onEvents.value })) function onClick(e) { if (e !== void 0) { if (e.defaultPrevented === true) { return } const el = document.activeElement // focus button if it came from ENTER on form // prevent the new submit (already done) if ( props.type === 'submit' && el !== document.body && rootRef.value?.contains(el) === false && // required for iOS and desktop Safari el?.contains(rootRef.value) === false ) { rootRef.value.focus() const onClickCleanup = () => { document.removeEventListener('keydown', stopAndPrevent, true) document.removeEventListener('keyup', onClickCleanup, passiveCapture) rootRef.value !== null && rootRef.value.removeEventListener('blur', onClickCleanup, passiveCapture) } document.addEventListener('keydown', stopAndPrevent, true) document.addEventListener('keyup', onClickCleanup, passiveCapture) rootRef.value.addEventListener('blur', onClickCleanup, passiveCapture) } } const go = () => { // navigateToLink(e) } emit('click', e, go) // TODO vue3 - not accounting for e.navigate // hasLink.value === true && e.navigate !== false && go() } function onKeydown(e) { if (isKeyCode(e, [13, 32]) === true) { stopAndPrevent(e) if (keyboardTarget !== rootRef.value) { keyboardTarget !== null && cleanup() // focus external button if the focus helper was focused before rootRef.value?.focus() keyboardTarget = rootRef.value rootRef.value?.classList.add('vc-btn--active') document.addEventListener('keyup', onPressEnd, true) rootRef.value?.addEventListener('blur', onPressEnd, passiveCapture) } } emit('keydown', e) } function onTouchstart(e) { if (touchTarget !== rootRef.value) { touchTarget !== null && cleanup() touchTarget = rootRef.value localTouchTargetEl = getTouchTarget(e.target) localTouchTargetEl?.addEventListener('touchcancel', onPressEnd, passiveCapture) localTouchTargetEl?.addEventListener('touchend', onPressEnd, passiveCapture) } // avoid duplicated mousedown event // triggering another early ripple avoidMouseRipple = true clearTimeout(mouseTimer) mouseTimer = setTimeout(() => { avoidMouseRipple = false }, 200) emit('touchstart', e) } function onMousedown(e) { if (mouseTarget !== rootRef.value) { mouseTarget !== null && cleanup() mouseTarget = rootRef.value rootRef.value?.classList.add('vc-btn--active') document.addEventListener('mouseup', onPressEnd, passiveCapture) } e.qSkipRipple = avoidMouseRipple === true emit('mousedown', e) } function onPressEnd(e) { // needed for IE (because it emits blur when focusing button from focus helper) if (e !== void 0 && e.type === 'blur' && document.activeElement === rootRef.value) { return } if (e !== void 0 && e.type === 'keyup') { if (keyboardTarget === rootRef.value && isKeyCode(e, [13, 32]) === true) { // for click trigger const evt = new MouseEvent('click', e) ;(evt as any).qKeyEvent = true e.defaultPrevented === true && prevent(evt) e.cancelBubble === true && stop(evt) rootRef.value?.dispatchEvent(evt) stopAndPrevent(e) // for ripple e.qKeyEvent = true } emit('keyup', e) } cleanup() } function cleanup(destroying?) { const blurTarget = blurTargetRef.value if ( destroying !== true && (touchTarget === rootRef.value || mouseTarget === rootRef.value) && blurTarget !== null && blurTarget !== document.activeElement ) { blurTarget.setAttribute('tabindex', '-1') blurTarget.focus() } if (touchTarget === rootRef.value) { if (localTouchTargetEl !== null) { localTouchTargetEl.removeEventListener('touchcancel', onPressEnd, passiveCapture) localTouchTargetEl.removeEventListener('touchend', onPressEnd, passiveCapture) } touchTarget = localTouchTargetEl = null } if (mouseTarget === rootRef.value) { document.removeEventListener('mouseup', onPressEnd, passiveCapture) mouseTarget = null } if (keyboardTarget === rootRef.value) { document.removeEventListener('keyup', onPressEnd, true) rootRef.value !== null && rootRef.value.removeEventListener('blur', onPressEnd, passiveCapture) keyboardTarget = null } rootRef.value !== null && rootRef.value.classList.remove('vc-btn--active') } function onLoadingEvt(evt) { stopAndPrevent(evt) evt.qSkipRipple = true } onBeforeUnmount(() => { cleanup(true) }) // expose public methods Object.assign(proxy, { click: onClick }) return () => { let inner: Array<VNode> = [] props.icon !== void 0 && inner.push( h(VcIcon, { name: props.icon, left: props.stack === false && hasLabel.value === true, role: 'img', 'aria-hidden': 'true' }) ) hasLabel.value === true && inner.push(h('span', { class: 'block' }, [props.label])) inner = hMergeSlot(slots.default, inner) if (props.iconRight !== void 0 && props.round === false) { inner.push( h(VcIcon, { name: props.iconRight, right: props.stack === false && hasLabel.value === true, role: 'img', 'aria-hidden': 'true' }) ) } const child = [ h('span', { class: 'vc-focus-helper', ref: blurTargetRef }) ] if (props.loading === true && props.percentage !== void 0) { child.push( h( 'span', { class: 'vc-btn__progress absolute-full overflow-hidden' }, [ h('span', { class: 'vc-btn__progress-indicator fit block' + (props.darkPercentage === true ? ' vc-btn__progress--dark' : ''), style: percentageStyle.value }) ] ) ) } child.push( h( 'span', { class: 'vc-btn__content text-center col items-center vc-anchor--skip ' + innerClasses.value }, inner ) ) props.loading !== null && child.push( h( Transition, { name: 'vc-transition--fade' }, () => props.loading === true ? [ h( 'span', { key: 'loading', class: 'absolute-full flex flex-center' }, slots.loading !== void 0 ? slots.loading() : [h(VcSpinner)] ) ] : null ) ) return hDir('button', nodeProps.value, child, 'ripple', props.disable !== true && props.ripple !== false, () => directives.value) } } })
the_stack
import React, { FC, useState, useCallback, } from 'react'; import { useTranslation } from 'react-i18next'; import UserGroupForm from '../UserGroup/UserGroupForm'; import UserGroupTable from '../UserGroup/UserGroupTable'; import UserGroupModal from '../UserGroup/UserGroupModal'; import UserGroupDeleteModal from '../UserGroup/UserGroupDeleteModal'; import UpdateParentConfirmModal from './UpdateParentConfirmModal'; import UserGroupDropdown from '../UserGroup/UserGroupDropdown'; import UserGroupUserTable from './UserGroupUserTable'; import UserGroupUserModal from './UserGroupUserModal'; import UserGroupPageList from './UserGroupPageList'; import { apiv3Get, apiv3Put, apiv3Delete, apiv3Post, } from '~/client/util/apiv3-client'; import { toastSuccess, toastError } from '~/client/util/apiNotification'; import { IPageHasId } from '~/interfaces/page'; import { IUserGroup, IUserGroupHasId, } from '~/interfaces/user'; import { useSWRxUserGroupPages, useSWRxUserGroupRelationList, useSWRxChildUserGroupList, useSWRxSelectableParentUserGroups, useSWRxSelectableChildUserGroups, useSWRxAncestorUserGroups, } from '~/stores/user-group'; import { useIsAclEnabled } from '~/stores/context'; import { useUpdateUserGroupConfirmModal } from '~/stores/modal'; const UserGroupDetailPage: FC = () => { const { t } = useTranslation(); const adminUserGroupDetailElem = document.getElementById('admin-user-group-detail'); /* * State (from AdminUserGroupDetailContainer) */ const [currentUserGroup, setUserGroup] = useState<IUserGroupHasId>(JSON.parse(adminUserGroupDetailElem?.getAttribute('data-user-group') || 'null')); const [relatedPages, setRelatedPages] = useState<IPageHasId[]>([]); // For page list const [searchType, setSearchType] = useState<string>('partial'); const [isAlsoMailSearched, setAlsoMailSearched] = useState<boolean>(false); const [isAlsoNameSearched, setAlsoNameSearched] = useState<boolean>(false); const [selectedUserGroup, setSelectedUserGroup] = useState<IUserGroupHasId | undefined>(undefined); // not null but undefined (to use defaultProps in UserGroupDeleteModal) const [isCreateModalShown, setCreateModalShown] = useState<boolean>(false); const [isUpdateModalShown, setUpdateModalShown] = useState<boolean>(false); const [isDeleteModalShown, setDeleteModalShown] = useState<boolean>(false); /* * Fetch */ const { data: userGroupPages } = useSWRxUserGroupPages(currentUserGroup._id, 10, 0); const { data: childUserGroupsList, mutate: mutateChildUserGroups } = useSWRxChildUserGroupList([currentUserGroup._id], true); const childUserGroups = childUserGroupsList != null ? childUserGroupsList.childUserGroups : []; const grandChildUserGroups = childUserGroupsList != null ? childUserGroupsList.grandChildUserGroups : []; const childUserGroupIds = childUserGroups.map(group => group._id); const { data: userGroupRelationList, mutate: mutateUserGroupRelations } = useSWRxUserGroupRelationList(childUserGroupIds); const childUserGroupRelations = userGroupRelationList != null ? userGroupRelationList : []; const { data: selectableParentUserGroups, mutate: mutateSelectableParentUserGroups } = useSWRxSelectableParentUserGroups(currentUserGroup._id); const { data: selectableChildUserGroups, mutate: mutateSelectableChildUserGroups } = useSWRxSelectableChildUserGroups(currentUserGroup._id); const { data: ancestorUserGroups, mutate: mutateAncestorUserGroups } = useSWRxAncestorUserGroups(currentUserGroup._id); const { data: isAclEnabled } = useIsAclEnabled(); const { open: openUpdateParentConfirmModal } = useUpdateUserGroupConfirmModal(); /* * Function */ // TODO 85062: old name: switchIsAlsoMailSearched const toggleIsAlsoMailSearched = useCallback(() => { setAlsoMailSearched(prev => !prev); }, []); // TODO 85062: old name: switchIsAlsoNameSearched const toggleAlsoNameSearched = useCallback(() => { setAlsoNameSearched(prev => !prev); }, []); const switchSearchType = useCallback((searchType) => { setSearchType(searchType); }, []); const updateUserGroup = useCallback(async(userGroup: IUserGroupHasId, update: Partial<IUserGroupHasId>, forceUpdateParents: boolean) => { if (update.parent == null) { throw Error('"parent" attr must not be null'); } const parentId = typeof update.parent === 'string' ? update.parent : update.parent?._id; const res = await apiv3Put<{ userGroup: IUserGroupHasId }>(`/user-groups/${userGroup._id}`, { name: update.name, description: update.description, parentId, forceUpdateParents, }); const { userGroup: updatedUserGroup } = res.data; setUserGroup(updatedUserGroup); // mutate mutateAncestorUserGroups(); mutateSelectableChildUserGroups(); mutateSelectableParentUserGroups(); }, [setUserGroup, mutateAncestorUserGroups, mutateSelectableChildUserGroups, mutateSelectableParentUserGroups]); const onSubmitUpdateGroup = useCallback( async(targetGroup: IUserGroupHasId, userGroupData: Partial<IUserGroupHasId>, forceUpdateParents: boolean): Promise<void> => { try { await updateUserGroup(targetGroup, userGroupData, forceUpdateParents); toastSuccess(t('toaster.update_successed', { target: t('UserGroup') })); } catch { toastError(t('toaster.update_failed', { target: t('UserGroup') })); } }, [t, updateUserGroup], ); const onClickSubmitForm = useCallback(async(targetGroup: IUserGroupHasId, userGroupData: Partial<IUserGroupHasId>): Promise<void> => { if (userGroupData?.parent === undefined || typeof userGroupData?.parent === 'string') { toastError(t('Something went wrong. Please try again.')); return; } const prevParentId = typeof targetGroup.parent === 'string' ? targetGroup.parent : (targetGroup.parent?._id || null); const newParentId = typeof userGroupData.parent?._id === 'string' ? userGroupData.parent?._id : null; const shouldShowConfirmModal = prevParentId !== newParentId; if (shouldShowConfirmModal) { // show confirm modal before submiting await openUpdateParentConfirmModal( targetGroup, userGroupData, onSubmitUpdateGroup, ); } else { // directly submit await onSubmitUpdateGroup(targetGroup, userGroupData, false); } }, [t, openUpdateParentConfirmModal, onSubmitUpdateGroup]); const fetchApplicableUsers = useCallback(async(searchWord) => { const res = await apiv3Get(`/user-groups/${currentUserGroup._id}/unrelated-users`, { searchWord, searchType, isAlsoMailSearched, isAlsoNameSearched, }); const { users } = res.data; return users; }, [searchType, isAlsoMailSearched, isAlsoNameSearched]); // TODO 85062: will be used in UserGroupUserFormByInput const addUserByUsername = useCallback(async(username: string) => { await apiv3Post(`/user-groups/${currentUserGroup._id}/users/${username}`); mutateUserGroupRelations(); }, [currentUserGroup, mutateUserGroupRelations]); const removeUserByUsername = useCallback(async(username: string) => { await apiv3Delete(`/user-groups/${currentUserGroup._id}/users/${username}`); mutateUserGroupRelations(); }, [currentUserGroup, mutateUserGroupRelations]); const showUpdateModal = useCallback((group: IUserGroupHasId) => { setUpdateModalShown(true); setSelectedUserGroup(group); }, [setUpdateModalShown]); const hideUpdateModal = useCallback(() => { setUpdateModalShown(false); setSelectedUserGroup(undefined); }, [setUpdateModalShown]); const updateChildUserGroup = useCallback(async(userGroupData: IUserGroupHasId) => { try { await apiv3Put(`/user-groups/${userGroupData._id}`, { name: userGroupData.name, description: userGroupData.description, parentId: userGroupData.parent, }); toastSuccess(t('toaster.update_successed', { target: t('UserGroup') })); // mutate mutateChildUserGroups(); hideUpdateModal(); } catch (err) { toastError(err); } }, [t, mutateChildUserGroups, hideUpdateModal]); const onClickAddExistingUserGroupButtonHandler = useCallback(async(selectedChild: IUserGroupHasId): Promise<void> => { // show confirm modal before submiting await openUpdateParentConfirmModal( selectedChild, { parent: currentUserGroup._id, }, onSubmitUpdateGroup, ); }, [openUpdateParentConfirmModal, onSubmitUpdateGroup, currentUserGroup]); const showCreateModal = useCallback(() => { setCreateModalShown(true); }, [setCreateModalShown]); const hideCreateModal = useCallback(() => { setCreateModalShown(false); }, [setCreateModalShown]); const createChildUserGroup = useCallback(async(userGroupData: IUserGroup) => { try { await apiv3Post('/user-groups', { name: userGroupData.name, description: userGroupData.description, parentId: currentUserGroup._id, }); toastSuccess(t('toaster.update_successed', { target: t('UserGroup') })); // mutate mutateChildUserGroups(); mutateSelectableChildUserGroups(); mutateSelectableParentUserGroups(); hideCreateModal(); } catch (err) { toastError(err); } }, [t, currentUserGroup, mutateChildUserGroups, mutateSelectableChildUserGroups, mutateSelectableParentUserGroups, hideCreateModal]); const showDeleteModal = useCallback(async(group: IUserGroupHasId) => { setSelectedUserGroup(group); setDeleteModalShown(true); }, [setSelectedUserGroup, setDeleteModalShown]); const hideDeleteModal = useCallback(() => { setSelectedUserGroup(undefined); setDeleteModalShown(false); }, [setSelectedUserGroup, setDeleteModalShown]); const deleteChildUserGroupById = useCallback(async(deleteGroupId: string, actionName: string, transferToUserGroupId: string) => { try { const res = await apiv3Delete(`/user-groups/${deleteGroupId}`, { actionName, transferToUserGroupId, }); // sync await mutateChildUserGroups(); setSelectedUserGroup(undefined); setDeleteModalShown(false); toastSuccess(`Deleted ${res.data.userGroups.length} groups.`); } catch (err) { toastError(new Error('Unable to delete the groups')); } }, [mutateChildUserGroups, setSelectedUserGroup, setDeleteModalShown]); const removeChildUserGroup = useCallback(async(userGroupData: IUserGroupHasId) => { try { await apiv3Put(`/user-groups/${userGroupData._id}`, { name: userGroupData.name, description: userGroupData.description, parentId: null, }); toastSuccess(t('toaster.update_successed', { target: t('UserGroup') })); // mutate mutateChildUserGroups(); mutateSelectableChildUserGroups(); } catch (err) { toastError(err); throw err; } }, [t, mutateChildUserGroups, mutateSelectableChildUserGroups]); /* * Dependencies */ if (currentUserGroup == null) { return <></>; } return ( <div> <nav aria-label="breadcrumb"> <ol className="breadcrumb"> <li className="breadcrumb-item"><a href="/admin/user-groups">{t('admin:user_group_management.group_list')}</a></li> { ancestorUserGroups != null && ancestorUserGroups.length > 0 && ( ancestorUserGroups.map((ancestorUserGroup: IUserGroupHasId) => ( // eslint-disable-next-line max-len <li key={ancestorUserGroup._id} className={`breadcrumb-item ${ancestorUserGroup._id === currentUserGroup._id ? 'active' : ''}`} aria-current="page"> { ancestorUserGroup._id === currentUserGroup._id ? ( <>{ancestorUserGroup.name}</> ) : ( <a href={`/admin/user-group-detail/${ancestorUserGroup._id}`}>{ancestorUserGroup.name}</a> )} </li> )) ) } </ol> </nav> <div className="mt-4 form-box"> <UserGroupForm userGroup={currentUserGroup} selectableParentUserGroups={selectableParentUserGroups} submitButtonLabel={t('Update')} onSubmit={onClickSubmitForm} /> </div> <h2 className="admin-setting-header mt-4">{t('admin:user_group_management.user_list')}</h2> <UserGroupUserTable /> <UserGroupUserModal /> <h2 className="admin-setting-header mt-4">{t('admin:user_group_management.child_group_list')}</h2> <UserGroupDropdown selectableUserGroups={selectableChildUserGroups} onClickAddExistingUserGroupButton={onClickAddExistingUserGroupButtonHandler} onClickCreateUserGroupButton={showCreateModal} /> <UserGroupModal userGroup={selectedUserGroup} buttonLabel={t('Update')} onClickSubmit={updateChildUserGroup} isShow={isUpdateModalShown} onHide={hideUpdateModal} /> <UserGroupModal buttonLabel={t('Create')} onClickSubmit={createChildUserGroup} isShow={isCreateModalShown} onHide={hideCreateModal} /> <UpdateParentConfirmModal /> <UserGroupTable userGroups={childUserGroups} childUserGroups={grandChildUserGroups} isAclEnabled={isAclEnabled ?? false} onEdit={showUpdateModal} onRemove={removeChildUserGroup} onDelete={showDeleteModal} userGroupRelations={childUserGroupRelations} /> <UserGroupDeleteModal userGroups={childUserGroups} deleteUserGroup={selectedUserGroup} onDelete={deleteChildUserGroupById} isShow={isDeleteModalShown} onHide={hideDeleteModal} /> <h2 className="admin-setting-header mt-4">{t('Page')}</h2> <div className="page-list"> <UserGroupPageList /> </div> </div> ); }; export default UserGroupDetailPage;
the_stack
export type Maybe<T> = T | null; export type InputMaybe<T> = Maybe<T>; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; jsonb: any; timestamptz: string; uuid: string; }; /** columns and relationships of "Account" */ export type Account = { __typename?: 'Account'; accessToken?: Maybe<Scalars['String']>; expiresAt?: Maybe<Scalars['timestamptz']>; id: Scalars['uuid']; idToken?: Maybe<Scalars['String']>; oauthToken?: Maybe<Scalars['String']>; oauthTokenSecret?: Maybe<Scalars['String']>; provider: Scalars['String']; providerAccountId: Scalars['String']; refreshToken?: Maybe<Scalars['String']>; scope?: Maybe<Scalars['String']>; sessionState?: Maybe<Scalars['String']>; tokenType?: Maybe<Scalars['String']>; type: Scalars['String']; /** An object relationship */ user: User; userId: Scalars['uuid']; }; /** aggregated selection of "Account" */ export type Account_Aggregate = { __typename?: 'Account_aggregate'; aggregate?: Maybe<Account_Aggregate_Fields>; nodes: Array<Account>; }; /** aggregate fields of "Account" */ export type Account_Aggregate_Fields = { __typename?: 'Account_aggregate_fields'; count: Scalars['Int']; max?: Maybe<Account_Max_Fields>; min?: Maybe<Account_Min_Fields>; }; /** aggregate fields of "Account" */ export type Account_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<Account_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "Account" */ export type Account_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<Account_Max_Order_By>; min?: InputMaybe<Account_Min_Order_By>; }; /** input type for inserting array relation for remote table "Account" */ export type Account_Arr_Rel_Insert_Input = { data: Array<Account_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<Account_On_Conflict>; }; /** Boolean expression to filter rows from the table "Account". All fields are combined with a logical 'AND'. */ export type Account_Bool_Exp = { _and?: InputMaybe<Array<Account_Bool_Exp>>; _not?: InputMaybe<Account_Bool_Exp>; _or?: InputMaybe<Array<Account_Bool_Exp>>; accessToken?: InputMaybe<String_Comparison_Exp>; expiresAt?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; idToken?: InputMaybe<String_Comparison_Exp>; oauthToken?: InputMaybe<String_Comparison_Exp>; oauthTokenSecret?: InputMaybe<String_Comparison_Exp>; provider?: InputMaybe<String_Comparison_Exp>; providerAccountId?: InputMaybe<String_Comparison_Exp>; refreshToken?: InputMaybe<String_Comparison_Exp>; scope?: InputMaybe<String_Comparison_Exp>; sessionState?: InputMaybe<String_Comparison_Exp>; tokenType?: InputMaybe<String_Comparison_Exp>; type?: InputMaybe<String_Comparison_Exp>; user?: InputMaybe<User_Bool_Exp>; userId?: InputMaybe<Uuid_Comparison_Exp>; }; /** unique or primary key constraints on table "Account" */ export type Account_Constraint = /** unique or primary key constraint */ | 'Account_pkey' /** unique or primary key constraint */ | 'Account_providerAccountId_provider_key'; /** input type for inserting data into table "Account" */ export type Account_Insert_Input = { accessToken?: InputMaybe<Scalars['String']>; expiresAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; idToken?: InputMaybe<Scalars['String']>; oauthToken?: InputMaybe<Scalars['String']>; oauthTokenSecret?: InputMaybe<Scalars['String']>; provider?: InputMaybe<Scalars['String']>; providerAccountId?: InputMaybe<Scalars['String']>; refreshToken?: InputMaybe<Scalars['String']>; scope?: InputMaybe<Scalars['String']>; sessionState?: InputMaybe<Scalars['String']>; tokenType?: InputMaybe<Scalars['String']>; type?: InputMaybe<Scalars['String']>; user?: InputMaybe<User_Obj_Rel_Insert_Input>; userId?: InputMaybe<Scalars['uuid']>; }; /** aggregate max on columns */ export type Account_Max_Fields = { __typename?: 'Account_max_fields'; accessToken?: Maybe<Scalars['String']>; expiresAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; idToken?: Maybe<Scalars['String']>; oauthToken?: Maybe<Scalars['String']>; oauthTokenSecret?: Maybe<Scalars['String']>; provider?: Maybe<Scalars['String']>; providerAccountId?: Maybe<Scalars['String']>; refreshToken?: Maybe<Scalars['String']>; scope?: Maybe<Scalars['String']>; sessionState?: Maybe<Scalars['String']>; tokenType?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; userId?: Maybe<Scalars['uuid']>; }; /** order by max() on columns of table "Account" */ export type Account_Max_Order_By = { accessToken?: InputMaybe<Order_By>; expiresAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; idToken?: InputMaybe<Order_By>; oauthToken?: InputMaybe<Order_By>; oauthTokenSecret?: InputMaybe<Order_By>; provider?: InputMaybe<Order_By>; providerAccountId?: InputMaybe<Order_By>; refreshToken?: InputMaybe<Order_By>; scope?: InputMaybe<Order_By>; sessionState?: InputMaybe<Order_By>; tokenType?: InputMaybe<Order_By>; type?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type Account_Min_Fields = { __typename?: 'Account_min_fields'; accessToken?: Maybe<Scalars['String']>; expiresAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; idToken?: Maybe<Scalars['String']>; oauthToken?: Maybe<Scalars['String']>; oauthTokenSecret?: Maybe<Scalars['String']>; provider?: Maybe<Scalars['String']>; providerAccountId?: Maybe<Scalars['String']>; refreshToken?: Maybe<Scalars['String']>; scope?: Maybe<Scalars['String']>; sessionState?: Maybe<Scalars['String']>; tokenType?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; userId?: Maybe<Scalars['uuid']>; }; /** order by min() on columns of table "Account" */ export type Account_Min_Order_By = { accessToken?: InputMaybe<Order_By>; expiresAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; idToken?: InputMaybe<Order_By>; oauthToken?: InputMaybe<Order_By>; oauthTokenSecret?: InputMaybe<Order_By>; provider?: InputMaybe<Order_By>; providerAccountId?: InputMaybe<Order_By>; refreshToken?: InputMaybe<Order_By>; scope?: InputMaybe<Order_By>; sessionState?: InputMaybe<Order_By>; tokenType?: InputMaybe<Order_By>; type?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** response of any mutation on the table "Account" */ export type Account_Mutation_Response = { __typename?: 'Account_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<Account>; }; /** on_conflict condition type for table "Account" */ export type Account_On_Conflict = { constraint: Account_Constraint; update_columns?: Array<Account_Update_Column>; where?: InputMaybe<Account_Bool_Exp>; }; /** Ordering options when selecting data from "Account". */ export type Account_Order_By = { accessToken?: InputMaybe<Order_By>; expiresAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; idToken?: InputMaybe<Order_By>; oauthToken?: InputMaybe<Order_By>; oauthTokenSecret?: InputMaybe<Order_By>; provider?: InputMaybe<Order_By>; providerAccountId?: InputMaybe<Order_By>; refreshToken?: InputMaybe<Order_By>; scope?: InputMaybe<Order_By>; sessionState?: InputMaybe<Order_By>; tokenType?: InputMaybe<Order_By>; type?: InputMaybe<Order_By>; user?: InputMaybe<User_Order_By>; userId?: InputMaybe<Order_By>; }; /** primary key columns input for table: Account */ export type Account_Pk_Columns_Input = { id: Scalars['uuid']; }; /** select columns of table "Account" */ export type Account_Select_Column = /** column name */ | 'accessToken' /** column name */ | 'expiresAt' /** column name */ | 'id' /** column name */ | 'idToken' /** column name */ | 'oauthToken' /** column name */ | 'oauthTokenSecret' /** column name */ | 'provider' /** column name */ | 'providerAccountId' /** column name */ | 'refreshToken' /** column name */ | 'scope' /** column name */ | 'sessionState' /** column name */ | 'tokenType' /** column name */ | 'type' /** column name */ | 'userId'; /** input type for updating data in table "Account" */ export type Account_Set_Input = { accessToken?: InputMaybe<Scalars['String']>; expiresAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; idToken?: InputMaybe<Scalars['String']>; oauthToken?: InputMaybe<Scalars['String']>; oauthTokenSecret?: InputMaybe<Scalars['String']>; provider?: InputMaybe<Scalars['String']>; providerAccountId?: InputMaybe<Scalars['String']>; refreshToken?: InputMaybe<Scalars['String']>; scope?: InputMaybe<Scalars['String']>; sessionState?: InputMaybe<Scalars['String']>; tokenType?: InputMaybe<Scalars['String']>; type?: InputMaybe<Scalars['String']>; userId?: InputMaybe<Scalars['uuid']>; }; /** update columns of table "Account" */ export type Account_Update_Column = /** column name */ | 'accessToken' /** column name */ | 'expiresAt' /** column name */ | 'id' /** column name */ | 'idToken' /** column name */ | 'oauthToken' /** column name */ | 'oauthTokenSecret' /** column name */ | 'provider' /** column name */ | 'providerAccountId' /** column name */ | 'refreshToken' /** column name */ | 'scope' /** column name */ | 'sessionState' /** column name */ | 'tokenType' /** column name */ | 'type' /** column name */ | 'userId'; /** Boolean expression to compare columns of type "Boolean". All fields are combined with logical 'AND'. */ export type Boolean_Comparison_Exp = { _eq?: InputMaybe<Scalars['Boolean']>; _gt?: InputMaybe<Scalars['Boolean']>; _gte?: InputMaybe<Scalars['Boolean']>; _in?: InputMaybe<Array<Scalars['Boolean']>>; _is_null?: InputMaybe<Scalars['Boolean']>; _lt?: InputMaybe<Scalars['Boolean']>; _lte?: InputMaybe<Scalars['Boolean']>; _neq?: InputMaybe<Scalars['Boolean']>; _nin?: InputMaybe<Array<Scalars['Boolean']>>; }; /** columns and relationships of "Comment" */ export type Comment = { __typename?: 'Comment'; content: Scalars['jsonb']; createdAt: Scalars['timestamptz']; deletedAt?: Maybe<Scalars['timestamptz']>; id: Scalars['uuid']; /** An array relationship */ likes: Array<Like>; /** An aggregate relationship */ likes_aggregate: Like_Aggregate; /** An object relationship */ page: Page; pageId: Scalars['uuid']; /** An object relationship */ parent?: Maybe<Comment>; parentId?: Maybe<Scalars['uuid']>; /** An array relationship */ replies: Array<Comment>; /** An aggregate relationship */ replies_aggregate: Comment_Aggregate; updatedAt: Scalars['timestamptz']; /** An object relationship */ user: User; userId: Scalars['uuid']; }; /** columns and relationships of "Comment" */ export type CommentContentArgs = { path?: InputMaybe<Scalars['String']>; }; /** columns and relationships of "Comment" */ export type CommentLikesArgs = { distinct_on?: InputMaybe<Array<Like_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Like_Order_By>>; where?: InputMaybe<Like_Bool_Exp>; }; /** columns and relationships of "Comment" */ export type CommentLikes_AggregateArgs = { distinct_on?: InputMaybe<Array<Like_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Like_Order_By>>; where?: InputMaybe<Like_Bool_Exp>; }; /** columns and relationships of "Comment" */ export type CommentRepliesArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; /** columns and relationships of "Comment" */ export type CommentReplies_AggregateArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; /** aggregated selection of "Comment" */ export type Comment_Aggregate = { __typename?: 'Comment_aggregate'; aggregate?: Maybe<Comment_Aggregate_Fields>; nodes: Array<Comment>; }; /** aggregate fields of "Comment" */ export type Comment_Aggregate_Fields = { __typename?: 'Comment_aggregate_fields'; count: Scalars['Int']; max?: Maybe<Comment_Max_Fields>; min?: Maybe<Comment_Min_Fields>; }; /** aggregate fields of "Comment" */ export type Comment_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<Comment_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "Comment" */ export type Comment_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<Comment_Max_Order_By>; min?: InputMaybe<Comment_Min_Order_By>; }; /** append existing jsonb value of filtered columns with new jsonb value */ export type Comment_Append_Input = { content?: InputMaybe<Scalars['jsonb']>; }; /** input type for inserting array relation for remote table "Comment" */ export type Comment_Arr_Rel_Insert_Input = { data: Array<Comment_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<Comment_On_Conflict>; }; /** Boolean expression to filter rows from the table "Comment". All fields are combined with a logical 'AND'. */ export type Comment_Bool_Exp = { _and?: InputMaybe<Array<Comment_Bool_Exp>>; _not?: InputMaybe<Comment_Bool_Exp>; _or?: InputMaybe<Array<Comment_Bool_Exp>>; content?: InputMaybe<Jsonb_Comparison_Exp>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; deletedAt?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; likes?: InputMaybe<Like_Bool_Exp>; page?: InputMaybe<Page_Bool_Exp>; pageId?: InputMaybe<Uuid_Comparison_Exp>; parent?: InputMaybe<Comment_Bool_Exp>; parentId?: InputMaybe<Uuid_Comparison_Exp>; replies?: InputMaybe<Comment_Bool_Exp>; updatedAt?: InputMaybe<Timestamptz_Comparison_Exp>; user?: InputMaybe<User_Bool_Exp>; userId?: InputMaybe<Uuid_Comparison_Exp>; }; /** unique or primary key constraints on table "Comment" */ export type Comment_Constraint = /** unique or primary key constraint */ 'Comment_pkey'; /** delete the field or element with specified path (for JSON arrays, negative integers count from the end) */ export type Comment_Delete_At_Path_Input = { content?: InputMaybe<Array<Scalars['String']>>; }; /** delete the array element with specified index (negative integers count from the end). throws an error if top level container is not an array */ export type Comment_Delete_Elem_Input = { content?: InputMaybe<Scalars['Int']>; }; /** delete key/value pair or string element. key/value pairs are matched based on their key value */ export type Comment_Delete_Key_Input = { content?: InputMaybe<Scalars['String']>; }; /** input type for inserting data into table "Comment" */ export type Comment_Insert_Input = { content?: InputMaybe<Scalars['jsonb']>; createdAt?: InputMaybe<Scalars['timestamptz']>; deletedAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; likes?: InputMaybe<Like_Arr_Rel_Insert_Input>; page?: InputMaybe<Page_Obj_Rel_Insert_Input>; pageId?: InputMaybe<Scalars['uuid']>; parent?: InputMaybe<Comment_Obj_Rel_Insert_Input>; parentId?: InputMaybe<Scalars['uuid']>; replies?: InputMaybe<Comment_Arr_Rel_Insert_Input>; updatedAt?: InputMaybe<Scalars['timestamptz']>; user?: InputMaybe<User_Obj_Rel_Insert_Input>; userId?: InputMaybe<Scalars['uuid']>; }; /** aggregate max on columns */ export type Comment_Max_Fields = { __typename?: 'Comment_max_fields'; createdAt?: Maybe<Scalars['timestamptz']>; deletedAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; pageId?: Maybe<Scalars['uuid']>; parentId?: Maybe<Scalars['uuid']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by max() on columns of table "Comment" */ export type Comment_Max_Order_By = { createdAt?: InputMaybe<Order_By>; deletedAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; pageId?: InputMaybe<Order_By>; parentId?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type Comment_Min_Fields = { __typename?: 'Comment_min_fields'; createdAt?: Maybe<Scalars['timestamptz']>; deletedAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; pageId?: Maybe<Scalars['uuid']>; parentId?: Maybe<Scalars['uuid']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by min() on columns of table "Comment" */ export type Comment_Min_Order_By = { createdAt?: InputMaybe<Order_By>; deletedAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; pageId?: InputMaybe<Order_By>; parentId?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** response of any mutation on the table "Comment" */ export type Comment_Mutation_Response = { __typename?: 'Comment_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<Comment>; }; /** input type for inserting object relation for remote table "Comment" */ export type Comment_Obj_Rel_Insert_Input = { data: Comment_Insert_Input; /** upsert condition */ on_conflict?: InputMaybe<Comment_On_Conflict>; }; /** on_conflict condition type for table "Comment" */ export type Comment_On_Conflict = { constraint: Comment_Constraint; update_columns?: Array<Comment_Update_Column>; where?: InputMaybe<Comment_Bool_Exp>; }; /** Ordering options when selecting data from "Comment". */ export type Comment_Order_By = { content?: InputMaybe<Order_By>; createdAt?: InputMaybe<Order_By>; deletedAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; likes_aggregate?: InputMaybe<Like_Aggregate_Order_By>; page?: InputMaybe<Page_Order_By>; pageId?: InputMaybe<Order_By>; parent?: InputMaybe<Comment_Order_By>; parentId?: InputMaybe<Order_By>; replies_aggregate?: InputMaybe<Comment_Aggregate_Order_By>; updatedAt?: InputMaybe<Order_By>; user?: InputMaybe<User_Order_By>; userId?: InputMaybe<Order_By>; }; /** primary key columns input for table: Comment */ export type Comment_Pk_Columns_Input = { id: Scalars['uuid']; }; /** prepend existing jsonb value of filtered columns with new jsonb value */ export type Comment_Prepend_Input = { content?: InputMaybe<Scalars['jsonb']>; }; /** select columns of table "Comment" */ export type Comment_Select_Column = /** column name */ | 'content' /** column name */ | 'createdAt' /** column name */ | 'deletedAt' /** column name */ | 'id' /** column name */ | 'pageId' /** column name */ | 'parentId' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** input type for updating data in table "Comment" */ export type Comment_Set_Input = { content?: InputMaybe<Scalars['jsonb']>; createdAt?: InputMaybe<Scalars['timestamptz']>; deletedAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; pageId?: InputMaybe<Scalars['uuid']>; parentId?: InputMaybe<Scalars['uuid']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; userId?: InputMaybe<Scalars['uuid']>; }; /** update columns of table "Comment" */ export type Comment_Update_Column = /** column name */ | 'content' /** column name */ | 'createdAt' /** column name */ | 'deletedAt' /** column name */ | 'id' /** column name */ | 'pageId' /** column name */ | 'parentId' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** columns and relationships of "Like" */ export type Like = { __typename?: 'Like'; /** An object relationship */ comment: Comment; commentId: Scalars['uuid']; createdAt: Scalars['timestamptz']; id: Scalars['uuid']; updatedAt: Scalars['timestamptz']; /** An object relationship */ user: User; userId: Scalars['uuid']; }; /** aggregated selection of "Like" */ export type Like_Aggregate = { __typename?: 'Like_aggregate'; aggregate?: Maybe<Like_Aggregate_Fields>; nodes: Array<Like>; }; /** aggregate fields of "Like" */ export type Like_Aggregate_Fields = { __typename?: 'Like_aggregate_fields'; count: Scalars['Int']; max?: Maybe<Like_Max_Fields>; min?: Maybe<Like_Min_Fields>; }; /** aggregate fields of "Like" */ export type Like_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<Like_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "Like" */ export type Like_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<Like_Max_Order_By>; min?: InputMaybe<Like_Min_Order_By>; }; /** input type for inserting array relation for remote table "Like" */ export type Like_Arr_Rel_Insert_Input = { data: Array<Like_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<Like_On_Conflict>; }; /** Boolean expression to filter rows from the table "Like". All fields are combined with a logical 'AND'. */ export type Like_Bool_Exp = { _and?: InputMaybe<Array<Like_Bool_Exp>>; _not?: InputMaybe<Like_Bool_Exp>; _or?: InputMaybe<Array<Like_Bool_Exp>>; comment?: InputMaybe<Comment_Bool_Exp>; commentId?: InputMaybe<Uuid_Comparison_Exp>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; updatedAt?: InputMaybe<Timestamptz_Comparison_Exp>; user?: InputMaybe<User_Bool_Exp>; userId?: InputMaybe<Uuid_Comparison_Exp>; }; /** unique or primary key constraints on table "Like" */ export type Like_Constraint = /** unique or primary key constraint */ | 'Like_commentId_userId_key' /** unique or primary key constraint */ | 'Like_pkey'; /** input type for inserting data into table "Like" */ export type Like_Insert_Input = { comment?: InputMaybe<Comment_Obj_Rel_Insert_Input>; commentId?: InputMaybe<Scalars['uuid']>; createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; user?: InputMaybe<User_Obj_Rel_Insert_Input>; userId?: InputMaybe<Scalars['uuid']>; }; /** aggregate max on columns */ export type Like_Max_Fields = { __typename?: 'Like_max_fields'; commentId?: Maybe<Scalars['uuid']>; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by max() on columns of table "Like" */ export type Like_Max_Order_By = { commentId?: InputMaybe<Order_By>; createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type Like_Min_Fields = { __typename?: 'Like_min_fields'; commentId?: Maybe<Scalars['uuid']>; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by min() on columns of table "Like" */ export type Like_Min_Order_By = { commentId?: InputMaybe<Order_By>; createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** response of any mutation on the table "Like" */ export type Like_Mutation_Response = { __typename?: 'Like_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<Like>; }; /** on_conflict condition type for table "Like" */ export type Like_On_Conflict = { constraint: Like_Constraint; update_columns?: Array<Like_Update_Column>; where?: InputMaybe<Like_Bool_Exp>; }; /** Ordering options when selecting data from "Like". */ export type Like_Order_By = { comment?: InputMaybe<Comment_Order_By>; commentId?: InputMaybe<Order_By>; createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; user?: InputMaybe<User_Order_By>; userId?: InputMaybe<Order_By>; }; /** primary key columns input for table: Like */ export type Like_Pk_Columns_Input = { id: Scalars['uuid']; }; /** select columns of table "Like" */ export type Like_Select_Column = /** column name */ | 'commentId' /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** input type for updating data in table "Like" */ export type Like_Set_Input = { commentId?: InputMaybe<Scalars['uuid']>; createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; userId?: InputMaybe<Scalars['uuid']>; }; /** update columns of table "Like" */ export type Like_Update_Column = /** column name */ | 'commentId' /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** columns and relationships of "Member" */ export type Member = { __typename?: 'Member'; /** An object relationship */ Role: Role; createdAt: Scalars['timestamptz']; id: Scalars['uuid']; role: Role_Enum; /** An object relationship */ team: Team; teamId: Scalars['uuid']; updatedAt: Scalars['timestamptz']; /** An object relationship */ user: User; userId: Scalars['uuid']; }; /** aggregated selection of "Member" */ export type Member_Aggregate = { __typename?: 'Member_aggregate'; aggregate?: Maybe<Member_Aggregate_Fields>; nodes: Array<Member>; }; /** aggregate fields of "Member" */ export type Member_Aggregate_Fields = { __typename?: 'Member_aggregate_fields'; count: Scalars['Int']; max?: Maybe<Member_Max_Fields>; min?: Maybe<Member_Min_Fields>; }; /** aggregate fields of "Member" */ export type Member_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<Member_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "Member" */ export type Member_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<Member_Max_Order_By>; min?: InputMaybe<Member_Min_Order_By>; }; /** input type for inserting array relation for remote table "Member" */ export type Member_Arr_Rel_Insert_Input = { data: Array<Member_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<Member_On_Conflict>; }; /** Boolean expression to filter rows from the table "Member". All fields are combined with a logical 'AND'. */ export type Member_Bool_Exp = { Role?: InputMaybe<Role_Bool_Exp>; _and?: InputMaybe<Array<Member_Bool_Exp>>; _not?: InputMaybe<Member_Bool_Exp>; _or?: InputMaybe<Array<Member_Bool_Exp>>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; role?: InputMaybe<Role_Enum_Comparison_Exp>; team?: InputMaybe<Team_Bool_Exp>; teamId?: InputMaybe<Uuid_Comparison_Exp>; updatedAt?: InputMaybe<Timestamptz_Comparison_Exp>; user?: InputMaybe<User_Bool_Exp>; userId?: InputMaybe<Uuid_Comparison_Exp>; }; /** unique or primary key constraints on table "Member" */ export type Member_Constraint = /** unique or primary key constraint */ | 'Member_pkey' /** unique or primary key constraint */ | 'Member_teamId_userId_key'; /** input type for inserting data into table "Member" */ export type Member_Insert_Input = { Role?: InputMaybe<Role_Obj_Rel_Insert_Input>; createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; role?: InputMaybe<Role_Enum>; team?: InputMaybe<Team_Obj_Rel_Insert_Input>; teamId?: InputMaybe<Scalars['uuid']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; user?: InputMaybe<User_Obj_Rel_Insert_Input>; userId?: InputMaybe<Scalars['uuid']>; }; /** aggregate max on columns */ export type Member_Max_Fields = { __typename?: 'Member_max_fields'; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; teamId?: Maybe<Scalars['uuid']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by max() on columns of table "Member" */ export type Member_Max_Order_By = { createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; teamId?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type Member_Min_Fields = { __typename?: 'Member_min_fields'; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; teamId?: Maybe<Scalars['uuid']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by min() on columns of table "Member" */ export type Member_Min_Order_By = { createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; teamId?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** response of any mutation on the table "Member" */ export type Member_Mutation_Response = { __typename?: 'Member_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<Member>; }; /** on_conflict condition type for table "Member" */ export type Member_On_Conflict = { constraint: Member_Constraint; update_columns?: Array<Member_Update_Column>; where?: InputMaybe<Member_Bool_Exp>; }; /** Ordering options when selecting data from "Member". */ export type Member_Order_By = { Role?: InputMaybe<Role_Order_By>; createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; role?: InputMaybe<Order_By>; team?: InputMaybe<Team_Order_By>; teamId?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; user?: InputMaybe<User_Order_By>; userId?: InputMaybe<Order_By>; }; /** primary key columns input for table: Member */ export type Member_Pk_Columns_Input = { id: Scalars['uuid']; }; /** select columns of table "Member" */ export type Member_Select_Column = /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'role' /** column name */ | 'teamId' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** input type for updating data in table "Member" */ export type Member_Set_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; role?: InputMaybe<Role_Enum>; teamId?: InputMaybe<Scalars['uuid']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; userId?: InputMaybe<Scalars['uuid']>; }; /** update columns of table "Member" */ export type Member_Update_Column = /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'role' /** column name */ | 'teamId' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** columns and relationships of "NotificationMessage" */ export type NotificationMessage = { __typename?: 'NotificationMessage'; /** Content of message, e.g. comment content */ content?: Maybe<Scalars['String']>; /** Triggered entity's id, e.g. CommentId or LikeId */ contextId: Scalars['uuid']; createdAt: Scalars['timestamptz']; deletedAt?: Maybe<Scalars['timestamptz']>; id: Scalars['uuid']; /** An object relationship */ notificationType: NotificationType; read: Scalars['Boolean']; /** An object relationship */ recipient: User; recipientId: Scalars['uuid']; /** An object relationship */ triggeredBy: User; triggeredById: Scalars['uuid']; type: NotificationType_Enum; url: Scalars['String']; }; /** aggregated selection of "NotificationMessage" */ export type NotificationMessage_Aggregate = { __typename?: 'NotificationMessage_aggregate'; aggregate?: Maybe<NotificationMessage_Aggregate_Fields>; nodes: Array<NotificationMessage>; }; /** aggregate fields of "NotificationMessage" */ export type NotificationMessage_Aggregate_Fields = { __typename?: 'NotificationMessage_aggregate_fields'; count: Scalars['Int']; max?: Maybe<NotificationMessage_Max_Fields>; min?: Maybe<NotificationMessage_Min_Fields>; }; /** aggregate fields of "NotificationMessage" */ export type NotificationMessage_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<NotificationMessage_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "NotificationMessage" */ export type NotificationMessage_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<NotificationMessage_Max_Order_By>; min?: InputMaybe<NotificationMessage_Min_Order_By>; }; /** input type for inserting array relation for remote table "NotificationMessage" */ export type NotificationMessage_Arr_Rel_Insert_Input = { data: Array<NotificationMessage_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<NotificationMessage_On_Conflict>; }; /** Boolean expression to filter rows from the table "NotificationMessage". All fields are combined with a logical 'AND'. */ export type NotificationMessage_Bool_Exp = { _and?: InputMaybe<Array<NotificationMessage_Bool_Exp>>; _not?: InputMaybe<NotificationMessage_Bool_Exp>; _or?: InputMaybe<Array<NotificationMessage_Bool_Exp>>; content?: InputMaybe<String_Comparison_Exp>; contextId?: InputMaybe<Uuid_Comparison_Exp>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; deletedAt?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; notificationType?: InputMaybe<NotificationType_Bool_Exp>; read?: InputMaybe<Boolean_Comparison_Exp>; recipient?: InputMaybe<User_Bool_Exp>; recipientId?: InputMaybe<Uuid_Comparison_Exp>; triggeredBy?: InputMaybe<User_Bool_Exp>; triggeredById?: InputMaybe<Uuid_Comparison_Exp>; type?: InputMaybe<NotificationType_Enum_Comparison_Exp>; url?: InputMaybe<String_Comparison_Exp>; }; /** unique or primary key constraints on table "NotificationMessage" */ export type NotificationMessage_Constraint = /** unique or primary key constraint */ | 'NotificationMessage_pkey' /** unique or primary key constraint */ | 'NotificationMessage_type_triggeredById_contextId_recipientI_key'; /** input type for inserting data into table "NotificationMessage" */ export type NotificationMessage_Insert_Input = { /** Content of message, e.g. comment content */ content?: InputMaybe<Scalars['String']>; /** Triggered entity's id, e.g. CommentId or LikeId */ contextId?: InputMaybe<Scalars['uuid']>; createdAt?: InputMaybe<Scalars['timestamptz']>; deletedAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; notificationType?: InputMaybe<NotificationType_Obj_Rel_Insert_Input>; read?: InputMaybe<Scalars['Boolean']>; recipient?: InputMaybe<User_Obj_Rel_Insert_Input>; recipientId?: InputMaybe<Scalars['uuid']>; triggeredBy?: InputMaybe<User_Obj_Rel_Insert_Input>; triggeredById?: InputMaybe<Scalars['uuid']>; type?: InputMaybe<NotificationType_Enum>; url?: InputMaybe<Scalars['String']>; }; /** aggregate max on columns */ export type NotificationMessage_Max_Fields = { __typename?: 'NotificationMessage_max_fields'; /** Content of message, e.g. comment content */ content?: Maybe<Scalars['String']>; /** Triggered entity's id, e.g. CommentId or LikeId */ contextId?: Maybe<Scalars['uuid']>; createdAt?: Maybe<Scalars['timestamptz']>; deletedAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; recipientId?: Maybe<Scalars['uuid']>; triggeredById?: Maybe<Scalars['uuid']>; url?: Maybe<Scalars['String']>; }; /** order by max() on columns of table "NotificationMessage" */ export type NotificationMessage_Max_Order_By = { /** Content of message, e.g. comment content */ content?: InputMaybe<Order_By>; /** Triggered entity's id, e.g. CommentId or LikeId */ contextId?: InputMaybe<Order_By>; createdAt?: InputMaybe<Order_By>; deletedAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; recipientId?: InputMaybe<Order_By>; triggeredById?: InputMaybe<Order_By>; url?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type NotificationMessage_Min_Fields = { __typename?: 'NotificationMessage_min_fields'; /** Content of message, e.g. comment content */ content?: Maybe<Scalars['String']>; /** Triggered entity's id, e.g. CommentId or LikeId */ contextId?: Maybe<Scalars['uuid']>; createdAt?: Maybe<Scalars['timestamptz']>; deletedAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; recipientId?: Maybe<Scalars['uuid']>; triggeredById?: Maybe<Scalars['uuid']>; url?: Maybe<Scalars['String']>; }; /** order by min() on columns of table "NotificationMessage" */ export type NotificationMessage_Min_Order_By = { /** Content of message, e.g. comment content */ content?: InputMaybe<Order_By>; /** Triggered entity's id, e.g. CommentId or LikeId */ contextId?: InputMaybe<Order_By>; createdAt?: InputMaybe<Order_By>; deletedAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; recipientId?: InputMaybe<Order_By>; triggeredById?: InputMaybe<Order_By>; url?: InputMaybe<Order_By>; }; /** response of any mutation on the table "NotificationMessage" */ export type NotificationMessage_Mutation_Response = { __typename?: 'NotificationMessage_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<NotificationMessage>; }; /** on_conflict condition type for table "NotificationMessage" */ export type NotificationMessage_On_Conflict = { constraint: NotificationMessage_Constraint; update_columns?: Array<NotificationMessage_Update_Column>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; /** Ordering options when selecting data from "NotificationMessage". */ export type NotificationMessage_Order_By = { content?: InputMaybe<Order_By>; contextId?: InputMaybe<Order_By>; createdAt?: InputMaybe<Order_By>; deletedAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; notificationType?: InputMaybe<NotificationType_Order_By>; read?: InputMaybe<Order_By>; recipient?: InputMaybe<User_Order_By>; recipientId?: InputMaybe<Order_By>; triggeredBy?: InputMaybe<User_Order_By>; triggeredById?: InputMaybe<Order_By>; type?: InputMaybe<Order_By>; url?: InputMaybe<Order_By>; }; /** primary key columns input for table: NotificationMessage */ export type NotificationMessage_Pk_Columns_Input = { id: Scalars['uuid']; }; /** select columns of table "NotificationMessage" */ export type NotificationMessage_Select_Column = /** column name */ | 'content' /** column name */ | 'contextId' /** column name */ | 'createdAt' /** column name */ | 'deletedAt' /** column name */ | 'id' /** column name */ | 'read' /** column name */ | 'recipientId' /** column name */ | 'triggeredById' /** column name */ | 'type' /** column name */ | 'url'; /** input type for updating data in table "NotificationMessage" */ export type NotificationMessage_Set_Input = { /** Content of message, e.g. comment content */ content?: InputMaybe<Scalars['String']>; /** Triggered entity's id, e.g. CommentId or LikeId */ contextId?: InputMaybe<Scalars['uuid']>; createdAt?: InputMaybe<Scalars['timestamptz']>; deletedAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; read?: InputMaybe<Scalars['Boolean']>; recipientId?: InputMaybe<Scalars['uuid']>; triggeredById?: InputMaybe<Scalars['uuid']>; type?: InputMaybe<NotificationType_Enum>; url?: InputMaybe<Scalars['String']>; }; /** update columns of table "NotificationMessage" */ export type NotificationMessage_Update_Column = /** column name */ | 'content' /** column name */ | 'contextId' /** column name */ | 'createdAt' /** column name */ | 'deletedAt' /** column name */ | 'id' /** column name */ | 'read' /** column name */ | 'recipientId' /** column name */ | 'triggeredById' /** column name */ | 'type' /** column name */ | 'url'; /** columns and relationships of "NotificationSubscription" */ export type NotificationSubscription = { __typename?: 'NotificationSubscription'; createdAt: Scalars['timestamptz']; id: Scalars['uuid']; subscription: Scalars['jsonb']; /** An object relationship */ user: User; userId: Scalars['uuid']; }; /** columns and relationships of "NotificationSubscription" */ export type NotificationSubscriptionSubscriptionArgs = { path?: InputMaybe<Scalars['String']>; }; /** aggregated selection of "NotificationSubscription" */ export type NotificationSubscription_Aggregate = { __typename?: 'NotificationSubscription_aggregate'; aggregate?: Maybe<NotificationSubscription_Aggregate_Fields>; nodes: Array<NotificationSubscription>; }; /** aggregate fields of "NotificationSubscription" */ export type NotificationSubscription_Aggregate_Fields = { __typename?: 'NotificationSubscription_aggregate_fields'; count: Scalars['Int']; max?: Maybe<NotificationSubscription_Max_Fields>; min?: Maybe<NotificationSubscription_Min_Fields>; }; /** aggregate fields of "NotificationSubscription" */ export type NotificationSubscription_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<NotificationSubscription_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "NotificationSubscription" */ export type NotificationSubscription_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<NotificationSubscription_Max_Order_By>; min?: InputMaybe<NotificationSubscription_Min_Order_By>; }; /** append existing jsonb value of filtered columns with new jsonb value */ export type NotificationSubscription_Append_Input = { subscription?: InputMaybe<Scalars['jsonb']>; }; /** input type for inserting array relation for remote table "NotificationSubscription" */ export type NotificationSubscription_Arr_Rel_Insert_Input = { data: Array<NotificationSubscription_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<NotificationSubscription_On_Conflict>; }; /** Boolean expression to filter rows from the table "NotificationSubscription". All fields are combined with a logical 'AND'. */ export type NotificationSubscription_Bool_Exp = { _and?: InputMaybe<Array<NotificationSubscription_Bool_Exp>>; _not?: InputMaybe<NotificationSubscription_Bool_Exp>; _or?: InputMaybe<Array<NotificationSubscription_Bool_Exp>>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; subscription?: InputMaybe<Jsonb_Comparison_Exp>; user?: InputMaybe<User_Bool_Exp>; userId?: InputMaybe<Uuid_Comparison_Exp>; }; /** unique or primary key constraints on table "NotificationSubscription" */ export type NotificationSubscription_Constraint = /** unique or primary key constraint */ | 'NotificationSubscription_pkey' /** unique or primary key constraint */ | 'NotificationSubscription_subscription_userId_key'; /** delete the field or element with specified path (for JSON arrays, negative integers count from the end) */ export type NotificationSubscription_Delete_At_Path_Input = { subscription?: InputMaybe<Array<Scalars['String']>>; }; /** delete the array element with specified index (negative integers count from the end). throws an error if top level container is not an array */ export type NotificationSubscription_Delete_Elem_Input = { subscription?: InputMaybe<Scalars['Int']>; }; /** delete key/value pair or string element. key/value pairs are matched based on their key value */ export type NotificationSubscription_Delete_Key_Input = { subscription?: InputMaybe<Scalars['String']>; }; /** input type for inserting data into table "NotificationSubscription" */ export type NotificationSubscription_Insert_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; subscription?: InputMaybe<Scalars['jsonb']>; user?: InputMaybe<User_Obj_Rel_Insert_Input>; userId?: InputMaybe<Scalars['uuid']>; }; /** aggregate max on columns */ export type NotificationSubscription_Max_Fields = { __typename?: 'NotificationSubscription_max_fields'; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; userId?: Maybe<Scalars['uuid']>; }; /** order by max() on columns of table "NotificationSubscription" */ export type NotificationSubscription_Max_Order_By = { createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type NotificationSubscription_Min_Fields = { __typename?: 'NotificationSubscription_min_fields'; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; userId?: Maybe<Scalars['uuid']>; }; /** order by min() on columns of table "NotificationSubscription" */ export type NotificationSubscription_Min_Order_By = { createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** response of any mutation on the table "NotificationSubscription" */ export type NotificationSubscription_Mutation_Response = { __typename?: 'NotificationSubscription_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<NotificationSubscription>; }; /** on_conflict condition type for table "NotificationSubscription" */ export type NotificationSubscription_On_Conflict = { constraint: NotificationSubscription_Constraint; update_columns?: Array<NotificationSubscription_Update_Column>; where?: InputMaybe<NotificationSubscription_Bool_Exp>; }; /** Ordering options when selecting data from "NotificationSubscription". */ export type NotificationSubscription_Order_By = { createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; subscription?: InputMaybe<Order_By>; user?: InputMaybe<User_Order_By>; userId?: InputMaybe<Order_By>; }; /** primary key columns input for table: NotificationSubscription */ export type NotificationSubscription_Pk_Columns_Input = { id: Scalars['uuid']; }; /** prepend existing jsonb value of filtered columns with new jsonb value */ export type NotificationSubscription_Prepend_Input = { subscription?: InputMaybe<Scalars['jsonb']>; }; /** select columns of table "NotificationSubscription" */ export type NotificationSubscription_Select_Column = /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'subscription' /** column name */ | 'userId'; /** input type for updating data in table "NotificationSubscription" */ export type NotificationSubscription_Set_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; subscription?: InputMaybe<Scalars['jsonb']>; userId?: InputMaybe<Scalars['uuid']>; }; /** update columns of table "NotificationSubscription" */ export type NotificationSubscription_Update_Column = /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'subscription' /** column name */ | 'userId'; /** columns and relationships of "NotificationType" */ export type NotificationType = { __typename?: 'NotificationType'; comment: Scalars['String']; /** An array relationship */ notificationMessages: Array<NotificationMessage>; /** An aggregate relationship */ notificationMessages_aggregate: NotificationMessage_Aggregate; value: Scalars['String']; }; /** columns and relationships of "NotificationType" */ export type NotificationTypeNotificationMessagesArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; /** columns and relationships of "NotificationType" */ export type NotificationTypeNotificationMessages_AggregateArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; /** aggregated selection of "NotificationType" */ export type NotificationType_Aggregate = { __typename?: 'NotificationType_aggregate'; aggregate?: Maybe<NotificationType_Aggregate_Fields>; nodes: Array<NotificationType>; }; /** aggregate fields of "NotificationType" */ export type NotificationType_Aggregate_Fields = { __typename?: 'NotificationType_aggregate_fields'; count: Scalars['Int']; max?: Maybe<NotificationType_Max_Fields>; min?: Maybe<NotificationType_Min_Fields>; }; /** aggregate fields of "NotificationType" */ export type NotificationType_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<NotificationType_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** Boolean expression to filter rows from the table "NotificationType". All fields are combined with a logical 'AND'. */ export type NotificationType_Bool_Exp = { _and?: InputMaybe<Array<NotificationType_Bool_Exp>>; _not?: InputMaybe<NotificationType_Bool_Exp>; _or?: InputMaybe<Array<NotificationType_Bool_Exp>>; comment?: InputMaybe<String_Comparison_Exp>; notificationMessages?: InputMaybe<NotificationMessage_Bool_Exp>; value?: InputMaybe<String_Comparison_Exp>; }; /** unique or primary key constraints on table "NotificationType" */ export type NotificationType_Constraint = /** unique or primary key constraint */ 'NotificationType_pkey'; export type NotificationType_Enum = /** Comment deleted by moderator */ | 'CommentDeleted' /** Received a comment */ | 'ReceivedAComment' /** Received a like */ | 'ReceivedALike' /** Received a reply */ | 'ReceivedAReply'; /** Boolean expression to compare columns of type "NotificationType_enum". All fields are combined with logical 'AND'. */ export type NotificationType_Enum_Comparison_Exp = { _eq?: InputMaybe<NotificationType_Enum>; _in?: InputMaybe<Array<NotificationType_Enum>>; _is_null?: InputMaybe<Scalars['Boolean']>; _neq?: InputMaybe<NotificationType_Enum>; _nin?: InputMaybe<Array<NotificationType_Enum>>; }; /** input type for inserting data into table "NotificationType" */ export type NotificationType_Insert_Input = { comment?: InputMaybe<Scalars['String']>; notificationMessages?: InputMaybe<NotificationMessage_Arr_Rel_Insert_Input>; value?: InputMaybe<Scalars['String']>; }; /** aggregate max on columns */ export type NotificationType_Max_Fields = { __typename?: 'NotificationType_max_fields'; comment?: Maybe<Scalars['String']>; value?: Maybe<Scalars['String']>; }; /** aggregate min on columns */ export type NotificationType_Min_Fields = { __typename?: 'NotificationType_min_fields'; comment?: Maybe<Scalars['String']>; value?: Maybe<Scalars['String']>; }; /** response of any mutation on the table "NotificationType" */ export type NotificationType_Mutation_Response = { __typename?: 'NotificationType_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<NotificationType>; }; /** input type for inserting object relation for remote table "NotificationType" */ export type NotificationType_Obj_Rel_Insert_Input = { data: NotificationType_Insert_Input; /** upsert condition */ on_conflict?: InputMaybe<NotificationType_On_Conflict>; }; /** on_conflict condition type for table "NotificationType" */ export type NotificationType_On_Conflict = { constraint: NotificationType_Constraint; update_columns?: Array<NotificationType_Update_Column>; where?: InputMaybe<NotificationType_Bool_Exp>; }; /** Ordering options when selecting data from "NotificationType". */ export type NotificationType_Order_By = { comment?: InputMaybe<Order_By>; notificationMessages_aggregate?: InputMaybe<NotificationMessage_Aggregate_Order_By>; value?: InputMaybe<Order_By>; }; /** primary key columns input for table: NotificationType */ export type NotificationType_Pk_Columns_Input = { value: Scalars['String']; }; /** select columns of table "NotificationType" */ export type NotificationType_Select_Column = /** column name */ | 'comment' /** column name */ | 'value'; /** input type for updating data in table "NotificationType" */ export type NotificationType_Set_Input = { comment?: InputMaybe<Scalars['String']>; value?: InputMaybe<Scalars['String']>; }; /** update columns of table "NotificationType" */ export type NotificationType_Update_Column = /** column name */ | 'comment' /** column name */ | 'value'; /** columns and relationships of "Page" */ export type Page = { __typename?: 'Page'; /** An array relationship */ comments: Array<Comment>; /** An aggregate relationship */ comments_aggregate: Comment_Aggregate; createdAt: Scalars['timestamptz']; id: Scalars['uuid']; /** An object relationship */ project: Project; projectId: Scalars['uuid']; title?: Maybe<Scalars['String']>; updatedAt: Scalars['timestamptz']; url: Scalars['String']; }; /** columns and relationships of "Page" */ export type PageCommentsArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; /** columns and relationships of "Page" */ export type PageComments_AggregateArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; /** aggregated selection of "Page" */ export type Page_Aggregate = { __typename?: 'Page_aggregate'; aggregate?: Maybe<Page_Aggregate_Fields>; nodes: Array<Page>; }; /** aggregate fields of "Page" */ export type Page_Aggregate_Fields = { __typename?: 'Page_aggregate_fields'; count: Scalars['Int']; max?: Maybe<Page_Max_Fields>; min?: Maybe<Page_Min_Fields>; }; /** aggregate fields of "Page" */ export type Page_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<Page_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "Page" */ export type Page_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<Page_Max_Order_By>; min?: InputMaybe<Page_Min_Order_By>; }; /** input type for inserting array relation for remote table "Page" */ export type Page_Arr_Rel_Insert_Input = { data: Array<Page_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<Page_On_Conflict>; }; /** Boolean expression to filter rows from the table "Page". All fields are combined with a logical 'AND'. */ export type Page_Bool_Exp = { _and?: InputMaybe<Array<Page_Bool_Exp>>; _not?: InputMaybe<Page_Bool_Exp>; _or?: InputMaybe<Array<Page_Bool_Exp>>; comments?: InputMaybe<Comment_Bool_Exp>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; project?: InputMaybe<Project_Bool_Exp>; projectId?: InputMaybe<Uuid_Comparison_Exp>; title?: InputMaybe<String_Comparison_Exp>; updatedAt?: InputMaybe<Timestamptz_Comparison_Exp>; url?: InputMaybe<String_Comparison_Exp>; }; /** unique or primary key constraints on table "Page" */ export type Page_Constraint = /** unique or primary key constraint */ | 'Page_pkey' /** unique or primary key constraint */ | 'Page_url_key'; /** input type for inserting data into table "Page" */ export type Page_Insert_Input = { comments?: InputMaybe<Comment_Arr_Rel_Insert_Input>; createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; project?: InputMaybe<Project_Obj_Rel_Insert_Input>; projectId?: InputMaybe<Scalars['uuid']>; title?: InputMaybe<Scalars['String']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; url?: InputMaybe<Scalars['String']>; }; /** aggregate max on columns */ export type Page_Max_Fields = { __typename?: 'Page_max_fields'; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; projectId?: Maybe<Scalars['uuid']>; title?: Maybe<Scalars['String']>; updatedAt?: Maybe<Scalars['timestamptz']>; url?: Maybe<Scalars['String']>; }; /** order by max() on columns of table "Page" */ export type Page_Max_Order_By = { createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; projectId?: InputMaybe<Order_By>; title?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; url?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type Page_Min_Fields = { __typename?: 'Page_min_fields'; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; projectId?: Maybe<Scalars['uuid']>; title?: Maybe<Scalars['String']>; updatedAt?: Maybe<Scalars['timestamptz']>; url?: Maybe<Scalars['String']>; }; /** order by min() on columns of table "Page" */ export type Page_Min_Order_By = { createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; projectId?: InputMaybe<Order_By>; title?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; url?: InputMaybe<Order_By>; }; /** response of any mutation on the table "Page" */ export type Page_Mutation_Response = { __typename?: 'Page_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<Page>; }; /** input type for inserting object relation for remote table "Page" */ export type Page_Obj_Rel_Insert_Input = { data: Page_Insert_Input; /** upsert condition */ on_conflict?: InputMaybe<Page_On_Conflict>; }; /** on_conflict condition type for table "Page" */ export type Page_On_Conflict = { constraint: Page_Constraint; update_columns?: Array<Page_Update_Column>; where?: InputMaybe<Page_Bool_Exp>; }; /** Ordering options when selecting data from "Page". */ export type Page_Order_By = { comments_aggregate?: InputMaybe<Comment_Aggregate_Order_By>; createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; project?: InputMaybe<Project_Order_By>; projectId?: InputMaybe<Order_By>; title?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; url?: InputMaybe<Order_By>; }; /** primary key columns input for table: Page */ export type Page_Pk_Columns_Input = { id: Scalars['uuid']; }; /** select columns of table "Page" */ export type Page_Select_Column = /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'projectId' /** column name */ | 'title' /** column name */ | 'updatedAt' /** column name */ | 'url'; /** input type for updating data in table "Page" */ export type Page_Set_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; projectId?: InputMaybe<Scalars['uuid']>; title?: InputMaybe<Scalars['String']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; url?: InputMaybe<Scalars['String']>; }; /** update columns of table "Page" */ export type Page_Update_Column = /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'projectId' /** column name */ | 'title' /** column name */ | 'updatedAt' /** column name */ | 'url'; /** columns and relationships of "Project" */ export type Project = { __typename?: 'Project'; createdAt: Scalars['timestamptz']; domain: Scalars['String']; id: Scalars['uuid']; name: Scalars['String']; /** An array relationship */ pages: Array<Page>; /** An aggregate relationship */ pages_aggregate: Page_Aggregate; /** An object relationship */ team?: Maybe<Team>; teamId?: Maybe<Scalars['uuid']>; theme?: Maybe<Scalars['jsonb']>; updatedAt: Scalars['timestamptz']; /** An object relationship */ user?: Maybe<User>; userId?: Maybe<Scalars['uuid']>; }; /** columns and relationships of "Project" */ export type ProjectPagesArgs = { distinct_on?: InputMaybe<Array<Page_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Page_Order_By>>; where?: InputMaybe<Page_Bool_Exp>; }; /** columns and relationships of "Project" */ export type ProjectPages_AggregateArgs = { distinct_on?: InputMaybe<Array<Page_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Page_Order_By>>; where?: InputMaybe<Page_Bool_Exp>; }; /** columns and relationships of "Project" */ export type ProjectThemeArgs = { path?: InputMaybe<Scalars['String']>; }; /** aggregated selection of "Project" */ export type Project_Aggregate = { __typename?: 'Project_aggregate'; aggregate?: Maybe<Project_Aggregate_Fields>; nodes: Array<Project>; }; /** aggregate fields of "Project" */ export type Project_Aggregate_Fields = { __typename?: 'Project_aggregate_fields'; count: Scalars['Int']; max?: Maybe<Project_Max_Fields>; min?: Maybe<Project_Min_Fields>; }; /** aggregate fields of "Project" */ export type Project_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<Project_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "Project" */ export type Project_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<Project_Max_Order_By>; min?: InputMaybe<Project_Min_Order_By>; }; /** append existing jsonb value of filtered columns with new jsonb value */ export type Project_Append_Input = { theme?: InputMaybe<Scalars['jsonb']>; }; /** input type for inserting array relation for remote table "Project" */ export type Project_Arr_Rel_Insert_Input = { data: Array<Project_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<Project_On_Conflict>; }; /** Boolean expression to filter rows from the table "Project". All fields are combined with a logical 'AND'. */ export type Project_Bool_Exp = { _and?: InputMaybe<Array<Project_Bool_Exp>>; _not?: InputMaybe<Project_Bool_Exp>; _or?: InputMaybe<Array<Project_Bool_Exp>>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; domain?: InputMaybe<String_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; name?: InputMaybe<String_Comparison_Exp>; pages?: InputMaybe<Page_Bool_Exp>; team?: InputMaybe<Team_Bool_Exp>; teamId?: InputMaybe<Uuid_Comparison_Exp>; theme?: InputMaybe<Jsonb_Comparison_Exp>; updatedAt?: InputMaybe<Timestamptz_Comparison_Exp>; user?: InputMaybe<User_Bool_Exp>; userId?: InputMaybe<Uuid_Comparison_Exp>; }; /** unique or primary key constraints on table "Project" */ export type Project_Constraint = /** unique or primary key constraint */ | 'Project_domain_key' /** unique or primary key constraint */ | 'Project_pkey'; /** delete the field or element with specified path (for JSON arrays, negative integers count from the end) */ export type Project_Delete_At_Path_Input = { theme?: InputMaybe<Array<Scalars['String']>>; }; /** delete the array element with specified index (negative integers count from the end). throws an error if top level container is not an array */ export type Project_Delete_Elem_Input = { theme?: InputMaybe<Scalars['Int']>; }; /** delete key/value pair or string element. key/value pairs are matched based on their key value */ export type Project_Delete_Key_Input = { theme?: InputMaybe<Scalars['String']>; }; /** input type for inserting data into table "Project" */ export type Project_Insert_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; domain?: InputMaybe<Scalars['String']>; id?: InputMaybe<Scalars['uuid']>; name?: InputMaybe<Scalars['String']>; pages?: InputMaybe<Page_Arr_Rel_Insert_Input>; team?: InputMaybe<Team_Obj_Rel_Insert_Input>; teamId?: InputMaybe<Scalars['uuid']>; theme?: InputMaybe<Scalars['jsonb']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; user?: InputMaybe<User_Obj_Rel_Insert_Input>; userId?: InputMaybe<Scalars['uuid']>; }; /** aggregate max on columns */ export type Project_Max_Fields = { __typename?: 'Project_max_fields'; createdAt?: Maybe<Scalars['timestamptz']>; domain?: Maybe<Scalars['String']>; id?: Maybe<Scalars['uuid']>; name?: Maybe<Scalars['String']>; teamId?: Maybe<Scalars['uuid']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by max() on columns of table "Project" */ export type Project_Max_Order_By = { createdAt?: InputMaybe<Order_By>; domain?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; name?: InputMaybe<Order_By>; teamId?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type Project_Min_Fields = { __typename?: 'Project_min_fields'; createdAt?: Maybe<Scalars['timestamptz']>; domain?: Maybe<Scalars['String']>; id?: Maybe<Scalars['uuid']>; name?: Maybe<Scalars['String']>; teamId?: Maybe<Scalars['uuid']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by min() on columns of table "Project" */ export type Project_Min_Order_By = { createdAt?: InputMaybe<Order_By>; domain?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; name?: InputMaybe<Order_By>; teamId?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** response of any mutation on the table "Project" */ export type Project_Mutation_Response = { __typename?: 'Project_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<Project>; }; /** input type for inserting object relation for remote table "Project" */ export type Project_Obj_Rel_Insert_Input = { data: Project_Insert_Input; /** upsert condition */ on_conflict?: InputMaybe<Project_On_Conflict>; }; /** on_conflict condition type for table "Project" */ export type Project_On_Conflict = { constraint: Project_Constraint; update_columns?: Array<Project_Update_Column>; where?: InputMaybe<Project_Bool_Exp>; }; /** Ordering options when selecting data from "Project". */ export type Project_Order_By = { createdAt?: InputMaybe<Order_By>; domain?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; name?: InputMaybe<Order_By>; pages_aggregate?: InputMaybe<Page_Aggregate_Order_By>; team?: InputMaybe<Team_Order_By>; teamId?: InputMaybe<Order_By>; theme?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; user?: InputMaybe<User_Order_By>; userId?: InputMaybe<Order_By>; }; /** primary key columns input for table: Project */ export type Project_Pk_Columns_Input = { id: Scalars['uuid']; }; /** prepend existing jsonb value of filtered columns with new jsonb value */ export type Project_Prepend_Input = { theme?: InputMaybe<Scalars['jsonb']>; }; /** select columns of table "Project" */ export type Project_Select_Column = /** column name */ | 'createdAt' /** column name */ | 'domain' /** column name */ | 'id' /** column name */ | 'name' /** column name */ | 'teamId' /** column name */ | 'theme' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** input type for updating data in table "Project" */ export type Project_Set_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; domain?: InputMaybe<Scalars['String']>; id?: InputMaybe<Scalars['uuid']>; name?: InputMaybe<Scalars['String']>; teamId?: InputMaybe<Scalars['uuid']>; theme?: InputMaybe<Scalars['jsonb']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; userId?: InputMaybe<Scalars['uuid']>; }; /** update columns of table "Project" */ export type Project_Update_Column = /** column name */ | 'createdAt' /** column name */ | 'domain' /** column name */ | 'id' /** column name */ | 'name' /** column name */ | 'teamId' /** column name */ | 'theme' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** User's role in teams */ export type Role = { __typename?: 'Role'; comment?: Maybe<Scalars['String']>; /** An array relationship */ members: Array<Member>; /** An aggregate relationship */ members_aggregate: Member_Aggregate; value: Scalars['String']; }; /** User's role in teams */ export type RoleMembersArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; /** User's role in teams */ export type RoleMembers_AggregateArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; /** aggregated selection of "Role" */ export type Role_Aggregate = { __typename?: 'Role_aggregate'; aggregate?: Maybe<Role_Aggregate_Fields>; nodes: Array<Role>; }; /** aggregate fields of "Role" */ export type Role_Aggregate_Fields = { __typename?: 'Role_aggregate_fields'; count: Scalars['Int']; max?: Maybe<Role_Max_Fields>; min?: Maybe<Role_Min_Fields>; }; /** aggregate fields of "Role" */ export type Role_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<Role_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** Boolean expression to filter rows from the table "Role". All fields are combined with a logical 'AND'. */ export type Role_Bool_Exp = { _and?: InputMaybe<Array<Role_Bool_Exp>>; _not?: InputMaybe<Role_Bool_Exp>; _or?: InputMaybe<Array<Role_Bool_Exp>>; comment?: InputMaybe<String_Comparison_Exp>; members?: InputMaybe<Member_Bool_Exp>; value?: InputMaybe<String_Comparison_Exp>; }; /** unique or primary key constraints on table "Role" */ export type Role_Constraint = /** unique or primary key constraint */ 'Role_pkey'; export type Role_Enum = /** Manager of a team */ | 'manager' /** Normal user */ | 'user'; /** Boolean expression to compare columns of type "Role_enum". All fields are combined with logical 'AND'. */ export type Role_Enum_Comparison_Exp = { _eq?: InputMaybe<Role_Enum>; _in?: InputMaybe<Array<Role_Enum>>; _is_null?: InputMaybe<Scalars['Boolean']>; _neq?: InputMaybe<Role_Enum>; _nin?: InputMaybe<Array<Role_Enum>>; }; /** input type for inserting data into table "Role" */ export type Role_Insert_Input = { comment?: InputMaybe<Scalars['String']>; members?: InputMaybe<Member_Arr_Rel_Insert_Input>; value?: InputMaybe<Scalars['String']>; }; /** aggregate max on columns */ export type Role_Max_Fields = { __typename?: 'Role_max_fields'; comment?: Maybe<Scalars['String']>; value?: Maybe<Scalars['String']>; }; /** aggregate min on columns */ export type Role_Min_Fields = { __typename?: 'Role_min_fields'; comment?: Maybe<Scalars['String']>; value?: Maybe<Scalars['String']>; }; /** response of any mutation on the table "Role" */ export type Role_Mutation_Response = { __typename?: 'Role_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<Role>; }; /** input type for inserting object relation for remote table "Role" */ export type Role_Obj_Rel_Insert_Input = { data: Role_Insert_Input; /** upsert condition */ on_conflict?: InputMaybe<Role_On_Conflict>; }; /** on_conflict condition type for table "Role" */ export type Role_On_Conflict = { constraint: Role_Constraint; update_columns?: Array<Role_Update_Column>; where?: InputMaybe<Role_Bool_Exp>; }; /** Ordering options when selecting data from "Role". */ export type Role_Order_By = { comment?: InputMaybe<Order_By>; members_aggregate?: InputMaybe<Member_Aggregate_Order_By>; value?: InputMaybe<Order_By>; }; /** primary key columns input for table: Role */ export type Role_Pk_Columns_Input = { value: Scalars['String']; }; /** select columns of table "Role" */ export type Role_Select_Column = /** column name */ | 'comment' /** column name */ | 'value'; /** input type for updating data in table "Role" */ export type Role_Set_Input = { comment?: InputMaybe<Scalars['String']>; value?: InputMaybe<Scalars['String']>; }; /** update columns of table "Role" */ export type Role_Update_Column = /** column name */ | 'comment' /** column name */ | 'value'; /** columns and relationships of "Session" */ export type Session = { __typename?: 'Session'; createdAt: Scalars['timestamptz']; expires: Scalars['timestamptz']; id: Scalars['uuid']; sessionToken: Scalars['String']; updatedAt: Scalars['timestamptz']; /** An object relationship */ user: User; userId: Scalars['uuid']; }; /** aggregated selection of "Session" */ export type Session_Aggregate = { __typename?: 'Session_aggregate'; aggregate?: Maybe<Session_Aggregate_Fields>; nodes: Array<Session>; }; /** aggregate fields of "Session" */ export type Session_Aggregate_Fields = { __typename?: 'Session_aggregate_fields'; count: Scalars['Int']; max?: Maybe<Session_Max_Fields>; min?: Maybe<Session_Min_Fields>; }; /** aggregate fields of "Session" */ export type Session_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<Session_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "Session" */ export type Session_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<Session_Max_Order_By>; min?: InputMaybe<Session_Min_Order_By>; }; /** input type for inserting array relation for remote table "Session" */ export type Session_Arr_Rel_Insert_Input = { data: Array<Session_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<Session_On_Conflict>; }; /** Boolean expression to filter rows from the table "Session". All fields are combined with a logical 'AND'. */ export type Session_Bool_Exp = { _and?: InputMaybe<Array<Session_Bool_Exp>>; _not?: InputMaybe<Session_Bool_Exp>; _or?: InputMaybe<Array<Session_Bool_Exp>>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; expires?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; sessionToken?: InputMaybe<String_Comparison_Exp>; updatedAt?: InputMaybe<Timestamptz_Comparison_Exp>; user?: InputMaybe<User_Bool_Exp>; userId?: InputMaybe<Uuid_Comparison_Exp>; }; /** unique or primary key constraints on table "Session" */ export type Session_Constraint = /** unique or primary key constraint */ | 'Session_pkey' /** unique or primary key constraint */ | 'Session_sessionToken_key'; /** input type for inserting data into table "Session" */ export type Session_Insert_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; expires?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; sessionToken?: InputMaybe<Scalars['String']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; user?: InputMaybe<User_Obj_Rel_Insert_Input>; userId?: InputMaybe<Scalars['uuid']>; }; /** aggregate max on columns */ export type Session_Max_Fields = { __typename?: 'Session_max_fields'; createdAt?: Maybe<Scalars['timestamptz']>; expires?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; sessionToken?: Maybe<Scalars['String']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by max() on columns of table "Session" */ export type Session_Max_Order_By = { createdAt?: InputMaybe<Order_By>; expires?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; sessionToken?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type Session_Min_Fields = { __typename?: 'Session_min_fields'; createdAt?: Maybe<Scalars['timestamptz']>; expires?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; sessionToken?: Maybe<Scalars['String']>; updatedAt?: Maybe<Scalars['timestamptz']>; userId?: Maybe<Scalars['uuid']>; }; /** order by min() on columns of table "Session" */ export type Session_Min_Order_By = { createdAt?: InputMaybe<Order_By>; expires?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; sessionToken?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userId?: InputMaybe<Order_By>; }; /** response of any mutation on the table "Session" */ export type Session_Mutation_Response = { __typename?: 'Session_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<Session>; }; /** on_conflict condition type for table "Session" */ export type Session_On_Conflict = { constraint: Session_Constraint; update_columns?: Array<Session_Update_Column>; where?: InputMaybe<Session_Bool_Exp>; }; /** Ordering options when selecting data from "Session". */ export type Session_Order_By = { createdAt?: InputMaybe<Order_By>; expires?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; sessionToken?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; user?: InputMaybe<User_Order_By>; userId?: InputMaybe<Order_By>; }; /** primary key columns input for table: Session */ export type Session_Pk_Columns_Input = { id: Scalars['uuid']; }; /** select columns of table "Session" */ export type Session_Select_Column = /** column name */ | 'createdAt' /** column name */ | 'expires' /** column name */ | 'id' /** column name */ | 'sessionToken' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** input type for updating data in table "Session" */ export type Session_Set_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; expires?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; sessionToken?: InputMaybe<Scalars['String']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; userId?: InputMaybe<Scalars['uuid']>; }; /** update columns of table "Session" */ export type Session_Update_Column = /** column name */ | 'createdAt' /** column name */ | 'expires' /** column name */ | 'id' /** column name */ | 'sessionToken' /** column name */ | 'updatedAt' /** column name */ | 'userId'; /** Boolean expression to compare columns of type "String". All fields are combined with logical 'AND'. */ export type String_Comparison_Exp = { _eq?: InputMaybe<Scalars['String']>; _gt?: InputMaybe<Scalars['String']>; _gte?: InputMaybe<Scalars['String']>; /** does the column match the given case-insensitive pattern */ _ilike?: InputMaybe<Scalars['String']>; _in?: InputMaybe<Array<Scalars['String']>>; /** does the column match the given POSIX regular expression, case insensitive */ _iregex?: InputMaybe<Scalars['String']>; _is_null?: InputMaybe<Scalars['Boolean']>; /** does the column match the given pattern */ _like?: InputMaybe<Scalars['String']>; _lt?: InputMaybe<Scalars['String']>; _lte?: InputMaybe<Scalars['String']>; _neq?: InputMaybe<Scalars['String']>; /** does the column NOT match the given case-insensitive pattern */ _nilike?: InputMaybe<Scalars['String']>; _nin?: InputMaybe<Array<Scalars['String']>>; /** does the column NOT match the given POSIX regular expression, case insensitive */ _niregex?: InputMaybe<Scalars['String']>; /** does the column NOT match the given pattern */ _nlike?: InputMaybe<Scalars['String']>; /** does the column NOT match the given POSIX regular expression, case sensitive */ _nregex?: InputMaybe<Scalars['String']>; /** does the column NOT match the given SQL regular expression */ _nsimilar?: InputMaybe<Scalars['String']>; /** does the column match the given POSIX regular expression, case sensitive */ _regex?: InputMaybe<Scalars['String']>; /** does the column match the given SQL regular expression */ _similar?: InputMaybe<Scalars['String']>; }; /** columns and relationships of "Team" */ export type Team = { __typename?: 'Team'; createdAt: Scalars['timestamptz']; id: Scalars['uuid']; /** An array relationship */ members: Array<Member>; /** An aggregate relationship */ members_aggregate: Member_Aggregate; name: Scalars['String']; /** An array relationship */ projects: Array<Project>; /** An aggregate relationship */ projects_aggregate: Project_Aggregate; uid?: Maybe<Scalars['String']>; updatedAt: Scalars['timestamptz']; }; /** columns and relationships of "Team" */ export type TeamMembersArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; /** columns and relationships of "Team" */ export type TeamMembers_AggregateArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; /** columns and relationships of "Team" */ export type TeamProjectsArgs = { distinct_on?: InputMaybe<Array<Project_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Project_Order_By>>; where?: InputMaybe<Project_Bool_Exp>; }; /** columns and relationships of "Team" */ export type TeamProjects_AggregateArgs = { distinct_on?: InputMaybe<Array<Project_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Project_Order_By>>; where?: InputMaybe<Project_Bool_Exp>; }; /** aggregated selection of "Team" */ export type Team_Aggregate = { __typename?: 'Team_aggregate'; aggregate?: Maybe<Team_Aggregate_Fields>; nodes: Array<Team>; }; /** aggregate fields of "Team" */ export type Team_Aggregate_Fields = { __typename?: 'Team_aggregate_fields'; count: Scalars['Int']; max?: Maybe<Team_Max_Fields>; min?: Maybe<Team_Min_Fields>; }; /** aggregate fields of "Team" */ export type Team_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<Team_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** Boolean expression to filter rows from the table "Team". All fields are combined with a logical 'AND'. */ export type Team_Bool_Exp = { _and?: InputMaybe<Array<Team_Bool_Exp>>; _not?: InputMaybe<Team_Bool_Exp>; _or?: InputMaybe<Array<Team_Bool_Exp>>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; members?: InputMaybe<Member_Bool_Exp>; name?: InputMaybe<String_Comparison_Exp>; projects?: InputMaybe<Project_Bool_Exp>; uid?: InputMaybe<String_Comparison_Exp>; updatedAt?: InputMaybe<Timestamptz_Comparison_Exp>; }; /** unique or primary key constraints on table "Team" */ export type Team_Constraint = /** unique or primary key constraint */ | 'Team_pkey' /** unique or primary key constraint */ | 'Team_uid_key'; /** input type for inserting data into table "Team" */ export type Team_Insert_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; members?: InputMaybe<Member_Arr_Rel_Insert_Input>; name?: InputMaybe<Scalars['String']>; projects?: InputMaybe<Project_Arr_Rel_Insert_Input>; uid?: InputMaybe<Scalars['String']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; }; /** aggregate max on columns */ export type Team_Max_Fields = { __typename?: 'Team_max_fields'; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; name?: Maybe<Scalars['String']>; uid?: Maybe<Scalars['String']>; updatedAt?: Maybe<Scalars['timestamptz']>; }; /** aggregate min on columns */ export type Team_Min_Fields = { __typename?: 'Team_min_fields'; createdAt?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; name?: Maybe<Scalars['String']>; uid?: Maybe<Scalars['String']>; updatedAt?: Maybe<Scalars['timestamptz']>; }; /** response of any mutation on the table "Team" */ export type Team_Mutation_Response = { __typename?: 'Team_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<Team>; }; /** input type for inserting object relation for remote table "Team" */ export type Team_Obj_Rel_Insert_Input = { data: Team_Insert_Input; /** upsert condition */ on_conflict?: InputMaybe<Team_On_Conflict>; }; /** on_conflict condition type for table "Team" */ export type Team_On_Conflict = { constraint: Team_Constraint; update_columns?: Array<Team_Update_Column>; where?: InputMaybe<Team_Bool_Exp>; }; /** Ordering options when selecting data from "Team". */ export type Team_Order_By = { createdAt?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; members_aggregate?: InputMaybe<Member_Aggregate_Order_By>; name?: InputMaybe<Order_By>; projects_aggregate?: InputMaybe<Project_Aggregate_Order_By>; uid?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; }; /** primary key columns input for table: Team */ export type Team_Pk_Columns_Input = { id: Scalars['uuid']; }; /** select columns of table "Team" */ export type Team_Select_Column = /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'name' /** column name */ | 'uid' /** column name */ | 'updatedAt'; /** input type for updating data in table "Team" */ export type Team_Set_Input = { createdAt?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; name?: InputMaybe<Scalars['String']>; uid?: InputMaybe<Scalars['String']>; updatedAt?: InputMaybe<Scalars['timestamptz']>; }; /** update columns of table "Team" */ export type Team_Update_Column = /** column name */ | 'createdAt' /** column name */ | 'id' /** column name */ | 'name' /** column name */ | 'uid' /** column name */ | 'updatedAt'; /** columns and relationships of "User" */ export type User = { __typename?: 'User'; /** An array relationship */ accounts: Array<Account>; /** An aggregate relationship */ accounts_aggregate: Account_Aggregate; avatar?: Maybe<Scalars['String']>; bio?: Maybe<Scalars['String']>; /** An array relationship */ comments: Array<Comment>; /** An aggregate relationship */ comments_aggregate: Comment_Aggregate; createdAt: Scalars['timestamptz']; email?: Maybe<Scalars['String']>; emailVerified?: Maybe<Scalars['timestamptz']>; id: Scalars['uuid']; /** An array relationship */ likes: Array<Like>; /** An aggregate relationship */ likes_aggregate: Like_Aggregate; /** An array relationship */ members: Array<Member>; /** An aggregate relationship */ members_aggregate: Member_Aggregate; name?: Maybe<Scalars['String']>; /** An array relationship */ notificationSubscriptions: Array<NotificationSubscription>; /** An aggregate relationship */ notificationSubscriptions_aggregate: NotificationSubscription_Aggregate; /** An array relationship */ projects: Array<Project>; /** An aggregate relationship */ projects_aggregate: Project_Aggregate; /** An array relationship */ recipientNotificationMessages: Array<NotificationMessage>; /** An aggregate relationship */ recipientNotificationMessages_aggregate: NotificationMessage_Aggregate; /** An array relationship */ sessions: Array<Session>; /** An aggregate relationship */ sessions_aggregate: Session_Aggregate; /** An array relationship */ triggeredNotificationMessages: Array<NotificationMessage>; /** An aggregate relationship */ triggeredNotificationMessages_aggregate: NotificationMessage_Aggregate; twitterUserName?: Maybe<Scalars['String']>; type?: Maybe<UserType_Enum>; updatedAt: Scalars['timestamptz']; /** An object relationship */ userType?: Maybe<UserType>; username?: Maybe<Scalars['String']>; website?: Maybe<Scalars['String']>; }; /** columns and relationships of "User" */ export type UserAccountsArgs = { distinct_on?: InputMaybe<Array<Account_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Account_Order_By>>; where?: InputMaybe<Account_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserAccounts_AggregateArgs = { distinct_on?: InputMaybe<Array<Account_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Account_Order_By>>; where?: InputMaybe<Account_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserCommentsArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserComments_AggregateArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserLikesArgs = { distinct_on?: InputMaybe<Array<Like_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Like_Order_By>>; where?: InputMaybe<Like_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserLikes_AggregateArgs = { distinct_on?: InputMaybe<Array<Like_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Like_Order_By>>; where?: InputMaybe<Like_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserMembersArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserMembers_AggregateArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserNotificationSubscriptionsArgs = { distinct_on?: InputMaybe<Array<NotificationSubscription_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationSubscription_Order_By>>; where?: InputMaybe<NotificationSubscription_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserNotificationSubscriptions_AggregateArgs = { distinct_on?: InputMaybe<Array<NotificationSubscription_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationSubscription_Order_By>>; where?: InputMaybe<NotificationSubscription_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserProjectsArgs = { distinct_on?: InputMaybe<Array<Project_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Project_Order_By>>; where?: InputMaybe<Project_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserProjects_AggregateArgs = { distinct_on?: InputMaybe<Array<Project_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Project_Order_By>>; where?: InputMaybe<Project_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserRecipientNotificationMessagesArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserRecipientNotificationMessages_AggregateArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserSessionsArgs = { distinct_on?: InputMaybe<Array<Session_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Session_Order_By>>; where?: InputMaybe<Session_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserSessions_AggregateArgs = { distinct_on?: InputMaybe<Array<Session_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Session_Order_By>>; where?: InputMaybe<Session_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserTriggeredNotificationMessagesArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; /** columns and relationships of "User" */ export type UserTriggeredNotificationMessages_AggregateArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; /** columns and relationships of "UserType" */ export type UserType = { __typename?: 'UserType'; comment: Scalars['String']; /** An array relationship */ users: Array<User>; /** An aggregate relationship */ users_aggregate: User_Aggregate; value: Scalars['String']; }; /** columns and relationships of "UserType" */ export type UserTypeUsersArgs = { distinct_on?: InputMaybe<Array<User_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<User_Order_By>>; where?: InputMaybe<User_Bool_Exp>; }; /** columns and relationships of "UserType" */ export type UserTypeUsers_AggregateArgs = { distinct_on?: InputMaybe<Array<User_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<User_Order_By>>; where?: InputMaybe<User_Bool_Exp>; }; /** aggregated selection of "UserType" */ export type UserType_Aggregate = { __typename?: 'UserType_aggregate'; aggregate?: Maybe<UserType_Aggregate_Fields>; nodes: Array<UserType>; }; /** aggregate fields of "UserType" */ export type UserType_Aggregate_Fields = { __typename?: 'UserType_aggregate_fields'; count: Scalars['Int']; max?: Maybe<UserType_Max_Fields>; min?: Maybe<UserType_Min_Fields>; }; /** aggregate fields of "UserType" */ export type UserType_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<UserType_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** Boolean expression to filter rows from the table "UserType". All fields are combined with a logical 'AND'. */ export type UserType_Bool_Exp = { _and?: InputMaybe<Array<UserType_Bool_Exp>>; _not?: InputMaybe<UserType_Bool_Exp>; _or?: InputMaybe<Array<UserType_Bool_Exp>>; comment?: InputMaybe<String_Comparison_Exp>; users?: InputMaybe<User_Bool_Exp>; value?: InputMaybe<String_Comparison_Exp>; }; /** unique or primary key constraints on table "UserType" */ export type UserType_Constraint = /** unique or primary key constraint */ 'UserType_pkey'; export type UserType_Enum = /** Site administrator */ | 'admin' /** Anonymous widget vsisitor */ | 'anonymous' /** Free user */ | 'free' /** Paid user */ | 'pro'; /** Boolean expression to compare columns of type "UserType_enum". All fields are combined with logical 'AND'. */ export type UserType_Enum_Comparison_Exp = { _eq?: InputMaybe<UserType_Enum>; _in?: InputMaybe<Array<UserType_Enum>>; _is_null?: InputMaybe<Scalars['Boolean']>; _neq?: InputMaybe<UserType_Enum>; _nin?: InputMaybe<Array<UserType_Enum>>; }; /** input type for inserting data into table "UserType" */ export type UserType_Insert_Input = { comment?: InputMaybe<Scalars['String']>; users?: InputMaybe<User_Arr_Rel_Insert_Input>; value?: InputMaybe<Scalars['String']>; }; /** aggregate max on columns */ export type UserType_Max_Fields = { __typename?: 'UserType_max_fields'; comment?: Maybe<Scalars['String']>; value?: Maybe<Scalars['String']>; }; /** aggregate min on columns */ export type UserType_Min_Fields = { __typename?: 'UserType_min_fields'; comment?: Maybe<Scalars['String']>; value?: Maybe<Scalars['String']>; }; /** response of any mutation on the table "UserType" */ export type UserType_Mutation_Response = { __typename?: 'UserType_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<UserType>; }; /** input type for inserting object relation for remote table "UserType" */ export type UserType_Obj_Rel_Insert_Input = { data: UserType_Insert_Input; /** upsert condition */ on_conflict?: InputMaybe<UserType_On_Conflict>; }; /** on_conflict condition type for table "UserType" */ export type UserType_On_Conflict = { constraint: UserType_Constraint; update_columns?: Array<UserType_Update_Column>; where?: InputMaybe<UserType_Bool_Exp>; }; /** Ordering options when selecting data from "UserType". */ export type UserType_Order_By = { comment?: InputMaybe<Order_By>; users_aggregate?: InputMaybe<User_Aggregate_Order_By>; value?: InputMaybe<Order_By>; }; /** primary key columns input for table: UserType */ export type UserType_Pk_Columns_Input = { value: Scalars['String']; }; /** select columns of table "UserType" */ export type UserType_Select_Column = /** column name */ | 'comment' /** column name */ | 'value'; /** input type for updating data in table "UserType" */ export type UserType_Set_Input = { comment?: InputMaybe<Scalars['String']>; value?: InputMaybe<Scalars['String']>; }; /** update columns of table "UserType" */ export type UserType_Update_Column = /** column name */ | 'comment' /** column name */ | 'value'; /** aggregated selection of "User" */ export type User_Aggregate = { __typename?: 'User_aggregate'; aggregate?: Maybe<User_Aggregate_Fields>; nodes: Array<User>; }; /** aggregate fields of "User" */ export type User_Aggregate_Fields = { __typename?: 'User_aggregate_fields'; count: Scalars['Int']; max?: Maybe<User_Max_Fields>; min?: Maybe<User_Min_Fields>; }; /** aggregate fields of "User" */ export type User_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<User_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** order by aggregate values of table "User" */ export type User_Aggregate_Order_By = { count?: InputMaybe<Order_By>; max?: InputMaybe<User_Max_Order_By>; min?: InputMaybe<User_Min_Order_By>; }; /** input type for inserting array relation for remote table "User" */ export type User_Arr_Rel_Insert_Input = { data: Array<User_Insert_Input>; /** upsert condition */ on_conflict?: InputMaybe<User_On_Conflict>; }; /** Boolean expression to filter rows from the table "User". All fields are combined with a logical 'AND'. */ export type User_Bool_Exp = { _and?: InputMaybe<Array<User_Bool_Exp>>; _not?: InputMaybe<User_Bool_Exp>; _or?: InputMaybe<Array<User_Bool_Exp>>; accounts?: InputMaybe<Account_Bool_Exp>; avatar?: InputMaybe<String_Comparison_Exp>; bio?: InputMaybe<String_Comparison_Exp>; comments?: InputMaybe<Comment_Bool_Exp>; createdAt?: InputMaybe<Timestamptz_Comparison_Exp>; email?: InputMaybe<String_Comparison_Exp>; emailVerified?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; likes?: InputMaybe<Like_Bool_Exp>; members?: InputMaybe<Member_Bool_Exp>; name?: InputMaybe<String_Comparison_Exp>; notificationSubscriptions?: InputMaybe<NotificationSubscription_Bool_Exp>; projects?: InputMaybe<Project_Bool_Exp>; recipientNotificationMessages?: InputMaybe<NotificationMessage_Bool_Exp>; sessions?: InputMaybe<Session_Bool_Exp>; triggeredNotificationMessages?: InputMaybe<NotificationMessage_Bool_Exp>; twitterUserName?: InputMaybe<String_Comparison_Exp>; type?: InputMaybe<UserType_Enum_Comparison_Exp>; updatedAt?: InputMaybe<Timestamptz_Comparison_Exp>; userType?: InputMaybe<UserType_Bool_Exp>; username?: InputMaybe<String_Comparison_Exp>; website?: InputMaybe<String_Comparison_Exp>; }; /** unique or primary key constraints on table "User" */ export type User_Constraint = /** unique or primary key constraint */ | 'User_email_key' /** unique or primary key constraint */ | 'User_pkey' /** unique or primary key constraint */ | 'User_username_key'; /** input type for inserting data into table "User" */ export type User_Insert_Input = { accounts?: InputMaybe<Account_Arr_Rel_Insert_Input>; avatar?: InputMaybe<Scalars['String']>; bio?: InputMaybe<Scalars['String']>; comments?: InputMaybe<Comment_Arr_Rel_Insert_Input>; createdAt?: InputMaybe<Scalars['timestamptz']>; email?: InputMaybe<Scalars['String']>; emailVerified?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; likes?: InputMaybe<Like_Arr_Rel_Insert_Input>; members?: InputMaybe<Member_Arr_Rel_Insert_Input>; name?: InputMaybe<Scalars['String']>; notificationSubscriptions?: InputMaybe<NotificationSubscription_Arr_Rel_Insert_Input>; projects?: InputMaybe<Project_Arr_Rel_Insert_Input>; recipientNotificationMessages?: InputMaybe<NotificationMessage_Arr_Rel_Insert_Input>; sessions?: InputMaybe<Session_Arr_Rel_Insert_Input>; triggeredNotificationMessages?: InputMaybe<NotificationMessage_Arr_Rel_Insert_Input>; twitterUserName?: InputMaybe<Scalars['String']>; type?: InputMaybe<UserType_Enum>; updatedAt?: InputMaybe<Scalars['timestamptz']>; userType?: InputMaybe<UserType_Obj_Rel_Insert_Input>; username?: InputMaybe<Scalars['String']>; website?: InputMaybe<Scalars['String']>; }; /** aggregate max on columns */ export type User_Max_Fields = { __typename?: 'User_max_fields'; avatar?: Maybe<Scalars['String']>; bio?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['timestamptz']>; email?: Maybe<Scalars['String']>; emailVerified?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; name?: Maybe<Scalars['String']>; twitterUserName?: Maybe<Scalars['String']>; updatedAt?: Maybe<Scalars['timestamptz']>; username?: Maybe<Scalars['String']>; website?: Maybe<Scalars['String']>; }; /** order by max() on columns of table "User" */ export type User_Max_Order_By = { avatar?: InputMaybe<Order_By>; bio?: InputMaybe<Order_By>; createdAt?: InputMaybe<Order_By>; email?: InputMaybe<Order_By>; emailVerified?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; name?: InputMaybe<Order_By>; twitterUserName?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; username?: InputMaybe<Order_By>; website?: InputMaybe<Order_By>; }; /** aggregate min on columns */ export type User_Min_Fields = { __typename?: 'User_min_fields'; avatar?: Maybe<Scalars['String']>; bio?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['timestamptz']>; email?: Maybe<Scalars['String']>; emailVerified?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; name?: Maybe<Scalars['String']>; twitterUserName?: Maybe<Scalars['String']>; updatedAt?: Maybe<Scalars['timestamptz']>; username?: Maybe<Scalars['String']>; website?: Maybe<Scalars['String']>; }; /** order by min() on columns of table "User" */ export type User_Min_Order_By = { avatar?: InputMaybe<Order_By>; bio?: InputMaybe<Order_By>; createdAt?: InputMaybe<Order_By>; email?: InputMaybe<Order_By>; emailVerified?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; name?: InputMaybe<Order_By>; twitterUserName?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; username?: InputMaybe<Order_By>; website?: InputMaybe<Order_By>; }; /** response of any mutation on the table "User" */ export type User_Mutation_Response = { __typename?: 'User_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<User>; }; /** input type for inserting object relation for remote table "User" */ export type User_Obj_Rel_Insert_Input = { data: User_Insert_Input; /** upsert condition */ on_conflict?: InputMaybe<User_On_Conflict>; }; /** on_conflict condition type for table "User" */ export type User_On_Conflict = { constraint: User_Constraint; update_columns?: Array<User_Update_Column>; where?: InputMaybe<User_Bool_Exp>; }; /** Ordering options when selecting data from "User". */ export type User_Order_By = { accounts_aggregate?: InputMaybe<Account_Aggregate_Order_By>; avatar?: InputMaybe<Order_By>; bio?: InputMaybe<Order_By>; comments_aggregate?: InputMaybe<Comment_Aggregate_Order_By>; createdAt?: InputMaybe<Order_By>; email?: InputMaybe<Order_By>; emailVerified?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; likes_aggregate?: InputMaybe<Like_Aggregate_Order_By>; members_aggregate?: InputMaybe<Member_Aggregate_Order_By>; name?: InputMaybe<Order_By>; notificationSubscriptions_aggregate?: InputMaybe<NotificationSubscription_Aggregate_Order_By>; projects_aggregate?: InputMaybe<Project_Aggregate_Order_By>; recipientNotificationMessages_aggregate?: InputMaybe<NotificationMessage_Aggregate_Order_By>; sessions_aggregate?: InputMaybe<Session_Aggregate_Order_By>; triggeredNotificationMessages_aggregate?: InputMaybe<NotificationMessage_Aggregate_Order_By>; twitterUserName?: InputMaybe<Order_By>; type?: InputMaybe<Order_By>; updatedAt?: InputMaybe<Order_By>; userType?: InputMaybe<UserType_Order_By>; username?: InputMaybe<Order_By>; website?: InputMaybe<Order_By>; }; /** primary key columns input for table: User */ export type User_Pk_Columns_Input = { id: Scalars['uuid']; }; /** select columns of table "User" */ export type User_Select_Column = /** column name */ | 'avatar' /** column name */ | 'bio' /** column name */ | 'createdAt' /** column name */ | 'email' /** column name */ | 'emailVerified' /** column name */ | 'id' /** column name */ | 'name' /** column name */ | 'twitterUserName' /** column name */ | 'type' /** column name */ | 'updatedAt' /** column name */ | 'username' /** column name */ | 'website'; /** input type for updating data in table "User" */ export type User_Set_Input = { avatar?: InputMaybe<Scalars['String']>; bio?: InputMaybe<Scalars['String']>; createdAt?: InputMaybe<Scalars['timestamptz']>; email?: InputMaybe<Scalars['String']>; emailVerified?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; name?: InputMaybe<Scalars['String']>; twitterUserName?: InputMaybe<Scalars['String']>; type?: InputMaybe<UserType_Enum>; updatedAt?: InputMaybe<Scalars['timestamptz']>; username?: InputMaybe<Scalars['String']>; website?: InputMaybe<Scalars['String']>; }; /** update columns of table "User" */ export type User_Update_Column = /** column name */ | 'avatar' /** column name */ | 'bio' /** column name */ | 'createdAt' /** column name */ | 'email' /** column name */ | 'emailVerified' /** column name */ | 'id' /** column name */ | 'name' /** column name */ | 'twitterUserName' /** column name */ | 'type' /** column name */ | 'updatedAt' /** column name */ | 'username' /** column name */ | 'website'; /** columns and relationships of "VerificationToken" */ export type VerificationToken = { __typename?: 'VerificationToken'; expires: Scalars['timestamptz']; id: Scalars['uuid']; identifier: Scalars['String']; token: Scalars['String']; }; /** aggregated selection of "VerificationToken" */ export type VerificationToken_Aggregate = { __typename?: 'VerificationToken_aggregate'; aggregate?: Maybe<VerificationToken_Aggregate_Fields>; nodes: Array<VerificationToken>; }; /** aggregate fields of "VerificationToken" */ export type VerificationToken_Aggregate_Fields = { __typename?: 'VerificationToken_aggregate_fields'; count: Scalars['Int']; max?: Maybe<VerificationToken_Max_Fields>; min?: Maybe<VerificationToken_Min_Fields>; }; /** aggregate fields of "VerificationToken" */ export type VerificationToken_Aggregate_FieldsCountArgs = { columns?: InputMaybe<Array<VerificationToken_Select_Column>>; distinct?: InputMaybe<Scalars['Boolean']>; }; /** Boolean expression to filter rows from the table "VerificationToken". All fields are combined with a logical 'AND'. */ export type VerificationToken_Bool_Exp = { _and?: InputMaybe<Array<VerificationToken_Bool_Exp>>; _not?: InputMaybe<VerificationToken_Bool_Exp>; _or?: InputMaybe<Array<VerificationToken_Bool_Exp>>; expires?: InputMaybe<Timestamptz_Comparison_Exp>; id?: InputMaybe<Uuid_Comparison_Exp>; identifier?: InputMaybe<String_Comparison_Exp>; token?: InputMaybe<String_Comparison_Exp>; }; /** unique or primary key constraints on table "VerificationToken" */ export type VerificationToken_Constraint = /** unique or primary key constraint */ | 'VerificationToken_identifier_token_key' /** unique or primary key constraint */ | 'VerificationToken_pkey'; /** input type for inserting data into table "VerificationToken" */ export type VerificationToken_Insert_Input = { expires?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; identifier?: InputMaybe<Scalars['String']>; token?: InputMaybe<Scalars['String']>; }; /** aggregate max on columns */ export type VerificationToken_Max_Fields = { __typename?: 'VerificationToken_max_fields'; expires?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; identifier?: Maybe<Scalars['String']>; token?: Maybe<Scalars['String']>; }; /** aggregate min on columns */ export type VerificationToken_Min_Fields = { __typename?: 'VerificationToken_min_fields'; expires?: Maybe<Scalars['timestamptz']>; id?: Maybe<Scalars['uuid']>; identifier?: Maybe<Scalars['String']>; token?: Maybe<Scalars['String']>; }; /** response of any mutation on the table "VerificationToken" */ export type VerificationToken_Mutation_Response = { __typename?: 'VerificationToken_mutation_response'; /** number of rows affected by the mutation */ affected_rows: Scalars['Int']; /** data from the rows affected by the mutation */ returning: Array<VerificationToken>; }; /** on_conflict condition type for table "VerificationToken" */ export type VerificationToken_On_Conflict = { constraint: VerificationToken_Constraint; update_columns?: Array<VerificationToken_Update_Column>; where?: InputMaybe<VerificationToken_Bool_Exp>; }; /** Ordering options when selecting data from "VerificationToken". */ export type VerificationToken_Order_By = { expires?: InputMaybe<Order_By>; id?: InputMaybe<Order_By>; identifier?: InputMaybe<Order_By>; token?: InputMaybe<Order_By>; }; /** primary key columns input for table: VerificationToken */ export type VerificationToken_Pk_Columns_Input = { id: Scalars['uuid']; }; /** select columns of table "VerificationToken" */ export type VerificationToken_Select_Column = /** column name */ | 'expires' /** column name */ | 'id' /** column name */ | 'identifier' /** column name */ | 'token'; /** input type for updating data in table "VerificationToken" */ export type VerificationToken_Set_Input = { expires?: InputMaybe<Scalars['timestamptz']>; id?: InputMaybe<Scalars['uuid']>; identifier?: InputMaybe<Scalars['String']>; token?: InputMaybe<Scalars['String']>; }; /** update columns of table "VerificationToken" */ export type VerificationToken_Update_Column = /** column name */ | 'expires' /** column name */ | 'id' /** column name */ | 'identifier' /** column name */ | 'token'; export type Jsonb_Cast_Exp = { String?: InputMaybe<String_Comparison_Exp>; }; /** Boolean expression to compare columns of type "jsonb". All fields are combined with logical 'AND'. */ export type Jsonb_Comparison_Exp = { _cast?: InputMaybe<Jsonb_Cast_Exp>; /** is the column contained in the given json value */ _contained_in?: InputMaybe<Scalars['jsonb']>; /** does the column contain the given json value at the top level */ _contains?: InputMaybe<Scalars['jsonb']>; _eq?: InputMaybe<Scalars['jsonb']>; _gt?: InputMaybe<Scalars['jsonb']>; _gte?: InputMaybe<Scalars['jsonb']>; /** does the string exist as a top-level key in the column */ _has_key?: InputMaybe<Scalars['String']>; /** do all of these strings exist as top-level keys in the column */ _has_keys_all?: InputMaybe<Array<Scalars['String']>>; /** do any of these strings exist as top-level keys in the column */ _has_keys_any?: InputMaybe<Array<Scalars['String']>>; _in?: InputMaybe<Array<Scalars['jsonb']>>; _is_null?: InputMaybe<Scalars['Boolean']>; _lt?: InputMaybe<Scalars['jsonb']>; _lte?: InputMaybe<Scalars['jsonb']>; _neq?: InputMaybe<Scalars['jsonb']>; _nin?: InputMaybe<Array<Scalars['jsonb']>>; }; /** mutation root */ export type Mutation_Root = { __typename?: 'mutation_root'; /** delete single row from the table: "Account" */ deleteAccountByPk?: Maybe<Account>; /** delete data from the table: "Account" */ deleteAccounts?: Maybe<Account_Mutation_Response>; /** delete single row from the table: "Comment" */ deleteCommentByPk?: Maybe<Comment>; /** delete data from the table: "Comment" */ deleteComments?: Maybe<Comment_Mutation_Response>; /** delete single row from the table: "Like" */ deleteLikeByPk?: Maybe<Like>; /** delete data from the table: "Like" */ deleteLikes?: Maybe<Like_Mutation_Response>; /** delete single row from the table: "Member" */ deleteMemberByPk?: Maybe<Member>; /** delete data from the table: "Member" */ deleteMembers?: Maybe<Member_Mutation_Response>; /** delete single row from the table: "NotificationMessage" */ deleteNotificationMessageByPk?: Maybe<NotificationMessage>; /** delete data from the table: "NotificationMessage" */ deleteNotificationMessages?: Maybe<NotificationMessage_Mutation_Response>; /** delete single row from the table: "NotificationSubscription" */ deleteNotificationSubscriptionByPk?: Maybe<NotificationSubscription>; /** delete data from the table: "NotificationSubscription" */ deleteNotificationSubscriptions?: Maybe<NotificationSubscription_Mutation_Response>; /** delete single row from the table: "Page" */ deletePageByPk?: Maybe<Page>; /** delete data from the table: "Page" */ deletePages?: Maybe<Page_Mutation_Response>; /** delete single row from the table: "Project" */ deleteProjectByPk?: Maybe<Project>; /** delete data from the table: "Project" */ deleteProjects?: Maybe<Project_Mutation_Response>; /** delete single row from the table: "Role" */ deleteRoleByPk?: Maybe<Role>; /** delete data from the table: "Role" */ deleteRoles?: Maybe<Role_Mutation_Response>; /** delete single row from the table: "Session" */ deleteSessionByPk?: Maybe<Session>; /** delete data from the table: "Session" */ deleteSessions?: Maybe<Session_Mutation_Response>; /** delete single row from the table: "Team" */ deleteTeamByPk?: Maybe<Team>; /** delete data from the table: "Team" */ deleteTeams?: Maybe<Team_Mutation_Response>; /** delete single row from the table: "User" */ deleteUserByPk?: Maybe<User>; /** delete single row from the table: "UserType" */ deleteUserTypeByPk?: Maybe<UserType>; /** delete data from the table: "UserType" */ deleteUserTypes?: Maybe<UserType_Mutation_Response>; /** delete data from the table: "User" */ deleteUsers?: Maybe<User_Mutation_Response>; /** delete single row from the table: "VerificationToken" */ deleteVerificationTokenByPk?: Maybe<VerificationToken>; /** delete data from the table: "VerificationToken" */ deleteVerificationTokens?: Maybe<VerificationToken_Mutation_Response>; /** delete data from the table: "NotificationType" */ delete_NotificationType?: Maybe<NotificationType_Mutation_Response>; /** delete single row from the table: "NotificationType" */ delete_NotificationType_by_pk?: Maybe<NotificationType>; /** insert data into the table: "Account" */ insertAccounts?: Maybe<Account_Mutation_Response>; /** insert data into the table: "Comment" */ insertComments?: Maybe<Comment_Mutation_Response>; /** insert data into the table: "Like" */ insertLikes?: Maybe<Like_Mutation_Response>; /** insert data into the table: "Member" */ insertMembers?: Maybe<Member_Mutation_Response>; /** insert data into the table: "NotificationMessage" */ insertNotificationMessages?: Maybe<NotificationMessage_Mutation_Response>; /** insert data into the table: "NotificationSubscription" */ insertNotificationSubscriptions?: Maybe<NotificationSubscription_Mutation_Response>; /** insert a single row into the table: "Account" */ insertOneAccount?: Maybe<Account>; /** insert a single row into the table: "Comment" */ insertOneComment?: Maybe<Comment>; /** insert a single row into the table: "Like" */ insertOneLike?: Maybe<Like>; /** insert a single row into the table: "Member" */ insertOneMember?: Maybe<Member>; /** insert a single row into the table: "NotificationMessage" */ insertOneNotificationMessage?: Maybe<NotificationMessage>; /** insert a single row into the table: "NotificationSubscription" */ insertOneNotificationSubscription?: Maybe<NotificationSubscription>; /** insert a single row into the table: "Page" */ insertOnePage?: Maybe<Page>; /** insert a single row into the table: "Project" */ insertOneProject?: Maybe<Project>; /** insert a single row into the table: "Role" */ insertOneRole?: Maybe<Role>; /** insert a single row into the table: "Session" */ insertOneSession?: Maybe<Session>; /** insert a single row into the table: "Team" */ insertOneTeam?: Maybe<Team>; /** insert a single row into the table: "User" */ insertOneUser?: Maybe<User>; /** insert a single row into the table: "UserType" */ insertOneUserType?: Maybe<UserType>; /** insert a single row into the table: "VerificationToken" */ insertOneVerificationToken?: Maybe<VerificationToken>; /** insert data into the table: "Page" */ insertPages?: Maybe<Page_Mutation_Response>; /** insert data into the table: "Project" */ insertProjects?: Maybe<Project_Mutation_Response>; /** insert data into the table: "Role" */ insertRoles?: Maybe<Role_Mutation_Response>; /** insert data into the table: "Session" */ insertSessions?: Maybe<Session_Mutation_Response>; /** insert data into the table: "Team" */ insertTeams?: Maybe<Team_Mutation_Response>; /** insert data into the table: "UserType" */ insertUserTypes?: Maybe<UserType_Mutation_Response>; /** insert data into the table: "User" */ insertUsers?: Maybe<User_Mutation_Response>; /** insert data into the table: "VerificationToken" */ insertVerificationTokens?: Maybe<VerificationToken_Mutation_Response>; /** insert data into the table: "NotificationType" */ insert_NotificationType?: Maybe<NotificationType_Mutation_Response>; /** insert a single row into the table: "NotificationType" */ insert_NotificationType_one?: Maybe<NotificationType>; /** update single row of the table: "Account" */ updateAccountByPk?: Maybe<Account>; /** update data of the table: "Account" */ updateAccounts?: Maybe<Account_Mutation_Response>; /** update single row of the table: "Comment" */ updateCommentByPk?: Maybe<Comment>; /** update data of the table: "Comment" */ updateComments?: Maybe<Comment_Mutation_Response>; /** update single row of the table: "Like" */ updateLikeByPk?: Maybe<Like>; /** update data of the table: "Like" */ updateLikes?: Maybe<Like_Mutation_Response>; /** update single row of the table: "Member" */ updateMemberByPk?: Maybe<Member>; /** update data of the table: "Member" */ updateMembers?: Maybe<Member_Mutation_Response>; /** update single row of the table: "NotificationMessage" */ updateNotificationMessageByPk?: Maybe<NotificationMessage>; /** update data of the table: "NotificationMessage" */ updateNotificationMessages?: Maybe<NotificationMessage_Mutation_Response>; /** update single row of the table: "NotificationSubscription" */ updateNotificationSubscriptionByPk?: Maybe<NotificationSubscription>; /** update data of the table: "NotificationSubscription" */ updateNotificationSubscriptions?: Maybe<NotificationSubscription_Mutation_Response>; /** update single row of the table: "Page" */ updatePageByPk?: Maybe<Page>; /** update data of the table: "Page" */ updatePages?: Maybe<Page_Mutation_Response>; /** update single row of the table: "Project" */ updateProjectByPk?: Maybe<Project>; /** update data of the table: "Project" */ updateProjects?: Maybe<Project_Mutation_Response>; /** update single row of the table: "Role" */ updateRoleByPk?: Maybe<Role>; /** update data of the table: "Role" */ updateRoles?: Maybe<Role_Mutation_Response>; /** update single row of the table: "Session" */ updateSessionByPk?: Maybe<Session>; /** update data of the table: "Session" */ updateSessions?: Maybe<Session_Mutation_Response>; /** update single row of the table: "Team" */ updateTeamByPk?: Maybe<Team>; /** update data of the table: "Team" */ updateTeams?: Maybe<Team_Mutation_Response>; /** update single row of the table: "User" */ updateUserByPk?: Maybe<User>; /** update single row of the table: "UserType" */ updateUserTypeByPk?: Maybe<UserType>; /** update data of the table: "UserType" */ updateUserTypes?: Maybe<UserType_Mutation_Response>; /** update data of the table: "User" */ updateUsers?: Maybe<User_Mutation_Response>; /** update single row of the table: "VerificationToken" */ updateVerificationTokenByPk?: Maybe<VerificationToken>; /** update data of the table: "VerificationToken" */ updateVerificationTokens?: Maybe<VerificationToken_Mutation_Response>; /** update data of the table: "NotificationType" */ update_NotificationType?: Maybe<NotificationType_Mutation_Response>; /** update single row of the table: "NotificationType" */ update_NotificationType_by_pk?: Maybe<NotificationType>; }; /** mutation root */ export type Mutation_RootDeleteAccountByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteAccountsArgs = { where: Account_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteCommentByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteCommentsArgs = { where: Comment_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteLikeByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteLikesArgs = { where: Like_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteMemberByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteMembersArgs = { where: Member_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteNotificationMessageByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteNotificationMessagesArgs = { where: NotificationMessage_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteNotificationSubscriptionByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteNotificationSubscriptionsArgs = { where: NotificationSubscription_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeletePageByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeletePagesArgs = { where: Page_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteProjectByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteProjectsArgs = { where: Project_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteRoleByPkArgs = { value: Scalars['String']; }; /** mutation root */ export type Mutation_RootDeleteRolesArgs = { where: Role_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteSessionByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteSessionsArgs = { where: Session_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteTeamByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteTeamsArgs = { where: Team_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteUserByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteUserTypeByPkArgs = { value: Scalars['String']; }; /** mutation root */ export type Mutation_RootDeleteUserTypesArgs = { where: UserType_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteUsersArgs = { where: User_Bool_Exp; }; /** mutation root */ export type Mutation_RootDeleteVerificationTokenByPkArgs = { id: Scalars['uuid']; }; /** mutation root */ export type Mutation_RootDeleteVerificationTokensArgs = { where: VerificationToken_Bool_Exp; }; /** mutation root */ export type Mutation_RootDelete_NotificationTypeArgs = { where: NotificationType_Bool_Exp; }; /** mutation root */ export type Mutation_RootDelete_NotificationType_By_PkArgs = { value: Scalars['String']; }; /** mutation root */ export type Mutation_RootInsertAccountsArgs = { objects: Array<Account_Insert_Input>; on_conflict?: InputMaybe<Account_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertCommentsArgs = { objects: Array<Comment_Insert_Input>; on_conflict?: InputMaybe<Comment_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertLikesArgs = { objects: Array<Like_Insert_Input>; on_conflict?: InputMaybe<Like_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertMembersArgs = { objects: Array<Member_Insert_Input>; on_conflict?: InputMaybe<Member_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertNotificationMessagesArgs = { objects: Array<NotificationMessage_Insert_Input>; on_conflict?: InputMaybe<NotificationMessage_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertNotificationSubscriptionsArgs = { objects: Array<NotificationSubscription_Insert_Input>; on_conflict?: InputMaybe<NotificationSubscription_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneAccountArgs = { object: Account_Insert_Input; on_conflict?: InputMaybe<Account_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneCommentArgs = { object: Comment_Insert_Input; on_conflict?: InputMaybe<Comment_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneLikeArgs = { object: Like_Insert_Input; on_conflict?: InputMaybe<Like_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneMemberArgs = { object: Member_Insert_Input; on_conflict?: InputMaybe<Member_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneNotificationMessageArgs = { object: NotificationMessage_Insert_Input; on_conflict?: InputMaybe<NotificationMessage_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneNotificationSubscriptionArgs = { object: NotificationSubscription_Insert_Input; on_conflict?: InputMaybe<NotificationSubscription_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOnePageArgs = { object: Page_Insert_Input; on_conflict?: InputMaybe<Page_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneProjectArgs = { object: Project_Insert_Input; on_conflict?: InputMaybe<Project_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneRoleArgs = { object: Role_Insert_Input; on_conflict?: InputMaybe<Role_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneSessionArgs = { object: Session_Insert_Input; on_conflict?: InputMaybe<Session_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneTeamArgs = { object: Team_Insert_Input; on_conflict?: InputMaybe<Team_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneUserArgs = { object: User_Insert_Input; on_conflict?: InputMaybe<User_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneUserTypeArgs = { object: UserType_Insert_Input; on_conflict?: InputMaybe<UserType_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertOneVerificationTokenArgs = { object: VerificationToken_Insert_Input; on_conflict?: InputMaybe<VerificationToken_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertPagesArgs = { objects: Array<Page_Insert_Input>; on_conflict?: InputMaybe<Page_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertProjectsArgs = { objects: Array<Project_Insert_Input>; on_conflict?: InputMaybe<Project_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertRolesArgs = { objects: Array<Role_Insert_Input>; on_conflict?: InputMaybe<Role_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertSessionsArgs = { objects: Array<Session_Insert_Input>; on_conflict?: InputMaybe<Session_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertTeamsArgs = { objects: Array<Team_Insert_Input>; on_conflict?: InputMaybe<Team_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertUserTypesArgs = { objects: Array<UserType_Insert_Input>; on_conflict?: InputMaybe<UserType_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertUsersArgs = { objects: Array<User_Insert_Input>; on_conflict?: InputMaybe<User_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsertVerificationTokensArgs = { objects: Array<VerificationToken_Insert_Input>; on_conflict?: InputMaybe<VerificationToken_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsert_NotificationTypeArgs = { objects: Array<NotificationType_Insert_Input>; on_conflict?: InputMaybe<NotificationType_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsert_NotificationType_OneArgs = { object: NotificationType_Insert_Input; on_conflict?: InputMaybe<NotificationType_On_Conflict>; }; /** mutation root */ export type Mutation_RootUpdateAccountByPkArgs = { _set?: InputMaybe<Account_Set_Input>; pk_columns: Account_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateAccountsArgs = { _set?: InputMaybe<Account_Set_Input>; where: Account_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateCommentByPkArgs = { _append?: InputMaybe<Comment_Append_Input>; _delete_at_path?: InputMaybe<Comment_Delete_At_Path_Input>; _delete_elem?: InputMaybe<Comment_Delete_Elem_Input>; _delete_key?: InputMaybe<Comment_Delete_Key_Input>; _prepend?: InputMaybe<Comment_Prepend_Input>; _set?: InputMaybe<Comment_Set_Input>; pk_columns: Comment_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateCommentsArgs = { _append?: InputMaybe<Comment_Append_Input>; _delete_at_path?: InputMaybe<Comment_Delete_At_Path_Input>; _delete_elem?: InputMaybe<Comment_Delete_Elem_Input>; _delete_key?: InputMaybe<Comment_Delete_Key_Input>; _prepend?: InputMaybe<Comment_Prepend_Input>; _set?: InputMaybe<Comment_Set_Input>; where: Comment_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateLikeByPkArgs = { _set?: InputMaybe<Like_Set_Input>; pk_columns: Like_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateLikesArgs = { _set?: InputMaybe<Like_Set_Input>; where: Like_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateMemberByPkArgs = { _set?: InputMaybe<Member_Set_Input>; pk_columns: Member_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateMembersArgs = { _set?: InputMaybe<Member_Set_Input>; where: Member_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateNotificationMessageByPkArgs = { _set?: InputMaybe<NotificationMessage_Set_Input>; pk_columns: NotificationMessage_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateNotificationMessagesArgs = { _set?: InputMaybe<NotificationMessage_Set_Input>; where: NotificationMessage_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateNotificationSubscriptionByPkArgs = { _append?: InputMaybe<NotificationSubscription_Append_Input>; _delete_at_path?: InputMaybe<NotificationSubscription_Delete_At_Path_Input>; _delete_elem?: InputMaybe<NotificationSubscription_Delete_Elem_Input>; _delete_key?: InputMaybe<NotificationSubscription_Delete_Key_Input>; _prepend?: InputMaybe<NotificationSubscription_Prepend_Input>; _set?: InputMaybe<NotificationSubscription_Set_Input>; pk_columns: NotificationSubscription_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateNotificationSubscriptionsArgs = { _append?: InputMaybe<NotificationSubscription_Append_Input>; _delete_at_path?: InputMaybe<NotificationSubscription_Delete_At_Path_Input>; _delete_elem?: InputMaybe<NotificationSubscription_Delete_Elem_Input>; _delete_key?: InputMaybe<NotificationSubscription_Delete_Key_Input>; _prepend?: InputMaybe<NotificationSubscription_Prepend_Input>; _set?: InputMaybe<NotificationSubscription_Set_Input>; where: NotificationSubscription_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdatePageByPkArgs = { _set?: InputMaybe<Page_Set_Input>; pk_columns: Page_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdatePagesArgs = { _set?: InputMaybe<Page_Set_Input>; where: Page_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateProjectByPkArgs = { _append?: InputMaybe<Project_Append_Input>; _delete_at_path?: InputMaybe<Project_Delete_At_Path_Input>; _delete_elem?: InputMaybe<Project_Delete_Elem_Input>; _delete_key?: InputMaybe<Project_Delete_Key_Input>; _prepend?: InputMaybe<Project_Prepend_Input>; _set?: InputMaybe<Project_Set_Input>; pk_columns: Project_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateProjectsArgs = { _append?: InputMaybe<Project_Append_Input>; _delete_at_path?: InputMaybe<Project_Delete_At_Path_Input>; _delete_elem?: InputMaybe<Project_Delete_Elem_Input>; _delete_key?: InputMaybe<Project_Delete_Key_Input>; _prepend?: InputMaybe<Project_Prepend_Input>; _set?: InputMaybe<Project_Set_Input>; where: Project_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateRoleByPkArgs = { _set?: InputMaybe<Role_Set_Input>; pk_columns: Role_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateRolesArgs = { _set?: InputMaybe<Role_Set_Input>; where: Role_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateSessionByPkArgs = { _set?: InputMaybe<Session_Set_Input>; pk_columns: Session_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateSessionsArgs = { _set?: InputMaybe<Session_Set_Input>; where: Session_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateTeamByPkArgs = { _set?: InputMaybe<Team_Set_Input>; pk_columns: Team_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateTeamsArgs = { _set?: InputMaybe<Team_Set_Input>; where: Team_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateUserByPkArgs = { _set?: InputMaybe<User_Set_Input>; pk_columns: User_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateUserTypeByPkArgs = { _set?: InputMaybe<UserType_Set_Input>; pk_columns: UserType_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateUserTypesArgs = { _set?: InputMaybe<UserType_Set_Input>; where: UserType_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateUsersArgs = { _set?: InputMaybe<User_Set_Input>; where: User_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdateVerificationTokenByPkArgs = { _set?: InputMaybe<VerificationToken_Set_Input>; pk_columns: VerificationToken_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdateVerificationTokensArgs = { _set?: InputMaybe<VerificationToken_Set_Input>; where: VerificationToken_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdate_NotificationTypeArgs = { _set?: InputMaybe<NotificationType_Set_Input>; where: NotificationType_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdate_NotificationType_By_PkArgs = { _set?: InputMaybe<NotificationType_Set_Input>; pk_columns: NotificationType_Pk_Columns_Input; }; /** column ordering options */ export type Order_By = /** in ascending order, nulls last */ | 'asc' /** in ascending order, nulls first */ | 'asc_nulls_first' /** in ascending order, nulls last */ | 'asc_nulls_last' /** in descending order, nulls first */ | 'desc' /** in descending order, nulls first */ | 'desc_nulls_first' /** in descending order, nulls last */ | 'desc_nulls_last'; export type Query_Root = { __typename?: 'query_root'; /** fetch data from the table: "NotificationType" */ NotificationType: Array<NotificationType>; /** fetch aggregated fields from the table: "NotificationType" */ NotificationType_aggregate: NotificationType_Aggregate; /** fetch data from the table: "NotificationType" using primary key columns */ NotificationType_by_pk?: Maybe<NotificationType>; /** fetch aggregated fields from the table: "Account" */ accountAggregate: Account_Aggregate; /** fetch data from the table: "Account" using primary key columns */ accountByPk?: Maybe<Account>; /** An array relationship */ accounts: Array<Account>; /** fetch aggregated fields from the table: "Comment" */ commentAggregate: Comment_Aggregate; /** fetch data from the table: "Comment" using primary key columns */ commentByPk?: Maybe<Comment>; /** An array relationship */ comments: Array<Comment>; /** fetch aggregated fields from the table: "Like" */ likeAggregate: Like_Aggregate; /** fetch data from the table: "Like" using primary key columns */ likeByPk?: Maybe<Like>; /** An array relationship */ likes: Array<Like>; /** fetch aggregated fields from the table: "Member" */ memberAggregate: Member_Aggregate; /** fetch data from the table: "Member" using primary key columns */ memberByPk?: Maybe<Member>; /** An array relationship */ members: Array<Member>; /** An array relationship */ notificationMessages: Array<NotificationMessage>; /** fetch aggregated fields from the table: "NotificationMessage" */ notificationMessagesAggregate: NotificationMessage_Aggregate; /** fetch data from the table: "NotificationMessage" using primary key columns */ notificationMessagesByPk?: Maybe<NotificationMessage>; /** fetch aggregated fields from the table: "NotificationSubscription" */ notificationSubscriptionAggregate: NotificationSubscription_Aggregate; /** fetch data from the table: "NotificationSubscription" using primary key columns */ notificationSubscriptionByPk?: Maybe<NotificationSubscription>; /** An array relationship */ notificationSubscriptions: Array<NotificationSubscription>; /** fetch aggregated fields from the table: "Page" */ pageAggregate: Page_Aggregate; /** fetch data from the table: "Page" using primary key columns */ pageByPk?: Maybe<Page>; /** An array relationship */ pages: Array<Page>; /** fetch aggregated fields from the table: "Project" */ projectAggregate: Project_Aggregate; /** fetch data from the table: "Project" using primary key columns */ projectByPk?: Maybe<Project>; /** An array relationship */ projects: Array<Project>; /** fetch aggregated fields from the table: "Role" */ roleAggregate: Role_Aggregate; /** fetch data from the table: "Role" using primary key columns */ roleByPk?: Maybe<Role>; /** fetch data from the table: "Role" */ roles: Array<Role>; /** fetch aggregated fields from the table: "Session" */ sessionAggregate: Session_Aggregate; /** fetch data from the table: "Session" using primary key columns */ sessionByPk?: Maybe<Session>; /** An array relationship */ sessions: Array<Session>; /** fetch aggregated fields from the table: "Team" */ teamAggregate: Team_Aggregate; /** fetch data from the table: "Team" using primary key columns */ teamByPk?: Maybe<Team>; /** fetch data from the table: "Team" */ teams: Array<Team>; /** fetch aggregated fields from the table: "User" */ userAggregate: User_Aggregate; /** fetch data from the table: "User" using primary key columns */ userByPk?: Maybe<User>; /** fetch aggregated fields from the table: "UserType" */ userTypeAggregate: UserType_Aggregate; /** fetch data from the table: "UserType" using primary key columns */ userTypeByPk?: Maybe<UserType>; /** fetch data from the table: "UserType" */ userTypes: Array<UserType>; /** An array relationship */ users: Array<User>; /** fetch aggregated fields from the table: "VerificationToken" */ verificationTokenAggregate: VerificationToken_Aggregate; /** fetch data from the table: "VerificationToken" using primary key columns */ verificationTokenByPk?: Maybe<VerificationToken>; /** fetch data from the table: "VerificationToken" */ verificationTokens: Array<VerificationToken>; }; export type Query_RootNotificationTypeArgs = { distinct_on?: InputMaybe<Array<NotificationType_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationType_Order_By>>; where?: InputMaybe<NotificationType_Bool_Exp>; }; export type Query_RootNotificationType_AggregateArgs = { distinct_on?: InputMaybe<Array<NotificationType_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationType_Order_By>>; where?: InputMaybe<NotificationType_Bool_Exp>; }; export type Query_RootNotificationType_By_PkArgs = { value: Scalars['String']; }; export type Query_RootAccountAggregateArgs = { distinct_on?: InputMaybe<Array<Account_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Account_Order_By>>; where?: InputMaybe<Account_Bool_Exp>; }; export type Query_RootAccountByPkArgs = { id: Scalars['uuid']; }; export type Query_RootAccountsArgs = { distinct_on?: InputMaybe<Array<Account_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Account_Order_By>>; where?: InputMaybe<Account_Bool_Exp>; }; export type Query_RootCommentAggregateArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; export type Query_RootCommentByPkArgs = { id: Scalars['uuid']; }; export type Query_RootCommentsArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; export type Query_RootLikeAggregateArgs = { distinct_on?: InputMaybe<Array<Like_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Like_Order_By>>; where?: InputMaybe<Like_Bool_Exp>; }; export type Query_RootLikeByPkArgs = { id: Scalars['uuid']; }; export type Query_RootLikesArgs = { distinct_on?: InputMaybe<Array<Like_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Like_Order_By>>; where?: InputMaybe<Like_Bool_Exp>; }; export type Query_RootMemberAggregateArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; export type Query_RootMemberByPkArgs = { id: Scalars['uuid']; }; export type Query_RootMembersArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; export type Query_RootNotificationMessagesArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; export type Query_RootNotificationMessagesAggregateArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; export type Query_RootNotificationMessagesByPkArgs = { id: Scalars['uuid']; }; export type Query_RootNotificationSubscriptionAggregateArgs = { distinct_on?: InputMaybe<Array<NotificationSubscription_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationSubscription_Order_By>>; where?: InputMaybe<NotificationSubscription_Bool_Exp>; }; export type Query_RootNotificationSubscriptionByPkArgs = { id: Scalars['uuid']; }; export type Query_RootNotificationSubscriptionsArgs = { distinct_on?: InputMaybe<Array<NotificationSubscription_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationSubscription_Order_By>>; where?: InputMaybe<NotificationSubscription_Bool_Exp>; }; export type Query_RootPageAggregateArgs = { distinct_on?: InputMaybe<Array<Page_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Page_Order_By>>; where?: InputMaybe<Page_Bool_Exp>; }; export type Query_RootPageByPkArgs = { id: Scalars['uuid']; }; export type Query_RootPagesArgs = { distinct_on?: InputMaybe<Array<Page_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Page_Order_By>>; where?: InputMaybe<Page_Bool_Exp>; }; export type Query_RootProjectAggregateArgs = { distinct_on?: InputMaybe<Array<Project_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Project_Order_By>>; where?: InputMaybe<Project_Bool_Exp>; }; export type Query_RootProjectByPkArgs = { id: Scalars['uuid']; }; export type Query_RootProjectsArgs = { distinct_on?: InputMaybe<Array<Project_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Project_Order_By>>; where?: InputMaybe<Project_Bool_Exp>; }; export type Query_RootRoleAggregateArgs = { distinct_on?: InputMaybe<Array<Role_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Role_Order_By>>; where?: InputMaybe<Role_Bool_Exp>; }; export type Query_RootRoleByPkArgs = { value: Scalars['String']; }; export type Query_RootRolesArgs = { distinct_on?: InputMaybe<Array<Role_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Role_Order_By>>; where?: InputMaybe<Role_Bool_Exp>; }; export type Query_RootSessionAggregateArgs = { distinct_on?: InputMaybe<Array<Session_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Session_Order_By>>; where?: InputMaybe<Session_Bool_Exp>; }; export type Query_RootSessionByPkArgs = { id: Scalars['uuid']; }; export type Query_RootSessionsArgs = { distinct_on?: InputMaybe<Array<Session_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Session_Order_By>>; where?: InputMaybe<Session_Bool_Exp>; }; export type Query_RootTeamAggregateArgs = { distinct_on?: InputMaybe<Array<Team_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Team_Order_By>>; where?: InputMaybe<Team_Bool_Exp>; }; export type Query_RootTeamByPkArgs = { id: Scalars['uuid']; }; export type Query_RootTeamsArgs = { distinct_on?: InputMaybe<Array<Team_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Team_Order_By>>; where?: InputMaybe<Team_Bool_Exp>; }; export type Query_RootUserAggregateArgs = { distinct_on?: InputMaybe<Array<User_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<User_Order_By>>; where?: InputMaybe<User_Bool_Exp>; }; export type Query_RootUserByPkArgs = { id: Scalars['uuid']; }; export type Query_RootUserTypeAggregateArgs = { distinct_on?: InputMaybe<Array<UserType_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<UserType_Order_By>>; where?: InputMaybe<UserType_Bool_Exp>; }; export type Query_RootUserTypeByPkArgs = { value: Scalars['String']; }; export type Query_RootUserTypesArgs = { distinct_on?: InputMaybe<Array<UserType_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<UserType_Order_By>>; where?: InputMaybe<UserType_Bool_Exp>; }; export type Query_RootUsersArgs = { distinct_on?: InputMaybe<Array<User_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<User_Order_By>>; where?: InputMaybe<User_Bool_Exp>; }; export type Query_RootVerificationTokenAggregateArgs = { distinct_on?: InputMaybe<Array<VerificationToken_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<VerificationToken_Order_By>>; where?: InputMaybe<VerificationToken_Bool_Exp>; }; export type Query_RootVerificationTokenByPkArgs = { id: Scalars['uuid']; }; export type Query_RootVerificationTokensArgs = { distinct_on?: InputMaybe<Array<VerificationToken_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<VerificationToken_Order_By>>; where?: InputMaybe<VerificationToken_Bool_Exp>; }; export type Subscription_Root = { __typename?: 'subscription_root'; /** fetch data from the table: "NotificationType" */ NotificationType: Array<NotificationType>; /** fetch aggregated fields from the table: "NotificationType" */ NotificationType_aggregate: NotificationType_Aggregate; /** fetch data from the table: "NotificationType" using primary key columns */ NotificationType_by_pk?: Maybe<NotificationType>; /** fetch aggregated fields from the table: "Account" */ accountAggregate: Account_Aggregate; /** fetch data from the table: "Account" using primary key columns */ accountByPk?: Maybe<Account>; /** An array relationship */ accounts: Array<Account>; /** fetch aggregated fields from the table: "Comment" */ commentAggregate: Comment_Aggregate; /** fetch data from the table: "Comment" using primary key columns */ commentByPk?: Maybe<Comment>; /** An array relationship */ comments: Array<Comment>; /** fetch aggregated fields from the table: "Like" */ likeAggregate: Like_Aggregate; /** fetch data from the table: "Like" using primary key columns */ likeByPk?: Maybe<Like>; /** An array relationship */ likes: Array<Like>; /** fetch aggregated fields from the table: "Member" */ memberAggregate: Member_Aggregate; /** fetch data from the table: "Member" using primary key columns */ memberByPk?: Maybe<Member>; /** An array relationship */ members: Array<Member>; /** An array relationship */ notificationMessages: Array<NotificationMessage>; /** fetch aggregated fields from the table: "NotificationMessage" */ notificationMessagesAggregate: NotificationMessage_Aggregate; /** fetch data from the table: "NotificationMessage" using primary key columns */ notificationMessagesByPk?: Maybe<NotificationMessage>; /** fetch aggregated fields from the table: "NotificationSubscription" */ notificationSubscriptionAggregate: NotificationSubscription_Aggregate; /** fetch data from the table: "NotificationSubscription" using primary key columns */ notificationSubscriptionByPk?: Maybe<NotificationSubscription>; /** An array relationship */ notificationSubscriptions: Array<NotificationSubscription>; /** fetch aggregated fields from the table: "Page" */ pageAggregate: Page_Aggregate; /** fetch data from the table: "Page" using primary key columns */ pageByPk?: Maybe<Page>; /** An array relationship */ pages: Array<Page>; /** fetch aggregated fields from the table: "Project" */ projectAggregate: Project_Aggregate; /** fetch data from the table: "Project" using primary key columns */ projectByPk?: Maybe<Project>; /** An array relationship */ projects: Array<Project>; /** fetch aggregated fields from the table: "Role" */ roleAggregate: Role_Aggregate; /** fetch data from the table: "Role" using primary key columns */ roleByPk?: Maybe<Role>; /** fetch data from the table: "Role" */ roles: Array<Role>; /** fetch aggregated fields from the table: "Session" */ sessionAggregate: Session_Aggregate; /** fetch data from the table: "Session" using primary key columns */ sessionByPk?: Maybe<Session>; /** An array relationship */ sessions: Array<Session>; /** fetch aggregated fields from the table: "Team" */ teamAggregate: Team_Aggregate; /** fetch data from the table: "Team" using primary key columns */ teamByPk?: Maybe<Team>; /** fetch data from the table: "Team" */ teams: Array<Team>; /** fetch aggregated fields from the table: "User" */ userAggregate: User_Aggregate; /** fetch data from the table: "User" using primary key columns */ userByPk?: Maybe<User>; /** fetch aggregated fields from the table: "UserType" */ userTypeAggregate: UserType_Aggregate; /** fetch data from the table: "UserType" using primary key columns */ userTypeByPk?: Maybe<UserType>; /** fetch data from the table: "UserType" */ userTypes: Array<UserType>; /** An array relationship */ users: Array<User>; /** fetch aggregated fields from the table: "VerificationToken" */ verificationTokenAggregate: VerificationToken_Aggregate; /** fetch data from the table: "VerificationToken" using primary key columns */ verificationTokenByPk?: Maybe<VerificationToken>; /** fetch data from the table: "VerificationToken" */ verificationTokens: Array<VerificationToken>; }; export type Subscription_RootNotificationTypeArgs = { distinct_on?: InputMaybe<Array<NotificationType_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationType_Order_By>>; where?: InputMaybe<NotificationType_Bool_Exp>; }; export type Subscription_RootNotificationType_AggregateArgs = { distinct_on?: InputMaybe<Array<NotificationType_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationType_Order_By>>; where?: InputMaybe<NotificationType_Bool_Exp>; }; export type Subscription_RootNotificationType_By_PkArgs = { value: Scalars['String']; }; export type Subscription_RootAccountAggregateArgs = { distinct_on?: InputMaybe<Array<Account_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Account_Order_By>>; where?: InputMaybe<Account_Bool_Exp>; }; export type Subscription_RootAccountByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootAccountsArgs = { distinct_on?: InputMaybe<Array<Account_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Account_Order_By>>; where?: InputMaybe<Account_Bool_Exp>; }; export type Subscription_RootCommentAggregateArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; export type Subscription_RootCommentByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootCommentsArgs = { distinct_on?: InputMaybe<Array<Comment_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Comment_Order_By>>; where?: InputMaybe<Comment_Bool_Exp>; }; export type Subscription_RootLikeAggregateArgs = { distinct_on?: InputMaybe<Array<Like_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Like_Order_By>>; where?: InputMaybe<Like_Bool_Exp>; }; export type Subscription_RootLikeByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootLikesArgs = { distinct_on?: InputMaybe<Array<Like_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Like_Order_By>>; where?: InputMaybe<Like_Bool_Exp>; }; export type Subscription_RootMemberAggregateArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; export type Subscription_RootMemberByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootMembersArgs = { distinct_on?: InputMaybe<Array<Member_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Member_Order_By>>; where?: InputMaybe<Member_Bool_Exp>; }; export type Subscription_RootNotificationMessagesArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; export type Subscription_RootNotificationMessagesAggregateArgs = { distinct_on?: InputMaybe<Array<NotificationMessage_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationMessage_Order_By>>; where?: InputMaybe<NotificationMessage_Bool_Exp>; }; export type Subscription_RootNotificationMessagesByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootNotificationSubscriptionAggregateArgs = { distinct_on?: InputMaybe<Array<NotificationSubscription_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationSubscription_Order_By>>; where?: InputMaybe<NotificationSubscription_Bool_Exp>; }; export type Subscription_RootNotificationSubscriptionByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootNotificationSubscriptionsArgs = { distinct_on?: InputMaybe<Array<NotificationSubscription_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<NotificationSubscription_Order_By>>; where?: InputMaybe<NotificationSubscription_Bool_Exp>; }; export type Subscription_RootPageAggregateArgs = { distinct_on?: InputMaybe<Array<Page_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Page_Order_By>>; where?: InputMaybe<Page_Bool_Exp>; }; export type Subscription_RootPageByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootPagesArgs = { distinct_on?: InputMaybe<Array<Page_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Page_Order_By>>; where?: InputMaybe<Page_Bool_Exp>; }; export type Subscription_RootProjectAggregateArgs = { distinct_on?: InputMaybe<Array<Project_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Project_Order_By>>; where?: InputMaybe<Project_Bool_Exp>; }; export type Subscription_RootProjectByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootProjectsArgs = { distinct_on?: InputMaybe<Array<Project_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Project_Order_By>>; where?: InputMaybe<Project_Bool_Exp>; }; export type Subscription_RootRoleAggregateArgs = { distinct_on?: InputMaybe<Array<Role_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Role_Order_By>>; where?: InputMaybe<Role_Bool_Exp>; }; export type Subscription_RootRoleByPkArgs = { value: Scalars['String']; }; export type Subscription_RootRolesArgs = { distinct_on?: InputMaybe<Array<Role_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Role_Order_By>>; where?: InputMaybe<Role_Bool_Exp>; }; export type Subscription_RootSessionAggregateArgs = { distinct_on?: InputMaybe<Array<Session_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Session_Order_By>>; where?: InputMaybe<Session_Bool_Exp>; }; export type Subscription_RootSessionByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootSessionsArgs = { distinct_on?: InputMaybe<Array<Session_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Session_Order_By>>; where?: InputMaybe<Session_Bool_Exp>; }; export type Subscription_RootTeamAggregateArgs = { distinct_on?: InputMaybe<Array<Team_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Team_Order_By>>; where?: InputMaybe<Team_Bool_Exp>; }; export type Subscription_RootTeamByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootTeamsArgs = { distinct_on?: InputMaybe<Array<Team_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<Team_Order_By>>; where?: InputMaybe<Team_Bool_Exp>; }; export type Subscription_RootUserAggregateArgs = { distinct_on?: InputMaybe<Array<User_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<User_Order_By>>; where?: InputMaybe<User_Bool_Exp>; }; export type Subscription_RootUserByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootUserTypeAggregateArgs = { distinct_on?: InputMaybe<Array<UserType_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<UserType_Order_By>>; where?: InputMaybe<UserType_Bool_Exp>; }; export type Subscription_RootUserTypeByPkArgs = { value: Scalars['String']; }; export type Subscription_RootUserTypesArgs = { distinct_on?: InputMaybe<Array<UserType_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<UserType_Order_By>>; where?: InputMaybe<UserType_Bool_Exp>; }; export type Subscription_RootUsersArgs = { distinct_on?: InputMaybe<Array<User_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<User_Order_By>>; where?: InputMaybe<User_Bool_Exp>; }; export type Subscription_RootVerificationTokenAggregateArgs = { distinct_on?: InputMaybe<Array<VerificationToken_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<VerificationToken_Order_By>>; where?: InputMaybe<VerificationToken_Bool_Exp>; }; export type Subscription_RootVerificationTokenByPkArgs = { id: Scalars['uuid']; }; export type Subscription_RootVerificationTokensArgs = { distinct_on?: InputMaybe<Array<VerificationToken_Select_Column>>; limit?: InputMaybe<Scalars['Int']>; offset?: InputMaybe<Scalars['Int']>; order_by?: InputMaybe<Array<VerificationToken_Order_By>>; where?: InputMaybe<VerificationToken_Bool_Exp>; }; /** Boolean expression to compare columns of type "timestamptz". All fields are combined with logical 'AND'. */ export type Timestamptz_Comparison_Exp = { _eq?: InputMaybe<Scalars['timestamptz']>; _gt?: InputMaybe<Scalars['timestamptz']>; _gte?: InputMaybe<Scalars['timestamptz']>; _in?: InputMaybe<Array<Scalars['timestamptz']>>; _is_null?: InputMaybe<Scalars['Boolean']>; _lt?: InputMaybe<Scalars['timestamptz']>; _lte?: InputMaybe<Scalars['timestamptz']>; _neq?: InputMaybe<Scalars['timestamptz']>; _nin?: InputMaybe<Array<Scalars['timestamptz']>>; }; /** Boolean expression to compare columns of type "uuid". All fields are combined with logical 'AND'. */ export type Uuid_Comparison_Exp = { _eq?: InputMaybe<Scalars['uuid']>; _gt?: InputMaybe<Scalars['uuid']>; _gte?: InputMaybe<Scalars['uuid']>; _in?: InputMaybe<Array<Scalars['uuid']>>; _is_null?: InputMaybe<Scalars['Boolean']>; _lt?: InputMaybe<Scalars['uuid']>; _lte?: InputMaybe<Scalars['uuid']>; _neq?: InputMaybe<Scalars['uuid']>; _nin?: InputMaybe<Array<Scalars['uuid']>>; };
the_stack
import crypto from "crypto"; import { FiatTokenV2Instance } from "../../../@types/generated"; import { AuthorizationUsed, Transfer, } from "../../../@types/generated/FiatTokenV2"; import { ACCOUNTS_AND_KEYS, MAX_UINT256 } from "../../helpers/constants"; import { expectRevert, hexStringFromBuffer } from "../../helpers"; import { receiveWithAuthorizationTypeHash, signReceiveAuthorization, TestParams, } from "./helpers"; export function testReceiveWithAuthorization({ getFiatToken, getDomainSeparator, fiatTokenOwner, accounts, }: TestParams): void { describe("receiveWithAuthorization", () => { let fiatToken: FiatTokenV2Instance; let domainSeparator: string; const [alice, charlie] = ACCOUNTS_AND_KEYS; const [, bob, david] = accounts; let nonce: string; const initialBalance = 10e6; const receiveParams = { from: alice.address, to: bob, value: 7e6, validAfter: 0, validBefore: MAX_UINT256, }; beforeEach(async () => { fiatToken = getFiatToken(); domainSeparator = getDomainSeparator(); nonce = hexStringFromBuffer(crypto.randomBytes(32)); await fiatToken.configureMinter(fiatTokenOwner, 1000000e6, { from: fiatTokenOwner, }); await fiatToken.mint(receiveParams.from, initialBalance, { from: fiatTokenOwner, }); }); it("has the expected type hash", async () => { expect(await fiatToken.RECEIVE_WITH_AUTHORIZATION_TYPEHASH()).to.equal( receiveWithAuthorizationTypeHash ); }); it("executes a transfer when a valid authorization is given and the caller is the payee", async () => { const { from, to, value, validAfter, validBefore } = receiveParams; // create an authorization to transfer money from Alice to Bob and sign // with Alice's key const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // check initial balance expect((await fiatToken.balanceOf(from)).toNumber()).to.equal(10e6); expect((await fiatToken.balanceOf(to)).toNumber()).to.equal(0); // check that the authorization state is false expect(await fiatToken.authorizationState(from, nonce)).to.equal(false); // The recipient (Bob) submits the signed authorization const result = await fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: bob } ); // check that balance is updated expect((await fiatToken.balanceOf(from)).toNumber()).to.equal( initialBalance - value ); expect((await fiatToken.balanceOf(to)).toNumber()).to.equal(value); // check that AuthorizationUsed event is emitted const log0 = result.logs[0] as Truffle.TransactionLog<AuthorizationUsed>; expect(log0.event).to.equal("AuthorizationUsed"); expect(log0.args[0]).to.equal(from); expect(log0.args[1]).to.equal(nonce); // check that Transfer event is emitted const log1 = result.logs[1] as Truffle.TransactionLog<Transfer>; expect(log1.event).to.equal("Transfer"); expect(log1.args[0]).to.equal(from); expect(log1.args[1]).to.equal(to); expect(log1.args[2].toNumber()).to.equal(value); // check that the authorization state is now true expect(await fiatToken.authorizationState(from, nonce)).to.equal(true); }); it("reverts if the caller is not the payee", async () => { const { from, to, value, validAfter, validBefore } = receiveParams; // create a signed authorization const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // submit the signed authorization from await expectRevert( fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: david } ), "caller must be the payee" ); }); it("reverts if the signature does not match given parameters", async () => { const { from, to, value, validAfter, validBefore } = receiveParams; // create a signed authorization const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // try to cheat by claiming the transfer amount is double await expectRevert( fiatToken.receiveWithAuthorization( from, to, value * 2, // pass incorrect value validAfter, validBefore, nonce, v, r, s, { from: bob } ), "invalid signature" ); }); it("reverts if the signature is not signed with the right key", async () => { const { from, to, value, validAfter, validBefore } = receiveParams; // create an authorization to transfer money from Alice to Bob, but // sign with Bob's key instead of Alice's const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, charlie.key ); // try to cheat by submitting the signed authorization that is signed by // a wrong person await expectRevert( fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: bob } ), "invalid signature" ); }); it("reverts if the authorization is not yet valid", async () => { const { from, to, value, validBefore } = receiveParams; // create a signed authorization that won't be valid until 10 seconds // later const validAfter = Math.floor(Date.now() / 1000) + 10; const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // try to submit the authorization early await expectRevert( fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: bob } ), "authorization is not yet valid" ); }); it("reverts if the authorization is expired", async () => { // create a signed authorization that expires immediately const { from, to, value, validAfter } = receiveParams; const validBefore = Math.floor(Date.now() / 1000); const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // try to submit the authorization that is expired await expectRevert( fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: bob } ), "authorization is expired" ); }); it("reverts if the authorization has already been used", async () => { const { from, to, validAfter, validBefore } = receiveParams; // create a signed authorization const value = 1e6; const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // submit the authorization await fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: bob } ); // try to submit the authorization again await expectRevert( fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: bob } ), "authorization is used or canceled" ); }); it("reverts if the authorization has a nonce that has already been used by the signer", async () => { const { from, to, value, validAfter, validBefore } = receiveParams; // create a signed authorization const authorization = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // submit the authorization await fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, authorization.v, authorization.r, authorization.s, { from: bob } ); // create another authorization with the same nonce, but with different // parameters const authorization2 = signReceiveAuthorization( from, to, 1e6, validAfter, validBefore, nonce, domainSeparator, alice.key ); // try to submit the authorization again await expectRevert( fiatToken.receiveWithAuthorization( from, to, 1e6, validAfter, validBefore, nonce, authorization2.v, authorization2.r, authorization2.s, { from: bob } ), "authorization is used or canceled" ); }); it("reverts if the authorization includes invalid transfer parameters", async () => { const { from, to, validAfter, validBefore } = receiveParams; // create a signed authorization that attempts to transfer an amount // that exceeds the sender's balance const value = initialBalance + 1; const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // try to submit the authorization with invalid transfer parameters await expectRevert( fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: bob } ), "transfer amount exceeds balance" ); }); it("reverts if the contract is paused", async () => { const { from, to, value, validAfter, validBefore } = receiveParams; // create a signed authorization const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // pause the contract await fiatToken.pause({ from: fiatTokenOwner }); // try to submit the authorization await expectRevert( fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: bob } ), "paused" ); }); it("reverts if the payer or the payee is blacklisted", async () => { const { from, to, value, validAfter, validBefore } = receiveParams; // create a signed authorization const { v, r, s } = signReceiveAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // payer is blacklisted await fiatToken.blacklist(from, { from: fiatTokenOwner }); const submitTx = () => fiatToken.receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s, { from: bob } ); // try to submit the authorization await expectRevert(submitTx(), "account is blacklisted"); // payee is blacklisted await fiatToken.unBlacklist(from, { from: fiatTokenOwner }); await fiatToken.blacklist(to, { from: fiatTokenOwner }); // try to submit the authorization await expectRevert(submitTx(), "account is blacklisted"); }); }); }
the_stack
import React, { Component } from 'react' import { StyleSheet, ToastAndroid, Text, View, Image, Dimensions, InteractionManager, ActivityIndicator, StatusBar, Animated, Keyboard, ToolbarAndroid, PixelRatio } from 'react-native' import { sync, updown, fav, upBase, block } from '../../dao/sync' import Ionicons from 'react-native-vector-icons/Ionicons' import { standardColor, idColor, levelColor, rankColor, trophyColor1, trophyColor2, trophyColor3, trophyColor4 } from '../../constant/colorConfig' import { getHomeAPI } from '../../dao' import CreateUserTab from './UserTab' declare var global let toolbarHeight = 56 const iconMapper = { '游戏同步': 'md-sync', '关注': 'md-star-half', '感谢': 'md-thumbs-up', '等级同步': 'md-sync', '屏蔽': 'md-sync' } const limit = 360 // - toolbarHeight import { AppBarLayoutAndroid, CoordinatorLayoutAndroid, CollapsingToolbarLayoutAndroid } from 'mao-rn-android-kit' import ImageBackground from '../../component/ImageBackground' export default class Home extends Component<any, any> { constructor(props) { super(props) this.state = { data: false, isLoading: true, toolbar: [], afterEachHooks: [], mainContent: false, rotation: new Animated.Value(1), scale: new Animated.Value(1), opacity: new Animated.Value(1), openVal: new Animated.Value(0), modalVisible: false, modalOpenVal: new Animated.Value(0), marginTop: new Animated.Value(0), onActionSelected: this._onActionSelected, icons: false, leftIcon: false, rightIcon: false, middleIcon: false, _scrollHeight: this.props.screenProps.modeInfo.height - 64 } } componentWillReceiveProps(nextProps) { if (this.props.screenProps.modeInfo.width !== nextProps.screenProps.modeInfo.width) { this.preFetch() // this.props.navigation.navigate('Home', params) } } removeListener: any = false keyboardDidHideListener: any = false timeout: any = false _coordinatorLayout: any = false sad: any = false componentWillUnmount() { this.removeListener && this.removeListener.remove() if (this.timeout) clearTimeout(this.timeout) // this.keyboardDidShowListener && this.keyboardDidShowListener.remove() this.keyboardDidHideListener && this.keyboardDidHideListener.remove() } componentWillMount() { // this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', (event) => { // // console.log(event.nativeEvent, this._coordinatorLayout.resetBehavior) // this._coordinatorLayout.resetBehavior(this._appBarLayout, false, true) // }) this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => { // this._coordinatorLayout.setScrollingViewBehavior(this._scrollView) this._coordinatorLayout.resetBehavior(this._appBarLayout, false) }) this.preFetch() } preFetch = async () => { const { params } = this.props.navigation.state await this.setState({ isLoading: true }) const targetColor = this.props.screenProps.modeInfo.isNightMode ? '#000' : '#fff' const result = await Promise.all([ Ionicons.getImageSource('md-arrow-back', 24, targetColor), Ionicons.getImageSource('md-sync', 24, targetColor), Ionicons.getImageSource('md-more', 24, targetColor) ]) await this.setState({ leftIcon: result[0], middleIcon: result[1], rightIcon: result[2] }) InteractionManager.runAfterInteractions(() => { getHomeAPI(params.URL).then(data => { this.hasGameTable = data.gameTable.length !== 0 // console.log(profileToolbar) this.setState({ data, isLoading: false }, () => this._coordinatorLayout.setScrollingViewBehavior(this._scrollView)) }) }) } hasGameTable = false handleImageOnclick = (url) => this.props.navigation.navigate('ImageViewer', { images: [ { url } ] }) renderHeader = (rowData) => { const color = 'rgba(255,255,255,1)' const infoColor = 'rgba(255,255,255,0.8)' const { width: SCREEN_WIDTH } = Dimensions.get('window') const onPressPoint = () => { global.toast(rowData.point) } const statusHeight = StatusBar.currentHeight || 0 return ( <ImageBackground source={{uri: rowData.backgroundImage}} style={{ height: limit + toolbarHeight + 1, width: SCREEN_WIDTH }} blurRadis={0} > <global.LinearGradient colors={['rgba(0,0,0,0.6)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0.5)']} locations={[0, 0.4, 0.6, 1]} start={{x: 0.5, y: 0}} end={{x: 0.5, y: 1}}> <View key={rowData.id} style={{ backgroundColor: 'transparent', height: 360, marginTop: 56 + statusHeight / 2 + 8 }}> <View style={{ flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', flex: -1, padding: 5, marginTop: -10 }}> <View style={{ justifyContent: 'center', alignItems: 'center', flex: 2, marginTop: 2 }}> <Text style={{ flex: -1, color: infoColor, fontSize: 15, textAlign: 'center' }}>{rowData.description}</Text> { rowData.icons && rowData.icons.length && <View style={{flexDirection: 'row', marginVertical: 2}}>{rowData.icons.filter((item, index) => index <= 2).map((item, index) => { return ( <Image key={index} borderRadius={12} source={{ uri: item}} style={[styles.avatar, { width: 20, height: 20, overlayColor: 'rgba(0,0,0,0.0)', backgroundColor: 'transparent' }]} /> ) })}</View> } </View> <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}> <Text style={{ flex: -1, color: levelColor, fontSize: 20 }} onPress={onPressPoint}>{rowData.exp.split('经验')[0]}</Text> <Text style={{ flex: -1, color: infoColor, fontSize: 12 }} onPress={onPressPoint}>经验{rowData.exp.split('经验')[1]}</Text> </View> <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}> <Text style={{ flex: -1, color: rankColor, fontSize: 20 }}>{rowData.ranking || 'None'}</Text> <Text style={{ flex: -1, color: infoColor, fontSize: 12 }}>所在服排名</Text> </View> </View> <View style={{ position: 'absolute', top: 0, left: 0, right: 0, height: limit }}> <View style={{ justifyContent: 'center', alignItems: 'center', alignSelf: 'center', flex: 3, marginTop: -70 - (statusHeight || 0) * 1.5 + 10 }}> <View borderRadius={75} style={{width: 150, height: 150, backgroundColor: 'transparent'}} > <Image borderRadius={75} source={{ uri: rowData.avatar}} style={[styles.avatar, { width: 150, height: 150, overlayColor: 'rgba(0,0,0,0.0)', backgroundColor: 'transparent' }]} /> </View> </View> </View> <View style={{ flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', flex: 3, elevation: 4 }}> </View> <View style={{ flex: 1, padding: 0}}> <View borderRadius={20} style={{ paddingHorizontal: 10, alignSelf: 'center', alignContent: 'center', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.5)' }}> <Text style={{ height: 30, textAlignVertical: 'center', textAlign: 'center' }}> <Text style={{ flex: 1, color: trophyColor1, marginVertical: 2, textAlign: 'center', fontSize: 15 }}>{rowData.platinum + ' '}</Text> <Text style={{ flex: 1, color: trophyColor2, marginVertical: 2, textAlign: 'center', fontSize: 15 }}>{rowData.gold + ' '}</Text> <Text style={{ flex: 1, color: trophyColor3, marginVertical: 2, textAlign: 'center', fontSize: 15 }}>{rowData.silver + ' '}</Text> <Text style={{ flex: 1, color: trophyColor4, marginVertical: 2, textAlign: 'center', fontSize: 15 }}>{rowData.bronze + ' '}</Text> </Text> </View> </View> <View style={{ flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', flex: 1, padding: 6, bottom: 20 }}> <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}> <Text style={{ flex: 1, color: color, textAlign: 'center', fontSize: 20 }}>{rowData. allGames}</Text> <Text style={{ flex: 1, color: infoColor, textAlign: 'center', fontSize: 12 }}>总游戏</Text> </View> <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}> <Text style={{ flex: 1, color: color, textAlign: 'center', fontSize: 20 }}>{rowData.perfectGames}</Text> <Text style={{ flex: 1, color: infoColor, textAlign: 'center', fontSize: 12 }}>完美数</Text> </View> <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}> <Text style={{ flex: 1, color: color, textAlign: 'center', fontSize: 20 }}>{rowData.hole}</Text> <Text style={{ flex: 1, color: infoColor, textAlign: 'center', fontSize: 12 }}>坑数</Text> </View> <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}> <Text style={{ flex: 1, color: color, textAlign: 'center', fontSize: 20 }}>{(rowData.ratio || '').replace('完成率', '')}</Text> <Text style={{ flex: 1, color: infoColor, textAlign: 'center', fontSize: 12 }}>完成率</Text> </View> <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}> <Text style={{ flex: 1, color: color, textAlign: 'center', fontSize: 20 }}>{rowData.followed}</Text> <Text style={{ flex: 1, color: infoColor, textAlign: 'center', fontSize: 12 }}>总奖杯</Text> </View> </View> </View> </global.LinearGradient> </ImageBackground> ) } renderTabContainer = (list) => { const { modeInfo } = this.props.screenProps const { params } = this.props.navigation.state return ( <CreateUserTab screenProps={{ modeInfo: modeInfo, toolbar: list, preFetch: this.preFetch, setToolbar: ({ toolbar, toolbarActions, componentDidFocus }) => { const obj: any = { toolbar, onActionSelected: toolbarActions } if (componentDidFocus) { const { index, handler } = componentDidFocus if (!this.state.afterEachHooks[index]) { obj.afterEachHooks = [...this.state.afterEachHooks] obj.afterEachHooks[index] = handler } } {/*this.setState(obj)*/} }, profileToolbar: this.state.data.psnButtonInfo.reverse().map(item => { const result = { title: item.text, iconName: iconMapper[item.text], show: item.text.includes('游戏同步') ? 'always' : 'never' } if (!iconMapper[item.text]) delete result.iconName if (item.text.includes('冷却') || iconMapper[item.text]) return result return undefined }).filter(item => item), psnid: params.title, gameTable: this.state.data.gameTable, diaryTable: this.state.data.diaryTable, navigation: this.props.navigation }} onNavigationStateChange={(prevRoute, nextRoute, action) => { if (prevRoute.index !== nextRoute.index && action.type === 'Navigation/NAVIGATE') { } }}/> ) } _onActionSelected = (index) => { const { params } = this.props.navigation.state const { preFetch } = this const psnid = params.URL.split('/').filter(item => item.trim()).pop() // alert(index) switch (index) { case 5: this.props.navigation.navigate('Stats', { URL: params.URL, psnid, title: `${psnid} 奖杯统计` }) return case 4: // if (psnid === modeInfo.settingInfo.psnid) return global.toast('不可以屏蔽自己') block({ type: 'psnid', param: psnid }).then(res => res.text()).then(text => { // console.log(text) // ToastAndroid.show('同步成功', ToastAndroid.SHORT); if (text) return global.toast(text) global.toast('屏蔽成功') preFetch && preFetch() }).catch(err => { const msg = `屏蔽失败: ${err.toString()}` global.toast(msg) // ToastAndroid.show(msg, ToastAndroid.SHORT); }) return case 3: fav({ type: 'psnid', param: psnid }).then(res => res.text()).then(text => { // console.log(text) // ToastAndroid.show('同步成功', ToastAndroid.SHORT); if (text) return global.toast(text) global.toast('关注成功') preFetch && preFetch() }).catch(err => { const msg = `操作失败: ${err.toString()}` global.toast(msg) // ToastAndroid.show(msg, ToastAndroid.SHORT); }) return case 2: updown({ type: 'psnid', param: psnid, updown: 'up' }).then(res => res.text()).then(text => { // ToastAndroid.show('同步成功', ToastAndroid.SHORT); if (text) return global.toast(text) global.toast('感谢成功') preFetch && preFetch() }).catch(err => { const msg = `操作失败: ${err.toString()}` global.toast(msg) // ToastAndroid.show(msg, ToastAndroid.SHORT); }) return case 1: ToastAndroid.show('等级同步中..', ToastAndroid.SHORT) upBase(psnid).then(res => res.text()).then(text => { // console.log(text) if (text.includes('玩脱了')) { const arr = text.match(/\<title\>(.*?)\<\/title\>/) if (arr && arr[1]) { const msg = `同步失败: ${arr[1]}` // ToastAndroid.show(msg, ToastAndroid.SHORT); global.toast(msg) return } } // ToastAndroid.show('同步成功', ToastAndroid.SHORT); global.toast('同步成功') preFetch && preFetch() }).catch(err => { const msg = `同步失败: ${err.toString()}` global.toast(msg) // ToastAndroid.show(msg, ToastAndroid.SHORT); }) return case 0: ToastAndroid.show('游戏同步中..', ToastAndroid.SHORT) sync(psnid).then(res => res.text()).then(text => { if (text.includes('玩脱了')) { const arr = text.match(/\<title\>(.*?)\<\/title\>/) if (arr && arr[1]) { const msg = `同步失败: ${arr[1]}` // ToastAndroid.show(msg, ToastAndroid.SHORT); global.toast(msg) return } } // ToastAndroid.show('同步成功', ToastAndroid.SHORT); global.toast('同步成功') preFetch && preFetch() }).catch(err => { const msg = `同步失败: ${err.toString()}` global.toast(msg) // ToastAndroid.show(msg, ToastAndroid.SHORT); }) return } } onIconClicked = () => this.props.navigation.goBack() toolbar = [ {'title': '游戏同步', 'iconName': 'md-sync', 'show': 'never'}, {'title': '等级同步', 'iconName': 'md-sync', 'show': 'never'}, {'title': '感谢', 'iconName': 'md-thumbs-up', 'show': 'never'}, {'title': '关注', 'iconName': 'md-star-half', 'show': 'never'}, {'title': '屏蔽', 'iconName': 'md-sync', 'show': 'never'} ] render() { const { params } = this.props.navigation.state console.log('Home.js rendered') const { modeInfo } = this.props.screenProps const { data: source } = this.state // console.log(JSON.stringify(profileToolbar)) const psnid = modeInfo.settingInfo.psnid.toLowerCase() const toolbar: any = this.toolbar.slice() if (psnid === 'secondlife_xhm') { toolbar.push({ title: '奖杯统计', show: 'never' }) } // alert(PixelRatio.getPixelSizeForLayoutSize(56 + StatusBar.currentHeight / 2)) return source.playerInfo && this.state.leftIcon && !this.state.isLoading ? ( <View style={{flex: 1}}> <CoordinatorLayoutAndroid fitsSystemWindows={false} ref={this._setCoordinatorLayout}> <AppBarLayoutAndroid ref={this._setAppBarLayout} fitsSystemWindows={false} style={styles.appbar} > <CollapsingToolbarLayoutAndroid collapsedTitleColor={modeInfo.backgroundColor} contentScrimColor={modeInfo.standardColor} expandedTitleColor={modeInfo.titleTextColor} statusBarScrimColor={'#f00000'} titleEnable={false} layoutParams={{ scrollFlags: ( AppBarLayoutAndroid.SCROLL_FLAG_SCROLL | AppBarLayoutAndroid.SCROLL_FLAG_SNAP | AppBarLayoutAndroid.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED ) }}> <View style={{ flex: 1, backgroundColor: modeInfo.standardColor }} layoutParams={{ collapseParallaxMultiplie: 0.7, collapseMode: CollapsingToolbarLayoutAndroid.CollapseMode.COLLAPSE_MODE_PARALLAX }}> {source.playerInfo && this.renderHeader(source.playerInfo)} </View> <ToolbarAndroid navIcon={this.state.leftIcon} overflowIcon={this.state.rightIcon} title={`${params.title}`} origin titleColor={modeInfo.isNightMode ? '#000' : '#fff'} actions={toolbar} layoutParams={{ height: parseInt(56 + (StatusBar.currentHeight || 0) / 2, 10), // required, collapseMode: CollapsingToolbarLayoutAndroid.CollapseMode.COLLAPSE_MODE_PIN // required }} onIconClicked={this.onIconClicked} onActionSelected={this._onActionSelected} paddingTop={PixelRatio.getPixelSizeForLayoutSize(8)} minHeight={PixelRatio.getPixelSizeForLayoutSize(64)} /> </CollapsingToolbarLayoutAndroid> </AppBarLayoutAndroid> <View style={[styles.scrollView, { height: this.state._scrollHeight, backgroundColor: modeInfo.backgroundColor }]} ref={this._setScrollView}> {/*<NestedScrollViewAndroid> {this._getItems(30)} </NestedScrollViewAndroid>*/} {this.renderTabContainer(source.toolbarInfo)} </View> </CoordinatorLayoutAndroid> </View> ) : <View style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }}> <Ionicons.ToolbarAndroid navIconName='md-arrow-back' overflowIconName='md-more' iconColor={modeInfo.isNightMode ? '#000' : '#fff'} title={params.title} titleColor={modeInfo.isNightMode ? '#000' : '#fff'} style={[styles.toolbar, { backgroundColor: this.state.isLoading ? modeInfo.standardColor : 'transparent' }]} actions={[]} key={this.state.toolbar.map(item => item.text || '').join('::')} onIconClicked={() => this.props.navigation.goBack()} /> <ActivityIndicator animating={this.state.isLoading} style={{ flex: 999, justifyContent: 'center', alignItems: 'center' }} color={modeInfo.accentColor} size={50} /> </View> } _appBarLayout = null _scrollView = null _setCoordinatorLayout = component => { this._coordinatorLayout = component } _setAppBarLayout = component => { this._appBarLayout = component } _setScrollView = component => { this._scrollView = component } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#F5FCFF' }, toolbar: { backgroundColor: standardColor, height: 56, elevation: 4 }, selectedTitle: { // backgroundColor: '#00ffff' // fontSize: 20 }, avatar: { width: 50, height: 50 }, a: { fontWeight: '300', color: idColor // make links coloured pink }, appbar: { backgroundColor: '#2278F6', height: 360 + 56 }, navbar: { height: 56, alignItems: 'center', justifyContent: 'center', backgroundColor: 'transparent', position: 'relative' }, backBtn: { top: 0, left: 0, height: 56, position: 'absolute' }, caption: { color: '#fff', fontSize: 20 }, heading: { height: 38, alignItems: 'center', justifyContent: 'center', backgroundColor: '#4889F1' }, headingText: { color: 'rgba(255, 255, 255, .6)' }, scrollView: { backgroundColor: '#f2f2f2' }, item: { borderRadius: 2, height: 200, marginLeft: 10, marginRight: 10, marginTop: 5, marginBottom: 5, justifyContent: 'center', alignItems: 'center' }, itemContent: { fontSize: 30, color: '#FFF' } })
the_stack
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { SharedModule } from './../../../shared/shared.module'; import { ComplianceDashboardComponent } from './compliance-dashboard/compliance-dashboard.component'; import { ComplianceRoutingModule } from './compliance-routing.module'; import { ComplianceComponent } from './compliance.component'; import { ComplianceIssuesComponent } from './../../secondary-components/compliance-issues/compliance-issues.component'; import { PacmanIssuesComponent } from './../../secondary-components/pacman-issues/pacman-issues.component'; import { AutofixScheduleComponent } from './../../secondary-components/autofix-schedule/autofix-schedule.component'; import { MultilineBrushZoomComponent } from './../../secondary-components/multiline-brush-zoom/multiline-brush-zoom.component'; import { MultiBandDonutComponent } from './../../secondary-components/multi-band-donut/multi-band-donut.component'; import { IssuesCategoryComponent } from './../../secondary-components/issues-category/issues-category.component'; import { OverviewPatchingComponent } from './../../secondary-components/overview-patching/overview-patching.component'; import { OverviewTaggingComponent } from './../../secondary-components/overview-tagging/overview-tagging.component'; import { OverviewCertificatesComponent } from './../../secondary-components/overview-certificates/overview-certificates.component'; import { OverviewVulnerabilitiesComponent } from './../../secondary-components/overview-vulnerabilities/overview-vulnerabilities.component'; import { SelectComplianceDropdown } from './../../services/select-compliance-dropdown.service'; import { IssueListingComponent } from './issue-listing/issue-listing.component'; import { IssueDetailsComponent } from './issue-details/issue-details.component'; import { VulnerabilitiesComplianceComponent } from './vulnerabilities-compliance/vulnerabilities-compliance.component'; import { IssueBlocksComponent } from './../../secondary-components/issue-blocks/issue-blocks.component'; import { DetailsInfoComponent } from './../../secondary-components/details-info/details-info.component'; import { VulnerabilityIssueComponent } from './../../secondary-components/vulnerability-issue/vulnerability-issue.component'; import { VulnerabilityOverallComponent } from './../../secondary-components/vulnerability-overall/vulnerability-overall.component'; import { VulnerabilityAcrossApplicationComponent } from './../../secondary-components/vulnerability-across-application/vulnerability-across-application.component'; import { ListTableComponent } from './../../secondary-components/list-table/list-table.component'; import { IssuesTrendHistoryComponent } from './../../secondary-components/issues-trend-history/issues-trend-history.component'; import { AllVulnerabilityTableComponent } from './../../secondary-components/all-vulnerability-table/all-vulnerability-table.component'; import { VulnerabilityTrendComponent } from './../../secondary-components/vulnerability-trend/vulnerability-trend.component'; import { PatchingComplianceComponent } from './patching-compliance/patching-compliance.component'; import { TaggingComplianceComponent } from './tagging-compliance/tagging-compliance.component'; import { CloudNotificationsComponent } from './cloud-notifications/cloud-notifications.component'; import { EventDetailsComponent } from './event-details/event-details.component'; import { CertificateComplianceComponent } from './certificate-compliance/certificate-compliance.component'; import { WindowRefService } from './../../services/window.service'; import { AllPatchingTableComponent } from './../../secondary-components/all-patching-table/all-patching-table.component'; import { PatchingIssueComponent } from './../../secondary-components/patching-issue/patching-issue.component'; import { PatchingCurrentStateComponent } from './../../secondary-components/patching-current-state/patching-current-state.component'; import { StateTableComponent } from './../../secondary-components/state-table/state-table.component'; import { OverallComplianceComponent } from './../../secondary-components/overall-compliance/overall-compliance.component'; import { PatchingTrendComponent } from './../../secondary-components/patching-trend/patching-trend.component'; import { PatchingGraphComponent } from './../../secondary-components/patching-graph/patching-graph.component'; import { HighlightModule } from 'ngx-highlight'; import { CertificateSummaryComponent } from './../../secondary-components/certificate-summary/certificate-summary.component'; import { CertificateStageComponent } from './../../secondary-components/certificate-stage/certificate-stage.component'; import { ProgressSummaryComponent } from './../../secondary-components/progress-summary/progress-summary.component'; import { AllCertificateTableComponent } from './../../secondary-components/all-certificate-table/all-certificate-table.component'; import { CertificateTrendComponent } from './../../secondary-components/certificate-trend/certificate-trend.component'; import { QuarterGraphComponent } from './../../secondary-components/quarter-graph/quarter-graph.component'; import { PolicyDetailsComponent } from './policy-details/policy-details.component'; import { PolicySummaryComponent } from './../../secondary-components/policy-summary/policy-summary.component'; import { PolicyAcrossApplicationComponent } from './../../secondary-components/policy-across-application/policy-across-application.component'; import { AllPolicyViolationsComponent } from './../../secondary-components/all-policy-violations/all-policy-violations.component'; import { PolicyTrendComponent } from './../../secondary-components/policy-trend/policy-trend.component'; import { TaggingTrendComponent } from './../../secondary-components/tagging-trend/tagging-trend.component'; import { TaggingSummaryComponent } from './../../secondary-components/tagging-summary/tagging-summary.component'; import { TotalTagComplianceComponent } from './../../secondary-components/total-tag-compliance/total-tag-compliance.component'; import { PolicyContentSliderComponent } from './../../secondary-components/policy-content-slider/policy-content-slider.component'; import { TargetTypeTaggingTileComponent } from './../../secondary-components/target-type-tagging-tile/target-type-tagging-tile.component'; import { TaggingAcrossTargetTypeComponent } from './../../secondary-components/tagging-across-target-type/tagging-across-target-type.component'; import { TaggingInstancesTableComponent } from './../../secondary-components/tagging-instances-table/tagging-instances-table.component'; import { ComplianceOverviewTrendComponent } from './../../secondary-components/compliance-overview-trend/compliance-overview-trend.component'; import { TaggingComplianceTrendComponent } from './../../secondary-components/tagging-compliance-trend/tagging-compliance-trend.component'; import { VulnerabilitiesComplianceTrendComponent } from './../../secondary-components/vulnerabilities-compliance-trend/vulnerabilities-compliance-trend.component'; import { CertificatesComplianceTrendComponent } from './../../secondary-components/certificates-compliance-trend/certificates-compliance-trend.component'; import { PolicyKnowledgebaseComponent } from './policy-knowledgebase/policy-knowledgebase.component'; import { PolicyKnowledgebaseDetailsComponent } from './policy-knowledgebase-details/policy-knowledgebase-details.component'; import { CertificateAssetsTrendComponent } from './../../secondary-components/certificate-assets-trend/certificate-assets-trend.component'; import { TaggingAssetsTrendComponent } from './../../secondary-components/tagging-assets-trend/tagging-assets-trend.component'; import { VulnerabilityAssetsTrendComponent } from './../../secondary-components/vulnerability-assets-trend/vulnerability-assets-trend.component'; import { PolicyAssetsTrendComponent } from './../../secondary-components/policy-assets-trend/policy-assets-trend.component'; import { VulnerabilitiesComponent } from './vulnerabilities/vulnerabilities.component'; import { CertificatesComponent } from './certificates/certificates.component'; import { OnpremPatchingGraphComponent } from './../../secondary-components/onprem-patching-graph/onprem-patching-graph.component'; import { PatchingSponsorComponent } from './../../secondary-components/patching-sponsor/patching-sponsor.component'; import { PatchingSnapshotComponent } from './../../secondary-components/patching-snapshot/patching-snapshot.component'; import { PatchingProjectionsComponent } from './patching-projections/patching-projections.component'; import { VulnerabilitySummaryTableComponent } from './../../secondary-components/vulnerability-summary-table/vulnerability-summary-table.component'; import { AgGridModule } from 'ag-grid-angular/main'; import { DigitalDevDashboardComponent } from './digital-dev-dashboard/digital-dev-dashboard.component'; import { PullRequestLineMetricsComponent } from './../../secondary-components/pull-request-line-metrics/pull-request-line-metrics.component'; import { DigitalApplicationDistributionComponent } from './../../secondary-components/digital-application-distribution/digital-application-distribution.component'; import { DigitalDevStrategyDistributionComponent } from './../../secondary-components/digital-dev-strategy-distribution/digital-dev-strategy-distribution.component'; import { VulnerabilityAgingGraphComponent } from './../../secondary-components/vulnerability-aging-graph/vulnerability-aging-graph.component'; import { DevStandardPullRequestAgeComponent } from './../../secondary-components/dev-standard-pull-request-age/dev-standard-pull-request-age.component'; import { DevStandardStaleBranchAgeComponent } from './../../secondary-components/dev-standard-stale-branch-age/dev-standard-stale-branch-age.component'; import { DevStandardTotalStaleBranchesComponent } from './../../secondary-components/dev-standard-total-stale-branches/dev-standard-total-stale-branches.component'; import { DevPullRequestApplicationsComponent } from './../../secondary-components/dev-pull-request-applications/dev-pull-request-applications.component'; import { DevStaleBranchApplicationsComponent } from './../../secondary-components/dev-stale-branch-applications/dev-stale-branch-applications.component'; import { DigitalDevManagementService } from '../../services/digital-dev-management.service'; import { VulnerabilityDetailsComponent } from './vulnerability-details/vulnerability-details.component'; import { PolicyViolationDescComponent } from './../../secondary-components/policy-violation-desc/policy-violation-desc.component'; import { IssueExceptionComponent } from './../../secondary-components/issue-exception/issue-exception.component'; import { PolicyViolationsListComponent } from './policy-violations-list/policy-violations-list.component'; import { IssueListingService } from '../../services/issue-listing.service'; import { RecommendationsComponent} from '../../modules/compliance/recommendations/recommendations.component'; import { RecommandCategoryComponent } from '../../secondary-components/recommand-category/recommand-category.component'; import { RecommendationsDetailsComponent } from './recommendations-details/recommendations-details.component'; import { OverallVulnerabilitiesComponent } from './../../secondary-components/overall-vulnerabilities/overall-vulnerabilities.component'; @NgModule({ imports: [ CommonModule, ComplianceRoutingModule, SharedModule, HighlightModule, AgGridModule.withComponents([ PatchingSnapshotComponent, PatchingSponsorComponent, VulnerabilitySummaryTableComponent, DevPullRequestApplicationsComponent, DevStaleBranchApplicationsComponent ]) ], declarations: [ ComplianceIssuesComponent, PacmanIssuesComponent, MultilineBrushZoomComponent, MultiBandDonutComponent, IssuesCategoryComponent, ComplianceComponent, ComplianceDashboardComponent, OverviewPatchingComponent, OverviewTaggingComponent, OverviewCertificatesComponent, OverviewVulnerabilitiesComponent, IssueListingComponent, IssueDetailsComponent, VulnerabilitiesComplianceComponent, AutofixScheduleComponent, IssueBlocksComponent, DetailsInfoComponent, VulnerabilityIssueComponent, VulnerabilityOverallComponent, VulnerabilityAcrossApplicationComponent, ListTableComponent, IssuesTrendHistoryComponent, AllVulnerabilityTableComponent, VulnerabilityTrendComponent, PatchingComplianceComponent, TaggingComplianceComponent, CloudNotificationsComponent, CertificateComplianceComponent, EventDetailsComponent, AllPatchingTableComponent, PatchingIssueComponent, PatchingCurrentStateComponent, StateTableComponent, OverallComplianceComponent, PatchingTrendComponent, PatchingGraphComponent, CertificateSummaryComponent, CertificateStageComponent, ProgressSummaryComponent, AllCertificateTableComponent, CertificateTrendComponent, QuarterGraphComponent, PolicyDetailsComponent, PolicySummaryComponent, PolicyAcrossApplicationComponent, AllPolicyViolationsComponent, PolicyTrendComponent, TaggingTrendComponent, TaggingSummaryComponent, TotalTagComplianceComponent, PolicyContentSliderComponent, TargetTypeTaggingTileComponent, TaggingAcrossTargetTypeComponent, TaggingInstancesTableComponent, ComplianceOverviewTrendComponent, TaggingComplianceTrendComponent, VulnerabilitiesComplianceTrendComponent, CertificatesComplianceTrendComponent, PolicyKnowledgebaseComponent, PolicyKnowledgebaseDetailsComponent, CertificateAssetsTrendComponent, TaggingAssetsTrendComponent, OnpremPatchingGraphComponent, PullRequestLineMetricsComponent, VulnerabilityAssetsTrendComponent, PolicyAssetsTrendComponent, VulnerabilitiesComponent, CertificatesComponent, PatchingSnapshotComponent, PatchingProjectionsComponent, PatchingSponsorComponent, VulnerabilitySummaryTableComponent, DigitalDevDashboardComponent, DigitalApplicationDistributionComponent, DigitalDevStrategyDistributionComponent, VulnerabilityAgingGraphComponent, DevStandardPullRequestAgeComponent, DevStandardStaleBranchAgeComponent, DevStandardTotalStaleBranchesComponent, DevPullRequestApplicationsComponent, DevStaleBranchApplicationsComponent, VulnerabilityDetailsComponent, PolicyViolationDescComponent, IssueExceptionComponent, PolicyViolationsListComponent, RecommendationsComponent, RecommandCategoryComponent, RecommendationsDetailsComponent, OverallVulnerabilitiesComponent ], providers: [ SelectComplianceDropdown, WindowRefService, DigitalDevManagementService, IssueListingService ] }) export class ComplianceModule {}
the_stack
import { ObjectFormat, RowEntry, ObjectRow, FieldsByConfigId, StyleById, getHeight, getWidth } from '@google/dscc'; import ApexCharts from 'apexcharts'; interface FontInfo { family: string; size: number; color: string; } interface Chart { chart: ApexCharts; element: Element; } let myChart: Chart | undefined; const CHARTNAME = 'myChart'; const ERRORNAME = 'Error'; /** * Main driver function, takes data from DS as ObjectFormat * and populates the viz accordingly. * @param data */ export function drawViz(data: ObjectFormat): void { const hasData: boolean = data.tables.DEFAULT.length > 0; const oldErrorMsg = document.getElementById(ERRORNAME); if (oldErrorMsg && oldErrorMsg.parentNode) { oldErrorMsg.parentNode.removeChild(oldErrorMsg); } if (!hasData) { if (myChart && document.body.contains(myChart.element)) { myChart.chart.destroy(); document.body.removeChild(myChart.element); myChart = undefined; } const errorChartElement = document.createElement('div'); errorChartElement.id = ERRORNAME; const height = getHeight()/2; errorChartElement.innerHTML = ` <div style=" position:absolute;padding-top:`+height+`px; bottom:30%;left:30%;right:30%"> <h1 style="text-align:center;">No Data</h1> <p style="text-align:center;">Data Studio returned no data.</p> </div> `; document.body.appendChild(errorChartElement); return; } const tables = populateTables(data.tables.DEFAULT, data.fields); const styling = populateStyle(data.style, tables.labels.length); const options = { series: tables.series, labels: tables.labels, tooltip: styling.tooltip, chart: styling.chart, fill: styling.fill, markers: styling.markers, dataLabels: styling.datalabels, plotOptions: styling.plotoptions, xaxis: styling.xaxis, yaxis: styling.yaxis, stroke: styling.stroke, legend: styling.legend, responsive: [{ breakpoint: 5000, options: { chart:{ type: 'radar', toolbar: { show: false, }, height:getHeight()-20, width:getWidth() }}, }] }; if (!myChart) { const newChartElement = document.createElement('div'); newChartElement.id = CHARTNAME; document.body.appendChild(newChartElement); const newApexChart = new ApexCharts(newChartElement, options); newApexChart.render(); myChart = { element: newChartElement, chart: newApexChart }; } else { myChart.chart.updateOptions(options); } } /** * Logic to translate Dims/Metrics into ApexSeries and ApexLabels * @param vizData * @param vizFields */ export function populateTables( vizData: ObjectRow[], vizFields: FieldsByConfigId ) { const metrics: (number)[][] = []; const series: ApexAxisChartSeries = []; const labels: (RowEntry)[] = []; for (let i = 0; i < vizData.length; ++i) { labels[i] = vizData[i].dimID[0]; for (let j = 0; j < vizData[i].metricID.length; j++) { if (!metrics[j]) metrics[j] = []; metrics[j][i] = Number(vizData[i].metricID[j]); } } //create a 'Series' for each metric for (let i = 0; i < metrics.length; ++i) { const newSeries = { name: vizFields.metricID[i].name, data: metrics[i], }; series.push(newSeries); } return { series: series, labels: labels, }; } /** * Invokes the other style populate functions: * Fill, Markers, DataLabels, PlotOptons, XAxis, YAxis, Stroke, Legend * @param vizStyle * @param numDims */ export function populateStyle(vizStyle: StyleById, numDims: number) { const lineColors: string[] = [ vizStyle.fillColor1.value.color, vizStyle.fillColor2.value.color, vizStyle.fillColor3.value.color, vizStyle.fillColor4.value.color, vizStyle.fillColor5.value.color, ]; const axisFontInfo: FontInfo = { color: vizStyle.axisFontColor.value.color, size: vizStyle.axisFontSize.value, family: vizStyle.axisFontFamily.value, }; const chart = { type: 'radar', toolbar: { show: false, } }; const tooltip = { marker: { show: false, }, }; return { tooltip: tooltip, chart: chart, fill: populateFill( vizStyle.fillRadar.value, vizStyle.fillOpacity.value, lineColors ), markers: populateMarkers( vizStyle.showMarkers.value, vizStyle.markerType.value, lineColors ), datalabels: populateDataLabels( vizStyle.showMarkers.value, vizStyle.markerType.value, lineColors,axisFontInfo.family ), plotoptions: populatePlotOptions( vizStyle.plotColor1.value.color, vizStyle.plotColor2.value.color ), xaxis: populateXAxis(vizStyle.enableXAxis.value, axisFontInfo, numDims), yaxis: populateYAxis(vizStyle.enableYAxis.value, axisFontInfo), stroke: populateStroke(lineColors), legend: populateLegend(vizStyle.enableLegend.value,vizStyle.legendPosition.value,lineColors,axisFontInfo), }; } /** * Takes fillRadar bool, fillOpacity level and lineColors to generate ApexFill * @param fillRadar * @param fillOpacity * @param lineColors */ export function populateFill( fillRadar: boolean, fillOpacity: number, lineColors: string[] ): ApexFill { const fill = { opacity: fillRadar ? fillOpacity : 0, colors: lineColors, }; return fill; } /** * Takes showMarkers bool, the markerType and lineColors to populate ApexDataLabels * @param showMarkers * @param markerType * @param lineColors */ export function populateMarkers( showMarkers: boolean, markerType: string, lineColors: string[] ): ApexMarkers { const size = showMarkers && markerType === 'default' ? 4 : 0; const markers = { size: size, colors: lineColors, }; return markers; } /** * Takes showMarkers bool, the markerType and lineColors to populate ApexDataLabels * @param showMarkers * @param markerType * @param lineColors */ export function populateDataLabels( showMarkers: boolean, markerType: string, lineColors: string[], fontFamily:string ): ApexDataLabels { if (showMarkers && markerType === 'data') { const dataLabels = { enabled: true, style: { fontFamily:fontFamily, colors: lineColors, }, background: { enabled: true, borderRadius: 2, dropShadow: { enabled: false, }, }, }; return dataLabels; } const dataLabels = { enabled: false, }; return dataLabels; } /** * Takes 2 colors and populates ApexPlotOptions * @param color1 * @param color2 */ export function populatePlotOptions(color1: string, color2: string): ApexPlotOptions { const plotOptions = { radar: { polygons: { strokeColors: 'white', fill: { colors: [color1, color2], }, }, }, }; return plotOptions; } /** * Takes XAxisEnable boolean and fontInfo and creates ApexXAxis * Uses numDims to properly add color to axis from fontInfo * @param enableAxis * @param fontInfo * @param numDims */ export function populateXAxis( enableAxis: boolean, fontInfo: FontInfo, numDims: number ): ApexXAxis { if (enableAxis) { //super hacky but it works- creates an array with the desired color n times //this lets the color apply to all the labels on the xx axis const axisColors = []; for (let i = 0; i < numDims; i++) { axisColors[i] = fontInfo.color; } const xAxis = { labels: { show: enableAxis, style: { colors: axisColors, fontSize: fontInfo.size + 'px', fontFamily: fontInfo.family, }, }, }; return xAxis; } const xAxis = { labels: { show: enableAxis, }, }; return xAxis; } /** * Takes YAxisEnable boolean and fontInfo and creates ApexYAxis * @param enableAxis * @param fontInfo */ export function populateYAxis(enableAxis: boolean, fontInfo: FontInfo): ApexYAxis { const yAxis: ApexYAxis = { show: enableAxis, floating: true, labels: { style: { colors: fontInfo.color, fontSize: fontInfo.size + 'px', fontFamily: fontInfo.family, }, }, }; return yAxis; } /** * Takes lineColors and creates ApexStroke * @param lineColors */ export function populateStroke(lineColors: string[]): ApexStroke { const stroke = { show: true, curve: 'smooth' as ApexStroke["curve"], lineCap: 'butt' as ApexStroke["lineCap"], width: 2, colors: lineColors, dashArray: 0, }; return stroke; } /** * Takes lineColors and creates ApexLegend * @param lineColors */ export function populateLegend(enableLegend: boolean,legendPosition:ApexLegend["position"],lineColors: string[],fontInfo:FontInfo): ApexLegend { const legend = { show:enableLegend, showForSingleSeries:true, position:legendPosition, fontSize:fontInfo.size+'px', fontFamily:fontInfo.family, labels:{ colors:fontInfo.color, }, markers: { fillColors: lineColors, }, }; return legend; }
the_stack
import URL from 'url'; import PATH from 'path'; import * as net from "net"; import * as http from "http"; import { Request, Response, NextFunction, Application } from 'express'; import bodyParser from 'body-parser'; import httpProxy from 'http-proxy'; import * as toRegexp from 'path-to-regexp'; import clearModule from 'clear-module'; import chokidar from 'chokidar'; import color from 'colors-cli/safe'; import { proxyHandle } from './proxyHandle'; import { mockerHandle } from './mockerHandle'; export * from './delay'; export * from './utils'; export type ProxyTargetUrl = string | Partial<URL.Url>; export type MockerResultFunction = ((req: Request, res: Response, next?: NextFunction) => void); export type MockerResult = string | number| Array<any> | Record<string, any> | MockerResultFunction; /** * Setting a proxy router. * @example * * ```json * { * '/api/user': { * id: 1, * username: 'kenny', * sex: 6 * }, * 'DELETE /api/user/:id': (req, res) => { * res.send({ status: 'ok', message: '删除成功!' }); * } * } * ``` */ export type MockerProxyRoute = Record<string, MockerResult> & { /** * This is the option parameter setting for apiMocker * Priority processing. * apiMocker(app, path, option) * {@link MockerOption} */ _proxy?: MockerOption; } /** * Listening for proxy events. * This options contains listeners for [node-http-proxy](https://github.com/http-party/node-http-proxy#listening-for-proxy-events). * {typeof httpProxy.on} * {@link httpProxy} */ export interface HttpProxyListeners extends Record<string, any> { start?: ( req: http.IncomingMessage, res: http.ServerResponse, target: ProxyTargetUrl ) => void; proxyReq?: ( proxyReq: http.ClientRequest, req: http.IncomingMessage, res: http.ServerResponse, options: httpProxy.ServerOptions ) => void; proxyRes?: ( proxyRes: http.IncomingMessage, req: http.IncomingMessage, res: http.ServerResponse ) => void; proxyReqWs?: ( proxyReq: http.ClientRequest, req: http.IncomingMessage, socket: net.Socket, options: httpProxy.ServerOptions, head: any ) => void; econnreset?: ( err: Error, req: http.IncomingMessage, res: http.ServerResponse, target: ProxyTargetUrl ) => void end?: ( req: http.IncomingMessage, res: http.ServerResponse, proxyRes: http.IncomingMessage ) => void; /** * This event is emitted once the proxy websocket was closed. */ close?: ( proxyRes: http.IncomingMessage, proxySocket: net.Socket, proxyHead: any ) => void; } export interface MockerOption { /** * priority 'proxy' or 'mocker' * @default `proxy` * @issue [#151](https://github.com/jaywcjlove/mocker-api/issues/151) */ priority?: 'proxy' | 'mocker'; /** * `Boolean` Setting req headers host. */ changeHost?: boolean; /** * rewrite target's url path. * Object-keys will be used as RegExp to match paths. [#62](https://github.com/jaywcjlove/mocker-api/issues/62) * @default `{}` */ pathRewrite?: Record<string, string>, /** * Proxy settings, Turn a path string such as `/user/:name` into a regular expression. [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) * @default `{}` */ proxy?: Record<string, string>, /** * Set the [listen event](https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events) and [configuration](https://github.com/nodejitsu/node-http-proxy#options) of [http-proxy](https://github.com/nodejitsu/node-http-proxy) * @default `{}` */ httpProxy?: { options?: httpProxy.ServerOptions; listeners?: HttpProxyListeners }; /** * bodyParser settings. * @example * * ```js * bodyParser = {"text/plain": "text","text/html": "text"} * ``` * * will parsed `Content-Type='text/plain' and Content-Type='text/html'` with `bodyParser.text` * * @default `{}` */ bodyParserConf?: { [key: string]: 'raw' | 'text' | 'urlencoded' | 'json'; }; /** * [`bodyParserJSON`](https://github.com/expressjs/body-parser/tree/56a2b73c26b2238bc3050ad90af9ab9c62f4eb97#bodyparserjsonoptions) JSON body parser * @default `{}` */ bodyParserJSON?: bodyParser.OptionsJson; /** * [`bodyParserText`](https://github.com/expressjs/body-parser/tree/56a2b73c26b2238bc3050ad90af9ab9c62f4eb97#bodyparsertextoptions) Text body parser * @default `{}` */ bodyParserText?: bodyParser.OptionsText; /** * [`bodyParserRaw`](https://github.com/expressjs/body-parser/tree/56a2b73c26b2238bc3050ad90af9ab9c62f4eb97#bodyparserrawoptions) Raw body parser * @default `{}` */ bodyParserRaw?: bodyParser.Options; /** * [`bodyParserUrlencoded`](https://github.com/expressjs/body-parser/tree/56a2b73c26b2238bc3050ad90af9ab9c62f4eb97#bodyparserurlencodedoptions) URL-encoded form body parser * @default `{}` */ bodyParserUrlencoded?: bodyParser.OptionsUrlencoded; /** * Options object as defined [chokidar api options](https://github.com/paulmillr/chokidar#api) * @default `{}` */ watchOptions?: chokidar.WatchOptions; /** * Access Control Allow options. * @default `{}` * @example * ```js * { * header: { * 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE', * } * } * ``` */ header?: Record<string,string | number | string[]>, /** * `Boolean` the proxy regular expression support full url path. * if the proxy regular expression like /test?a=1&b=1 can be matched */ withFullUrlPath?: boolean } const pathToRegexp = toRegexp.pathToRegexp; let mocker: MockerProxyRoute = {}; module.exports = mockerApi export default function mockerApi(app: Application, watchFile: string | string[] | MockerProxyRoute, conf: MockerOption = {}) { const watchFiles = (Array.isArray(watchFile) ? watchFile : typeof watchFile === 'string' ? [watchFile] : []).map(str => PATH.resolve(str)); if (watchFiles.some(file => !file)) { throw new Error('Mocker file does not exist!.'); } /** * Mybe watch file or pass parameters * https://github.com/jaywcjlove/mocker-api/issues/116 */ const isWatchFilePath = (Array.isArray(watchFile) && watchFile.every(val => typeof val === 'string')) || typeof watchFile === 'string'; mocker = isWatchFilePath ? getConfig() : watchFile; if (!mocker) { return (req: Request, res: Response, next: NextFunction) => { next(); } } let options: MockerOption = {...conf, ...(mocker._proxy || {})} const defaultOptions: MockerOption = { changeHost: true, pathRewrite: {}, proxy: {}, // proxy: proxyConf: {}, httpProxy: {}, // httpProxy: httpProxyConf: {}, bodyParserConf: {}, bodyParserJSON: {}, bodyParserText: {}, bodyParserRaw: {}, bodyParserUrlencoded: {}, watchOptions: {}, header: {}, priority: 'proxy', withFullUrlPath: false } options = { ...defaultOptions, ...options }; // changeHost = true, // pathRewrite = {}, // proxy: proxyConf = {}, // httpProxy: httpProxyConf = {}, // bodyParserConf= {}, // bodyParserJSON = {}, // bodyParserText = {}, // bodyParserRaw = {}, // bodyParserUrlencoded = {}, // watchOptions = {}, // header = {} if (isWatchFilePath) { // 监听配置入口文件所在的目录,一般为认为在配置文件/mock 目录下的所有文件 // 加上require.resolve,保证 `./mock/`能够找到`./mock/index.js`,要不然就要监控到上一级目录了 const watcher = chokidar.watch(watchFiles.map(watchFile => PATH.dirname(require.resolve(watchFile))), options.watchOptions); watcher.on('all', (event, path) => { if (event === 'change' || event === 'add') { try { // 当监听的可能是多个配置文件时,需要清理掉更新文件以及入口文件的缓存,重新获取 cleanCache(path); watchFiles.forEach(file => cleanCache(file)); mocker = getConfig(); if (mocker._proxy) { options = { ...options, ...mocker._proxy }; } console.log(`${color.green_b.black(' Done: ')} Hot Mocker ${color.green(path.replace(process.cwd(), ''))} file replacement success!`); } catch (ex) { console.error(`${color.red_b.black(' Failed: ')} Hot Mocker ${color.red(path.replace(process.cwd(), ''))} file replacement failed!!`); } } }) } // 监听文件修改重新加载代码 // 配置热更新 app.all('/*', (req: Request, res: Response, next: NextFunction) => { const getExecUrlPath = (req: Request) => { return options.withFullUrlPath ? req.url : req.path; } /** * Get Proxy key */ const proxyKey = Object.keys(options.proxy).find((kname) => { return !!pathToRegexp(kname.replace((new RegExp('^' + req.method + ' ')), '')).exec(getExecUrlPath(req)); }); /** * Get Mocker key * => `GET /api/:owner/:repo/raw/:ref` * => `GET /api/:owner/:repo/raw/:ref/(.*)` */ const mockerKey: string = Object.keys(mocker).find((kname) => { return !!pathToRegexp(kname.replace((new RegExp('^' + req.method + ' ')), '')).exec(getExecUrlPath(req)); }); /** * Access Control Allow options. * https://github.com/jaywcjlove/mocker-api/issues/61 */ const accessOptions: MockerOption['header'] = { 'Access-Control-Allow-Origin': req.get('Origin') || '*', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE', 'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With,' + (req.header('access-control-request-headers') || ''), 'Access-Control-Allow-Credentials': 'true', ...options.header, } Object.keys(accessOptions).forEach(keyName => { res.setHeader(keyName, accessOptions[keyName]); }); // fix issue 34 https://github.com/jaywcjlove/mocker-api/issues/34 // In some cross-origin http request, the browser will send the preflighted options request before sending the request methods written in the code. if (!mockerKey && req.method.toLocaleUpperCase() === 'OPTIONS' && Object.keys(mocker).find((kname) => !!pathToRegexp(kname.replace((new RegExp('^(PUT|POST|GET|DELETE) ')), '')).exec(getExecUrlPath(req))) ) { return res.sendStatus(200); } /** * priority 'proxy' or 'mocker' [#151](https://github.com/jaywcjlove/mocker-api/issues/151) */ if (options.priority === 'mocker') { if (mocker[mockerKey]) { return mockerHandle({ req, res, next, mocker, options, mockerKey}) } else if (proxyKey && options.proxy[proxyKey]) { return proxyHandle(req, res, options, proxyKey); } } else { if (proxyKey && options.proxy[proxyKey]) { return proxyHandle(req, res, options, proxyKey); } else if (mocker[mockerKey]) { return mockerHandle({ req, res, next, mocker, options, mockerKey}) } } next(); }); /** * The old module's resources to be released. * @param modulePath */ function cleanCache(modulePath: string) { // The entry file does not have a .js suffix, // causing the module's resources not to be released. // https://github.com/jaywcjlove/webpack-api-mocker/issues/30 try { modulePath = require.resolve(modulePath); } catch (e) {} var module = require.cache[modulePath]; if (!module) return; // remove reference in module.parent if (module.parent) { module.parent.children.splice(module.parent.children.indexOf(module), 1); } // https://github.com/jaywcjlove/mocker-api/issues/42 clearModule(modulePath); } /** * Merge multiple Mockers */ function getConfig() { return watchFiles.reduce((mocker, file) => { const mockerItem = require(file); return Object.assign(mocker, mockerItem.default ? mockerItem.default : mockerItem); }, {}) } return (req: Request, res: Response, next: NextFunction) => { next(); } }
the_stack
import {Class, AnyTiming, Timing, Creatable, InitType} from "@swim/util"; import {Affinity, MemberAnimatorInit} from "@swim/component"; import {Transform} from "@swim/math"; import {Look, Mood, MoodVector, ThemeMatrix} from "@swim/theme"; import {ViewFlags, AnyView, ViewCreator, View} from "@swim/view"; import {AttributeAnimator} from "../animator/AttributeAnimator"; import {StyleMapInit, StyleMap} from "../css/StyleMap"; import type {ViewNodeType} from "../node/NodeView"; import { AnyElementView, ElementViewInit, ElementViewFactory, ElementViewClass, ElementViewConstructor, ElementView, } from "../element/ElementView"; import type {HtmlViewObserver} from "./HtmlViewObserver"; import {StyleView} from "./"; // forward import import {SvgView} from "../"; // forward import /** @public */ export interface ViewHtml extends HTMLElement { view?: HtmlView; } /** @public */ export type AnyHtmlView<V extends HtmlView = HtmlView> = AnyElementView<V> | keyof HtmlViewTagMap; /** @public */ export interface HtmlViewInit extends ElementViewInit { attributes?: HtmlViewAttributesInit; style?: HtmlViewStyleInit; } /** @public */ export interface HtmlViewAttributesInit { autocomplete?: MemberAnimatorInit<HtmlView, "autocomplete">; checked?: MemberAnimatorInit<HtmlView, "checked">; colspan?: MemberAnimatorInit<HtmlView, "colspan">; disabled?: MemberAnimatorInit<HtmlView, "disabled">; placeholder?: MemberAnimatorInit<HtmlView, "placeholder">; rowspan?: MemberAnimatorInit<HtmlView, "rowspan">; selected?: MemberAnimatorInit<HtmlView, "selected">; title?: MemberAnimatorInit<HtmlView, "title">; type?: MemberAnimatorInit<HtmlView, "type">; value?: MemberAnimatorInit<HtmlView, "value">; } /** @public */ export interface HtmlViewStyleInit extends StyleMapInit { } /** @public */ export interface HtmlViewTagMap { a: HtmlView; abbr: HtmlView; address: HtmlView; area: HtmlView; article: HtmlView; aside: HtmlView; audio: HtmlView; b: HtmlView; base: HtmlView; bdi: HtmlView; bdo: HtmlView; blockquote: HtmlView; body: HtmlView; br: HtmlView; button: HtmlView; canvas: HtmlView; caption: HtmlView; cite: HtmlView; code: HtmlView; col: HtmlView; colgroup: HtmlView; data: HtmlView; datalist: HtmlView; dd: HtmlView; del: HtmlView; details: HtmlView; dfn: HtmlView; dialog: HtmlView; div: HtmlView; dl: HtmlView; dt: HtmlView; em: HtmlView; embed: HtmlView; fieldset: HtmlView; figcaption: HtmlView; figure: HtmlView; footer: HtmlView; form: HtmlView; h1: HtmlView; h2: HtmlView; h3: HtmlView; h4: HtmlView; h5: HtmlView; h6: HtmlView; head: HtmlView; header: HtmlView; hr: HtmlView; html: HtmlView; i: HtmlView; iframe: HtmlView; img: HtmlView; input: HtmlView; ins: HtmlView; kbd: HtmlView; label: HtmlView; legend: HtmlView; li: HtmlView; link: HtmlView; main: HtmlView; map: HtmlView; mark: HtmlView; meta: HtmlView; meter: HtmlView; nav: HtmlView; noscript: HtmlView; object: HtmlView; ol: HtmlView; optgroup: HtmlView; option: HtmlView; output: HtmlView; p: HtmlView; param: HtmlView; picture: HtmlView; pre: HtmlView; progress: HtmlView; q: HtmlView; rb: HtmlView; rp: HtmlView; rt: HtmlView; rtc: HtmlView; ruby: HtmlView; s: HtmlView; samp: HtmlView; script: HtmlView; section: HtmlView; select: HtmlView; small: HtmlView; slot: HtmlView; source: HtmlView; span: HtmlView; strong: HtmlView; style: StyleView; sub: HtmlView; summary: HtmlView; sup: HtmlView; table: HtmlView; tbody: HtmlView; td: HtmlView; template: HtmlView; textarea: HtmlView; tfoot: HtmlView; th: HtmlView; thead: HtmlView; time: HtmlView; title: HtmlView; tr: HtmlView; track: HtmlView; u: HtmlView; ul: HtmlView; var: HtmlView; video: HtmlView; wbr: HtmlView; } /** @public */ export interface HtmlViewFactory<V extends HtmlView = HtmlView, U = AnyHtmlView<V>> extends ElementViewFactory<V, U> { } /** @public */ export interface HtmlViewClass<V extends HtmlView = HtmlView, U = AnyHtmlView<V>> extends ElementViewClass<V, U>, HtmlViewFactory<V, U> { readonly tag: string; } /** @public */ export interface HtmlViewConstructor<V extends HtmlView = HtmlView, U = AnyHtmlView<V>> extends ElementViewConstructor<V, U>, HtmlViewClass<V, U> { readonly tag: string; } /** @public */ export class HtmlView extends ElementView { constructor(node: HTMLElement) { super(node); } override readonly observerType?: Class<HtmlViewObserver>; override readonly node!: HTMLElement; override setChild<V extends View>(key: string, newChild: V): View | null; override setChild<F extends ViewCreator<F>>(key: string, factory: F): View | null; override setChild(key: string, newChild: AnyView | Node | keyof HtmlViewTagMap | null): View | null; override setChild(key: string, newChild: AnyView | Node | keyof HtmlViewTagMap | null): View | null { if (typeof newChild === "string") { newChild = HtmlView.fromTag(newChild); } return super.setChild(key, newChild); } override appendChild<V extends View>(child: V, key?: string): V; override appendChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>; override appendChild<K extends keyof HtmlViewTagMap>(tag: K, key?: string): HtmlViewTagMap[K]; override appendChild(child: AnyView | Node | keyof HtmlViewTagMap, key?: string): View; override appendChild(child: AnyView | Node | keyof HtmlViewTagMap, key?: string): View { if (typeof child === "string") { child = HtmlView.fromTag(child); } return super.appendChild(child, key); } override prependChild<V extends View>(child: V, key?: string): V; override prependChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>; override prependChild<K extends keyof HtmlViewTagMap>(tag: K, key?: string): HtmlViewTagMap[K]; override prependChild(child: AnyView | Node | keyof HtmlViewTagMap, key?: string): View; override prependChild(child: AnyView | Node | keyof HtmlViewTagMap, key?: string): View { if (typeof child === "string") { child = HtmlView.fromTag(child); } return super.prependChild(child, key); } override insertChild<V extends View>(child: V, target: View | Node | null, key?: string): V; override insertChild<F extends ViewCreator<F>>(factory: F, target: View | Node | null, key?: string): InstanceType<F>; override insertChild<K extends keyof HtmlViewTagMap>(tag: K, target: View | Node | null, key?: string): HtmlViewTagMap[K]; override insertChild(child: AnyView | Node | keyof HtmlViewTagMap, target: View | Node | null, key?: string): View; override insertChild(child: AnyView | Node | keyof HtmlViewTagMap, target: View | Node | null, key?: string): View { if (typeof child === "string") { child = HtmlView.fromTag(child); } return super.insertChild(child, target, key); } override replaceChild<V extends View>(newChild: View, oldChild: V): V; override replaceChild<V extends View>(newChild: AnyView | Node | keyof HtmlViewTagMap, oldChild: V): V; override replaceChild(newChild: AnyView | Node | keyof HtmlViewTagMap, oldChild: View): View { if (typeof newChild === "string") { newChild = HtmlView.fromTag(newChild); } return super.replaceChild(newChild, oldChild); } @AttributeAnimator({attributeName: "autocomplete", type: String}) readonly autocomplete!: AttributeAnimator<this, string>; @AttributeAnimator({attributeName: "checked", type: Boolean}) readonly checked!: AttributeAnimator<this, boolean, boolean | string>; @AttributeAnimator({attributeName: "colspan", type: Number}) readonly colspan!: AttributeAnimator<this, number, number | string>; @AttributeAnimator({attributeName: "disabled", type: Boolean}) readonly disabled!: AttributeAnimator<this, boolean, boolean | string>; @AttributeAnimator({attributeName: "placeholder", type: String}) readonly placeholder!: AttributeAnimator<this, string>; @AttributeAnimator({attributeName: "rowspan", type: Number}) readonly rowspan!: AttributeAnimator<this, number, number | string>; @AttributeAnimator({attributeName: "selected", type: Boolean}) readonly selected!: AttributeAnimator<this, boolean, boolean | string>; @AttributeAnimator({attributeName: "title", type: String}) readonly title!: AttributeAnimator<this, string>; @AttributeAnimator({attributeName: "type", type: String}) readonly type!: AttributeAnimator<this, string>; @AttributeAnimator({attributeName: "value", type: String}) readonly value!: AttributeAnimator<this, string>; protected override onApplyTheme(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean): void { super.onApplyTheme(theme, mood, timing); if (this.node.hasAttribute("swim-theme")) { this.applyRootTheme(theme, mood, timing); } } /** @internal */ applyRootTheme(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean): void { const font = theme.getOr(Look.font, Mood.ambient, null); if (font !== null) { if (font.style !== void 0) { this.fontStyle.setState(font.style, void 0, 0); } if (font.variant !== void 0) { this.fontVariant.setState(font.variant, void 0, 0); } if (font.weight !== void 0) { this.fontWeight.setState(font.weight, void 0, 0); } if (font.stretch !== void 0) { this.fontStretch.setState(font.stretch, void 0, 0); } if (font.size !== null) { this.fontSize.setState(font.size, void 0, 0); } if (font.height !== null) { this.lineHeight.setState(font.height, void 0, 0); } this.fontFamily.setState(font.family, void 0, 0); } this.backgroundColor.setState(theme.getOr(Look.backgroundColor, Mood.ambient, null), timing, Affinity.Intrinsic); this.color.setState(theme.getOr(Look.color, Mood.ambient, null), timing, Affinity.Intrinsic); } /** @internal */ static isPositioned(element: HTMLElement): boolean { const style = window.getComputedStyle(element); return style.position === "relative" || style.position === "absolute"; } isPositioned(): boolean { return HtmlView.isPositioned(this.node); } /** @internal */ static parentTransform(element: HTMLElement): Transform { if (HtmlView.isPositioned(element)) { const dx = element.offsetLeft; const dy = element.offsetTop; if (dx !== 0 || dy !== 0) { return Transform.translate(-dx, -dy); } } return Transform.identity(); } /** @internal */ static pageTransform(element: HTMLElement): Transform { const parentNode = element.parentNode; if (parentNode instanceof HTMLElement) { return HtmlView.pageTransform(parentNode).transform(HtmlView.parentTransform(element)); } else { return Transform.identity(); } } override get parentTransform(): Transform { const transform = this.transform.value; if (transform !== null) { return transform; } else if (this.isPositioned()) { const dx = this.node.offsetLeft; const dy = this.node.offsetTop; if (dx !== 0 || dy !== 0) { return Transform.translate(-dx, -dy); } } return Transform.identity(); } override get pageTransform(): Transform { const parentView = this.parent; if (parentView !== null) { return parentView.pageTransform.transform(this.parentTransform); } else { const parentNode = this.node.parentNode; if (parentNode instanceof HTMLElement) { return HtmlView.pageTransform(parentNode).transform(this.parentTransform); } else { return Transform.identity(); } } } override on<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, event: HTMLElementEventMap[K]) => unknown, options?: AddEventListenerOptions | boolean): this; override on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this; override on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this { this.node.addEventListener(type, listener, options); return this; } override off<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, event: HTMLElementEventMap[K]) => unknown, options?: EventListenerOptions | boolean): this; override off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this; override off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this { this.node.removeEventListener(type, listener, options); return this; } /** @internal */ protected initAttributes(init: HtmlViewAttributesInit): void { if (init.autocomplete !== void 0) { this.autocomplete(init.autocomplete); } if (init.checked !== void 0) { this.checked(init.checked); } if (init.colspan !== void 0) { this.colspan(init.colspan); } if (init.disabled !== void 0) { this.disabled(init.disabled); } if (init.placeholder !== void 0) { this.placeholder(init.placeholder); } if (init.rowspan !== void 0) { this.rowspan(init.rowspan); } if (init.selected !== void 0) { this.selected(init.selected); } if (init.title !== void 0) { this.title(init.title); } if (init.type !== void 0) { this.type(init.type); } if (init.value !== void 0) { this.value(init.value); } } /** @internal */ protected initStyle(init: HtmlViewStyleInit): void { StyleMap.init(this, init); } override init(init: HtmlViewInit): void { super.init(init); if (init.attributes !== void 0) { this.initAttributes(init.attributes); } if (init.style !== void 0) { this.initStyle(init.style); } } static override readonly tag: string = "div"; static override create<S extends abstract new (...args: any) => InstanceType<S>>(this: S): InstanceType<S>; static override create(): HtmlView; static override create(): HtmlView { return this.fromTag(this.tag); } static override fromTag(tag: "style"): StyleView; static override fromTag(tag: "svg"): SvgView; static override fromTag<S extends abstract new (...args: any) => InstanceType<S>>(this: S, tag: string): InstanceType<S>; static override fromTag(tag: string): HtmlView; static override fromTag(tag: string): ElementView { if (tag === "style" && this !== StyleView) { return StyleView.create(); } else if (tag === "svg") { return SvgView.create(); } else { const node = document.createElement(tag); return this.fromNode(node); } } static override fromNode<S extends new (node: HTMLElement) => InstanceType<S>>(this: S, node: ViewNodeType<InstanceType<S>>): InstanceType<S>; static override fromNode(node: HTMLElement): HtmlView; static override fromNode(node: HTMLElement): HtmlView { let view = (node as ViewHtml).view; if (view === void 0) { view = new this(node); this.mount(view); } else if (!(view instanceof this)) { throw new TypeError(view + " not an instance of " + this); } return view; } static override fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnyHtmlView<InstanceType<S>>): InstanceType<S>; static override fromAny(value: AnyHtmlView | string): HtmlView; static override fromAny(value: AnyHtmlView | string): HtmlView { if (value === void 0 || value === null) { return value; } else if (value instanceof View) { if (value instanceof this) { return value; } else { throw new TypeError(value + " not an instance of " + this); } } else if (value instanceof Node) { return this.fromNode(value); } else if (typeof value === "string") { return this.fromTag(value); } else if (Creatable.is(value)) { return value.create(); } else { return this.fromInit(value); } } static forTag<S extends abstract new (...args: any) => InstanceType<S>>(this: S, tag: string): HtmlViewFactory<InstanceType<S>>; static forTag(tag: string): HtmlViewFactory; static forTag(tag: string): HtmlViewFactory { if (tag === this.tag) { return this; } else { return new HtmlViewTagFactory(this, tag); } } } /** @public */ export interface HtmlView extends StyleMap { applyTheme(theme: ThemeMatrix, mood: MoodVector, timing?: AnyTiming | boolean): void; requireUpdate(updateFlags: ViewFlags, immediate?: boolean): void; } StyleMap.define(HtmlView.prototype); /** @internal */ export class HtmlViewTagFactory<V extends HtmlView> implements HtmlViewFactory<V> { constructor(factory: HtmlViewFactory<V>, tag: string) { this.factory = factory; this.tag = tag; } /** @internal */ readonly factory: HtmlViewFactory<V>; readonly tag: string; create(): V { return this.fromTag(this.tag); } fromTag(tag: string): V { const node = document.createElement(tag); return this.fromNode(node as ViewNodeType<V>); } fromNode(node: ViewNodeType<V>): V { return this.factory.fromNode(node); } fromInit(init: InitType<V>): V { let type = init.type; if (type === void 0) { type = this; } const view = type.create() as V; view.init(init); return view; } fromAny(value: AnyHtmlView<V>): V { return this.factory.fromAny(value); } }
the_stack
'use strict' import { FunctionDefinitionAstNode, ModifierDefinitionAstNode, ParameterListAstNode, ForStatementAstNode, WhileStatementAstNode, VariableDeclarationAstNode, ContractDefinitionAstNode, InheritanceSpecifierAstNode, MemberAccessAstNode, BinaryOperationAstNode, FunctionCallAstNode, ExpressionStatementAstNode, UnaryOperationAstNode, IdentifierAstNode, IndexAccessAstNode, BlockAstNode, AssignmentAstNode, InlineAssemblyAstNode, IfStatementAstNode, CompiledContractObj, ABIParameter, CompiledContract } from '../../types' import { util } from '@remix-project/remix-lib' type SpecialObjDetail = { obj: string member: string type: string } const nodeTypes: Record<string, string> = { SOURCEUNIT: 'SourceUnit', PRAGMADIRECTIVE: 'PragmaDirective', IMPORTDIRECTIVE: 'ImportDirective', CONTRACTDEFINITION: 'ContractDefinition', INHERITANCESPECIFIER: 'InheritanceSpecifier', USINGFORDIRECTIVE: 'UsingForDirective', STRUCTDEFINITION: 'StructDefinition', ENUMDEFINITION: 'EnumDefinition', ENUMVALUE: 'EnumValue', PARAMETERLIST: 'ParameterList', OVERRIDESPECIFIER: 'OverrideSpecifier', FUNCTIONDEFINITION: 'FunctionDefinition', VARIABLEDECLARATION: 'VariableDeclaration', MODIFIERDEFINITION: 'ModifierDefinition', MODIFIERINVOCATION: 'ModifierInvocation', EVENTDEFINITION: 'EventDefinition', ELEMENTARYTYPENAME: 'ElementaryTypeName', USERDEFINEDTYPENAME: 'UserDefinedTypeName', FUNCTIONTYPENAME: 'FunctionTypeName', MAPPING: 'Mapping', ARRAYTYPENAME: 'ArrayTypeName', INLINEASSEMBLY: 'InlineAssembly', BLOCK: 'Block', PLACEHOLDERSTATEMENT: 'PlaceholderStatement', IFSTATEMENT: 'IfStatement', TRYCATCHCLAUSE: 'TryCatchClause', TRYSTATEMENT: 'TryStatement', WHILESTATEMENT: 'WhileStatement', DOWHILESTATEMENT: 'DoWhileStatement', FORSTATEMENT: 'ForStatement', CONTINUE: 'Continue', BREAK: 'Break', RETURN: 'Return', THROW: 'Throw', EMITSTATEMENT: 'EmitStatement', VARIABLEDECLARATIONSTATEMENT: 'VariableDeclarationStatement', EXPRESSIONSTATEMENT: 'ExpressionStatement', CONDITIONAL: 'Conditional', ASSIGNMENT: 'Assignment', TUPLEEXPRESSION: 'TupleExpression', UNARYOPERATION: 'UnaryOperation', BINARYOPERATION: 'BinaryOperation', FUNCTIONCALL: 'FunctionCall', FUNCTIONCALLOPTIONS: 'FunctionCallOptions', NEWEXPRESSION: 'NewExpression', MEMBERACCESS: 'MemberAccess', INDEXACCESS: 'IndexAccess', INDEXRANGEACCESS: 'IndexRangeAccess', ELEMENTARYTYPENAMEEXPRESSION: 'ElementaryTypeNameExpression', LITERAL: 'Literal', IDENTIFIER: 'Identifier', STRUCTUREDDOCUMENTATION: 'StructuredDocumentation' } const basicTypes: Record<string, string> = { UINT: 'uint256', BOOL: 'bool', ADDRESS: 'address', PAYABLE_ADDRESS: 'address payable', BYTES32: 'bytes32', STRING_MEM: 'string memory', BYTES_MEM: 'bytes memory', BYTES4: 'bytes4' } const basicRegex: Record<string, string> = { CONTRACTTYPE: '^contract ', FUNCTIONTYPE: '^function \\(', EXTERNALFUNCTIONTYPE: '^function \\(.*\\).* external', CONSTANTFUNCTIONTYPE: '^function \\(.*\\).* (view|pure)', REFTYPE: '(storage)|(mapping\\()|(\\[\\])', FUNCTIONSIGNATURE: '^function \\(([^\\(]*)\\)', LIBRARYTYPE: '^type\\(library (.*)\\)' } const basicFunctionTypes: Record<string, string> = { SEND: buildFunctionSignature([basicTypes.UINT], [basicTypes.BOOL], false), 'CALL-0.4': buildFunctionSignature([], [basicTypes.BOOL], true), CALL: buildFunctionSignature([basicTypes.BYTES_MEM], [basicTypes.BOOL, basicTypes.BYTES_MEM], true), 'DELEGATECALL-0.4': buildFunctionSignature([], [basicTypes.BOOL], false), DELEGATECALL: buildFunctionSignature([basicTypes.BYTES_MEM], [basicTypes.BOOL, basicTypes.BYTES_MEM], false), TRANSFER: buildFunctionSignature([basicTypes.UINT], [], false) } const builtinFunctions: Record<string, boolean> = { 'keccak256()': true, 'sha3()': true, 'sha256()': true, 'ripemd160()': true, 'ecrecover(bytes32,uint8,bytes32,bytes32)': true, 'addmod(uint256,uint256,uint256)': true, 'mulmod(uint256,uint256,uint256)': true, 'selfdestruct(address)': true, 'selfdestruct(address payable)': true, 'revert()': true, 'revert(string memory)': true, 'assert(bool)': true, 'require(bool)': true, 'require(bool,string memory)': true, 'gasleft()': true, 'blockhash(uint256)': true, 'address(address)': true } const lowLevelCallTypes: Record<string, Record<string, string>> = { 'CALL-0.4': { ident: 'call', type: basicFunctionTypes['CALL-0.4'] }, CALL: { ident: 'call', type: basicFunctionTypes.CALL }, CALLCODE: { ident: 'callcode', type: basicFunctionTypes['CALL-0.4'] }, 'DELEGATECALL-0.4': { ident: 'delegatecall', type: basicFunctionTypes['DELEGATECALL-0.4'] }, DELEGATECALL: { ident: 'delegatecall', type: basicFunctionTypes.DELEGATECALL }, SEND: { ident: 'send', type: basicFunctionTypes.SEND }, TRANSFER: { ident: 'transfer', type: basicFunctionTypes.TRANSFER } } const specialVariables: Record<string, SpecialObjDetail> = { BLOCKTIMESTAMP: { obj: 'block', member: 'timestamp', type: basicTypes.UINT }, BLOCKHASH: { obj: 'block', member: 'blockhash', type: buildFunctionSignature([basicTypes.UINT], [basicTypes.BYTES32], false, 'view') } } const abiNamespace: Record<string, SpecialObjDetail> = { ENCODE: { obj: 'abi', member: 'encode', type: buildFunctionSignature([], [basicTypes.BYTES_MEM], false, 'pure') }, ENCODEPACKED: { obj: 'abi', member: 'encodePacked', type: buildFunctionSignature([], [basicTypes.BYTES_MEM], false, 'pure') }, ENCODE_SELECT: { obj: 'abi', member: 'encodeWithSelector', type: buildFunctionSignature([basicTypes.BYTES4], [basicTypes.BYTES_MEM], false, 'pure') }, ENCODE_SIG: { obj: 'abi', member: 'encodeWithSignature', type: buildFunctionSignature([basicTypes.STRING_MEM], [basicTypes.BYTES_MEM], false, 'pure') } } // #################### Trivial Getters // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function getType (node: any): string { return node.typeDescriptions.typeString } // #################### Complex Getters /** * Returns the type parameter of function call AST nodes. Throws if not a function call node * @func {ASTNode} Function call node * @return {string} type of function call */ function getFunctionCallType (func: FunctionCallAstNode): string { return getType(func.expression) } /** * Get the variable name written to by a effect node, except for inline assembly because there is no information to find out where we write to. Trows if not a effect node or is inlineassmbly. * Example: x = 10; => x * @effectNode {ASTNode} Assignmnet node * @return {string} variable name written to */ function getEffectedVariableName (effectNode: AssignmentAstNode | UnaryOperationAstNode): string { if (!isEffect(effectNode)) throw new Error('staticAnalysisCommon.js: not an effect Node') if (effectNode.nodeType === 'Assignment' || effectNode.nodeType === 'UnaryOperation') { const IdentNode: IdentifierAstNode = findFirstSubNodeLTR(effectNode, exactMatch(nodeTypes.IDENTIFIER)) return IdentNode.name } else throw new Error('staticAnalysisCommon.js: wrong node type') } /** * Returns the identifier of a local call, Throws on wrong node. * Example: f(103) => f * @localCallNode {ASTNode} Function call node * @return {string} name of the function called */ function getLocalCallName (localCallNode: FunctionCallAstNode): string { if (!isLocalCall(localCallNode) && !isAbiNamespaceCall(localCallNode)) throw new Error('staticAnalysisCommon.js: not a local call Node') return localCallNode.expression.name } /** * Returns the identifier of a this local call, Throws on wrong node. * Example: this.f(103) => f * @localCallNode {ASTNode} Function call node * @return {string} name of the function called */ function getThisLocalCallName (thisLocalCallNode: FunctionCallAstNode): string { if (!isThisLocalCall(thisLocalCallNode.expression)) throw new Error('staticAnalysisCommon.js: not a this local call Node') return thisLocalCallNode.expression.memberName } /** * Returns the identifier of a super local call, Throws on wrong node. * Example: super.f(103) => f * @localCallNode {ASTNode} Function call node * @return {string} name of the function called */ function getSuperLocalCallName (superLocalCallNode: FunctionCallAstNode): string { if (!isSuperLocalCall(superLocalCallNode.expression)) throw new Error('staticAnalysisCommon.js: not a super local call Node') return superLocalCallNode.expression.memberName } /** * Returns the contract type of a external direct call, Throws on wrong node. * Example: * foo x = foo(0xdeadbeef...); * x.f(103) => foo * @extDirectCall {ASTNode} Function call node * @return {string} name of the contract the function is defined in */ function getExternalDirectCallContractName (extDirectCall: FunctionCallAstNode): string { if (!isExternalDirectCall(extDirectCall)) throw new Error('staticAnalysisCommon.js: not an external direct call Node') return extDirectCall.expression.expression.typeDescriptions.typeString.replace(new RegExp(basicRegex.CONTRACTTYPE), '') } /** * Returns the name of the contract of a this local call (current contract), Throws on wrong node. * Example: * Contract foo { * ... * this.f(103) => foo * ... * @thisLocalCall {ASTNode} Function call node * @return {string} name of the contract the function is defined in */ function getThisLocalCallContractName (thisLocalCall: FunctionCallAstNode): string { if (!isThisLocalCall(thisLocalCall.expression)) throw new Error('staticAnalysisCommon.js: not a this local call Node') return thisLocalCall.expression.expression.typeDescriptions.typeString.replace(new RegExp(basicRegex.CONTRACTTYPE), '') } /** * Returns the function identifier of a external direct call, Throws on wrong node. * Example: * foo x = foo(0xdeadbeef...); * x.f(103) => f * @extDirectCall {ASTNode} Function call node * @return {string} name of the function called */ function getExternalDirectCallMemberName (extDirectCall: FunctionCallAstNode): string { if (!isExternalDirectCall(extDirectCall)) throw new Error('staticAnalysisCommon.js: not an external direct call Node') return extDirectCall.expression.memberName } /** * Returns the name of a contract, Throws on wrong node. * Example: * Contract foo { => foo * @contract {ASTNode} Contract Definition node * @return {string} name of a contract defined */ function getContractName (contract: ContractDefinitionAstNode): string { if (!nodeType(contract, exactMatch(nodeTypes.CONTRACTDEFINITION))) throw new Error('staticAnalysisCommon.js: not a ContractDefinition Node') return contract.name } /** * Returns the name of a function definition, Throws on wrong node. * Example: * func foo(uint bla) { => foo * @funcDef {ASTNode} Function Definition node * @return {string} name of a function defined */ function getFunctionDefinitionName (funcDef: FunctionDefinitionAstNode): string { if (!nodeType(funcDef, exactMatch(nodeTypes.FUNCTIONDEFINITION))) throw new Error('staticAnalysisCommon.js: not a FunctionDefinition Node') return funcDef.name } /** * Returns the identifier of an inheritance specifier, Throws on wrong node. * Example: * contract KingOfTheEtherThrone is b { => b * @func {ASTNode} Inheritance specifier * @return {string} name of contract inherited from */ function getInheritsFromName (inheritsNode: InheritanceSpecifierAstNode): string { if (!nodeType(inheritsNode, exactMatch(nodeTypes.INHERITANCESPECIFIER))) throw new Error('staticAnalysisCommon.js: not an InheritanceSpecifier Node') return inheritsNode.baseName.name } /** * Returns the identifier of a variable definition, Throws on wrong node. * Example: * var x = 10; => x * @varDeclNode {ASTNode} Variable declaration node * @return {string} variable name */ function getDeclaredVariableName (varDeclNode: VariableDeclarationAstNode): string { if (!nodeType(varDeclNode, exactMatch(nodeTypes.VARIABLEDECLARATION))) throw new Error('staticAnalysisCommon.js: not a VariableDeclaration Node') return varDeclNode.name } /** * Returns the type of a variable definition, Throws on wrong node. * Example: * var x = 10; => x * @varDeclNode {ASTNode} Variable declaration node * @return {string} variable type */ function getDeclaredVariableType (varDeclNode: VariableDeclarationAstNode): string { return varDeclNode.typeName.name } /** * Returns state variable declaration nodes for a contract, Throws on wrong node. * Example: * contract foo { * ... * var y = true; * var x = 10; => [y,x] * @contractNode {ASTNode} Contract Definition node * @return {list variable declaration} state variable node list */ function getStateVariableDeclarationsFromContractNode (contractNode: ContractDefinitionAstNode): VariableDeclarationAstNode[] { return contractNode.nodes.filter(el => el.nodeType === 'VariableDeclaration') } /** * Returns parameter node for a function or modifier definition, Throws on wrong node. * Example: * function bar(uint a, uint b) => uint a, uint b * @funcNode {ASTNode} Contract Definition node * @return {parameterlist node} parameterlist node */ function getFunctionOrModifierDefinitionParameterPart (funcNode: FunctionDefinitionAstNode | ModifierDefinitionAstNode): ParameterListAstNode { if (!nodeTypeIn(funcNode, [exactMatch(nodeTypes.FUNCTIONDEFINITION), exactMatch(nodeTypes.MODIFIERDEFINITION)])) throw new Error('staticAnalysisCommon.js: not a FunctionDefinition or ModifierDefinition Node') return funcNode.parameters } /** * Returns return parameter node for a function or modifier definition, Throws on wrong node. * Example: * function bar(uint a, uint b) returns (bool a, bool b) => bool a, bool b * @funcNode {ASTNode} Contract Definition node * @return {parameterlist node} parameterlist node */ function getFunctionDefinitionReturnParameterPart (funcNode: FunctionDefinitionAstNode): ParameterListAstNode { return funcNode.returnParameters } /** * Extracts the parameter types for a function type signature * Example: * function(uint a, uint b) returns (bool) => uint a, uint b * @func {ASTNode} function call node * @return {string} parameter signature */ function getFunctionCallTypeParameterType (func: FunctionCallAstNode): string | undefined { const type: string = getFunctionCallType(func) if (type.startsWith('function (')) { let paramTypes = '' let openPar = 1 for (let x = 10; x < type.length; x++) { const c: string = type.charAt(x) if (c === '(') openPar++ else if (c === ')') openPar-- if (openPar === 0) return paramTypes paramTypes += c } } else { throw new Error('staticAnalysisCommon.js: cannot extract parameter types from function call') } } /** * Returns the name of the library called, Throws on wrong node. * Example: * library set{...} * contract foo { * ... * function () { set.union() => set} * @funcCall {ASTNode} function call node * @return {string} name of the lib defined */ function getLibraryCallContractName (node: FunctionCallAstNode): string | undefined { if (!isLibraryCall(node.expression)) throw new Error('staticAnalysisCommon.js: not a library call Node') const types: RegExpExecArray | null = new RegExp(basicRegex.LIBRARYTYPE).exec(node.expression.expression.typeDescriptions.typeString) if (types) { return types[1] } } /** * Returns the name of the function of a library call, Throws on wrong node. * Example: * library set{...} * contract foo { * ... * function () { set.union() => uinion} * @func {ASTNode} function call node * @return {string} name of function called on the library */ function getLibraryCallMemberName (funcCall: FunctionCallAstNode): string { if (!isLibraryCall(funcCall.expression)) throw new Error('staticAnalysisCommon.js: not a library call Node') return funcCall.expression.memberName } /** * Returns full qualified name for a function call, Throws on wrong node. * Example: * contract foo { * ... * function bar(uint b) { } * function baz() { * bar(10) => foo.bar(uint) * @func {ASTNode} function call node * @func {ASTNode} contract defintion * @return {string} full qualified identifier for the function call */ function getFullQualifiedFunctionCallIdent (contract: ContractDefinitionAstNode, func: FunctionCallAstNode): string { if (isLocalCall(func)) return getContractName(contract) + '.' + getLocalCallName(func) + '(' + getFunctionCallTypeParameterType(func) + ')' else if (isThisLocalCall(func.expression)) return getThisLocalCallContractName(func) + '.' + getThisLocalCallName(func) + '(' + getFunctionCallTypeParameterType(func) + ')' else if (isSuperLocalCall(func.expression)) return getContractName(contract) + '.' + getSuperLocalCallName(func) + '(' + getFunctionCallTypeParameterType(func) + ')' else if (isExternalDirectCall(func)) return getExternalDirectCallContractName(func) + '.' + getExternalDirectCallMemberName(func) + '(' + getFunctionCallTypeParameterType(func) + ')' else if (isLibraryCall(func.expression)) return getLibraryCallContractName(func) + '.' + getLibraryCallMemberName(func) + '(' + getFunctionCallTypeParameterType(func) + ')' else throw new Error('staticAnalysisCommon.js: Can not get function name from non function call node') } function getFullQuallyfiedFuncDefinitionIdent (contract: ContractDefinitionAstNode, func: FunctionDefinitionAstNode, paramTypes: any[]): string { return getContractName(contract) + '.' + getFunctionDefinitionName(func) + '(' + util.concatWithSeperator(paramTypes, ',') + ')' } function getUnAssignedTopLevelBinOps (subScope: BlockAstNode | IfStatementAstNode | WhileStatementAstNode | ForStatementAstNode): ExpressionStatementAstNode[] { let result: ExpressionStatementAstNode[] = [] if (subScope && subScope.nodeType === 'Block') result = subScope.statements.filter(isBinaryOpInExpression) // for 'without braces' loops else if (subScope && subScope.nodeType && subScope.nodeType !== 'Block' && isSubScopeStatement(subScope)) { if (subScope.nodeType === 'IfStatement') { if ((subScope.trueBody && subScope.trueBody.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(subScope.trueBody))) { result.push(subScope.trueBody) } if (subScope.falseBody && subScope.falseBody.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(subScope.falseBody)) { result.push(subScope.falseBody) } } else { if (subScope.body && subScope.body.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(subScope.body)) { result.push(subScope.body) } } } return result } // #################### Trivial Node Identification // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function isStatement (node: any): boolean { return nodeType(node, 'Statement$') || node.nodeType === 'Block' || node.nodeType === 'Return' } // #################### Complex Node Identification /** * True if function defintion has function body * @funcNode {ASTNode} function defintion node * @return {bool} */ function hasFunctionBody (funcNode: FunctionDefinitionAstNode): boolean { return funcNode.body !== null } /** * True if node is a delete instruction of a dynamic array * @node {ASTNode} node to check for * @return {bool} */ function isDeleteOfDynamicArray (node: UnaryOperationAstNode): boolean { return isDeleteUnaryOperation(node) && isDynamicArrayAccess(node.subExpression) } /** * True if node is node is a ref to a dynamic array * @node {ASTNode} node to check for * @return {bool} */ function isDynamicArrayAccess (node: IdentifierAstNode): boolean { return getType(node).endsWith('[] storage ref') || typeDescription(node, 'bytes storage ref') || typeDescription(node, 'string storage ref') } /** * True if node accesses 'length' member of dynamic array * @node {ASTNode} node to check for * @return {bool} */ function isDynamicArrayLengthAccess (node: MemberAccessAstNode): boolean { return (node.memberName === 'length') && // accessing 'length' member node.expression.typeDescriptions.typeString.indexOf('[]') !== -1 // member is accessed from dynamic array, notice [] without any number } /** * True if node is a delete instruction for an element from a dynamic array * @node {ASTNode} node to check for * @return {bool} */ function isDeleteFromDynamicArray (node: UnaryOperationAstNode): boolean { return isDeleteUnaryOperation(node) && node.subExpression.nodeType === 'IndexAccess' } /** * True if node is the access of a mapping index * @node {ASTNode} node to check for * @return {bool} */ function isMappingIndexAccess (node: IndexAccessAstNode): boolean { return node.typeDescriptions.typeString.startsWith('mapping') } /** * True if call to code within the current contracts context including (delegate) library call * @node {ASTNode} some AstNode * @return {bool} */ function isLocalCallGraphRelevantNode (node: FunctionCallAstNode): boolean { return ((isLocalCall(node) || isSuperLocalCall(node.expression) || isLibraryCall(node.expression)) && !isBuiltinFunctionCall(node)) } /** * True if is builtin function like assert, sha3, erecover, ... * @node {ASTNode} some AstNode * @return {bool} */ function isBuiltinFunctionCall (node: FunctionCallAstNode): boolean { return (node.nodeType === 'FunctionCall' && isLocalCall(node) && builtinFunctions[getLocalCallName(node) + '(' + getFunctionCallTypeParameterType(node) + ')'] === true) || isAbiNamespaceCall(node) } /** * True if is builtin function like assert, sha3, erecover, ... * @node {ASTNode} some AstNode * @return {bool} */ function isAbiNamespaceCall (node: FunctionCallAstNode): boolean { return Object.keys(abiNamespace).some((key) => Object.prototype.hasOwnProperty.call(abiNamespace, key) && node.expression && isSpecialVariableAccess(node.expression, abiNamespace[key])) } /** * True if node is a call to selfdestruct * @node {ASTNode} some AstNode * @return {bool} */ function isSelfdestructCall (node: FunctionCallAstNode): boolean { return isBuiltinFunctionCall(node) && getLocalCallName(node) === 'selfdestruct' } /** * True if node is a call to builtin assert(bool) * @node {ASTNode} some AstNode * @return {bool} */ function isAssertCall (node: FunctionCallAstNode): boolean { return isBuiltinFunctionCall(node) && getLocalCallName(node) === 'assert' } /** * True if node is a call to builtin require(bool) * @node {ASTNode} some AstNode * @return {bool} */ function isRequireCall (node: FunctionCallAstNode): boolean { return isBuiltinFunctionCall(node) && getLocalCallName(node) === 'require' } /** * True if is storage variable declaration * @node {ASTNode} some AstNode * @return {bool} */ function isStorageVariableDeclaration (node: VariableDeclarationAstNode): boolean { return node.storageLocation === 'storage' && new RegExp(basicRegex.REFTYPE).test(node.typeDescriptions.typeIdentifier) } /** * True if is interaction with external contract (change in context, no delegate calls) (send, call of other contracts) * @node {ASTNode} some AstNode * @return {bool} */ function isInteraction (node: FunctionCallAstNode): boolean { return isLLCall(node.expression) || isLLSend(node.expression) || isExternalDirectCall(node) || isTransfer(node.expression) || isLLCall04(node.expression) || isLLSend04(node.expression) || // to cover case of address.call.value.gas , See: inheritance.sol (node.expression && node.expression.expression && isLLCall(node.expression.expression)) || (node.expression && node.expression.expression && isLLCall04(node.expression.expression)) } /** * True if node changes state of a variable or is inline assembly (does not include check if it is a global state change, on a state variable) * @node {ASTNode} some AstNode * @return {bool} */ function isEffect (node: AssignmentAstNode | UnaryOperationAstNode | InlineAssemblyAstNode): boolean { return node.nodeType === 'Assignment' || (node.nodeType === 'UnaryOperation' && (isPlusPlusUnaryOperation(node) || isMinusMinusUnaryOperation(node))) || node.nodeType === 'InlineAssembly' } /** * True if node changes state of a variable or is inline assembly (Checks if variable is a state variable via provided list) * @node {ASTNode} some AstNode * @node {list Variable declaration} state variable declaration currently in scope * @return {bool} */ function isWriteOnStateVariable (effectNode: AssignmentAstNode | InlineAssemblyAstNode | UnaryOperationAstNode, stateVariables: VariableDeclarationAstNode[]): boolean { return effectNode.nodeType === 'InlineAssembly' || (isEffect(effectNode) && isStateVariable(getEffectedVariableName(effectNode), stateVariables)) } /** * True if there is a variable with name, name in stateVariables * @node {ASTNode} some AstNode * @node {list Variable declaration} state variable declaration currently in scope * @return {bool} */ function isStateVariable (name: string, stateVariables: VariableDeclarationAstNode[]): boolean { return stateVariables.some((item: VariableDeclarationAstNode) => item.stateVariable && name === getDeclaredVariableName(item)) } /** * True if is function defintion that is flaged as constant * @node {ASTNode} some AstNode * @return {bool} */ function isConstantFunction (node: FunctionDefinitionAstNode): boolean { return node.stateMutability === 'view' || node.stateMutability === 'pure' } /** * True if variable decalaration is converted into a getter method * @node {ASTNode} variable declaration AstNode * @return {bool} */ function isVariableTurnedIntoGetter (varDeclNode: VariableDeclarationAstNode): boolean { return varDeclNode.stateVariable && varDeclNode.visibility === 'public' } /** * True if is function defintion has payable modifier * @node {ASTNode} some AstNode * @return {bool} */ function isPayableFunction (node: FunctionDefinitionAstNode): boolean { return node.stateMutability === 'payable' } /** * True if is constructor * @node {ASTNode} some AstNode * @return {bool} */ function isConstructor (node: FunctionDefinitionAstNode): boolean { return node.kind === 'constructor' } /** * True if node is integer division that truncates (not only int literals since those yield a rational value) * @node {ASTNode} some AstNode * @return {bool} */ function isIntDivision (node: BinaryOperationAstNode): boolean { return operator(node, exactMatch(util.escapeRegExp('/'))) && typeDescription(node.rightExpression, util.escapeRegExp('int')) } /** * True if is block / SubScope has top level binops (e.g. that are not assigned to anything, most of the time confused compare instead of assign) * @node {ASTNode} some AstNode * @return {bool} */ function isSubScopeWithTopLevelUnAssignedBinOp (node: BlockAstNode | IfStatementAstNode | WhileStatementAstNode | ForStatementAstNode): boolean | undefined { if (node.nodeType === 'Block') return node.statements.some(isBinaryOpInExpression) // for 'without braces' loops else if (node && node.nodeType && isSubScopeStatement(node)) { if (node.nodeType === 'IfStatement') { return (node.trueBody && node.trueBody.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(node.trueBody)) || (node.falseBody && node.falseBody.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(node.falseBody)) } else { return node.body && node.body.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(node.body) } } } function isSubScopeStatement (node: IfStatementAstNode | WhileStatementAstNode | ForStatementAstNode): boolean { if (node.nodeType === 'IfStatement') { return (node.trueBody && node.trueBody.nodeType && !nodeType(node.trueBody, exactMatch(nodeTypes.BLOCK))) || (node.falseBody && node.falseBody.nodeType && !nodeType(node.falseBody, exactMatch(nodeTypes.BLOCK))) } else { return node.body && node.body.nodeType && !nodeType(node.body, exactMatch(nodeTypes.BLOCK)) } } /** * True if binary operation inside of expression statement * @node {ASTNode} some AstNode * @return {bool} */ function isBinaryOpInExpression (node: ExpressionStatementAstNode): boolean { return node.nodeType === 'ExpressionStatement' && node.expression.nodeType === 'BinaryOperation' } /** * True if unary increment operation * @node {ASTNode} some AstNode * @return {bool} */ function isPlusPlusUnaryOperation (node: UnaryOperationAstNode): boolean { return node.operator === '++' } /** * True if unary delete operation * @node {ASTNode} some AstNode * @return {bool} */ function isDeleteUnaryOperation (node: UnaryOperationAstNode): boolean { return node.operator === 'delete' } /** * True if unary decrement operation * @node {ASTNode} some AstNode * @return {bool} */ function isMinusMinusUnaryOperation (node: UnaryOperationAstNode): boolean { return node.operator === '--' } /** * True if all functions on a contract are implemented * @node {ASTNode} some AstNode * @return {bool} */ function isFullyImplementedContract (node: ContractDefinitionAstNode): boolean { return node.fullyImplemented === true } /** * True if it is a library contract defintion * @node {ASTNode} some AstNode * @return {bool} */ function isLibrary (node: ContractDefinitionAstNode): boolean { return node.contractKind === 'library' } /** * True if it is a local call to non const function * @node {ASTNode} some AstNode * @return {bool} */ function isCallToNonConstLocalFunction (node: FunctionCallAstNode): boolean { return isLocalCall(node) && !expressionTypeDescription(node, basicRegex.CONSTANTFUNCTIONTYPE) } /** * True if it is a call to a library * @node {ASTNode} some AstNode * @return {bool} */ function isLibraryCall (node: MemberAccessAstNode): boolean { return isMemberAccess(node, basicRegex.FUNCTIONTYPE, undefined, basicRegex.LIBRARYTYPE, undefined) } /** * True if it is an external call via defined interface (not low level call) * @node {ASTNode} some AstNode * @return {bool} */ function isExternalDirectCall (node: FunctionCallAstNode): boolean { return isMemberAccess(node.expression, basicRegex.EXTERNALFUNCTIONTYPE, undefined, basicRegex.CONTRACTTYPE, undefined) && !isThisLocalCall(node.expression) && !isSuperLocalCall(node.expression) } /** * True if access to block.timestamp via now alias * @node {ASTNode} some AstNode * @return {bool} */ function isNowAccess (node: IdentifierAstNode): boolean { return node.name === 'now' && typeDescription(node, exactMatch(basicTypes.UINT)) } /** * True if access to block.timestamp via now alias * @node {ASTNode} some AstNode * @return {bool} */ function isTxOriginAccess (node: MemberAccessAstNode): boolean { return isMemberAccess(node, 'address', 'tx', 'tx', 'origin') } /** * True if access to block.timestamp * @node {ASTNode} some AstNode * @return {bool} */ function isBlockTimestampAccess (node: MemberAccessAstNode): boolean { return isSpecialVariableAccess(node, specialVariables.BLOCKTIMESTAMP) } /** * True if access to block.blockhash * @node {ASTNode} some AstNode * @return {bool} */ function isBlockBlockHashAccess (node: FunctionCallAstNode): boolean { return (isBuiltinFunctionCall(node) && getLocalCallName(node) === 'blockhash') || isSpecialVariableAccess(node.expression, specialVariables.BLOCKHASH) } /** * True if call to local function via this keyword * @node {ASTNode} some AstNode * @return {bool} */ function isThisLocalCall (node: MemberAccessAstNode): boolean { return isMemberAccess(node, basicRegex.FUNCTIONTYPE, exactMatch('this'), basicRegex.CONTRACTTYPE, undefined) } /** * True if access to local function via super keyword * @node {ASTNode} some AstNode * @return {bool} */ function isSuperLocalCall (node: MemberAccessAstNode): boolean { return isMemberAccess(node, basicRegex.FUNCTIONTYPE, exactMatch('super'), basicRegex.CONTRACTTYPE, undefined) } /** * True if call to local function * @node {ASTNode} some AstNode * @return {bool} */ function isLocalCall (node: FunctionCallAstNode): boolean { return node.nodeType === 'FunctionCall' && node.kind === 'functionCall' && node.expression.nodeType === 'Identifier' && expressionTypeDescription(node, basicRegex.FUNCTIONTYPE) && !expressionTypeDescription(node, basicRegex.EXTERNALFUNCTIONTYPE) } /** * True if low level call (send, call, delegatecall, callcode) * @node {ASTNode} some AstNode * @return {bool} */ function isLowLevelCall (node: MemberAccessAstNode): boolean { return isLLCall(node) || isLLDelegatecall(node) || isLLSend(node) || isLLSend04(node) || isLLCallcode(node) || isLLCall04(node) || isLLDelegatecall04(node) } /** * True if low level send (solidity < 0.5) * @node {ASTNode} some AstNode * @return {bool} */ function isLLSend04 (node: MemberAccessAstNode): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.SEND.type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.SEND.ident)) } /** * True if low level send (solidity >= 0.5) * @node {ASTNode} some AstNode * @return {bool} */ function isLLSend (node: MemberAccessAstNode): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.SEND.type)), undefined, exactMatch(basicTypes.PAYABLE_ADDRESS), exactMatch(lowLevelCallTypes.SEND.ident)) } /** * True if low level call * @node {ASTNode} some AstNode * @return {bool} */ function isLLCall (node: MemberAccessAstNode): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.CALL.type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALL.ident)) || isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.CALL.type)), undefined, exactMatch(basicTypes.PAYABLE_ADDRESS), exactMatch(lowLevelCallTypes.CALL.ident)) } /** * True if low level payable call (solidity < 0.5) * @node {ASTNode} some AstNode * @return {bool} */ function isLLCall04 (node: MemberAccessAstNode): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes['CALL-0.4'].type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes['CALL-0.4'].ident)) } /** * True if low level callcode * @node {ASTNode} some AstNode * @return {bool} */ function isLLCallcode (node: MemberAccessAstNode): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.CALLCODE.type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALLCODE.ident)) } /** * True if low level delegatecall * @node {ASTNode} some AstNode * @return {bool} */ function isLLDelegatecall (node: MemberAccessAstNode): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.DELEGATECALL.type)), undefined, matches(basicTypes.PAYABLE_ADDRESS, basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.DELEGATECALL.ident)) } /** * True if low level delegatecall (solidity < 0.5) * @node {ASTNode} some AstNode * @return {bool} */ function isLLDelegatecall04 (node: MemberAccessAstNode): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes['DELEGATECALL-0.4'].type)), undefined, matches(basicTypes.PAYABLE_ADDRESS, basicTypes.ADDRESS), exactMatch(lowLevelCallTypes['DELEGATECALL-0.4'].ident)) } /** * True if transfer call * @node {ASTNode} some AstNode * @return {bool} */ function isTransfer (node: MemberAccessAstNode): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.TRANSFER.type)), undefined, matches(basicTypes.ADDRESS, basicTypes.PAYABLE_ADDRESS), exactMatch(lowLevelCallTypes.TRANSFER.ident)) } function isStringToBytesConversion (node: FunctionCallAstNode): boolean { return isExplicitCast(node, util.escapeRegExp('string *'), util.escapeRegExp('bytes')) } function isExplicitCast (node: FunctionCallAstNode, castFromType: string, castToType: string): boolean { return node.kind === 'typeConversion' && nodeType(node.expression, exactMatch(nodeTypes.ELEMENTARYTYPENAMEEXPRESSION)) && node.expression.typeName === castToType && nodeType(node.arguments[0], exactMatch(nodeTypes.IDENTIFIER)) && typeDescription(node.arguments[0], castFromType) } function isBytesLengthCheck (node: MemberAccessAstNode): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(basicTypes.UINT)), undefined, util.escapeRegExp('bytes *'), 'length') } /** * True if it is a loop * @node {ASTNode} some AstNode * @return {bool} */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function isLoop (node: any): boolean { return nodeType(node, exactMatch(nodeTypes.FORSTATEMENT)) || nodeType(node, exactMatch(nodeTypes.WHILESTATEMENT)) || nodeType(node, exactMatch(nodeTypes.DOWHILESTATEMENT)) } // #################### Complex Node Identification - Private function isMemberAccess (node: MemberAccessAstNode, retType: string, accessor: string| undefined, accessorType: string, memberName: string | undefined): boolean { if (node && nodeType(node, exactMatch('MemberAccess'))) { const nodeTypeDef: boolean = typeDescription(node, retType) const nodeMemName: boolean = memName(node, memberName) const nodeExpMemName: boolean = memName(node.expression, accessor) const nodeExpTypeDef: boolean = expressionTypeDescription(node, accessorType) return nodeTypeDef && nodeMemName && nodeExpTypeDef && nodeExpMemName } else return false } function isSpecialVariableAccess (node: MemberAccessAstNode, varType: SpecialObjDetail): boolean { return isMemberAccess(node, exactMatch(util.escapeRegExp(varType.type)), varType.obj, varType.obj, varType.member) } // #################### Node Identification Primitives // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function expressionTypeDescription (node: any, typeRegex: string): boolean { return new RegExp(typeRegex).test(node.expression.typeDescriptions.typeString) } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function typeDescription (node: any, typeRegex: string): boolean { return new RegExp(typeRegex).test(node.typeDescriptions.typeString) } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function nodeType (node: any, typeRegex: string): boolean { return new RegExp(typeRegex).test(node.nodeType) } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function nodeTypeIn (node: any, typeRegex: string[]): boolean { return typeRegex.some((typeRegex) => nodeType(node, typeRegex)) } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function memName (node: any, memNameRegex: any): boolean { return (node && !memNameRegex) || new RegExp(memNameRegex).test(node.name) || new RegExp(memNameRegex).test(node.memberName) } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function operator (node: any, opRegex: string): boolean { return new RegExp(opRegex).test(node.operator) } // #################### Helpers function exactMatch (regexStr: string): string { return '^' + regexStr + '$' } function matches (...fnArgs: any[]): string { const args: any[] = [] for (let k = 0; k < fnArgs.length; k++) { args.push(fnArgs[k]) } return '(' + args.join('|') + ')' } /** * Finds first node of a certain type under a specific node. * @node {AstNode} node to start form * @type {String} Type the ast node should have * @return {AstNode} null or node found * Note: developed keeping identifier node search in mind to get first identifier node from left in subscope */ function findFirstSubNodeLTR (node: any, type: string): any { if (node.nodeType && nodeType(node, type)) { return node } else if (node.nodeType && nodeType(node, exactMatch('Assignment'))) { return findFirstSubNodeLTR(node.leftHandSide, type) } else if (node.nodeType && nodeType(node, exactMatch('MemberAccess'))) { return findFirstSubNodeLTR(node.expression, type) } else if (node.nodeType && nodeType(node, exactMatch('IndexAccess'))) { return findFirstSubNodeLTR(node.baseExpression, type) } else if (node.nodeType && nodeType(node, exactMatch('UnaryOperation'))) { return findFirstSubNodeLTR(node.subExpression, type) } } /** * Builds a function signature as used in the AST of the solc-json AST * @param {Array} paramTypes * list of parameter type names * @param {Array} returnTypes * list of return type names * @return {Boolean} isPayable */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function buildFunctionSignature (paramTypes: any[], returnTypes: any[], isPayable: boolean, additionalMods?: any): string { return 'function (' + util.concatWithSeperator(paramTypes, ',') + ')' + ((isPayable) ? ' payable' : '') + ((additionalMods) ? ' ' + additionalMods : '') + ((returnTypes.length) ? ' returns (' + util.concatWithSeperator(returnTypes, ',') + ')' : '') } function buildAbiSignature (funName: string, paramTypes: any[]): string { return funName + '(' + util.concatWithSeperator(paramTypes, ',') + ')' } // To create the method signature similar to contract.evm.gasEstimates.external object // For address payable, return address function getMethodParamsSplittedTypeDesc (node: FunctionDefinitionAstNode, contracts: CompiledContractObj): string[] { return node.parameters.parameters.map((varNode, varIndex) => { let finalTypeString const typeString = varNode.typeDescriptions.typeString if (typeString.includes('struct')) { const fnName = node.name for (const filename in contracts) { for (const contractName in contracts[filename]) { const methodABI = contracts[filename][contractName].abi .find(e => e.name === fnName && e.inputs?.length && e.inputs[varIndex]['type'].includes('tuple') && e.inputs[varIndex]['internalType'] === typeString) if (methodABI && methodABI.inputs) { const inputs = methodABI.inputs[varIndex] const typeStr = getTypeStringFromComponents(inputs['components']) finalTypeString = typeStr + inputs['type'].replace('tuple', '') } } } } else { finalTypeString = typeString.split(' ')[0] } return finalTypeString }) } function getTypeStringFromComponents (components: ABIParameter[]) { let typeString = '(' for (let i = 0; i < components.length; i++) { const param = components[i] if (param.type.includes('tuple') && param.components && param.components.length > 0) { typeString = typeString + getTypeStringFromComponents(param.components) typeString = typeString + param.type.replace('tuple', '') } else { typeString = typeString + param.type } if (i !== components.length - 1) { typeString = typeString + ',' } } typeString = typeString + ')' return typeString } /** * Get compiler version from compiler contract object * This is used to redirect the user to specific version of Solidity documentation * @param contractFiles compiled contract object */ function getCompilerVersion (contractFiles: CompiledContractObj): string { let version = 'latest' const fileNames: string[] = Object.keys(contractFiles) const contracts = contractFiles[fileNames[0]] const contractNames: string[] = Object.keys(contracts) const contract: CompiledContract = contracts[contractNames[0]] // For some compiler/contract, metadata is "" if (contract && contract.metadata) { const metadata = JSON.parse(contract.metadata) const compilerVersion: string = metadata.compiler.version if (!compilerVersion.includes('nightly')) { version = 'v' + compilerVersion.split('+commit')[0] } } return version } const helpers = { expressionTypeDescription, nodeType, memName, operator, buildFunctionSignature, buildAbiSignature } export { // #################### Trivial Getters getType, // #################### Complex Getters getThisLocalCallName, getSuperLocalCallName, getFunctionCallType, getContractName, getEffectedVariableName, getDeclaredVariableName, getDeclaredVariableType, getLocalCallName, getInheritsFromName, getExternalDirectCallContractName, getThisLocalCallContractName, getExternalDirectCallMemberName, getFunctionDefinitionName, getFunctionCallTypeParameterType, getLibraryCallContractName, getLibraryCallMemberName, getFullQualifiedFunctionCallIdent, getFullQuallyfiedFuncDefinitionIdent, getStateVariableDeclarationsFromContractNode, getFunctionOrModifierDefinitionParameterPart, getFunctionDefinitionReturnParameterPart, getUnAssignedTopLevelBinOps, getMethodParamsSplittedTypeDesc, getCompilerVersion, // #################### Complex Node Identification isDeleteOfDynamicArray, isDeleteFromDynamicArray, isAbiNamespaceCall, isSpecialVariableAccess, isVariableTurnedIntoGetter, isDynamicArrayAccess, isDynamicArrayLengthAccess, isMappingIndexAccess, isSubScopeWithTopLevelUnAssignedBinOp, hasFunctionBody, isInteraction, isEffect, isTxOriginAccess, isNowAccess, isBlockTimestampAccess, isBlockBlockHashAccess, isThisLocalCall, isSuperLocalCall, isLibraryCall, isLocalCallGraphRelevantNode, isLocalCall, isWriteOnStateVariable, isStateVariable, isTransfer, isLowLevelCall, isLLCall, isLLCall04, isLLCallcode, isLLDelegatecall, isLLDelegatecall04, isLLSend, isLLSend04, isExternalDirectCall, isFullyImplementedContract, isLibrary, isCallToNonConstLocalFunction, isPlusPlusUnaryOperation, isMinusMinusUnaryOperation, isBuiltinFunctionCall, isSelfdestructCall, isAssertCall, isRequireCall, isIntDivision, isStringToBytesConversion, isBytesLengthCheck, isLoop, // #################### Trivial Node Identification isDeleteUnaryOperation, isStorageVariableDeclaration, isConstantFunction, isPayableFunction, isConstructor, isStatement, // #################### Constants nodeTypes, basicTypes, basicFunctionTypes, lowLevelCallTypes, specialVariables, helpers }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/webServicesMappers"; import * as Parameters from "../models/parameters"; import { AzureMLWebServicesManagementClientContext } from "../azureMLWebServicesManagementClientContext"; /** Class representing a WebServices. */ export class WebServices { private readonly client: AzureMLWebServicesManagementClientContext; /** * Create a WebServices. * @param {AzureMLWebServicesManagementClientContext} client Reference to the service client. */ constructor(client: AzureMLWebServicesManagementClientContext) { this.client = client; } /** * Create or update a web service. This call will overwrite an existing web service. Note that * there is no warning or confirmation. This is a nonrecoverable operation. If your intent is to * create a new web service, call the Get operation first to verify that it does not exist. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param createOrUpdatePayload The payload that is used to create or update the web service. * @param [options] The optional parameters * @returns Promise<Models.WebServicesCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, webServiceName: string, createOrUpdatePayload: Models.WebService, options?: msRest.RequestOptionsBase): Promise<Models.WebServicesCreateOrUpdateResponse> { return this.beginCreateOrUpdate(resourceGroupName,webServiceName,createOrUpdatePayload,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.WebServicesCreateOrUpdateResponse>; } /** * Gets the Web Service Definition as specified by a subscription, resource group, and name. Note * that the storage credentials and web service keys are not returned by this call. To get the web * service access keys, call List Keys. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param [options] The optional parameters * @returns Promise<Models.WebServicesGetResponse> */ get(resourceGroupName: string, webServiceName: string, options?: Models.WebServicesGetOptionalParams): Promise<Models.WebServicesGetResponse>; /** * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param callback The callback */ get(resourceGroupName: string, webServiceName: string, callback: msRest.ServiceCallback<Models.WebService>): void; /** * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, webServiceName: string, options: Models.WebServicesGetOptionalParams, callback: msRest.ServiceCallback<Models.WebService>): void; get(resourceGroupName: string, webServiceName: string, options?: Models.WebServicesGetOptionalParams | msRest.ServiceCallback<Models.WebService>, callback?: msRest.ServiceCallback<Models.WebService>): Promise<Models.WebServicesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, webServiceName, options }, getOperationSpec, callback) as Promise<Models.WebServicesGetResponse>; } /** * Modifies an existing web service resource. The PATCH API call is an asynchronous operation. To * determine whether it has completed successfully, you must perform a Get operation. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param patchPayload The payload to use to patch the web service. * @param [options] The optional parameters * @returns Promise<Models.WebServicesPatchResponse> */ patch(resourceGroupName: string, webServiceName: string, patchPayload: Models.WebService, options?: msRest.RequestOptionsBase): Promise<Models.WebServicesPatchResponse> { return this.beginPatch(resourceGroupName,webServiceName,patchPayload,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.WebServicesPatchResponse>; } /** * Deletes the specified web service. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ remove(resourceGroupName: string, webServiceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginRemove(resourceGroupName,webServiceName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Creates an encrypted credentials parameter blob for the specified region. To get the web service * from a region other than the region in which it has been created, you must first call Create * Regional Web Services Properties to create a copy of the encrypted credential parameter blob in * that region. You only need to do this before the first time that you get the web service in the * new region. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param region The region for which encrypted credential parameters are created. * @param [options] The optional parameters * @returns Promise<Models.WebServicesCreateRegionalPropertiesResponse> */ createRegionalProperties(resourceGroupName: string, webServiceName: string, region: string, options?: msRest.RequestOptionsBase): Promise<Models.WebServicesCreateRegionalPropertiesResponse> { return this.beginCreateRegionalProperties(resourceGroupName,webServiceName,region,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.WebServicesCreateRegionalPropertiesResponse>; } /** * Gets the access keys for the specified web service. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param [options] The optional parameters * @returns Promise<Models.WebServicesListKeysResponse> */ listKeys(resourceGroupName: string, webServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.WebServicesListKeysResponse>; /** * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param callback The callback */ listKeys(resourceGroupName: string, webServiceName: string, callback: msRest.ServiceCallback<Models.WebServiceKeys>): void; /** * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param options The optional parameters * @param callback The callback */ listKeys(resourceGroupName: string, webServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebServiceKeys>): void; listKeys(resourceGroupName: string, webServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebServiceKeys>, callback?: msRest.ServiceCallback<Models.WebServiceKeys>): Promise<Models.WebServicesListKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, webServiceName, options }, listKeysOperationSpec, callback) as Promise<Models.WebServicesListKeysResponse>; } /** * Gets the web services in the specified resource group. * @param resourceGroupName Name of the resource group in which the web service is located. * @param [options] The optional parameters * @returns Promise<Models.WebServicesListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: Models.WebServicesListByResourceGroupOptionalParams): Promise<Models.WebServicesListByResourceGroupResponse>; /** * @param resourceGroupName Name of the resource group in which the web service is located. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.PaginatedWebServicesList>): void; /** * @param resourceGroupName Name of the resource group in which the web service is located. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: Models.WebServicesListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.PaginatedWebServicesList>): void; listByResourceGroup(resourceGroupName: string, options?: Models.WebServicesListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.PaginatedWebServicesList>, callback?: msRest.ServiceCallback<Models.PaginatedWebServicesList>): Promise<Models.WebServicesListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.WebServicesListByResourceGroupResponse>; } /** * Gets the web services in the specified subscription. * @param [options] The optional parameters * @returns Promise<Models.WebServicesListBySubscriptionIdResponse> */ listBySubscriptionId(options?: Models.WebServicesListBySubscriptionIdOptionalParams): Promise<Models.WebServicesListBySubscriptionIdResponse>; /** * @param callback The callback */ listBySubscriptionId(callback: msRest.ServiceCallback<Models.PaginatedWebServicesList>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscriptionId(options: Models.WebServicesListBySubscriptionIdOptionalParams, callback: msRest.ServiceCallback<Models.PaginatedWebServicesList>): void; listBySubscriptionId(options?: Models.WebServicesListBySubscriptionIdOptionalParams | msRest.ServiceCallback<Models.PaginatedWebServicesList>, callback?: msRest.ServiceCallback<Models.PaginatedWebServicesList>): Promise<Models.WebServicesListBySubscriptionIdResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionIdOperationSpec, callback) as Promise<Models.WebServicesListBySubscriptionIdResponse>; } /** * Create or update a web service. This call will overwrite an existing web service. Note that * there is no warning or confirmation. This is a nonrecoverable operation. If your intent is to * create a new web service, call the Get operation first to verify that it does not exist. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param createOrUpdatePayload The payload that is used to create or update the web service. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(resourceGroupName: string, webServiceName: string, createOrUpdatePayload: Models.WebService, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, webServiceName, createOrUpdatePayload, options }, beginCreateOrUpdateOperationSpec, options); } /** * Modifies an existing web service resource. The PATCH API call is an asynchronous operation. To * determine whether it has completed successfully, you must perform a Get operation. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param patchPayload The payload to use to patch the web service. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginPatch(resourceGroupName: string, webServiceName: string, patchPayload: Models.WebService, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, webServiceName, patchPayload, options }, beginPatchOperationSpec, options); } /** * Deletes the specified web service. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginRemove(resourceGroupName: string, webServiceName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, webServiceName, options }, beginRemoveOperationSpec, options); } /** * Creates an encrypted credentials parameter blob for the specified region. To get the web service * from a region other than the region in which it has been created, you must first call Create * Regional Web Services Properties to create a copy of the encrypted credential parameter blob in * that region. You only need to do this before the first time that you get the web service in the * new region. * @param resourceGroupName Name of the resource group in which the web service is located. * @param webServiceName The name of the web service. * @param region The region for which encrypted credential parameters are created. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateRegionalProperties(resourceGroupName: string, webServiceName: string, region: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, webServiceName, region, options }, beginCreateRegionalPropertiesOperationSpec, options); } /** * Gets the web services in the specified resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.WebServicesListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.WebServicesListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PaginatedWebServicesList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PaginatedWebServicesList>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PaginatedWebServicesList>, callback?: msRest.ServiceCallback<Models.PaginatedWebServicesList>): Promise<Models.WebServicesListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.WebServicesListByResourceGroupNextResponse>; } /** * Gets the web services in the specified subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.WebServicesListBySubscriptionIdNextResponse> */ listBySubscriptionIdNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.WebServicesListBySubscriptionIdNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionIdNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PaginatedWebServicesList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionIdNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PaginatedWebServicesList>): void; listBySubscriptionIdNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PaginatedWebServicesList>, callback?: msRest.ServiceCallback<Models.PaginatedWebServicesList>): Promise<Models.WebServicesListBySubscriptionIdNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionIdNextOperationSpec, callback) as Promise<Models.WebServicesListBySubscriptionIdNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.webServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.region0, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.WebService }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listKeysOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}/listKeys", urlParameters: [ Parameters.resourceGroupName, Parameters.webServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.WebServiceKeys }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId ], queryParameters: [ Parameters.skiptoken, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PaginatedWebServicesList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listBySubscriptionIdOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.MachineLearning/webServices", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.skiptoken, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PaginatedWebServicesList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.webServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "createOrUpdatePayload", mapper: { ...Mappers.WebService, required: true } }, responses: { 200: { bodyMapper: Mappers.WebService }, 201: { bodyMapper: Mappers.WebService }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginPatchOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.webServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "patchPayload", mapper: { ...Mappers.WebService, required: true } }, responses: { 200: { bodyMapper: Mappers.WebService }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginRemoveOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.webServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateRegionalPropertiesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}/CreateRegionalBlob", urlParameters: [ Parameters.resourceGroupName, Parameters.webServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.region1, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.AsyncOperationStatus }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PaginatedWebServicesList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listBySubscriptionIdNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PaginatedWebServicesList }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import { tracked } from '@glimmer/tracking'; import { defer, hash } from 'rsvp'; import BN from 'bn.js'; import Web3 from 'web3'; import { TransactionReceipt } from 'web3-core'; import * as Sentry from '@sentry/browser'; import { Emitter, SimpleEmitter, UnbindEventListener } from '../events'; import { BridgeableSymbol, ConversionFunction, Layer1TokenSymbol, TokenContractInfo, } from '../token'; import WalletInfo from '../wallet-info'; import { WalletProvider, WalletProviderId } from '../wallet-providers'; import { ApproveOptions, Layer1ChainEvent, Layer1Web3Strategy, TransactionHash, TxnBlockNumber, Layer1NetworkSymbol, ClaimBridgedTokensOptions, RelayTokensOptions, } from './types'; import { BridgeValidationResult, getConstantByNetwork, getSDK, IAssets, ILayerOneOracle, networkIds, waitUntilBlock, } from '@cardstack/cardpay-sdk'; import { ConnectionManager, ConnectionManagerEvent, } from './layer-1-connection-manager'; import { task } from 'ember-concurrency'; import { taskFor } from 'ember-concurrency-ts'; import { action } from '@ember/object'; import { UsdConvertibleSymbol } from '@cardstack/web-client/services/token-to-usd'; export default abstract class Layer1ChainWeb3Strategy implements Layer1Web3Strategy, Emitter<Layer1ChainEvent> { chainId: number; networkSymbol: Layer1NetworkSymbol; simpleEmitter = new SimpleEmitter(); // changes with connection state #waitForAccountDeferred = defer<void>(); web3: Web3 | undefined; #layerOneOracleApi?: ILayerOneOracle; #assetsApi?: IAssets; connectionManager: ConnectionManager; eventListenersToUnbind: { [event in ConnectionManagerEvent]?: UnbindEventListener; } = {}; @tracked currentProviderId: string | undefined; @tracked defaultTokenBalance: BN | undefined; @tracked daiBalance: BN | undefined; @tracked cardBalance: BN | undefined; @tracked walletInfo: WalletInfo; @tracked connectedChainId: number | undefined; @tracked bridgeConfirmationBlockCount: number; nativeTokenSymbol: string; constructor(networkSymbol: Layer1NetworkSymbol) { this.chainId = networkIds[networkSymbol]; this.walletInfo = new WalletInfo([]); this.networkSymbol = networkSymbol; this.bridgeConfirmationBlockCount = Number( getConstantByNetwork('ambFinalizationRate', this.networkSymbol) ); this.connectionManager = new ConnectionManager(networkSymbol); // may need this for testing? this.connectionManager.on('connected', this.onConnect); this.connectionManager.on('disconnected', this.onDisconnect); this.connectionManager.on('chain-changed', this.onChainChanged); this.connectionManager.on( 'cross-tab-connection', this.onCrossTabConnection ); this.connectionManager.on( 'websocket-disconnected', this.onWebsocketDisconnected ); this.nativeTokenSymbol = getConstantByNetwork( 'nativeTokenSymbol', this.networkSymbol ); taskFor(this.initializeTask).perform(); } get isInitializing() { return taskFor(this.initializeTask).isRunning; } @task *initializeTask() { yield this.reconnect(); } @action async onCrossTabConnection(payload: { providerId: WalletProviderId; session?: any; }) { try { if ( payload.providerId !== 'wallet-connect' && payload.providerId !== 'metamask' ) { return; } this.web3 = new Web3(); await this.connectionManager.reconnect( this.web3, payload.providerId, payload.session ); } catch (e) { console.error( `Failed to establish connection to ${payload.providerId} from cross-tab communication` ); console.error(e); Sentry.captureException(e); this.cleanupConnectionState(); } } @action async onConnect(accounts: string[]) { await this.updateWalletInfo(accounts); this.currentProviderId = this.connectionManager?.providerId; this.#waitForAccountDeferred.resolve(); } @action onChainChanged(chainId: number) { this.connectedChainId = chainId; if (this.connectedChainId !== this.chainId) { this.simpleEmitter.emit('incorrect-chain'); } else { this.simpleEmitter.emit('correct-chain'); } } @action private onDisconnect() { if (this.isConnected) { this.simpleEmitter.emit('disconnect'); } this.cleanupConnectionState(); } @action private onWebsocketDisconnected() { this.simpleEmitter.emit('websocket-disconnected'); } async reconnect() { try { let providerId = ConnectionManager.getProviderIdForChain(this.chainId); if (providerId !== 'wallet-connect' && providerId !== 'metamask') { return; } this.web3 = new Web3(); this.#layerOneOracleApi = await getSDK('LayerOneOracle', this.web3); this.#assetsApi = await getSDK('Assets', this.web3); await this.connectionManager.reconnect(this.web3, providerId); } catch (e) { console.error('Failed to initialize connection from local storage'); console.error(e); Sentry.captureException(e); this.cleanupConnectionState(); ConnectionManager.removeProviderFromStorage(this.chainId); } } async connect(walletProvider: WalletProvider): Promise<void> { try { this.web3 = new Web3(); this.#layerOneOracleApi = await getSDK('LayerOneOracle', this.web3); this.#assetsApi = await getSDK('Assets', this.web3); let completedConnectionAttempt = await this.connectionManager.connect( this.web3, walletProvider.id ); /** * If the user cancels the process midway of connection * so connection effectively fails before trying * we want to clean up any state that was set */ if (!completedConnectionAttempt) { this.cleanupConnectionState(); ConnectionManager.removeProviderFromStorage(this.chainId); } } catch (e) { console.error( `Failed to create connection manager: ${walletProvider.id}` ); console.error(e); Sentry.captureException(e); this.cleanupConnectionState(); ConnectionManager.removeProviderFromStorage(this.chainId); } } async disconnect(): Promise<void> { return this.connectionManager?.disconnect(); } cleanupConnectionState() { this.clearWalletInfo(); Object.entries(this.eventListenersToUnbind).forEach( ([event, unbind]: [ConnectionManagerEvent, UnbindEventListener]) => { unbind(); delete this.eventListenersToUnbind[event]; } ); this.connectionManager?.reset(); this.web3 = undefined; this.currentProviderId = ''; this.connectedChainId = undefined; this.#layerOneOracleApi = undefined; this.#assetsApi = undefined; this.#waitForAccountDeferred = defer(); } get waitForAccount(): Promise<void> { return this.#waitForAccountDeferred.promise; } get isConnected(): boolean { return this.walletInfo.accounts.length > 0; } on(event: Layer1ChainEvent, cb: Function): UnbindEventListener { return this.simpleEmitter.on(event, cb); } private async updateWalletInfo(accounts: string[]) { let newWalletInfo = new WalletInfo(accounts); if (this.walletInfo.isEqualTo(newWalletInfo)) { return; } if (this.walletInfo.firstAddress && newWalletInfo.firstAddress) { this.simpleEmitter.emit('account-changed'); } this.walletInfo = newWalletInfo; if (accounts.length > 0) { await this.refreshBalances(); } else { this.defaultTokenBalance = undefined; this.cardBalance = undefined; this.daiBalance = undefined; } } private clearWalletInfo() { this.updateWalletInfo([]); } contractForToken(symbol: BridgeableSymbol) { if (!this.web3) throw new Error('Cannot get contract for bridgeable tokens without web3'); let { address, abi } = new TokenContractInfo(symbol, this.networkSymbol); return new this.web3.eth.Contract(abi, address); } async refreshBalances() { if (!this.isConnected) return; try { let balances = await Promise.all<string>([ this.getDefaultTokenBalance(), this.getErc20Balance('DAI'), this.getErc20Balance('CARD'), ]); let [defaultTokenBalance, daiBalance, cardBalance] = balances; this.defaultTokenBalance = new BN(defaultTokenBalance); this.daiBalance = new BN(daiBalance); this.cardBalance = new BN(cardBalance); } catch (e) { // Incorrect chain id triggers controller:card-pay#onLayer2Incorrect to show a modal if (e.message.includes('what name the network id')) { // Exception being ignored: Don't know what name the network id ID is Sentry.captureException(e); throw e; } } } private async getErc20Balance( tokenSymbol: Layer1TokenSymbol ): Promise<string> { if (!this.#assetsApi) { throw new Error('Cannot get token balances without a web3 connection'); } if (!this.walletInfo.firstAddress) { return '0'; } let { address } = new TokenContractInfo(tokenSymbol, this.networkSymbol); return this.#assetsApi.getBalanceForToken( address, this.walletInfo.firstAddress ); } private async getDefaultTokenBalance(): Promise<string> { if (!this.#assetsApi) { throw new Error('Cannot get token balances without a web3 connection'); } if (!this.walletInfo.firstAddress) { return '0'; } return this.#assetsApi.getNativeTokenBalance(this.walletInfo.firstAddress); } async approve( amountInWei: BN, tokenSymbol: BridgeableSymbol, { onTxnHash }: ApproveOptions ): Promise<TransactionReceipt> { if (!this.web3) throw new Error('Cannot unlock tokens without web3'); let tokenBridge = await getSDK('TokenBridgeForeignSide', this.web3); return tokenBridge.unlockTokens( new TokenContractInfo(tokenSymbol, this.networkSymbol).address, amountInWei.toString(), { onTxnHash } ); } async resumeApprove(txnHash: TransactionHash): Promise<TransactionReceipt> { if (!this.web3) throw new Error('Cannot unlock tokens without web3'); let tokenBridge = await getSDK('TokenBridgeForeignSide', this.web3); return tokenBridge.unlockTokens(txnHash); } async relayTokens( tokenSymbol: BridgeableSymbol, receiverAddress: string, amountInWei: BN, { onTxnHash }: RelayTokensOptions ): Promise<TransactionReceipt> { if (!this.web3) throw new Error('Cannot relay tokens without web3'); let tokenBridge = await getSDK('TokenBridgeForeignSide', this.web3); return tokenBridge.relayTokens( new TokenContractInfo(tokenSymbol, this.networkSymbol).address, receiverAddress, amountInWei.toString(), { onTxnHash } ); } async resumeRelayTokens( txnHash: TransactionHash ): Promise<TransactionReceipt> { if (!this.web3) throw new Error('Cannot unlock tokens without web3'); let tokenBridge = await getSDK('TokenBridgeForeignSide', this.web3); return tokenBridge.relayTokens(txnHash); } async resumeClaimBridgedTokens(txnHash: string): Promise<TransactionReceipt> { if (!this.web3) throw new Error('Cannot claim bridged tokens without web3'); let tokenBridge = await getSDK('TokenBridgeForeignSide', this.web3); return tokenBridge.claimBridgedTokens(txnHash); } async claimBridgedTokens( bridgeValidationResult: BridgeValidationResult, options?: ClaimBridgedTokensOptions ): Promise<TransactionReceipt> { if (!this.web3) throw new Error('Cannot claim bridged tokens without web3'); let tokenBridge = await getSDK('TokenBridgeForeignSide', this.web3); return tokenBridge.claimBridgedTokens( bridgeValidationResult.messageId, bridgeValidationResult.encodedData, bridgeValidationResult.signatures, { onTxnHash: options?.onTxnHash } ); } async getBlockConfirmation(blockNumber: TxnBlockNumber): Promise<void> { if (!this.web3) throw new Error('Cannot get block confirmations without web3'); return await waitUntilBlock(this.web3, blockNumber); } blockExplorerUrl(txnHash: TransactionHash): string { return `${getConstantByNetwork( 'blockExplorer', this.networkSymbol )}/tx/${txnHash}`; } bridgeExplorerUrl(txnHash: TransactionHash): string { return `${getConstantByNetwork( 'bridgeExplorer', this.networkSymbol )}/${txnHash}`; } async getEstimatedGasForWithdrawalClaim( symbol: BridgeableSymbol ): Promise<BN> { if (!this.web3) throw new Error('Cannot getEstimatedGasForWithdrawalClaim without web3'); let tokenBridge = await getSDK('TokenBridgeForeignSide', this.web3); let { address } = new TokenContractInfo(symbol, this.networkSymbol); return tokenBridge.getEstimatedGasForWithdrawalClaim(address); } async updateUsdConverters( symbolsToUpdate: UsdConvertibleSymbol[] ): Promise<Record<UsdConvertibleSymbol, ConversionFunction>> { let layerOneOracleApi = this.#layerOneOracleApi; if (!layerOneOracleApi) throw new Error('Cannot updateUsdConverters without a web3 connection'); let promisesHash = {} as Record< UsdConvertibleSymbol, Promise<ConversionFunction> >; for (let symbol of symbolsToUpdate) { promisesHash[symbol] = layerOneOracleApi.getEthToUsdConverter(); } return hash(promisesHash); } }
the_stack
import {CONSUMED_CAPACITY_TYPE, Replace} from '@typedorm/common'; import {User} from '@typedorm/core/__mocks__/user'; import {UserUniqueEmail} from '@typedorm/core/__mocks__/user-unique-email'; import {createTestConnection, resetTestConnection} from '@typedorm/testing'; import {WriteBatch} from '../../batch/write-batch'; import {Connection} from '../../connection/connection'; import {BatchManager} from '../batch-manager'; import {EntityManager} from '../entity-manager'; import {TransactionManager} from '../transaction-manager'; import {ReadBatch} from '../../batch/read-batch'; let connection: Connection; let manager: BatchManager; let entityManager: Replace< EntityManager, 'findOne', {findOne: jest.SpyInstance} >; let transactionManager: Replace< TransactionManager, 'writeRaw', { writeRaw: jest.SpyInstance; } >; const documentClientMock = { batchWrite: jest.fn(), batchGet: jest.fn(), }; let originalPromiseAll: jasmine.Spy; beforeEach(() => { connection = createTestConnection({ entities: [User, UserUniqueEmail], documentClient: documentClientMock, }); manager = new BatchManager(connection); entityManager = connection.entityManager as any; transactionManager = connection.transactionManger as any; entityManager.findOne = jest.fn(); transactionManager.writeRaw = jest.fn(); originalPromiseAll = spyOn(Promise, 'all').and.callThrough(); }); afterEach(() => { resetTestConnection(); }); /** * @group write */ test('processes empty batch write request', async () => { const writeBatch = new WriteBatch(); const result = await manager.write(writeBatch); expect(originalPromiseAll).toHaveBeenCalledTimes(1); expect(originalPromiseAll.calls.mostRecent).toEqual(expect.any(Function)); expect(result).toEqual({ failedItems: [], unprocessedItems: [], }); }); test('processes batch write request with simple request items', async () => { // mock document client with data documentClientMock.batchWrite.mockReturnValue({ promise: () => ({UnprocessedItems: {}}), }); const largeBatchOfUsers = mockSimpleBatchWriteData(60); const writeBatch = new WriteBatch().add(largeBatchOfUsers); const result = await manager.write( writeBatch, {}, { requestId: 'MY_UNIQUE_CUSTOM_REQUEST_ID', } ); expect(originalPromiseAll).toHaveBeenCalledTimes(1); expect(documentClientMock.batchWrite).toHaveBeenCalledTimes(3); expect(entityManager.findOne).not.toHaveBeenCalled(); expect(transactionManager.writeRaw).not.toHaveBeenCalled(); expect(result).toEqual({ failedItems: [], unprocessedItems: [], }); }); test('processes batch write request and retries as needed', async () => { // mock document client with data let counter = 0; documentClientMock.batchWrite.mockImplementation(({RequestItems}) => ({ promise: () => { counter++; if (counter % 2 === 0) { return { UnprocessedItems: {}, }; } else { const tableName = Object.keys(RequestItems)[0]; return { UnprocessedItems: {[tableName]: RequestItems[tableName]}, }; } }, })); const largeBatchOfUsers = mockSimpleBatchWriteData(120); const writeBatch = new WriteBatch().add(largeBatchOfUsers); const result = await manager.write(writeBatch); expect(originalPromiseAll).toHaveBeenCalledTimes(4); expect(documentClientMock.batchWrite).toHaveBeenCalledTimes(10); expect(entityManager.findOne).not.toHaveBeenCalled(); expect(transactionManager.writeRaw).not.toHaveBeenCalled(); expect(result).toEqual({ failedItems: [], unprocessedItems: [], }); }); test('processes batch write requests that contains mix of unique and lazy load items', async () => { // mock document client with data randomlyRejectDataMock(); entityManager.findOne.mockImplementation((en, primaryAttrs) => { return { ...primaryAttrs, email: 'test@example.com', }; }); transactionManager.writeRaw.mockImplementation(() => { return {}; }); const largeBatchOfUsers = mockTransactionAndBatchData(114); const writeBatch = new WriteBatch().add(largeBatchOfUsers); const result = await manager.write(writeBatch); expect(originalPromiseAll).toHaveBeenCalledTimes(4); expect(documentClientMock.batchWrite).toHaveBeenCalledTimes(6); expect(entityManager.findOne).toHaveBeenCalled(); expect(transactionManager.writeRaw).toHaveBeenCalled(); expect(result).toEqual({ failedItems: [], unprocessedItems: [], }); }); test('processes batch write requests where some of the items failed to put', async () => { documentClientMock.batchWrite .mockImplementationOnce(({RequestItems}) => ({ promise: () => { const tableName = Object.keys(RequestItems)[0]; return { UnprocessedItems: { [tableName]: (RequestItems[tableName] as any[]).slice(1), }, }; }, })) .mockImplementationOnce(({RequestItems}) => ({ promise: () => { const tableName = Object.keys(RequestItems)[0]; return { UnprocessedItems: { [tableName]: (RequestItems[tableName] as any[]).slice(6), }, }; }, })) .mockImplementationOnce(() => ({ promise: () => { throw new Error(); }, })); const largeBatchOfUsers = mockSimpleBatchWriteData(10); const writeBatch = new WriteBatch().add(largeBatchOfUsers); const result = await manager.write(writeBatch); expect(originalPromiseAll).toHaveBeenCalledTimes(3); expect(documentClientMock.batchWrite).toHaveBeenCalledTimes(3); expect(result).toEqual({ failedItems: [ { create: { item: { id: '8', name: 'User 8', status: 'active', }, }, }, { delete: { item: User, primaryKey: { id: '3', }, }, }, { create: { item: { id: '10', name: 'User 10', status: 'active', }, }, }, ], unprocessedItems: [], }); }); test('processes batch write requests where some of the items could not be processed properly', async () => { let counter = 0; documentClientMock.batchWrite.mockImplementation(({RequestItems}) => ({ promise: () => { ++counter; const tableName = Object.keys(RequestItems)[0]; return { UnprocessedItems: { [tableName]: (RequestItems[tableName] as any[]).slice( // when on last counter return less items, makes it easy ti test counter === 10 ? 9 : 1 ), }, }; }, })); transactionManager.writeRaw.mockImplementation(() => { throw new Error(); }); // mock input data const uniqueEmailUser = new UserUniqueEmail(); uniqueEmailUser.id = '11-22'; uniqueEmailUser.status = 'active'; uniqueEmailUser.name = 'User 11-2'; uniqueEmailUser.email = 'user11-22.example.com'; const largeBatchOfUsers = [ ...mockSimpleBatchWriteData(20), { create: { item: uniqueEmailUser, }, }, ]; const writeBatch = new WriteBatch().add(largeBatchOfUsers); const result = await manager.write(writeBatch); expect(originalPromiseAll).toHaveBeenCalledTimes(11); expect(documentClientMock.batchWrite).toHaveBeenCalledTimes(11); expect(result).toEqual({ failedItems: [ { create: { item: { email: 'user11-22.example.com', id: '11-22', name: 'User 11-2', status: 'active', }, }, }, ], unprocessedItems: [ { create: { item: { id: '20', name: 'User 20', status: 'active', }, }, }, ], }); // increase timeout, since there can be some delays due to backoff retries }, 20000); test('uses user defined retry attempts for write batch requests', async () => { documentClientMock.batchWrite.mockImplementation(({RequestItems}) => ({ promise: () => { const tableName = Object.keys(RequestItems)[0]; return { UnprocessedItems: { [tableName]: RequestItems[tableName] as any[], }, }; }, })); const largeBatchOfUsers = mockSimpleBatchWriteData(10); const writeBatch = new WriteBatch().add(largeBatchOfUsers); await manager.write(writeBatch, { maxRetryAttempts: 2, }); expect(originalPromiseAll).toHaveBeenCalledTimes(3); expect(documentClientMock.batchWrite).toHaveBeenCalledTimes(3); // 2 retries + 1 original request // increase timeout, since there can be some delays due to backoff retries }); /** * @group read */ test('processes empty batch read request', async () => { const readBatch = new ReadBatch(); const result = await manager.read(readBatch); expect(originalPromiseAll).toHaveBeenCalledTimes(1); expect(originalPromiseAll).toHaveBeenCalledWith([]); expect(documentClientMock.batchGet).toHaveBeenCalledTimes(0); expect(result).toEqual({failedItems: [], items: [], unprocessedItems: []}); }); test('processes simple batch read request', async () => { // mock response documentClientMock.batchGet.mockReturnValue({ promise: () => ({ Responses: { 'simple-table': [ { id: 1, name: 'test', __en: 'user', PK: 'USER#1', SK: 'USER#1', status: 'active', }, { id: 2, name: 'test', __en: 'user', PK: 'USER#2', SK: 'USER#2', status: 'active', }, ], }, }), }); const readTestBatch = new ReadBatch().add([ { item: User, primaryKey: { id: 1, }, }, { item: User, primaryKey: { id: 2, }, }, ]); const response = await manager.read( readTestBatch, {}, { returnConsumedCapacity: CONSUMED_CAPACITY_TYPE.TOTAL, } ); expect(originalPromiseAll).toHaveBeenCalledTimes(1); expect(originalPromiseAll).toHaveBeenCalledWith([expect.any(Promise)]); expect(response).toEqual({ failedItems: [], items: [ { id: 1, name: 'test', status: 'active', }, { id: 2, name: 'test', status: 'active', }, ], unprocessedItems: [], }); }); test('processes batch read request with multiple calls', async () => { // mock document client to return random unprocessed items // when unprocessed items are returned, TypeDORM should auto retry until, // either max attempts is reached or all items have resolved let counter = 0; documentClientMock.batchGet.mockImplementation(() => ({ promise: () => { counter++; // return success items for even requests if (counter % 2 === 0) { return { Responses: { 'simple-table': [ { id: 1, name: 'test', __en: 'user', PK: 'USER#1', SK: 'USER#1', status: 'active', }, ], 'test-table': [ { id: 2, name: 'test', __en: 'user', PK: 'USER#2', SK: 'USER#2', status: 'active', }, ], }, }; } return { Responses: { 'simple-table': [ { id: 4, name: 'test', __en: 'user', PK: 'USER#4', SK: 'USER#4', status: 'active', }, ], }, UnprocessedKeys: { 'simple-table': {Keys: [{PK: 'USER#3', SK: 'USER#3'}]}, }, }; }, })); const readBatch = new ReadBatch().add(mockSimpleBatchReadData(117)); const response = await manager.read(readBatch); expect(originalPromiseAll).toHaveBeenCalledTimes(3); expect(response).toEqual({ failedItems: [], items: [ { id: 4, name: 'test', status: 'active', }, { id: 1, name: 'test', status: 'active', }, { id: 2, name: 'test', status: 'active', }, { id: 4, name: 'test', status: 'active', }, { id: 1, name: 'test', status: 'active', }, { id: 2, name: 'test', status: 'active', }, ], unprocessedItems: [], }); // increase time to allow retries to finish with backoff }, 10000); test('processes batch read request when some items failed to get', async () => { // mock document client to return error for some items, documentClientMock.batchGet .mockImplementationOnce(({RequestItems}) => ({ promise: () => { const tableName = Object.keys(RequestItems)[0]; const itemForCurrTable = RequestItems[tableName]; return { Responses: { [tableName]: { id: 0, name: 'test', __en: 'user', PK: 'USER#0', SK: 'USER#0', status: 'active', }, }, UnprocessedKeys: { [tableName]: {Keys: itemForCurrTable.Keys.slice(1)}, }, }; }, })) .mockImplementationOnce(({RequestItems}) => ({ promise: () => { const tableName = Object.keys(RequestItems)[0]; const itemForCurrTable = RequestItems[tableName]; return { Responses: { [tableName]: [ { id: 1, name: 'test', __en: 'user', PK: 'USER#1', SK: 'USER#1', status: 'inactive', }, { id: 2, name: 'test', __en: 'user', PK: 'USER#2', SK: 'USER#2', status: 'inactive', }, ], }, UnprocessedKeys: { [tableName]: {Keys: itemForCurrTable.Keys.slice(2)}, }, }; }, })) // thrown an error after third api to mock document client's throttling behavior .mockImplementationOnce(() => ({ promise: () => { throw new Error(); }, })); // create mock batch const readBatch = new ReadBatch().add(mockSimpleBatchReadData(6)); const response = await manager.read(readBatch); expect(documentClientMock.batchGet).toHaveReturnedTimes(3); expect(originalPromiseAll).toHaveBeenCalledTimes(3); expect(response).toEqual({ failedItems: [ { item: User, primaryKey: { id: '3', }, }, { item: User, primaryKey: { id: '4', }, }, { item: User, primaryKey: { id: '5', }, }, ], items: [ { id: 0, name: 'test', status: 'active', }, { id: 1, name: 'test', status: 'inactive', }, { id: 2, name: 'test', status: 'inactive', }, ], unprocessedItems: [], }); }, 10000); test('processes batch read request and returns unprocessed items back to user', async () => { // mock document client to behave like one with very low read throughput, let index = -1; documentClientMock.batchGet.mockImplementation(({RequestItems}) => ({ promise: () => { const tableName = Object.keys(RequestItems)[0]; const itemForCurrTable = RequestItems[tableName]; index++; return { Responses: { [tableName]: { id: index, name: 'test', __en: 'user', PK: `USER#${index}`, SK: `USER#${index}`, status: 'active', }, }, UnprocessedKeys: { // only process one item return others back [tableName]: {Keys: itemForCurrTable.Keys.slice(1)}, }, }; }, })); // create mock batch const readBatch = new ReadBatch().add(mockSimpleBatchReadData(13)); const response = await manager.read(readBatch); expect(documentClientMock.batchGet).toHaveReturnedTimes(11); expect(originalPromiseAll).toHaveBeenCalledTimes(11); // Our mocked read batch api returns one item for each request, // util max read retry limit is reached, hence we get 1 initial + 10 items from retries expect(response.items.length).toEqual(11); expect(response.failedItems.length).toBeFalsy(); expect(response.unprocessedItems).toEqual([ { item: User, primaryKey: { id: '11', }, }, { item: User, primaryKey: { id: '12', }, }, ]); }, 20000); test('uses user defined retry attempts for read batch request', async () => { // mock document client to behave like one with very low read throughput, documentClientMock.batchGet.mockImplementation(({RequestItems}) => ({ promise: () => { const tableName = Object.keys(RequestItems)[0]; const itemForCurrTable = RequestItems[tableName]; return { UnprocessedKeys: { // does not process any request [tableName]: itemForCurrTable, }, }; }, })); // create mock batch const readBatch = new ReadBatch().add(mockSimpleBatchReadData(80)); const response = await manager.read(readBatch, { maxRetryAttempts: 3, }); expect(documentClientMock.batchGet).toHaveReturnedTimes(4); expect(originalPromiseAll).toHaveBeenCalledTimes(4); // no item is processed expect(response.unprocessedItems.length).toEqual(80); }, 10000); /** * * * MOCK HELPERS used within this test suite * * */ function mockSimpleBatchWriteData(items: number) { let largeBatchOfUsers = Array(items).fill({}); largeBatchOfUsers = largeBatchOfUsers.map((empty, index) => { const user = new User(); user.id = (++index).toString(); user.status = 'active'; user.name = `User ${index}`; // randomize mock data with create and delete requests if (index % 2 === 0) { return { create: { item: user, }, }; } else { return { delete: { item: User, primaryKey: { id: '3', }, }, }; } }); return largeBatchOfUsers; } function mockSimpleBatchReadData(count: number) { const largeBatchOfUsers = Array(count).fill({}); return largeBatchOfUsers.map((empty, index) => ({ item: User, primaryKey: { id: index.toString(), }, })); } function mockTransactionAndBatchData(items: number) { let currentIndex = 0; const largeBatchOfUsers = new Array(items).fill({}); return largeBatchOfUsers.map((empty, index) => { if (currentIndex === 2) { currentIndex = 0; } else { currentIndex++; } const user = new User(); user.id = index.toString(); user.status = 'active'; user.name = `User ${index}`; const simpleItem = { create: { item: user, }, }; const lazyLoadedItem = { delete: { item: UserUniqueEmail, primaryKey: { id: index, }, }, }; const uniqueEmailUser = new UserUniqueEmail(); uniqueEmailUser.id = index.toString(); uniqueEmailUser.status = 'active'; uniqueEmailUser.name = `User ${index}`; uniqueEmailUser.email = `user${index}.example.com`; const transactionItems = { create: { item: uniqueEmailUser, }, }; const itemOptions = [simpleItem, lazyLoadedItem, transactionItems]; // select of three items return itemOptions[currentIndex]; }); } function randomlyRejectDataMock() { let counter = 0; documentClientMock.batchWrite.mockImplementation(({RequestItems}) => ({ promise: () => { counter++; if (counter % 3 === 0) { return { UnprocessedItems: {}, }; } else { const tableName = Object.keys(RequestItems)[0]; return { UnprocessedItems: {[tableName]: RequestItems[tableName]}, }; } }, })); }
the_stack
import { IContentType, FieldLink, FieldLinkProps } from "gd-sprest-def/lib/SP"; import { IsetContentTypeFields } from "../../../@types/helper/methods"; import { ContextInfo, Web } from "../../lib"; declare var SP; /** * Sets the field links associated with a content type. * @param ctInfo - The content type information */ export const setContentTypeFields: IsetContentTypeFields = (ctInfo: { id: string, fields: Array<string | FieldLinkProps>, listName?: string, webUrl?: string }): PromiseLike<void> => { // Clears the content type field links let clearLinks = (): PromiseLike<Array<FieldLink>> => { // Return a promise return new Promise((resolve, reject) => { // Get the links getLinks().then(fieldLinks => { let skipFields: Array<FieldLink> = []; // See if we need to remove any fields if (fieldLinks.length > 0) { let updateFl = false; // Set the context let ctx = ctInfo.webUrl ? new SP.ClientContext(ctInfo.webUrl) : new SP.ClientContext(ContextInfo.webServerRelativeUrl); // Get the source let src = ctInfo.listName ? ctx.get_web().get_lists().getByTitle(ctInfo.listName) : ctx.get_web(); // Get the content type let contentType = src.get_contentTypes().getById(ctInfo.id); // Parse the content type field links for (let i = 0; i < fieldLinks.length; i++) { let fieldLink = fieldLinks[i]; let removeFl = true; // Parse the fields to add for (let j = 0; j < ctInfo.fields.length; j++) { let field = ctInfo.fields[j]; let fieldName = typeof (field) === "string" ? field : field.Name || field.FieldInternalName; // See if we are keeping this field if (fieldName == fieldLink.Name) { let propUpdateFl = false; // Checks if an update is needed let updateField = (oldValue, newValue) => { // Ensure a value exists if (newValue == null) { return; } // See if an update is needed if (oldValue == newValue) { return; } // Set the flag propUpdateFl = true; } // Update the properties updateField(fieldLink.DisplayName, (field as FieldLinkProps).DisplayName); updateField(fieldLink.Hidden, (field as FieldLinkProps).Hidden); updateField(fieldLink.ReadOnly, (field as FieldLinkProps).ReadOnly); updateField(fieldLink.Required, (field as FieldLinkProps).Required); updateField(fieldLink.ShowInDisplayForm, (field as FieldLinkProps).ShowInDisplayForm); // See if an update to the property is needed if (!propUpdateFl) { // Set the flag to not remove this field reference removeFl = false; // Add the field to skip skipFields.push(fieldLink); } // Break from the loop break; } } // See if we are removing the field if (removeFl) { // Remove the field link contentType.get_fieldLinks().getById(fieldLink.Id).deleteObject(); // Set the flag updateFl = true; // Log console.log("[gd-sprest][Set Content Type Fields] Removing the field link: " + fieldLink.Name); } } // See if an update is required if (updateFl) { // Update the content type contentType.update(false); // Execute the request ctx.executeQueryAsync( // Success () => { // Log console.log("[gd-sprest][Set Content Type Fields] Removed the field links successfully."); // Resolve the request resolve(skipFields); }, // Error (sender, args) => { // Log console.log("[gd-sprest][Set Content Type Fields] Error removing the field links."); // Reject the request reject(); }); } else { // Log console.log("[gd-sprest][Set Content Type Fields] No fields need to be removed."); // Resolve the request resolve(skipFields); } } else { // Resolve the request resolve(skipFields); } }, reject); }); } // Creates the field links let createLinks = (skipFields: Array<FieldLink>): PromiseLike<void> => { // Return a promise return new Promise((resolve, reject) => { // Set the context let ctx = ctInfo.webUrl ? new SP.ClientContext(ctInfo.webUrl) : new SP.ClientContext(ContextInfo.webServerRelativeUrl); // Get the source let src = ctInfo.listName ? ctx.get_web().get_lists().getByTitle(ctInfo.listName) : ctx.get_web(); let skipField = (fieldName: string, fields: Array<FieldLink>): boolean => { for (let i = 0; i < fields.length; i++) { // See if we are skipping this field if (fields[i].Name == fieldName) { return true; } } } // Parse the fields to add let fields: Array<{ ref: any, info: string | FieldLinkProps }> = []; for (let i = 0; i < ctInfo.fields.length; i++) { let fieldInfo = ctInfo.fields[i]; let fieldName = typeof (fieldInfo) === "string" ? fieldInfo : fieldInfo.Name || fieldInfo.FieldInternalName; // See if we are skipping this field if (skipField(fieldName, skipFields)) { continue; } // Load the field let field = src.get_fields().getByInternalNameOrTitle(fieldName); ctx.load(field); // Log console.log("[gd-sprest][Set Content Type Fields] Adding the field link: " + fieldName); // Save a reference to this field fields.push({ ref: field, info: fieldInfo }); } // See if an update is needed if (fields.length > 0) { // Execute the request ctx.executeQueryAsync(() => { // Get the content type let contentType = src.get_contentTypes().getById(ctInfo.id); ctx.load(contentType); // Parse the fields for (let i = 0; i < fields.length; i++) { let field = fields[i]; /** * The field link set_[property] methods don't seem to work. Setting the field information seems to be the only way. * The read only property is the only one that doesn't seem to work. */ // See if the field ref has properties to update if (typeof (field.info) !== "string") { // Update the field properties field.info.DisplayName != null ? field.ref.set_title(field.info.DisplayName) : null; field.info.Hidden != null ? field.ref.set_hidden(field.info.Hidden) : null; field.info.ReadOnly != null ? field.ref.set_readOnlyField(field.info.ReadOnly) : null; field.info.Required != null ? field.ref.set_required(field.info.Required) : null; field.info.ShowInDisplayForm != null ? field.ref.setShowInDisplayForm(field.info.ShowInDisplayForm) : null; } // Create the field link let fieldLink = new SP.FieldLinkCreationInformation(); fieldLink.set_field(field.ref); // Add the field link to the content type contentType.get_fieldLinks().add(fieldLink); } // Update the content type contentType.update(false); // Execute the request ctx.executeQueryAsync( // Success () => { // Log console.log("[gd-sprest][Set Content Type Fields] Added the field links successfully."); // Resolve the request resolve(); }, // Error (sender, args) => { // Log console.log("[gd-sprest][Set Content Type Fields] Error adding field references.", args.get_message()); // Reject the request reject(); }); }, (sender, args) => { // Log console.log("[gd-sprest][Set Content Type Fields] Error getting field references.", args.get_message()); // Resolve the request resolve(); }); } else { // Log console.log("[gd-sprest][Set Content Type Fields] No fields need to be added."); // Resolve the request resolve(); } }); } // Gets the content type field links let getLinks = (): PromiseLike<Array<FieldLink>> => { // Return a promise return new Promise((resolve, reject) => { let ct: IContentType = null; // See if list name exists if (ctInfo.listName) { // Get the list content type ct = Web(ctInfo.webUrl).Lists(ctInfo.listName).ContentTypes(ctInfo.id); } else { // Get the content type ct = Web(ctInfo.webUrl).ContentTypes(ctInfo.id); } // Query the field links ct.FieldLinks().query({ Select: ["DisplayName", "Id", "Name", "Required", "ReadOnly", "ShowInDisplayForm"] }).execute(fieldLinks => { // Resolve the request resolve(fieldLinks.results); }, reject); }); } // Set the order of the field references let setOrder = (): PromiseLike<void> => { // Return a promise return new Promise((resolve, reject) => { // Set the context let ctx = ctInfo.webUrl ? new SP.ClientContext(ctInfo.webUrl) : new SP.ClientContext(ContextInfo.webServerRelativeUrl); // Get the source let src = ctInfo.listName ? ctx.get_web().get_lists().getByTitle(ctInfo.listName) : ctx.get_web(); // Get the content type let contentType = src.get_contentTypes().getById(ctInfo.id); // Parse the fields to add let fieldNames = []; for (let i = 0; i < ctInfo.fields.length; i++) { let fieldInfo = ctInfo.fields[i]; let fieldName = typeof (fieldInfo) === "string" ? fieldInfo : fieldInfo.Name || fieldInfo.FieldInternalName; // Add the field name fieldNames.push(fieldName); } // Reorder the content type contentType.get_fieldLinks().reorder(fieldNames); // Update the content type contentType.update(ctInfo.listName ? false : true); // Execute the request ctx.executeQueryAsync( // Success () => { // Log console.log("[gd-sprest][Set Content Type Fields] Updated the field order successfully."); // Resolve the request resolve(); }, // Error (sender, args) => { // Log console.log("[gd-sprest][Set Content Type Fields] Error updating the field order.", args.get_message()); // Reject the request reject(); }); }); } // Return a promise return new Promise((resolve, reject) => { // Ensure the SP object exists if (window["SP"]) { // Ensure fields exist if (ctInfo.fields) { // Clear the links clearLinks().then(skipFields => { // Create the links createLinks(skipFields).then(() => { // Set the field order setOrder().then(resolve, reject); }, reject); }, reject); } else { // Resolve the promise resolve(); } } else { // Resolve the request // This will cause issues in the SPConfig class resolve(); } }); }
the_stack
import { IExecuteFunctions, } from 'n8n-core'; import { IDataObject, ILoadOptionsFunctions, INodeExecutionData, INodePropertyOptions, INodeType, INodeTypeDescription, NodeOperationError, } from 'n8n-workflow'; import { attendeeFields, attendeeOperations, coorganizerFields, coorganizerOperations, panelistFields, panelistOperations, registrantFields, registrantOperations, sessionFields, sessionOperations, webinarFields, webinarOperations, } from './descriptions'; import { goToWebinarApiRequest, goToWebinarApiRequestAllItems, handleGetAll, loadAnswers, loadRegistranMultiChoiceQuestions, loadRegistranSimpleQuestions, loadWebinars, loadWebinarSessions, } from './GenericFunctions'; import { isEmpty, omit, } from 'lodash'; import * as moment from 'moment-timezone'; export class GoToWebinar implements INodeType { description: INodeTypeDescription = { displayName: 'GoToWebinar', name: 'goToWebinar', icon: 'file:gotowebinar.svg', group: ['transform'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Consume the GoToWebinar API', defaults: { name: 'GoToWebinar', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'goToWebinarOAuth2Api', required: true, }, ], properties: [ { displayName: 'Resource', name: 'resource', type: 'options', options: [ { name: 'Attendee', value: 'attendee', }, { name: 'Co-Organizer', value: 'coorganizer', }, { name: 'Panelist', value: 'panelist', }, { name: 'Registrant', value: 'registrant', }, { name: 'Session', value: 'session', }, { name: 'Webinar', value: 'webinar', }, ], default: 'attendee', description: 'Resource to consume', }, ...attendeeOperations, ...attendeeFields, ...coorganizerOperations, ...coorganizerFields, ...panelistOperations, ...panelistFields, ...registrantOperations, ...registrantFields, ...sessionOperations, ...sessionFields, ...webinarOperations, ...webinarFields, ], }; methods = { loadOptions: { async getWebinars(this: ILoadOptionsFunctions) { return await loadWebinars.call(this); }, async getAnswers(this: ILoadOptionsFunctions) { return await loadAnswers.call(this); }, async getWebinarSessions(this: ILoadOptionsFunctions) { return await loadWebinarSessions.call(this); }, // Get all the timezones to display them to user so that he can // select them easily async getTimezones(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> { const returnData: INodePropertyOptions[] = []; for (const timezone of moment.tz.names()) { const timezoneName = timezone; const timezoneId = timezone; returnData.push({ name: timezoneName, value: timezoneId, }); } return returnData; }, async getRegistranSimpleQuestions(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> { return await loadRegistranSimpleQuestions.call(this); }, async getRegistranMultiChoiceQuestions(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> { return await loadRegistranMultiChoiceQuestions.call(this); }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; let responseData; const returnData: IDataObject[] = []; const { oauthTokenData } = await this.getCredentials('goToWebinarOAuth2Api') as { oauthTokenData: { account_key: string, organizer_key: string } }; const accountKey = oauthTokenData.account_key; const organizerKey = oauthTokenData.organizer_key; for (let i = 0; i < items.length; i++) { try { if (resource === 'attendee') { // ********************************************************************* // attendee // ********************************************************************* // https://developer.goto.com/GoToWebinarV2/#tag/Attendees if (operation === 'get') { // ---------------------------------- // attendee: get // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const sessionKey = this.getNodeParameter('sessionKey', i) as string; const registrantKey = this.getNodeParameter('registrantKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/sessions/${sessionKey}/attendees/${registrantKey}`; responseData = await goToWebinarApiRequest.call(this, 'GET', endpoint, {}, {}); } else if (operation === 'getAll') { // ---------------------------------- // attendee: getAll // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const sessionKey = this.getNodeParameter('sessionKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/sessions/${sessionKey}/attendees`; responseData = await handleGetAll.call(this, endpoint, {}, {}, resource); } else if (operation === 'getDetails') { // ---------------------------------- // attendee: getDetails // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const sessionKey = this.getNodeParameter('sessionKey', i) as string; const registrantKey = this.getNodeParameter('registrantKey', i) as string; const details = this.getNodeParameter('details', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/sessions/${sessionKey}/attendees/${registrantKey}/${details}`; responseData = await goToWebinarApiRequest.call(this, 'GET', endpoint, {}, {}); } } else if (resource === 'coorganizer') { // ********************************************************************* // coorganizer // ********************************************************************* // https://developer.goto.com/GoToWebinarV2/#tag/Co-organizers if (operation === 'create') { // ---------------------------------- // coorganizer: create // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const body = { external: this.getNodeParameter('isExternal', i) as boolean, } as IDataObject; if (body.external === false) { body.organizerKey = this.getNodeParameter('organizerKey', i) as string; } if (body.external === true) { body.givenName = this.getNodeParameter('givenName', i) as string; body.email = this.getNodeParameter('email', i) as string; } const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/coorganizers`; responseData = await goToWebinarApiRequest.call(this, 'POST', endpoint, {}, [body]); } else if (operation === 'delete') { // ---------------------------------- // coorganizer: delete // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const coorganizerKey = this.getNodeParameter('coorganizerKey', i) as string; const qs = { external: this.getNodeParameter('isExternal', i) as boolean, }; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/coorganizers/${coorganizerKey}`; responseData = await goToWebinarApiRequest.call(this, 'DELETE', endpoint, qs, {}); responseData = { success: true }; } else if (operation === 'getAll') { // ---------------------------------- // coorganizer: getAll // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/coorganizers`; responseData = await handleGetAll.call(this, endpoint, {}, {}, resource); } else if (operation === 'reinvite') { // ---------------------------------- // coorganizer: reinvite // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const coorganizerKey = this.getNodeParameter('coorganizerKey', i) as string; const qs = { external: this.getNodeParameter('isExternal', i) as boolean, }; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/coorganizers/${coorganizerKey}/resendInvitation`; responseData = await goToWebinarApiRequest.call(this, 'POST', endpoint, qs, {}); responseData = { success: true }; } } else if (resource === 'panelist') { // ********************************************************************* // panelist // ********************************************************************* // https://developer.goto.com/GoToWebinarV2/#tag/Panelists if (operation === 'create') { // ---------------------------------- // panelist: create // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const body = [ { name: this.getNodeParameter('name', i) as string, email: this.getNodeParameter('email', i) as string, }, ] as IDataObject[]; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/panelists`; responseData = await goToWebinarApiRequest.call(this, 'POST', endpoint, {}, body); } else if (operation === 'delete') { // ---------------------------------- // panelist: delete // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const panelistKey = this.getNodeParameter('panelistKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/panelists/${panelistKey}`; responseData = await goToWebinarApiRequest.call(this, 'DELETE', endpoint, {}, {}); responseData = { success: true }; } else if (operation === 'getAll') { // ---------------------------------- // panelist: getAll // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/panelists`; responseData = await handleGetAll.call(this, endpoint, {}, {}, resource); } else if (operation === 'reinvite') { // ---------------------------------- // panelist: reinvite // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const panelistKey = this.getNodeParameter('panelistKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/panelists/${panelistKey}/resendInvitation`; responseData = await goToWebinarApiRequest.call(this, 'POST', endpoint, {}, {}); responseData = { success: true }; } } else if (resource === 'registrant') { // ********************************************************************* // registrant // ********************************************************************* // https://developer.goto.com/GoToWebinarV2/#tag/Registrants if (operation === 'create') { // ---------------------------------- // registrant: create // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const qs = {} as IDataObject; const body = { firstName: this.getNodeParameter('firstName', i) as string, lastName: this.getNodeParameter('lastName', i) as string, email: this.getNodeParameter('email', i) as string, responses: [], } as IDataObject; let additionalFields = this.getNodeParameter('additionalFields', i) as Partial<{ resendConfirmation: boolean, fullAddress: { details: { [key: string]: string } } simpleResponses: [ { [key: string]: string } ], multiChoiceResponses: [ { [key: string]: string } ], }>; if (additionalFields.resendConfirmation) { qs.resendConfirmation = additionalFields.resendConfirmation; additionalFields = omit(additionalFields, ['resendConfirmation']); } if (additionalFields.fullAddress) { Object.assign(body, additionalFields.fullAddress.details); additionalFields = omit(additionalFields, ['fullAddress']); } if (additionalFields.simpleResponses) { //@ts-ignore body.responses.push(...additionalFields.simpleResponses.details); additionalFields = omit(additionalFields, ['simpleResponses']); } if (additionalFields.multiChoiceResponses) { //@ts-ignore body.responses.push(...additionalFields.multiChoiceResponses.details); additionalFields = omit(additionalFields, ['multiChoiceResponses']); } Object.assign(body, additionalFields); const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/registrants`; responseData = await goToWebinarApiRequest.call(this, 'POST', endpoint, qs, body); } else if (operation === 'delete') { // ---------------------------------- // registrant: delete // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const registrantKey = this.getNodeParameter('registrantKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/registrants/${registrantKey}`; responseData = await goToWebinarApiRequest.call(this, 'DELETE', endpoint, {}, {}); responseData = { success: true }; } else if (operation === 'get') { // ---------------------------------- // registrant: get // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const registrantKey = this.getNodeParameter('registrantKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/registrants/${registrantKey}`; responseData = await goToWebinarApiRequest.call(this, 'GET', endpoint, {}, {}); } else if (operation === 'getAll') { // ---------------------------------- // registrant: getAll // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/registrants`; responseData = await handleGetAll.call(this, endpoint, {}, {}, resource); } } else if (resource === 'session') { // ********************************************************************* // session // ********************************************************************* // https://developer.goto.com/GoToWebinarV2/#tag/Sessions if (operation === 'get') { // ---------------------------------- // session: get // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const sessionKey = this.getNodeParameter('sessionKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/sessions/${sessionKey}`; responseData = await goToWebinarApiRequest.call(this, 'GET', endpoint, {}, {}); } else if (operation === 'getAll') { // ---------------------------------- // session: getAll // ---------------------------------- const qs = {} as IDataObject; const returnAll = this.getNodeParameter('returnAll', 0) as boolean; if (!returnAll) { qs.limit = this.getNodeParameter('limit', 0) as number; } const { webinarKey, times, } = this.getNodeParameter('additionalFields', i) as { filterByWebinar: boolean, webinarKey: string, times: { timesProperties: { [key: string]: string } } }; if (times) { qs.fromTime = moment(times.timesProperties.fromTime).format(); qs.toTime = moment(times.timesProperties.toTime).format(); } else { qs.fromTime = moment().subtract(1, 'years').format(); qs.toTime = moment().format(); } if (webinarKey !== undefined) { const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/sessions`; responseData = await goToWebinarApiRequestAllItems.call(this, 'GET', endpoint, qs, {}, resource); } else { const endpoint = `organizers/${organizerKey}/sessions`; responseData = await goToWebinarApiRequestAllItems.call(this, 'GET', endpoint, qs, {}, resource); } } else if (operation === 'getDetails') { // ---------------------------------- // session: getDetails // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const sessionKey = this.getNodeParameter('sessionKey', i) as string; const details = this.getNodeParameter('details', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}/sessions/${sessionKey}/${details}`; responseData = await goToWebinarApiRequest.call(this, 'GET', endpoint, {}, {}); } } else if (resource === 'webinar') { // ********************************************************************* // webinar // ********************************************************************* // https://developer.goto.com/GoToWebinarV2/#tag/Webinars if (operation === 'create') { // ---------------------------------- // webinar: create // ---------------------------------- const timesProperties = this.getNodeParameter('times.timesProperties', i, []) as IDataObject; const body = { subject: this.getNodeParameter('subject', i) as string, times: timesProperties, } as IDataObject; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const endpoint = `organizers/${organizerKey}/webinars`; responseData = await goToWebinarApiRequest.call(this, 'POST', endpoint, {}, body); } else if (operation === 'delete') { // ---------------------------------- // webinar: delete // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const { sendCancellationEmails } = this.getNodeParameter('additionalFields', i) as IDataObject; const qs = {} as IDataObject; if (sendCancellationEmails) { qs.sendCancellationEmails = sendCancellationEmails; } const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}`; await goToWebinarApiRequest.call(this, 'DELETE', endpoint, qs, {}); responseData = { success: true }; } else if (operation === 'get') { // ---------------------------------- // webinar: get // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}`; responseData = await goToWebinarApiRequest.call(this, 'GET', endpoint, {}, {}); } else if (operation === 'getAll') { // ---------------------------------- // webinar: getAll // ---------------------------------- const qs = {} as IDataObject; const returnAll = this.getNodeParameter('returnAll', 0) as boolean; if (!returnAll) { qs.limit = this.getNodeParameter('limit', 0) as number; } const { times } = this.getNodeParameter('additionalFields', i) as { times: { timesProperties: { [key: string]: string } } }; if (times) { qs.fromTime = moment(times.timesProperties.fromTime).format(); qs.toTime = moment(times.timesProperties.toTime).format(); } else { qs.fromTime = moment().subtract(1, 'years').format(); qs.toTime = moment().format(); } const endpoint = `accounts/${accountKey}/webinars`; responseData = await goToWebinarApiRequestAllItems.call(this, 'GET', endpoint, qs, {}, resource); } else if (operation === 'update') { // ---------------------------------- // webinar: update // ---------------------------------- const webinarKey = this.getNodeParameter('webinarKey', i) as string; const qs = { notifyParticipants: this.getNodeParameter('notifyParticipants', i) as boolean, } as IDataObject; let body = {}; let updateFields = this.getNodeParameter('updateFields', i) as IDataObject; if (updateFields.times) { const { times } = updateFields as { times: { timesProperties: Array<{ startTime: string, endTime: string }> } }; body = { times: times.timesProperties, } as IDataObject; updateFields = omit(updateFields, ['times']); } Object.assign(body, updateFields); if (isEmpty(updateFields)) { throw new NodeOperationError(this.getNode(), `Please enter at least one field to update for the ${resource}.`); } const endpoint = `organizers/${organizerKey}/webinars/${webinarKey}`; await goToWebinarApiRequest.call(this, 'PUT', endpoint, qs, body); responseData = { success: true }; } } } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } Array.isArray(responseData) ? returnData.push(...responseData) : returnData.push(responseData); } return [this.helpers.returnJsonArray(returnData)]; } }
the_stack
namespace LiteMol.Extensions.RNALoops { import Entity = Bootstrap.Entity; import Transformer = Bootstrap.Entity.Transformer; export interface LoopAnnotation extends Entity<Entity.Behaviour.Props<Interactivity.Behaviour>> { } export const LoopAnnotation = Entity.create<Entity.Behaviour.Props<Interactivity.Behaviour>>({ name: 'BGSU RNA Loops', typeClass: 'Behaviour', shortName: 'RL', description: 'Represents BGSU loop annotation.' }); export namespace Api { export interface ResidueRef { modelId: string, authAsymId: string, authSeqNumber: number, insCode: string } export interface Entry { id: string, type: 'IL' | 'HL' | 'J3', residues: ResidueRef[] } export interface Annotation { [modelId: string]: { [chainId: string]: { [resSeqNumber: number]: { [insCode: string]: Entry[] } } } } export function parseCSV(data: string) { const lines = data.split('\n'); const entries: Entry[] = []; for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); const comma = line.indexOf(','); if (comma < 0) continue; const id = line.substring(1, comma - 2); const type = (id[0] + id[1]) as Entry['type']; const residueIds = line.substring(comma + 2, line.length - 1).split(','); const residues: Entry['residues'] = []; for (let j = 0; j < residueIds.length; j++) { const t = residueIds[j].split('|'); residues.push({ modelId: t[1], authAsymId: t[2], authSeqNumber: +t[4], insCode: t[7] || '' }); } entries.push({ id, type, residues }); } return entries; } export function create(entries: Entry[]) { const annotation: Annotation = { }; if (!entries.length) { return annotation; } for (const entry of entries) { for (const residue of entry.residues) { const model = annotation[residue.modelId] || (annotation[residue.modelId] = { }); const chain = model[residue.authAsymId] || (model[residue.authAsymId] = { }); const seq = chain[residue.authSeqNumber] || (chain[residue.authSeqNumber] = { }); const ins = seq[residue.insCode] || (seq[residue.insCode] = []); ins[ins.length] = entry; } } return annotation; } export function getEntries(annotation: Annotation, modelId: string, asymId: string, seqNumber: number, insCode: string) { const m = annotation[modelId]; if (!m) return void 0; const c = m[asymId]; if (!c) return void 0; const r = c[seqNumber]; if (!r) return void 0; return r[insCode]; } } export namespace Interactivity { export class Behaviour implements Bootstrap.Behaviour.Dynamic { private provider: Bootstrap.Interactivity.HighlightProvider; dispose() { this.context.highlight.removeProvider(this.provider); } register(behaviour: any) { this.context.highlight.addProvider(this.provider); } private processInfo(info: Bootstrap.Interactivity.Info): string | undefined { const i = Bootstrap.Interactivity.Molecule.transformInteraction(info); if (!i || i.residues.length !== 1) return void 0; const r = i.residues[0]; const xs = Api.getEntries(this.annotation, i.modelId, r.chain.authAsymId, r.authSeqNumber, r.insCode || ''); if (!xs || !xs.length) return void 0; return 'RNA Loops: ' + xs.map(x => `<b>${x.type}</b> (${x.id})`).join(', '); } constructor(public context: Bootstrap.Context, public annotation: Api.Annotation) { this.provider = info => { try { return this.processInfo(info); } catch (e) { console.error('Error showing loop annotation label', e); return void 0; } }; } } } namespace Theme { const colorMap = (function () { const colors = Core.Utils.FastMap.create<number, LiteMol.Visualization.Color>(); colors.set(0, { r: 0x5B / 0xFF, g: 0xB7 / 0xFF, b: 0x5B / 0xFF }); // (IL): #5BB75B colors.set(1, { r: 0x49 / 0xFF, g: 0xAF / 0xFF, b: 0xCD / 0xFF }); // (HL): #49AFCD colors.set(2, { r: 0xCD / 0xFF, g: 0xAC / 0xFF, b: 0x4A / 0xFF }); // (J3): #CDAC4A colors.set(3, { r: 0.6, g: 0.6, b: 0.6 }); // not applicable return colors; })(); const defaultColor = <LiteMol.Visualization.Color>{ r: 0.6, g: 0.6, b: 0.6 }; const selectionColor = <LiteMol.Visualization.Color>{ r: 0, g: 0, b: 1 }; const highlightColor = <LiteMol.Visualization.Color>{ r: 1, g: 0, b: 1 }; function createResidueMapNormal(model: LiteMol.Core.Structure.Molecule.Model, annotation: Api.Annotation) { const map = new Uint8Array(model.data.residues.count); const mId = model.modelId; const { authAsymId, authSeqNumber, insCode } = model.data.residues; for (let i = 0, _b = model.data.residues.count; i < _b; i++) { const entries = Api.getEntries(annotation, mId, authAsymId[i], authSeqNumber[i], insCode[i] || ''); if (!entries) { map[i] = 3; continue; } const e = entries[0]; if (e.type === 'IL') map[i] = 0; else if (e.type === 'HL') map[i] = 1; else if (e.type === 'J3') map[i] = 2; else map[i] = 3; } return map; } function createResidueMapComputed(model: LiteMol.Core.Structure.Molecule.Model, annotation: Api.Annotation) { const map = new Uint8Array(model.data.residues.count); const mId = model.modelId; const parent = model.parent!; const { chainIndex, authSeqNumber, insCode } = model.data.residues; const { sourceChainIndex } = model.data.chains; const { authAsymId } = parent.data.chains; for (let i = 0, _b = model.data.residues.count; i < _b; i++) { const aId = authAsymId[sourceChainIndex![chainIndex[i]]]; const entries = Api.getEntries(annotation, mId, aId, authSeqNumber[i], insCode[i] || ''); if (!entries) { map[i] = 3; continue; } const e = entries[0]; if (e.type === 'IL') map[i] = 0; else if (e.type === 'HL') map[i] = 1; else if (e.type === 'J3') map[i] = 2; else map[i] = 3; } return map; } export function create(entity: Bootstrap.Entity.Molecule.Model, report: any) { const model = entity.props.model; const map = model.source === Core.Structure.Molecule.Model.Source.File ? createResidueMapNormal(model, report) : createResidueMapComputed(model, report); const colors = Core.Utils.FastMap.create<string, LiteMol.Visualization.Color>(); colors.set('Uniform', defaultColor) colors.set('Selection', selectionColor) colors.set('Highlight', highlightColor); const residueIndex = model.data.atoms.residueIndex; const mapping = Visualization.Theme.createColorMapMapping(i => map[residueIndex[i]], colorMap, defaultColor); return Visualization.Theme.createMapping(mapping, { colors, interactive: true, transparency: { alpha: 1.0 } }); } } const Create = Bootstrap.Tree.Transformer.create<Entity.Data.String, LoopAnnotation, { id?: string }>({ id: 'rna-loops-create', name: 'RNA Loops', description: 'Create the RNA loop annotation object from a string.', from: [Entity.Data.String], to: [LoopAnnotation], defaultParams: () => ({}) }, (context, a, t) => { return Bootstrap.Task.create<LoopAnnotation>(`RNA Loop Annotation (${t.params.id})`, 'Normal', async ctx => { await ctx.updateProgress('Parsing...'); const entries = Api.parseCSV(a.props.data); if (!entries.length) { throw new Error(`No RNA loop annotation for '${t.params.id}' is available.`); } const annotation = Api.create(entries); return LoopAnnotation.create(t, { label: 'RNA Loop Annotation', behaviour: new Interactivity.Behaviour(context, annotation) }); }).setReportTime(true); } ); export interface DownloadAndCreateProps { server: string, reportRef?: string } export const DownloadAndCreate = Bootstrap.Tree.Transformer.actionWithContext<Entity.Molecule.Molecule, Entity.Action, DownloadAndCreateProps, { reportRef: string }>({ id: 'rna-loops-download-and-create', name: 'BGSU RNA Loop Annotation', description: 'Download RNA loop annotation from BGSU', from: [Entity.Molecule.Molecule], to: [Entity.Action], defaultParams: (ctx) => ({ server: ctx.settings.get('extensions.rnaLoops.defaultServer') }) }, (context, a, t) => { const id = a.props.molecule.id.trim().toLocaleUpperCase(); const reportRef = t.params.reportRef || Bootstrap.Utils.generateUUID(); const action = Bootstrap.Tree.Transform.build() .add(a, Transformer.Data.Download, { url: t.params.server.replace('#id', id), type: 'String', id, description: 'Annotation Data', title: 'RNA Annotation' }) .then(Create, { id }, { isBinding: true, ref: reportRef }); return { action, context: { reportRef} }; }, (ctx, actionCtx) => { if (!actionCtx || !ctx.select(actionCtx.reportRef).length) { ctx.logger.error('Failed to load BGSU RNA annotation. Possible causes: no annotation available, server is down, server does not support HTTPS (use http:// in LiteMol URL to fix).'); return; } ctx.logger.info('BGSU RNA annotation loaded. Hovering over RNA residue will now contain loop info. To apply coloring, select the entity in the tree and apply it the right panel.'); }); export const ApplyTheme = Bootstrap.Tree.Transformer.create<LoopAnnotation, Entity.Action, { }>({ id: 'rna-loops-apply-theme', name: 'Apply Coloring', description: 'Colors RNA strands according to annotation of secondary structure loops.', from: [LoopAnnotation], to: [Entity.Action], defaultParams: () => ({}) }, (context, a, t) => { return Bootstrap.Task.create<Entity.Action>('RNA Annotation Coloring', 'Background', async ctx => { const molecule = Bootstrap.Tree.Node.findAncestor(a, Bootstrap.Entity.Molecule.Molecule); if (!molecule) { throw 'No suitable parent found.'; } const themes = Core.Utils.FastMap.create<number, Visualization.Theme>(); const visuals = context.select(Bootstrap.Tree.Selection.byValue(molecule).subtree().ofType(Bootstrap.Entity.Molecule.Visual)); for (const v of visuals) { const model = Bootstrap.Utils.Molecule.findModel(v); if (!model) continue; let theme = themes.get(model.id); if (!theme) { theme = Theme.create(model, a.props.behaviour.annotation); themes.set(model.id, theme); } Bootstrap.Command.Visual.UpdateBasicTheme.dispatch(context, { visual: v as any, theme }); } context.logger.message('RNA annotation coloring applied.'); return Bootstrap.Tree.Node.Null; }); }); }
the_stack
import { Component, ViewChild } from '@angular/core'; import { NavParams, Slides, ViewController, LoadingController, ToastController } from 'ionic-angular'; //Components import { ProgressBarComponent } from '../../components/progress-bar/progress-bar.component'; //Services import { StorageService } from '../../services/storage/storage.service'; import { SettingsService } from '../../services/settings/settings.service'; import { DeviceManagerService } from 'dip-angular2/services'; import { CommandUtilityService } from '../../services/device/command-utility.service'; import { UtilityService } from '../../services/utility/utility.service'; //Interfaces import { DeviceCardInfo } from '../device-manager-page/device-manager-page.interface'; declare var waveformsLiveDictionary: any; @Component({ templateUrl: 'update-firmware.html', }) export class UpdateFirmwarePage { @ViewChild('updateFirmwareSlider') slider: Slides; @ViewChild('digilentProgressBar') progressBarComponent: ProgressBarComponent; public storageService: StorageService; public settingsService: SettingsService; public loadingCtrl: LoadingController; public commandUtilityService: CommandUtilityService; public utilityService: UtilityService; public params: NavParams; public viewCtrl: ViewController; public deviceManagerService: DeviceManagerService; public toastCtrl: ToastController; public updateComplete: boolean = false; public deviceFirmwareVersion: string = ''; public latestFirmwareVersion: string = 'Unable to load latest firmware version. This may be due to no internet connection or a firewall.'; public updateStatus: string = 'Ready'; public deviceObject: DeviceCardInfo; public agentAddress: string; public firmwareUpToDate: boolean = false; public availableFirmwareVersions: string[] = ['None']; public selectedFirmwareVersion: string = ''; public hexFileStaged: boolean = false; public selectedFileInfo: { name: string, size: number } = { name: '', size: 0 }; public arrayBufferFirmware: ArrayBuffer; public uploadStatusAttemptCount: number = 0; public maxUploadStatusAttempts: number = 50; public errorUpdatingFirmware: boolean = false; public errorDevice: boolean = false; public listUrl: string = 'https://s3-us-west-2.amazonaws.com/digilent?prefix=Software/OpenScope+MZ/release/firmware/without-bootloader'; public firmwareRepositoryUrl: string = 'https://s3-us-west-2.amazonaws.com/digilent/Software/OpenScope+MZ/release/firmware/without-bootloader' constructor( _storageService: StorageService, _settingsService: SettingsService, _params: NavParams, _viewCtrl: ViewController, _cmdUtilSrv: CommandUtilityService, _utilSertice: UtilityService, _loadingCtrl: LoadingController, _deviceManagerService: DeviceManagerService, _toastCtrl: ToastController ) { this.deviceManagerService = _deviceManagerService; this.commandUtilityService = _cmdUtilSrv; this.utilityService = _utilSertice; this.storageService = _storageService; this.loadingCtrl = _loadingCtrl; this.settingsService = _settingsService; this.viewCtrl = _viewCtrl; this.params = _params; this.toastCtrl = _toastCtrl; this.agentAddress = this.params.get('agentAddress'); this.deviceObject = this.params.get('deviceObject'); console.log('update firmware constructor'); console.log(this.settingsService.useDevBuilds); if (this.settingsService.useDevBuilds) { this.listUrl = 'https://s3-us-west-2.amazonaws.com/digilent?prefix=Software/OpenScope+MZ/development/firmware/without-bootloader'; this.firmwareRepositoryUrl = 'https://s3-us-west-2.amazonaws.com/digilent/Software/OpenScope+MZ/development/firmware/without-bootloader'; } this.deviceManagerService.transport.setHttpTransport(this.deviceObject.deviceBridgeAddress); // note(andrew): In the edge case where a different device has been connected to the PC and has // the same COM port as the previous one, we double check the device here, // as programming the wrong firmware can damage the hardware this.checkDevice().then((descriptor) => { this.deviceObject.deviceDescriptor = descriptor; let deviceModel = this.utilityService.transformModelToPropKey(descriptor.deviceModel); let {listUrl, firmwareUrl} = this.settingsService.knownFirmwareUrls[deviceModel]; this.listUrl = listUrl; this.firmwareRepositoryUrl = firmwareUrl; this.getDeviceFirmware(); this.getFirmwareList(); }) .catch((err) => { console.log(err); this.toastCtrl.create({ message: 'Error connecting to the device', showCloseButton: true, duration: 3000 }).present(); this.viewCtrl.dismiss(); }); } public retrievedModel: string; /** * * @param expectedModel */ private checkDevice(): Promise<any>{ return new Promise((resolve, reject) => { let command = { device: [ {command: "enumerate"} ] } this.deviceManagerService.transport.writeRead("/", JSON.stringify(command), 'json').subscribe((res) => { let response = JSON.parse(String.fromCharCode.apply(null, new Int8Array(res.slice(0)))); let deviceDescriptor = response.device[0]; resolve(deviceDescriptor); }, (err) => { reject(err); }); }); } public cautionMessage() { return waveformsLiveDictionary.getMessage('firmwareCautionMessage').message; } getDeviceFirmware() { let firmwareVersionObject = this.deviceObject.deviceDescriptor.firmwareVersion; let deviceFirmwareVersion = [firmwareVersionObject.major, firmwareVersionObject.minor, firmwareVersionObject.patch].join('.'); this.deviceFirmwareVersion = deviceFirmwareVersion; } getFirmwareList() { this.deviceManagerService.getFirmwareVersionsFromUrl(this.listUrl).then((firmwareVersionArray: string[]) => { console.log(firmwareVersionArray); this.availableFirmwareVersions = firmwareVersionArray; this.getLatestFirmware(); this.availableFirmwareVersions.push('Other'); }).catch((e) => { console.log(e); this.availableFirmwareVersions = ['Other']; this.availableFirmwareVersionsChange('Other'); this.updateStatus = 'Unable to get firmware versions. Please upload a local hex file.'; }); } getFirmwareFromUrl(firmwareUrl: string): Promise<any> { return new Promise((resolve, reject) => { this.deviceManagerService.transport.getRequest(firmwareUrl, 30000).subscribe( (data) => { //console.log(data); console.log('got hex file'); if (data.indexOf('Error') !== -1) { reject('Error getting file'); return; } let buf = new ArrayBuffer(data.length); let bufView = new Uint8Array(buf); for (var i = 0; i < data.length; i < i++) { bufView[i] = data.charCodeAt(i); } this.arrayBufferFirmware = buf; this.postHexFile() .then(() => { resolve(); }) .catch((e) => { reject(e); }); }, (err) => { console.log(err); reject(err); }, () => { } ); }); } availableFirmwareVersionsChange(event) { console.log(event); this.selectedFirmwareVersion = event; if (event === 'Other') { this.hexFileStaged = true; if (this.selectedFileInfo.size !== 0) { this.updateStatus = 'Ready to upload "' + this.selectedFileInfo.name + '". File size is ' + this.selectedFileInfo.size + ' bytes.'; this.firmwareUpToDate = false; } else { this.firmwareUpToDate = true; this.updateStatus = 'Select a hex file to upload'; } return; } this.hexFileStaged = false; this.firmwareUpToDate = this.deviceFirmwareVersion === event; if (this.firmwareUpToDate) { this.updateStatus = 'Firmware up to date'; return; } this.updateStatus = 'Ready to upload firmware version ' + event; } openFileInput() { document.getElementById('updateFileSelect').click(); } fileChange(event) { if (event.target.files.length === 0) { return; } let fileReader = new FileReader(); let fileName = event.target.files[0].name; this.selectedFileInfo.name = fileName; this.updateStatus = 'Ready to upload "' + fileName + '".'; let fileNameSplit = fileName.split('.'); let fileEnding = fileNameSplit[fileNameSplit.length - 1]; if (fileEnding === 'hex') { fileReader.onload = ((file: any) => { this.updateStatus += '\r\nFile size is ' + file.loaded + ' bytes.'; this.selectedFileInfo.size = parseInt(file.loaded); this.arrayBufferFirmware = file.target.result; this.firmwareUpToDate = false; }); fileReader.readAsArrayBuffer(event.target.files[0]); } else { alert('You Must Upload A Hex File'); } } getLatestFirmware() { //TODO: read device enum for ip address and then call device man service getFirmwareVersionsFromUrl this.latestFirmwareVersion = this.deviceManagerService.getLatestFirmwareVersionFromArray(this.availableFirmwareVersions); this.firmwareUpToDate = this.latestFirmwareVersion === this.deviceFirmwareVersion; if (this.firmwareUpToDate) { this.updateStatus = 'Your device firmware is up to date'; } this.selectedFirmwareVersion = this.latestFirmwareVersion; } displayLoading(message?: string) { message = message || 'Transferring Hex File...'; let loading = this.loadingCtrl.create({ content: message, spinner: 'crescent', cssClass: 'custom-loading-indicator' }); loading.present(); return loading; } //Need to use this lifestyle hook to make sure the slider exists before trying to get a reference to it ionViewDidEnter() { let swiperInstance: any = this.slider.getSlider(); if (swiperInstance == undefined) { setTimeout(() => { this.ionViewDidEnter(); }, 20); return; } swiperInstance.lockSwipes(); } toProgressBar() { console.log(this.selectedFirmwareVersion); let loading = this.displayLoading(); this.sendHexFile() .then(() => { this.updateStatus = 'Updating firmware'; let swiperInstance: any = this.slider.getSlider(); swiperInstance.unlockSwipes(); this.slider.slideTo(1); swiperInstance.lockSwipes(); this.progressBarComponent.manualStart(); this.getUploadStatus(); loading.dismiss(); }) .catch((e) => { console.log('Error caught trying to upload the firmware:', e); loading.dismiss(); this.updateStatus = 'Error uploading firmware. Please try again.'; }); } sendHexFile(): Promise<any> { return new Promise((resolve, reject) => { if (this.selectedFirmwareVersion === 'Other' && !this.arrayBufferFirmware) { this.updateStatus = 'Please select a hex file to upload or choose from the default firmware.'; reject(); } else if (this.selectedFirmwareVersion === 'Other' && this.arrayBufferFirmware) { this.postHexFile() .then(() => { resolve(); }) .catch((e) => { reject(e); }); } else { let device = this.deviceObject.deviceDescriptor.deviceModel.replace(" ", ""); this.getFirmwareFromUrl(this.firmwareRepositoryUrl + `/${device}-` + this.selectedFirmwareVersion + '.hex') .then(() => { resolve(); }) .catch((e) => { reject(e); }); } }); } getUploadStatus() { let command = { "agent": [ { "command": "updateFirmwareGetStatus" } ] }; this.deviceManagerService.transport.writeRead('/config', JSON.stringify(command), 'json').subscribe( (data) => { this.arrayBufferToObject(data) .then((parsedData) => { if (parsedData.agent == undefined || parsedData.agent[0].statusCode !== 0) { this.updateStatus = 'Error uploading firmware'; this.errorUpdatingFirmware = true; } if (parsedData.agent[0].status && parsedData.agent[0].status === 'uploading' && parsedData.agent[0].progress) { this.progressBarComponent.manualUpdateVal(parsedData.agent[0].progress); } if (parsedData.agent[0].status !== 'idle' && this.uploadStatusAttemptCount < this.maxUploadStatusAttempts) { console.log('update is still running'); this.uploadStatusAttemptCount++; setTimeout(() => { this.getUploadStatus(); }, 1000); return; } if (parsedData.agent[0].status === 'idle') { this.progressBarComponent.manualUpdateVal(100); return; } this.updateStatus = 'Error uploading firmware'; this.errorUpdatingFirmware = true; }) .catch((parsedData) => { if (parsedData.agent && parsedData.agent[0].status && parsedData.agent[0].status === 'uploading' && parsedData.agent[0].progress) { this.progressBarComponent.manualUpdateVal(parsedData.agent[0].progress); } if ((parsedData.agent == undefined || parsedData.agent[0].statusCode > 0 || parsedData.agent[0].status !== 'idle') && this.uploadStatusAttemptCount < this.maxUploadStatusAttempts) { console.log('statusCode error'); this.uploadStatusAttemptCount++; setTimeout(() => { this.getUploadStatus(); }, 1000); return; } if (parsedData.agent[0].status === 'idle') { this.progressBarComponent.manualUpdateVal(100); } }); }, (err) => { console.log(err); }, () => { } ); } doneUpdating() { let loading = this.displayLoading('Reconnecting To Device'); this.uploadStatusAttemptCount = 0; this.enterJsonModeAttemptWrapper(loading); } enterJsonModeAttemptWrapper(loadingRef: any) { setTimeout(() => { this.enterJsonMode() .then(() => { console.log('entered json mode'); this.updateComplete = true; this.updateStatus = 'Update complete!'; loadingRef.dismiss(); }) .catch((e) => { console.log(e); if (this.uploadStatusAttemptCount < this.maxUploadStatusAttempts) { this.uploadStatusAttemptCount++; this.enterJsonModeAttemptWrapper(loadingRef); } else { loadingRef.dismiss(); this.updateStatus = 'Update failed.'; this.errorUpdatingFirmware = true; } }); }, 1000); } enterJsonMode(): Promise<any> { let command = { "agent": [ { "command": "enterJsonMode" } ] }; return new Promise((resolve, reject) => { this.deviceManagerService.transport.writeRead('/config', JSON.stringify(command), 'json').subscribe( (arrayBuffer) => { console.log('enter json mode'); let data; try { let stringify = String.fromCharCode.apply(null, new Int8Array(arrayBuffer.slice(0))); console.log(stringify); data = JSON.parse(stringify); } catch (e) { console.log('Error Parsing JSON mode Device Response'); console.log(e); reject(e); } if (data.agent[0] == undefined || data.agent[0].statusCode > 0) { reject(data); return; } console.log(data); resolve(data); }, (err) => { console.log(err); reject(err); }, () => { } ); }); } closeModal() { this.viewCtrl.dismiss(); } postHexFile(): Promise<any> { //this.processBinaryDataAndSend(this.arrayBufferFirmware); return new Promise((resolve, reject) => { this.deviceManagerService.transport.writeRead('/config', this.generateOsjb(this.arrayBufferFirmware), 'binary').subscribe( (data) => { this.arrayBufferToObject(data) .then((data) => { resolve(data); }) .catch((e) => { reject(e); }); }, (err) => { console.log(err); reject(err); }, () => { } ); }); } generateOsjb(firmwareArrayBuffer: ArrayBuffer) { let commandObject = { agent: [ { command: "saveToTempFile", fileName: "openscope-mz-firmware.hex" }, { command: 'uploadFirmware', firmwarePath: 'openscope-mz-firmware.hex', enterBootloader: true } ] }; let temp = this.commandUtilityService.createChunkedArrayBuffer(commandObject, firmwareArrayBuffer); console.log(temp); return temp; } arrayBufferToObject(arrayBuffer): Promise<any> { return new Promise((resolve, reject) => { let data; try { let stringify = String.fromCharCode.apply(null, new Int8Array(arrayBuffer.slice(0))); console.log(stringify); data = JSON.parse(stringify); } catch (e) { reject(data); return; } if (data.agent == undefined || data.agent[0].statusCode > 0) { reject(data); return; } for (let i = 0; i < data.agent.length; i++) { if (data.agent[i].statusCode > 0) { reject(data); return; } } resolve(data); }); } }
the_stack
import path from 'path'; import { cloneDeep } from 'lodash'; import { MappingExporter, Package } from '../../src/export'; import { FSHDocument, FSHTank } from '../../src/import'; import { TestFisher } from '../testhelpers'; import { loggerSpy } from '../testhelpers'; import { FHIRDefinitions, loadFromPath } from '../../src/fhirdefs'; import { StructureDefinition } from '../../src/fhirtypes'; import { Mapping, RuleSet } from '../../src/fshtypes'; import { MappingRule, InsertRule, AssignmentRule } from '../../src/fshtypes/rules'; import { minimalConfig } from '../utils/minimalConfig'; describe('MappingExporter', () => { let defs: FHIRDefinitions; let doc: FSHDocument; let exporter: MappingExporter; let observation: StructureDefinition; let practitioner: StructureDefinition; let logical: StructureDefinition; let resource: StructureDefinition; beforeAll(() => { defs = new FHIRDefinitions(); loadFromPath(path.join(__dirname, '..', 'testhelpers', 'testdefs'), 'r4-definitions', defs); }); beforeEach(() => { loggerSpy.reset(); doc = new FSHDocument('fileName'); const input = new FSHTank([doc], minimalConfig); const pkg = new Package(input.config); const fisher = new TestFisher(input, defs, pkg); exporter = new MappingExporter(input, pkg, fisher); observation = fisher.fishForStructureDefinition('Observation'); observation.id = 'MyObservation'; pkg.profiles.push(observation); practitioner = fisher.fishForStructureDefinition('Practitioner'); practitioner.id = 'MyPractitioner'; pkg.profiles.push(practitioner); logical = fisher.fishForStructureDefinition('eLTSSServiceModel'); logical.id = 'MyLogical'; pkg.logicals.push(logical); resource = fisher.fishForStructureDefinition('Duration'); resource.id = 'MyResource'; pkg.resources.push(resource); }); it('should log an error when the mapping source does not exist', () => { /** * Mapping: MyMapping * Source: MyInvalidSource */ const mapping = new Mapping('MyMapping').withFile('NoSource.fsh').withLocation([1, 2, 3, 4]); mapping.source = 'MyInvalidSource'; doc.mappings.set(mapping.name, mapping); exporter.export(); expect(loggerSpy.getLastMessage('error')).toMatch( /Unable to find source "MyInvalidSource".*File: NoSource\.fsh.*Line: 1 - 3\D*/s ); }); describe('#setMetadata', () => { it('should export no mappings with empty input', () => { const originalLength = observation.mapping.length; exporter.export(); expect(observation.mapping.length).toBe(originalLength); }); it('should export the simplest possible mapping', () => { /** * Mapping: MyMapping * Source: MyObservation */ const originalLength = observation.mapping.length; const mapping = new Mapping('MyMapping'); mapping.source = 'MyObservation'; doc.mappings.set(mapping.name, mapping); exporter.export(); expect(observation.mapping.length).toBe(originalLength + 1); const exported = observation.mapping.slice(-1)[0]; expect(exported.identity).toBe('MyMapping'); }); it('should export a mapping when one does not yet exist', () => { /** * Mapping: MyMapping * Source: MyObservation */ delete observation.mapping; const mapping = new Mapping('MyMapping'); mapping.source = 'MyObservation'; doc.mappings.set(mapping.name, mapping); exporter.export(); expect(observation.mapping.length).toBe(1); const exported = observation.mapping.slice(-1)[0]; expect(exported.identity).toBe('MyMapping'); }); it('should export a mapping with optional metadata', () => { /** * Mapping: MyMapping * Id: my-map * Source: MyObservation * Target: "http://mytarget.com" * Description: "Hello there" * Title: "HEY THERE" */ const originalLength = observation.mapping.length; const mapping = new Mapping('MyMapping'); mapping.id = 'my-map'; mapping.source = 'MyObservation'; mapping.target = 'http://mytarget.com'; mapping.description = 'Hello there'; mapping.title = 'HEY THERE'; doc.mappings.set(mapping.name, mapping); exporter.export(); expect(observation.mapping.length).toBe(originalLength + 1); const exported = observation.mapping.slice(-1)[0]; expect(exported.identity).toBe('my-map'); expect(exported.name).toBe('HEY THERE'); expect(exported.uri).toBe('http://mytarget.com'); expect(exported.comment).toBe('Hello there'); }); it('should log an error and not apply a mapping with an invalid Id', () => { /** * Mapping: MyMapping * Source: MyObservation * Id: Invalid! */ const originalLength = observation.mapping.length; const mapping = new Mapping('MyMapping') .withLocation([1, 2, 3, 4]) .withFile('BadMapping.fsh'); mapping.source = 'MyObservation'; mapping.id = 'Invalid!'; doc.mappings.set(mapping.name, mapping); exporter.export(); expect(observation.mapping.length).toBe(originalLength); expect(loggerSpy.getLastMessage('error')).toMatch( /The string "Invalid!" does not represent a valid FHIR id/ ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: BadMapping\.fsh.*Line: 1 - 3\D*/s); }); it('should log an error when multiple mappings have the same source and the same id', () => { /** * Mapping: FirstMapping * Source: MyObservation * Id: reused-id * * Mapping: SecondMapping * Source: MyObservation * Id: reused-id */ const firstMapping = new Mapping('FirstMapping') .withFile('Mappings.fsh') .withLocation([3, 8, 7, 18]); firstMapping.source = 'MyObservation'; firstMapping.id = 'reused-id'; doc.mappings.set(firstMapping.name, firstMapping); const secondMapping = new Mapping('SecondMapping') .withFile('Mappings.fsh') .withLocation([8, 8, 11, 19]); secondMapping.source = 'MyObservation'; secondMapping.id = 'reused-id'; doc.mappings.set(secondMapping.name, secondMapping); exporter.export(); expect(loggerSpy.getLastMessage('error')).toMatch( /Multiple mappings on MyObservation found with id reused-id/ ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Mappings\.fsh.*Line: 8 - 11\D*/s); }); it('should not log an error when multiple mappings have different sources and the same id', () => { /** * Mapping: FirstMapping * Source: MyObservation * Id: reused-id * * Mapping: SecondMapping * Source: MyPractitioner * Id: reused-id */ const firstMapping = new Mapping('FirstMapping') .withFile('Mappings.fsh') .withLocation([3, 8, 7, 18]); firstMapping.source = 'MyObservation'; firstMapping.id = 'reused-id'; doc.mappings.set(firstMapping.name, firstMapping); const secondMapping = new Mapping('SecondMapping') .withFile('Mappings.fsh') .withLocation([8, 8, 11, 19]); secondMapping.source = 'MyPractitioner'; secondMapping.id = 'reused-id'; doc.mappings.set(secondMapping.name, secondMapping); exporter.export(); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); }); it('should not log an error and not add metadata but add rules for a simple Mapping that is inherited from the parent', () => { /** * Mapping: rim * Source: MyObservation * * status -> "Something.new" */ const mapping = new Mapping('rim'); mapping.source = 'MyObservation'; const newRule = new MappingRule('status'); newRule.map = 'Something.new'; mapping.rules.push(newRule); doc.mappings.set(mapping.name, mapping); const originalMappingLength = observation.mapping.length; const status = observation.elements.find(e => e.id === 'Observation.status'); const originalStatusMappingLength = status.mapping.length; const originalRimMapping = cloneDeep(observation.mapping.find(m => m.identity === 'rim')); exporter.export(); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(observation.mapping.length).toBe(originalMappingLength); // No metadata added expect(status.mapping.length).toBe(originalStatusMappingLength + 1); // New rule added to status element // Metadata is same as the parent const rimMapping = observation.mapping.find(m => m.identity === 'rim'); expect(rimMapping).toEqual(originalRimMapping); }); it('should not log an error and not add metadata but add rules for a Mapping that is inherited from the parent with the same metadata', () => { /** * Mapping: rim * Id: rim * Source: MyObservation * Title: "RIM Mapping" * Target: "http://hl7.org/v3" * * status -> "Something.new" */ const mapping = new Mapping('rim'); mapping.source = 'MyObservation'; mapping.id = 'rim'; mapping.title = 'RIM Mapping'; mapping.target = 'http://hl7.org/v3'; const newRule = new MappingRule('status'); newRule.map = 'Something.new'; mapping.rules.push(newRule); doc.mappings.set(mapping.name, mapping); const originalMappingLength = observation.mapping.length; const status = observation.elements.find(e => e.id === 'Observation.status'); const originalStatusMappingLength = status.mapping.length; exporter.export(); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(observation.mapping.length).toBe(originalMappingLength); // No metadata added expect(status.mapping.length).toBe(originalStatusMappingLength + 1); // New rule added to status element }); it('should not log an error, should update metadata, and should add rules for a Mapping that is inherited from the parent and has additional metadata not on the parent', () => { /** * Mapping: rim * Source: MyObservation * Description: "A totally new description" * * status -> "Something.new" */ const mapping = new Mapping('rim'); mapping.source = 'MyObservation'; mapping.description = 'A totally new description'; // There is no comment on the parent rim mapping const newRule = new MappingRule('status'); newRule.map = 'Something.new'; mapping.rules.push(newRule); doc.mappings.set(mapping.name, mapping); const originalMappingLength = observation.mapping.length; const status = observation.elements.find(e => e.id === 'Observation.status'); const originalStatusMappingLength = status.mapping.length; const originalRimMapping = cloneDeep(observation.mapping.find(m => m.identity === 'rim')); exporter.export(); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(observation.mapping.length).toBe(originalMappingLength); // No metadata added expect(status.mapping.length).toBe(originalStatusMappingLength + 1); // New rule added to status element // New comment (Description) is added to mapping, all other metadata should be the same const rimMapping = observation.mapping.find(m => m.identity === 'rim'); originalRimMapping.comment = 'A totally new description'; // Description is added expect(rimMapping).toEqual(originalRimMapping); }); it('should log an error and not add mapping or rules when a Mapping has the same identity as one on the parent but name or uri differs', () => { /** * Mapping: rim * Id: rim * Source: MyObservation * Title: "RIM Mapping" * Target: "http://real.org/not" * * status -> "Something.new" */ const mapping = new Mapping('rim'); mapping.source = 'MyObservation'; mapping.id = 'rim'; mapping.title = 'RIM Mapping'; mapping.target = 'http://real.org/not'; const newRule = new MappingRule('status'); newRule.map = 'Something.new'; mapping.rules.push(newRule); doc.mappings.set(mapping.name, mapping); const originalMappingLength = observation.mapping.length; const status = observation.elements.find(e => e.id === 'Observation.status'); const originalStatusMappingLength = status.mapping.length; exporter.export(); expect(loggerSpy.getAllMessages('error')).toHaveLength(1); expect(observation.mapping.length).toBe(originalMappingLength); // No metadata added expect(status.mapping.length).toBe(originalStatusMappingLength); // No rule added to status element }); }); describe('#setMappingRules', () => { let mapping: Mapping; beforeEach(() => { mapping = new Mapping('MyMapping'); mapping.source = 'MyObservation'; doc.mappings.set(mapping.name, mapping); }); it('should apply a valid mapping rule', () => { /** * Mapping: MyMapping * Source: MyObservation * * status -> "Observation.otherStatus" */ const mapRule = new MappingRule('status'); mapRule.map = 'Observation.otherStatus'; mapping.rules.push(mapRule); const status = observation.elements.find(e => e.id === 'Observation.status'); const originalLength = status.mapping.length; exporter.export(); expect(status.mapping.length).toBe(originalLength + 1); const exported = status.mapping.slice(-1)[0]; expect(exported.map).toBe('Observation.otherStatus'); expect(exported.identity).toBe('MyMapping'); }); it('should apply a valid mapping rule with no path', () => { /** * Mapping: MyMapping * Source: MyObservation * * -> "OtherObservation" */ const mapRule = new MappingRule(''); mapRule.map = 'OtherObservation'; mapping.rules.push(mapRule); const baseElement = observation.elements.find(e => e.id === 'Observation'); const originalLength = baseElement.mapping.length; exporter.export(); expect(baseElement.mapping.length).toBe(originalLength + 1); const exported = baseElement.mapping.slice(-1)[0]; expect(exported.map).toBe('OtherObservation'); expect(exported.identity).toBe('MyMapping'); }); it('should apply a valid mapping rule with a Logical source', () => { /** * Mapping: MyMapping * Source: MyLogical * * name -> "Something.provider.name" */ mapping.source = 'MyLogical'; const mapRule = new MappingRule('name'); mapRule.map = 'Something.provider.name'; mapping.rules.push(mapRule); const baseName = logical.elements.find(e => e.id === 'eLTSSServiceModel.name'); expect(baseName.mapping).toBeUndefined(); exporter.export(); expect(baseName.mapping).toHaveLength(1); expect(baseName.mapping[0].identity).toBe('MyMapping'); expect(baseName.mapping[0].map).toBe('Something.provider.name'); }); it('should apply a valid mapping rule with a Resource source', () => { /** * Mapping: MyMapping * Source: MyResource * * comparator -> "Something.operator" */ mapping.source = 'MyResource'; const mapRule = new MappingRule('comparator'); mapRule.map = 'Something.operator'; mapping.rules.push(mapRule); const baseComparator = resource.elements.find(e => e.id === 'Duration.comparator'); const originalMappingLength = baseComparator.mapping.length; exporter.export(); expect(baseComparator.mapping).toHaveLength(originalMappingLength + 1); const exported = baseComparator.mapping.slice(-1)[0]; expect(exported.identity).toBe('MyMapping'); expect(exported.map).toBe('Something.operator'); }); it('should log an error and skip rules with paths that cannot be found', () => { /** * Mapping: MyMapping * Source: MyObservation * * notAPath -> "whoCares" * * status -> "Observation.otherStatus" */ const fakePathRule = new MappingRule('notAPath') .withFile('BadRule.fsh') .withLocation([1, 2, 1, 3]); fakePathRule.map = 'whoCares'; mapping.rules.push(fakePathRule); const statusRule = new MappingRule('status'); statusRule.map = 'Observation.otherStatus'; mapping.rules.push(statusRule); const status = observation.elements.find(e => e.id === 'Observation.status'); const originalLength = status.mapping.length; exporter.export(); // valid rule on status should still be applied expect(status.mapping.length).toBe(originalLength + 1); const exported = status.mapping.slice(-1)[0]; expect(exported.map).toBe('Observation.otherStatus'); expect(exported.identity).toBe('MyMapping'); expect(loggerSpy.getLastMessage('error')).toMatch( /No element found at path notAPath for MyMapping.*File: BadRule\.fsh.*Line: 1\D*/s ); }); it('should log an error and skip rules with invalid mappings', () => { /** * Mapping: MyMapping * Source: MyObservation * * category -> * * status -> "Observation.otherStatus" */ const noTargetRule = new MappingRule('category') .withFile('BadRule.fsh') .withLocation([1, 2, 1, 3]); mapping.rules.push(noTargetRule); const statusRule = new MappingRule('status'); statusRule.map = 'Observation.otherStatus'; mapping.rules.push(statusRule); const status = observation.elements.find(e => e.id === 'Observation.status'); const originalLength = status.mapping.length; exporter.export(); // valid rule on status should still be applied expect(status.mapping.length).toBe(originalLength + 1); const exported = status.mapping.slice(-1)[0]; expect(exported.map).toBe('Observation.otherStatus'); expect(exported.identity).toBe('MyMapping'); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid mapping, mapping.identity and mapping.map are 1..1 and must be set.*File: BadRule\.fsh.*Line: 1\D*/s ); }); }); describe('#insertRules', () => { let mapping: Mapping; let ruleSet: RuleSet; beforeEach(() => { mapping = new Mapping('Foo'); mapping.source = 'MyObservation'; doc.mappings.set(mapping.name, mapping); ruleSet = new RuleSet('Bar'); doc.ruleSets.set(ruleSet.name, ruleSet); }); it('should apply rules from an insert rule', () => { // RuleSet: Bar // * status -> Observation.otherStatus // // Mapping: Foo // * insert Bar const mapRule = new MappingRule('status'); mapRule.map = 'Observation.otherStatus'; ruleSet.rules.push(mapRule); const insertRule = new InsertRule(''); insertRule.ruleSet = 'Bar'; mapping.rules.push(insertRule); exporter.export(); const status = observation.elements.find(e => e.id === 'Observation.status'); const exported = status.mapping.slice(-1)[0]; expect(exported.map).toBe('Observation.otherStatus'); expect(exported.identity).toBe('Foo'); }); it('should log an error and not apply rules from an invalid insert rule', () => { // RuleSet: Bar // * experimental = true // * status -> Observation.otherStatus // // Mapping: Foo // * insert Bar const valueRule = new AssignmentRule('experimental') .withFile('Value.fsh') .withLocation([1, 2, 3, 4]); valueRule.value = true; const mapRule = new MappingRule('status'); mapRule.map = 'Observation.otherStatus'; ruleSet.rules.push(mapRule); ruleSet.rules.push(valueRule, mapRule); const insertRule = new InsertRule('').withFile('Insert.fsh').withLocation([5, 6, 7, 8]); insertRule.ruleSet = 'Bar'; mapping.rules.push(insertRule); exporter.export(); // mapping rule is still applied const status = observation.elements.find(e => e.id === 'Observation.status'); const exported = status.mapping.slice(-1)[0]; expect(exported.map).toBe('Observation.otherStatus'); expect(exported.identity).toBe('Foo'); expect(loggerSpy.getLastMessage('error')).toMatch( /AssignmentRule.*Mapping.*File: Value\.fsh.*Line: 1 - 3.*Applied in File: Insert\.fsh.*Applied on Line: 5 - 7/s ); }); }); });
the_stack
import { IDataOptions, IDataSet } from '../../src/base/engine'; import { pivot_nodata } from '../base/datasource.spec'; import { PivotView } from '../../src/pivotview/base/pivotview'; import { createElement, remove, extend } from '@syncfusion/ej2-base'; import { FieldList } from '../../src/common/actions/field-list'; import { CalculatedField } from '../../src/common/calculatedfield/calculated-field'; import { VirtualScroll } from '../../src/pivotview/actions'; import { profile, inMB, getMemoryProfile } from '../common.spec'; describe(' - no data', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe(' - no data', () => { let pivotGridObj: PivotView; let elem: HTMLElement = createElement('div', { id: 'PivotGrid' }); let noData: IDataSet[] = [ { "Teams": "Application Support", "Priority": "p1", "Calls": 4 }, { "Teams": "Application Support", "Priority": "p2", "Calls": 1 }, { "Teams": "Application Support", "Priority": "p3", "Calls": 2 }, { "Teams": "Service Desk", "Priority": "p1", "Calls": 4 }, { "Teams": "Service Desk", "Priority": "p2", "Calls": 1 }, { "Teams": "Service Desk", "Priority": "p3", "Calls": 2 }, { "Teams": "Network Support", "Priority": "p4", "Calls": 5 }, { "Teams": "Network Support", "Priority": "p5", "Calls": 6 } ]; document.body.appendChild(elem); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll(() => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); PivotView.Inject(FieldList, CalculatedField); pivotGridObj = new PivotView({ dataSourceSettings: { expandAll: true, dataSource: noData as IDataSet[], rows: [{ name: 'Teams', showNoDataItems: true }], columns: [{ name: 'Priority', showNoDataItems: true }], values: [{ name: 'Calls', showNoDataItems: true }], allowLabelFilter: true, allowValueFilter: true }, showFieldList: true, allowCalculatedField: true, height: 400 }); pivotGridObj.appendTo('#PivotGrid'); }); let dataSourceSettings: IDataOptions it('pivotgrid render testing', (done: Function) => { dataSourceSettings = extend({}, pivotGridObj.dataSourceSettings, null, true); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Network Support'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="4"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('5'); done(); }, 1000); }); it('priority to row', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { rows: [{ name: 'Teams', showNoDataItems: true }, { name: 'Priority', showNoDataItems: true }] } }, true); pivotGridObj.dataSourceSettings.columns = []; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { // expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Application Support'); // expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[4] as HTMLElement).innerText).toBe('p4'); // expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[4] as HTMLElement).innerText).toBe(''); done(); }, 1000); }); it('swap row elements', (done: Function) => { pivotGridObj.dataSourceSettings.rows = [ { name: 'Priority', showNoDataItems: true }, { name: 'Teams', showNoDataItems: true } ]; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('Network Support'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[6] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[14] as HTMLElement).innerText).toBe('Network Support'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[14] as HTMLElement).innerText).toBe('5'); done(); }, 1000); }); it('swap to columns', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { rows: [] } }, true); pivotGridObj.dataSourceSettings.columns = [ { name: 'Priority', showNoDataItems: true }, { name: 'Teams', showNoDataItems: true } ]; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="13"] .e-cellvalue')[0] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('th[aria-colindex="13"] .e-headertext')[0] as HTMLElement).innerText).toBe('Application Support'); expect((document.querySelectorAll('td[aria-colindex="14"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('5'); expect((document.querySelectorAll('th[aria-colindex="14"] .e-headertext')[0] as HTMLElement).innerText).toBe('Network Support'); done(); }, 1000); }); it('swap to rows', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { columns: [] } }, true); pivotGridObj.dataSourceSettings.rows = [ { name: 'Priority', showNoDataItems: true }, { name: 'Teams', showNoDataItems: true } ]; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('Network Support'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[6] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[14] as HTMLElement).innerText).toBe('Network Support'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[14] as HTMLElement).innerText).toBe('5'); done(); }, 1000); }); it('exclude p4,p5', (done: Function) => { pivotGridObj.dataSourceSettings.rows = [ { name: 'Teams', showNoDataItems: true }, { name: 'Priority', showNoDataItems: true } ]; pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'Priority', type: 'Exclude', items: ['p4', 'p5'] } ], jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[4] as HTMLElement).innerText).toBe('Network Support'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[4] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[8] as HTMLElement).innerText).toBe('7'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[7] as HTMLElement).innerText).toBe(''); done(); }, 1000); }); it('exclude p1,p2,p3', (done: Function) => { pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'Priority', type: 'Include', items: ['p4', 'p5'] } ], jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Application Support'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('p4'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Network Support'); done(); }, 1000); }); it('dont show priority no items', (done: Function) => { pivotGridObj.dataSourceSettings.rows[1].showNoDataItems = false; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Application Support'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('p4'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Network Support'); done(); }, 1000); }); it('sort teams', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { sortSettings: [{ name: 'Teams', order: 'Descending' }] } }, true); pivotGridObj.dataSourceSettings.rows[1].showNoDataItems = true; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Service Desk'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('p4'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Network Support'); done(); }, 1000); }); it('sort priority', (done: Function) => { pivotGridObj.dataSourceSettings.sortSettings = [{ name: 'Priority', order: 'Descending' }]; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Application Support'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('p5'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Network Support'); done(); }, 1000); }); it('change data source', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { dataSource: pivot_nodata, expandAll: false, drilledMembers: [{ name: 'Country', items: ['Canada'] }], rows: [{ name: 'Country', showNoDataItems: true }, { name: 'State', showNoDataItems: true }], columns: [{ name: 'Product', showNoDataItems: true }, { name: 'Date', showNoDataItems: true }], values: [{ name: 'Amount' }, { name: 'Quantity' }], filters: [], filterSettings: [] } }, true); pivotGridObj.dataSourceSettings.sortSettings = []; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('99960'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alabama'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Bayern'); done(); }, 1000); }); it('filter state BeginWith e', (done: Function) => { pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Label', condition: 'BeginWith', value1: 'e' } ] jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('England'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('France'); done(); }, 1000); }); it('filter state DoesNotBeginWith e', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { drilledMembers: [{ name: 'Country', items: ['United Kingdom'] }] } }); pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Label', condition: 'DoesNotBeginWith', value1: 'e' } ] jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('United Kingdom'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[3] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[13] as HTMLElement).innerText).toBe('Garonne (Haute)'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[13] as HTMLElement).innerText).toBe(''); done(); }, 1000); }); it('state nodata false', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { rows: [{ name: 'Country', showNoDataItems: true }, { name: 'State', showNoDataItems: false }], drilledMembers: [{ name: 'Country', items: ['Canada'] }], } }, true); pivotGridObj.dataSourceSettings.filterSettings = []; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('99960'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alberta'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('5250'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Brunswick'); done(); }, 1000); }); it('filter state BeginWith e', (done: Function) => { pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Label', condition: 'BeginWith', value1: 'e' } ] jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('England'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('France'); done(); }, 1000); }); it('filter state DoesNotBeginWith e', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { drilledMembers: [{ name: 'Country', items: ['United Kingdom'] }] } }); pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Label', condition: 'DoesNotBeginWith', value1: 'e' } ] jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('United Kingdom'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[3] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[13] as HTMLElement).innerText).toBe('Garonne (Haute)'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[13] as HTMLElement).innerText).toBe(''); done(); }, 1000); }); it('filter clear', (done: Function) => { pivotGridObj.dataSourceSettings.filterSettings = []; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('99960'); done(); }, 1000); }); it('filter state quantity LessThan 500', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { drilledMembers: [{ name: 'Country', items: ['Canada'] }] } }); pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Value', condition: 'LessThan', value1: '500', measure: 'Quantity' } ] jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('19260'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alberta'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('5250'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Grand Total'); done(); }, 1000); }); it('filter state quantity GreaterThan 500', (done: Function) => { pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Value', condition: 'GreaterThan', value1: '500', measure: 'Quantity' } ] jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('80700'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('British Columbia'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('13500'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Ontario'); done(); }, 1000); }); it('filter state quantity LessThan 500', (done: Function) => { pivotGridObj.setProperties({ dataSourceSettings: { rows: [{ name: 'Country', showNoDataItems: true }, { name: 'State', showNoDataItems: true }], } }, true); pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Value', condition: 'LessThan', value1: '500', measure: 'Quantity' } ] jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('19260'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alberta'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('5250'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Grand Total'); done(); }, 1000); }); it('filter state quantity GreaterThan 500', (done: Function) => { pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Value', condition: 'GreaterThan', value1: '500', measure: 'Quantity' } ] jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('80700'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('British Columbia'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('13500'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[3] as HTMLElement).innerText).toBe('Ontario'); done(); }, 1000); }); }); describe(' - virtual scroll ', () => { let pivotGridObj: PivotView; let elem: HTMLElement = createElement('div', { id: 'PivotGrid' }); document.body.appendChild(elem); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll(() => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); PivotView.Inject(VirtualScroll); pivotGridObj = new PivotView({ dataSourceSettings: { expandAll: true, dataSource: pivot_nodata as IDataSet[], rows: [{ name: 'Country', showNoDataItems: true }, { name: 'State', showNoDataItems: true }], columns: [{ name: 'Product', showNoDataItems: true }, { name: 'Date', showNoDataItems: true }], values: [{ name: 'Amount' }, { name: 'Quantity' }], filters: [], }, enableVirtualization: true, width: 800, height: 300 }); pivotGridObj.appendTo('#PivotGrid'); }); let scrollEvent: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true }); let upEvent: MouseEvent = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); let dataSourceSettings: IDataOptions it('pivotgrid render testing', (done: Function) => { dataSourceSettings = extend({}, pivotGridObj.dataSourceSettings, null, true); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('28550'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alabama'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe(''); done(); }, 2000); }); it('state false', (done: Function) => { pivotGridObj.dataSourceSettings.rows = [{ name: 'Country', showNoDataItems: true }, { name: 'State', showNoDataItems: false }]; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('28550'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alberta'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('2100'); done(); }, 2000); }); it('include england', (done: Function) => { pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Include', items: ['England'] } ], jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('England'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('United Kingdom'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('1040'); done(); }, 2000); }); it('exclude england', (done: Function) => { pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'State', type: 'Exclude', items: ['England'] } ], jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('28550'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alberta'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('2100'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('Quebec'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('6400'); done(); }, 2000); }); it('state true', (done: Function) => { pivotGridObj.dataSourceSettings.rows = [{ name: 'Country', showNoDataItems: true }, { name: 'State', showNoDataItems: true }]; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('28550'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alabama'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('Brunswick'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('6300'); done(); }, 2000); }); it('scroll bottom', (done: Function) => { document.querySelector('.e-movablecontent').scrollTop = 100; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('28550'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alabama'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('Brunswick'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('6300'); done(); }, 2000); }); it('scroll top', (done: Function) => { document.querySelector('.e-movablecontent').scrollTop = 0; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('Canada'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[0] as HTMLElement).innerText).toBe('28550'); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[1] as HTMLElement).innerText).toBe('Alabama'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[1] as HTMLElement).innerText).toBe(''); expect((document.querySelectorAll('td[aria-colindex="0"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('Brunswick'); expect((document.querySelectorAll('td[aria-colindex="1"] .e-cellvalue')[6] as HTMLElement).innerText).toBe('6300'); pivotGridObj.scrollerBrowserLimit = 1000; done(); }, 2000); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange); //Check average change in memory samples to not be over 10MB //expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()); //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
export default class JquerySmartTab { // volmarg - fix adding logic to initial call private initialCall: boolean = true; private defaults = { selected: 0, // Initial selected tab, 0 = first tab theme: 'default', // theme for the tab, related css need to include for other than default theme orientation: 'horizontal', // Nav menu orientation. horizontal/vertical justified: true, // Nav menu justification. true/false autoAdjustHeight: true, // Automatically adjust content height backButtonSupport: true, // Enable the back button support enableURLhash: true, // Enable selection of the tab based on url hash transition: { animation: 'none', // Effect on navigation, none/fade/slide-horizontal/slide-vertical/slide-swing speed: '400', // Transion animation speed easing: '' // Transition animation easing. Not supported without a jQuery easing plugin }, autoProgress: { // Auto navigate tabs on interval enabled: false, // Enable/Disable Auto navigation interval: 3500, // Auto navigate Interval (used only if "autoProgress" is enabled) stopOnFocus: true // Stop auto navigation on focus and resume on outfocus }, keyboardSettings: { keyNavigation: true, // Enable/Disable keyboard navigation(left and right keys are used if enabled) keyLeft: [37], // Left key code keyRight: [39] // Right key code } }; private options; private main; private nav; private tabs; private container; private pages; private current_index; private autoProgressId; _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { this._typeof = function _typeof(obj) { return typeof obj; }; } else { this._typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return this._typeof(obj); } _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } _createClass(Constructor, protoProps, staticProps) { if (protoProps) this._defineProperties(Constructor.prototype, protoProps); if (staticProps) this._defineProperties(Constructor, staticProps); return Constructor; } public initForElementAndOptions(element, options) { // this._classCallCheck(this, this.initForElementAndOptions); // Merge user settings with default this.options = $.extend(true, {}, this.defaults, options); // Main container element this.main = $(element); // Navigation bar element this.nav = this._getFirstDescendant('.nav'); // Tab anchor elements this.tabs = this.nav.find('.nav-link'); // Content container this.container = this._getFirstDescendant('.tab-content'); // Content pages this.pages = this.container.children('.tab-pane'); // Active Tab index this.current_index = null; // Autoprogress timer id this.autoProgressId = null; // Assign options this._initOptions(); // Initial load this._initLoad(); } // Initial Load Method private _initLoad() { // Clean the elements this.pages.hide(); this.tabs.removeClass('active'); // Get the initial tab index var idx = this._getTabIndex(); // Show the initial tab this._showTab(idx); } // Initialize options private _initOptions() { // Set the elements this._setElements(); // Assign plugin events this._setEvents(); } private _getFirstDescendant(selector) { // Check for first level element var elm = this.main.children(selector); if (elm.length > 0) { return elm; } // Check for second level element this.main.children().each(function (i, n) { var tmp = $(n).children(selector); if (tmp.length > 0) { elm = tmp; return false; } }); if (elm.length > 0) { return elm; } // Element not found this._showError("Element not found " + selector); return false; } private _setElements() { // Set the main element this.main.addClass('st'); if (this.options.justified === true) { this.main.addClass('st-justified'); } else { this.main.removeClass('st-justified'); } this._setTheme(this.options.theme); this._setOrientation(this.options.orientation); } private _setEvents() { var _this = this; // Check if event handler already exists if (this.main.data('click-init')) { return true; } // Flag item to prevent attaching handler again this.main.data('click-init', true); // Anchor click event $(this.tabs).on("click", function (e) { e.preventDefault(); _this._showTab(_this.tabs.index(e.currentTarget)); }); // Keyboard navigation event if (this.options.keyboardSettings.keyNavigation) { $(document).keyup(function (e) { _this._keyNav(e); }); } // Back/forward browser button event if (this.options.backButtonSupport) { $(window).on('hashchange', function (e) { var idx = _this._getURLHashIndex(); if (idx !== false) { e.preventDefault(); _this._showTab(idx); } }); } if (this.options.autoProgress.enabled && this.options.autoProgress.stopOnFocus) { $(this.main).on("mouseover", function (e) { e.preventDefault(); _this._stopAutoProgress(); }); $(this.main).on("mouseleave", function (e) { e.preventDefault(); _this._startAutoProgress(); }); } } private _showNext() { var si = 0; // Find the next showable step for (var i = this.current_index + 1; i < this.tabs.length; i++) { if (this._isShowable(i)) { si = i; break; } } this._showTab(si); } private _showPrevious() { var si = this.tabs.length - 1; // Find the previous showable step for (var i = this.current_index - 1; i >= 0; i--) { if (this._isShowable(i)) { si = i; break; } } this._showTab(si); } private _isShowable(idx) { if (this.tabs.eq(idx).hasClass('disabled') || this.tabs.eq(idx).hasClass('hidden')) { return false; } return true; } private _showTab(idx) { // If current tab is requested again, skip if (idx == this.current_index) { return false; } // If tab not found, skip if (!this.tabs.eq(idx)) { return false; } // If it is a disabled tab, skip if (!this._isShowable(idx)) { return false; } // Load tab content this._loadTab(idx); } private _loadTab(idx) { var _this2 = this; // Get current tab element var curTab = this._getAnchor(this.current_index); if (this.current_index !== null) { // Trigger "leaveTab" event if (this._triggerEvent("leaveTab", [curTab, this.current_index]) === false) { return false; } } // Get next tab element var selTab = this._getAnchor(idx); // Get the content if used var getTabContent = this._triggerEvent("tabContent", [selTab, idx]); if (getTabContent) { if (_this2._typeof(getTabContent) == "object") { getTabContent.then(function (res) { _this2._setTabContent(idx, res); _this2._transitTab(idx); })["catch"](function (err) { console.error(err); _this2._setTabContent(idx, err); _this2._transitTab(idx); }); } else if (typeof getTabContent == "string") { this._setTabContent(idx, getTabContent); this._transitTab(idx); } else { this._transitTab(idx); } } else { this._transitTab(idx); } } private _getAnchor(idx) { if (idx == null) { return null; } return this.tabs.eq(idx); } private _getPage(idx) { if (idx == null) { return null; } var anchor = this._getAnchor(idx); return anchor.length > 0 ? this.main.find(anchor.attr("href")) : null; } private _setTabContent(idx, html) { var page = this._getPage(idx); if (page) { page.html(html); } } private _transitTab(idx) { var _this3 = this; // Get tab to show element var selTab = this._getAnchor(idx); // Change the url hash to new tab this._setURLHash(selTab.attr("href")); // Update controls this._setAnchor(idx); // Animate the tab this._doTabAnimation(idx, function () { // Fix height with content _this3._fixHeight(idx); // Trigger "showTab" event _this3._triggerEvent("showTab", [selTab, _this3.current_index]); // Restart auto progress if enabled _this3._restartAutoProgress(); }); // Update the current index this.current_index = idx; } private _doTabAnimation(idx, callback) { var _this4 = this; // Get current tab element var curPage = this._getPage(this.current_index); // Get next tab element var selPage = this._getPage(idx); // Get the transition effect var transitionEffect = this.options.transition.animation.toLowerCase(); // Complete any ongoing animations this._stopAnimations(); switch (transitionEffect) { case 'slide-horizontal': case 'slide-h': // horizontal slide var containerWidth = this.container.width(); var curLastLeft = containerWidth; var nextFirstLeft = containerWidth * -2; // Forward direction if (idx > this.current_index) { curLastLeft = containerWidth * -1; nextFirstLeft = containerWidth; } // First load set the container width if (this.current_index == null) { this.container.height(selPage.outerHeight()); } var css_pos, css_left; if (curPage) { css_pos = curPage.css("position"); css_left = curPage.css("left"); curPage.css("position", 'absolute').css("left", 0).animate({ left: curLastLeft }, this.options.transition.speed, this.options.transition.easing, function () { $(this).hide(); curPage.css("position", css_pos).css("left", css_left); }); } css_pos = selPage.css("position"); css_left = selPage.css("left"); selPage.css("position", 'absolute').css("left", nextFirstLeft).outerWidth(containerWidth).show().animate({ left: 0 }, this.options.transition.speed, this.options.transition.easing, function () { selPage.css("position", css_pos).css("left", css_left); callback(); }); break; case 'slide-vertical': case 'slide-v': // vertical slide var containerHeight = this.container.height(); var curLastTop = containerHeight; var nextFirstTop = containerHeight * -2; // Forward direction if (idx > this.current_index) { curLastTop = containerHeight * -1; nextFirstTop = containerHeight; } var css_vpos, css_vtop; if (curPage) { css_vpos = curPage.css("position"); css_vtop = curPage.css("top"); curPage.css("position", 'absolute').css("top", 0).animate({ top: curLastTop }, this.options.transition.speed, this.options.transition.easing, function () { $(this).hide(); curPage.css("position", css_vpos).css("top", css_vtop); }); } css_vpos = selPage.css("position"); css_vtop = selPage.css("top"); selPage.css("position", 'absolute').css("top", nextFirstTop).show().animate({ top: 0 }, this.options.transition.speed, this.options.transition.easing, function () { selPage.css("position", css_vpos).css("top", css_vtop); callback(); }); break; case 'slide-swing': case 'slide-s': // normal slide if (curPage) { curPage.slideUp('fast', this.options.transition.easing, function () { selPage.slideDown(_this4.options.transition.speed, _this4.options.transition.easing, function () { callback(); }); }); } else { selPage.slideDown(this.options.transition.speed, this.options.transition.easing, function () { callback(); }); } break; case 'fade': // normal fade if (curPage) { curPage.fadeOut('fast', this.options.transition.easing, function () { selPage.fadeIn('fast', _this4.options.transition.easing, function () { callback(); }); }); } else { selPage.fadeIn(this.options.transition.speed, this.options.transition.easing, function () { callback(); }); } break; default: if (curPage) { curPage.hide(); } selPage.show(); callback(); break; } } private _stopAnimations() { this.pages.finish(); this.container.finish(); }; private _setAnchor(idx) { this.tabs.eq(this.current_index).removeClass("active"); this.tabs.eq(idx).addClass("active"); } private _getTabIndex() { // Get selected tab from the url var idx = this._getURLHashIndex(); return idx === false ? this.options.selected : idx; } /** * @description here is the logic for handling animated height for wrapper - works good for modals, * but the issue is that when modal is being hidden the panel height is initially 0 */ public _fixHeight(idx) { // volmarg - fix first tab not being active, add animation later on here // Auto adjust height of the container // if (this.options.autoAdjustHeight) { // var selPage = this._getPage(idx); // console.log(selPage.outerHeight()); // // this.container.finish().animate({ // height: selPage.outerHeight() // }, this.options.transition.speed); // } } private _setTheme(theme) { this.main.removeClass(function (index, className) { return (className.match(/(^|\s)st-theme-\S+/g) || []).join(' '); }).addClass('st-theme-' + theme); } private _setOrientation(orientation) { this.main.removeClass('st-vertical st-horizontal').addClass('st-' + orientation); } // HELPER FUNCTIONS private _keyNav(e) { // Keyboard navigation if ($.inArray(e.which, this.options.keyboardSettings.keyLeft) > -1) { // left this._showPrevious(); e.preventDefault(); } else if ($.inArray(e.which, this.options.keyboardSettings.keyRight) > -1) { // right this._showNext(); e.preventDefault(); } else { return; // exit this handler for other keys } } // Auto progress private _startAutoProgress() { var _this5 = this; if (this.options.autoProgress.enabled && !this.autoProgressId) { this.autoProgressId = setInterval(function () { return _this5._showNext(); }, this.options.autoProgress.interval); } } private _stopAutoProgress() { if (this.autoProgressId) { clearInterval(this.autoProgressId); this.autoProgressId = null; } } private _restartAutoProgress() { this._stopAutoProgress(); this._startAutoProgress(); } private _triggerEvent(name, params) { // Trigger an event var e = $.Event(name); this.main.trigger(e, params); if (e.isDefaultPrevented()) { return false; } //@ts-ignore return e.result; } private _setURLHash(hash) { if (this.options.enableURLhash && window.location.hash !== hash) { history.pushState(null, null, hash); } } private _getURLHashIndex() { if (this.options.enableURLhash) { // Get tab number from url hash if available var hash = window.location.hash; if (hash.length > 0) { var elm = this.nav.find("a[href*='" + hash + "']"); if (elm.length > 0) { return this.tabs.index(elm); } } } return false; } private _loader(action) { switch (action) { case 'show': this.main.addClass('st-loading'); break; case 'hide': this.main.removeClass('st-loading'); break; default: this.main.toggleClass('st-loading'); } } private _showError(msg) { console.error(msg); } // PUBLIC FUNCTIONS private goToTab(tabIndex) { this._showTab(tabIndex); } public setOptions(options) { this.options = $.extend(true, {}, this.options, options); this._initOptions(); } public loader(state) { if (state === "show") { this.main.addClass('st-loading'); } else { this.main.removeClass('st-loading'); } } }
the_stack
import { expectAssignable, expectError, expectNotAssignable, expectType } from 'tsd'; import '../../../index'; // benchmark declare function functionWithoutParameters(): void; declare function functionWithParameters(a: number, b: string, c?: boolean): void; declare function functionWithReturnTypeOtherThanVoid(): number; expectType<Promise<void>>(foundry.utils.benchmark(functionWithoutParameters, 42)); expectError(foundry.utils.benchmark(functionWithoutParameters, 42, 'unknown argument')); expectType<Promise<void>>(foundry.utils.benchmark(functionWithParameters, 42, 1, '', false)); expectType<Promise<void>>(foundry.utils.benchmark(functionWithParameters, 42, 1, '')); expectError(foundry.utils.benchmark(functionWithParameters, 42, 1)); expectError(foundry.utils.benchmark(functionWithParameters, 42, 1, '', 'unknown argument')); expectType<Promise<void>>(foundry.utils.benchmark(functionWithReturnTypeOtherThanVoid, 42)); // deepClone const complexObject = { a: '', b: 0, toJSON: () => [ false, undefined, { c: undefined, d: ((): boolean | symbol => false)(), e: [true], f: { g: 0, h: ((): number | undefined => 0)() } } ] }; expectType<string>(foundry.utils.deepClone('abc' as string)); expectType<'abc'>(foundry.utils.deepClone('abc')); expectType<number>(foundry.utils.deepClone(1 as number)); expectType<1>(foundry.utils.deepClone(1)); expectType<bigint>(foundry.utils.deepClone(1n as bigint)); expectType<1n>(foundry.utils.deepClone(1n)); expectType<true>(foundry.utils.deepClone(true)); expectType<boolean>(foundry.utils.deepClone(true as boolean)); expectType<symbol>(foundry.utils.deepClone(Symbol('customSymbol'))); expectType<undefined>(foundry.utils.deepClone(undefined)); expectType<null>(foundry.utils.deepClone(null)); expectType<Array<string>>(foundry.utils.deepClone(['a', 'b'])); expectType<Array<string>>(foundry.utils.deepClone(['a', 'b'])); expectType<{ a: string; b: number }>(foundry.utils.deepClone({ a: 'foo', b: 42 })); expectType<Date>(foundry.utils.deepClone(new Date())); expectType<typeof complexObject>(foundry.utils.deepClone(complexObject)); expectType<string>(foundry.utils.deepClone('abc' as string, { strict: false })); expectType<string>(foundry.utils.deepClone('abc' as string, { strict: true })); expectType<string>(foundry.utils.deepClone('abc' as string, { strict: true as boolean })); // duplicate expectType<string>(foundry.utils.duplicate('')); expectType<number>(foundry.utils.duplicate(0)); expectType<0 | 1>(foundry.utils.duplicate<0 | 1>(0)); expectType<'foo' | 'bar'>(foundry.utils.duplicate<'foo' | 'bar'>('foo')); expectType<number>(foundry.utils.duplicate<number>(0)); /* `NaN` will actually be converted to `null` but for ease of use, this is ignored. */ expectType<number>(foundry.utils.duplicate<number>(NaN)); expectType<boolean>(foundry.utils.duplicate(((): boolean => false)())); expectType<null>(foundry.utils.duplicate(null)); expectType<never>(foundry.utils.duplicate(undefined)); expectType<never>(foundry.utils.duplicate(() => 0)); expectType<never>(foundry.utils.duplicate(Symbol(''))); expectType<false>(foundry.utils.duplicate(false)); expectType<string | boolean>(foundry.utils.duplicate(((): string | boolean => '')())); expectType<string | number>(foundry.utils.duplicate(((): string | number => '')())); expectType<string | null>(foundry.utils.duplicate(((): string | null => '')())); expectType<string>(foundry.utils.duplicate(((): string | undefined => '')())); expectType<string>(foundry.utils.duplicate(((): string | Function => '')())); expectType<string>(foundry.utils.duplicate(((): string | symbol => '')())); expectType<Array<string>>(foundry.utils.duplicate([''])); expectType<Array<number>>(foundry.utils.duplicate([0])); expectType<Array<boolean>>(foundry.utils.duplicate([false, true])); expectType<Array<null>>(foundry.utils.duplicate([null])); expectType<Array<null>>(foundry.utils.duplicate([undefined])); expectType<Array<null>>(foundry.utils.duplicate([() => 0])); expectType<Array<null>>(foundry.utils.duplicate([Symbol('')])); expectType<Array<false>>(foundry.utils.duplicate([false])); expectType<Array<string | boolean>>(foundry.utils.duplicate(['', false, true])); expectType<Array<string | number>>(foundry.utils.duplicate(['', 0])); expectType<Array<string | null>>(foundry.utils.duplicate(['', null])); expectType<Array<string | null>>(foundry.utils.duplicate(['', undefined])); expectType<Array<string | null>>(foundry.utils.duplicate(['', () => 0])); expectType<Array<string | null>>(foundry.utils.duplicate(['', Symbol('')])); expectType<Array<'a' | 'b'>>(foundry.utils.duplicate([((): 'a' | 'b' => 'a')()])); expectType<Array<Array<boolean>>>(foundry.utils.duplicate([[false, true]])); expectType<Array<{ a: string }>>(foundry.utils.duplicate([{ a: '' }])); expectType<{ a: string }>(foundry.utils.duplicate({ a: '' })); expectType<{ a: number }>(foundry.utils.duplicate({ a: 0 })); expectType<{ a: boolean }>(foundry.utils.duplicate({ a: ((): boolean => false)() })); expectType<{ a: null }>(foundry.utils.duplicate({ a: null })); expectType<{}>(foundry.utils.duplicate({ a: undefined })); expectType<{}>(foundry.utils.duplicate({ a: () => 0 })); expectType<{}>(foundry.utils.duplicate({ a: Symbol('') })); expectType<{ a: string | boolean }>(foundry.utils.duplicate({ a: ((): string | boolean => '')() })); expectType<{ a: string | number }>(foundry.utils.duplicate({ a: ((): string | number => '')() })); expectType<{ a: string | null }>(foundry.utils.duplicate({ a: ((): string | null => '')() })); expectType<{ a?: string | undefined }>(foundry.utils.duplicate({ a: ((): string | undefined => '')() })); expectType<{ a?: string | undefined }>(foundry.utils.duplicate({ a: ((): string | Function => '')() })); expectType<{ a?: string | undefined }>(foundry.utils.duplicate({ a: ((): string | symbol => '')() })); expectType<{ a: Array<string> }>(foundry.utils.duplicate({ a: [''] })); expectType<{ a: { b: string } }>(foundry.utils.duplicate({ a: { b: '' } })); expectType<{ a: false }>(foundry.utils.duplicate({ a: false })); expectType<{ a: 'a' | 'b' }>(foundry.utils.duplicate({ a: ((): 'a' | 'b' => 'a')() })); expectType<string>(foundry.utils.duplicate({ a: 0, b: '', c: false, toJSON: (): string => '' })); expectType<{ foo: string; bar: boolean }>( foundry.utils.duplicate({ a: 0, b: '', c: false, toJSON: () => ({ foo: '', bar: ((): boolean => false)() }) }) ); expectType<{ foo: string; bar: boolean }>( foundry.utils.duplicate({ a: 0, b: '', c: false, toJSON: () => ({ foo: '', bar: ((): boolean => false)(), toJSON: () => '' }) }) ); expectType<{ foo: string; bar: false }>( foundry.utils.duplicate({ a: 0, b: '', c: false, toJSON: () => ({ foo: '', bar: { baz: '', toJSON: () => false } }) }) ); expectType< Array< | boolean | null | { d?: boolean | undefined; e: Array<boolean>; f: { g: number; h?: number | undefined }; } > >(foundry.utils.duplicate(complexObject)); // isSubclass declare class ClassWithNoConstructorParameters {} declare class ClassWithConstructorParameters { constructor(a: number, b: string); } expectType<boolean>(foundry.utils.isSubclass(ClassWithNoConstructorParameters, ClassWithConstructorParameters)); expectType<boolean>(foundry.utils.isSubclass(ClassWithConstructorParameters, ClassWithNoConstructorParameters)); // invertObject expectType<{ readonly 1: 'a'; readonly foo: 'b' }>(foundry.utils.invertObject({ a: 1, b: 'foo' } as const)); // mergeObject: expectAssignable is used here because of https://github.com/SamVerschueren/tsd/issues/67 // mergeObject (1): tests from the docs expectAssignable<{ k1: string }>(foundry.utils.mergeObject({ k1: 'v1' }, { k2: 'v2' }, { insertKeys: false })); expectAssignable<{ k1: string; k2: string }>( foundry.utils.mergeObject({ k1: 'v1' }, { k2: 'v2' }, { insertKeys: true }) ); expectAssignable<{ k1: { i1: string } }>( foundry.utils.mergeObject({ k1: { i1: 'v1' } }, { k1: { i2: 'v2' } }, { insertValues: false }) ); expectAssignable<{ k1: { i1: string; i2: string } }>( foundry.utils.mergeObject({ k1: { i1: 'v1' } }, { k1: { i2: 'v2' } }, { insertValues: true }) ); expectAssignable<{ k1: string }>(foundry.utils.mergeObject({ k1: 'v1' }, { k1: 'v2' }, { overwrite: true })); expectAssignable<{ k1: string }>(foundry.utils.mergeObject({ k1: 'v1' }, { k1: 'v2' }, { overwrite: false })); expectAssignable<{ k1: { i2: string } }>( foundry.utils.mergeObject({ k1: { i1: 'v1' } }, { k1: { i2: 'v2' } }, { recursive: false }) ); expectAssignable<{ k1: { i1: string; i2: string } }>( foundry.utils.mergeObject({ k1: { i1: 'v1' } }, { k1: { i2: 'v2' } }, { recursive: true }) ); expectAssignable<{ k2: string }>(foundry.utils.mergeObject({ k1: 'v1', k2: 'v2' }, { '-=k1': null })); // mergeObject (2): more simple tests expectAssignable<{ k1: string }>(foundry.utils.mergeObject({ k1: '' }, { k1: '' })); expectAssignable<{ k1: string }>(foundry.utils.mergeObject({ k1: '' }, { k1: '' }, {})); expectAssignable<{ k1: string }>(foundry.utils.mergeObject({ k1: '' }, { k1: '' }, { insertKeys: false })); expectAssignable<{ k1: string }>(foundry.utils.mergeObject({ k1: '' }, { k1: '' }, { insertKeys: true })); expectAssignable<{ k1: string; k2: string }>(foundry.utils.mergeObject({ k1: '' }, { k2: '' })); expectAssignable<{ k1: string; k2: string }>(foundry.utils.mergeObject({ k1: '' }, { k2: '' }, {})); expectAssignable<{ k1: string }>(foundry.utils.mergeObject({ k1: '' }, { k2: '' }, { insertKeys: false })); expectAssignable<{ k1: string; k2: string }>(foundry.utils.mergeObject({ k1: '' }, { k2: '' }, { insertKeys: true })); expectAssignable<{ k1: number; k2: string }>(foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' })); expectAssignable<{ k1: number; k2: string }>(foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, {})); expectAssignable<{ k1: number }>(foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { insertKeys: false })); expectAssignable<{ k1: number; k2: string }>( foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { insertKeys: true }) ); expectAssignable<never>(foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { enforceTypes: true })); expectAssignable<{ k1: number; k2: string }>( foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { enforceTypes: false }) ); expectAssignable<never>( foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { enforceTypes: true, insertKeys: false }) ); expectAssignable<never>( foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { enforceTypes: true, insertKeys: true }) ); expectAssignable<{ k1: string; k2: string }>( foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { overwrite: false }) ); expectAssignable<{ k1: number; k2: string }>( foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { overwrite: true }) ); expectAssignable<{ k1: number; k2: string }>(foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, {})); expectAssignable<{ k1: string }>( foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { overwrite: false, insertKeys: false }) ); expectAssignable<{ k1: string; k2: string }>( foundry.utils.mergeObject({ k1: '' }, { k1: 2, k2: '' }, { overwrite: false, insertKeys: true }) ); // mergeObject (3): more complex examples expectAssignable<{ k1: { i1: string; i2: string }; k2: number; k3: number }>( foundry.utils.mergeObject({ k1: { i1: 'foo' }, k2: 2 }, { k1: { i2: 'bar' }, k3: 3 }) ); expectAssignable<{ k1: { i1: string; i2: string; i3: number }; k2: number; k3: number }>( foundry.utils.mergeObject({ k1: { i1: 'foo', i3: { j1: 0 } }, k2: 2 }, { k1: { i2: 'bar', i3: 2 }, k3: 3 }) ); expectAssignable<{ k1: { i2: string; i3: number }; k2: number; k3: number }>( foundry.utils.mergeObject( { k1: { i1: 'foo', i3: { j1: 0 } }, k2: 2 }, { k1: { i2: 'bar', i3: 2 }, k3: 3 }, { recursive: false } ) ); expectType<{ i2: string; i3: number }>( foundry.utils.mergeObject( { k1: { i1: 'foo', i3: { j1: 0 } }, k2: 2 }, { k1: { i2: 'bar', i3: 2 }, k3: 3 }, { recursive: false } ).k1 ); expectAssignable<{ k1: { i1: string; i2: string; i3: { j1: string; j2: number; j3: string } }; k2: number; k3: number; }>( foundry.utils.mergeObject( { k1: { i1: 'foo', i3: { j1: 1, j2: 2 } }, k2: 2 }, { k1: { i2: 'bar', i3: { j1: '1', j3: '3' } }, k3: 3 } ) ); expectAssignable<{ k1: { i1: string; i3: { j1: string; j2: number } }; k2: number; k3: number }>( foundry.utils.mergeObject( { k1: { i1: 'foo', i3: { j1: 1, j2: 2 } }, k2: 2 }, { k1: { i2: 'bar', i3: { j1: '1', j3: '3' } }, k3: 3 }, { insertValues: false } ) ); expectAssignable<{ k1: { i2: string; i3: { j1: string; j3: string } }; k2: number; k3: number }>( foundry.utils.mergeObject( { k1: { i1: 'foo', i3: { j1: 1, j2: 2 } }, k2: 2 }, { k1: { i2: 'bar', i3: { j1: '1', j3: '3' } }, k3: 3 }, { recursive: false } ) ); // Array merging expectAssignable<FormApplication.Options>( foundry.utils.mergeObject(FormApplication.defaultOptions, { classes: ['my', 'custom', 'css'] }) ); expectAssignable<{ a: number[] }>(foundry.utils.mergeObject({ a: ['foo'] }, { a: [0] })); expectAssignable<{ a: number[] }>(foundry.utils.mergeObject({ a: ['foo'] }, { a: [0] }, { insertKeys: true })); expectAssignable<{ a: number[] }>(foundry.utils.mergeObject({ a: ['foo'] }, { a: [0] }, { insertValues: true })); expectAssignable<{ a: number[] }>(foundry.utils.mergeObject({ a: ['foo'] }, { a: [0] }, { insertKeys: false })); expectAssignable<{ a: number[] }>(foundry.utils.mergeObject({ a: ['foo'] }, { a: [0] }, { insertValues: false })); expectAssignable<{ a: number[] }>(foundry.utils.mergeObject({ a: ['foo'] }, { a: [0] }, { enforceTypes: true })); expectAssignable<never>(foundry.utils.mergeObject({ a: ['foo'] }, { a: { b: 'foo' } }, { enforceTypes: true })); expectAssignable<{ a: { b: string } }>( foundry.utils.mergeObject({ a: ['foo'] }, { a: { b: 'foo' } }, { enforceTypes: false }) ); expectAssignable<never>(foundry.utils.mergeObject({ a: { b: 'foo' } }, { a: ['foo'] }, { enforceTypes: true })); expectAssignable<{ a: string[] }>( foundry.utils.mergeObject({ a: { b: 'foo' } }, { a: ['foo'] }, { enforceTypes: false }) ); // bonus round expectAssignable<{ a: number; b: number }>(foundry.utils.mergeObject({ a: 1 }, { b: 2 }, { enforceTypes: true })); expectNotAssignable<never>(foundry.utils.mergeObject({ a: 1 }, { b: 2 }, { enforceTypes: true })); expectAssignable<{ a: { a: number; b: number } }>( foundry.utils.mergeObject({ a: { a: 1 } }, { a: { b: 2 } }, { enforceTypes: true }) ); expectNotAssignable<never>(foundry.utils.mergeObject({ a: { a: 1 } }, { b: { a: 2 } }, { enforceTypes: true })); expectAssignable<{ a: { a: number }; b: { a: number }; c: number }>( foundry.utils.mergeObject({ a: { a: 1 }, c: 1 }, { b: { a: 2 }, c: 1 }, { enforceTypes: true }) ); expectNotAssignable<never>( foundry.utils.mergeObject({ a: { a: 1 }, c: 1 }, { b: { a: 2 }, c: 1 }, { enforceTypes: true }) ); expectError(foundry.utils.mergeObject(1, 2)); expectError(foundry.utils.mergeObject('foo', 'bar'));
the_stack
import window from 'global/window'; import document from 'global/document'; import console from 'global/console'; import svgToMiniDataURI from 'mini-svg-data-uri'; import {IMAGE_EXPORT_ERRORS} from 'constants/user-feedbacks'; import { canvasToBlob, escape, escapeXhtml, delay, processClone, asArray, makeImage, mimeType, dataAsUrl, isDataUrl, isSrcAsDataUrl, resolveUrl, getWidth, getHeight, getAndEncode } from './dom-utils'; const inliner = newInliner(); const fontFaces = newFontFaces(); const images = newImages(); // Default impl options const defaultOptions = { // Default is to fail on error, no placeholder imagePlaceholder: undefined, // Default cache bust is false, it will use the cache cacheBust: false }; const domtoimage = { toSvg, toPng, toJpeg, toBlob, toPixelData, impl: { fontFaces, images, inliner, options: {} as any } }; /** * @param {Node} node - The DOM Node object to render * @param {Object} options - Rendering options * @param {Function} [options.filter] - Should return true if passed node should be included in the output * (excluding node means excluding it's children as well). Not called on the root node. * @param {String} [options.bgcolor] - color for the background, any valid CSS color value. * @param {Number} [options.width] - width to be applied to node before rendering. * @param {Number} [options.height] - height to be applied to node before rendering. * @param {Object} [options.style] - an object whose properties to be copied to node's style before rendering. * @param {Number} [options.quality] - a Number between 0 and 1 indicating image quality (applicable to JPEG only), defaults to 1.0. * @param {String} [options.imagePlaceholder] - dataURL to use as a placeholder for failed images, default behaviour is to fail fast on images we can't fetch * @param {Boolean} [options.cacheBust] - set to true to cache bust by appending the time to the request url * @return {Promise} - A promise that is fulfilled with a SVG image data URL * */ function toSvg(node, options) { options = options || {}; copyOptions(options); return Promise.resolve(node) .then(nd => cloneNode(nd, options.filter, true)) .then(embedFonts) .then(inlineImages) .then(applyOptions) .then(clone => makeSvgDataUri(clone, options.width || getWidth(node), options.height || getHeight(node)) ); function applyOptions(clone) { if (options.bgcolor) clone.style.backgroundColor = options.bgcolor; if (options.width) clone.style.width = `${options.width}px`; if (options.height) clone.style.height = `${options.height}px`; if (options.style) Object.keys(options.style).forEach(property => { clone.style[property] = options.style[property]; }); return clone; } } /** * @param {Node} node - The DOM Node object to render * @param {Object} options - Rendering options * @return {Promise} - A promise that is fulfilled with a Uint8Array containing RGBA pixel data. * */ function toPixelData(node, options) { return draw(node, options || {}).then( canvas => canvas.getContext('2d').getImageData(0, 0, getWidth(node), getHeight(node)).data ); } /** * @param {Node} node - The DOM Node object to render * @param {Object} options - Rendering options * @return {Promise} - A promise that is fulfilled with a PNG image data URL * */ function toPng(node, options) { return draw(node, options || {}).then(canvas => canvas.toDataURL()); } /** * @param {Node} node - The DOM Node object to render * @param {Object} options - Rendering options * @return {Promise} - A promise that is fulfilled with a JPEG image data URL * */ function toJpeg(node, options) { options = options || {}; return draw(node, options).then(canvas => canvas.toDataURL('image/jpeg', options.quality || 1.0)); } /** * @param {Node} node - The DOM Node object to render * @param {Object} options - Rendering options * @return {Promise} - A promise that is fulfilled with a PNG image blob * */ function toBlob(node, options) { return draw(node, options || {}).then(canvasToBlob); } function copyOptions(options) { // Copy options to impl options for use in impl if (typeof options.imagePlaceholder === 'undefined') { domtoimage.impl.options.imagePlaceholder = defaultOptions.imagePlaceholder; } else { domtoimage.impl.options.imagePlaceholder = options.imagePlaceholder; } if (typeof options.cacheBust === 'undefined') { domtoimage.impl.options.cacheBust = defaultOptions.cacheBust; } else { domtoimage.impl.options.cacheBust = options.cacheBust; } } function draw(domNode, options) { return toSvg(domNode, options) .then(makeImage) .then(delay(100)) .then(image => { const canvas = newCanvas(domNode); canvas.getContext('2d').drawImage(image, 0, 0); return canvas; }); function newCanvas(dNode) { const canvas = document.createElement('canvas'); canvas.width = options.width || getWidth(dNode); canvas.height = options.height || getHeight(dNode); if (options.bgcolor) { const ctx = canvas.getContext('2d'); ctx.fillStyle = options.bgcolor; ctx.fillRect(0, 0, canvas.width, canvas.height); } return canvas; } } function cloneNode(node, filter, root) { if (!root && filter && !filter(node)) { return Promise.resolve(); } return Promise.resolve(node) .then(makeNodeCopy) .then(clone => cloneChildren(node, clone, filter)) .then(clone => processClone(node, clone)); function makeNodeCopy(nd) { if (nd instanceof window.HTMLCanvasElement) { return makeImage(nd.toDataURL()); } return nd.cloneNode(false); } function cloneChildrenInOrder(parent, arrChildren, flt) { let done = Promise.resolve(); arrChildren.forEach(child => { done = done .then(() => cloneNode(child, flt, null)) .then(childClone => { if (childClone) { parent.appendChild(childClone); } }); }); return done; } function cloneChildren(original, clone, flt) { const children = original.childNodes; if (children.length === 0) { return Promise.resolve(clone); } return cloneChildrenInOrder(clone, asArray(children), flt).then(() => clone); } } function embedFonts(node) { return fontFaces.resolveAll().then(cssText => { const styleNode = document.createElement('style'); node.appendChild(styleNode); styleNode.appendChild(document.createTextNode(cssText)); return node; }); } function inlineImages(node) { return images.inlineAll(node).then(() => node); } function makeSvgDataUri(node, width, height) { return Promise.resolve(node).then(nd => { nd.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); const serializedString = new window.XMLSerializer().serializeToString(nd); const xhtml = escapeXhtml(serializedString); const foreignObject = `<foreignObject x="0" y="0" width="100%" height="100%">${xhtml}</foreignObject>`; const svgStr = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">${foreignObject}</svg>`; // Optimizing SVGs in data URIs // see https://codepen.io/tigt/post/optimizing-svgs-in-data-uris // the best way of encoding SVG in a data: URI is data:image/svg+xml,[actual data]. // We don’t need the ;charset=utf-8 parameter because the given SVG is ASCII. return svgToMiniDataURI(svgStr); }); } function newInliner() { const URL_REGEX = /url\(['"]?([^'"]+?)['"]?\)/g; return { inlineAll, shouldProcess, impl: { readUrls, inline } }; function shouldProcess(string) { return string.search(URL_REGEX) !== -1; } function readUrls(string) { const result: string[] = []; let match: null | RegExpExecArray; while ((match = URL_REGEX.exec(string)) !== null) { result.push(match[1]); } return result.filter(url => { return !isDataUrl(url); }); } function urlAsRegex(url0) { return new RegExp(`(url\\([\'"]?)(${escape(url0)})([\'"]?\\))`, 'g'); } function inline(string, url, baseUrl, get) { return Promise.resolve(url) .then(ul => (baseUrl ? resolveUrl(ul, baseUrl) : ul)) .then(ul => (typeof get === 'function' ? get(ul) : getAndEncode(ul, domtoimage.impl.options))) .then(data => dataAsUrl(data, mimeType(url))) .then(dataUrl => string.replace(urlAsRegex(url), `$1${dataUrl}$3`)); } function inlineAll(string, baseUrl, get) { if (!shouldProcess(string) || isSrcAsDataUrl(string)) { return Promise.resolve(string); } return Promise.resolve(string) .then(readUrls) .then(urls => { let done = Promise.resolve(string); urls.forEach(url => { done = done.then(str => inline(str, url, baseUrl, get)); }); return done; }); } } function newFontFaces() { return { resolveAll, impl: {readAll} }; function resolveAll() { return readAll() .then(webFonts => { return Promise.all(webFonts.map(webFont => webFont.resolve())); }) .then(cssStrings => cssStrings.join('\n')); } function readAll() { return Promise.resolve(asArray(document.styleSheets)) .then(loadExternalStyleSheets) .then(getCssRules) .then(selectWebFontRules) .then(rules => rules.map(newWebFont)); function selectWebFontRules(cssRules) { return cssRules .filter(rule => rule.type === window.CSSRule.FONT_FACE_RULE) .filter(rule => inliner.shouldProcess(rule.style.getPropertyValue('src'))); } function loadExternalStyleSheets(styleSheets) { return Promise.all( styleSheets.map(sheet => { if (sheet.href) { // cloudfont doesn't have allow origin header properly set // error response will remain in cache const cache = sheet.href.includes('uber-fonts') ? 'no-cache' : 'default'; return window .fetch(sheet.href, {credentials: 'omit', cache}) .then(response => response.text()) .then(setBaseHref(sheet.href)) .then(toStyleSheet) .catch(err => { // Handle any error that occurred in any of the previous // promises in the chain. stylesheet failed to load should not stop // the process, hence result in only a warning, instead of reject console.warn(IMAGE_EXPORT_ERRORS.styleSheet, sheet.href); console.log(err); return; }); } return Promise.resolve(sheet); }) ); function setBaseHref(base) { base = base.split('/'); base.pop(); base = base.join('/'); function addBaseHrefToUrl(match, p1) { const url = /^http/i.test(p1) ? p1 : concatAndResolveUrl(base, p1); return `url('${url}')`; } // Source: http://stackoverflow.com/a/2676231/3786856 function concatAndResolveUrl(url, concat) { const url1: string[] = url.split('/'); const url2: string[] = concat.split('/'); const url3: string[] = []; for (let i = 0, l = url1.length; i < l; i++) { if (url1[i] === '..') { url3.pop(); } else if (url1[i] !== '.') { url3.push(url1[i]); } } for (let i = 0, l = url2.length; i < l; i++) { if (url2[i] === '..') { url3.pop(); } else if (url2[i] !== '.') { url3.push(url2[i]); } } return url3.join('/'); } return text => { return isSrcAsDataUrl(text) ? text : text.replace(/url\(['"]?([^'"]+?)['"]?\)/g, addBaseHrefToUrl); }; } function toStyleSheet(text) { const doc = document.implementation.createHTMLDocument(''); const styleElement = document.createElement('style'); styleElement.textContent = text; doc.body.appendChild(styleElement); return styleElement.sheet; } } function getCssRules(styleSheets) { const cssRules: any[] = []; styleSheets.forEach(sheet => { // try...catch because browser may not able to enumerate rules for cross-domain sheets if (!sheet) { return; } let rules; try { rules = sheet.rules || sheet.cssRules; } catch (e) { console.log(`'Can't read the css rules of: ${sheet.href}`, e); return; } if (rules && typeof rules === 'object') { try { asArray(rules || []).forEach(cssRules.push.bind(cssRules)); } catch (e) { console.log(`Error while reading CSS rules from ${sheet.href}`, e); return; } } else { console.log('getCssRules can not find cssRules'); return; } }); return cssRules; } function newWebFont(webFontRule) { return { resolve: () => { const baseUrl = (webFontRule.parentStyleSheet || {}).href; return inliner.inlineAll(webFontRule.cssText, baseUrl, null); }, src: () => webFontRule.style.getPropertyValue('src') }; } } } function newImages() { return { inlineAll, impl: { newImage } }; function newImage(element) { function inline(get) { if (isDataUrl(element.src)) { return Promise.resolve(); } return Promise.resolve(element.src) .then(ul => typeof get === 'function' ? get(ul) : getAndEncode(ul, domtoimage.impl.options) ) .then(data => dataAsUrl(data, mimeType(element.src))) .then( dataUrl => new Promise((resolve, reject) => { element.onload = resolve; element.onerror = reject; element.src = dataUrl; }) ); } return { inline }; } function inlineAll(node) { if (!(node instanceof Element)) { return Promise.resolve(node); } return inlineBackground(node).then(() => { if (node instanceof HTMLImageElement) { return newImage(node).inline(null); } return Promise.all(asArray(node.childNodes).map(child => inlineAll(child))); }); function inlineBackground(nd) { const background = nd.style.getPropertyValue('background'); if (!background) { return Promise.resolve(nd); } return inliner .inlineAll(background, null, null) .then(inlined => { nd.style.setProperty('background', inlined, nd.style.getPropertyPriority('background')); }) .then(() => nd); } } } export default domtoimage;
the_stack
import { FreeVars, Heap, Heaps, Locs, P, Reducer, Substituter, Syntax, Transformer, Traverser, Vars, and, copy, eqExpr, eqHeap, eqProp, implies, tru } from './logic'; import { getOptions } from './options'; import { propositionToSMT } from './smt'; declare const console: { log: (s: string) => void }; class TriggerEraser extends Transformer { visitCallTrigger (prop: Syntax.CallTrigger): P { return tru; } visitAccessTrigger (prop: Syntax.AccessTrigger): P { return tru; } visitForAllCalls (prop: Syntax.ForAllCalls): P { // do not erase under quantifier -> leave unchanged return copy(prop); } visitForAllAccessObject (prop: Syntax.ForAllAccessObject): P { // do not erase under quantifier -> leave unchanged return copy(prop); } visitForAllAccessProperty (prop: Syntax.ForAllAccessProperty): P { // do not erase under quantifier -> leave unchanged return copy(prop); } } export function eraseTriggersProp (prop: P): P { const v = new TriggerEraser(); return v.visitProp(prop); } abstract class QuantifierTransformer extends Transformer { readonly heaps: Heaps; readonly locs: Locs; readonly vars: Vars; position: boolean; constructor (heaps: Heaps, locs: Locs, vars: Vars) { super(); this.heaps = heaps; this.locs = locs; this.vars = vars; this.position = true; } freshHeap (prefered: Heap): Heap { let n = prefered; while (this.heaps.has(n)) n++; this.heaps.add(n); return n; } freshLoc (prefered: Syntax.Location): Syntax.Location { let name = prefered; if (this.locs.has(name)) { const m = name.match(/(.*)_(\d+)$/); let idx = m ? +m[2] : 0; name = m ? m[1] : name; while (this.locs.has(`${name}_${idx}`)) idx++; name = `${name}_${idx}`; } this.locs.add(name); return name; } freshVar (prefered: Syntax.Variable): Syntax.Variable { let name = prefered; if (this.vars.has(name)) { const m = name.match(/(.*)_(\d+)$/); let idx = m ? +m[2] : 0; name = m ? m[1] : name; while (this.vars.has(`${name}_${idx}`)) idx++; name = `${name}_${idx}`; } this.vars.add(name); return name; } liftExistantials (prop: Syntax.ForAllCalls, newHeap: Syntax.HeapExpression = this.freshHeap(prop.heap)): Substituter { const sub = new Substituter(); sub.replaceHeap(prop.heap, newHeap); prop.existsHeaps.forEach(h => sub.replaceHeap(h, this.freshHeap(h))); prop.existsLocs.forEach(l => sub.replaceLoc(l, this.freshLoc(l))); prop.existsVars.forEach(v => sub.replaceVar(v, this.freshVar(v))); return sub; } visitNot (prop: Syntax.Not): P { this.position = !this.position; try { return super.visitNot(prop); } finally { this.position = !this.position; } } abstract visitForAllCalls (prop: Syntax.ForAllCalls): P; abstract visitForAllAccessObject (prop: Syntax.ForAllAccessObject): P; abstract visitForAllAccessProperty (prop: Syntax.ForAllAccessProperty): P; } class QuantifierLifter extends QuantifierTransformer { freeVars: FreeVars; constructor (heaps: Heaps, locs: Locs, vars: Vars, freeVars: FreeVars) { super(heaps, locs, vars); this.freeVars = freeVars; } visitForAllCalls (prop: Syntax.ForAllCalls): P { if (this.position) return copy(prop); if (prop.existsHeaps.size + prop.existsLocs.size + prop.existsVars.size > 0) { throw new Error('Existentials in negative positions not supported'); } const thisArg: string = this.freshVar(prop.thisArg); const trigger: P = { type: 'CallTrigger', callee: prop.callee, heap: prop.heap, thisArg: prop.thisArg, args: prop.args, fuel: prop.fuel }; const sub = this.liftExistantials(prop); sub.replaceVar(prop.thisArg, thisArg); const renamedVars: Array<Syntax.Variable> = []; prop.args.forEach(a => { const renamedVar = this.freshVar(a); renamedVars.push(renamedVar); this.freeVars.push(renamedVar); sub.replaceVar(a, renamedVar); }); prop.liftCallback(thisArg, renamedVars); return this.visitProp(sub.visitProp(implies(trigger, prop.prop))); } visitForAllAccessObject (prop: Syntax.ForAllAccessObject): P { if (this.position) return copy(prop); const trigger: P = { type: 'AccessTrigger', object: prop.thisArg, property: this.freshVar('prop'), heap: prop.heap, fuel: prop.fuel }; const sub = new Substituter(); sub.replaceVar(prop.thisArg, this.freshVar(prop.thisArg)); return this.visitProp(sub.visitProp(implies(trigger, prop.prop))); } visitForAllAccessProperty (prop: Syntax.ForAllAccessProperty): P { if (this.position) return copy(prop); const trigger: P = { type: 'AccessTrigger', object: prop.object, property: prop.property, heap: prop.heap, fuel: prop.fuel }; const sub = new Substituter(); sub.replaceVar(prop.property, this.freshVar(prop.property)); return this.visitProp(sub.visitProp(implies(trigger, prop.prop))); } } class MaximumDepthFinder extends Reducer<number> { empty (): number { return 0; } reduce (a: number, b: number): number { return Math.max(a, b); } visitForAllCalls (prop: Syntax.ForAllCalls): number { return 1 + super.visitForAllCalls(prop); } visitForAllAccessObject (prop: Syntax.ForAllAccessObject): number { return 1 + super.visitForAllAccessObject(prop); } visitForAllAccessProperty (prop: Syntax.ForAllAccessProperty): number { return 1 + super.visitForAllAccessProperty(prop); } } class TriggerFueler extends Traverser { fuel: number = 0; visitCallTrigger (prop: Syntax.CallTrigger): void { super.visitCallTrigger(prop); prop.fuel = this.fuel; } visitForAllCalls (prop: Syntax.ForAllCalls): void { super.visitForAllCalls(prop); prop.fuel = this.fuel; } visitAccessTrigger (prop: Syntax.AccessTrigger): void { super.visitAccessTrigger(prop); prop.fuel = this.fuel; } visitForAllAccessObject (prop: Syntax.ForAllAccessObject): void { super.visitForAllAccessObject(prop); prop.fuel = this.fuel; } visitForAllAccessProperty (prop: Syntax.ForAllAccessProperty): void { super.visitForAllAccessProperty(prop); prop.fuel = this.fuel; } process (prop: P): P { this.fuel = (new MaximumDepthFinder()).visitProp(prop); this.visitProp(prop); return prop; } } type Triggers = [Array<Syntax.CallTrigger>, Array<Syntax.AccessTrigger>]; class TriggerCollector extends Reducer<Triggers> { position: boolean; constructor (position: boolean) { super(); this.position = position; } empty (): Triggers { return [[], []]; } reduce (a: Triggers, b: Triggers): Triggers { return [a[0].concat(b[0]), a[1].concat(b[1])]; } visitNot (prop: Syntax.Not): Triggers { this.position = !this.position; try { return super.visitNot(prop); } finally { this.position = !this.position; } } visitCallTrigger (prop: Syntax.CallTrigger): Triggers { const res = super.visitCallTrigger(prop); return this.position && prop.fuel > 0 ? this.r([[prop],[]], res) : res; } visitAccessTrigger (prop: Syntax.AccessTrigger): Triggers { const res = super.visitAccessTrigger(prop); return this.position && prop.fuel > 0 ? this.r([[],[prop]], res) : res; } visitForAllCalls (prop: Syntax.ForAllCalls): Triggers { return this.visitExpr(prop.callee); // do not collect under quantifier } visitForAllAccessObject (prop: Syntax.ForAllAccessObject): Triggers { return this.empty(); // do not collect under quantifier } visitForAllAccessProperty (prop: Syntax.ForAllAccessProperty): Triggers { return this.empty(); // do not collect under quantifier } } class QuantifierInstantiator extends QuantifierTransformer { triggers: Triggers = [[], []]; instantiations: number; constructor (heaps: Heaps, locs: Locs, vars: Vars) { super(heaps, locs, vars); this.instantiations = 0; } consumeFuel (prop: P, prevFuel: number): P { const fueler = new TriggerFueler(); fueler.fuel = prevFuel - 1; fueler.visitProp(prop); return prop; } instantiateCall (prop: Syntax.ForAllCalls, trigger: Syntax.CallTrigger) { const sub = this.liftExistantials(prop, trigger.heap); // substitute arguments sub.replaceVar(prop.thisArg, trigger.thisArg); prop.args.forEach((a, idx) => { sub.replaceVar(a, trigger.args[idx]); }); const replaced = sub.visitProp(prop.prop); return this.consumeFuel(replaced, trigger.fuel); } instantiateAccessObject (prop: Syntax.ForAllAccessObject, trigger: Syntax.AccessTrigger) { const sub = new Substituter(); sub.replaceVar(prop.thisArg, trigger.object); sub.replaceHeap(prop.heap, trigger.heap); const replaced = sub.visitProp(prop.prop); return this.consumeFuel(replaced, trigger.fuel); } instantiateAccessProperty (prop: Syntax.ForAllAccessProperty, trigger: Syntax.AccessTrigger) { const sub = new Substituter(); sub.replaceVar(prop.property, trigger.property); sub.replaceHeap(prop.heap, trigger.heap); const replaced = sub.visitProp(prop.prop); return this.consumeFuel(replaced, trigger.fuel); } visitForAllCalls (prop: Syntax.ForAllCalls): P { if (!this.position) return copy(prop); const clauses: Array<P> = [prop]; for (const t of this.triggers[0]) { // continue if already instantiated with same trigger if (prop.args.length !== t.args.length || prop.instantiations.some(trigger => eqProp(t, trigger))) { continue; } const instantiated: P = this.instantiateCall(prop, t); clauses.push(instantiated); prop.instantiations.push(t); this.instantiations++; if (getOptions().verbose && !getOptions().quiet) { console.log('trigger: ' + propositionToSMT(t)); } } return and(...clauses); } visitForAllAccessObject (prop: Syntax.ForAllAccessObject): P { if (!this.position) return copy(prop); const clauses: Array<P> = [prop]; for (const t of this.triggers[1]) { // continue if already instantiated with same trigger, ignoring trigger.property if (prop.instantiations.some(trigger => eqHeap(t.heap, trigger.heap) && eqExpr(t.object, trigger.object))) { continue; } const instantiated: P = this.instantiateAccessObject(prop, t); clauses.push(instantiated); prop.instantiations.push(t); this.instantiations++; if (getOptions().verbose && !getOptions().quiet) { console.log('trigger: ' + propositionToSMT(t)); } } return and(...clauses); } visitForAllAccessProperty (prop: Syntax.ForAllAccessProperty): P { if (!this.position) return copy(prop); const clauses: Array<P> = [prop]; for (const t of this.triggers[1]) { // continue if already instantiated with same trigger if (prop.instantiations.some(trigger => eqProp(t, trigger))) { continue; } const instantiated: P = this.instantiateAccessProperty(prop, t); clauses.push(instantiated); prop.instantiations.push(t); this.instantiations++; if (getOptions().verbose && !getOptions().quiet) { console.log('trigger: ' + propositionToSMT(t)); } } return and(...clauses); } process (prop: P) { this.triggers = (new TriggerCollector(true)).visitProp(prop); return this.visitProp(prop); } } class QuantifierEraser extends Transformer { visitCallTrigger (prop: Syntax.CallTrigger): P { return tru; } visitForAllCalls (prop: Syntax.ForAllCalls): P { return tru; } visitAccessTrigger (prop: Syntax.AccessTrigger): P { return tru; } visitForAllAccessObject (prop: Syntax.ForAllAccessObject): P { return tru; } visitForAllAccessProperty (prop: Syntax.ForAllAccessProperty): P { return tru; } } export function instantiateQuantifiers (heaps: Heaps, locs: Locs, vars: Vars, freeVars: FreeVars, p: P): P { const initialFuel = new TriggerFueler(); const lifter = new QuantifierLifter(heaps, locs, vars, freeVars); const instantiator = new QuantifierInstantiator(heaps, locs, vars); let prop = initialFuel.process(lifter.visitProp(p)); let num = -1; while (instantiator.instantiations > num) { num = instantiator.instantiations; prop = instantiator.process(prop); prop = lifter.visitProp(prop); } prop = (new QuantifierEraser()).visitProp(prop); return prop; }
the_stack
import {AnimationData, Track, Tracks, WidgetInit} from "../../../common/common"; import {Gif, Image, StaticImage} from "./image"; import {RELATIVE_WIDGET_SIZE, Size, TimeRange, UPDATE, Utility, getAspect, resizeMinimumKeepAspect} from "./utility"; import {Background} from "./background"; import {Gizmo} from "./gizmo"; import {Renderer} from "./renderer"; import {Spinner} from "./spinner"; import {Timeline} from "./timeline"; import {VideoPlayer} from "./videoPlayer"; import {setHasUnsavedChanges} from "../shared/unload"; // eslint-disable-next-line @typescript-eslint/no-var-requires const uuidv4: typeof import("uuid/v4") = require("uuid/v4"); const FakeFrameTime = -1; export type ElementFactory = (id: string) => Promise<HTMLElement>; export class Widget { public readonly element: HTMLElement; public readonly init: WidgetInit; /** @internal */ public constructor (element: HTMLElement, init: WidgetInit) { this.element = element; this.init = init; } } export class Manager { private tracks: Tracks = {}; private widgetContainer: HTMLDivElement; private videoPlayer: VideoPlayer; private timeline: Timeline; public selection: Gizmo = null; private widgets: Widget[] = []; private readonly renderer: Renderer; public updateExternally = false; public readonly spinner = new Spinner(); private requestedAnimationFrame: number; public constructor ( background: Background, container: HTMLDivElement, widgetContainer: HTMLDivElement, videoPlayer: VideoPlayer, timeline: Timeline, renderer: Renderer ) { this.widgetContainer = widgetContainer; this.videoPlayer = videoPlayer; this.timeline = timeline; this.renderer = renderer; this.update(); const updateContainerSize = (aspectSize: Size, scale: number) => { container.style.width = `${aspectSize[0]}px`; container.style.height = `${aspectSize[1]}px`; container.style.transform = `translate(${0}px, ${0}px) scale(${scale})`; const width = aspectSize[0] * scale; const height = aspectSize[1] * scale; container.style.left = `${(window.innerWidth - width) / 2}px`; container.style.top = `${(window.innerHeight - height) / 2}px`; }; const onResize = () => { const aspectSize = videoPlayer.getAspectSize(); const windowSize: Size = [ window.innerWidth, window.innerHeight ]; if (getAspect(aspectSize) > getAspect(windowSize)) { updateContainerSize(aspectSize, window.innerWidth / aspectSize[0]); } else { updateContainerSize(aspectSize, window.innerHeight / aspectSize[1]); } }; videoPlayer.video.addEventListener("canplay", onResize); window.addEventListener("resize", onResize); onResize(); const onUpdate = () => { this.requestedAnimationFrame = requestAnimationFrame(onUpdate); window.dispatchEvent(new Event(UPDATE)); this.update(); }; onUpdate(); const deselectElement = (event: Event) => { if (event.target === widgetContainer || event.target === background.canvas) { // If we're touching down, only deselect if it's the only touch (we may be dragging the gizmo). if (window.TouchEvent && event instanceof TouchEvent ? event.touches.length === 1 : true) { this.selectWidget(null); } } }; const onKeyDown = (event) => { if (event.key === "Delete") { this.attemptDeleteSelection(); } }; const registerInputEvents = (element: HTMLElement) => { element.addEventListener("mousedown", deselectElement); element.addEventListener("touchstart", deselectElement); element.addEventListener("keydown", onKeyDown); }; registerInputEvents(widgetContainer); registerInputEvents(background.canvas); registerInputEvents(document.body); } public attemptDeleteSelection () { if (this.selection) { this.destroyWidget(this.selection.widget); } } public updateMarkers () { if (this.selection) { const track = this.tracks[`#${this.selection.widget.element.id}`]; this.videoPlayer.setMarkers(Object.keys(track).map((str) => parseFloat(str))); } else { this.videoPlayer.setMarkers([]); } } public updateChanges () { const tracksCopy: Tracks = JSON.parse(JSON.stringify(this.tracks)); for (const track of Object.values(tracksCopy)) { let hasTransform = false; for (const keyframe of Object.values(track)) { if (keyframe.transform) { hasTransform = true; } } // It's better to always have a frame of visibility so that the user can add a keyframe that hides it. track[FakeFrameTime] = {clip: "auto"}; if (!hasTransform) { track[FakeFrameTime].transform = this.centerTransform(); } } this.timeline.updateTracks(tracksCopy); this.updateMarkers(); } public save (): AnimationData { return { tracks: JSON.parse(JSON.stringify(this.tracks)), videoAttributedSource: this.videoPlayer.getAttributedSrc(), widgets: this.widgets.map((widget) => JSON.parse(JSON.stringify(widget.init))) }; } public async load (data: AnimationData) { this.videoPlayer.setAttributedSrc(data.videoAttributedSource); this.clearWidgets(); for (const init of data.widgets) { await this.addWidget(init); } this.selectWidget(null); this.tracks = data.tracks; this.updateChanges(); // Force a change so everything updates this.timeline.setNormalizedTime(1); this.timeline.setNormalizedTime(0); this.videoPlayer.video.currentTime = 0; await this.videoPlayer.loadPromise; setHasUnsavedChanges(false); } private update () { if (this.updateExternally) { return; } const normalizedCurrentTime = this.videoPlayer.getNormalizedCurrentTime(); this.timeline.setNormalizedTime(normalizedCurrentTime); if (this.selection) { this.selection.update(); } this.renderer.drawFrame(this.videoPlayer.video.currentTime, false); } private centerTransform () { return Utility.transformToCss(Utility.centerTransform(this.videoPlayer.getAspectSize())); } public async addWidget (init: WidgetInit): Promise<Widget> { this.spinner.show(); const element = await (async () => { const img = document.createElement("img"); img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; const {src} = init.attributedSource; const image = init.attributedSource.mimeType === "image/gif" ? new Gif(src) : new StaticImage(src); Image.setImage(img, image); await image.loadPromise; const frame = image.getFrameAtTime(0); const size = resizeMinimumKeepAspect([frame.width, frame.height], [RELATIVE_WIDGET_SIZE, RELATIVE_WIDGET_SIZE]); [img.width, img.height] = size; img.style.left = `${-size[0] / 2}px`; img.style.top = `${-size[1] / 2}px`; return img; })(); let track: Track = {}; if (!init.id) { // Replace the current widget if any is selected. if (this.selection) { init.id = this.selection.widget.init.id; track = this.tracks[`#${init.id}`]; this.destroyWidget(this.selection.widget); } else { init.id = `id-${uuidv4()}`; } } const {id} = init; if (this.tracks[`#${id}`]) { this.spinner.hide(); throw new Error(`Widget id already exists: ${id}`); } element.id = id; element.className = "widget"; element.draggable = false; element.ondragstart = (event) => { event.preventDefault(); return false; }; element.style.transform = this.centerTransform(); element.style.clip = "auto"; this.widgetContainer.appendChild(element); this.tracks[`#${id}`] = track; this.updateChanges(); setHasUnsavedChanges(true); const widget = new Widget(element, init); this.widgets.push(widget); const grabElement = (event) => { this.selectWidget(widget); this.selection.moveable.dragStart(event); }; element.addEventListener("mousedown", grabElement, true); element.addEventListener("touchstart", grabElement, true); this.selectWidget(widget); this.spinner.hide(); return widget; } private isSelected (widget?: Widget) { if (this.selection === null && widget === null) { return true; } if (this.selection && widget && this.selection.widget.element === widget.element) { return true; } return false; } public selectWidget (widget?: Widget) { if (this.isSelected(widget)) { return; } if (this.selection) { this.selection.destroy(); this.selection = null; } if (widget) { this.widgetContainer.focus(); this.selection = new Gizmo(widget); // We intentionally do not call removeEventListener because we already create a new Gizmo each time. this.selection.addEventListener( "transformKeyframe", // We also do not use `this.selection.widget` because we clear selection on motion capture. () => this.keyframe(widget.element, "transform") ); } this.updateMarkers(); } public destroyWidget (widget: Widget) { if (this.isSelected(widget)) { this.selectWidget(null); } widget.element.remove(); delete this.tracks[`#${widget.init.id}`]; this.updateChanges(); setHasUnsavedChanges(true); this.widgets.splice(this.widgets.indexOf(widget), 1); } public clearWidgets () { while (this.widgets.length !== 0) { this.destroyWidget(this.widgets[0]); } } public toggleVisibility (element: HTMLElement) { const {style} = element; style.clip = style.clip === "auto" ? "unset" : "auto"; this.keyframe(element, "clip"); } private keyframe (element: HTMLElement, type: "clip" | "transform") { const track = this.tracks[`#${element.id}`]; const normalizedTime = this.videoPlayer.getNormalizedCurrentTime(); const existingKeyframe = track[normalizedTime]; const newKeyframe = type === "clip" ? {clip: element.style.clip} : {transform: Utility.transformToCss(Utility.getTransform(element))}; // If on the same frame where a 'clip' existed you add a 'transform', this keeps both. track[normalizedTime] = {...existingKeyframe, ...newKeyframe}; this.updateChanges(); setHasUnsavedChanges(true); } public deleteKeyframesInRange (widgetTrackId: string, range: TimeRange) { let result = false; const track = this.tracks[widgetTrackId]; if (track) { for (const normalizedTimeStr of Object.keys(track)) { const normalizedTime = parseFloat(normalizedTimeStr); if (normalizedTime >= range[0] && normalizedTime <= range[1]) { delete track[normalizedTimeStr]; result = true; } } } return result; } public destroy () { this.selectWidget(null); cancelAnimationFrame(this.requestedAnimationFrame); setHasUnsavedChanges(false); } }
the_stack
import { GraphNode } from '@urbit/api'; import BigIntOrderedMap from '@urbit/api/lib/BigIntOrderedMap'; import BigIntArrayOrderedMap, { arrToString, stringToArr } from '@urbit/api/lib/BigIntArrayOrderedMap'; import bigInt, { BigInteger } from 'big-integer'; import produce from 'immer'; import _ from 'lodash'; import { BaseState, reduceState } from '../state/base'; import useGraphState, { GraphState as State } from '../state/graph'; /* eslint-disable camelcase */ import { unstable_batchedUpdates } from 'react-dom'; type GraphState = State & BaseState<State>; const mapifyChildren = (children) => { return new BigIntOrderedMap().gas( _.map(children, (node, idx) => { idx = idx && idx.startsWith('/') ? idx.slice(1) : idx; const nd = { ...node, children: mapifyChildren(node.children || {}) }; return [bigInt(idx), nd]; })); }; const processNode = (node) => { // is empty if (!node.children) { return produce<GraphNode>(node, (draft: GraphNode) => { draft.children = new BigIntOrderedMap(); }); } // is graph return produce<GraphNode>(node, (draft: GraphNode) => { draft.children = new BigIntOrderedMap<GraphNode>() .gas(_.map(draft.children, (item, idx) => [bigInt(idx), processNode(item)] as [BigInteger, any] )); }); }; const acceptOrRejectDm = (json: any, state: GraphState): GraphState => { const data = _.get(json, 'accept', _.get(json, 'decline', false)); if(data) { state.pendingDms.delete(data); } return state; }; const pendings = (json: any, state: GraphState): GraphState => { const data = _.get(json, 'pendings', false); if(data) { state.pendingDms = new Set(data); } return state; }; const setScreen = (json: any, state: GraphState): GraphState => { if('screen' in json) { state.screening = json.screen; } return state; }; const addNodesLoose = (json: any, state: GraphState): GraphState => { const data = _.get(json, 'add-nodes', false); if(data) { const { resource: { ship, name }, nodes } = data; const resource = `${ship}/${name}`; const indices = _.get(state.looseNodes, [resource], {}); _.forIn(nodes, (node, index) => { indices[index] = processNode(node); }); _.set(state.looseNodes, [resource], indices); } return state; }; const addNodesFlat = (json: any, state: GraphState): GraphState => { const data = _.get(json, 'add-nodes', false); if (data) { if (!('flatGraphs' in state)) { return state; } const resource = data.resource.ship + '/' + data.resource.name; if (!(resource in state.flatGraphs)) { state.flatGraphs[resource] = new BigIntArrayOrderedMap(); } if (!(resource in state.graphTimesentMap)) { state.graphTimesentMap[resource] = {}; } const indices = Array.from(Object.keys(data.nodes)); indices.forEach((index) => { if (index.split('/').length === 0) { return; } const indexArr = stringToArr(index); if (indexArr.length === 0) { return state; } const node = data.nodes[index]; node.children = mapifyChildren({}); state.flatGraphs[resource] = state.flatGraphs[resource].set(indexArr, node); }); } return state; }; const addNodesThread = (json: any, state: GraphState): GraphState => { const data = _.get(json, 'add-nodes', false); const parentIndex = _.get(json, 'index', false); if (data && parentIndex) { if (!('threadGraphs' in state)) { return state; } const resource = data.resource.ship + '/' + data.resource.name; if (!(resource in state.threadGraphs)) { state.threadGraphs[resource] = {}; } const indices = Array.from(Object.keys(data.nodes)); if (!(parentIndex in state.threadGraphs[resource])) { state.threadGraphs[resource][parentIndex] = new BigIntArrayOrderedMap([], true); } indices.forEach((index) => { if (index.split('/').length === 0) { return; } const indexArr = stringToArr(index); if (indexArr.length === 0) { return state; } const node = data.nodes[index]; node.children = mapifyChildren({}); state.threadGraphs[resource][parentIndex] = state.threadGraphs[resource][parentIndex].set(indexArr, node); }); } return state; }; const keys = (json, state: GraphState): GraphState => { const data = _.get(json, 'keys', false); if (data) { state.graphKeys = new Set(data.map((res) => { const resource = res.ship + '/' + res.name; return resource; })); } return state; }; const addGraph = (json, state: GraphState): GraphState => { const data = _.get(json, 'add-graph', false); if (data) { if (!('graphs' in state)) { // @ts-ignore investigate zustand types state.graphs = {}; } if (!('flatGraphs' in state)) { // @ts-ignore investigate zustand types state.flatGraphs = {}; } const resource = data.resource.ship + '/' + data.resource.name; state.graphs[resource] = new BigIntOrderedMap(); state.graphTimesentMap[resource] = {}; state.graphs[resource] = state.graphs[resource].gas(Object.keys(data.graph).map((idx) => { return [bigInt(idx), processNode(data.graph[idx])]; })); state.graphKeys.add(resource); } return state; }; const removeGraph = (json, state: GraphState): GraphState => { const data = _.get(json, 'remove-graph', false); if (data) { if (!('graphs' in state)) { // @ts-ignore investigate zustand types state.graphs = {}; } if (!('graphs' in state)) { // @ts-ignore investigate zustand types state.flatGraphs = {}; } const resource = data.ship + '/' + data.name; state.graphKeys.delete(resource); delete state.graphs[resource]; } return state; }; export const addNodes = (json, state) => { const _addNode = (graph, index, node) => { // set child of graph if (index.length === 1) { if (graph.has(index[0])) { return graph; } return graph.set(index[0], node); } // set parent of graph const parNode = graph.get(index[0]); if (!parNode) { console.error('parent node does not exist, cannot add child'); return graph; } return graph.set(index[0], produce(parNode, (draft) => { draft.children = _addNode(draft.children, index.slice(1), node); })); }; const _remove = (graph, index) => { if (index.length === 1) { return graph.delete(index[0]); } else { const child = graph.get(index[0]); if (child) { return graph.set(index[0], produce(child, (draft) => { draft.children = _remove(draft.children, index.slice(1)); })); } } return graph; }; const _removePending = ( graph, flatGraph, threadGraphs, post, resource ) => { const timestamp = post['time-sent']; if (state.graphTimesentMap[resource][timestamp]) { const index = state.graphTimesentMap[resource][timestamp]; if (index.split('/').length === 0) { return graph; } const indexArr = stringToArr(index); delete state.graphTimesentMap[resource][timestamp]; if (graph) { graph = _remove(graph, indexArr); } if (flatGraph) { flatGraph = flatGraph.delete(indexArr); } if (threadGraphs) { const k = []; for (const i in indexArr) { k.push(indexArr[i]); const arr = arrToString(k); if (threadGraphs[arr]) { threadGraphs[arr] = threadGraphs[arr].delete(indexArr); } } } } return [graph, flatGraph, threadGraphs]; }; const data = _.get(json, 'add-nodes', false); if (data) { if (!('graphs' in state)) { return state; } if (!('flatGraphs' in state)) { return state; } if (!('threadGraphs' in state)) { return state; } const resource = data.resource.ship + '/' + data.resource.name; if (!(resource in state.graphs)) { if(json.fetch) { state.graphs[resource] = new BigIntOrderedMap(); } else { // ignore updates until we load backlog deliberately, to avoid // unnecessary memory usage return state; } } if (!(resource in state.graphTimesentMap)) { state.graphTimesentMap[resource] = {}; } state.graphKeys.add(resource); const indices = Array.from(Object.keys(data.nodes)); indices.sort((a, b) => { const aArr = a.split('/'); const bArr = b.split('/'); return aArr.length - bArr.length; }); indices.forEach((index) => { const node = data.nodes[index]; const old = state.graphs[resource].size; if (index.split('/').length === 0) { return state; } const indexArr = stringToArr(index); const [graph, flatGraph, threadGraphs] = _removePending( state.graphs[resource], state.flatGraphs[resource], state.threadGraphs[resource], node.post, resource ); if (graph) { state.graphs[resource] = graph; } if (flatGraph) { state.flatGraphs[resource] = flatGraph; } if (threadGraphs) { state.threadGraphs[resource] = threadGraphs; } const newSize = state.graphs[resource].size; if (node.post.pending) { state.graphTimesentMap[resource][node.post['time-sent']] = index; } state.graphs[resource] = _addNode( state.graphs[resource], indexArr, produce(node, (draft) => { draft.children = mapifyChildren(draft?.children || {}); }) ); if (resource in state.flatGraphs) { state.flatGraphs[resource] = state.flatGraphs[resource].set(indexArr, produce(node, (draft) => { draft.children = mapifyChildren({}); })); } if (indexArr.length > 1 && resource in state.threadGraphs) { const parentKey = arrToString(indexArr.slice(0, indexArr.length - 1)); if (parentKey in state.threadGraphs[resource]) { const thread = state.threadGraphs[resource][parentKey]; const isFirstChild = Array.from(thread.keys()).filter((k) => { // @ts-ignore @tacryt-socryp what do? return stringToArr(parentKey).length < k.length; }).length === 0; if (isFirstChild) { state.threadGraphs[resource][parentKey] = state.threadGraphs[resource][parentKey].set( indexArr, produce(node, (draft) => { draft.children = mapifyChildren({}); }) ); } } } if(newSize !== old) { console.log(`${resource}, (${old}, ${newSize}, ${state.graphs[resource].size})`); } }); } return state; }; const removePosts = (json, state: GraphState): GraphState => { const _remove = (graph, index) => { const child = graph.get(index[0]); if(!child) { return graph; } if (index.length === 1) { return graph.set(index[0], { post: child.post.hash || '', children: child.children }); } else { const node = { ...child, children: _remove(child.children, index.slice(1)) }; return graph.set(index[0], node); } }; const data = _.get(json, 'remove-posts', false); if (data) { const { ship, name } = data.resource; const res = `${ship}/${name}`; if (!(res in state.graphs)) { return state; } data.indices.forEach((index) => { if (index.split('/').length === 0) { return; } const indexArr = stringToArr(index); state.graphs[res] = _remove(state.graphs[res], indexArr); }); } return state; }; export const reduceDm = [ acceptOrRejectDm, pendings, setScreen ]; export const GraphReducer = (json) => { const data = _.get(json, 'graph-update', false); unstable_batchedUpdates(() => { if (data) { reduceState<GraphState, any>(useGraphState, data, [ keys, addGraph, removeGraph, addNodes, removePosts ]); } const loose = _.get(json, 'graph-update-loose', false); if(loose) { reduceState<GraphState, any>(useGraphState, loose, [addNodesLoose]); } const flat = _.get(json, 'graph-update-flat', false); if (flat) { reduceState<GraphState, any>(useGraphState, flat, [addNodesFlat]); } const thread = _.get(json, 'graph-update-thread', false); if (thread) { reduceState<GraphState, any>(useGraphState, thread, [addNodesThread]); } }); };
the_stack
import { b2_linearSlop, b2Maybe, b2_maxFloat } from "../common/b2_settings.js"; import { b2Abs, b2Clamp, b2Vec2, b2Rot, XY, b2Max, b2Transform } from "../common/b2_math.js"; import { b2Joint, b2JointDef, b2JointType, b2IJointDef } from "./b2_joint.js"; import { b2SolverData } from "./b2_time_step.js"; import { b2Body } from "./b2_body.js"; import { b2Color, b2Draw } from "../common/b2_draw.js"; export interface b2IDistanceJointDef extends b2IJointDef { localAnchorA?: XY; localAnchorB?: XY; length?: number; minLength?: number; maxLength?: number; stiffness?: number; damping?: number; } /// Distance joint definition. This requires defining an /// anchor point on both bodies and the non-zero length of the /// distance joint. The definition uses local anchor points /// so that the initial configuration can violate the constraint /// slightly. This helps when saving and loading a game. /// @warning Do not use a zero or short length. export class b2DistanceJointDef extends b2JointDef implements b2IDistanceJointDef { public readonly localAnchorA: b2Vec2 = new b2Vec2(); public readonly localAnchorB: b2Vec2 = new b2Vec2(); public length: number = 1; public minLength: number = 0; public maxLength: number = b2_maxFloat; // FLT_MAX; public stiffness: number = 0; public damping: number = 0; constructor() { super(b2JointType.e_distanceJoint); } public Initialize(b1: b2Body, b2: b2Body, anchor1: XY, anchor2: XY): void { this.bodyA = b1; this.bodyB = b2; this.bodyA.GetLocalPoint(anchor1, this.localAnchorA); this.bodyB.GetLocalPoint(anchor2, this.localAnchorB); this.length = b2Max(b2Vec2.DistanceVV(anchor1, anchor2), b2_linearSlop); this.minLength = this.length; this.maxLength = this.length; } } export class b2DistanceJoint extends b2Joint { public m_stiffness: number = 0; public m_damping: number = 0; public m_bias: number = 0; public m_length: number = 0; public m_minLength: number = 0; public m_maxLength: number = 0; // Solver shared public readonly m_localAnchorA: b2Vec2 = new b2Vec2(); public readonly m_localAnchorB: b2Vec2 = new b2Vec2(); public m_gamma: number = 0; public m_impulse: number = 0; public m_lowerImpulse: number = 0; public m_upperImpulse: number = 0; // Solver temp public m_indexA: number = 0; public m_indexB: number = 0; public readonly m_u: b2Vec2 = new b2Vec2(); public readonly m_rA: b2Vec2 = new b2Vec2(); public readonly m_rB: b2Vec2 = new b2Vec2(); public readonly m_localCenterA: b2Vec2 = new b2Vec2(); public readonly m_localCenterB: b2Vec2 = new b2Vec2(); public m_currentLength: number = 0; public m_invMassA: number = 0; public m_invMassB: number = 0; public m_invIA: number = 0; public m_invIB: number = 0; public m_softMass: number = 0; public m_mass: number = 0; public readonly m_qA: b2Rot = new b2Rot(); public readonly m_qB: b2Rot = new b2Rot(); public readonly m_lalcA: b2Vec2 = new b2Vec2(); public readonly m_lalcB: b2Vec2 = new b2Vec2(); constructor(def: b2IDistanceJointDef) { super(def); this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, b2Vec2.ZERO)); this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, b2Vec2.ZERO)); this.m_length = b2Max(b2Maybe(def.length, this.GetCurrentLength()), b2_linearSlop); this.m_minLength = b2Max(b2Maybe(def.minLength, this.m_length), b2_linearSlop); this.m_maxLength = b2Max(b2Maybe(def.maxLength, this.m_length), this.m_minLength); this.m_stiffness = b2Maybe(def.stiffness, 0); this.m_damping = b2Maybe(def.damping, 0); } public GetAnchorA<T extends XY>(out: T): T { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); } public GetAnchorB<T extends XY>(out: T): T { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); } public GetReactionForce<T extends XY>(inv_dt: number, out: T): T { // b2Vec2 F = inv_dt * (m_impulse + m_lowerImpulse - m_upperImpulse) * m_u; out.x = inv_dt * (this.m_impulse + this.m_lowerImpulse - this.m_upperImpulse) * this.m_u.x; out.y = inv_dt * (this.m_impulse + this.m_lowerImpulse - this.m_upperImpulse) * this.m_u.y; return out; } public GetReactionTorque(inv_dt: number): number { return 0; } public GetLocalAnchorA(): Readonly<b2Vec2> { return this.m_localAnchorA; } public GetLocalAnchorB(): Readonly<b2Vec2> { return this.m_localAnchorB; } public SetLength(length: number): number { this.m_impulse = 0; this.m_length = b2Max(b2_linearSlop, length); return this.m_length; } public GetLength(): number { return this.m_length; } public SetMinLength(minLength: number): number { this.m_lowerImpulse = 0; this.m_minLength = b2Clamp(minLength, b2_linearSlop, this.m_maxLength); return this.m_minLength; } public SetMaxLength(maxLength: number): number { this.m_upperImpulse = 0; this.m_maxLength = b2Max(maxLength, this.m_minLength); return this.m_maxLength; } public GetCurrentLength(): number { const pA: b2Vec2 = this.m_bodyA.GetWorldPoint(this.m_localAnchorA, new b2Vec2()); const pB: b2Vec2 = this.m_bodyB.GetWorldPoint(this.m_localAnchorB, new b2Vec2()); return b2Vec2.DistanceVV(pA, pB); } public SetStiffness(stiffness: number): void { this.m_stiffness = stiffness; } public GetStiffness() { return this.m_stiffness; } public SetDamping(damping: number): void { this.m_damping = damping; } public GetDamping() { return this.m_damping; } public override Dump(log: (format: string, ...args: any[]) => void) { const indexA: number = this.m_bodyA.m_islandIndex; const indexB: number = this.m_bodyB.m_islandIndex; log(" const jd: b2DistanceJointDef = new b2DistanceJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", (this.m_collideConnected) ? ("true") : ("false")); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.length = %.15f;\n", this.m_length); log(" jd.minLength = %.15f;\n", this.m_minLength); log(" jd.maxLength = %.15f;\n", this.m_maxLength); log(" jd.stiffness = %.15f;\n", this.m_stiffness); log(" jd.damping = %.15f;\n", this.m_damping); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); } private static InitVelocityConstraints_s_P = new b2Vec2(); public InitVelocityConstraints(data: b2SolverData): void { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const cA: b2Vec2 = data.positions[this.m_indexA].c; const aA: number = data.positions[this.m_indexA].a; const vA: b2Vec2 = data.velocities[this.m_indexA].v; let wA: number = data.velocities[this.m_indexA].w; const cB: b2Vec2 = data.positions[this.m_indexB].c; const aB: number = data.positions[this.m_indexB].a; const vB: b2Vec2 = data.velocities[this.m_indexB].v; let wB: number = data.velocities[this.m_indexB].w; // const qA: b2Rot = new b2Rot(aA), qB: b2Rot = new b2Rot(aB); const qA: b2Rot = this.m_qA.SetAngle(aA), qB: b2Rot = this.m_qB.SetAngle(aB); // m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // m_u = cB + m_rB - cA - m_rA; this.m_u.x = cB.x + this.m_rB.x - cA.x - this.m_rA.x; this.m_u.y = cB.y + this.m_rB.y - cA.y - this.m_rA.y; // Handle singularity. this.m_currentLength = this.m_u.Length(); if (this.m_currentLength > b2_linearSlop) { this.m_u.SelfMul(1 / this.m_currentLength); } else { this.m_u.SetZero(); this.m_mass = 0; this.m_impulse = 0; this.m_lowerImpulse = 0; this.m_upperImpulse = 0; } // float32 crAu = b2Cross(m_rA, m_u); const crAu: number = b2Vec2.CrossVV(this.m_rA, this.m_u); // float32 crBu = b2Cross(m_rB, m_u); const crBu: number = b2Vec2.CrossVV(this.m_rB, this.m_u); // float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu; let invMass: number = this.m_invMassA + this.m_invIA * crAu * crAu + this.m_invMassB + this.m_invIB * crBu * crBu; this.m_mass = invMass !== 0 ? 1 / invMass : 0; if (this.m_stiffness > 0 && this.m_minLength < this.m_maxLength) { // soft const C: number = this.m_currentLength - this.m_length; const d: number = this.m_damping; const k: number = this.m_stiffness; // magic formulas const h: number = data.step.dt; // gamma = 1 / (h * (d + h * k)) // the extra factor of h in the denominator is since the lambda is an impulse, not a force this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma !== 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invMass += this.m_gamma; this.m_softMass = invMass !== 0 ? 1 / invMass : 0; } else { // rigid this.m_gamma = 0; this.m_bias = 0; this.m_softMass = this.m_mass; } if (data.step.warmStarting) { // Scale the impulse to support a variable time step. this.m_impulse *= data.step.dtRatio; this.m_lowerImpulse *= data.step.dtRatio; this.m_upperImpulse *= data.step.dtRatio; const P: b2Vec2 = b2Vec2.MulSV(this.m_impulse + this.m_lowerImpulse - this.m_upperImpulse, this.m_u, b2DistanceJoint.InitVelocityConstraints_s_P); vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); } else { this.m_impulse = 0; } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } private static SolveVelocityConstraints_s_vpA = new b2Vec2(); private static SolveVelocityConstraints_s_vpB = new b2Vec2(); private static SolveVelocityConstraints_s_P = new b2Vec2(); public SolveVelocityConstraints(data: b2SolverData): void { const vA: b2Vec2 = data.velocities[this.m_indexA].v; let wA: number = data.velocities[this.m_indexA].w; const vB: b2Vec2 = data.velocities[this.m_indexB].v; let wB: number = data.velocities[this.m_indexB].w; if (this.m_minLength < this.m_maxLength) { if (this.m_stiffness > 0) { // Cdot = dot(u, v + cross(w, r)) const vpA: b2Vec2 = b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2DistanceJoint.SolveVelocityConstraints_s_vpA); const vpB: b2Vec2 = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2DistanceJoint.SolveVelocityConstraints_s_vpB); const Cdot: number = b2Vec2.DotVV(this.m_u, b2Vec2.SubVV(vpB, vpA, b2Vec2.s_t0)); const impulse: number = -this.m_softMass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse); this.m_impulse += impulse; const P: b2Vec2 = b2Vec2.MulSV(impulse, this.m_u, b2DistanceJoint.SolveVelocityConstraints_s_P); vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); } // lower { const C: number = this.m_currentLength - this.m_minLength; const bias: number = b2Max(0, C) * data.step.inv_dt; const vpA: b2Vec2 = b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2DistanceJoint.SolveVelocityConstraints_s_vpA); const vpB: b2Vec2 = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2DistanceJoint.SolveVelocityConstraints_s_vpB); const Cdot: number = b2Vec2.DotVV(this.m_u, b2Vec2.SubVV(vpB, vpA, b2Vec2.s_t0)); let impulse: number = -this.m_mass * (Cdot + bias); const oldImpulse: number = this.m_lowerImpulse; this.m_lowerImpulse = b2Max(0, this.m_lowerImpulse + impulse); impulse = this.m_lowerImpulse - oldImpulse; const P: b2Vec2 = b2Vec2.MulSV(impulse, this.m_u, b2DistanceJoint.SolveVelocityConstraints_s_P); vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); } // upper { const C: number = this.m_maxLength - this.m_currentLength; const bias: number = b2Max(0, C) * data.step.inv_dt; const vpA: b2Vec2 = b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2DistanceJoint.SolveVelocityConstraints_s_vpA); const vpB: b2Vec2 = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2DistanceJoint.SolveVelocityConstraints_s_vpB); const Cdot: number = b2Vec2.DotVV(this.m_u, b2Vec2.SubVV(vpA, vpB, b2Vec2.s_t0)); let impulse: number = -this.m_mass * (Cdot + bias); const oldImpulse: number = this.m_upperImpulse; this.m_upperImpulse = b2Max(0, this.m_upperImpulse + impulse); impulse = this.m_upperImpulse - oldImpulse; const P: b2Vec2 = b2Vec2.MulSV(-impulse, this.m_u, b2DistanceJoint.SolveVelocityConstraints_s_P); vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); } } else { // Equal limits // Cdot = dot(u, v + cross(w, r)) const vpA: b2Vec2 = b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2DistanceJoint.SolveVelocityConstraints_s_vpA); const vpB: b2Vec2 = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2DistanceJoint.SolveVelocityConstraints_s_vpB); const Cdot: number = b2Vec2.DotVV(this.m_u, b2Vec2.SubVV(vpB, vpA, b2Vec2.s_t0)); const impulse: number = -this.m_mass * Cdot; this.m_impulse += impulse; const P: b2Vec2 = b2Vec2.MulSV(impulse, this.m_u, b2DistanceJoint.SolveVelocityConstraints_s_P); vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); } // data.velocities[this.m_indexA].v = vA; data.velocities[this.m_indexA].w = wA; // data.velocities[this.m_indexB].v = vB; data.velocities[this.m_indexB].w = wB; } private static SolvePositionConstraints_s_P = new b2Vec2(); public SolvePositionConstraints(data: b2SolverData): boolean { const cA: b2Vec2 = data.positions[this.m_indexA].c; let aA: number = data.positions[this.m_indexA].a; const cB: b2Vec2 = data.positions[this.m_indexB].c; let aB: number = data.positions[this.m_indexB].a; // const qA: b2Rot = new b2Rot(aA), qB: b2Rot = new b2Rot(aB); const qA: b2Rot = this.m_qA.SetAngle(aA), qB: b2Rot = this.m_qB.SetAngle(aB); // b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); const rA: b2Vec2 = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); // use m_rA // b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); const rB: b2Vec2 = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); // use m_rB // b2Vec2 u = cB + rB - cA - rA; const u: b2Vec2 = this.m_u; // use m_u u.x = cB.x + rB.x - cA.x - rA.x; u.y = cB.y + rB.y - cA.y - rA.y; const length: number = this.m_u.Normalize(); let C: number; if (this.m_minLength == this.m_maxLength) { C = length - this.m_minLength; } else if (length < this.m_minLength) { C = length - this.m_minLength; } else if (this.m_maxLength < length) { C = length - this.m_maxLength; } else { return true; } const impulse: number = -this.m_mass * C; const P: b2Vec2 = b2Vec2.MulSV(impulse, u, b2DistanceJoint.SolvePositionConstraints_s_P); cA.SelfMulSub(this.m_invMassA, P); aA -= this.m_invIA * b2Vec2.CrossVV(rA, P); cB.SelfMulAdd(this.m_invMassB, P); aB += this.m_invIB * b2Vec2.CrossVV(rB, P); // data.positions[this.m_indexA].c = cA; data.positions[this.m_indexA].a = aA; // data.positions[this.m_indexB].c = cB; data.positions[this.m_indexB].a = aB; return b2Abs(C) < b2_linearSlop; } private static Draw_s_pA = new b2Vec2(); private static Draw_s_pB = new b2Vec2(); private static Draw_s_axis = new b2Vec2(); private static Draw_s_c1 = new b2Color(0.7, 0.7, 0.7); private static Draw_s_c2 = new b2Color(0.3, 0.9, 0.3); private static Draw_s_c3 = new b2Color(0.9, 0.3, 0.3); private static Draw_s_c4 = new b2Color(0.4, 0.4, 0.4); private static Draw_s_pRest = new b2Vec2(); private static Draw_s_pMin = new b2Vec2(); private static Draw_s_pMax = new b2Vec2(); public override Draw(draw: b2Draw): void { const xfA: Readonly<b2Transform> = this.m_bodyA.GetTransform(); const xfB: Readonly<b2Transform> = this.m_bodyB.GetTransform(); const pA = b2Transform.MulXV(xfA, this.m_localAnchorA, b2DistanceJoint.Draw_s_pA); const pB = b2Transform.MulXV(xfB, this.m_localAnchorB, b2DistanceJoint.Draw_s_pB); const axis: b2Vec2 = b2Vec2.SubVV(pB, pA, b2DistanceJoint.Draw_s_axis); axis.Normalize(); const c1 = b2DistanceJoint.Draw_s_c1; // b2Color c1(0.7f, 0.7f, 0.7f); const c2 = b2DistanceJoint.Draw_s_c2; // b2Color c2(0.3f, 0.9f, 0.3f); const c3 = b2DistanceJoint.Draw_s_c3; // b2Color c3(0.9f, 0.3f, 0.3f); const c4 = b2DistanceJoint.Draw_s_c4; // b2Color c4(0.4f, 0.4f, 0.4f); draw.DrawSegment(pA, pB, c4); // b2Vec2 pRest = pA + this.m_length * axis; const pRest: b2Vec2 = b2Vec2.AddVMulSV(pA, this.m_length, axis, b2DistanceJoint.Draw_s_pRest); draw.DrawPoint(pRest, 8.0, c1); if (this.m_minLength != this.m_maxLength) { if (this.m_minLength > b2_linearSlop) { // b2Vec2 pMin = pA + this.m_minLength * axis; const pMin: b2Vec2 = b2Vec2.AddVMulSV(pA, this.m_minLength, axis, b2DistanceJoint.Draw_s_pMin); draw.DrawPoint(pMin, 4.0, c2); } if (this.m_maxLength < b2_maxFloat) { // b2Vec2 pMax = pA + this.m_maxLength * axis; const pMax: b2Vec2 = b2Vec2.AddVMulSV(pA, this.m_maxLength, axis, b2DistanceJoint.Draw_s_pMax); draw.DrawPoint(pMax, 4.0, c3); } } } }
the_stack
import { DagManagerService } from './dag-manager.service'; import { DagModelItem } from './interfaces/dag-model-item'; interface TestDagModel extends DagModelItem { name: string; } describe('DagManagerService', () => { let service: DagManagerService<TestDagModel>; beforeEach(() => { service = new DagManagerService<TestDagModel>(); }); it('should be created', () => { expect(service).toBeTruthy(); }); /* *************************************************************************** 1 2 3 4 **************************************************************************** */ it('should convert the simple array to a DAG model', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, ]; const result = service.convertArrayToDagModel(items); const expectedResult = [ [{ branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }], [ { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, ], [{ branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }], ]; expect(result).toStrictEqual(expectedResult); }); /* *************************************************************************** 1 2 3 4 5 **************************************************************************** */ it('should convert a more complicated array to a DAG model', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, { branchPath: 1, name: 'Step 5', parentIds: [4, 3], stepId: 5 }, ]; const result = service.convertArrayToDagModel(items); const expectedResult = [ [{ branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }], [ { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, ], [{ branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }], [{ branchPath: 1, name: 'Step 5', parentIds: [4, 3], stepId: 5 }], ]; expect(result).toStrictEqual(expectedResult); }); /* *************************************************************************** 1 5 6 7 2 3 4 **************************************************************************** */ it('should properly display the graph with a node that has three children', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [5], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [5], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, { branchPath: 1, name: 'Step 5', parentIds: [1], stepId: 5 }, { branchPath: 2, name: 'Step 6', parentIds: [1], stepId: 6 }, { branchPath: 3, name: 'Step 7', parentIds: [1], stepId: 7 }, ]; const dagModel = [ [{ branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }], [ { branchPath: 1, name: 'Step 5', parentIds: [1], stepId: 5 }, { branchPath: 2, name: 'Step 6', parentIds: [1], stepId: 6 }, { branchPath: 3, name: 'Step 7', parentIds: [1], stepId: 7 }, ], [ { branchPath: 1, name: 'Step 2', parentIds: [5], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [5], stepId: 3 }, ], [{ branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }], ]; const result = service.convertArrayToDagModel(items); expect(result).toStrictEqual(dagModel); }); /* *************************************************************************** 1 4 3 **************************************************************************** */ it('should properly order the items on a row by branch path', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [1], stepId: 4 }, ]; const dagModel = [ [{ branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }], [ { branchPath: 1, name: 'Step 4', parentIds: [1], stepId: 4 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, ], ]; const result = service.convertArrayToDagModel(items); expect(result).toStrictEqual(dagModel); }); it('should return if an item is found in a two dimensional array', () => { const dagModel = [ [{ branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }], [ { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, ], [{ branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }], [{ branchPath: 1, name: 'Step 5', parentIds: [4, 3], stepId: 5 }], ]; const found1 = service.findInDoubleArray(1, dagModel); const found6 = service.findInDoubleArray(6, dagModel); expect(found1).toBe(0); expect(found6).toBe(-1); }); /* *************************************************************************** 1 | 1 2 3 | 5 4 | 2 3 | 4 **************************************************************************** */ it('should add an item to the array', () => { service.setNextNumber(5); const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [5], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [5], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, { branchPath: 1, name: '', parentIds: [1], stepId: 5 }, ]; const itemsList = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, ]; const result = service.addItem([1], itemsList, 1, 1, { name: '' }); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 1 2 3 | 5 6 4 | 2 3 | 4 **************************************************************************** */ it('should add two items to the array', () => { service.setNextNumber(5); const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [5], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [5], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, { branchPath: 1, name: '', parentIds: [1], stepId: 5 }, { branchPath: 2, name: '', parentIds: [1], stepId: 6 }, ]; const itemsList = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, ]; const result = service.addItem([1], itemsList, 2, 1, { name: '' }); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 1 2 3 | 5 6 7 4 | 2 3 | 4 **************************************************************************** */ it('should add three items to the array', () => { service.setNextNumber(5); const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [5], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [5], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, { branchPath: 1, name: '', parentIds: [1], stepId: 5 }, { branchPath: 2, name: '', parentIds: [1], stepId: 6 }, { branchPath: 3, name: '', parentIds: [1], stepId: 7 }, ]; const itemsList = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, ]; const result = service.addItem([1], itemsList, 3, 1, { name: '' }); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 1 2 3 | 4 5 | 2 3 | **************************************************************************** */ it('should add two items to the array as a child to the first node and a parent to the original branch', () => { service.setNextNumber(4); const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [4], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [4], stepId: 3 }, { branchPath: 1, name: '', parentIds: [1], stepId: 4 }, { branchPath: 2, name: '', parentIds: [1], stepId: 5 }, ]; const itemsList = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, ]; const result = service.addItem([1], itemsList, 2, 1, { name: '' }); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 1 2 3 | 2 3 5 4 | 4 | **************************************************************************** */ it('should add a new child path from 1 at the same level as 2 and 3', () => { service.setNextNumber(5); const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, { branchPath: 3, name: '', parentIds: [1], stepId: 5 }, ]; const itemsList = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, ]; const result = service.addItemAsNewPath(1, itemsList, 1, { name: '' }); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 1 2 3 | 2 3 5 6 4 | 4 | **************************************************************************** */ it('should add a new child path from 1 at the same level as 2 and 3', () => { service.setNextNumber(5); const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, { branchPath: 3, name: '', parentIds: [1], stepId: 5 }, { branchPath: 4, name: '', parentIds: [1], stepId: 6 }, ]; const itemsList = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, ]; const result = service.addItemAsNewPath(1, itemsList, 2, { name: '' }); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 1 2 3 | 2 3 4 | **************************************************************************** */ it('should remove a child at the end of the graph', () => { const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, ]; const itemsArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2, 3], stepId: 4 }, ]; const result = service.removeItem(4, itemsArray); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 1 2 | 3 3 | **************************************************************************** */ it('should remove a child with only a single child', () => { const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 3', parentIds: [1], stepId: 3 }, ]; const itemsArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 1, name: 'Step 3', parentIds: [2], stepId: 3 }, ]; const result = service.removeItem(2, itemsArray); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 1 2 3 | 2 5 4 5 | 4 **************************************************************************** */ it('should remove the branch 2 child and rearrange', () => { const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, { branchPath: 2, name: 'Step 5', parentIds: [1], stepId: 5 }, ]; const itemsArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, { branchPath: 1, name: 'Step 5', parentIds: [3], stepId: 5 }, ]; const result = service.removeItem(3, itemsArray); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 2 2 3 | 4 4 5 | **************************************************************************** */ it('should remove a parent of nodes that branch and rearrange', () => { const expectedResultArray = [ { branchPath: 1, name: 'Step 2', parentIds: [0], stepId: 2 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, ]; const itemsArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, { branchPath: 1, name: 'Step 5', parentIds: [3], stepId: 5 }, ]; const result = service.removeItem(1, itemsArray); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 2 2 3 4 | 5 5 6 7 | **************************************************************************** */ it('should remove all but the branch 1 child and rearrange', () => { const expectedResultArray = [ { branchPath: 1, name: 'Step 2', parentIds: [0], stepId: 2 }, { branchPath: 1, name: 'Step 5', parentIds: [2], stepId: 5 }, ]; const itemsArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 3, name: 'Step 4', parentIds: [1], stepId: 4 }, { branchPath: 1, name: 'Step 5', parentIds: [2], stepId: 5 }, { branchPath: 1, name: 'Step 6', parentIds: [3], stepId: 6 }, { branchPath: 1, name: 'Step 7', parentIds: [4], stepId: 7 }, ]; const result = service.removeItem(1, itemsArray); expect(result).toStrictEqual(expectedResultArray); }); /* *************************************************************************** 1 | 1 2 3 4 | 2 6 4 5 6 7 | 5 7 **************************************************************************** */ it('should remove all but the branch 1 child and rearrange', () => { const expectedResultArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 3, name: 'Step 4', parentIds: [1], stepId: 4 }, { branchPath: 1, name: 'Step 5', parentIds: [2], stepId: 5 }, { branchPath: 2, name: 'Step 6', parentIds: [1], stepId: 6 }, { branchPath: 1, name: 'Step 7', parentIds: [4], stepId: 7 }, ]; const itemsArray = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 3, name: 'Step 4', parentIds: [1], stepId: 4 }, { branchPath: 1, name: 'Step 5', parentIds: [2], stepId: 5 }, { branchPath: 1, name: 'Step 6', parentIds: [3], stepId: 6 }, { branchPath: 1, name: 'Step 7', parentIds: [4], stepId: 7 }, ]; const result = service.removeItem(3, itemsArray); expect(result).toStrictEqual(expectedResultArray); }); it('should return result if two nodes are siblings', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 3, name: 'Step 3', parentIds: [1], stepId: 3 }, ]; const result1 = service.areNodesSiblings(2, 3, items); const result2 = service.areNodesSiblings(1, 3, items); expect(result1).toBe(true); expect(result2).toBe(false); }); it('should return the proper depth for a node', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, { branchPath: 2, name: 'Step 5', parentIds: [2], stepId: 5 }, { branchPath: 1, name: 'Step 6', parentIds: [5, 3], stepId: 6 }, ]; const depth1 = service.getNodeDepth(1, items); const depth3 = service.getNodeDepth(3, items); const depth5 = service.getNodeDepth(5, items); const depth6 = service.getNodeDepth(6, items); expect(depth1).toBe(0); expect(depth3).toBe(1); expect(depth5).toBe(2); expect(depth6).toBe(3); }); it('should return if a node is a child of another node', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, { branchPath: 2, name: 'Step 5', parentIds: [2], stepId: 5 }, { branchPath: 1, name: 'Step 6', parentIds: [5, 3], stepId: 6 }, ]; const isChild1 = service.isNodeAChildOfParent(6, 1, items); const isChild2 = service.isNodeAChildOfParent(4, 3, items); const isChild3 = service.isNodeAChildOfParent(4, 6, items); const isChild4 = service.isNodeAChildOfParent(6, 4, items); const isChild5 = service.isNodeAChildOfParent(1, 4, items); expect(isChild1).toBe(true); expect(isChild2).toBe(false); expect(isChild3).toBe(false); expect(isChild4).toBe(false); expect(isChild5).toBe(false); }); it('should return if two nodes would create a circular dependency', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, { branchPath: 2, name: 'Step 5', parentIds: [2], stepId: 5 }, { branchPath: 1, name: 'Step 6', parentIds: [5, 3], stepId: 6 }, ]; const result1 = service.wouldCreateCircularDependency(6, 1, items); const result2 = service.wouldCreateCircularDependency(5, 6, items); const result3 = service.wouldCreateCircularDependency(4, 6, items); expect(result1).toBe(false); expect(result2).toBe(true); expect(result3).toBe(false); }); it('should return if a relationship can be added between two nodes', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, { branchPath: 2, name: 'Step 5', parentIds: [2], stepId: 5 }, { branchPath: 1, name: 'Step 6', parentIds: [5, 3], stepId: 6 }, ]; const result1 = service.canAddRelation(6, 4, items); const result2 = service.canAddRelation(5, 4, items); const result3 = service.canAddRelation(6, 1, items); const result4 = service.canAddRelation(6, 3, items); const result5 = service.canAddRelation(5, 3, items); expect(result1).toBe(true); expect(result2).toBe(false); expect(result3).toBe(false); expect(result4).toBe(false); expect(result5).toBe(true); }); it('should return the proper number of children for a given node', () => { const items = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, { branchPath: 2, name: 'Step 5', parentIds: [2], stepId: 5 }, { branchPath: 1, name: 'Step 6', parentIds: [5, 3], stepId: 6 }, ]; service.setNewItemsArrayAsDagModel(items); const result1 = service.nodeChildrenCount(1); expect(result1).toBe(2); const result3 = service.nodeChildrenCount(3); expect(result3).toBe(1); }); it('should add the relation between a parent and child node', () => { const items: Array<TestDagModel> = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 1, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, ]; service.setNewItemsArrayAsDagModel(items); const returnedItems = service.addRelation(4, 3); const returnedItems4 = returnedItems.find( (i: TestDagModel) => i.stepId === 4 ); expect(returnedItems4.parentIds).toStrictEqual([2, 3]); }); it('should throw an error if a relationship cannot be made between two nodes', () => { const items: Array<TestDagModel> = [ { branchPath: 1, name: 'Parent', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Child', parentIds: [1], stepId: 2 }, ]; service.setNewItemsArrayAsDagModel(items); try { service.addRelation(2, 1); } catch (error) { expect(error).toBeTruthy(); expect(error.message).toBe( 'DagManagerService error: Cannot add parent ID 1 to child 2' ); } }); /* *************************************************************************** 1 | 1 2 3 | 4 3 | 2 **************************************************************************** */ it('should insert a node between two others', () => { const items: Array<TestDagModel> = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, ]; service.setNextNumber(4); service.setNewItemsArrayAsDagModel(items); const updated = service.insertNode(2, { branchPath: null, name: 'Step 4', parentIds: [], stepId: null, }); expect(updated).toStrictEqual([ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [4], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [1], stepId: 4 }, ]); }); /* *************************************************************************** 1 | 1 2 3 | 4 3 | **************************************************************************** */ it('should insert a node and remove the node that was previously there', () => { const items: Array<TestDagModel> = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, ]; service.setNextNumber(4); service.setNewItemsArrayAsDagModel(items); const updated = service.insertNodeAndRemoveOld(2, { branchPath: null, name: 'Step 4', parentIds: [], stepId: null, }); expect(updated).toStrictEqual([ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [1], stepId: 4 }, ]); }); /* *************************************************************************** 1 | 1 2 3 | 5 3 4 | 4 **************************************************************************** */ it('should insert a node and remove the node that was previously there', () => { const items: Array<TestDagModel> = [ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 1, name: 'Step 2', parentIds: [1], stepId: 2 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [2], stepId: 4 }, ]; service.setNextNumber(5); service.setNewItemsArrayAsDagModel(items); const updated = service.insertNodeAndRemoveOld(2, { branchPath: null, name: 'Step 5', parentIds: [], stepId: null, }); expect(updated).toStrictEqual([ { branchPath: 1, name: 'Step 1', parentIds: [0], stepId: 1 }, { branchPath: 2, name: 'Step 3', parentIds: [1], stepId: 3 }, { branchPath: 1, name: 'Step 4', parentIds: [5], stepId: 4 }, { branchPath: 1, name: 'Step 5', parentIds: [1], stepId: 5 }, ]); }); });
the_stack
import * as pc from 'playcanvas'; // @ts-ignore: No extras declarations import * as pcx from 'playcanvas/build/playcanvas-extras.js'; import DebugLines from './debug'; // @ts-ignore: library file import import * as MeshoptDecoder from 'lib/meshopt_decoder.js'; import { getAssetPath } from './helpers'; import { Morph, URL, Entry, Observer, HierarchyNode } from './types'; class Viewer { app: pc.Application; prevCameraMat: pc.Mat4; camera: pc.Entity; cameraFocusBBox: pc.BoundingBox | null; cameraPosition: pc.Vec3 | null; light: pc.Entity; sceneRoot: pc.Entity; debugRoot: pc.Entity; entities: Array<pc.Entity>; assets: Array<pc.Asset>; meshInstances: Array<pc.MeshInstance>; // TODO replace with Array<pc.AnimTrack> when definition is available in pc animTracks: Array<any>; animationMap: Record<string, string>; morphs: Array<Morph>; firstFrame: boolean; skyboxLoaded: boolean; animSpeed: number; animTransition: number; animLoops: number; showWireframe: boolean; showBounds: boolean; showSkeleton: boolean; normalLength: number; skyboxMip: number; dirtyWireframe: boolean; dirtyBounds: boolean; dirtySkeleton: boolean; dirtyNormals: boolean; debugBounds: DebugLines; debugSkeleton: DebugLines; debugNormals: DebugLines; miniStats: any; observer: Observer; constructor(canvas: any, observer: Observer) { // create the application const app = new pc.Application(canvas, { mouse: new pc.Mouse(canvas), touch: new pc.TouchDevice(canvas), graphicsDeviceOptions: { alpha: false } }); this.app = app; app.graphicsDevice.maxPixelRatio = window.devicePixelRatio; // Set the canvas to fill the window and automatically change resolution to be the same as the canvas size const canvasSize = this.getCanvasSize(); app.setCanvasFillMode(pc.FILLMODE_NONE, canvasSize.width, canvasSize.height); app.setCanvasResolution(pc.RESOLUTION_AUTO); window.addEventListener("resize", function () { this.resizeCanvas(); }.bind(this)); // create the orbit camera const camera = new pc.Entity("Camera"); camera.addComponent("camera", { fov: 75, clearColor: new pc.Color(0.4, 0.45, 0.5), frustumCulling: true }); // load orbit script app.assets.loadFromUrl( getAssetPath("scripts/orbit-camera.js"), "script", function () { // setup orbit script component camera.addComponent("script"); camera.script.create("orbitCamera", { attributes: { inertiaFactor: 0.1 } }); camera.script.create("orbitCameraInputMouse"); camera.script.create("orbitCameraInputTouch"); app.root.addChild(camera); }); // create the light const light = new pc.Entity(); light.addComponent("light", { type: "directional", color: new pc.Color(1, 1, 1), castShadows: true, intensity: 1, shadowBias: 0.2, shadowDistance: 5, normalOffsetBias: 0.05, shadowResolution: 2048 }); light.setLocalEulerAngles(45, 30, 0); app.root.addChild(light); // disable autorender app.autoRender = false; this.prevCameraMat = new pc.Mat4(); app.on('update', this.update.bind(this)); // configure drag and drop const preventDefault = function (ev: { preventDefault: () => void }) { ev.preventDefault(); }; window.addEventListener('dragenter', preventDefault, false); window.addEventListener('dragover', preventDefault, false); window.addEventListener('drop', this.dropHandler.bind(this), false); app.on('prerender', this.onPrerender, this); app.on('frameend', this.onFrameend, this); // create the scene and debug root nodes const sceneRoot = new pc.Entity("sceneRoot", app); app.root.addChild(sceneRoot); const debugRoot = new pc.Entity("debugRoot", app); app.root.addChild(debugRoot); // store app things this.camera = camera; this.cameraFocusBBox = null; this.cameraPosition = null; this.light = light; this.sceneRoot = sceneRoot; this.debugRoot = debugRoot; this.entities = []; this.assets = []; this.meshInstances = []; this.animTracks = []; this.animationMap = { }; this.morphs = []; this.firstFrame = false; this.skyboxLoaded = false; this.animSpeed = observer.get('animation.speed'); this.animTransition = observer.get('animation.transition'); this.animLoops = observer.get('animation.loops'); this.showWireframe = observer.get('show.wireframe'); this.showBounds = observer.get('show.bounds'); this.showSkeleton = observer.get('show.skeleton'); this.normalLength = observer.get('show.normals'); this.skyboxMip = observer.get('lighting.skybox.mip'); this.setTonemapping(observer.get('lighting.tonemapping')); this.dirtyWireframe = false; this.dirtyBounds = false; this.dirtySkeleton = false; this.dirtyNormals = false; this.debugBounds = new DebugLines(app, camera); this.debugSkeleton = new DebugLines(app, camera); this.debugNormals = new DebugLines(app, camera); // construct ministats, default off this.miniStats = new pcx.MiniStats(app); this.miniStats.enabled = observer.get('show.stats'); this.observer = observer; // initialize control events this.bindControlEvents(); // start the application app.start(); // extract query params. taken from https://stackoverflow.com/a/21152762 const urlParams: any = {}; if (location.search) { location.search.substr(1).split("&").forEach(function (item) { const s = item.split("="), k = s[0], v = s[1] && decodeURIComponent(s[1]); (urlParams[k] = urlParams[k] || []).push(v); }); } // handle load url param const loadUrls = (urlParams.load || []).concat(urlParams.assetUrl || []); if (loadUrls.length > 0) { this.load( loadUrls.map((url: string) => { return { url, filename: url }; }) ); } // load the default skybox if one wasn't specified in url params if (!this.skyboxLoaded) { // this.loadHeliSkybox(); const skybox = observer.get('lighting.skybox.value') || observer.get('lighting.skybox.default'); this.load([{ url: skybox, filename: skybox }]); } // set camera position if (urlParams.hasOwnProperty('cameraPosition')) { const pos = urlParams.cameraPosition[0].split(',').map(Number); if (pos.length === 3) { this.cameraPosition = new pc.Vec3(pos); } } } // collects all mesh instances from entity hierarchy private collectMeshInstances(entity: pc.Entity) { const meshInstances: Array<pc.MeshInstance> = []; if (entity) { const components = entity.findComponents("render"); for (let i = 0; i < components.length; i++) { const render = components[i] as pc.RenderComponent; if (render.meshInstances) { for (let m = 0; m < render.meshInstances.length; m++) { const meshInstance = render.meshInstances[m]; meshInstances.push(meshInstance); } } } } return meshInstances; } private updateMeshInstanceList() { this.meshInstances = []; for (let e = 0; e < this.entities.length; e++) { const meshInstances = this.collectMeshInstances(this.entities[e]); this.meshInstances = this.meshInstances.concat(meshInstances); } } // calculate the bounding box of the given mesh private static calcMeshBoundingBox(meshInstances: Array<pc.MeshInstance>) { const bbox = new pc.BoundingBox(); for (let i = 0; i < meshInstances.length; ++i) { if (i === 0) { bbox.copy(meshInstances[i].aabb); } else { bbox.add(meshInstances[i].aabb); } } return bbox; } // calculate the bounding box of the graph-node hierarchy private static calcHierBoundingBox(rootNode: pc.Entity) { const position = rootNode.getPosition(); let min_x = position.x; let min_y = position.y; let min_z = position.z; let max_x = position.x; let max_y = position.y; let max_z = position.z; const recurse = function (node: pc.GraphNode) { const p = node.getPosition(); if (p.x < min_x) min_x = p.x; else if (p.x > max_x) max_x = p.x; if (p.y < min_y) min_y = p.y; else if (p.y > max_y) max_y = p.y; if (p.z < min_z) min_z = p.z; else if (p.z > max_z) max_z = p.z; for (let i = 0; i < node.children.length; ++i) { recurse(node.children[i]); } }; recurse(rootNode); const result = new pc.BoundingBox(); result.setMinMax(new pc.Vec3(min_x, min_y, min_z), new pc.Vec3(max_x, max_y, max_z)); return result; } // calculate the intersection of the two bounding boxes private static calcBoundingBoxIntersection = function (bbox1: pc.BoundingBox, bbox2: pc.BoundingBox) { // bounds don't intersect if (!bbox1.intersects(bbox2)) { return null; } const min1 = bbox1.getMin(); const max1 = bbox1.getMax(); const min2 = bbox2.getMin(); const max2 = bbox2.getMax(); const result = new pc.BoundingBox(); result.setMinMax(new pc.Vec3(Math.max(min1.x, min2.x), Math.max(min1.y, min2.y), Math.max(min1.z, min2.z)), new pc.Vec3(Math.min(max1.x, max2.x), Math.min(max1.y, max2.y), Math.min(max1.z, max2.z))); return result; } // construct the controls interface and initialize controls private bindControlEvents() { const controlEvents:any = { 'show.stats': this.setStats.bind(this), 'show.wireframe': this.setShowWireframe.bind(this), 'show.bounds': this.setShowBounds.bind(this), 'show.skeleton': this.setShowSkeleton.bind(this), 'show.normals': this.setNormalLength.bind(this), 'show.fov': this.setFov.bind(this), 'lighting.shadow': this.setDirectShadow.bind(this), 'lighting.direct': this.setDirectLighting.bind(this), 'lighting.env': this.setEnvLighting.bind(this), 'lighting.tonemapping': this.setTonemapping.bind(this), 'lighting.skybox.mip': this.setSkyboxMip.bind(this), 'lighting.skybox.value': (value: string) => { if (value) { this.load([{ url: value, filename: value }]); } else { this.clearSkybox(); } }, 'lighting.rotation': this.setLightingRotation.bind(this), 'animation.playing': (playing: boolean) => { if (playing) { this.play(); } else { this.stop(); } }, 'animation.selectedTrack': this.play.bind(this), 'animation.speed': this.setSpeed.bind(this), 'animation.transition': this.setTransition.bind(this), 'animation.loops': this.setLoops.bind(this), 'animation.progress': this.setAnimationProgress.bind(this), 'model.selectedNode.path': this.setSelectedNode.bind(this) }; // register control events Object.keys(controlEvents).forEach((e) => { this.observer.on(`${e}:set`, controlEvents[e]); this.observer.set(e, this.observer.get(e), false, false, true); }); this.observer.on('canvasResized', () => { this.resizeCanvas(); }); } // initialize the faces and prefiltered lighting data from the given // skybox texture, which is either a cubemap or equirect texture. private initSkyboxFromTexture(skybox: pc.Texture) { const app = this.app; const device = app.graphicsDevice; const cubemaps = []; const reprojectToCubemap = function (src: pc.Texture, size: number) { // generate faces cubemap const faces = new pc.Texture(device, { name: 'skyboxFaces', cubemap: true, width: size, height: size, type: pc.TEXTURETYPE_RGBM.toString(), addressU: pc.ADDRESS_CLAMP_TO_EDGE, addressV: pc.ADDRESS_CLAMP_TO_EDGE, fixCubemapSeams: false, mipmaps: false }); pc.reprojectTexture(src, faces); return faces; }; if (skybox.cubemap) { // @ts-ignore TODO type property missing from pc.Texture if (skybox.type === pc.TEXTURETYPE_DEFAULT || skybox.type === pc.TEXTURETYPE_RGBM) { // cubemap format is acceptible, use it directly cubemaps.push(skybox); } else { // cubemap must be rgbm or default to be used on the skybox cubemaps.push(reprojectToCubemap(skybox, skybox.width)); } } else { // @ts-ignore TODO type property missing from pc.Texture skybox.projection = pc.TEXTUREPROJECTION_EQUIRECT; // reproject equirect to cubemap for skybox cubemaps.push(reprojectToCubemap(skybox, skybox.width / 4)); } // generate prefiltered lighting data const sizes = [128, 64, 32, 16, 8, 4]; const specPower = [undefined, 512, 128, 32, 8, 2]; for (let i = 0; i < sizes.length; ++i) { const prefilter = new pc.Texture(device, { cubemap: true, name: 'skyboxPrefilter' + i, width: sizes[i], height: sizes[i], // @ts-ignore TODO type property missing from pc.Texture type: pc.TEXTURETYPE_RGBM, addressU: pc.ADDRESS_CLAMP_TO_EDGE, addressV: pc.ADDRESS_CLAMP_TO_EDGE, fixCubemapSeams: true, mipmaps: false }); // @ts-ignore pc.reprojectTexture(device, cubemaps[1] || skybox, prefilter, specPower[i], 4096); cubemaps.push(prefilter); } // assign the textures to the scene app.scene.gammaCorrection = pc.GAMMA_SRGB; app.scene.skyboxMip = this.skyboxMip; // Set the skybox to the 128x128 cubemap mipmap level app.scene.setSkybox(cubemaps); app.renderNextFrame = true; // ensure we render again when the cubemap arrives } // load the image files into the skybox. this function supports loading a single equirectangular // skybox image or 6 cubemap faces. private loadSkybox(files: Array<URL>) { const app = this.app; if (files.length !== 6) { // load equirectangular skybox const textureAsset = new pc.Asset('skybox_equi', 'texture', { url: files[0].url, filename: files[0].filename }); textureAsset.ready(() => { const texture = textureAsset.resource; if (texture.type === pc.TEXTURETYPE_DEFAULT && texture.format === pc.PIXELFORMAT_R8_G8_B8_A8) { // assume RGBA data (pngs) are RGBM texture.type = pc.TEXTURETYPE_RGBM; } this.initSkyboxFromTexture(texture); }); app.assets.add(textureAsset); app.assets.load(textureAsset); } else { // sort files into the correct order based on filename const names = [ ['posx', 'negx', 'posy', 'negy', 'posz', 'negz'], ['px', 'nx', 'py', 'ny', 'pz', 'nz'], ['right', 'left', 'up', 'down', 'front', 'back'], ['right', 'left', 'top', 'bottom', 'forward', 'backward'], ['0', '1', '2', '3', '4', '5'] ]; const getOrder = function (filename: string) { const fn = filename.toLowerCase(); for (let i = 0; i < names.length; ++i) { const nameList = names[i]; for (let j = 0; j < nameList.length; ++j) { if (fn.indexOf(nameList[j] + '.') !== -1) { return j; } } } return 0; }; const sortPred = function (first: URL, second: URL) { const firstOrder = getOrder(first.filename); const secondOrder = getOrder(second.filename); return firstOrder < secondOrder ? -1 : (secondOrder < firstOrder ? 1 : 0); }; files.sort(sortPred); // construct an asset for each cubemap face const faceAssets = files.map(function (file, index) { const faceAsset = new pc.Asset('skybox_face' + index, 'texture', file); app.assets.add(faceAsset); app.assets.load(faceAsset); return faceAsset; }); // construct the cubemap asset const cubemapAsset = new pc.Asset('skybox_cubemap', 'cubemap', null, { textures: faceAssets.map(function (faceAsset) { return faceAsset.id; }) }); // @ts-ignore TODO not defined in pc cubemapAsset.loadFaces = true; cubemapAsset.on('load', function () { this.initSkyboxFromTexture(cubemapAsset.resource); }.bind(this)); app.assets.add(cubemapAsset); app.assets.load(cubemapAsset); } this.skyboxLoaded = true; } // load the built in helipad cubemap private loadHeliSkybox() { const app = this.app; const cubemap = new pc.Asset('helipad', 'cubemap', { url: getAssetPath("cubemaps/Helipad.dds") }, { magFilter: pc.FILTER_LINEAR, minFilter: pc.FILTER_LINEAR_MIPMAP_LINEAR, anisotropy: 1, type: pc.TEXTURETYPE_RGBM }); cubemap.on('load', function () { app.scene.gammaCorrection = pc.GAMMA_SRGB; app.scene.skyboxMip = this.skyboxMip; // Set the skybox to the 128x128 cubemap mipmap level app.scene.setSkybox(cubemap.resources); app.renderNextFrame = true; // ensure we render again when the cubemap arrives }.bind(this)); app.assets.add(cubemap); app.assets.load(cubemap); this.skyboxLoaded = true; } private getCanvasSize() { return { width: document.body.clientWidth - document.getElementById("panel").offsetWidth, height: document.body.clientHeight }; } resizeCanvas() { const canvasSize = this.getCanvasSize(); this.app.resizeCanvas(canvasSize.width, canvasSize.height); this.app.renderNextFrame = true; } // reset the viewer, unloading resources resetScene() { const app = this.app; for (let i = 0; i < this.entities.length; ++i) { const entity = this.entities[i]; this.sceneRoot.removeChild(entity); entity.destroy(); } this.entities = []; for (let i = 0; i < this.assets.length; ++i) { const asset = this.assets[i]; app.assets.remove(asset); asset.unload(); } this.assets = []; this.meshInstances = []; // reset animation state this.animTracks = []; this.animationMap = { }; this.observer.set('animations.list', '[]'); this.morphs = []; this.observer.set('morphTargets', null); this.dirtyWireframe = this.dirtyBounds = this.dirtySkeleton = this.dirtyNormals = true; this.app.renderNextFrame = true; } clearSkybox() { this.app.scene.setSkybox(null); this.app.renderNextFrame = true; this.skyboxLoaded = false; } // move the camera to view the loaded object focusCamera() { const camera = this.camera.camera; const bbox = this.meshInstances.length ? Viewer.calcMeshBoundingBox(this.meshInstances) : Viewer.calcHierBoundingBox(this.sceneRoot); if (this.cameraFocusBBox) { const intersection = Viewer.calcBoundingBoxIntersection(this.cameraFocusBBox, bbox); if (intersection) { const len1 = bbox.halfExtents.length(); const len2 = this.cameraFocusBBox.halfExtents.length(); const len3 = intersection.halfExtents.length(); if ((Math.abs(len3 - len1) / len1 < 0.1) && (Math.abs(len3 - len2) / len2 < 0.1)) { return; } } } // @ts-ignore TODO not defined in pc const orbitCamera = this.camera.script.orbitCamera; // calculate scene bounding box const radius = bbox.halfExtents.length(); const distance = (radius * 1.4) / Math.sin(0.5 * camera.fov * camera.aspectRatio * pc.math.DEG_TO_RAD); if (this.cameraPosition) { orbitCamera.resetAndLookAtPoint(this.cameraPosition, bbox.center); this.cameraPosition = null; } else { orbitCamera.pivotPoint = bbox.center; orbitCamera.distance = distance; } camera.nearClip = distance / 10; camera.farClip = distance * 10; const light = this.light; light.light.shadowDistance = distance * 2; this.cameraFocusBBox = bbox; } // load gltf model given its url and list of external urls private loadGltf(gltfUrl: URL, externalUrls: Array<URL>) { // provide buffer view callback so we can handle meshoptimizer'd models // https://github.com/zeux/meshoptimizer const processBufferView = function (gltfBuffer: any, buffers: Array<any>, continuation: (err: string, result: any) => void) { if (gltfBuffer.extensions && gltfBuffer.extensions.EXT_meshopt_compression) { const extensionDef = gltfBuffer.extensions.EXT_meshopt_compression; const decoder = MeshoptDecoder; decoder.ready.then(function () { const byteOffset = extensionDef.byteOffset || 0; const byteLength = extensionDef.byteLength || 0; const count = extensionDef.count; const stride = extensionDef.byteStride; const result = new Uint8Array(count * stride); const source = new Uint8Array(buffers[extensionDef.buffer].buffer, buffers[extensionDef.buffer].byteOffset + byteOffset, byteLength); decoder.decodeGltfBuffer(result, count, stride, source, extensionDef.mode, extensionDef.filter); continuation(null, result); }); } else { continuation(null, null); } }; const processImage = function (gltfImage: any, continuation: (err: string, result: any) => void) { const u: URL = externalUrls.find(function (url) { return url.filename === pc.path.normalize(gltfImage.uri || ""); }); if (u) { const textureAsset = new pc.Asset(u.filename, 'texture', { url: u.url, filename: u.filename }); textureAsset.on('load', function () { continuation(null, textureAsset); }); this.app.assets.add(textureAsset); this.app.assets.load(textureAsset); } else { continuation(null, null); } }; const processBuffer = function (gltfBuffer: any, continuation: (err: string, result: any) => void) { const u = externalUrls.find(function (url) { return url.filename === pc.path.normalize(gltfBuffer.uri || ""); }); if (u) { const bufferAsset = new pc.Asset(u.filename, 'binary', { url: u.url, filename: u.filename }); bufferAsset.on('load', function () { continuation(null, new Uint8Array(bufferAsset.resource)); }); this.app.assets.add(bufferAsset); this.app.assets.load(bufferAsset); } else { continuation(null, null); } }; const containerAsset = new pc.Asset(gltfUrl.filename, 'container', gltfUrl, null, { // @ts-ignore TODO no definition in pc bufferView: { processAsync: processBufferView.bind(this) }, image: { processAsync: processImage.bind(this) }, buffer: { processAsync: processBuffer.bind(this) } }); containerAsset.on('load', () => { this.onLoaded(null, containerAsset); }); containerAsset.on('error', (err : string) => { this.onLoaded(err, containerAsset); }); this.observer.set('spinner', true); this.observer.set('error', null); this.clearCta(); this.app.assets.add(containerAsset); this.app.assets.load(containerAsset); } // load the list of urls. // urls can reference glTF files, glb files and skybox textures. // returns true if a model was loaded. load(urls: Array<URL>) { // convert single url to list if (!Array.isArray(urls)) { urls = [urls]; } // step through urls loading gltf/glb models let result = false; urls.forEach((url) => { const filenameExt = pc.path.getExtension(url.filename).toLowerCase(); if (filenameExt === '.gltf' || filenameExt === '.glb') { this.loadGltf(url, urls); result = true; } }); if (!result) { // if no models were loaded, load the files as skydome images instead this.loadSkybox(urls); } // return true if a model/scene was loaded and false otherwise return result; } // play an animation / play all the animations play() { let a: string; const animationName: string = this.observer.get('animation.selectedTrack'); if (animationName !== 'ALL_TRACKS') { a = this.animationMap[animationName]; } this.entities.forEach(function (e) { // @ts-ignore const anim = e.anim; if (anim) { anim.setBoolean('loop', !!a); anim.findAnimationLayer('all_layer').play(a || 'START'); anim.playing = true; } }); } // stop playing animations stop() { this.entities.forEach(function (e) { // @ts-ignore const anim = e.anim; if (anim) { anim.findAnimationLayer('all_layer').pause(); } }); } // set the animation speed setSpeed(speed: number) { this.animSpeed = speed; this.entities.forEach(function (e) { // @ts-ignore const anim = e.anim; if (anim) { anim.speed = speed; } }); } setTransition(transition: number) { this.animTransition = transition; // it's not possible to change the transition time afer creation, // so rebuilt the animation graph with the new transition if (this.animTracks.length > 0) { this.rebuildAnimTracks(); } } setLoops(loops: number) { this.animLoops = loops; // it's not possible to change the transition time afer creation, // so rebuilt the animation graph with the new transition if (this.animTracks.length > 0) { this.rebuildAnimTracks(); } } setAnimationProgress(progress: number) { this.observer.set('animation.playing', false); this.entities.forEach((e) => { // @ts-ignore const anim = e.anim; anim.playing = true; anim.baseLayer.activeStateCurrentTime = anim.baseLayer.activeStateDuration * progress; // @ts-ignore anim.system.onAnimationUpdate(0); anim.playing = false; anim.baseLayer.play(); }); } setSelectedNode(path: string) { const graphNode = this.app.root.findByPath(path); if (graphNode) { this.observer.set('model.selectedNode', { name: graphNode.name, path: path, // @ts-ignore position: graphNode.localPosition.toString(), // @ts-ignore rotation: graphNode.localRotation.toString(), // @ts-ignore scale: graphNode.localScale.toString() }); } } setStats(show: boolean) { this.miniStats.enabled = show; this.renderNextFrame(); } setShowWireframe(show: boolean) { this.showWireframe = show; this.dirtyWireframe = true; this.renderNextFrame(); } setShowBounds(show: boolean) { this.showBounds = show; this.dirtyBounds = true; this.renderNextFrame(); } setShowSkeleton(show: boolean) { this.showSkeleton = show; this.dirtySkeleton = true; this.renderNextFrame(); } setNormalLength(length: number) { this.normalLength = length; this.dirtyNormals = true; this.renderNextFrame(); } setFov(fov: number) { this.camera.camera.fov = fov; this.renderNextFrame(); } setDirectLighting(factor: number) { this.light.light.intensity = factor; this.renderNextFrame(); } setDirectShadow(enable: boolean) { this.light.light.castShadows = enable; this.renderNextFrame(); } setLightingRotation(factor: number) { // update skybox const rot = new pc.Quat(); rot.setFromEulerAngles(0, factor, 0); this.app.scene.skyboxRotation = rot; // update directional light this.light.setLocalEulerAngles(45, 30 + factor, 0); this.renderNextFrame(); } setEnvLighting(factor: number) { this.app.scene.skyboxIntensity = factor; this.renderNextFrame(); } setTonemapping(tonemapping: string) { const mapping = { Linear: pc.TONEMAP_LINEAR, Filmic: pc.TONEMAP_FILMIC, Hejl: pc.TONEMAP_HEJL, ACES: pc.TONEMAP_ACES }; // @ts-ignore this.app.scene.toneMapping = mapping.hasOwnProperty(tonemapping) ? mapping[tonemapping] : pc.TONEMAP_ACES; this.renderNextFrame(); } setSkyboxMip(mip: number) { this.skyboxMip = mip; this.app.scene.skyboxMip = mip; this.renderNextFrame(); } update() { // if the camera has moved since the last render const cameraWorldTransform = this.camera.getWorldTransform(); if (!this.prevCameraMat.equals(cameraWorldTransform)) { this.prevCameraMat.copy(cameraWorldTransform); this.renderNextFrame(); } // or an animation is loaded and we're animating let isAnimationPlaying = false; for (let i = 0; i < this.entities.length; ++i) { // @ts-ignore const anim = this.entities[i].anim; if (anim && anim.findAnimationLayer('all_layer').playing) { isAnimationPlaying = true; break; } } if (isAnimationPlaying) { this.dirtyBounds = true; this.dirtySkeleton = true; this.dirtyNormals = true; this.renderNextFrame(); this.observer.emit('animationUpdate'); } // or the ministats is enabled if (this.miniStats.enabled) { this.renderNextFrame(); } } renderNextFrame() { this.app.renderNextFrame = true; } // use webkitGetAsEntry to extract files so we can include folders private dropHandler(event: DragEvent) { const removeCommonPrefix = function (urls: Array<URL>) { const split = function (pathname: string) { const parts = pathname.split(pc.path.delimiter); const base = parts[0]; const rest = parts.slice(1).join(pc.path.delimiter); return [base, rest]; }; while (true) { const parts = split(urls[0].filename); if (parts[1].length === 0) { return; } for (let i = 1; i < urls.length; ++i) { const other = split(urls[i].filename); if (parts[0] !== other[0]) { return; } } for (let i = 0; i < urls.length; ++i) { urls[i].filename = split(urls[i].filename)[1]; } } }; const resolveFiles = (entries: Array<Entry>) => { const urls: Array<URL> = []; entries.forEach((entry: Entry) => { entry.file((file: URL) => { urls.push({ url: URL.createObjectURL(file), filename: entry.fullPath.substring(1) }); if (urls.length === entries.length) { // remove common prefix from files in order to support dragging in the // root of a folder containing related assets if (urls.length > 1) { removeCommonPrefix(urls); } // if a scene was loaded (and not just a skybox), clear the current scene if (this.load(urls) && !event.shiftKey) { this.resetScene(); } } }); }); }; const resolveDirectories = function (entries: Array<Entry>) { let awaiting = 0; const files: Array<Entry> = []; const recurse = function (entries: Array<Entry>) { entries.forEach(function (entry: Entry) { if (entry.isFile) { files.push(entry); } else if (entry.isDirectory) { awaiting++; entry.createReader().readEntries(function (subEntries: Array<Entry>) { awaiting--; recurse(subEntries); }); } }); if (awaiting === 0) { resolveFiles(files); } }; recurse(entries); }; // first things first event.preventDefault(); const items = event.dataTransfer.items; if (!items) { return; } const entries = []; for (let i = 0; i < items.length; ++i) { entries.push(items[i].webkitGetAsEntry()); } resolveDirectories(entries); } clearCta() { document.querySelector('#panel').classList.add('no-cta'); document.querySelector('#application-canvas').classList.add('no-cta'); document.querySelector('.load-button-panel').classList.add('hide'); } // container asset has been loaded, add it to the scene private onLoaded(err: string, asset: pc.Asset) { this.observer.set('spinner', false); if (err) { this.observer.set('error', err); return; } const resource = asset.resource; const meshesLoaded = resource.renders && resource.renders.length > 0; const animLoaded = resource.animations && resource.animations.length > 0; const prevEntity : pc.Entity = this.entities.length === 0 ? null : this.entities[this.entities.length - 1]; let entity: pc.Entity; if (prevEntity) { // check if this loaded resource can be added to the existing entity, // for example loading an animation onto an existing model (or visa versa) const preEntityRenders = !!prevEntity.findComponent("render"); if ((meshesLoaded && !preEntityRenders) || (animLoaded && !meshesLoaded)) { entity = prevEntity; } } let meshCount = 0; let vertexCount = 0; let primitiveCount = 0; if (!entity) { // create entity entity = asset.resource.instantiateRenderEntity(); // update mesh stats resource.renders.forEach((renderAsset : pc.Asset) => { renderAsset.resource.meshes.forEach((mesh : pc.Mesh) => { meshCount++; vertexCount += mesh.vertexBuffer.getNumVertices(); primitiveCount += mesh.primitive[0].count; }); }); this.entities.push(entity); this.sceneRoot.addChild(entity); } const mapChildren = function (node: pc.GraphNode): Array<HierarchyNode> { return node.children.map((child: pc.GraphNode) => ({ name: child.name, path: child.path, children: mapChildren(child) })); }; const graph: Array<HierarchyNode> = [{ name: entity.name, path: entity.path, children: mapChildren(entity) }]; // hierarchy this.observer.set('model.nodes', JSON.stringify(graph)); // mesh stats this.observer.set('model.meshCount', meshCount); this.observer.set('model.vertexCount', vertexCount); this.observer.set('model.primitiveCount', primitiveCount); // create animation component if (animLoaded) { // create the anim component if there isn't one already // @ts-ignore TODO not defined in pc if (!entity.anim) { entity.addComponent('anim', { activate: true, speed: this.animSpeed }); } // append anim tracks to global list resource.animations.forEach(function (a : any) { this.animTracks.push(a.resource); }.bind(this)); } // rebuild the anim state graph if (this.animTracks.length > 0) { this.rebuildAnimTracks(); } // get all morph targets const morphInstances: Array<pc.MorphInstance> = []; const meshInstances = this.collectMeshInstances(entity); for (let i = 0; i < meshInstances.length; i++) { // @ts-ignore TODO morphInstance is not public if (meshInstances[i].morphInstance) { // @ts-ignore TODO morphInstance is not public morphInstances.push(meshInstances[i].morphInstance); } } // initialize morph targets if (morphInstances.length > 0) { // make a list of all the morph instance target names const morphs: Array<Morph> = this.morphs; morphInstances.forEach((morphInstance: any, morphIndex: number) => { // @ts-ignore TODO expose meshInstance on morphInstance in pc const meshInstance = morphInstance.meshInstance; // mesh name line morphs.push(<Morph> { name: (meshInstance && meshInstance.node && meshInstance.node.name) || "Mesh " + morphIndex }); // morph targets // @ts-ignore TODO accessing private const morphInstance.morph._targets.forEach((target, targetIndex) => { morphs.push({ name: target.name, targetIndex: targetIndex }); }); }); const morphTargets: Record<number, { name: string, morphs: Record<number, Morph> }> = {}; let panelCount = 0; let morphCount = 0; morphs.forEach((morph: Morph) => { if (!morph.hasOwnProperty('targetIndex')) { morphTargets[panelCount] = { name: morph.name, morphs: {} }; panelCount++; morphCount = 0; } else { morphTargets[panelCount - 1].morphs[morphCount] = { // prepend morph index to morph target diplay name name: (morph.name === `${morph.targetIndex}`) ? `${morph.name}.` : `${morph.targetIndex}. ${morph.name}`, targetIndex: morph.targetIndex }; const morphInstance = morphInstances[panelCount - 1]; this.observer.on(`morphTargets.${panelCount - 1}.morphs.${morphCount}.weight:set`, (weight: number) => { if (!morphInstance) return; morphInstance.setWeight(morph.targetIndex, weight); this.dirtyNormals = true; this.renderNextFrame(); }); morphCount++; } }); this.observer.set('morphTargets', morphTargets); this.observer.on('animationUpdate', () => { const morphTargets = this.observer.get('morphTargets'); morphInstances.forEach((morphInstance: any, i: number) => { if (morphTargets) Object.keys(morphTargets[i].morphs).forEach((morphKey) => { const newWeight = morphInstance.getWeight(Number(morphKey)); if (morphTargets[i].morphs[morphKey].weight !== newWeight) { this.observer.set(`morphTargets.${i}.morphs.${morphKey}.weight`, newWeight); } }); }); }); } // store the loaded asset this.assets.push(asset); // construct a list of meshInstances so we can quickly access them when configuring wireframe rendering etc. this.updateMeshInstanceList(); // if no meshes are loaded then enable skeleton rendering so user can see something if (this.meshInstances.length === 0) { this.observer.set('show.skeleton', true); } // dirty everything this.dirtyWireframe = this.dirtyBounds = this.dirtySkeleton = this.dirtyNormals = true; // we can't refocus the camera here because the scene hierarchy only gets updated // during render. we must instead set a flag, wait for a render to take place and // then focus the camera. this.firstFrame = true; this.renderNextFrame(); } // rebuild the animation state graph private rebuildAnimTracks() { const entity = this.entities[this.entities.length - 1]; // create states const states : Array<{ name: string, speed?: number }> = [{ name: 'START' }]; this.animTracks.forEach(function (t, i) { states.push({ name: 'track_' + i, speed: 1 }); }); // create a transition for each state const transition = this.animTransition; const loops = this.animLoops; const transitions = states.map(function (s, i) { return { from: s.name, to: states[(i + 1) % states.length || 1].name, time: s.name == 'START' ? 0.0 : transition, exitTime: s.name === 'START' ? 0.0 : loops, conditions: [{ parameterName: 'loop', predicate: "EQUAL_TO", value: false }], // @ts-ignore interruptionSource: pc.ANIM_INTERRUPTION_NEXT }; }); // create the state graph instance // @ts-ignore TODO anim property missing from pc.Entity entity.anim.loadStateGraph(new pc.AnimStateGraph({ layers: [{ name: 'all_layer', states: states, transitions: transitions }], parameters: { loop: { name: 'loop', // @ts-ignore type: pc.ANIM_PARAMETER_BOOLEAN, value: false } } })); // @ts-ignore TODO anim property missing from pc.Entity const allLayer = entity.anim.findAnimationLayer('all_layer'); this.animTracks.forEach(function (t: any, i: number) { const name = states[i + 1].name; allLayer.assignAnimation(name, t); this.animationMap[t.name] = name; }.bind(this)); // let the controls know about the new animations this.observer.set('animation.list', JSON.stringify(Object.keys(this.animationMap))); // immediately start playing the animation this.observer.set('animation.playing', true); } // generate and render debug elements on prerender private onPrerender() { if (!this.firstFrame) { // don't update on the first frame let meshInstance; // wireframe if (this.dirtyWireframe) { this.dirtyWireframe = false; for (let i = 0; i < this.meshInstances.length; ++i) { this.meshInstances[i].renderStyle = this.showWireframe ? pc.RENDERSTYLE_WIREFRAME : pc.RENDERSTYLE_SOLID; } } // debug bounds if (this.dirtyBounds) { this.dirtyBounds = false; this.debugBounds.clear(); if (this.showBounds) { const bbox = Viewer.calcMeshBoundingBox(this.meshInstances); this.debugBounds.box(bbox.getMin(), bbox.getMax()); } this.debugBounds.update(); } // debug normals if (this.dirtyNormals) { this.dirtyNormals = false; this.debugNormals.clear(); if (this.normalLength > 0) { for (let i = 0; i < this.meshInstances.length; ++i) { meshInstance = this.meshInstances[i]; // @ts-ignore TODO not defined in pc const vertexBuffer = meshInstance.morphInstance ? // @ts-ignore TODO not defined in pc meshInstance.morphInstance._vertexBuffer : meshInstance.mesh.vertexBuffer; if (vertexBuffer) { // @ts-ignore TODO not defined in pc const skinMatrices = meshInstance.skinInstance ? // @ts-ignore TODO not defined in pc meshInstance.skinInstance.matrices : null; // if there is skinning we need to manually update matrices here otherwise // our normals are always a frame behind if (skinMatrices) { // @ts-ignore TODO not defined in pc meshInstance.skinInstance.updateMatrices(meshInstance.node); } this.debugNormals.generateNormals(vertexBuffer, meshInstance.node.getWorldTransform(), this.normalLength, skinMatrices); } } } this.debugNormals.update(); } // debug skeleton if (this.dirtySkeleton) { this.dirtySkeleton = false; this.debugSkeleton.clear(); if (this.showSkeleton) { for (let i = 0; i < this.entities.length; ++i) { const entity = this.entities[i]; if (entity.findComponent("render")) { this.debugSkeleton.generateSkeleton(entity); } } } this.debugSkeleton.update(); } } } private onFrameend() { if (this.firstFrame) { this.firstFrame = false; // focus camera after first frame otherwise skinned model bounding // boxes are incorrect this.focusCamera(); this.renderNextFrame(); } } } export default Viewer;
the_stack
import { BoolPropertyDefinition } from "../../../PropertyDefinitions/BoolPropertyDefinition"; import { ByteArrayArray } from "../../../ComplexProperties/ByteArrayArray"; import { ByteArrayPropertyDefinition } from "../../../PropertyDefinitions/ByteArrayPropertyDefinition"; import { CompleteName } from "../../../ComplexProperties/CompleteName"; import { ComplexPropertyDefinition } from "../../../PropertyDefinitions/ComplexPropertyDefinition"; import { ContactSource } from "../../../Enumerations/ContactSource"; import { ContainedPropertyDefinition } from "../../../PropertyDefinitions/ContainedPropertyDefinition"; import { DateTimePropertyDefinition } from "../../../PropertyDefinitions/DateTimePropertyDefinition"; import { EmailAddress } from "../../../ComplexProperties/EmailAddress"; import { EmailAddressCollection } from "../../../ComplexProperties/EmailAddressCollection"; import { EmailAddressDictionary } from "../../../ComplexProperties/EmailAddressDictionary"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { FileAsMapping } from "../../../Enumerations/FileAsMapping"; import { GenericPropertyDefinition } from "../../../PropertyDefinitions/GenericPropertyDefinition"; import { ImAddressDictionary } from "../../../ComplexProperties/ImAddressDictionary"; import { IndexedPropertyDefinition } from "../../../PropertyDefinitions/IndexedPropertyDefinition"; import { PhoneNumberDictionary } from "../../../ComplexProperties/PhoneNumberDictionary"; import { PhysicalAddressDictionary } from "../../../ComplexProperties/PhysicalAddressDictionary"; import { PhysicalAddressIndex } from "../../../Enumerations/PhysicalAddressIndex"; import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition"; import { PropertyDefinitionFlags } from "../../../Enumerations/PropertyDefinitionFlags"; import { Schemas } from "./Schemas"; import { StringList } from "../../../ComplexProperties/StringList"; import { StringPropertyDefinition } from "../../../PropertyDefinitions/StringPropertyDefinition"; import { XmlElementNames } from "../../XmlElementNames"; import { ItemSchema } from "./ItemSchema"; /** * FieldURIs for contacts. */ module FieldUris { export var FileAs: string = "contacts:FileAs"; export var FileAsMapping: string = "contacts:FileAsMapping"; export var DisplayName: string = "contacts:DisplayName"; export var GivenName: string = "contacts:GivenName"; export var Initials: string = "contacts:Initials"; export var MiddleName: string = "contacts:MiddleName"; export var NickName: string = "contacts:Nickname"; export var CompleteName: string = "contacts:CompleteName"; export var CompanyName: string = "contacts:CompanyName"; export var EmailAddress: string = "contacts:EmailAddress"; export var EmailAddresses: string = "contacts:EmailAddresses"; export var PhysicalAddresses: string = "contacts:PhysicalAddresses"; export var PhoneNumber: string = "contacts:PhoneNumber"; export var PhoneNumbers: string = "contacts:PhoneNumbers"; export var AssistantName: string = "contacts:AssistantName"; export var Birthday: string = "contacts:Birthday"; export var BusinessHomePage: string = "contacts:BusinessHomePage"; export var Children: string = "contacts:Children"; export var Companies: string = "contacts:Companies"; export var ContactSource: string = "contacts:ContactSource"; export var Department: string = "contacts:Department"; export var Generation: string = "contacts:Generation"; export var ImAddress: string = "contacts:ImAddress"; export var ImAddresses: string = "contacts:ImAddresses"; export var JobTitle: string = "contacts:JobTitle"; export var Manager: string = "contacts:Manager"; export var Mileage: string = "contacts:Mileage"; export var OfficeLocation: string = "contacts:OfficeLocation"; export var PhysicalAddressCity: string = "contacts:PhysicalAddress:City"; export var PhysicalAddressCountryOrRegion: string = "contacts:PhysicalAddress:CountryOrRegion"; export var PhysicalAddressState: string = "contacts:PhysicalAddress:State"; export var PhysicalAddressStreet: string = "contacts:PhysicalAddress:Street"; export var PhysicalAddressPostalCode: string = "contacts:PhysicalAddress:PostalCode"; export var PostalAddressIndex: string = "contacts:PostalAddressIndex"; export var Profession: string = "contacts:Profession"; export var SpouseName: string = "contacts:SpouseName"; export var Surname: string = "contacts:Surname"; export var WeddingAnniversary: string = "contacts:WeddingAnniversary"; export var HasPicture: string = "contacts:HasPicture"; export var PhoneticFullName: string = "contacts:PhoneticFullName"; export var PhoneticFirstName: string = "contacts:PhoneticFirstName"; export var PhoneticLastName: string = "contacts:PhoneticLastName"; export var Alias: string = "contacts:Alias"; export var Notes: string = "contacts:Notes"; export var Photo: string = "contacts:Photo"; export var UserSMIMECertificate: string = "contacts:UserSMIMECertificate"; export var MSExchangeCertificate: string = "contacts:MSExchangeCertificate"; export var DirectoryId: string = "contacts:DirectoryId"; export var ManagerMailbox: string = "contacts:ManagerMailbox"; export var DirectReports: string = "contacts:DirectReports"; } /** * Represents the schem for contacts. */ export class ContactSchema extends ItemSchema { /** * Defines the **FileAs** property. */ public static FileAs: PropertyDefinition = new StringPropertyDefinition( "FileAs", XmlElementNames.FileAs, FieldUris.FileAs, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **FileAsMapping** property. */ public static FileAsMapping: PropertyDefinition = new GenericPropertyDefinition<FileAsMapping>( "FileAsMapping", XmlElementNames.FileAsMapping, FieldUris.FileAsMapping, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, FileAsMapping ); /** * Defines the **DisplayName** property. */ public static DisplayName: PropertyDefinition = new StringPropertyDefinition( "DisplayName", XmlElementNames.DisplayName, FieldUris.DisplayName, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **GivenName** property. */ public static GivenName: PropertyDefinition = new StringPropertyDefinition( "GivenName", XmlElementNames.GivenName, FieldUris.GivenName, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Initials** property. */ public static Initials: PropertyDefinition = new StringPropertyDefinition( "Initials", XmlElementNames.Initials, FieldUris.Initials, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **MiddleName** property. */ public static MiddleName: PropertyDefinition = new StringPropertyDefinition( "MiddleName", XmlElementNames.MiddleName, FieldUris.MiddleName, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **NickName** property. */ public static NickName: PropertyDefinition = new StringPropertyDefinition( "Nickname", XmlElementNames.NickName, FieldUris.NickName, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **CompleteName** property. */ public static CompleteName: PropertyDefinition = new ComplexPropertyDefinition<CompleteName>( "CompleteName", XmlElementNames.CompleteName, FieldUris.CompleteName, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new CompleteName(); } ); /** * Defines the **CompanyName** property. */ public static CompanyName: PropertyDefinition = new StringPropertyDefinition( "CompanyName", XmlElementNames.CompanyName, FieldUris.CompanyName, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **EmailAddresses** property. */ public static EmailAddresses: PropertyDefinition = new ComplexPropertyDefinition<EmailAddressDictionary>( "EmailAddresses", XmlElementNames.EmailAddresses, FieldUris.EmailAddresses, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddressDictionary(); } ); /** * Defines the **PhysicalAddresses** property. */ public static PhysicalAddresses: PropertyDefinition = new ComplexPropertyDefinition<PhysicalAddressDictionary>( "PhysicalAddresses", XmlElementNames.PhysicalAddresses, FieldUris.PhysicalAddresses, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate, ExchangeVersion.Exchange2007_SP1, () => { return new PhysicalAddressDictionary(); } ); /** * Defines the **PhoneNumbers** property. */ public static PhoneNumbers: PropertyDefinition = new ComplexPropertyDefinition<PhoneNumberDictionary>( "PhoneNumbers", XmlElementNames.PhoneNumbers, FieldUris.PhoneNumbers, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate, ExchangeVersion.Exchange2007_SP1, () => { return new PhoneNumberDictionary(); } ); /** * Defines the **AssistantName** property. */ public static AssistantName: PropertyDefinition = new StringPropertyDefinition( "AssistantName", XmlElementNames.AssistantName, FieldUris.AssistantName, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Birthday** property. */ public static Birthday: PropertyDefinition = new DateTimePropertyDefinition( "Birthday", XmlElementNames.Birthday, FieldUris.Birthday, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **BusinessHomePage** property. */ public static BusinessHomePage: PropertyDefinition = new StringPropertyDefinition( "BusinessHomePage", XmlElementNames.BusinessHomePage, FieldUris.BusinessHomePage, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Children** property. */ public static Children: PropertyDefinition = new ComplexPropertyDefinition<StringList>( "Children", XmlElementNames.Children, FieldUris.Children, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new StringList(); } ); /** * Defines the **Companies** property. */ public static Companies: PropertyDefinition = new ComplexPropertyDefinition<StringList>( "Companies", XmlElementNames.Companies, FieldUris.Companies, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new StringList(); } ); /** * Defines the **ContactSource** property. */ public static ContactSource: PropertyDefinition = new GenericPropertyDefinition<ContactSource>( "ContactSource", XmlElementNames.ContactSource, FieldUris.ContactSource, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, ContactSource ); /** * Defines the **Department** property. */ public static Department: PropertyDefinition = new StringPropertyDefinition( "Department", XmlElementNames.Department, FieldUris.Department, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Generation** property. */ public static Generation: PropertyDefinition = new StringPropertyDefinition( "Generation", XmlElementNames.Generation, FieldUris.Generation, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ImAddresses** property. */ public static ImAddresses: PropertyDefinition = new ComplexPropertyDefinition<ImAddressDictionary>( "ImAddresses", XmlElementNames.ImAddresses, FieldUris.ImAddresses, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate, ExchangeVersion.Exchange2007_SP1, () => { return new ImAddressDictionary(); } ); /** * Defines the **JobTitle** property. */ public static JobTitle: PropertyDefinition = new StringPropertyDefinition( "JobTitle", XmlElementNames.JobTitle, FieldUris.JobTitle, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Manager** property. */ public static Manager: PropertyDefinition = new StringPropertyDefinition( "Manager", XmlElementNames.Manager, FieldUris.Manager, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Mileage** property. */ public static Mileage: PropertyDefinition = new StringPropertyDefinition( "Mileage", XmlElementNames.Mileage, FieldUris.Mileage, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **OfficeLocation** property. */ public static OfficeLocation: PropertyDefinition = new StringPropertyDefinition( "OfficeLocation", XmlElementNames.OfficeLocation, FieldUris.OfficeLocation, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **PostalAddressIndex** property. */ public static PostalAddressIndex: PropertyDefinition = new GenericPropertyDefinition<PhysicalAddressIndex>( "PostalAddressIndex", XmlElementNames.PostalAddressIndex, FieldUris.PostalAddressIndex, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, PhysicalAddressIndex ); /** * Defines the **Profession** property. */ public static Profession: PropertyDefinition = new StringPropertyDefinition( "Profession", XmlElementNames.Profession, FieldUris.Profession, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **SpouseName** property. */ public static SpouseName: PropertyDefinition = new StringPropertyDefinition( "SpouseName", XmlElementNames.SpouseName, FieldUris.SpouseName, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Surname** property. */ public static Surname: PropertyDefinition = new StringPropertyDefinition( "Surname", XmlElementNames.Surname, FieldUris.Surname, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **WeddingAnniversary** property. */ public static WeddingAnniversary: PropertyDefinition = new DateTimePropertyDefinition( "WeddingAnniversary", XmlElementNames.WeddingAnniversary, FieldUris.WeddingAnniversary, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **HasPicture** property. */ public static HasPicture: PropertyDefinition = new BoolPropertyDefinition( "HasPicture", XmlElementNames.HasPicture, FieldUris.HasPicture, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010 ); /** * Defines the **PhoneticFullName** property. */ public static PhoneticFullName: PropertyDefinition = new StringPropertyDefinition( "PhoneticFullName", XmlElementNames.PhoneticFullName, FieldUris.PhoneticFullName, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1 ); /** * Defines the **PhoneticFirstName** property. */ public static PhoneticFirstName: PropertyDefinition = new StringPropertyDefinition( "PhoneticFirstName", XmlElementNames.PhoneticFirstName, FieldUris.PhoneticFirstName, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1 ); /** * Defines the **PhoneticLastName** property. */ public static PhoneticLastName: PropertyDefinition = new StringPropertyDefinition( "PhoneticLastName", XmlElementNames.PhoneticLastName, FieldUris.PhoneticLastName, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1 ); /** * Defines the **Alias** property. */ public static Alias: PropertyDefinition = new StringPropertyDefinition( "Alias", XmlElementNames.Alias, FieldUris.Alias, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1 ); /** * Defines the **Notes** property. */ public static Notes: PropertyDefinition = new StringPropertyDefinition( "Notes", XmlElementNames.Notes, FieldUris.Notes, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1 ); /** * Defines the **Photo** property. */ public static Photo: PropertyDefinition = new ByteArrayPropertyDefinition( "Photo", XmlElementNames.Photo, FieldUris.Photo, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1 ); /** * Defines the **UserSMIMECertificate** property. */ public static UserSMIMECertificate: PropertyDefinition = new ComplexPropertyDefinition<ByteArrayArray>( "UserSMIMECertificate", XmlElementNames.UserSMIMECertificate, FieldUris.UserSMIMECertificate, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1, () => { return new ByteArrayArray(); } ); /** * Defines the **MSExchangeCertificate** property. */ public static MSExchangeCertificate: PropertyDefinition = new ComplexPropertyDefinition<ByteArrayArray>( "MSExchangeCertificate", XmlElementNames.MSExchangeCertificate, FieldUris.MSExchangeCertificate, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1, () => { return new ByteArrayArray(); } ); /** * Defines the **DirectoryId** property. */ public static DirectoryId: PropertyDefinition = new StringPropertyDefinition( "DirectoryId", XmlElementNames.DirectoryId, FieldUris.DirectoryId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1 ); /** * Defines the **ManagerMailbox** property. */ public static ManagerMailbox: PropertyDefinition = new ContainedPropertyDefinition<EmailAddress>( "ManagerMailbox", XmlElementNames.ManagerMailbox, FieldUris.ManagerMailbox, XmlElementNames.Mailbox, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1, () => { return new EmailAddress(); } ); /** * Defines the **DirectReports** property. */ public static DirectReports: PropertyDefinition = new ComplexPropertyDefinition<EmailAddressCollection>( "DirectReports", XmlElementNames.DirectReports, FieldUris.DirectReports, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010_SP1, () => { return new EmailAddressCollection(); } ); /** * Defines the **EmailAddress1** property. */ public static EmailAddress1: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.EmailAddress, "EmailAddress1" ); /** * Defines the **EmailAddress2** property. */ public static EmailAddress2: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.EmailAddress, "EmailAddress2" ); /** * Defines the **EmailAddress3** property. */ public static EmailAddress3: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.EmailAddress, "EmailAddress3" ); /** * Defines the **ImAddress1** property. */ public static ImAddress1: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.ImAddress, "ImAddress1" ); /** * Defines the **ImAddress2** property. */ public static ImAddress2: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.ImAddress, "ImAddress2" ); /** * Defines the **ImAddress3** property. */ public static ImAddress3: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.ImAddress, "ImAddress3" ); /** * Defines the **AssistantPhone** property. */ public static AssistantPhone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "AssistantPhone" ); /** * Defines the **BusinessFax** property. */ public static BusinessFax: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "BusinessFax" ); /** * Defines the **BusinessPhone** property. */ public static BusinessPhone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "BusinessPhone" ); /** * Defines the **BusinessPhone2** property. */ public static BusinessPhone2: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "BusinessPhone2" ); /** * Defines the **Callback** property. */ public static Callback: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "Callback" ); /** * Defines the **CarPhone** property. */ public static CarPhone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "CarPhone" ); /** * Defines the **CompanyMainPhone** property. */ public static CompanyMainPhone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "CompanyMainPhone" ); /** * Defines the **HomeFax** property. */ public static HomeFax: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "HomeFax" ); /** * Defines the **HomePhone** property. */ public static HomePhone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "HomePhone" ); /** * Defines the **HomePhone2** property. */ public static HomePhone2: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "HomePhone2" ); /** * Defines the **Isdn** property. */ public static Isdn: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "Isdn" ); /** * Defines the **MobilePhone** property. */ public static MobilePhone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "MobilePhone" ); /** * Defines the **OtherFax** property. */ public static OtherFax: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "OtherFax" ); /** * Defines the **OtherTelephone** property. */ public static OtherTelephone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "OtherTelephone" ); /** * Defines the **Pager** property. */ public static Pager: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "Pager" ); /** * Defines the **PrimaryPhone** property. */ public static PrimaryPhone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "PrimaryPhone" ); /** * Defines the **RadioPhone** property. */ public static RadioPhone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "RadioPhone" ); /** * Defines the **Telex** property. */ public static Telex: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "Telex" ); /** * Defines the **TtyTddPhone** property. */ public static TtyTddPhone: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhoneNumber, "TtyTddPhone" ); /** * Defines the **BusinessAddressStreet** property. */ public static BusinessAddressStreet: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressStreet, "Business" ); /** * Defines the **BusinessAddressCity** property. */ public static BusinessAddressCity: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressCity, "Business" ); /** * Defines the **BusinessAddressState** property. */ public static BusinessAddressState: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressState, "Business" ); /** * Defines the **BusinessAddressCountryOrRegion** property. */ public static BusinessAddressCountryOrRegion: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressCountryOrRegion, "Business" ); /** * Defines the **BusinessAddressPostalCode** property. */ public static BusinessAddressPostalCode: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressPostalCode, "Business" ); /** * Defines the **HomeAddressStreet** property. */ public static HomeAddressStreet: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressStreet, "Home" ); /** * Defines the **HomeAddressCity** property. */ public static HomeAddressCity: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressCity, "Home" ); /** * Defines the **HomeAddressState** property. */ public static HomeAddressState: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressState, "Home" ); /** * Defines the **HomeAddressCountryOrRegion** property. */ public static HomeAddressCountryOrRegion: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressCountryOrRegion, "Home" ); /** * Defines the **HomeAddressPostalCode** property. */ public static HomeAddressPostalCode: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressPostalCode, "Home" ); /** * Defines the **OtherAddressStreet** property. */ public static OtherAddressStreet: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressStreet, "Other" ); /** * Defines the **OtherAddressCity** property. */ public static OtherAddressCity: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressCity, "Other" ); /** * Defines the **OtherAddressState** property. */ public static OtherAddressState: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressState, "Other" ); /** * Defines the **OtherAddressCountryOrRegion** property. */ public static OtherAddressCountryOrRegion: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressCountryOrRegion, "Other" ); /** * Defines the **OtherAddressPostalCode** property. */ public static OtherAddressPostalCode: IndexedPropertyDefinition = new IndexedPropertyDefinition( FieldUris.PhysicalAddressPostalCode, "Other" ); /** * @internal Instance of **ContactSchema** */ static Instance: ContactSchema = new ContactSchema(); /** * Registers properties. * * /remarks/ IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd) */ RegisterProperties(): void { super.RegisterProperties(); this.RegisterProperty(ContactSchema, ContactSchema.FileAs); this.RegisterProperty(ContactSchema, ContactSchema.FileAsMapping); this.RegisterProperty(ContactSchema, ContactSchema.DisplayName); this.RegisterProperty(ContactSchema, ContactSchema.GivenName); this.RegisterProperty(ContactSchema, ContactSchema.Initials); this.RegisterProperty(ContactSchema, ContactSchema.MiddleName); this.RegisterProperty(ContactSchema, ContactSchema.NickName); this.RegisterProperty(ContactSchema, ContactSchema.CompleteName); this.RegisterProperty(ContactSchema, ContactSchema.CompanyName); this.RegisterProperty(ContactSchema, ContactSchema.EmailAddresses); this.RegisterProperty(ContactSchema, ContactSchema.PhysicalAddresses); this.RegisterProperty(ContactSchema, ContactSchema.PhoneNumbers); this.RegisterProperty(ContactSchema, ContactSchema.AssistantName); this.RegisterProperty(ContactSchema, ContactSchema.Birthday); this.RegisterProperty(ContactSchema, ContactSchema.BusinessHomePage); this.RegisterProperty(ContactSchema, ContactSchema.Children); this.RegisterProperty(ContactSchema, ContactSchema.Companies); this.RegisterProperty(ContactSchema, ContactSchema.ContactSource); this.RegisterProperty(ContactSchema, ContactSchema.Department); this.RegisterProperty(ContactSchema, ContactSchema.Generation); this.RegisterProperty(ContactSchema, ContactSchema.ImAddresses); this.RegisterProperty(ContactSchema, ContactSchema.JobTitle); this.RegisterProperty(ContactSchema, ContactSchema.Manager); this.RegisterProperty(ContactSchema, ContactSchema.Mileage); this.RegisterProperty(ContactSchema, ContactSchema.OfficeLocation); this.RegisterProperty(ContactSchema, ContactSchema.PostalAddressIndex); this.RegisterProperty(ContactSchema, ContactSchema.Profession); this.RegisterProperty(ContactSchema, ContactSchema.SpouseName); this.RegisterProperty(ContactSchema, ContactSchema.Surname); this.RegisterProperty(ContactSchema, ContactSchema.WeddingAnniversary); this.RegisterProperty(ContactSchema, ContactSchema.HasPicture); this.RegisterProperty(ContactSchema, ContactSchema.PhoneticFullName); this.RegisterProperty(ContactSchema, ContactSchema.PhoneticFirstName); this.RegisterProperty(ContactSchema, ContactSchema.PhoneticLastName); this.RegisterProperty(ContactSchema, ContactSchema.Alias); this.RegisterProperty(ContactSchema, ContactSchema.Notes); this.RegisterProperty(ContactSchema, ContactSchema.Photo); this.RegisterProperty(ContactSchema, ContactSchema.UserSMIMECertificate); this.RegisterProperty(ContactSchema, ContactSchema.MSExchangeCertificate); this.RegisterProperty(ContactSchema, ContactSchema.DirectoryId); this.RegisterProperty(ContactSchema, ContactSchema.ManagerMailbox); this.RegisterProperty(ContactSchema, ContactSchema.DirectReports); this.RegisterIndexedProperty(ContactSchema.EmailAddress1); this.RegisterIndexedProperty(ContactSchema.EmailAddress2); this.RegisterIndexedProperty(ContactSchema.EmailAddress3); this.RegisterIndexedProperty(ContactSchema.ImAddress1); this.RegisterIndexedProperty(ContactSchema.ImAddress2); this.RegisterIndexedProperty(ContactSchema.ImAddress3); this.RegisterIndexedProperty(ContactSchema.AssistantPhone); this.RegisterIndexedProperty(ContactSchema.BusinessFax); this.RegisterIndexedProperty(ContactSchema.BusinessPhone); this.RegisterIndexedProperty(ContactSchema.BusinessPhone2); this.RegisterIndexedProperty(ContactSchema.Callback); this.RegisterIndexedProperty(ContactSchema.CarPhone); this.RegisterIndexedProperty(ContactSchema.CompanyMainPhone); this.RegisterIndexedProperty(ContactSchema.HomeFax); this.RegisterIndexedProperty(ContactSchema.HomePhone); this.RegisterIndexedProperty(ContactSchema.HomePhone2); this.RegisterIndexedProperty(ContactSchema.Isdn); this.RegisterIndexedProperty(ContactSchema.MobilePhone); this.RegisterIndexedProperty(ContactSchema.OtherFax); this.RegisterIndexedProperty(ContactSchema.OtherTelephone); this.RegisterIndexedProperty(ContactSchema.Pager); this.RegisterIndexedProperty(ContactSchema.PrimaryPhone); this.RegisterIndexedProperty(ContactSchema.RadioPhone); this.RegisterIndexedProperty(ContactSchema.Telex); this.RegisterIndexedProperty(ContactSchema.TtyTddPhone); this.RegisterIndexedProperty(ContactSchema.BusinessAddressStreet); this.RegisterIndexedProperty(ContactSchema.BusinessAddressCity); this.RegisterIndexedProperty(ContactSchema.BusinessAddressState); this.RegisterIndexedProperty(ContactSchema.BusinessAddressCountryOrRegion); this.RegisterIndexedProperty(ContactSchema.BusinessAddressPostalCode); this.RegisterIndexedProperty(ContactSchema.HomeAddressStreet); this.RegisterIndexedProperty(ContactSchema.HomeAddressCity); this.RegisterIndexedProperty(ContactSchema.HomeAddressState); this.RegisterIndexedProperty(ContactSchema.HomeAddressCountryOrRegion); this.RegisterIndexedProperty(ContactSchema.HomeAddressPostalCode); this.RegisterIndexedProperty(ContactSchema.OtherAddressStreet); this.RegisterIndexedProperty(ContactSchema.OtherAddressCity); this.RegisterIndexedProperty(ContactSchema.OtherAddressState); this.RegisterIndexedProperty(ContactSchema.OtherAddressCountryOrRegion); this.RegisterIndexedProperty(ContactSchema.OtherAddressPostalCode); } } /** * Represents the schem for contacts. */ export interface ContactSchema { /** * Defines the **FileAs** property. */ FileAs: PropertyDefinition; /** * Defines the **FileAsMapping** property. */ FileAsMapping: PropertyDefinition; /** * Defines the **DisplayName** property. */ DisplayName: PropertyDefinition; /** * Defines the **GivenName** property. */ GivenName: PropertyDefinition; /** * Defines the **Initials** property. */ Initials: PropertyDefinition; /** * Defines the **MiddleName** property. */ MiddleName: PropertyDefinition; /** * Defines the **NickName** property. */ NickName: PropertyDefinition; /** * Defines the **CompleteName** property. */ CompleteName: PropertyDefinition; /** * Defines the **CompanyName** property. */ CompanyName: PropertyDefinition; /** * Defines the **EmailAddresses** property. */ EmailAddresses: PropertyDefinition; /** * Defines the **PhysicalAddresses** property. */ PhysicalAddresses: PropertyDefinition; /** * Defines the **PhoneNumbers** property. */ PhoneNumbers: PropertyDefinition; /** * Defines the **AssistantName** property. */ AssistantName: PropertyDefinition; /** * Defines the **Birthday** property. */ Birthday: PropertyDefinition; /** * Defines the **BusinessHomePage** property. */ BusinessHomePage: PropertyDefinition; /** * Defines the **Children** property. */ Children: PropertyDefinition; /** * Defines the **Companies** property. */ Companies: PropertyDefinition; /** * Defines the **ContactSource** property. */ ContactSource: PropertyDefinition; /** * Defines the **Department** property. */ Department: PropertyDefinition; /** * Defines the **Generation** property. */ Generation: PropertyDefinition; /** * Defines the **ImAddresses** property. */ ImAddresses: PropertyDefinition; /** * Defines the **JobTitle** property. */ JobTitle: PropertyDefinition; /** * Defines the **Manager** property. */ Manager: PropertyDefinition; /** * Defines the **Mileage** property. */ Mileage: PropertyDefinition; /** * Defines the **OfficeLocation** property. */ OfficeLocation: PropertyDefinition; /** * Defines the **PostalAddressIndex** property. */ PostalAddressIndex: PropertyDefinition; /** * Defines the **Profession** property. */ Profession: PropertyDefinition; /** * Defines the **SpouseName** property. */ SpouseName: PropertyDefinition; /** * Defines the **Surname** property. */ Surname: PropertyDefinition; /** * Defines the **WeddingAnniversary** property. */ WeddingAnniversary: PropertyDefinition; /** * Defines the **HasPicture** property. */ HasPicture: PropertyDefinition; /** * Defines the **PhoneticFullName** property. */ PhoneticFullName: PropertyDefinition; /** * Defines the **PhoneticFirstName** property. */ PhoneticFirstName: PropertyDefinition; /** * Defines the **PhoneticLastName** property. */ PhoneticLastName: PropertyDefinition; /** * Defines the **Alias** property. */ Alias: PropertyDefinition; /** * Defines the **Notes** property. */ Notes: PropertyDefinition; /** * Defines the **Photo** property. */ Photo: PropertyDefinition; /** * Defines the **UserSMIMECertificate** property. */ UserSMIMECertificate: PropertyDefinition; /** * Defines the **MSExchangeCertificate** property. */ MSExchangeCertificate: PropertyDefinition; /** * Defines the **DirectoryId** property. */ DirectoryId: PropertyDefinition; /** * Defines the **ManagerMailbox** property. */ ManagerMailbox: PropertyDefinition; /** * Defines the **DirectReports** property. */ DirectReports: PropertyDefinition; /** * Defines the **EmailAddress1** property. */ EmailAddress1: IndexedPropertyDefinition; /** * Defines the **EmailAddress2** property. */ EmailAddress2: IndexedPropertyDefinition; /** * Defines the **EmailAddress3** property. */ EmailAddress3: IndexedPropertyDefinition; /** * Defines the **ImAddress1** property. */ ImAddress1: IndexedPropertyDefinition; /** * Defines the **ImAddress2** property. */ ImAddress2: IndexedPropertyDefinition; /** * Defines the **ImAddress3** property. */ ImAddress3: IndexedPropertyDefinition; /** * Defines the **AssistantPhone** property. */ AssistantPhone: IndexedPropertyDefinition; /** * Defines the **BusinessFax** property. */ BusinessFax: IndexedPropertyDefinition; /** * Defines the **BusinessPhone** property. */ BusinessPhone: IndexedPropertyDefinition; /** * Defines the **BusinessPhone2** property. */ BusinessPhone2: IndexedPropertyDefinition; /** * Defines the **Callback** property. */ Callback: IndexedPropertyDefinition; /** * Defines the **CarPhone** property. */ CarPhone: IndexedPropertyDefinition; /** * Defines the **CompanyMainPhone** property. */ CompanyMainPhone: IndexedPropertyDefinition; /** * Defines the **HomeFax** property. */ HomeFax: IndexedPropertyDefinition; /** * Defines the **HomePhone** property. */ HomePhone: IndexedPropertyDefinition; /** * Defines the **HomePhone2** property. */ HomePhone2: IndexedPropertyDefinition; /** * Defines the **Isdn** property. */ Isdn: IndexedPropertyDefinition; /** * Defines the **MobilePhone** property. */ MobilePhone: IndexedPropertyDefinition; /** * Defines the **OtherFax** property. */ OtherFax: IndexedPropertyDefinition; /** * Defines the **OtherTelephone** property. */ OtherTelephone: IndexedPropertyDefinition; /** * Defines the **Pager** property. */ Pager: IndexedPropertyDefinition; /** * Defines the **PrimaryPhone** property. */ PrimaryPhone: IndexedPropertyDefinition; /** * Defines the **RadioPhone** property. */ RadioPhone: IndexedPropertyDefinition; /** * Defines the **Telex** property. */ Telex: IndexedPropertyDefinition; /** * Defines the **TtyTddPhone** property. */ TtyTddPhone: IndexedPropertyDefinition; /** * Defines the **BusinessAddressStreet** property. */ BusinessAddressStreet: IndexedPropertyDefinition; /** * Defines the **BusinessAddressCity** property. */ BusinessAddressCity: IndexedPropertyDefinition; /** * Defines the **BusinessAddressState** property. */ BusinessAddressState: IndexedPropertyDefinition; /** * Defines the **BusinessAddressCountryOrRegion** property. */ BusinessAddressCountryOrRegion: IndexedPropertyDefinition; /** * Defines the **BusinessAddressPostalCode** property. */ BusinessAddressPostalCode: IndexedPropertyDefinition; /** * Defines the **HomeAddressStreet** property. */ HomeAddressStreet: IndexedPropertyDefinition; /** * Defines the **HomeAddressCity** property. */ HomeAddressCity: IndexedPropertyDefinition; /** * Defines the **HomeAddressState** property. */ HomeAddressState: IndexedPropertyDefinition; /** * Defines the **HomeAddressCountryOrRegion** property. */ HomeAddressCountryOrRegion: IndexedPropertyDefinition; /** * Defines the **HomeAddressPostalCode** property. */ HomeAddressPostalCode: IndexedPropertyDefinition; /** * Defines the **OtherAddressStreet** property. */ OtherAddressStreet: IndexedPropertyDefinition; /** * Defines the **OtherAddressCity** property. */ OtherAddressCity: IndexedPropertyDefinition; /** * Defines the **OtherAddressState** property. */ OtherAddressState: IndexedPropertyDefinition; /** * Defines the **OtherAddressCountryOrRegion** property. */ OtherAddressCountryOrRegion: IndexedPropertyDefinition; /** * Defines the **OtherAddressPostalCode** property. */ OtherAddressPostalCode: IndexedPropertyDefinition; /** * @internal Instance of **ContactSchema** */ Instance: ContactSchema; } /** * Represents the schem for contacts. */ export interface ContactSchemaStatic extends ContactSchema { }
the_stack
'use strict'; import { window, OutputChannel, ExtensionContext, TextDocument, Diagnostic, DiagnosticSeverity } from 'vscode'; import { instrumentOperationAsVsCodeCommand } from "vscode-extension-telemetry-wrapper"; import * as process from 'child_process'; import { ProblemInfo, DomainInfo, HappeningsInfo, Happening, PlanStep } from 'pddl-workspace'; import { HappeningsToValStep, Util } from 'ai-planning-val'; import { PddlConfiguration } from '../configuration/configuration'; import { dirname } from 'path'; import { DomainAndProblem, isHappenings, getDomainAndProblemForHappenings } from '../workspace/workspaceUtils'; import { createRangeFromLine, createDiagnostic, createDiagnosticFromParsingProblem } from './validatorUtils'; import { CodePddlWorkspace } from '../workspace/CodePddlWorkspace'; export const PDDL_HAPPENINGS_VALIDATE = 'pddl.happenings.validate'; /** * Delegate for parsing and validating Plan Happenings files. */ export class HappeningsValidator { constructor(private output: OutputChannel, public codePddlWorkspace: CodePddlWorkspace, public plannerConfiguration: PddlConfiguration, context: ExtensionContext) { context.subscriptions.push(instrumentOperationAsVsCodeCommand(PDDL_HAPPENINGS_VALIDATE, async () => { if (window.activeTextEditor && isHappenings(window.activeTextEditor.document)) { try { const outcome = await this.validateTextDocument(window.activeTextEditor.document); if (outcome.getError()) { window.showErrorMessage(outcome.getError()!); } } catch (ex) { window.showErrorMessage("Happenings validation failed: " + ex); return; } } else { window.showErrorMessage("There is no happenings file open."); return; } })); } async validateTextDocument(happeningsDocument: TextDocument): Promise<HappeningsValidationOutcome> { const planFileInfo = await this.codePddlWorkspace.upsertAndParseFile(happeningsDocument) as HappeningsInfo; if (!planFileInfo) { throw new Error("Cannot open or parse plan file: " + happeningsDocument.uri.fsPath); } // eslint-disable-next-line @typescript-eslint/no-empty-function return this.validateAndReportDiagnostics(planFileInfo, true, () => { }, () => { }); } async validateAndReportDiagnostics(happeningsInfo: HappeningsInfo, showOutput: boolean, onSuccess: (diagnostics: Map<string, Diagnostic[]>) => void, onError: (error: string) => void): Promise<HappeningsValidationOutcome> { if (happeningsInfo.getParsingProblems().length > 0) { const diagnostics = happeningsInfo.getParsingProblems() .map(problem => createDiagnosticFromParsingProblem(problem)); const outcome = HappeningsValidationOutcome.failedWithDiagnostics(happeningsInfo, diagnostics); onSuccess(outcome.getDiagnostics()); return outcome; } let context: DomainAndProblem | null = null; try { context = getDomainAndProblemForHappenings(happeningsInfo, this.codePddlWorkspace.pddlWorkspace); } catch (err: unknown) { const outcome = HappeningsValidationOutcome.info(happeningsInfo, err as Error); onSuccess(outcome.getDiagnostics()); return outcome; } // are the actions in the plan declared in the domain? const actionNameDiagnostics = this.validateActionNames(context.domain, context.problem, happeningsInfo); if (actionNameDiagnostics.length) { const errorOutcome = HappeningsValidationOutcome.failedWithDiagnostics(happeningsInfo, actionNameDiagnostics); onSuccess(errorOutcome.getDiagnostics()); return errorOutcome; } // are the actions start times monotonically increasing? const actionTimeDiagnostics = this.validateActionTimes(happeningsInfo); if (actionTimeDiagnostics.length) { const errorOutcome = HappeningsValidationOutcome.failedWithDiagnostics(happeningsInfo, actionTimeDiagnostics); onSuccess(errorOutcome.getDiagnostics()); return errorOutcome; } const valStepPath = await this.plannerConfiguration.getValStepPath(); //const valVerbose = this.plannerConfiguration.getValStepVerbose(); if (!valStepPath) { onSuccess(HappeningsValidationOutcome.unknown(happeningsInfo, "ValStep not configured.").getDiagnostics()); } // copy editor content to temp files to avoid using out-of-date content on disk const domainFilePath = await Util.toPddlFile('domain', context.domain.getText()); const problemFilePath = await Util.toPddlFile('problem', context.problem.getText()); const happeningsConverter = new HappeningsToValStep(); happeningsConverter.convertAllHappenings(happeningsInfo); const valSteps = happeningsConverter.getExportedText(true); const args = [domainFilePath, problemFilePath]; const child = process.spawnSync(valStepPath!, args, { cwd: dirname(happeningsInfo.fileUri.fsPath), input: valSteps }); if (showOutput) { this.output.appendLine(valStepPath + ' ' + args.join(' ')); } const output = child.stdout.toString(); if (showOutput) { this.output.appendLine(output); } if (showOutput && child.stderr && child.stderr.length) { this.output.append('Error:'); this.output.appendLine(child.stderr.toString()); } const outcome = this.analyzeOutput(happeningsInfo, child.error, output); if (child.error) { if (showOutput) { this.output.appendLine(`Error: name=${child.error.name}, message=${child.error.message}`); } onError(child.error.name); } else { onSuccess(outcome.getDiagnostics()); } if (showOutput) { this.output.appendLine(`Exit code: ${child.status}`); this.output.show(); } return outcome; } // eslint-disable-next-line @typescript-eslint/no-unused-vars analyzeOutput(happeningsInfo: HappeningsInfo, error: Error | undefined, _output: string): HappeningsValidationOutcome { if (error) { return HappeningsValidationOutcome.failed(happeningsInfo, error); } return HappeningsValidationOutcome.valid(happeningsInfo); } /** * Validate that plan steps match domain actions * @param domain domain file * @param problem problem file * @param happeningsInfo happeningsInfo */ validateActionNames(domain: DomainInfo, problem: ProblemInfo, happeningsInfo: HappeningsInfo): Diagnostic[] { return happeningsInfo.getHappenings() .filter(happening => !this.isDomainAction(domain, problem, happening)) .map(happening => new Diagnostic(createRangeFromLine(happening.lineIndex ?? 0), `Action '${happening.getAction()}' not known by the domain '${domain.name}'`, DiagnosticSeverity.Error)); } /** * Validate that plan step times are monotonically increasing * @param domain domain file * @param problem problem file * @param happeningsInfo happeningsInfo */ validateActionTimes(happeningsInfo: HappeningsInfo): Diagnostic[] { return happeningsInfo.getHappenings() .slice(1) .filter((happening: Happening, index: number) => !this.isTimeMonotonociallyIncreasing(happeningsInfo.getHappenings()[index], happening)) .map(happening => new Diagnostic(createRangeFromLine(happening.lineIndex ?? 0), `Action '${happening.getAction()}' time ${happening.getTime()} is before the preceding action time`, DiagnosticSeverity.Error)); } private isDomainAction(domain: DomainInfo, problem: ProblemInfo, happening: Happening): boolean { const allActionNames = domain.getActions().map(a => a.name?.toLowerCase() ?? 'undefined').concat( problem.getSupplyDemands().map(sd => sd.getName().toLowerCase())); return allActionNames.includes(happening.getAction().toLowerCase()); } private isTimeMonotonociallyIncreasing(first: Happening, second: Happening): boolean { return first.getTime() <= second.getTime(); } } class HappeningsValidationOutcome { constructor(public readonly happeningsInfo: HappeningsInfo, private diagnostics: Diagnostic[], private error?: string) { } getError(): string | undefined { return this.error; } getDiagnostics(): Map<string, Diagnostic[]> { const diagnostics = new Map<string, Diagnostic[]>(); diagnostics.set(this.happeningsInfo.fileUri.toString(), this.diagnostics); return diagnostics; } static goalNotAttained(happeningsInfo: HappeningsInfo): HappeningsValidationOutcome { const errorLine = happeningsInfo.getHappenings().length > 0 ? happeningsInfo.getHappenings().slice(-1).pop()?.lineIndex ?? 0 + 1 : 0; const error = "Plan does not reach the goal."; const diagnostics = [createDiagnostic(errorLine, 0, error, DiagnosticSeverity.Warning)]; return new HappeningsValidationOutcome(happeningsInfo, diagnostics, error); } /** * Creates validation outcomes for invalid plan i.e. plans that do not parse or do not correspond to the domain/problem file. */ static invalidPlanDescription(happeningsInfo: HappeningsInfo): HappeningsValidationOutcome { const error = "Invalid plan description."; const diagnostics = [createDiagnostic(0, 0, error, DiagnosticSeverity.Error)]; return new HappeningsValidationOutcome(happeningsInfo, diagnostics, error); } /** * Creates validation outcomes for valid plan, which does not reach the goal. */ static valid(happeningsInfo: HappeningsInfo): HappeningsValidationOutcome { return new HappeningsValidationOutcome(happeningsInfo, [], undefined); } static failed(happeningsInfo: HappeningsInfo, error: Error): HappeningsValidationOutcome { const message = "Validate tool failed. " + error.message; const diagnostics = [createDiagnostic(0, 0, message, DiagnosticSeverity.Error)]; return new HappeningsValidationOutcome(happeningsInfo, diagnostics, message); } static info(happeningsInfo: HappeningsInfo, error: Error): HappeningsValidationOutcome { const message = error.message; const diagnostics = [createDiagnostic(0, 0, message, DiagnosticSeverity.Information)]; return new HappeningsValidationOutcome(happeningsInfo, diagnostics, message); } static failedWithDiagnostics(happeningsInfo: HappeningsInfo, diagnostics: Diagnostic[]): HappeningsValidationOutcome { return new HappeningsValidationOutcome(happeningsInfo, diagnostics); } static failedAtTime(happeningsInfo: HappeningsInfo, timeStamp: number, repairHints: string[]): HappeningsValidationOutcome { let errorLine = 0; const stepAtTimeStamp = happeningsInfo.getHappenings() .find(happening => PlanStep.equalsWithin(happening.getTime(), timeStamp, 1e-4)); if (stepAtTimeStamp && stepAtTimeStamp.lineIndex !== undefined) { errorLine = stepAtTimeStamp.lineIndex; } const diagnostics = repairHints.map(hint => new Diagnostic(createRangeFromLine(errorLine), hint, DiagnosticSeverity.Warning)); return new HappeningsValidationOutcome(happeningsInfo, diagnostics); } static unknown(happeningsInfo: HappeningsInfo, message = "Unknown error."): HappeningsValidationOutcome { const diagnostics = [new Diagnostic(createRangeFromLine(0), message, DiagnosticSeverity.Warning)]; return new HappeningsValidationOutcome(happeningsInfo, diagnostics, message); } }
the_stack
import {Z80} from "./Z80.js"; import {toHex, inc8, inc16, dec8, dec16, add8, add16, sub8, sub16, word, hi, lo, Flag, signedByte} from "z80-base"; type OpcodeFunc = (z80: Z80) => void; // Tables for computing flags after an operation. const halfCarryAddTable = [0, Flag.H, Flag.H, Flag.H, 0, 0, 0, Flag.H]; const halfCarrySubTable = [0, 0, Flag.H, 0, Flag.H, 0, Flag.H, Flag.H]; const overflowAddTable = [0, 0, 0, Flag.V, Flag.V, 0, 0, 0]; const overflowSubTable = [0, Flag.V, 0, 0, 0, 0, Flag.V, 0]; const decodeMapBASE = new Map<number, OpcodeFunc>(); decodeMapBASE.set(0x00, (z80: Z80) => { // nop }); decodeMapBASE.set(0x01, (z80: Z80) => { // ld bc,nnnn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); value = word(z80.readByte(z80.regs.pc), value); z80.regs.pc = inc16(z80.regs.pc); z80.regs.bc = value; }); decodeMapBASE.set(0x02, (z80: Z80) => { // ld (bc),a let value: number; value = z80.regs.a; z80.regs.memptr = word(z80.regs.a, inc16(z80.regs.bc)); z80.writeByte(z80.regs.bc, value); }); decodeMapBASE.set(0x03, (z80: Z80) => { // inc bc let value: number; value = z80.regs.bc; const oldValue = value; z80.incTStateCount(2); value = inc16(value); z80.regs.bc = value; }); decodeMapBASE.set(0x04, (z80: Z80) => { // inc b let value: number; value = z80.regs.b; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.b = value; }); decodeMapBASE.set(0x05, (z80: Z80) => { // dec b let value: number; value = z80.regs.b; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.b = value; }); decodeMapBASE.set(0x06, (z80: Z80) => { // ld b,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.b = value; }); decodeMapBASE.set(0x07, (z80: Z80) => { // rlca const oldA = z80.regs.a; z80.regs.a = ((z80.regs.a >> 7) | (z80.regs.a << 1)) & 0xFF; z80.regs.f = (z80.regs.f & (Flag.P | Flag.Z | Flag.S)) | (z80.regs.a & (Flag.X3 | Flag.X5)) | ((oldA & 0x80) !== 0 ? Flag.C : 0); }); decodeMapBASE.set(0x08, (z80: Z80) => { // ex af,af' const rightValue = z80.regs.afPrime; z80.regs.afPrime = z80.regs.af; z80.regs.af = rightValue; }); decodeMapBASE.set(0x09, (z80: Z80) => { // add hl,bc let value: number; z80.incTStateCount(7); value = z80.regs.bc; let result = z80.regs.hl + value; const lookup = (((z80.regs.hl & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapBASE.set(0x0A, (z80: Z80) => { // ld a,(bc) let value: number; z80.regs.memptr = inc16(z80.regs.bc); value = z80.readByte(z80.regs.bc); z80.regs.a = value; }); decodeMapBASE.set(0x0B, (z80: Z80) => { // dec bc let value: number; value = z80.regs.bc; const oldValue = value; z80.incTStateCount(2); value = dec16(value); z80.regs.bc = value; }); decodeMapBASE.set(0x0C, (z80: Z80) => { // inc c let value: number; value = z80.regs.c; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.c = value; }); decodeMapBASE.set(0x0D, (z80: Z80) => { // dec c let value: number; value = z80.regs.c; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.c = value; }); decodeMapBASE.set(0x0E, (z80: Z80) => { // ld c,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.c = value; }); decodeMapBASE.set(0x0F, (z80: Z80) => { // rrca const oldA = z80.regs.a; z80.regs.a = ((z80.regs.a >> 1) | (z80.regs.a << 7)) & 0xFF; z80.regs.f = (z80.regs.f & (Flag.P | Flag.Z | Flag.S)) | (z80.regs.a & (Flag.X3 | Flag.X5)) | ((oldA & 0x01) !== 0 ? Flag.C : 0); }); decodeMapBASE.set(0x10, (z80: Z80) => { // djnz offset z80.incTStateCount(1); z80.regs.b = dec8(z80.regs.b); if (z80.regs.b !== 0) { const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, signedByte(offset)); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = z80.regs.pc; } else { z80.incTStateCount(3); z80.regs.pc = inc16(z80.regs.pc); } }); decodeMapBASE.set(0x11, (z80: Z80) => { // ld de,nnnn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); value = word(z80.readByte(z80.regs.pc), value); z80.regs.pc = inc16(z80.regs.pc); z80.regs.de = value; }); decodeMapBASE.set(0x12, (z80: Z80) => { // ld (de),a let value: number; value = z80.regs.a; z80.regs.memptr = word(z80.regs.a, inc16(z80.regs.de)); z80.writeByte(z80.regs.de, value); }); decodeMapBASE.set(0x13, (z80: Z80) => { // inc de let value: number; value = z80.regs.de; const oldValue = value; z80.incTStateCount(2); value = inc16(value); z80.regs.de = value; }); decodeMapBASE.set(0x14, (z80: Z80) => { // inc d let value: number; value = z80.regs.d; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.d = value; }); decodeMapBASE.set(0x15, (z80: Z80) => { // dec d let value: number; value = z80.regs.d; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.d = value; }); decodeMapBASE.set(0x16, (z80: Z80) => { // ld d,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.d = value; }); decodeMapBASE.set(0x17, (z80: Z80) => { // rla const oldA = z80.regs.a; z80.regs.a = ((z80.regs.a << 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x01 : 0)) & 0xFF; z80.regs.f = (z80.regs.f & (Flag.P | Flag.Z | Flag.S)) | (z80.regs.a & (Flag.X3 | Flag.X5)) | ((oldA & 0x80) !== 0 ? Flag.C : 0); }); decodeMapBASE.set(0x18, (z80: Z80) => { // jr offset const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, signedByte(offset)); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = z80.regs.pc; }); decodeMapBASE.set(0x19, (z80: Z80) => { // add hl,de let value: number; z80.incTStateCount(7); value = z80.regs.de; let result = z80.regs.hl + value; const lookup = (((z80.regs.hl & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapBASE.set(0x1A, (z80: Z80) => { // ld a,(de) let value: number; z80.regs.memptr = inc16(z80.regs.de); value = z80.readByte(z80.regs.de); z80.regs.a = value; }); decodeMapBASE.set(0x1B, (z80: Z80) => { // dec de let value: number; value = z80.regs.de; const oldValue = value; z80.incTStateCount(2); value = dec16(value); z80.regs.de = value; }); decodeMapBASE.set(0x1C, (z80: Z80) => { // inc e let value: number; value = z80.regs.e; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.e = value; }); decodeMapBASE.set(0x1D, (z80: Z80) => { // dec e let value: number; value = z80.regs.e; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.e = value; }); decodeMapBASE.set(0x1E, (z80: Z80) => { // ld e,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.e = value; }); decodeMapBASE.set(0x1F, (z80: Z80) => { // rra const oldA = z80.regs.a; z80.regs.a = (z80.regs.a >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = (z80.regs.f & (Flag.P | Flag.Z | Flag.S)) | (z80.regs.a & (Flag.X3 | Flag.X5)) | ((oldA & 0x01) !== 0 ? Flag.C : 0); }); decodeMapBASE.set(0x20, (z80: Z80) => { // jr nz,offset if ((z80.regs.f & Flag.Z) === 0) { const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, signedByte(offset)); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = z80.regs.pc; } else { z80.incTStateCount(3); z80.regs.pc = inc16(z80.regs.pc); } }); decodeMapBASE.set(0x21, (z80: Z80) => { // ld hl,nnnn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); value = word(z80.readByte(z80.regs.pc), value); z80.regs.pc = inc16(z80.regs.pc); z80.regs.hl = value; }); decodeMapBASE.set(0x22, (z80: Z80) => { // ld (nnnn),hl let value: number; value = z80.regs.hl; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); z80.writeByte(addr, lo(value)); addr = inc16(addr); z80.regs.memptr = addr; z80.writeByte(addr, hi(value)); }); decodeMapBASE.set(0x23, (z80: Z80) => { // inc hl let value: number; value = z80.regs.hl; const oldValue = value; z80.incTStateCount(2); value = inc16(value); z80.regs.hl = value; }); decodeMapBASE.set(0x24, (z80: Z80) => { // inc h let value: number; value = z80.regs.h; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.h = value; }); decodeMapBASE.set(0x25, (z80: Z80) => { // dec h let value: number; value = z80.regs.h; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.h = value; }); decodeMapBASE.set(0x26, (z80: Z80) => { // ld h,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.h = value; }); decodeMapBASE.set(0x27, (z80: Z80) => { // daa let value = 0; let carry = z80.regs.f & Flag.C; if ((z80.regs.f & Flag.H) !== 0 || ((z80.regs.a & 0x0F) > 9)) { value = 6; // Skip over hex digits in lower nybble. } if (carry !== 0 || z80.regs.a > 0x99) { value |= 0x60; // Skip over hex digits in upper nybble. } if (z80.regs.a > 0x99) { carry = Flag.C; } if ((z80.regs.f & Flag.N) !== 0) { let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; } else { let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; } z80.regs.f = (z80.regs.f & ~(Flag.C | Flag.P)) | carry | z80.parityTable[z80.regs.a]; }); decodeMapBASE.set(0x28, (z80: Z80) => { // jr z,offset if ((z80.regs.f & Flag.Z) !== 0) { const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, signedByte(offset)); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = z80.regs.pc; } else { z80.incTStateCount(3); z80.regs.pc = inc16(z80.regs.pc); } }); decodeMapBASE.set(0x29, (z80: Z80) => { // add hl,hl let value: number; z80.incTStateCount(7); value = z80.regs.hl; let result = z80.regs.hl + value; const lookup = (((z80.regs.hl & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapBASE.set(0x2A, (z80: Z80) => { // ld hl,(nnnn) let value: number; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); value = z80.readByte(addr); z80.regs.memptr = inc16(addr); value = word(z80.readByte(z80.regs.memptr), value); z80.regs.hl = value; }); decodeMapBASE.set(0x2B, (z80: Z80) => { // dec hl let value: number; value = z80.regs.hl; const oldValue = value; z80.incTStateCount(2); value = dec16(value); z80.regs.hl = value; }); decodeMapBASE.set(0x2C, (z80: Z80) => { // inc l let value: number; value = z80.regs.l; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.l = value; }); decodeMapBASE.set(0x2D, (z80: Z80) => { // dec l let value: number; value = z80.regs.l; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.l = value; }); decodeMapBASE.set(0x2E, (z80: Z80) => { // ld l,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.l = value; }); decodeMapBASE.set(0x2F, (z80: Z80) => { // cpl z80.regs.a ^= 0xFF; z80.regs.f = (z80.regs.f & (Flag.C | Flag.P | Flag.Z | Flag.S)) | (z80.regs.a & (Flag.X3 | Flag.X5)) | Flag.N | Flag.H; }); decodeMapBASE.set(0x30, (z80: Z80) => { // jr nc,offset if ((z80.regs.f & Flag.C) === 0) { const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, signedByte(offset)); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = z80.regs.pc; } else { z80.incTStateCount(3); z80.regs.pc = inc16(z80.regs.pc); } }); decodeMapBASE.set(0x31, (z80: Z80) => { // ld sp,nnnn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); value = word(z80.readByte(z80.regs.pc), value); z80.regs.pc = inc16(z80.regs.pc); z80.regs.sp = value; }); decodeMapBASE.set(0x32, (z80: Z80) => { // ld (nnnn),a let value: number; value = z80.regs.a; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); value = word(z80.readByte(z80.regs.pc), value); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.regs.a, inc16(value)); z80.writeByte(value, z80.regs.a); }); decodeMapBASE.set(0x33, (z80: Z80) => { // inc sp let value: number; value = z80.regs.sp; const oldValue = value; z80.incTStateCount(2); value = inc16(value); z80.regs.sp = value; }); decodeMapBASE.set(0x34, (z80: Z80) => { // inc (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x35, (z80: Z80) => { // dec (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x36, (z80: Z80) => { // ld (hl),nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x37, (z80: Z80) => { // scf z80.regs.f = (z80.regs.f & (Flag.P | Flag.Z | Flag.S)) | Flag.C | (z80.regs.a & (Flag.X3 | Flag.X5)); }); decodeMapBASE.set(0x38, (z80: Z80) => { // jr c,offset if ((z80.regs.f & Flag.C) !== 0) { const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, signedByte(offset)); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = z80.regs.pc; } else { z80.incTStateCount(3); z80.regs.pc = inc16(z80.regs.pc); } }); decodeMapBASE.set(0x39, (z80: Z80) => { // add hl,sp let value: number; z80.incTStateCount(7); value = z80.regs.sp; let result = z80.regs.hl + value; const lookup = (((z80.regs.hl & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapBASE.set(0x3A, (z80: Z80) => { // ld a,(nnnn) let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); value = word(z80.readByte(z80.regs.pc), value); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = inc16(value); value = z80.readByte(value); z80.regs.a = value; }); decodeMapBASE.set(0x3B, (z80: Z80) => { // dec sp let value: number; value = z80.regs.sp; const oldValue = value; z80.incTStateCount(2); value = dec16(value); z80.regs.sp = value; }); decodeMapBASE.set(0x3C, (z80: Z80) => { // inc a let value: number; value = z80.regs.a; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.a = value; }); decodeMapBASE.set(0x3D, (z80: Z80) => { // dec a let value: number; value = z80.regs.a; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.a = value; }); decodeMapBASE.set(0x3E, (z80: Z80) => { // ld a,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.a = value; }); decodeMapBASE.set(0x3F, (z80: Z80) => { // ccf z80.regs.f = (z80.regs.f & (Flag.P | Flag.Z | Flag.S)) | ((z80.regs.f & Flag.C) !== 0 ? Flag.H : Flag.C) | (z80.regs.a & (Flag.X3 | Flag.X5)); }); decodeMapBASE.set(0x40, (z80: Z80) => { // ld b,b let value: number; value = z80.regs.b; z80.regs.b = value; }); decodeMapBASE.set(0x41, (z80: Z80) => { // ld b,c let value: number; value = z80.regs.c; z80.regs.b = value; }); decodeMapBASE.set(0x42, (z80: Z80) => { // ld b,d let value: number; value = z80.regs.d; z80.regs.b = value; }); decodeMapBASE.set(0x43, (z80: Z80) => { // ld b,e let value: number; value = z80.regs.e; z80.regs.b = value; }); decodeMapBASE.set(0x44, (z80: Z80) => { // ld b,h let value: number; value = z80.regs.h; z80.regs.b = value; }); decodeMapBASE.set(0x45, (z80: Z80) => { // ld b,l let value: number; value = z80.regs.l; z80.regs.b = value; }); decodeMapBASE.set(0x46, (z80: Z80) => { // ld b,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.b = value; }); decodeMapBASE.set(0x47, (z80: Z80) => { // ld b,a let value: number; value = z80.regs.a; z80.regs.b = value; }); decodeMapBASE.set(0x48, (z80: Z80) => { // ld c,b let value: number; value = z80.regs.b; z80.regs.c = value; }); decodeMapBASE.set(0x49, (z80: Z80) => { // ld c,c let value: number; value = z80.regs.c; z80.regs.c = value; }); decodeMapBASE.set(0x4A, (z80: Z80) => { // ld c,d let value: number; value = z80.regs.d; z80.regs.c = value; }); decodeMapBASE.set(0x4B, (z80: Z80) => { // ld c,e let value: number; value = z80.regs.e; z80.regs.c = value; }); decodeMapBASE.set(0x4C, (z80: Z80) => { // ld c,h let value: number; value = z80.regs.h; z80.regs.c = value; }); decodeMapBASE.set(0x4D, (z80: Z80) => { // ld c,l let value: number; value = z80.regs.l; z80.regs.c = value; }); decodeMapBASE.set(0x4E, (z80: Z80) => { // ld c,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.c = value; }); decodeMapBASE.set(0x4F, (z80: Z80) => { // ld c,a let value: number; value = z80.regs.a; z80.regs.c = value; }); decodeMapBASE.set(0x50, (z80: Z80) => { // ld d,b let value: number; value = z80.regs.b; z80.regs.d = value; }); decodeMapBASE.set(0x51, (z80: Z80) => { // ld d,c let value: number; value = z80.regs.c; z80.regs.d = value; }); decodeMapBASE.set(0x52, (z80: Z80) => { // ld d,d let value: number; value = z80.regs.d; z80.regs.d = value; }); decodeMapBASE.set(0x53, (z80: Z80) => { // ld d,e let value: number; value = z80.regs.e; z80.regs.d = value; }); decodeMapBASE.set(0x54, (z80: Z80) => { // ld d,h let value: number; value = z80.regs.h; z80.regs.d = value; }); decodeMapBASE.set(0x55, (z80: Z80) => { // ld d,l let value: number; value = z80.regs.l; z80.regs.d = value; }); decodeMapBASE.set(0x56, (z80: Z80) => { // ld d,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.d = value; }); decodeMapBASE.set(0x57, (z80: Z80) => { // ld d,a let value: number; value = z80.regs.a; z80.regs.d = value; }); decodeMapBASE.set(0x58, (z80: Z80) => { // ld e,b let value: number; value = z80.regs.b; z80.regs.e = value; }); decodeMapBASE.set(0x59, (z80: Z80) => { // ld e,c let value: number; value = z80.regs.c; z80.regs.e = value; }); decodeMapBASE.set(0x5A, (z80: Z80) => { // ld e,d let value: number; value = z80.regs.d; z80.regs.e = value; }); decodeMapBASE.set(0x5B, (z80: Z80) => { // ld e,e let value: number; value = z80.regs.e; z80.regs.e = value; }); decodeMapBASE.set(0x5C, (z80: Z80) => { // ld e,h let value: number; value = z80.regs.h; z80.regs.e = value; }); decodeMapBASE.set(0x5D, (z80: Z80) => { // ld e,l let value: number; value = z80.regs.l; z80.regs.e = value; }); decodeMapBASE.set(0x5E, (z80: Z80) => { // ld e,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.e = value; }); decodeMapBASE.set(0x5F, (z80: Z80) => { // ld e,a let value: number; value = z80.regs.a; z80.regs.e = value; }); decodeMapBASE.set(0x60, (z80: Z80) => { // ld h,b let value: number; value = z80.regs.b; z80.regs.h = value; }); decodeMapBASE.set(0x61, (z80: Z80) => { // ld h,c let value: number; value = z80.regs.c; z80.regs.h = value; }); decodeMapBASE.set(0x62, (z80: Z80) => { // ld h,d let value: number; value = z80.regs.d; z80.regs.h = value; }); decodeMapBASE.set(0x63, (z80: Z80) => { // ld h,e let value: number; value = z80.regs.e; z80.regs.h = value; }); decodeMapBASE.set(0x64, (z80: Z80) => { // ld h,h let value: number; value = z80.regs.h; z80.regs.h = value; }); decodeMapBASE.set(0x65, (z80: Z80) => { // ld h,l let value: number; value = z80.regs.l; z80.regs.h = value; }); decodeMapBASE.set(0x66, (z80: Z80) => { // ld h,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.h = value; }); decodeMapBASE.set(0x67, (z80: Z80) => { // ld h,a let value: number; value = z80.regs.a; z80.regs.h = value; }); decodeMapBASE.set(0x68, (z80: Z80) => { // ld l,b let value: number; value = z80.regs.b; z80.regs.l = value; }); decodeMapBASE.set(0x69, (z80: Z80) => { // ld l,c let value: number; value = z80.regs.c; z80.regs.l = value; }); decodeMapBASE.set(0x6A, (z80: Z80) => { // ld l,d let value: number; value = z80.regs.d; z80.regs.l = value; }); decodeMapBASE.set(0x6B, (z80: Z80) => { // ld l,e let value: number; value = z80.regs.e; z80.regs.l = value; }); decodeMapBASE.set(0x6C, (z80: Z80) => { // ld l,h let value: number; value = z80.regs.h; z80.regs.l = value; }); decodeMapBASE.set(0x6D, (z80: Z80) => { // ld l,l let value: number; value = z80.regs.l; z80.regs.l = value; }); decodeMapBASE.set(0x6E, (z80: Z80) => { // ld l,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.l = value; }); decodeMapBASE.set(0x6F, (z80: Z80) => { // ld l,a let value: number; value = z80.regs.a; z80.regs.l = value; }); decodeMapBASE.set(0x70, (z80: Z80) => { // ld (hl),b let value: number; value = z80.regs.b; z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x71, (z80: Z80) => { // ld (hl),c let value: number; value = z80.regs.c; z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x72, (z80: Z80) => { // ld (hl),d let value: number; value = z80.regs.d; z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x73, (z80: Z80) => { // ld (hl),e let value: number; value = z80.regs.e; z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x74, (z80: Z80) => { // ld (hl),h let value: number; value = z80.regs.h; z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x75, (z80: Z80) => { // ld (hl),l let value: number; value = z80.regs.l; z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x76, (z80: Z80) => { // halt z80.regs.halted = 1; z80.regs.pc = dec16(z80.regs.pc); }); decodeMapBASE.set(0x77, (z80: Z80) => { // ld (hl),a let value: number; value = z80.regs.a; z80.writeByte(z80.regs.hl, value); }); decodeMapBASE.set(0x78, (z80: Z80) => { // ld a,b let value: number; value = z80.regs.b; z80.regs.a = value; }); decodeMapBASE.set(0x79, (z80: Z80) => { // ld a,c let value: number; value = z80.regs.c; z80.regs.a = value; }); decodeMapBASE.set(0x7A, (z80: Z80) => { // ld a,d let value: number; value = z80.regs.d; z80.regs.a = value; }); decodeMapBASE.set(0x7B, (z80: Z80) => { // ld a,e let value: number; value = z80.regs.e; z80.regs.a = value; }); decodeMapBASE.set(0x7C, (z80: Z80) => { // ld a,h let value: number; value = z80.regs.h; z80.regs.a = value; }); decodeMapBASE.set(0x7D, (z80: Z80) => { // ld a,l let value: number; value = z80.regs.l; z80.regs.a = value; }); decodeMapBASE.set(0x7E, (z80: Z80) => { // ld a,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.a = value; }); decodeMapBASE.set(0x7F, (z80: Z80) => { // ld a,a let value: number; value = z80.regs.a; z80.regs.a = value; }); decodeMapBASE.set(0x80, (z80: Z80) => { // add a,b let value: number; value = z80.regs.b; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x81, (z80: Z80) => { // add a,c let value: number; value = z80.regs.c; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x82, (z80: Z80) => { // add a,d let value: number; value = z80.regs.d; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x83, (z80: Z80) => { // add a,e let value: number; value = z80.regs.e; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x84, (z80: Z80) => { // add a,h let value: number; value = z80.regs.h; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x85, (z80: Z80) => { // add a,l let value: number; value = z80.regs.l; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x86, (z80: Z80) => { // add a,(hl) let value: number; value = z80.readByte(z80.regs.hl); let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x87, (z80: Z80) => { // add a,a let value: number; value = z80.regs.a; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x88, (z80: Z80) => { // adc a,b let value: number; value = z80.regs.b; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x89, (z80: Z80) => { // adc a,c let value: number; value = z80.regs.c; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x8A, (z80: Z80) => { // adc a,d let value: number; value = z80.regs.d; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x8B, (z80: Z80) => { // adc a,e let value: number; value = z80.regs.e; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x8C, (z80: Z80) => { // adc a,h let value: number; value = z80.regs.h; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x8D, (z80: Z80) => { // adc a,l let value: number; value = z80.regs.l; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x8E, (z80: Z80) => { // adc a,(hl) let value: number; value = z80.readByte(z80.regs.hl); let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x8F, (z80: Z80) => { // adc a,a let value: number; value = z80.regs.a; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x90, (z80: Z80) => { // sub a,b let value: number; value = z80.regs.b; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x91, (z80: Z80) => { // sub a,c let value: number; value = z80.regs.c; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x92, (z80: Z80) => { // sub a,d let value: number; value = z80.regs.d; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x93, (z80: Z80) => { // sub a,e let value: number; value = z80.regs.e; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x94, (z80: Z80) => { // sub a,h let value: number; value = z80.regs.h; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x95, (z80: Z80) => { // sub a,l let value: number; value = z80.regs.l; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x96, (z80: Z80) => { // sub a,(hl) let value: number; value = z80.readByte(z80.regs.hl); let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x97, (z80: Z80) => { // sub a,a let value: number; value = z80.regs.a; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x98, (z80: Z80) => { // sbc a,b let value: number; value = z80.regs.b; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x99, (z80: Z80) => { // sbc a,c let value: number; value = z80.regs.c; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x9A, (z80: Z80) => { // sbc a,d let value: number; value = z80.regs.d; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x9B, (z80: Z80) => { // sbc a,e let value: number; value = z80.regs.e; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x9C, (z80: Z80) => { // sbc a,h let value: number; value = z80.regs.h; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x9D, (z80: Z80) => { // sbc a,l let value: number; value = z80.regs.l; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x9E, (z80: Z80) => { // sbc a,(hl) let value: number; value = z80.readByte(z80.regs.hl); let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0x9F, (z80: Z80) => { // sbc a,a let value: number; value = z80.regs.a; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0xA0, (z80: Z80) => { // and a,b let value: number; value = z80.regs.b; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapBASE.set(0xA1, (z80: Z80) => { // and a,c let value: number; value = z80.regs.c; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapBASE.set(0xA2, (z80: Z80) => { // and a,d let value: number; value = z80.regs.d; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapBASE.set(0xA3, (z80: Z80) => { // and a,e let value: number; value = z80.regs.e; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapBASE.set(0xA4, (z80: Z80) => { // and a,h let value: number; value = z80.regs.h; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapBASE.set(0xA5, (z80: Z80) => { // and a,l let value: number; value = z80.regs.l; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapBASE.set(0xA6, (z80: Z80) => { // and a,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapBASE.set(0xA7, (z80: Z80) => { // and a,a let value: number; value = z80.regs.a; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapBASE.set(0xA8, (z80: Z80) => { // xor a,b let value: number; value = z80.regs.b; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xA9, (z80: Z80) => { // xor a,c let value: number; value = z80.regs.c; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xAA, (z80: Z80) => { // xor a,d let value: number; value = z80.regs.d; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xAB, (z80: Z80) => { // xor a,e let value: number; value = z80.regs.e; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xAC, (z80: Z80) => { // xor a,h let value: number; value = z80.regs.h; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xAD, (z80: Z80) => { // xor a,l let value: number; value = z80.regs.l; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xAE, (z80: Z80) => { // xor a,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xAF, (z80: Z80) => { // xor a,a let value: number; value = z80.regs.a; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xB0, (z80: Z80) => { // or a,b let value: number; value = z80.regs.b; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xB1, (z80: Z80) => { // or a,c let value: number; value = z80.regs.c; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xB2, (z80: Z80) => { // or a,d let value: number; value = z80.regs.d; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xB3, (z80: Z80) => { // or a,e let value: number; value = z80.regs.e; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xB4, (z80: Z80) => { // or a,h let value: number; value = z80.regs.h; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xB5, (z80: Z80) => { // or a,l let value: number; value = z80.regs.l; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xB6, (z80: Z80) => { // or a,(hl) let value: number; value = z80.readByte(z80.regs.hl); z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xB7, (z80: Z80) => { // or a,a let value: number; value = z80.regs.a; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xB8, (z80: Z80) => { // cp b let value: number; value = z80.regs.b; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapBASE.set(0xB9, (z80: Z80) => { // cp c let value: number; value = z80.regs.c; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapBASE.set(0xBA, (z80: Z80) => { // cp d let value: number; value = z80.regs.d; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapBASE.set(0xBB, (z80: Z80) => { // cp e let value: number; value = z80.regs.e; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapBASE.set(0xBC, (z80: Z80) => { // cp h let value: number; value = z80.regs.h; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapBASE.set(0xBD, (z80: Z80) => { // cp l let value: number; value = z80.regs.l; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapBASE.set(0xBE, (z80: Z80) => { // cp (hl) let value: number; value = z80.readByte(z80.regs.hl); const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapBASE.set(0xBF, (z80: Z80) => { // cp a let value: number; value = z80.regs.a; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapBASE.set(0xC0, (z80: Z80) => { // ret nz z80.incTStateCount(1); if ((z80.regs.f & Flag.Z) === 0) { z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; } }); decodeMapBASE.set(0xC1, (z80: Z80) => { // pop bc z80.regs.bc = z80.popWord(); }); decodeMapBASE.set(0xC2, (z80: Z80) => { // jp nz,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.Z) === 0) { z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xC3, (z80: Z80) => { // jp nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); z80.regs.pc = z80.regs.memptr; }); decodeMapBASE.set(0xC4, (z80: Z80) => { // call nz,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.Z) === 0) { z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xC5, (z80: Z80) => { // push bc z80.incTStateCount(1); z80.pushWord(z80.regs.bc); }); decodeMapBASE.set(0xC6, (z80: Z80) => { // add a,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0xC7, (z80: Z80) => { // rst 00 z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = 0x0000; z80.regs.memptr = z80.regs.pc; }); decodeMapBASE.set(0xC8, (z80: Z80) => { // ret z z80.incTStateCount(1); if ((z80.regs.f & Flag.Z) !== 0) { z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; } }); decodeMapBASE.set(0xC9, (z80: Z80) => { // ret z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; }); decodeMapBASE.set(0xCA, (z80: Z80) => { // jp z,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.Z) !== 0) { z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xCB, (z80: Z80) => { // shift cb decodeCB(z80); }); decodeMapBASE.set(0xCC, (z80: Z80) => { // call z,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.Z) !== 0) { z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xCD, (z80: Z80) => { // call nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = z80.regs.memptr; }); decodeMapBASE.set(0xCE, (z80: Z80) => { // adc a,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0xCF, (z80: Z80) => { // rst 8 z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = 0x0008; z80.regs.memptr = z80.regs.pc; }); decodeMapBASE.set(0xD0, (z80: Z80) => { // ret nc z80.incTStateCount(1); if ((z80.regs.f & Flag.C) === 0) { z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; } }); decodeMapBASE.set(0xD1, (z80: Z80) => { // pop de z80.regs.de = z80.popWord(); }); decodeMapBASE.set(0xD2, (z80: Z80) => { // jp nc,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.C) === 0) { z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xD3, (z80: Z80) => { // out (nn),a const port = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.regs.a, inc8(port)); z80.writePort(word(z80.regs.a, port), z80.regs.a); }); decodeMapBASE.set(0xD4, (z80: Z80) => { // call nc,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.C) === 0) { z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xD5, (z80: Z80) => { // push de z80.incTStateCount(1); z80.pushWord(z80.regs.de); }); decodeMapBASE.set(0xD6, (z80: Z80) => { // sub a,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0xD7, (z80: Z80) => { // rst 10 z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = 0x0010; z80.regs.memptr = z80.regs.pc; }); decodeMapBASE.set(0xD8, (z80: Z80) => { // ret c z80.incTStateCount(1); if ((z80.regs.f & Flag.C) !== 0) { z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; } }); decodeMapBASE.set(0xD9, (z80: Z80) => { // exx let tmp: number; tmp = z80.regs.bc; z80.regs.bc = z80.regs.bcPrime; z80.regs.bcPrime = tmp; tmp = z80.regs.de; z80.regs.de = z80.regs.dePrime; z80.regs.dePrime = tmp; tmp = z80.regs.hl; z80.regs.hl = z80.regs.hlPrime; z80.regs.hlPrime = tmp; }); decodeMapBASE.set(0xDA, (z80: Z80) => { // jp c,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.C) !== 0) { z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xDB, (z80: Z80) => { // in a,(nn) const port = word(z80.regs.a, z80.readByte(z80.regs.pc)); z80.regs.pc = inc16(z80.regs.pc); z80.regs.a = z80.readPort(port); z80.regs.memptr = inc16(port); }); decodeMapBASE.set(0xDC, (z80: Z80) => { // call c,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.C) !== 0) { z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xDD, (z80: Z80) => { // shift dd decodeDD(z80); }); decodeMapBASE.set(0xDE, (z80: Z80) => { // sbc a,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapBASE.set(0xDF, (z80: Z80) => { // rst 18 z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = 0x0018; z80.regs.memptr = z80.regs.pc; }); decodeMapBASE.set(0xE0, (z80: Z80) => { // ret po z80.incTStateCount(1); if ((z80.regs.f & Flag.P) === 0) { z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; } }); decodeMapBASE.set(0xE1, (z80: Z80) => { // pop hl z80.regs.hl = z80.popWord(); }); decodeMapBASE.set(0xE2, (z80: Z80) => { // jp po,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.P) === 0) { z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xE3, (z80: Z80) => { // ex (sp),hl const rightValue = z80.regs.hl; const leftValueL = z80.readByte(z80.regs.sp); const leftValueH = z80.readByte(inc16(z80.regs.sp)); z80.incTStateCount(1); z80.writeByte(inc16(z80.regs.sp), hi(rightValue)); z80.writeByte(z80.regs.sp, lo(rightValue)); z80.incTStateCount(2); z80.regs.memptr = word(leftValueH, leftValueL); z80.regs.hl = word(leftValueH, leftValueL); }); decodeMapBASE.set(0xE4, (z80: Z80) => { // call po,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.P) === 0) { z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xE5, (z80: Z80) => { // push hl z80.incTStateCount(1); z80.pushWord(z80.regs.hl); }); decodeMapBASE.set(0xE6, (z80: Z80) => { // and nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapBASE.set(0xE7, (z80: Z80) => { // rst 20 z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = 0x0020; z80.regs.memptr = z80.regs.pc; }); decodeMapBASE.set(0xE8, (z80: Z80) => { // ret pe z80.incTStateCount(1); if ((z80.regs.f & Flag.P) !== 0) { z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; } }); decodeMapBASE.set(0xE9, (z80: Z80) => { // jp hl z80.regs.pc = z80.regs.hl; }); decodeMapBASE.set(0xEA, (z80: Z80) => { // jp pe,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.P) !== 0) { z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xEB, (z80: Z80) => { // ex de,hl const rightValue = z80.regs.hl; z80.regs.hl = z80.regs.de; z80.regs.de = rightValue; }); decodeMapBASE.set(0xEC, (z80: Z80) => { // call pe,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.P) !== 0) { z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xED, (z80: Z80) => { // shift ed decodeED(z80); }); decodeMapBASE.set(0xEE, (z80: Z80) => { // xor a,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xEF, (z80: Z80) => { // rst 28 z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = 0x0028; z80.regs.memptr = z80.regs.pc; }); decodeMapBASE.set(0xF0, (z80: Z80) => { // ret p z80.incTStateCount(1); if ((z80.regs.f & Flag.S) === 0) { z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; } }); decodeMapBASE.set(0xF1, (z80: Z80) => { // pop af z80.regs.af = z80.popWord(); }); decodeMapBASE.set(0xF2, (z80: Z80) => { // jp p,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.S) === 0) { z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xF3, (z80: Z80) => { // di z80.regs.iff1 = 0; z80.regs.iff2 = 0; }); decodeMapBASE.set(0xF4, (z80: Z80) => { // call p,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.S) === 0) { z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xF5, (z80: Z80) => { // push af z80.incTStateCount(1); z80.pushWord(z80.regs.af); }); decodeMapBASE.set(0xF6, (z80: Z80) => { // or nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapBASE.set(0xF7, (z80: Z80) => { // rst 30 z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = 0x0030; z80.regs.memptr = z80.regs.pc; }); decodeMapBASE.set(0xF8, (z80: Z80) => { // ret m z80.incTStateCount(1); if ((z80.regs.f & Flag.S) !== 0) { z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; } }); decodeMapBASE.set(0xF9, (z80: Z80) => { // ld sp,hl let value: number; value = z80.regs.hl; z80.incTStateCount(2); z80.regs.sp = value; }); decodeMapBASE.set(0xFA, (z80: Z80) => { // jp m,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.S) !== 0) { z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xFB, (z80: Z80) => { // ei z80.regs.iff1 = 1; z80.regs.iff2 = 1; }); decodeMapBASE.set(0xFC, (z80: Z80) => { // call m,nnnn z80.regs.memptr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr); z80.regs.pc = inc16(z80.regs.pc); if ((z80.regs.f & Flag.S) !== 0) { z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = z80.regs.memptr; } }); decodeMapBASE.set(0xFD, (z80: Z80) => { // shift fd decodeFD(z80); }); decodeMapBASE.set(0xFE, (z80: Z80) => { // cp nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapBASE.set(0xFF, (z80: Z80) => { // rst 38 z80.incTStateCount(1); z80.pushWord(z80.regs.pc); z80.regs.pc = 0x0038; z80.regs.memptr = z80.regs.pc; }); const decodeMapCB = new Map<number, OpcodeFunc>(); decodeMapCB.set(0x00, (z80: Z80) => { // rlc b let value: number; value = z80.regs.b; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; }); decodeMapCB.set(0x01, (z80: Z80) => { // rlc c let value: number; value = z80.regs.c; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; }); decodeMapCB.set(0x02, (z80: Z80) => { // rlc d let value: number; value = z80.regs.d; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; }); decodeMapCB.set(0x03, (z80: Z80) => { // rlc e let value: number; value = z80.regs.e; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; }); decodeMapCB.set(0x04, (z80: Z80) => { // rlc h let value: number; value = z80.regs.h; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; }); decodeMapCB.set(0x05, (z80: Z80) => { // rlc l let value: number; value = z80.regs.l; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; }); decodeMapCB.set(0x06, (z80: Z80) => { // rlc (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapCB.set(0x07, (z80: Z80) => { // rlc a let value: number; value = z80.regs.a; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; }); decodeMapCB.set(0x08, (z80: Z80) => { // rrc b let value: number; value = z80.regs.b; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; }); decodeMapCB.set(0x09, (z80: Z80) => { // rrc c let value: number; value = z80.regs.c; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; }); decodeMapCB.set(0x0A, (z80: Z80) => { // rrc d let value: number; value = z80.regs.d; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; }); decodeMapCB.set(0x0B, (z80: Z80) => { // rrc e let value: number; value = z80.regs.e; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; }); decodeMapCB.set(0x0C, (z80: Z80) => { // rrc h let value: number; value = z80.regs.h; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; }); decodeMapCB.set(0x0D, (z80: Z80) => { // rrc l let value: number; value = z80.regs.l; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; }); decodeMapCB.set(0x0E, (z80: Z80) => { // rrc (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapCB.set(0x0F, (z80: Z80) => { // rrc a let value: number; value = z80.regs.a; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; }); decodeMapCB.set(0x10, (z80: Z80) => { // rl b let value: number; value = z80.regs.b; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; }); decodeMapCB.set(0x11, (z80: Z80) => { // rl c let value: number; value = z80.regs.c; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; }); decodeMapCB.set(0x12, (z80: Z80) => { // rl d let value: number; value = z80.regs.d; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; }); decodeMapCB.set(0x13, (z80: Z80) => { // rl e let value: number; value = z80.regs.e; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; }); decodeMapCB.set(0x14, (z80: Z80) => { // rl h let value: number; value = z80.regs.h; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; }); decodeMapCB.set(0x15, (z80: Z80) => { // rl l let value: number; value = z80.regs.l; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; }); decodeMapCB.set(0x16, (z80: Z80) => { // rl (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapCB.set(0x17, (z80: Z80) => { // rl a let value: number; value = z80.regs.a; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; }); decodeMapCB.set(0x18, (z80: Z80) => { // rr b let value: number; value = z80.regs.b; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; }); decodeMapCB.set(0x19, (z80: Z80) => { // rr c let value: number; value = z80.regs.c; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; }); decodeMapCB.set(0x1A, (z80: Z80) => { // rr d let value: number; value = z80.regs.d; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; }); decodeMapCB.set(0x1B, (z80: Z80) => { // rr e let value: number; value = z80.regs.e; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; }); decodeMapCB.set(0x1C, (z80: Z80) => { // rr h let value: number; value = z80.regs.h; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; }); decodeMapCB.set(0x1D, (z80: Z80) => { // rr l let value: number; value = z80.regs.l; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; }); decodeMapCB.set(0x1E, (z80: Z80) => { // rr (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapCB.set(0x1F, (z80: Z80) => { // rr a let value: number; value = z80.regs.a; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; }); decodeMapCB.set(0x20, (z80: Z80) => { // sla b let value: number; value = z80.regs.b; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; }); decodeMapCB.set(0x21, (z80: Z80) => { // sla c let value: number; value = z80.regs.c; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; }); decodeMapCB.set(0x22, (z80: Z80) => { // sla d let value: number; value = z80.regs.d; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; }); decodeMapCB.set(0x23, (z80: Z80) => { // sla e let value: number; value = z80.regs.e; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; }); decodeMapCB.set(0x24, (z80: Z80) => { // sla h let value: number; value = z80.regs.h; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; }); decodeMapCB.set(0x25, (z80: Z80) => { // sla l let value: number; value = z80.regs.l; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; }); decodeMapCB.set(0x26, (z80: Z80) => { // sla (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapCB.set(0x27, (z80: Z80) => { // sla a let value: number; value = z80.regs.a; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; }); decodeMapCB.set(0x28, (z80: Z80) => { // sra b let value: number; value = z80.regs.b; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; }); decodeMapCB.set(0x29, (z80: Z80) => { // sra c let value: number; value = z80.regs.c; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; }); decodeMapCB.set(0x2A, (z80: Z80) => { // sra d let value: number; value = z80.regs.d; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; }); decodeMapCB.set(0x2B, (z80: Z80) => { // sra e let value: number; value = z80.regs.e; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; }); decodeMapCB.set(0x2C, (z80: Z80) => { // sra h let value: number; value = z80.regs.h; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; }); decodeMapCB.set(0x2D, (z80: Z80) => { // sra l let value: number; value = z80.regs.l; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; }); decodeMapCB.set(0x2E, (z80: Z80) => { // sra (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapCB.set(0x2F, (z80: Z80) => { // sra a let value: number; value = z80.regs.a; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; }); decodeMapCB.set(0x30, (z80: Z80) => { // sll b let value: number; value = z80.regs.b; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; }); decodeMapCB.set(0x31, (z80: Z80) => { // sll c let value: number; value = z80.regs.c; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; }); decodeMapCB.set(0x32, (z80: Z80) => { // sll d let value: number; value = z80.regs.d; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; }); decodeMapCB.set(0x33, (z80: Z80) => { // sll e let value: number; value = z80.regs.e; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; }); decodeMapCB.set(0x34, (z80: Z80) => { // sll h let value: number; value = z80.regs.h; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; }); decodeMapCB.set(0x35, (z80: Z80) => { // sll l let value: number; value = z80.regs.l; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; }); decodeMapCB.set(0x36, (z80: Z80) => { // sll (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapCB.set(0x37, (z80: Z80) => { // sll a let value: number; value = z80.regs.a; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; }); decodeMapCB.set(0x38, (z80: Z80) => { // srl b let value: number; value = z80.regs.b; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; }); decodeMapCB.set(0x39, (z80: Z80) => { // srl c let value: number; value = z80.regs.c; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; }); decodeMapCB.set(0x3A, (z80: Z80) => { // srl d let value: number; value = z80.regs.d; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; }); decodeMapCB.set(0x3B, (z80: Z80) => { // srl e let value: number; value = z80.regs.e; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; }); decodeMapCB.set(0x3C, (z80: Z80) => { // srl h let value: number; value = z80.regs.h; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; }); decodeMapCB.set(0x3D, (z80: Z80) => { // srl l let value: number; value = z80.regs.l; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; }); decodeMapCB.set(0x3E, (z80: Z80) => { // srl (hl) let value: number; value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.hl, value); }); decodeMapCB.set(0x3F, (z80: Z80) => { // srl a let value: number; value = z80.regs.a; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; }); decodeMapCB.set(0x40, (z80: Z80) => { // bit 0,b const value = z80.regs.b; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x41, (z80: Z80) => { // bit 0,c const value = z80.regs.c; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x42, (z80: Z80) => { // bit 0,d const value = z80.regs.d; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x43, (z80: Z80) => { // bit 0,e const value = z80.regs.e; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x44, (z80: Z80) => { // bit 0,h const value = z80.regs.h; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x45, (z80: Z80) => { // bit 0,l const value = z80.regs.l; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x46, (z80: Z80) => { // bit 0,(hl) const value = z80.readByte(z80.regs.hl); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x47, (z80: Z80) => { // bit 0,a const value = z80.regs.a; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x48, (z80: Z80) => { // bit 1,b const value = z80.regs.b; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x49, (z80: Z80) => { // bit 1,c const value = z80.regs.c; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x4A, (z80: Z80) => { // bit 1,d const value = z80.regs.d; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x4B, (z80: Z80) => { // bit 1,e const value = z80.regs.e; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x4C, (z80: Z80) => { // bit 1,h const value = z80.regs.h; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x4D, (z80: Z80) => { // bit 1,l const value = z80.regs.l; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x4E, (z80: Z80) => { // bit 1,(hl) const value = z80.readByte(z80.regs.hl); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x4F, (z80: Z80) => { // bit 1,a const value = z80.regs.a; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x50, (z80: Z80) => { // bit 2,b const value = z80.regs.b; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x51, (z80: Z80) => { // bit 2,c const value = z80.regs.c; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x52, (z80: Z80) => { // bit 2,d const value = z80.regs.d; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x53, (z80: Z80) => { // bit 2,e const value = z80.regs.e; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x54, (z80: Z80) => { // bit 2,h const value = z80.regs.h; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x55, (z80: Z80) => { // bit 2,l const value = z80.regs.l; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x56, (z80: Z80) => { // bit 2,(hl) const value = z80.readByte(z80.regs.hl); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x57, (z80: Z80) => { // bit 2,a const value = z80.regs.a; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x58, (z80: Z80) => { // bit 3,b const value = z80.regs.b; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x59, (z80: Z80) => { // bit 3,c const value = z80.regs.c; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x5A, (z80: Z80) => { // bit 3,d const value = z80.regs.d; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x5B, (z80: Z80) => { // bit 3,e const value = z80.regs.e; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x5C, (z80: Z80) => { // bit 3,h const value = z80.regs.h; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x5D, (z80: Z80) => { // bit 3,l const value = z80.regs.l; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x5E, (z80: Z80) => { // bit 3,(hl) const value = z80.readByte(z80.regs.hl); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x5F, (z80: Z80) => { // bit 3,a const value = z80.regs.a; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x60, (z80: Z80) => { // bit 4,b const value = z80.regs.b; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x61, (z80: Z80) => { // bit 4,c const value = z80.regs.c; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x62, (z80: Z80) => { // bit 4,d const value = z80.regs.d; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x63, (z80: Z80) => { // bit 4,e const value = z80.regs.e; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x64, (z80: Z80) => { // bit 4,h const value = z80.regs.h; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x65, (z80: Z80) => { // bit 4,l const value = z80.regs.l; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x66, (z80: Z80) => { // bit 4,(hl) const value = z80.readByte(z80.regs.hl); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x67, (z80: Z80) => { // bit 4,a const value = z80.regs.a; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x68, (z80: Z80) => { // bit 5,b const value = z80.regs.b; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x69, (z80: Z80) => { // bit 5,c const value = z80.regs.c; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x6A, (z80: Z80) => { // bit 5,d const value = z80.regs.d; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x6B, (z80: Z80) => { // bit 5,e const value = z80.regs.e; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x6C, (z80: Z80) => { // bit 5,h const value = z80.regs.h; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x6D, (z80: Z80) => { // bit 5,l const value = z80.regs.l; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x6E, (z80: Z80) => { // bit 5,(hl) const value = z80.readByte(z80.regs.hl); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x6F, (z80: Z80) => { // bit 5,a const value = z80.regs.a; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x70, (z80: Z80) => { // bit 6,b const value = z80.regs.b; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x71, (z80: Z80) => { // bit 6,c const value = z80.regs.c; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x72, (z80: Z80) => { // bit 6,d const value = z80.regs.d; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x73, (z80: Z80) => { // bit 6,e const value = z80.regs.e; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x74, (z80: Z80) => { // bit 6,h const value = z80.regs.h; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x75, (z80: Z80) => { // bit 6,l const value = z80.regs.l; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x76, (z80: Z80) => { // bit 6,(hl) const value = z80.readByte(z80.regs.hl); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x77, (z80: Z80) => { // bit 6,a const value = z80.regs.a; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapCB.set(0x78, (z80: Z80) => { // bit 7,b const value = z80.regs.b; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapCB.set(0x79, (z80: Z80) => { // bit 7,c const value = z80.regs.c; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapCB.set(0x7A, (z80: Z80) => { // bit 7,d const value = z80.regs.d; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapCB.set(0x7B, (z80: Z80) => { // bit 7,e const value = z80.regs.e; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapCB.set(0x7C, (z80: Z80) => { // bit 7,h const value = z80.regs.h; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapCB.set(0x7D, (z80: Z80) => { // bit 7,l const value = z80.regs.l; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapCB.set(0x7E, (z80: Z80) => { // bit 7,(hl) const value = z80.readByte(z80.regs.hl); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapCB.set(0x7F, (z80: Z80) => { // bit 7,a const value = z80.regs.a; const hiddenValue = value; let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapCB.set(0x80, (z80: Z80) => { // res 0,b z80.regs.b &= 0xFE; }); decodeMapCB.set(0x81, (z80: Z80) => { // res 0,c z80.regs.c &= 0xFE; }); decodeMapCB.set(0x82, (z80: Z80) => { // res 0,d z80.regs.d &= 0xFE; }); decodeMapCB.set(0x83, (z80: Z80) => { // res 0,e z80.regs.e &= 0xFE; }); decodeMapCB.set(0x84, (z80: Z80) => { // res 0,h z80.regs.h &= 0xFE; }); decodeMapCB.set(0x85, (z80: Z80) => { // res 0,l z80.regs.l &= 0xFE; }); decodeMapCB.set(0x86, (z80: Z80) => { // res 0,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value & 0xFE); }); decodeMapCB.set(0x87, (z80: Z80) => { // res 0,a z80.regs.a &= 0xFE; }); decodeMapCB.set(0x88, (z80: Z80) => { // res 1,b z80.regs.b &= 0xFD; }); decodeMapCB.set(0x89, (z80: Z80) => { // res 1,c z80.regs.c &= 0xFD; }); decodeMapCB.set(0x8A, (z80: Z80) => { // res 1,d z80.regs.d &= 0xFD; }); decodeMapCB.set(0x8B, (z80: Z80) => { // res 1,e z80.regs.e &= 0xFD; }); decodeMapCB.set(0x8C, (z80: Z80) => { // res 1,h z80.regs.h &= 0xFD; }); decodeMapCB.set(0x8D, (z80: Z80) => { // res 1,l z80.regs.l &= 0xFD; }); decodeMapCB.set(0x8E, (z80: Z80) => { // res 1,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value & 0xFD); }); decodeMapCB.set(0x8F, (z80: Z80) => { // res 1,a z80.regs.a &= 0xFD; }); decodeMapCB.set(0x90, (z80: Z80) => { // res 2,b z80.regs.b &= 0xFB; }); decodeMapCB.set(0x91, (z80: Z80) => { // res 2,c z80.regs.c &= 0xFB; }); decodeMapCB.set(0x92, (z80: Z80) => { // res 2,d z80.regs.d &= 0xFB; }); decodeMapCB.set(0x93, (z80: Z80) => { // res 2,e z80.regs.e &= 0xFB; }); decodeMapCB.set(0x94, (z80: Z80) => { // res 2,h z80.regs.h &= 0xFB; }); decodeMapCB.set(0x95, (z80: Z80) => { // res 2,l z80.regs.l &= 0xFB; }); decodeMapCB.set(0x96, (z80: Z80) => { // res 2,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value & 0xFB); }); decodeMapCB.set(0x97, (z80: Z80) => { // res 2,a z80.regs.a &= 0xFB; }); decodeMapCB.set(0x98, (z80: Z80) => { // res 3,b z80.regs.b &= 0xF7; }); decodeMapCB.set(0x99, (z80: Z80) => { // res 3,c z80.regs.c &= 0xF7; }); decodeMapCB.set(0x9A, (z80: Z80) => { // res 3,d z80.regs.d &= 0xF7; }); decodeMapCB.set(0x9B, (z80: Z80) => { // res 3,e z80.regs.e &= 0xF7; }); decodeMapCB.set(0x9C, (z80: Z80) => { // res 3,h z80.regs.h &= 0xF7; }); decodeMapCB.set(0x9D, (z80: Z80) => { // res 3,l z80.regs.l &= 0xF7; }); decodeMapCB.set(0x9E, (z80: Z80) => { // res 3,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value & 0xF7); }); decodeMapCB.set(0x9F, (z80: Z80) => { // res 3,a z80.regs.a &= 0xF7; }); decodeMapCB.set(0xA0, (z80: Z80) => { // res 4,b z80.regs.b &= 0xEF; }); decodeMapCB.set(0xA1, (z80: Z80) => { // res 4,c z80.regs.c &= 0xEF; }); decodeMapCB.set(0xA2, (z80: Z80) => { // res 4,d z80.regs.d &= 0xEF; }); decodeMapCB.set(0xA3, (z80: Z80) => { // res 4,e z80.regs.e &= 0xEF; }); decodeMapCB.set(0xA4, (z80: Z80) => { // res 4,h z80.regs.h &= 0xEF; }); decodeMapCB.set(0xA5, (z80: Z80) => { // res 4,l z80.regs.l &= 0xEF; }); decodeMapCB.set(0xA6, (z80: Z80) => { // res 4,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value & 0xEF); }); decodeMapCB.set(0xA7, (z80: Z80) => { // res 4,a z80.regs.a &= 0xEF; }); decodeMapCB.set(0xA8, (z80: Z80) => { // res 5,b z80.regs.b &= 0xDF; }); decodeMapCB.set(0xA9, (z80: Z80) => { // res 5,c z80.regs.c &= 0xDF; }); decodeMapCB.set(0xAA, (z80: Z80) => { // res 5,d z80.regs.d &= 0xDF; }); decodeMapCB.set(0xAB, (z80: Z80) => { // res 5,e z80.regs.e &= 0xDF; }); decodeMapCB.set(0xAC, (z80: Z80) => { // res 5,h z80.regs.h &= 0xDF; }); decodeMapCB.set(0xAD, (z80: Z80) => { // res 5,l z80.regs.l &= 0xDF; }); decodeMapCB.set(0xAE, (z80: Z80) => { // res 5,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value & 0xDF); }); decodeMapCB.set(0xAF, (z80: Z80) => { // res 5,a z80.regs.a &= 0xDF; }); decodeMapCB.set(0xB0, (z80: Z80) => { // res 6,b z80.regs.b &= 0xBF; }); decodeMapCB.set(0xB1, (z80: Z80) => { // res 6,c z80.regs.c &= 0xBF; }); decodeMapCB.set(0xB2, (z80: Z80) => { // res 6,d z80.regs.d &= 0xBF; }); decodeMapCB.set(0xB3, (z80: Z80) => { // res 6,e z80.regs.e &= 0xBF; }); decodeMapCB.set(0xB4, (z80: Z80) => { // res 6,h z80.regs.h &= 0xBF; }); decodeMapCB.set(0xB5, (z80: Z80) => { // res 6,l z80.regs.l &= 0xBF; }); decodeMapCB.set(0xB6, (z80: Z80) => { // res 6,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value & 0xBF); }); decodeMapCB.set(0xB7, (z80: Z80) => { // res 6,a z80.regs.a &= 0xBF; }); decodeMapCB.set(0xB8, (z80: Z80) => { // res 7,b z80.regs.b &= 0x7F; }); decodeMapCB.set(0xB9, (z80: Z80) => { // res 7,c z80.regs.c &= 0x7F; }); decodeMapCB.set(0xBA, (z80: Z80) => { // res 7,d z80.regs.d &= 0x7F; }); decodeMapCB.set(0xBB, (z80: Z80) => { // res 7,e z80.regs.e &= 0x7F; }); decodeMapCB.set(0xBC, (z80: Z80) => { // res 7,h z80.regs.h &= 0x7F; }); decodeMapCB.set(0xBD, (z80: Z80) => { // res 7,l z80.regs.l &= 0x7F; }); decodeMapCB.set(0xBE, (z80: Z80) => { // res 7,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value & 0x7F); }); decodeMapCB.set(0xBF, (z80: Z80) => { // res 7,a z80.regs.a &= 0x7F; }); decodeMapCB.set(0xC0, (z80: Z80) => { // set 0,b z80.regs.b |= 0x01; }); decodeMapCB.set(0xC1, (z80: Z80) => { // set 0,c z80.regs.c |= 0x01; }); decodeMapCB.set(0xC2, (z80: Z80) => { // set 0,d z80.regs.d |= 0x01; }); decodeMapCB.set(0xC3, (z80: Z80) => { // set 0,e z80.regs.e |= 0x01; }); decodeMapCB.set(0xC4, (z80: Z80) => { // set 0,h z80.regs.h |= 0x01; }); decodeMapCB.set(0xC5, (z80: Z80) => { // set 0,l z80.regs.l |= 0x01; }); decodeMapCB.set(0xC6, (z80: Z80) => { // set 0,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value | 0x01); }); decodeMapCB.set(0xC7, (z80: Z80) => { // set 0,a z80.regs.a |= 0x01; }); decodeMapCB.set(0xC8, (z80: Z80) => { // set 1,b z80.regs.b |= 0x02; }); decodeMapCB.set(0xC9, (z80: Z80) => { // set 1,c z80.regs.c |= 0x02; }); decodeMapCB.set(0xCA, (z80: Z80) => { // set 1,d z80.regs.d |= 0x02; }); decodeMapCB.set(0xCB, (z80: Z80) => { // set 1,e z80.regs.e |= 0x02; }); decodeMapCB.set(0xCC, (z80: Z80) => { // set 1,h z80.regs.h |= 0x02; }); decodeMapCB.set(0xCD, (z80: Z80) => { // set 1,l z80.regs.l |= 0x02; }); decodeMapCB.set(0xCE, (z80: Z80) => { // set 1,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value | 0x02); }); decodeMapCB.set(0xCF, (z80: Z80) => { // set 1,a z80.regs.a |= 0x02; }); decodeMapCB.set(0xD0, (z80: Z80) => { // set 2,b z80.regs.b |= 0x04; }); decodeMapCB.set(0xD1, (z80: Z80) => { // set 2,c z80.regs.c |= 0x04; }); decodeMapCB.set(0xD2, (z80: Z80) => { // set 2,d z80.regs.d |= 0x04; }); decodeMapCB.set(0xD3, (z80: Z80) => { // set 2,e z80.regs.e |= 0x04; }); decodeMapCB.set(0xD4, (z80: Z80) => { // set 2,h z80.regs.h |= 0x04; }); decodeMapCB.set(0xD5, (z80: Z80) => { // set 2,l z80.regs.l |= 0x04; }); decodeMapCB.set(0xD6, (z80: Z80) => { // set 2,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value | 0x04); }); decodeMapCB.set(0xD7, (z80: Z80) => { // set 2,a z80.regs.a |= 0x04; }); decodeMapCB.set(0xD8, (z80: Z80) => { // set 3,b z80.regs.b |= 0x08; }); decodeMapCB.set(0xD9, (z80: Z80) => { // set 3,c z80.regs.c |= 0x08; }); decodeMapCB.set(0xDA, (z80: Z80) => { // set 3,d z80.regs.d |= 0x08; }); decodeMapCB.set(0xDB, (z80: Z80) => { // set 3,e z80.regs.e |= 0x08; }); decodeMapCB.set(0xDC, (z80: Z80) => { // set 3,h z80.regs.h |= 0x08; }); decodeMapCB.set(0xDD, (z80: Z80) => { // set 3,l z80.regs.l |= 0x08; }); decodeMapCB.set(0xDE, (z80: Z80) => { // set 3,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value | 0x08); }); decodeMapCB.set(0xDF, (z80: Z80) => { // set 3,a z80.regs.a |= 0x08; }); decodeMapCB.set(0xE0, (z80: Z80) => { // set 4,b z80.regs.b |= 0x10; }); decodeMapCB.set(0xE1, (z80: Z80) => { // set 4,c z80.regs.c |= 0x10; }); decodeMapCB.set(0xE2, (z80: Z80) => { // set 4,d z80.regs.d |= 0x10; }); decodeMapCB.set(0xE3, (z80: Z80) => { // set 4,e z80.regs.e |= 0x10; }); decodeMapCB.set(0xE4, (z80: Z80) => { // set 4,h z80.regs.h |= 0x10; }); decodeMapCB.set(0xE5, (z80: Z80) => { // set 4,l z80.regs.l |= 0x10; }); decodeMapCB.set(0xE6, (z80: Z80) => { // set 4,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value | 0x10); }); decodeMapCB.set(0xE7, (z80: Z80) => { // set 4,a z80.regs.a |= 0x10; }); decodeMapCB.set(0xE8, (z80: Z80) => { // set 5,b z80.regs.b |= 0x20; }); decodeMapCB.set(0xE9, (z80: Z80) => { // set 5,c z80.regs.c |= 0x20; }); decodeMapCB.set(0xEA, (z80: Z80) => { // set 5,d z80.regs.d |= 0x20; }); decodeMapCB.set(0xEB, (z80: Z80) => { // set 5,e z80.regs.e |= 0x20; }); decodeMapCB.set(0xEC, (z80: Z80) => { // set 5,h z80.regs.h |= 0x20; }); decodeMapCB.set(0xED, (z80: Z80) => { // set 5,l z80.regs.l |= 0x20; }); decodeMapCB.set(0xEE, (z80: Z80) => { // set 5,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value | 0x20); }); decodeMapCB.set(0xEF, (z80: Z80) => { // set 5,a z80.regs.a |= 0x20; }); decodeMapCB.set(0xF0, (z80: Z80) => { // set 6,b z80.regs.b |= 0x40; }); decodeMapCB.set(0xF1, (z80: Z80) => { // set 6,c z80.regs.c |= 0x40; }); decodeMapCB.set(0xF2, (z80: Z80) => { // set 6,d z80.regs.d |= 0x40; }); decodeMapCB.set(0xF3, (z80: Z80) => { // set 6,e z80.regs.e |= 0x40; }); decodeMapCB.set(0xF4, (z80: Z80) => { // set 6,h z80.regs.h |= 0x40; }); decodeMapCB.set(0xF5, (z80: Z80) => { // set 6,l z80.regs.l |= 0x40; }); decodeMapCB.set(0xF6, (z80: Z80) => { // set 6,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value | 0x40); }); decodeMapCB.set(0xF7, (z80: Z80) => { // set 6,a z80.regs.a |= 0x40; }); decodeMapCB.set(0xF8, (z80: Z80) => { // set 7,b z80.regs.b |= 0x80; }); decodeMapCB.set(0xF9, (z80: Z80) => { // set 7,c z80.regs.c |= 0x80; }); decodeMapCB.set(0xFA, (z80: Z80) => { // set 7,d z80.regs.d |= 0x80; }); decodeMapCB.set(0xFB, (z80: Z80) => { // set 7,e z80.regs.e |= 0x80; }); decodeMapCB.set(0xFC, (z80: Z80) => { // set 7,h z80.regs.h |= 0x80; }); decodeMapCB.set(0xFD, (z80: Z80) => { // set 7,l z80.regs.l |= 0x80; }); decodeMapCB.set(0xFE, (z80: Z80) => { // set 7,(hl) const value = z80.readByte(z80.regs.hl); z80.incTStateCount(1); z80.writeByte(z80.regs.hl, value | 0x80); }); decodeMapCB.set(0xFF, (z80: Z80) => { // set 7,a z80.regs.a |= 0x80; }); const decodeMapDD = new Map<number, OpcodeFunc>(); decodeMapDD.set(0x09, (z80: Z80) => { // add ix,bc let value: number; z80.incTStateCount(7); value = z80.regs.bc; let result = z80.regs.ix + value; const lookup = (((z80.regs.ix & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.ix); z80.regs.ix = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapDD.set(0x19, (z80: Z80) => { // add ix,de let value: number; z80.incTStateCount(7); value = z80.regs.de; let result = z80.regs.ix + value; const lookup = (((z80.regs.ix & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.ix); z80.regs.ix = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapDD.set(0x21, (z80: Z80) => { // ld ix,nnnn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); value = word(z80.readByte(z80.regs.pc), value); z80.regs.pc = inc16(z80.regs.pc); z80.regs.ix = value; }); decodeMapDD.set(0x22, (z80: Z80) => { // ld (nnnn),ix let value: number; value = z80.regs.ix; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); z80.writeByte(addr, lo(value)); addr = inc16(addr); z80.regs.memptr = addr; z80.writeByte(addr, hi(value)); }); decodeMapDD.set(0x23, (z80: Z80) => { // inc ix let value: number; value = z80.regs.ix; const oldValue = value; z80.incTStateCount(2); value = inc16(value); z80.regs.ix = value; }); decodeMapDD.set(0x24, (z80: Z80) => { // inc ixh let value: number; value = z80.regs.ixh; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.ixh = value; }); decodeMapDD.set(0x25, (z80: Z80) => { // dec ixh let value: number; value = z80.regs.ixh; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.ixh = value; }); decodeMapDD.set(0x26, (z80: Z80) => { // ld ixh,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.ixh = value; }); decodeMapDD.set(0x29, (z80: Z80) => { // add ix,ix let value: number; z80.incTStateCount(7); value = z80.regs.ix; let result = z80.regs.ix + value; const lookup = (((z80.regs.ix & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.ix); z80.regs.ix = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapDD.set(0x2A, (z80: Z80) => { // ld ix,(nnnn) let value: number; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); value = z80.readByte(addr); z80.regs.memptr = inc16(addr); value = word(z80.readByte(z80.regs.memptr), value); z80.regs.ix = value; }); decodeMapDD.set(0x2B, (z80: Z80) => { // dec ix let value: number; value = z80.regs.ix; const oldValue = value; z80.incTStateCount(2); value = dec16(value); z80.regs.ix = value; }); decodeMapDD.set(0x2C, (z80: Z80) => { // inc ixl let value: number; value = z80.regs.ixl; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.ixl = value; }); decodeMapDD.set(0x2D, (z80: Z80) => { // dec ixl let value: number; value = z80.regs.ixl; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.ixl = value; }); decodeMapDD.set(0x2E, (z80: Z80) => { // ld ixl,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.ixl = value; }); decodeMapDD.set(0x34, (z80: Z80) => { // inc (ix+dd) let value: number; const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = add16(z80.regs.ix, signedByte(offset)); value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x35, (z80: Z80) => { // dec (ix+dd) let value: number; const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = add16(z80.regs.ix, signedByte(offset)); value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x36, (z80: Z80) => { // ld (ix+dd),nn const dd = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(2); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x39, (z80: Z80) => { // add ix,sp let value: number; z80.incTStateCount(7); value = z80.regs.sp; let result = z80.regs.ix + value; const lookup = (((z80.regs.ix & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.ix); z80.regs.ix = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapDD.set(0x44, (z80: Z80) => { // ld b,ixh let value: number; value = z80.regs.ixh; z80.regs.b = value; }); decodeMapDD.set(0x45, (z80: Z80) => { // ld b,ixl let value: number; value = z80.regs.ixl; z80.regs.b = value; }); decodeMapDD.set(0x46, (z80: Z80) => { // ld b,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.b = value; }); decodeMapDD.set(0x4C, (z80: Z80) => { // ld c,ixh let value: number; value = z80.regs.ixh; z80.regs.c = value; }); decodeMapDD.set(0x4D, (z80: Z80) => { // ld c,ixl let value: number; value = z80.regs.ixl; z80.regs.c = value; }); decodeMapDD.set(0x4E, (z80: Z80) => { // ld c,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.c = value; }); decodeMapDD.set(0x54, (z80: Z80) => { // ld d,ixh let value: number; value = z80.regs.ixh; z80.regs.d = value; }); decodeMapDD.set(0x55, (z80: Z80) => { // ld d,ixl let value: number; value = z80.regs.ixl; z80.regs.d = value; }); decodeMapDD.set(0x56, (z80: Z80) => { // ld d,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.d = value; }); decodeMapDD.set(0x5C, (z80: Z80) => { // ld e,ixh let value: number; value = z80.regs.ixh; z80.regs.e = value; }); decodeMapDD.set(0x5D, (z80: Z80) => { // ld e,ixl let value: number; value = z80.regs.ixl; z80.regs.e = value; }); decodeMapDD.set(0x5E, (z80: Z80) => { // ld e,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.e = value; }); decodeMapDD.set(0x60, (z80: Z80) => { // ld ixh,b let value: number; value = z80.regs.b; z80.regs.ixh = value; }); decodeMapDD.set(0x61, (z80: Z80) => { // ld ixh,c let value: number; value = z80.regs.c; z80.regs.ixh = value; }); decodeMapDD.set(0x62, (z80: Z80) => { // ld ixh,d let value: number; value = z80.regs.d; z80.regs.ixh = value; }); decodeMapDD.set(0x63, (z80: Z80) => { // ld ixh,e let value: number; value = z80.regs.e; z80.regs.ixh = value; }); decodeMapDD.set(0x64, (z80: Z80) => { // ld ixh,ixh let value: number; value = z80.regs.ixh; z80.regs.ixh = value; }); decodeMapDD.set(0x65, (z80: Z80) => { // ld ixh,ixl let value: number; value = z80.regs.ixl; z80.regs.ixh = value; }); decodeMapDD.set(0x66, (z80: Z80) => { // ld h,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.h = value; }); decodeMapDD.set(0x67, (z80: Z80) => { // ld ixh,a let value: number; value = z80.regs.a; z80.regs.ixh = value; }); decodeMapDD.set(0x68, (z80: Z80) => { // ld ixl,b let value: number; value = z80.regs.b; z80.regs.ixl = value; }); decodeMapDD.set(0x69, (z80: Z80) => { // ld ixl,c let value: number; value = z80.regs.c; z80.regs.ixl = value; }); decodeMapDD.set(0x6A, (z80: Z80) => { // ld ixl,d let value: number; value = z80.regs.d; z80.regs.ixl = value; }); decodeMapDD.set(0x6B, (z80: Z80) => { // ld ixl,e let value: number; value = z80.regs.e; z80.regs.ixl = value; }); decodeMapDD.set(0x6C, (z80: Z80) => { // ld ixl,ixh let value: number; value = z80.regs.ixh; z80.regs.ixl = value; }); decodeMapDD.set(0x6D, (z80: Z80) => { // ld ixl,ixl let value: number; value = z80.regs.ixl; z80.regs.ixl = value; }); decodeMapDD.set(0x6E, (z80: Z80) => { // ld l,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.l = value; }); decodeMapDD.set(0x6F, (z80: Z80) => { // ld ixl,a let value: number; value = z80.regs.a; z80.regs.ixl = value; }); decodeMapDD.set(0x70, (z80: Z80) => { // ld (ix+dd),b const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.b; z80.regs.memptr = (z80.regs.ix + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x71, (z80: Z80) => { // ld (ix+dd),c const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.c; z80.regs.memptr = (z80.regs.ix + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x72, (z80: Z80) => { // ld (ix+dd),d const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.d; z80.regs.memptr = (z80.regs.ix + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x73, (z80: Z80) => { // ld (ix+dd),e const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.e; z80.regs.memptr = (z80.regs.ix + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x74, (z80: Z80) => { // ld (ix+dd),h const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.h; z80.regs.memptr = (z80.regs.ix + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x75, (z80: Z80) => { // ld (ix+dd),l const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.l; z80.regs.memptr = (z80.regs.ix + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x77, (z80: Z80) => { // ld (ix+dd),a const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.a; z80.regs.memptr = (z80.regs.ix + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapDD.set(0x7C, (z80: Z80) => { // ld a,ixh let value: number; value = z80.regs.ixh; z80.regs.a = value; }); decodeMapDD.set(0x7D, (z80: Z80) => { // ld a,ixl let value: number; value = z80.regs.ixl; z80.regs.a = value; }); decodeMapDD.set(0x7E, (z80: Z80) => { // ld a,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.a = value; }); decodeMapDD.set(0x84, (z80: Z80) => { // add a,ixh let value: number; value = z80.regs.ixh; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x85, (z80: Z80) => { // add a,ixl let value: number; value = z80.regs.ixl; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x86, (z80: Z80) => { // add a,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x8C, (z80: Z80) => { // adc a,ixh let value: number; value = z80.regs.ixh; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x8D, (z80: Z80) => { // adc a,ixl let value: number; value = z80.regs.ixl; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x8E, (z80: Z80) => { // adc a,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x94, (z80: Z80) => { // sub a,ixh let value: number; value = z80.regs.ixh; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x95, (z80: Z80) => { // sub a,ixl let value: number; value = z80.regs.ixl; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x96, (z80: Z80) => { // sub a,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x9C, (z80: Z80) => { // sbc a,ixh let value: number; value = z80.regs.ixh; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x9D, (z80: Z80) => { // sbc a,ixl let value: number; value = z80.regs.ixl; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0x9E, (z80: Z80) => { // sbc a,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapDD.set(0xA4, (z80: Z80) => { // and a,ixh let value: number; value = z80.regs.ixh; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapDD.set(0xA5, (z80: Z80) => { // and a,ixl let value: number; value = z80.regs.ixl; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapDD.set(0xA6, (z80: Z80) => { // and a,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapDD.set(0xAC, (z80: Z80) => { // xor a,ixh let value: number; value = z80.regs.ixh; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapDD.set(0xAD, (z80: Z80) => { // xor a,ixl let value: number; value = z80.regs.ixl; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapDD.set(0xAE, (z80: Z80) => { // xor a,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapDD.set(0xB4, (z80: Z80) => { // or a,ixh let value: number; value = z80.regs.ixh; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapDD.set(0xB5, (z80: Z80) => { // or a,ixl let value: number; value = z80.regs.ixl; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapDD.set(0xB6, (z80: Z80) => { // or a,(ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapDD.set(0xBC, (z80: Z80) => { // cp ixh let value: number; value = z80.regs.ixh; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapDD.set(0xBD, (z80: Z80) => { // cp ixl let value: number; value = z80.regs.ixl; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapDD.set(0xBE, (z80: Z80) => { // cp (ix+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.ix + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapDD.set(0xCB, (z80: Z80) => { // shift ddcb decodeDDCB(z80); }); decodeMapDD.set(0xE1, (z80: Z80) => { // pop ix z80.regs.ix = z80.popWord(); }); decodeMapDD.set(0xE3, (z80: Z80) => { // ex (sp),ix const rightValue = z80.regs.ix; const leftValueL = z80.readByte(z80.regs.sp); const leftValueH = z80.readByte(inc16(z80.regs.sp)); z80.incTStateCount(1); z80.writeByte(inc16(z80.regs.sp), hi(rightValue)); z80.writeByte(z80.regs.sp, lo(rightValue)); z80.incTStateCount(2); z80.regs.memptr = word(leftValueH, leftValueL); z80.regs.ix = word(leftValueH, leftValueL); }); decodeMapDD.set(0xE5, (z80: Z80) => { // push ix z80.incTStateCount(1); z80.pushWord(z80.regs.ix); }); decodeMapDD.set(0xE9, (z80: Z80) => { // jp ix z80.regs.pc = z80.regs.ix; }); decodeMapDD.set(0xF9, (z80: Z80) => { // ld sp,ix let value: number; value = z80.regs.ix; z80.incTStateCount(2); z80.regs.sp = value; }); const decodeMapDDCB = new Map<number, OpcodeFunc>(); decodeMapDDCB.set(0x00, (z80: Z80) => { // ld b,rlc z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x01, (z80: Z80) => { // ld c,rlc z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x02, (z80: Z80) => { // ld d,rlc z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x03, (z80: Z80) => { // ld e,rlc z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x04, (z80: Z80) => { // ld h,rlc z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x05, (z80: Z80) => { // ld l,rlc z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x06, (z80: Z80) => { // rlc (ix+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDDCB.set(0x07, (z80: Z80) => { // ld a,rlc z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x08, (z80: Z80) => { // ld b,rrc z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x09, (z80: Z80) => { // ld c,rrc z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x0A, (z80: Z80) => { // ld d,rrc z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x0B, (z80: Z80) => { // ld e,rrc z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x0C, (z80: Z80) => { // ld h,rrc z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x0D, (z80: Z80) => { // ld l,rrc z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x0E, (z80: Z80) => { // rrc (ix+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDDCB.set(0x0F, (z80: Z80) => { // ld a,rrc z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x10, (z80: Z80) => { // ld b,rl z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x11, (z80: Z80) => { // ld c,rl z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x12, (z80: Z80) => { // ld d,rl z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x13, (z80: Z80) => { // ld e,rl z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x14, (z80: Z80) => { // ld h,rl z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x15, (z80: Z80) => { // ld l,rl z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x16, (z80: Z80) => { // rl (ix+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDDCB.set(0x17, (z80: Z80) => { // ld a,rl z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x18, (z80: Z80) => { // ld b,rr z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x19, (z80: Z80) => { // ld c,rr z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x1A, (z80: Z80) => { // ld d,rr z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x1B, (z80: Z80) => { // ld e,rr z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x1C, (z80: Z80) => { // ld h,rr z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x1D, (z80: Z80) => { // ld l,rr z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x1E, (z80: Z80) => { // rr (ix+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDDCB.set(0x1F, (z80: Z80) => { // ld a,rr z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x20, (z80: Z80) => { // ld b,sla z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x21, (z80: Z80) => { // ld c,sla z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x22, (z80: Z80) => { // ld d,sla z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x23, (z80: Z80) => { // ld e,sla z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x24, (z80: Z80) => { // ld h,sla z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x25, (z80: Z80) => { // ld l,sla z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x26, (z80: Z80) => { // sla (ix+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDDCB.set(0x27, (z80: Z80) => { // ld a,sla z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x28, (z80: Z80) => { // ld b,sra z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x29, (z80: Z80) => { // ld c,sra z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x2A, (z80: Z80) => { // ld d,sra z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x2B, (z80: Z80) => { // ld e,sra z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x2C, (z80: Z80) => { // ld h,sra z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x2D, (z80: Z80) => { // ld l,sra z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x2E, (z80: Z80) => { // sra (ix+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDDCB.set(0x2F, (z80: Z80) => { // ld a,sra z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x30, (z80: Z80) => { // ld b,sll z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x31, (z80: Z80) => { // ld c,sll z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x32, (z80: Z80) => { // ld d,sll z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x33, (z80: Z80) => { // ld e,sll z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x34, (z80: Z80) => { // ld h,sll z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x35, (z80: Z80) => { // ld l,sll z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x36, (z80: Z80) => { // sll (ix+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDDCB.set(0x37, (z80: Z80) => { // ld a,sll z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x38, (z80: Z80) => { // ld b,srl z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x39, (z80: Z80) => { // ld c,srl z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x3A, (z80: Z80) => { // ld d,srl z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x3B, (z80: Z80) => { // ld e,srl z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x3C, (z80: Z80) => { // ld h,srl z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x3D, (z80: Z80) => { // ld l,srl z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x3E, (z80: Z80) => { // srl (ix+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapDDCB.set(0x3F, (z80: Z80) => { // ld a,srl z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x47, (z80: Z80) => { // bit 0,(ix+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapDDCB.set(0x40, decodeMapDDCB.get(0x47) as OpcodeFunc); decodeMapDDCB.set(0x41, decodeMapDDCB.get(0x47) as OpcodeFunc); decodeMapDDCB.set(0x42, decodeMapDDCB.get(0x47) as OpcodeFunc); decodeMapDDCB.set(0x43, decodeMapDDCB.get(0x47) as OpcodeFunc); decodeMapDDCB.set(0x44, decodeMapDDCB.get(0x47) as OpcodeFunc); decodeMapDDCB.set(0x45, decodeMapDDCB.get(0x47) as OpcodeFunc); decodeMapDDCB.set(0x46, decodeMapDDCB.get(0x47) as OpcodeFunc); decodeMapDDCB.set(0x4F, (z80: Z80) => { // bit 1,(ix+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapDDCB.set(0x48, decodeMapDDCB.get(0x4F) as OpcodeFunc); decodeMapDDCB.set(0x49, decodeMapDDCB.get(0x4F) as OpcodeFunc); decodeMapDDCB.set(0x4A, decodeMapDDCB.get(0x4F) as OpcodeFunc); decodeMapDDCB.set(0x4B, decodeMapDDCB.get(0x4F) as OpcodeFunc); decodeMapDDCB.set(0x4C, decodeMapDDCB.get(0x4F) as OpcodeFunc); decodeMapDDCB.set(0x4D, decodeMapDDCB.get(0x4F) as OpcodeFunc); decodeMapDDCB.set(0x4E, decodeMapDDCB.get(0x4F) as OpcodeFunc); decodeMapDDCB.set(0x57, (z80: Z80) => { // bit 2,(ix+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapDDCB.set(0x50, decodeMapDDCB.get(0x57) as OpcodeFunc); decodeMapDDCB.set(0x51, decodeMapDDCB.get(0x57) as OpcodeFunc); decodeMapDDCB.set(0x52, decodeMapDDCB.get(0x57) as OpcodeFunc); decodeMapDDCB.set(0x53, decodeMapDDCB.get(0x57) as OpcodeFunc); decodeMapDDCB.set(0x54, decodeMapDDCB.get(0x57) as OpcodeFunc); decodeMapDDCB.set(0x55, decodeMapDDCB.get(0x57) as OpcodeFunc); decodeMapDDCB.set(0x56, decodeMapDDCB.get(0x57) as OpcodeFunc); decodeMapDDCB.set(0x5F, (z80: Z80) => { // bit 3,(ix+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapDDCB.set(0x58, decodeMapDDCB.get(0x5F) as OpcodeFunc); decodeMapDDCB.set(0x59, decodeMapDDCB.get(0x5F) as OpcodeFunc); decodeMapDDCB.set(0x5A, decodeMapDDCB.get(0x5F) as OpcodeFunc); decodeMapDDCB.set(0x5B, decodeMapDDCB.get(0x5F) as OpcodeFunc); decodeMapDDCB.set(0x5C, decodeMapDDCB.get(0x5F) as OpcodeFunc); decodeMapDDCB.set(0x5D, decodeMapDDCB.get(0x5F) as OpcodeFunc); decodeMapDDCB.set(0x5E, decodeMapDDCB.get(0x5F) as OpcodeFunc); decodeMapDDCB.set(0x67, (z80: Z80) => { // bit 4,(ix+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapDDCB.set(0x60, decodeMapDDCB.get(0x67) as OpcodeFunc); decodeMapDDCB.set(0x61, decodeMapDDCB.get(0x67) as OpcodeFunc); decodeMapDDCB.set(0x62, decodeMapDDCB.get(0x67) as OpcodeFunc); decodeMapDDCB.set(0x63, decodeMapDDCB.get(0x67) as OpcodeFunc); decodeMapDDCB.set(0x64, decodeMapDDCB.get(0x67) as OpcodeFunc); decodeMapDDCB.set(0x65, decodeMapDDCB.get(0x67) as OpcodeFunc); decodeMapDDCB.set(0x66, decodeMapDDCB.get(0x67) as OpcodeFunc); decodeMapDDCB.set(0x6F, (z80: Z80) => { // bit 5,(ix+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapDDCB.set(0x68, decodeMapDDCB.get(0x6F) as OpcodeFunc); decodeMapDDCB.set(0x69, decodeMapDDCB.get(0x6F) as OpcodeFunc); decodeMapDDCB.set(0x6A, decodeMapDDCB.get(0x6F) as OpcodeFunc); decodeMapDDCB.set(0x6B, decodeMapDDCB.get(0x6F) as OpcodeFunc); decodeMapDDCB.set(0x6C, decodeMapDDCB.get(0x6F) as OpcodeFunc); decodeMapDDCB.set(0x6D, decodeMapDDCB.get(0x6F) as OpcodeFunc); decodeMapDDCB.set(0x6E, decodeMapDDCB.get(0x6F) as OpcodeFunc); decodeMapDDCB.set(0x77, (z80: Z80) => { // bit 6,(ix+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapDDCB.set(0x70, decodeMapDDCB.get(0x77) as OpcodeFunc); decodeMapDDCB.set(0x71, decodeMapDDCB.get(0x77) as OpcodeFunc); decodeMapDDCB.set(0x72, decodeMapDDCB.get(0x77) as OpcodeFunc); decodeMapDDCB.set(0x73, decodeMapDDCB.get(0x77) as OpcodeFunc); decodeMapDDCB.set(0x74, decodeMapDDCB.get(0x77) as OpcodeFunc); decodeMapDDCB.set(0x75, decodeMapDDCB.get(0x77) as OpcodeFunc); decodeMapDDCB.set(0x76, decodeMapDDCB.get(0x77) as OpcodeFunc); decodeMapDDCB.set(0x7F, (z80: Z80) => { // bit 7,(ix+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapDDCB.set(0x78, decodeMapDDCB.get(0x7F) as OpcodeFunc); decodeMapDDCB.set(0x79, decodeMapDDCB.get(0x7F) as OpcodeFunc); decodeMapDDCB.set(0x7A, decodeMapDDCB.get(0x7F) as OpcodeFunc); decodeMapDDCB.set(0x7B, decodeMapDDCB.get(0x7F) as OpcodeFunc); decodeMapDDCB.set(0x7C, decodeMapDDCB.get(0x7F) as OpcodeFunc); decodeMapDDCB.set(0x7D, decodeMapDDCB.get(0x7F) as OpcodeFunc); decodeMapDDCB.set(0x7E, decodeMapDDCB.get(0x7F) as OpcodeFunc); decodeMapDDCB.set(0x80, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x81, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x82, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x83, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x84, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x85, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x86, (z80: Z80) => { // res 0,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xFE); }); decodeMapDDCB.set(0x87, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x88, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x89, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x8A, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x8B, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x8C, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x8D, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x8E, (z80: Z80) => { // res 1,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xFD); }); decodeMapDDCB.set(0x8F, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x90, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x91, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x92, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x93, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x94, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x95, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x96, (z80: Z80) => { // res 2,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xFB); }); decodeMapDDCB.set(0x97, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0x98, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0x99, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0x9A, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0x9B, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0x9C, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0x9D, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0x9E, (z80: Z80) => { // res 3,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xF7); }); decodeMapDDCB.set(0x9F, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xA0, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xA1, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xA2, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xA3, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xA4, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xA5, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xA6, (z80: Z80) => { // res 4,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xEF); }); decodeMapDDCB.set(0xA7, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xA8, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xA9, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xAA, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xAB, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xAC, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xAD, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xAE, (z80: Z80) => { // res 5,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xDF); }); decodeMapDDCB.set(0xAF, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xB0, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xB1, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xB2, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xB3, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xB4, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xB5, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xB6, (z80: Z80) => { // res 6,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xBF); }); decodeMapDDCB.set(0xB7, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xB8, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xB9, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xBA, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xBB, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xBC, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xBD, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xBE, (z80: Z80) => { // res 7,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0x7F); }); decodeMapDDCB.set(0xBF, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xC0, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xC1, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xC2, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xC3, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xC4, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xC5, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xC6, (z80: Z80) => { // set 0,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x01); }); decodeMapDDCB.set(0xC7, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xC8, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xC9, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xCA, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xCB, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xCC, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xCD, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xCE, (z80: Z80) => { // set 1,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x02); }); decodeMapDDCB.set(0xCF, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xD0, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xD1, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xD2, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xD3, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xD4, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xD5, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xD6, (z80: Z80) => { // set 2,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x04); }); decodeMapDDCB.set(0xD7, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xD8, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xD9, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xDA, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xDB, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xDC, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xDD, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xDE, (z80: Z80) => { // set 3,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x08); }); decodeMapDDCB.set(0xDF, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xE0, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xE1, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xE2, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xE3, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xE4, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xE5, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xE6, (z80: Z80) => { // set 4,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x10); }); decodeMapDDCB.set(0xE7, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xE8, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xE9, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xEA, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xEB, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xEC, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xED, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xEE, (z80: Z80) => { // set 5,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x20); }); decodeMapDDCB.set(0xEF, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xF0, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xF1, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xF2, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xF3, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xF4, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xF5, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xF6, (z80: Z80) => { // set 6,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x40); }); decodeMapDDCB.set(0xF7, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapDDCB.set(0xF8, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapDDCB.set(0xF9, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapDDCB.set(0xFA, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapDDCB.set(0xFB, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapDDCB.set(0xFC, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapDDCB.set(0xFD, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapDDCB.set(0xFE, (z80: Z80) => { // set 7,(ix+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x80); }); decodeMapDDCB.set(0xFF, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); const decodeMapED = new Map<number, OpcodeFunc>(); decodeMapED.set(0x40, (z80: Z80) => { // in b,(c) z80.regs.memptr = inc16(z80.regs.bc); z80.regs.b = z80.readPort(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.b]; }); decodeMapED.set(0x41, (z80: Z80) => { // out (c),b z80.writePort(z80.regs.bc, z80.regs.b); z80.regs.memptr = inc16(z80.regs.bc); }); decodeMapED.set(0x42, (z80: Z80) => { // sbc hl,bc let value: number; z80.incTStateCount(7); value = z80.regs.bc; let result = z80.regs.hl - value; if ((z80.regs.f & Flag.C) !== 0) { result -= 1; } const lookup = (((z80.regs.hl & 0x8800) >> 11) | ((value & 0x8800) >> 10) | ((result & 0x8800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | Flag.N | overflowSubTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarrySubTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z); }); decodeMapED.set(0x43, (z80: Z80) => { // ld (nnnn),bc let value: number; value = z80.regs.bc; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); z80.writeByte(addr, lo(value)); addr = inc16(addr); z80.regs.memptr = addr; z80.writeByte(addr, hi(value)); }); decodeMapED.set(0x7C, (z80: Z80) => { // neg const value = z80.regs.a; z80.regs.a = 0; const diff = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; z80.regs.a = diff; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= z80.sz53Table[z80.regs.a]; z80.regs.f = f; }); decodeMapED.set(0x44, decodeMapED.get(0x7C) as OpcodeFunc); decodeMapED.set(0x4C, decodeMapED.get(0x7C) as OpcodeFunc); decodeMapED.set(0x54, decodeMapED.get(0x7C) as OpcodeFunc); decodeMapED.set(0x5C, decodeMapED.get(0x7C) as OpcodeFunc); decodeMapED.set(0x64, decodeMapED.get(0x7C) as OpcodeFunc); decodeMapED.set(0x6C, decodeMapED.get(0x7C) as OpcodeFunc); decodeMapED.set(0x74, decodeMapED.get(0x7C) as OpcodeFunc); decodeMapED.set(0x7D, (z80: Z80) => { // retn z80.regs.iff1 = z80.regs.iff2; z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; }); decodeMapED.set(0x45, decodeMapED.get(0x7D) as OpcodeFunc); decodeMapED.set(0x55, decodeMapED.get(0x7D) as OpcodeFunc); decodeMapED.set(0x5D, decodeMapED.get(0x7D) as OpcodeFunc); decodeMapED.set(0x65, decodeMapED.get(0x7D) as OpcodeFunc); decodeMapED.set(0x6D, decodeMapED.get(0x7D) as OpcodeFunc); decodeMapED.set(0x75, decodeMapED.get(0x7D) as OpcodeFunc); decodeMapED.set(0x6E, (z80: Z80) => { // im 0 z80.regs.im = 0; }); decodeMapED.set(0x46, decodeMapED.get(0x6E) as OpcodeFunc); decodeMapED.set(0x4E, decodeMapED.get(0x6E) as OpcodeFunc); decodeMapED.set(0x66, decodeMapED.get(0x6E) as OpcodeFunc); decodeMapED.set(0x47, (z80: Z80) => { // ld i,a let value: number; value = z80.regs.a; z80.incTStateCount(1); z80.regs.i = value; }); decodeMapED.set(0x48, (z80: Z80) => { // in c,(c) z80.regs.memptr = inc16(z80.regs.bc); z80.regs.c = z80.readPort(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.c]; }); decodeMapED.set(0x49, (z80: Z80) => { // out (c),c z80.writePort(z80.regs.bc, z80.regs.c); z80.regs.memptr = inc16(z80.regs.bc); }); decodeMapED.set(0x4A, (z80: Z80) => { // adc hl,bc let value: number; z80.incTStateCount(7); value = z80.regs.bc; let result = z80.regs.hl + value; if ((z80.regs.f & Flag.C) !== 0) { result += 1; } const lookup = (((z80.regs.hl & 0x8800) >> 11) | ((value & 0x8800) >> 10) | ((result & 0x8800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | overflowAddTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarryAddTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z); }); decodeMapED.set(0x4B, (z80: Z80) => { // ld bc,(nnnn) let value: number; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); value = z80.readByte(addr); z80.regs.memptr = inc16(addr); value = word(z80.readByte(z80.regs.memptr), value); z80.regs.bc = value; }); decodeMapED.set(0x4D, (z80: Z80) => { // reti z80.regs.iff1 = z80.regs.iff2; z80.regs.pc = z80.popWord(); z80.regs.memptr = z80.regs.pc; }); decodeMapED.set(0x4F, (z80: Z80) => { // ld r,a let value: number; value = z80.regs.a; z80.incTStateCount(1); z80.regs.r = value; }); decodeMapED.set(0x50, (z80: Z80) => { // in d,(c) z80.regs.memptr = inc16(z80.regs.bc); z80.regs.d = z80.readPort(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.d]; }); decodeMapED.set(0x51, (z80: Z80) => { // out (c),d z80.writePort(z80.regs.bc, z80.regs.d); z80.regs.memptr = inc16(z80.regs.bc); }); decodeMapED.set(0x52, (z80: Z80) => { // sbc hl,de let value: number; z80.incTStateCount(7); value = z80.regs.de; let result = z80.regs.hl - value; if ((z80.regs.f & Flag.C) !== 0) { result -= 1; } const lookup = (((z80.regs.hl & 0x8800) >> 11) | ((value & 0x8800) >> 10) | ((result & 0x8800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | Flag.N | overflowSubTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarrySubTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z); }); decodeMapED.set(0x53, (z80: Z80) => { // ld (nnnn),de let value: number; value = z80.regs.de; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); z80.writeByte(addr, lo(value)); addr = inc16(addr); z80.regs.memptr = addr; z80.writeByte(addr, hi(value)); }); decodeMapED.set(0x76, (z80: Z80) => { // im 1 z80.regs.im = 1; }); decodeMapED.set(0x56, decodeMapED.get(0x76) as OpcodeFunc); decodeMapED.set(0x57, (z80: Z80) => { // ld a,i let value: number; value = z80.regs.i; z80.incTStateCount(1); z80.regs.a = value; z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53Table[z80.regs.a] | (z80.regs.iff2 ? Flag.V : 0); }); decodeMapED.set(0x58, (z80: Z80) => { // in e,(c) z80.regs.memptr = inc16(z80.regs.bc); z80.regs.e = z80.readPort(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.e]; }); decodeMapED.set(0x59, (z80: Z80) => { // out (c),e z80.writePort(z80.regs.bc, z80.regs.e); z80.regs.memptr = inc16(z80.regs.bc); }); decodeMapED.set(0x5A, (z80: Z80) => { // adc hl,de let value: number; z80.incTStateCount(7); value = z80.regs.de; let result = z80.regs.hl + value; if ((z80.regs.f & Flag.C) !== 0) { result += 1; } const lookup = (((z80.regs.hl & 0x8800) >> 11) | ((value & 0x8800) >> 10) | ((result & 0x8800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | overflowAddTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarryAddTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z); }); decodeMapED.set(0x5B, (z80: Z80) => { // ld de,(nnnn) let value: number; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); value = z80.readByte(addr); z80.regs.memptr = inc16(addr); value = word(z80.readByte(z80.regs.memptr), value); z80.regs.de = value; }); decodeMapED.set(0x7E, (z80: Z80) => { // im 2 z80.regs.im = 2; }); decodeMapED.set(0x5E, decodeMapED.get(0x7E) as OpcodeFunc); decodeMapED.set(0x5F, (z80: Z80) => { // ld a,r let value: number; value = z80.regs.rCombined; z80.incTStateCount(1); z80.regs.a = value; z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53Table[z80.regs.a] | (z80.regs.iff2 ? Flag.V : 0); }); decodeMapED.set(0x60, (z80: Z80) => { // in h,(c) z80.regs.memptr = inc16(z80.regs.bc); z80.regs.h = z80.readPort(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.h]; }); decodeMapED.set(0x61, (z80: Z80) => { // out (c),h z80.writePort(z80.regs.bc, z80.regs.h); z80.regs.memptr = inc16(z80.regs.bc); }); decodeMapED.set(0x62, (z80: Z80) => { // sbc hl,hl let value: number; z80.incTStateCount(7); value = z80.regs.hl; let result = z80.regs.hl - value; if ((z80.regs.f & Flag.C) !== 0) { result -= 1; } const lookup = (((z80.regs.hl & 0x8800) >> 11) | ((value & 0x8800) >> 10) | ((result & 0x8800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | Flag.N | overflowSubTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarrySubTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z); }); decodeMapED.set(0x63, (z80: Z80) => { // ld (nnnn),hl let value: number; value = z80.regs.hl; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); z80.writeByte(addr, lo(value)); addr = inc16(addr); z80.regs.memptr = addr; z80.writeByte(addr, hi(value)); }); decodeMapED.set(0x67, (z80: Z80) => { // rrd const tmp = z80.readByte(z80.regs.hl); z80.incTStateCount(4); z80.writeByte(z80.regs.hl, ((z80.regs.a << 4) | (tmp >> 4)) & 0xFF); z80.regs.a = (z80.regs.a & 0xF0) | (tmp & 0x0F); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.a]; z80.regs.memptr = inc16(z80.regs.hl); }); decodeMapED.set(0x68, (z80: Z80) => { // in l,(c) z80.regs.memptr = inc16(z80.regs.bc); z80.regs.l = z80.readPort(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.l]; }); decodeMapED.set(0x69, (z80: Z80) => { // out (c),l z80.writePort(z80.regs.bc, z80.regs.l); z80.regs.memptr = inc16(z80.regs.bc); }); decodeMapED.set(0x6A, (z80: Z80) => { // adc hl,hl let value: number; z80.incTStateCount(7); value = z80.regs.hl; let result = z80.regs.hl + value; if ((z80.regs.f & Flag.C) !== 0) { result += 1; } const lookup = (((z80.regs.hl & 0x8800) >> 11) | ((value & 0x8800) >> 10) | ((result & 0x8800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | overflowAddTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarryAddTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z); }); decodeMapED.set(0x6B, (z80: Z80) => { // ld hl,(nnnn) let value: number; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); value = z80.readByte(addr); z80.regs.memptr = inc16(addr); value = word(z80.readByte(z80.regs.memptr), value); z80.regs.hl = value; }); decodeMapED.set(0x6F, (z80: Z80) => { // rld const tmp = z80.readByte(z80.regs.hl); z80.incTStateCount(4); z80.writeByte(z80.regs.hl, ((tmp << 4) | (z80.regs.a & 0x0F)) & 0xFF); z80.regs.a = (z80.regs.a & 0xF0) | (tmp >> 4); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.a]; z80.regs.memptr = inc16(z80.regs.hl); }); decodeMapED.set(0x70, (z80: Z80) => { // in f,(c) z80.regs.memptr = inc16(z80.regs.bc); z80.regs.f = z80.readPort(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.f]; }); decodeMapED.set(0x71, (z80: Z80) => { // out (c),0 z80.writePort(z80.regs.bc, 0x00); z80.regs.memptr = inc16(z80.regs.bc); }); decodeMapED.set(0x72, (z80: Z80) => { // sbc hl,sp let value: number; z80.incTStateCount(7); value = z80.regs.sp; let result = z80.regs.hl - value; if ((z80.regs.f & Flag.C) !== 0) { result -= 1; } const lookup = (((z80.regs.hl & 0x8800) >> 11) | ((value & 0x8800) >> 10) | ((result & 0x8800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | Flag.N | overflowSubTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarrySubTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z); }); decodeMapED.set(0x73, (z80: Z80) => { // ld (nnnn),sp let value: number; value = z80.regs.sp; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); z80.writeByte(addr, lo(value)); addr = inc16(addr); z80.regs.memptr = addr; z80.writeByte(addr, hi(value)); }); decodeMapED.set(0x78, (z80: Z80) => { // in a,(c) z80.regs.memptr = inc16(z80.regs.bc); z80.regs.a = z80.readPort(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.a]; }); decodeMapED.set(0x79, (z80: Z80) => { // out (c),a z80.writePort(z80.regs.bc, z80.regs.a); z80.regs.memptr = inc16(z80.regs.bc); }); decodeMapED.set(0x7A, (z80: Z80) => { // adc hl,sp let value: number; z80.incTStateCount(7); value = z80.regs.sp; let result = z80.regs.hl + value; if ((z80.regs.f & Flag.C) !== 0) { result += 1; } const lookup = (((z80.regs.hl & 0x8800) >> 11) | ((value & 0x8800) >> 10) | ((result & 0x8800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.hl); z80.regs.hl = result & 0xFFFF; z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | overflowAddTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarryAddTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z); }); decodeMapED.set(0x7B, (z80: Z80) => { // ld sp,(nnnn) let value: number; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); value = z80.readByte(addr); z80.regs.memptr = inc16(addr); value = word(z80.readByte(z80.regs.memptr), value); z80.regs.sp = value; }); decodeMapED.set(0xA0, (z80: Z80) => { // ldi let value = z80.readByte(z80.regs.hl); z80.writeByte(z80.regs.de, value); z80.incTStateCount(2); z80.regs.bc = dec16(z80.regs.bc); value = add16(value, z80.regs.a); z80.regs.f = (z80.regs.f & (Flag.C | Flag.Z | Flag.S)) | (z80.regs.bc !== 0 ? Flag.V : 0) | (value & Flag.X3) | ((value & 0x02) !== 0 ? Flag.X5 : 0) z80.regs.hl = inc16(z80.regs.hl); z80.regs.de = inc16(z80.regs.de); }); decodeMapED.set(0xA1, (z80: Z80) => { // cpi const value = z80.readByte(z80.regs.hl); let diff = (z80.regs.a - value) & 0xFF; const lookup = ((z80.regs.a & 0x08) >> 3) | ((value & 0x08) >> 2) | ((diff & 0x08) >> 1); z80.incTStateCount(5); z80.regs.bc = dec16(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | (z80.regs.bc !== 0 ? Flag.V : 0) | Flag.N | halfCarrySubTable[lookup] | (diff !== 0 ? 0 : Flag.Z) | (diff & Flag.S); if ((z80.regs.f & Flag.H) !== 0) diff = dec8(diff); z80.regs.f |= (diff & Flag.X3) | (((diff & 0x02) !== 0) ? Flag.X5 : 0); z80.regs.memptr = inc16(z80.regs.memptr); z80.regs.hl = inc16(z80.regs.hl); }); decodeMapED.set(0xA2, (z80: Z80) => { // ini z80.incTStateCount(1); const value = z80.readPort(z80.regs.bc); z80.writeByte(z80.regs.hl, value); z80.regs.memptr = inc16(z80.regs.bc); z80.regs.b = dec8(z80.regs.b); const other = inc8(add8(value, z80.regs.c)); z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b]; z80.regs.hl = inc16(z80.regs.hl); }); decodeMapED.set(0xA3, (z80: Z80) => { // outi z80.incTStateCount(1); const value = z80.readByte(z80.regs.hl); z80.regs.b = dec8(z80.regs.b); z80.regs.memptr = inc16(z80.regs.bc); z80.writePort(z80.regs.bc, value); z80.regs.hl = inc16(z80.regs.hl); const other = add8(value, z80.regs.l); z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b]; }); decodeMapED.set(0xA8, (z80: Z80) => { // ldd let value = z80.readByte(z80.regs.hl); z80.writeByte(z80.regs.de, value); z80.incTStateCount(2); z80.regs.bc = dec16(z80.regs.bc); value = add16(value, z80.regs.a); z80.regs.f = (z80.regs.f & (Flag.C | Flag.Z | Flag.S)) | (z80.regs.bc !== 0 ? Flag.V : 0) | (value & Flag.X3) | ((value & 0x02) !== 0 ? Flag.X5 : 0) z80.regs.hl = dec16(z80.regs.hl); z80.regs.de = dec16(z80.regs.de); }); decodeMapED.set(0xA9, (z80: Z80) => { // cpd const value = z80.readByte(z80.regs.hl); let diff = (z80.regs.a - value) & 0xFF; const lookup = ((z80.regs.a & 0x08) >> 3) | ((value & 0x08) >> 2) | ((diff & 0x08) >> 1); z80.incTStateCount(5); z80.regs.bc = dec16(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | (z80.regs.bc !== 0 ? Flag.V : 0) | Flag.N | halfCarrySubTable[lookup] | (diff !== 0 ? 0 : Flag.Z) | (diff & Flag.S); if ((z80.regs.f & Flag.H) !== 0) diff = dec8(diff); z80.regs.f |= (diff & Flag.X3) | (((diff & 0x02) !== 0) ? Flag.X5 : 0); z80.regs.memptr = dec16(z80.regs.memptr); z80.regs.hl = dec16(z80.regs.hl); }); decodeMapED.set(0xAA, (z80: Z80) => { // ind z80.incTStateCount(1); const value = z80.readPort(z80.regs.bc); z80.writeByte(z80.regs.hl, value); z80.regs.memptr = dec16(z80.regs.bc); z80.regs.b = dec8(z80.regs.b); const other = dec8(add8(value, z80.regs.c)); z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b]; z80.regs.hl = dec16(z80.regs.hl); }); decodeMapED.set(0xAB, (z80: Z80) => { // outd z80.incTStateCount(1); const value = z80.readByte(z80.regs.hl); z80.regs.b = dec8(z80.regs.b); z80.regs.memptr = dec16(z80.regs.bc); z80.writePort(z80.regs.bc, value); z80.regs.hl = dec16(z80.regs.hl); const other = add8(value, z80.regs.l); z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b]; }); decodeMapED.set(0xB0, (z80: Z80) => { // ldir let value = z80.readByte(z80.regs.hl); z80.writeByte(z80.regs.de, value); z80.incTStateCount(2); z80.regs.bc = dec16(z80.regs.bc); value = add16(value, z80.regs.a); z80.regs.f = (z80.regs.f & (Flag.C | Flag.Z | Flag.S)) | (z80.regs.bc !== 0 ? Flag.V : 0) | (value & Flag.X3) | ((value & 0x02) !== 0 ? Flag.X5 : 0) if (z80.regs.bc !== 0) { z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, -2); z80.regs.memptr = add16(z80.regs.pc, 1); } z80.regs.hl = inc16(z80.regs.hl); z80.regs.de = inc16(z80.regs.de); }); decodeMapED.set(0xB1, (z80: Z80) => { // cpir const value = z80.readByte(z80.regs.hl); let diff = (z80.regs.a - value) & 0xFF; const lookup = ((z80.regs.a & 0x08) >> 3) | ((value & 0x08) >> 2) | ((diff & 0x08) >> 1); z80.incTStateCount(5); z80.regs.bc = dec16(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | (z80.regs.bc !== 0 ? Flag.V : 0) | Flag.N | halfCarrySubTable[lookup] | (diff !== 0 ? 0 : Flag.Z) | (diff & Flag.S); if ((z80.regs.f & Flag.H) !== 0) diff = dec8(diff); z80.regs.f |= (diff & Flag.X3) | (((diff & 0x02) !== 0) ? Flag.X5 : 0); if ((z80.regs.f & (Flag.V | Flag.Z)) === Flag.V) { z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, -2); z80.regs.memptr = add16(z80.regs.pc, 1); } else { z80.regs.memptr = inc16(z80.regs.memptr); } z80.regs.hl = inc16(z80.regs.hl); }); decodeMapED.set(0xB2, (z80: Z80) => { // inir z80.incTStateCount(1); const value = z80.readPort(z80.regs.bc); z80.writeByte(z80.regs.hl, value); z80.regs.memptr = inc16(z80.regs.bc); z80.regs.b = dec8(z80.regs.b); const other = inc8(add8(value, z80.regs.c)); z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b]; if (z80.regs.b > 0) { z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, -2); } z80.regs.hl = inc16(z80.regs.hl); }); decodeMapED.set(0xB3, (z80: Z80) => { // otir z80.incTStateCount(1); const value = z80.readByte(z80.regs.hl); z80.regs.b = dec8(z80.regs.b); z80.regs.memptr = inc16(z80.regs.bc); z80.writePort(z80.regs.bc, value); z80.regs.hl = inc16(z80.regs.hl); const other = add8(value, z80.regs.l); z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b]; if (z80.regs.b > 0) { z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, -2); } }); decodeMapED.set(0xB8, (z80: Z80) => { // lddr let value = z80.readByte(z80.regs.hl); z80.writeByte(z80.regs.de, value); z80.incTStateCount(2); z80.regs.bc = dec16(z80.regs.bc); value = add16(value, z80.regs.a); z80.regs.f = (z80.regs.f & (Flag.C | Flag.Z | Flag.S)) | (z80.regs.bc !== 0 ? Flag.V : 0) | (value & Flag.X3) | ((value & 0x02) !== 0 ? Flag.X5 : 0) if (z80.regs.bc !== 0) { z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, -2); z80.regs.memptr = add16(z80.regs.pc, 1); } z80.regs.hl = dec16(z80.regs.hl); z80.regs.de = dec16(z80.regs.de); }); decodeMapED.set(0xB9, (z80: Z80) => { // cpdr const value = z80.readByte(z80.regs.hl); let diff = (z80.regs.a - value) & 0xFF; const lookup = ((z80.regs.a & 0x08) >> 3) | ((value & 0x08) >> 2) | ((diff & 0x08) >> 1); z80.incTStateCount(5); z80.regs.bc = dec16(z80.regs.bc); z80.regs.f = (z80.regs.f & Flag.C) | (z80.regs.bc !== 0 ? Flag.V : 0) | Flag.N | halfCarrySubTable[lookup] | (diff !== 0 ? 0 : Flag.Z) | (diff & Flag.S); if ((z80.regs.f & Flag.H) !== 0) diff = dec8(diff); z80.regs.f |= (diff & Flag.X3) | (((diff & 0x02) !== 0) ? Flag.X5 : 0); if ((z80.regs.f & (Flag.V | Flag.Z)) === Flag.V) { z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, -2); z80.regs.memptr = add16(z80.regs.pc, 1); } else { z80.regs.memptr = dec16(z80.regs.memptr); } z80.regs.hl = dec16(z80.regs.hl); }); decodeMapED.set(0xBA, (z80: Z80) => { // indr z80.incTStateCount(1); const value = z80.readPort(z80.regs.bc); z80.writeByte(z80.regs.hl, value); z80.regs.memptr = dec16(z80.regs.bc); z80.regs.b = dec8(z80.regs.b); const other = dec8(add8(value, z80.regs.c)); z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b]; if (z80.regs.b > 0) { z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, -2); } z80.regs.hl = dec16(z80.regs.hl); }); decodeMapED.set(0xBB, (z80: Z80) => { // otdr z80.incTStateCount(1); const value = z80.readByte(z80.regs.hl); z80.regs.b = dec8(z80.regs.b); z80.regs.memptr = dec16(z80.regs.bc); z80.writePort(z80.regs.bc, value); z80.regs.hl = dec16(z80.regs.hl); const other = add8(value, z80.regs.l); z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b]; if (z80.regs.b > 0) { z80.incTStateCount(5); z80.regs.pc = add16(z80.regs.pc, -2); } }); const decodeMapFD = new Map<number, OpcodeFunc>(); decodeMapFD.set(0x09, (z80: Z80) => { // add iy,bc let value: number; z80.incTStateCount(7); value = z80.regs.bc; let result = z80.regs.iy + value; const lookup = (((z80.regs.iy & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.iy); z80.regs.iy = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapFD.set(0x19, (z80: Z80) => { // add iy,de let value: number; z80.incTStateCount(7); value = z80.regs.de; let result = z80.regs.iy + value; const lookup = (((z80.regs.iy & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.iy); z80.regs.iy = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapFD.set(0x21, (z80: Z80) => { // ld iy,nnnn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); value = word(z80.readByte(z80.regs.pc), value); z80.regs.pc = inc16(z80.regs.pc); z80.regs.iy = value; }); decodeMapFD.set(0x22, (z80: Z80) => { // ld (nnnn),iy let value: number; value = z80.regs.iy; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); z80.writeByte(addr, lo(value)); addr = inc16(addr); z80.regs.memptr = addr; z80.writeByte(addr, hi(value)); }); decodeMapFD.set(0x23, (z80: Z80) => { // inc iy let value: number; value = z80.regs.iy; const oldValue = value; z80.incTStateCount(2); value = inc16(value); z80.regs.iy = value; }); decodeMapFD.set(0x24, (z80: Z80) => { // inc iyh let value: number; value = z80.regs.iyh; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.iyh = value; }); decodeMapFD.set(0x25, (z80: Z80) => { // dec iyh let value: number; value = z80.regs.iyh; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.iyh = value; }); decodeMapFD.set(0x26, (z80: Z80) => { // ld iyh,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.iyh = value; }); decodeMapFD.set(0x29, (z80: Z80) => { // add iy,iy let value: number; z80.incTStateCount(7); value = z80.regs.iy; let result = z80.regs.iy + value; const lookup = (((z80.regs.iy & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.iy); z80.regs.iy = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapFD.set(0x2A, (z80: Z80) => { // ld iy,(nnnn) let value: number; let addr = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); addr = word(z80.readByte(z80.regs.pc), addr); z80.regs.pc = inc16(z80.regs.pc); value = z80.readByte(addr); z80.regs.memptr = inc16(addr); value = word(z80.readByte(z80.regs.memptr), value); z80.regs.iy = value; }); decodeMapFD.set(0x2B, (z80: Z80) => { // dec iy let value: number; value = z80.regs.iy; const oldValue = value; z80.incTStateCount(2); value = dec16(value); z80.regs.iy = value; }); decodeMapFD.set(0x2C, (z80: Z80) => { // inc iyl let value: number; value = z80.regs.iyl; const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.regs.iyl = value; }); decodeMapFD.set(0x2D, (z80: Z80) => { // dec iyl let value: number; value = z80.regs.iyl; const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.regs.iyl = value; }); decodeMapFD.set(0x2E, (z80: Z80) => { // ld iyl,nn let value: number; value = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); z80.regs.iyl = value; }); decodeMapFD.set(0x34, (z80: Z80) => { // inc (iy+dd) let value: number; const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = add16(z80.regs.iy, signedByte(offset)); value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = inc8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x35, (z80: Z80) => { // dec (iy+dd) let value: number; const offset = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = add16(z80.regs.iy, signedByte(offset)); value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = dec8(value); z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x36, (z80: Z80) => { // ld (iy+dd),nn const dd = z80.readByte(z80.regs.pc); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(2); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x39, (z80: Z80) => { // add iy,sp let value: number; z80.incTStateCount(7); value = z80.regs.sp; let result = z80.regs.iy + value; const lookup = (((z80.regs.iy & 0x0800) >> 11) | ((value & 0x0800) >> 10) | ((result & 0x0800) >> 9)) & 0xFF; z80.regs.memptr = inc16(z80.regs.iy); z80.regs.iy = result & 0xFFFF; z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup]; }); decodeMapFD.set(0x44, (z80: Z80) => { // ld b,iyh let value: number; value = z80.regs.iyh; z80.regs.b = value; }); decodeMapFD.set(0x45, (z80: Z80) => { // ld b,iyl let value: number; value = z80.regs.iyl; z80.regs.b = value; }); decodeMapFD.set(0x46, (z80: Z80) => { // ld b,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.b = value; }); decodeMapFD.set(0x4C, (z80: Z80) => { // ld c,iyh let value: number; value = z80.regs.iyh; z80.regs.c = value; }); decodeMapFD.set(0x4D, (z80: Z80) => { // ld c,iyl let value: number; value = z80.regs.iyl; z80.regs.c = value; }); decodeMapFD.set(0x4E, (z80: Z80) => { // ld c,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.c = value; }); decodeMapFD.set(0x54, (z80: Z80) => { // ld d,iyh let value: number; value = z80.regs.iyh; z80.regs.d = value; }); decodeMapFD.set(0x55, (z80: Z80) => { // ld d,iyl let value: number; value = z80.regs.iyl; z80.regs.d = value; }); decodeMapFD.set(0x56, (z80: Z80) => { // ld d,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.d = value; }); decodeMapFD.set(0x5C, (z80: Z80) => { // ld e,iyh let value: number; value = z80.regs.iyh; z80.regs.e = value; }); decodeMapFD.set(0x5D, (z80: Z80) => { // ld e,iyl let value: number; value = z80.regs.iyl; z80.regs.e = value; }); decodeMapFD.set(0x5E, (z80: Z80) => { // ld e,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.e = value; }); decodeMapFD.set(0x60, (z80: Z80) => { // ld iyh,b let value: number; value = z80.regs.b; z80.regs.iyh = value; }); decodeMapFD.set(0x61, (z80: Z80) => { // ld iyh,c let value: number; value = z80.regs.c; z80.regs.iyh = value; }); decodeMapFD.set(0x62, (z80: Z80) => { // ld iyh,d let value: number; value = z80.regs.d; z80.regs.iyh = value; }); decodeMapFD.set(0x63, (z80: Z80) => { // ld iyh,e let value: number; value = z80.regs.e; z80.regs.iyh = value; }); decodeMapFD.set(0x64, (z80: Z80) => { // ld iyh,iyh let value: number; value = z80.regs.iyh; z80.regs.iyh = value; }); decodeMapFD.set(0x65, (z80: Z80) => { // ld iyh,iyl let value: number; value = z80.regs.iyl; z80.regs.iyh = value; }); decodeMapFD.set(0x66, (z80: Z80) => { // ld h,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.h = value; }); decodeMapFD.set(0x67, (z80: Z80) => { // ld iyh,a let value: number; value = z80.regs.a; z80.regs.iyh = value; }); decodeMapFD.set(0x68, (z80: Z80) => { // ld iyl,b let value: number; value = z80.regs.b; z80.regs.iyl = value; }); decodeMapFD.set(0x69, (z80: Z80) => { // ld iyl,c let value: number; value = z80.regs.c; z80.regs.iyl = value; }); decodeMapFD.set(0x6A, (z80: Z80) => { // ld iyl,d let value: number; value = z80.regs.d; z80.regs.iyl = value; }); decodeMapFD.set(0x6B, (z80: Z80) => { // ld iyl,e let value: number; value = z80.regs.e; z80.regs.iyl = value; }); decodeMapFD.set(0x6C, (z80: Z80) => { // ld iyl,iyh let value: number; value = z80.regs.iyh; z80.regs.iyl = value; }); decodeMapFD.set(0x6D, (z80: Z80) => { // ld iyl,iyl let value: number; value = z80.regs.iyl; z80.regs.iyl = value; }); decodeMapFD.set(0x6E, (z80: Z80) => { // ld l,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.l = value; }); decodeMapFD.set(0x6F, (z80: Z80) => { // ld iyl,a let value: number; value = z80.regs.a; z80.regs.iyl = value; }); decodeMapFD.set(0x70, (z80: Z80) => { // ld (iy+dd),b const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.b; z80.regs.memptr = (z80.regs.iy + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x71, (z80: Z80) => { // ld (iy+dd),c const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.c; z80.regs.memptr = (z80.regs.iy + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x72, (z80: Z80) => { // ld (iy+dd),d const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.d; z80.regs.memptr = (z80.regs.iy + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x73, (z80: Z80) => { // ld (iy+dd),e const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.e; z80.regs.memptr = (z80.regs.iy + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x74, (z80: Z80) => { // ld (iy+dd),h const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.h; z80.regs.memptr = (z80.regs.iy + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x75, (z80: Z80) => { // ld (iy+dd),l const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.l; z80.regs.memptr = (z80.regs.iy + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x77, (z80: Z80) => { // ld (iy+dd),a const dd = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); let value: number; value = z80.regs.a; z80.regs.memptr = (z80.regs.iy + signedByte(dd)) & 0xFFFF; z80.writeByte(z80.regs.memptr, value); }); decodeMapFD.set(0x7C, (z80: Z80) => { // ld a,iyh let value: number; value = z80.regs.iyh; z80.regs.a = value; }); decodeMapFD.set(0x7D, (z80: Z80) => { // ld a,iyl let value: number; value = z80.regs.iyl; z80.regs.a = value; }); decodeMapFD.set(0x7E, (z80: Z80) => { // ld a,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.a = value; }); decodeMapFD.set(0x84, (z80: Z80) => { // add a,iyh let value: number; value = z80.regs.iyh; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x85, (z80: Z80) => { // add a,iyl let value: number; value = z80.regs.iyl; let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x86, (z80: Z80) => { // add a,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); let result = add16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x8C, (z80: Z80) => { // adc a,iyh let value: number; value = z80.regs.iyh; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x8D, (z80: Z80) => { // adc a,iyl let value: number; value = z80.regs.iyl; let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x8E, (z80: Z80) => { // adc a,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); let result = add16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = inc16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | halfCarryAddTable[lookup & 0x07] | overflowAddTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x94, (z80: Z80) => { // sub a,iyh let value: number; value = z80.regs.iyh; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x95, (z80: Z80) => { // sub a,iyl let value: number; value = z80.regs.iyl; let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x96, (z80: Z80) => { // sub a,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); let result = sub16(z80.regs.a, value); const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x9C, (z80: Z80) => { // sbc a,iyh let value: number; value = z80.regs.iyh; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x9D, (z80: Z80) => { // sbc a,iyl let value: number; value = z80.regs.iyl; let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0x9E, (z80: Z80) => { // sbc a,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); let result = sub16(z80.regs.a, value); if ((z80.regs.f & Flag.C) !== 0) { result = dec16(result); } const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((result & 0x88) >> 1)) & 0xFF; z80.regs.a = result & 0xFF; z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) | Flag.N | halfCarrySubTable[lookup & 0x07] | overflowSubTable[lookup >> 4] | z80.sz53Table[z80.regs.a]; }); decodeMapFD.set(0xA4, (z80: Z80) => { // and a,iyh let value: number; value = z80.regs.iyh; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapFD.set(0xA5, (z80: Z80) => { // and a,iyl let value: number; value = z80.regs.iyl; z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapFD.set(0xA6, (z80: Z80) => { // and a,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.a &= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; z80.regs.f |= Flag.H; }); decodeMapFD.set(0xAC, (z80: Z80) => { // xor a,iyh let value: number; value = z80.regs.iyh; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapFD.set(0xAD, (z80: Z80) => { // xor a,iyl let value: number; value = z80.regs.iyl; z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapFD.set(0xAE, (z80: Z80) => { // xor a,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.a ^= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapFD.set(0xB4, (z80: Z80) => { // or a,iyh let value: number; value = z80.regs.iyh; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapFD.set(0xB5, (z80: Z80) => { // or a,iyl let value: number; value = z80.regs.iyl; z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapFD.set(0xB6, (z80: Z80) => { // or a,(iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); z80.regs.a |= value; z80.regs.f = z80.sz53pTable[z80.regs.a]; }); decodeMapFD.set(0xBC, (z80: Z80) => { // cp iyh let value: number; value = z80.regs.iyh; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapFD.set(0xBD, (z80: Z80) => { // cp iyl let value: number; value = z80.regs.iyl; const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapFD.set(0xBE, (z80: Z80) => { // cp (iy+dd) let value: number; value = z80.readByte(z80.regs.pc); z80.incTStateCount(5); z80.regs.pc = inc16(z80.regs.pc); z80.regs.memptr = (z80.regs.iy + signedByte(value)) & 0xFFFF; value = z80.readByte(z80.regs.memptr); const diff = (z80.regs.a - value) & 0xFFFF; const lookup = (((z80.regs.a & 0x88) >> 3) | ((value & 0x88) >> 2) | ((diff & 0x88) >> 1)) & 0xFF; let f = Flag.N; if ((diff & 0x100) != 0) f |= Flag.C; if (diff == 0) f |= Flag.Z; f |= halfCarrySubTable[lookup & 0x07]; f |= overflowSubTable[lookup >> 4]; f |= value & (Flag.X3 | Flag.X5); f |= diff & Flag.S; z80.regs.af = word(z80.regs.a, f); }); decodeMapFD.set(0xCB, (z80: Z80) => { // shift fdcb decodeFDCB(z80); }); decodeMapFD.set(0xE1, (z80: Z80) => { // pop iy z80.regs.iy = z80.popWord(); }); decodeMapFD.set(0xE3, (z80: Z80) => { // ex (sp),iy const rightValue = z80.regs.iy; const leftValueL = z80.readByte(z80.regs.sp); const leftValueH = z80.readByte(inc16(z80.regs.sp)); z80.incTStateCount(1); z80.writeByte(inc16(z80.regs.sp), hi(rightValue)); z80.writeByte(z80.regs.sp, lo(rightValue)); z80.incTStateCount(2); z80.regs.memptr = word(leftValueH, leftValueL); z80.regs.iy = word(leftValueH, leftValueL); }); decodeMapFD.set(0xE5, (z80: Z80) => { // push iy z80.incTStateCount(1); z80.pushWord(z80.regs.iy); }); decodeMapFD.set(0xE9, (z80: Z80) => { // jp iy z80.regs.pc = z80.regs.iy; }); decodeMapFD.set(0xF9, (z80: Z80) => { // ld sp,iy let value: number; value = z80.regs.iy; z80.incTStateCount(2); z80.regs.sp = value; }); const decodeMapFDCB = new Map<number, OpcodeFunc>(); decodeMapFDCB.set(0x00, (z80: Z80) => { // ld b,rlc z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x01, (z80: Z80) => { // ld c,rlc z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x02, (z80: Z80) => { // ld d,rlc z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x03, (z80: Z80) => { // ld e,rlc z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x04, (z80: Z80) => { // ld h,rlc z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x05, (z80: Z80) => { // ld l,rlc z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x06, (z80: Z80) => { // rlc (iy+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFDCB.set(0x07, (z80: Z80) => { // ld a,rlc z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = ((value << 1) | (value >> 7)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x08, (z80: Z80) => { // ld b,rrc z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x09, (z80: Z80) => { // ld c,rrc z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x0A, (z80: Z80) => { // ld d,rrc z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x0B, (z80: Z80) => { // ld e,rrc z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x0C, (z80: Z80) => { // ld h,rrc z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x0D, (z80: Z80) => { // ld l,rrc z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x0E, (z80: Z80) => { // rrc (iy+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFDCB.set(0x0F, (z80: Z80) => { // ld a,rrc z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = ((value >> 1) | (value << 7)) & 0xFF; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x10, (z80: Z80) => { // ld b,rl z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x11, (z80: Z80) => { // ld c,rl z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x12, (z80: Z80) => { // ld d,rl z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x13, (z80: Z80) => { // ld e,rl z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x14, (z80: Z80) => { // ld h,rl z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x15, (z80: Z80) => { // ld l,rl z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x16, (z80: Z80) => { // rl (iy+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFDCB.set(0x17, (z80: Z80) => { // ld a,rl z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x18, (z80: Z80) => { // ld b,rr z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x19, (z80: Z80) => { // ld c,rr z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x1A, (z80: Z80) => { // ld d,rr z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x1B, (z80: Z80) => { // ld e,rr z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x1C, (z80: Z80) => { // ld h,rr z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x1D, (z80: Z80) => { // ld l,rr z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x1E, (z80: Z80) => { // rr (iy+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFDCB.set(0x1F, (z80: Z80) => { // ld a,rr z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x20, (z80: Z80) => { // ld b,sla z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x21, (z80: Z80) => { // ld c,sla z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x22, (z80: Z80) => { // ld d,sla z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x23, (z80: Z80) => { // ld e,sla z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x24, (z80: Z80) => { // ld h,sla z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x25, (z80: Z80) => { // ld l,sla z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x26, (z80: Z80) => { // sla (iy+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFDCB.set(0x27, (z80: Z80) => { // ld a,sla z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = (value << 1) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x28, (z80: Z80) => { // ld b,sra z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x29, (z80: Z80) => { // ld c,sra z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x2A, (z80: Z80) => { // ld d,sra z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x2B, (z80: Z80) => { // ld e,sra z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x2C, (z80: Z80) => { // ld h,sra z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x2D, (z80: Z80) => { // ld l,sra z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x2E, (z80: Z80) => { // sra (iy+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFDCB.set(0x2F, (z80: Z80) => { // ld a,sra z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = (value & 0x80) | (value >> 1); z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x30, (z80: Z80) => { // ld b,sll z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x31, (z80: Z80) => { // ld c,sll z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x32, (z80: Z80) => { // ld d,sll z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x33, (z80: Z80) => { // ld e,sll z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x34, (z80: Z80) => { // ld h,sll z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x35, (z80: Z80) => { // ld l,sll z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x36, (z80: Z80) => { // sll (iy+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFDCB.set(0x37, (z80: Z80) => { // ld a,sll z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = ((value << 1) | 0x01) & 0xFF; z80.regs.f = ((oldValue & 0x80) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x38, (z80: Z80) => { // ld b,srl z80.regs.b = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.b; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.b = value; } z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x39, (z80: Z80) => { // ld c,srl z80.regs.c = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.c; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.c = value; } z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x3A, (z80: Z80) => { // ld d,srl z80.regs.d = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.d; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.d = value; } z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x3B, (z80: Z80) => { // ld e,srl z80.regs.e = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.e; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.e = value; } z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x3C, (z80: Z80) => { // ld h,srl z80.regs.h = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.h; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.h = value; } z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x3D, (z80: Z80) => { // ld l,srl z80.regs.l = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.l; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.l = value; } z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x3E, (z80: Z80) => { // srl (iy+dd) let value: number; value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.writeByte(z80.regs.memptr, value); }); decodeMapFDCB.set(0x3F, (z80: Z80) => { // ld a,srl z80.regs.a = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); { let value: number; value = z80.regs.a; const oldValue = value; value = value >> 1; z80.regs.f = ((oldValue & 0x01) !== 0 ? Flag.C : 0) | z80.sz53pTable[value]; z80.regs.a = value; } z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x47, (z80: Z80) => { // bit 0,(iy+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x01) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapFDCB.set(0x40, decodeMapFDCB.get(0x47) as OpcodeFunc); decodeMapFDCB.set(0x41, decodeMapFDCB.get(0x47) as OpcodeFunc); decodeMapFDCB.set(0x42, decodeMapFDCB.get(0x47) as OpcodeFunc); decodeMapFDCB.set(0x43, decodeMapFDCB.get(0x47) as OpcodeFunc); decodeMapFDCB.set(0x44, decodeMapFDCB.get(0x47) as OpcodeFunc); decodeMapFDCB.set(0x45, decodeMapFDCB.get(0x47) as OpcodeFunc); decodeMapFDCB.set(0x46, decodeMapFDCB.get(0x47) as OpcodeFunc); decodeMapFDCB.set(0x4F, (z80: Z80) => { // bit 1,(iy+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x02) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapFDCB.set(0x48, decodeMapFDCB.get(0x4F) as OpcodeFunc); decodeMapFDCB.set(0x49, decodeMapFDCB.get(0x4F) as OpcodeFunc); decodeMapFDCB.set(0x4A, decodeMapFDCB.get(0x4F) as OpcodeFunc); decodeMapFDCB.set(0x4B, decodeMapFDCB.get(0x4F) as OpcodeFunc); decodeMapFDCB.set(0x4C, decodeMapFDCB.get(0x4F) as OpcodeFunc); decodeMapFDCB.set(0x4D, decodeMapFDCB.get(0x4F) as OpcodeFunc); decodeMapFDCB.set(0x4E, decodeMapFDCB.get(0x4F) as OpcodeFunc); decodeMapFDCB.set(0x57, (z80: Z80) => { // bit 2,(iy+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x04) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapFDCB.set(0x50, decodeMapFDCB.get(0x57) as OpcodeFunc); decodeMapFDCB.set(0x51, decodeMapFDCB.get(0x57) as OpcodeFunc); decodeMapFDCB.set(0x52, decodeMapFDCB.get(0x57) as OpcodeFunc); decodeMapFDCB.set(0x53, decodeMapFDCB.get(0x57) as OpcodeFunc); decodeMapFDCB.set(0x54, decodeMapFDCB.get(0x57) as OpcodeFunc); decodeMapFDCB.set(0x55, decodeMapFDCB.get(0x57) as OpcodeFunc); decodeMapFDCB.set(0x56, decodeMapFDCB.get(0x57) as OpcodeFunc); decodeMapFDCB.set(0x5F, (z80: Z80) => { // bit 3,(iy+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x08) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapFDCB.set(0x58, decodeMapFDCB.get(0x5F) as OpcodeFunc); decodeMapFDCB.set(0x59, decodeMapFDCB.get(0x5F) as OpcodeFunc); decodeMapFDCB.set(0x5A, decodeMapFDCB.get(0x5F) as OpcodeFunc); decodeMapFDCB.set(0x5B, decodeMapFDCB.get(0x5F) as OpcodeFunc); decodeMapFDCB.set(0x5C, decodeMapFDCB.get(0x5F) as OpcodeFunc); decodeMapFDCB.set(0x5D, decodeMapFDCB.get(0x5F) as OpcodeFunc); decodeMapFDCB.set(0x5E, decodeMapFDCB.get(0x5F) as OpcodeFunc); decodeMapFDCB.set(0x67, (z80: Z80) => { // bit 4,(iy+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x10) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapFDCB.set(0x60, decodeMapFDCB.get(0x67) as OpcodeFunc); decodeMapFDCB.set(0x61, decodeMapFDCB.get(0x67) as OpcodeFunc); decodeMapFDCB.set(0x62, decodeMapFDCB.get(0x67) as OpcodeFunc); decodeMapFDCB.set(0x63, decodeMapFDCB.get(0x67) as OpcodeFunc); decodeMapFDCB.set(0x64, decodeMapFDCB.get(0x67) as OpcodeFunc); decodeMapFDCB.set(0x65, decodeMapFDCB.get(0x67) as OpcodeFunc); decodeMapFDCB.set(0x66, decodeMapFDCB.get(0x67) as OpcodeFunc); decodeMapFDCB.set(0x6F, (z80: Z80) => { // bit 5,(iy+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x20) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapFDCB.set(0x68, decodeMapFDCB.get(0x6F) as OpcodeFunc); decodeMapFDCB.set(0x69, decodeMapFDCB.get(0x6F) as OpcodeFunc); decodeMapFDCB.set(0x6A, decodeMapFDCB.get(0x6F) as OpcodeFunc); decodeMapFDCB.set(0x6B, decodeMapFDCB.get(0x6F) as OpcodeFunc); decodeMapFDCB.set(0x6C, decodeMapFDCB.get(0x6F) as OpcodeFunc); decodeMapFDCB.set(0x6D, decodeMapFDCB.get(0x6F) as OpcodeFunc); decodeMapFDCB.set(0x6E, decodeMapFDCB.get(0x6F) as OpcodeFunc); decodeMapFDCB.set(0x77, (z80: Z80) => { // bit 6,(iy+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x40) === 0) { f |= Flag.P | Flag.Z; } z80.regs.f = f; }); decodeMapFDCB.set(0x70, decodeMapFDCB.get(0x77) as OpcodeFunc); decodeMapFDCB.set(0x71, decodeMapFDCB.get(0x77) as OpcodeFunc); decodeMapFDCB.set(0x72, decodeMapFDCB.get(0x77) as OpcodeFunc); decodeMapFDCB.set(0x73, decodeMapFDCB.get(0x77) as OpcodeFunc); decodeMapFDCB.set(0x74, decodeMapFDCB.get(0x77) as OpcodeFunc); decodeMapFDCB.set(0x75, decodeMapFDCB.get(0x77) as OpcodeFunc); decodeMapFDCB.set(0x76, decodeMapFDCB.get(0x77) as OpcodeFunc); decodeMapFDCB.set(0x7F, (z80: Z80) => { // bit 7,(iy+dd) const value = z80.readByte(z80.regs.memptr); const hiddenValue = hi(z80.regs.memptr); z80.incTStateCount(1); let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5)); if ((value & 0x80) === 0) { f |= Flag.P | Flag.Z; } if ((value & 0x80) !== 0) { f |= Flag.S; } z80.regs.f = f; }); decodeMapFDCB.set(0x78, decodeMapFDCB.get(0x7F) as OpcodeFunc); decodeMapFDCB.set(0x79, decodeMapFDCB.get(0x7F) as OpcodeFunc); decodeMapFDCB.set(0x7A, decodeMapFDCB.get(0x7F) as OpcodeFunc); decodeMapFDCB.set(0x7B, decodeMapFDCB.get(0x7F) as OpcodeFunc); decodeMapFDCB.set(0x7C, decodeMapFDCB.get(0x7F) as OpcodeFunc); decodeMapFDCB.set(0x7D, decodeMapFDCB.get(0x7F) as OpcodeFunc); decodeMapFDCB.set(0x7E, decodeMapFDCB.get(0x7F) as OpcodeFunc); decodeMapFDCB.set(0x80, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x81, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x82, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x83, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x84, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x85, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x86, (z80: Z80) => { // res 0,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xFE); }); decodeMapFDCB.set(0x87, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xFE; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x88, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x89, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x8A, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x8B, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x8C, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x8D, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x8E, (z80: Z80) => { // res 1,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xFD); }); decodeMapFDCB.set(0x8F, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xFD; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x90, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x91, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x92, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x93, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x94, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x95, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x96, (z80: Z80) => { // res 2,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xFB); }); decodeMapFDCB.set(0x97, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xFB; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0x98, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0x99, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0x9A, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0x9B, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0x9C, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0x9D, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0x9E, (z80: Z80) => { // res 3,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xF7); }); decodeMapFDCB.set(0x9F, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xF7; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xA0, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xA1, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xA2, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xA3, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xA4, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xA5, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xA6, (z80: Z80) => { // res 4,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xEF); }); decodeMapFDCB.set(0xA7, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xEF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xA8, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xA9, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xAA, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xAB, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xAC, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xAD, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xAE, (z80: Z80) => { // res 5,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xDF); }); decodeMapFDCB.set(0xAF, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xDF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xB0, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xB1, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xB2, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xB3, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xB4, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xB5, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xB6, (z80: Z80) => { // res 6,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0xBF); }); decodeMapFDCB.set(0xB7, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0xBF; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xB8, (z80: Z80) => { // ld b,res z80.regs.b = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xB9, (z80: Z80) => { // ld c,res z80.regs.c = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xBA, (z80: Z80) => { // ld d,res z80.regs.d = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xBB, (z80: Z80) => { // ld e,res z80.regs.e = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xBC, (z80: Z80) => { // ld h,res z80.regs.h = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xBD, (z80: Z80) => { // ld l,res z80.regs.l = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xBE, (z80: Z80) => { // res 7,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value & 0x7F); }); decodeMapFDCB.set(0xBF, (z80: Z80) => { // ld a,res z80.regs.a = z80.readByte(z80.regs.memptr) & 0x7F; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xC0, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xC1, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xC2, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xC3, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xC4, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xC5, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xC6, (z80: Z80) => { // set 0,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x01); }); decodeMapFDCB.set(0xC7, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x01; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xC8, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xC9, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xCA, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xCB, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xCC, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xCD, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xCE, (z80: Z80) => { // set 1,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x02); }); decodeMapFDCB.set(0xCF, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x02; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xD0, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xD1, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xD2, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xD3, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xD4, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xD5, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xD6, (z80: Z80) => { // set 2,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x04); }); decodeMapFDCB.set(0xD7, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x04; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xD8, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xD9, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xDA, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xDB, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xDC, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xDD, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xDE, (z80: Z80) => { // set 3,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x08); }); decodeMapFDCB.set(0xDF, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x08; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xE0, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xE1, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xE2, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xE3, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xE4, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xE5, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xE6, (z80: Z80) => { // set 4,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x10); }); decodeMapFDCB.set(0xE7, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x10; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xE8, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xE9, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xEA, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xEB, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xEC, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xED, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xEE, (z80: Z80) => { // set 5,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x20); }); decodeMapFDCB.set(0xEF, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x20; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xF0, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xF1, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xF2, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xF3, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xF4, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xF5, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xF6, (z80: Z80) => { // set 6,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x40); }); decodeMapFDCB.set(0xF7, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x40; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); decodeMapFDCB.set(0xF8, (z80: Z80) => { // ld b,set z80.regs.b = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.b); }); decodeMapFDCB.set(0xF9, (z80: Z80) => { // ld c,set z80.regs.c = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.c); }); decodeMapFDCB.set(0xFA, (z80: Z80) => { // ld d,set z80.regs.d = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.d); }); decodeMapFDCB.set(0xFB, (z80: Z80) => { // ld e,set z80.regs.e = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.e); }); decodeMapFDCB.set(0xFC, (z80: Z80) => { // ld h,set z80.regs.h = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.h); }); decodeMapFDCB.set(0xFD, (z80: Z80) => { // ld l,set z80.regs.l = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.l); }); decodeMapFDCB.set(0xFE, (z80: Z80) => { // set 7,(iy+dd) const value = z80.readByte(z80.regs.memptr); z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, value | 0x80); }); decodeMapFDCB.set(0xFF, (z80: Z80) => { // ld a,set z80.regs.a = z80.readByte(z80.regs.memptr) | 0x80; z80.incTStateCount(1); z80.writeByte(z80.regs.memptr, z80.regs.a); }); /** * Fetch an instruction for decode. */ function fetchInstruction(z80: Z80): number { z80.incTStateCount(4); const inst = z80.readByteInternal(z80.regs.pc); z80.regs.pc = (z80.regs.pc + 1) & 0xFFFF; z80.regs.r = (z80.regs.r + 1) & 0xFF; return inst; } /** * Decode the "CB" prefix (bit instructions). */ function decodeCB(z80: Z80): void { const inst = fetchInstruction(z80); const func = decodeMapCB.get(inst); if (func === undefined) { console.log("Unhandled opcode in CB: " + toHex(inst, 2)); } else { func(z80); } } /** * Decode the "DD" prefix (IX instructions). */ function decodeDD(z80: Z80): void { const inst = fetchInstruction(z80); const func = decodeMapDD.get(inst); if (func === undefined) { console.log("Unhandled opcode in DD: " + toHex(inst, 2)); } else { func(z80); } } /** * Decode the "DDCB" prefix (IX bit instructions). */ function decodeDDCB(z80: Z80): void { z80.incTStateCount(3); const offset = z80.readByteInternal(z80.regs.pc); z80.regs.memptr = add16(z80.regs.ix, signedByte(offset)); z80.regs.pc = inc16(z80.regs.pc); z80.incTStateCount(3); const inst = z80.readByteInternal(z80.regs.pc); z80.incTStateCount(2); z80.regs.pc = inc16(z80.regs.pc); const func = decodeMapDDCB.get(inst); if (func === undefined) { console.log("Unhandled opcode in DDCB: " + toHex(inst, 2)); } else { func(z80); } } /** * Decode the "ED" prefix (extended instructions). */ function decodeED(z80: Z80): void { const inst = fetchInstruction(z80); const func = decodeMapED.get(inst); if (func === undefined) { console.log("Unhandled opcode in ED: " + toHex(inst, 2)); } else { func(z80); } } /** * Decode the "FD" prefix (IY instructions). */ function decodeFD(z80: Z80): void { const inst = fetchInstruction(z80); const func = decodeMapFD.get(inst); if (func === undefined) { console.log("Unhandled opcode in FD: " + toHex(inst, 2)); } else { func(z80); } } /** * Decode the "FDCB" prefix (IY bit instructions). */ function decodeFDCB(z80: Z80): void { z80.incTStateCount(3); const offset = z80.readByteInternal(z80.regs.pc); z80.regs.memptr = add16(z80.regs.iy, signedByte(offset)); z80.regs.pc = inc16(z80.regs.pc); z80.incTStateCount(3); const inst = z80.readByteInternal(z80.regs.pc); z80.incTStateCount(2); z80.regs.pc = inc16(z80.regs.pc); const func = decodeMapFDCB.get(inst); if (func === undefined) { console.log("Unhandled opcode in FDCB: " + toHex(inst, 2)); } else { func(z80); } } /** * Decode the base (un-prefixed) instructions. */ export function decode(z80: Z80): void { const inst = fetchInstruction(z80); const func = decodeMapBASE.get(inst); if (func === undefined) { console.log("Unhandled opcode " + toHex(inst, 2)); } else { func(z80); } }
the_stack
"use strict"; import * as winston from 'winston'; import * as marked from 'marked' import * as fs from 'fs'; import * as path from 'path'; import { FileHandle } from 'fs/promises'; const {EOL} = require('os'); import slash from 'slash'; import normalizeUrl from 'normalize-url'; /** * Ebook commands */ class EbookCommand { logger: winston.Logger readFile: (path: fs.PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: fs.OpenMode } | BufferEncoding) => Promise<string> writeFile: (path: fs.PathLike | FileHandle, data: string | Uint8Array) => Promise<void> existsSync: (path: fs.PathLike) => boolean outputText: (text: string) => void constructor(logger: winston.Logger, defaultFs: any = null) { this.logger = logger if (defaultFs == null) { this.readFile = fs.promises.readFile this.writeFile = fs.promises.writeFile this.existsSync = fs.existsSync } else { this.readFile = defaultFs.readFile this.writeFile = defaultFs.writeFile this.existsSync = defaultFs.existsSync } this.outputText = (text: string) => console.log(text) } /** * Create the e-book content * @param args * @returns */ async create(args: EbookArguments) : Promise<void> { let content : string[] = ['<html><head><link href="prism.css" rel="stylesheet" /><link href="book.css" rel="stylesheet" /></head><body><img class="cover" src="./images/ebook-cover.png" />'] let toc : string[] = ['<div class="page"><ul class="toc">'] let tocLevels: number[] = [] for ( let l = 0; l < args.tocLevel; l++) { tocLevels.push(0) } marked.use({ pedantic: false, gfm: true, breaks: false, sanitize: false, smartLists: true, smartypants: false, xhtml: false }); let docsPath : string = args.docsPath if ( ! path.isAbsolute(docsPath)) { docsPath = path.normalize(path.join(__dirname, '..', '..', '..', docsPath)) } else { docsPath = path.normalize(docsPath) } let indexFile = path.join(docsPath, "index.txt") if (!this.existsSync(indexFile)) { this.logger?.error(`Unable to find index file ${indexFile}`) return Promise.resolve() } let data = await this.readFile(indexFile, 'utf-8') const lines = data.split(/\r?\n/); let fileReferences : { [id: string]: string[]; } = {} let links: string[] = [] for ( var i = 0; i < lines.length; i++ ) { content.push('<div class="page">') if ( lines[i].startsWith("#") || lines[i]?.trim().length == 0 ) { // Skip comment or empty line continue; } let file = path.normalize(path.join(docsPath, lines[i])) let md = await this.readFile(file, 'utf-8') let tokens = marked.lexer(md) let fileid = lines[i].replace(/\//g, '-').replace(".md", '') this.logger?.debug(`Importing ${file}`) fileReferences[fileid] = [] marked.walkTokens(tokens, (token) => { if ( token.type == "image" ) { if ( !path.isAbsolute(token.href) && !token.href.startsWith('http') ) { let relativePath = path.normalize(path.join(path.dirname(file), token.href)) relativePath = "." + relativePath.replace(docsPath, "").replace(/\\/g,'/') this.logger?.debug(`Updating image from ${token.href} to ${relativePath}`) token.href = relativePath } } if ( token.type == "link" ) { if (token.href.startsWith("#")) { let oldLink = token.href token.href = "#" + fileid + "-" + token.href.replace("#","").replace(/ /g,'-') if ( fileReferences[fileid].indexOf(token.href) < 0 ) { fileReferences[fileid].push(token.href) } this.logger?.debug(`Updating markdown link ${oldLink} to ${token.href}`) return } if (token.href.indexOf(".md") > 0 && !token.href.startsWith('http')) { let reference = token.href let fileName = reference.indexOf("#") > 0 ? reference.split('#')[0] : reference let section = reference.indexOf("#") > 0 ? reference.split('#')[1] : "" let targetFile = path.normalize(path.join(path.dirname(file), fileName)) let relativeFile = targetFile.replace(docsPath,"") // Change to unix like path relativeFile = relativeFile.replace(/\\/g,'/') if (relativeFile.startsWith('/')) { relativeFile = relativeFile.substr(1) } let newReference = "" if ( section.length == 0 ) { // Not a reference fo an internal part of the file // Assume link is to the start of the file newReference += "#section-" } newReference += relativeFile.replace(/\//g,'-').replace(".md","") if ( section.length > 0 ) { // Add link to heaing inside the document newReference += "-" + section.toLowerCase().replace(/ /g,'-') } this.logger?.debug(`Updating markdown link ${token.href} to ${newReference}`) if ( fileReferences[fileid].indexOf(newReference) < 0 ) { fileReferences[fileid].push(newReference) } token.href = newReference return } if ( !path.isAbsolute(token.href) && !token.href.startsWith('http') ) { let href = (<any>marked.lexer(token.raw.replace(/\\/g,'/'))[0]).tokens[0].href let relativePath = slash(path.normalize(path.join(path.dirname(file), href))) let offset = "./" let commonPath = docsPath // Assume that in docs path relativePath = relativePath.replace(docsPath,"") // Check if still have absolute path while ( path.isAbsolute(relativePath) ) { // Move up one folder offset += "../" commonPath = slash(path.normalize(path.join(commonPath, ".."))) // Try remove new common path folder relativePath = relativePath.replace(commonPath,"") if ( relativePath.startsWith('/')) { relativePath = relativePath.substr(1) } } let newPath = "." if ( args.repoPath?.length > 0 ) { newPath = args.repoPath if ( ! newPath.endsWith('/')) { newPath += '/' } relativePath = normalizeUrl(newPath + offset + relativePath) } else { relativePath = newPath + relativePath } if ( fileReferences[fileid].indexOf(relativePath) < 0 ) { fileReferences[fileid].push(relativePath) } this.logger?.debug(`Updating link from ${href} to ${relativePath}`) token.href = relativePath } } }) const renderer = new marked.Renderer(); renderer.heading = (text, level) => { const escapedText = "#" + fileid + '-' + text.toLowerCase().replace(/[^\w]+/g, '-'); if (links.indexOf(escapedText) < 0) { links.push(escapedText) } if (level <= args.tocLevel) { if ( level < args.tocLevel) { for ( let l = level; l < args.tocLevel; l++) { tocLevels[l] = 0 } } tocLevels[level - 1] = tocLevels[level - 1] + 1 let label = '' for (let l = 0; l < level; l++) { if (label.length > 0) { label += "." } label += tocLevels[l] } toc.push(`<li class="toc-${level}"><a href="${escapedText}">${label} ${text}</a><li>`) } return ` <h${level}> <a id="${escapedText.replace("#", "")}" class="anchor"> <span class="header-link"></span> </a> ${text} </h${level}>`; } const parser = new marked.Parser({ renderer: renderer }); let html = parser.parse(tokens) let fileReference = `section-${fileid}` let documentLink = `<a id="${fileReference}" class="section"></a>` if (links.indexOf(`#${fileReference}`) < 0) { // Add link to document start links.push(`#${fileReference}`) } if ( typeof args.htmlFile === "undefined" || args.htmlFile?.length == 0) { this.outputText(documentLink); this.outputText(html); } else { content.push(documentLink) content.push(html) } content.push('</div>') } if ( args.htmlFile?.length > 0) { content.push(`<script src='prism.js'></script></body></html>`) let htmlFile = args.htmlFile if ( !path.isAbsolute(args.htmlFile) ) { htmlFile = path.normalize(path.join(docsPath, htmlFile)) } toc.push("</ul></div>") content.splice(1, 0, toc.join(EOL)) await this.writeFile(htmlFile, content.join(EOL)) } this.logger?.info("Checking links") for ( var i = 0; i < lines.length; i++ ) { let fileid = lines[i].replace(/\//g, '-').replace(".md", '') let missing: string[] = [] for ( var l = 0; l < fileReferences[fileid]?.length; l++ ) { if ( fileReferences[fileid][l].startsWith("#") && links.indexOf(fileReferences[fileid][l]) < 0 ) { if (fileReferences[fileid][l].startsWith("#section-")) missing.push(`Unable to page ${fileReferences[fileid][l].replace('#section-','')}`) else { missing.push(`Unable to find heading ${fileReferences[fileid][l]}`) } } } if ( missing.length > 0 ) { this.logger?.info(lines[i]) for ( var l = 0; l < missing.length; l ++) { this.logger?.error(missing[l]) } } } return Promise.resolve(); } } /** * Ebook Command Arguments */ class EbookArguments { /** * The path to the documents */ docsPath: string /** * The path to the repo where the document files are located */ repoPath: string /** * The name of the combined HTML file to create */ htmlFile: string /** * The table of contents level */ tocLevel: number } export { EbookArguments, EbookCommand };
the_stack
import { Component, OnInit, Output, EventEmitter, Inject } from '@angular/core'; import { ValidatorFn, FormControl } from '@angular/forms'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { ToastrService } from 'ngx-toastr'; import { RolesGroupsService, HealthStatusService, ApplicationSecurityService, AppRoutingService } from '../../core/services'; import { CheckUtils, SortUtils } from '../../core/util'; import { DICTIONARY } from '../../../dictionary/global.dictionary'; import { ProgressBarService } from '../../core/services/progress-bar.service'; import { ConfirmationDialogComponent, ConfirmationDialogType } from '../../shared/modal-dialog/confirmation-dialog'; @Component({ selector: 'datalab-roles', templateUrl: './roles.component.html', styleUrls: ['../../resources/resources-grid/resources-grid.component.scss', './roles.component.scss'] }) export class RolesComponent implements OnInit { readonly DICTIONARY = DICTIONARY; @Output() manageRolesGroupAction: EventEmitter<{}> = new EventEmitter(); private startedGroups: Array<any>; public groupsData: Array<any> = []; public roles: Array<any> = []; public rolesList: Array<any> = []; public setupGroup: string = ''; public setupUser: string = ''; public manageUser: string = ''; public setupRoles: Array<any> = []; public updatedRoles: Array<string> = []; public healthStatus: any; public delimitersRegex = /[-_]?/g; public groupnamePattern = new RegExp(/^[a-zA-Z0-9_\-]+$/); public noPermissionMessage: string = 'You have not permissions for groups which are not assigned to your projects.'; public maxGroupLength: number = 25; stepperView: boolean = false; displayedColumns: string[] = ['name', 'roles', 'users', 'actions']; constructor( public toastr: ToastrService, public dialog: MatDialog, private rolesService: RolesGroupsService, private healthStatusService: HealthStatusService, private progressBarService: ProgressBarService, private applicationSecurityService: ApplicationSecurityService, private appRoutingService: AppRoutingService, ) { } ngOnInit() { this.getEnvironmentHealthStatus(); } openManageRolesDialog() { this.progressBarService.startProgressBar(); this.rolesService.getGroupsData().subscribe(groups => { this.rolesService.getRolesData().subscribe( (roles: any) => { this.roles = roles; this.rolesList = roles.map((role) => ({ role: role.description, type: role.type, cloud: role.cloud })); this.rolesList = SortUtils.sortByKeys(this.rolesList, ['role', 'cloud', 'type']); this.updateGroupData(groups); this.stepperView = false; }, error => this.toastr.error(error.message, 'Oops!')); this.progressBarService.stopProgressBar(); }, error => { this.toastr.error(error.message, 'Oops!'); this.progressBarService.stopProgressBar(); } ); } getGroupsData() { this.rolesService.getGroupsData() .subscribe( list => this.updateGroupData(list), error => this.toastr.error(error.message, 'Oops!') ); } public selectAllOptions(item, values, byKey?) { if (byKey) { item[byKey] = values ? values : []; } else { this.setupRoles = values ? values : []; } } public manageAction(action: string, type: string, item?: any, value?) { if (action === 'create') { this.manageRolesGroups({ action, type, value: { name: this.setupGroup, users: this.setupUser ? this.setupUser.split(',').map(elem => elem.trim()).filter(el => !!el) : [], roleIds: this.extractIds(this.roles, this.setupRoles.map(v => v.role)) } }); this.stepperView = false; } else if (action === 'delete') { const data = (type === 'users') ? { group: item.group, user: value } : { group: item.group, id: item }; const dialogRef: MatDialogRef<ConfirmDeleteUserAccountDialogComponent> = this.dialog.open( ConfirmDeleteUserAccountDialogComponent, { data: data, width: '550px', panelClass: 'error-modalbox' } ); dialogRef.afterClosed().subscribe(result => { if (result) { const emitValue = (type === 'users') ? { action, type, id: item.name, value: { user: value, group: item.group } } : { action, type, id: item.name, value: item.group }; this.manageRolesGroups(emitValue); } }); } else if (action === 'update') { const currGroupSource = this.startedGroups.filter(cur => cur.group === item.group)[0]; let deletedUsers = currGroupSource.users.filter(user => !item.users.includes(user)); this.dialog.open(ConfirmationDialogComponent, { data: { notebook: deletedUsers, type: ConfirmationDialogType.deleteUser }, panelClass: 'modal-sm' }) .afterClosed().subscribe((res) => { if (!res) { item.users = [...currGroupSource.users]; item.selected_roles = [...currGroupSource.selected_roles]; item.roles = [...currGroupSource.roles]; } else { const selectedRoles = item.selected_roles.map(v => v.role); this.manageRolesGroups({ action, type, value: { name: item.group, roles: this.extractIds(this.roles, selectedRoles), users: item.users || [] } }); } deletedUsers = []; }); } this.resetDialog(); } public manageRolesGroups($event) { switch ($event.action) { case 'create': this.rolesService.setupNewGroup($event.value) .subscribe( () => { this.toastr.success('Group creation success!', 'Created!'); this.getGroupsData(); }, () => this.toastr.error('Group creation failed!', 'Oops!')); break; case 'update': this.rolesService.updateGroup($event.value) .subscribe( () => { this.toastr.success(`Group data is updated successfully!`, 'Success!'); this.openManageRolesDialog(); }, () => this.toastr.error('Failed group data updating!', 'Oops!')); break; case 'delete': if ($event.type === 'users') { this.rolesService.removeUsersForGroup($event.value) .subscribe( () => { this.toastr.success('Users was successfully deleted!', 'Success!'); this.getGroupsData(); }, () => this.toastr.error('Failed users deleting!', 'Oops!')); } else if ($event.type === 'group') { this.rolesService.removeGroupById($event.value) .subscribe( () => { this.toastr.success('Group was successfully deleted!', 'Success!'); this.getGroupsData(); }, (error) => this.toastr.error(error.message, 'Oops!')); } break; default: } } public updateGroupData(groups) { this.groupsData = groups.map(v => { if (!v.users) { v.users = []; } return v; }).sort((a, b) => (a.group > b.group) ? 1 : ((b.group > a.group) ? -1 : 0)); this.groupsData.forEach(item => { const selectedRoles = item.roles.map(role => ({ role: role.description, type: role.type, cloud: role.cloud })); item.selected_roles = SortUtils.sortByKeys(selectedRoles, ['role', 'type']); }); this.getGroupsListCopy(); } public extractIds(sourceList, target) { const map = new Map(); const mapped = sourceList.reduce((acc, item) => { target.includes(item.description) && acc.set(item._id, item.description); return acc; }, map); return this.mapToObj(mapped); } mapToObj(inputMap) { const obj = {}; inputMap.forEach((value, key) => { obj[key] = value; }); return obj; } private getGroupsListCopy() { this.startedGroups = JSON.parse(JSON.stringify(this.groupsData)); } public groupValidation(): ValidatorFn { const duplicateList: any = this.groupsData.map(item => item.group.toLowerCase()); return <ValidatorFn>((control: FormControl) => { if (control.value && control.value.length > this.maxGroupLength) { return { long: true }; } if (control.value && duplicateList.includes(CheckUtils.delimitersFiltering(control.value.toLowerCase()))) { return { duplicate: true }; } if (control.value && !this.groupnamePattern.test(control.value)) return { patterns: true }; return null; }); } public isGroupChanded(currGroup) { const currGroupSource = this.startedGroups.filter(cur => cur.group === currGroup.group)[0]; if (currGroup.users.length !== currGroupSource.users.length && currGroup.selected_roles.length !== currGroupSource.selected_roles.length) { return false; } return JSON.stringify(currGroup.users) === JSON.stringify(currGroupSource.users) && JSON.stringify( currGroup.selected_roles.map(role => role.role).sort() ) === JSON .stringify( currGroupSource.selected_roles.map(role => role.role).sort() ); } public resetDialog() { this.stepperView = false; this.setupGroup = ''; this.setupUser = ''; this.manageUser = ''; this.setupRoles = []; this.updatedRoles = []; } public removeUser(list, item): void { list.splice(list.indexOf(item), 1); } public addUser(user, item): void { if (item.isUserAdded) { if (!this.toastr.toasts.length) this.toastr.error('User is already added to this group', 'Oops!'); return; } if (user.value && user.value.trim()) { item.users instanceof Array ? item.users.push(user.value.trim()) : item.users = [user.value.trim()]; } user.value = ''; } private getEnvironmentHealthStatus() { this.healthStatusService.getEnvironmentHealthStatus() .subscribe((result: any) => { this.healthStatus = result; if (!this.healthStatus.admin && !this.healthStatus.projectAdmin) { this.appRoutingService.redirectToHomePage(); } else { this.openManageRolesDialog(); } }); } public onUpdate($event): void { if ($event.type) { this.groupsData.filter(group => group.group === $event.type)[0].selected_roles = $event.model; } else { this.setupRoles = $event.model; } } public checkIfUserAdded(element: any, value: string) { element.isUserAdded = element.users .map(v => v.toLowerCase()) .includes(value.toLowerCase()); } } @Component({ selector: 'dialog-result-example-dialog', template: ` <div class="dialog-header"> <h4 class="modal-title"><i class="material-icons">priority_high</i>Warning</h4> <button type="button" class="close" (click)="dialogRef.close()">&times;</button> </div> <div mat-dialog-content class="content"> <p *ngIf="data.user">User <span class="strong"> {{ data.user }}</span> will be deleted from <span class="strong">{{ data.group }}</span> group. </p> <p *ngIf="data.id">Group <span class="ellipsis group-name strong"> {{ data.group }}</span> will be decommissioned. </p> <p class="m-top-20"> <span class="strong">Do you want to proceed?</span> </p> </div> <div class="text-center"> <button type="button" class="butt" mat-raised-button (click)="dialogRef.close()" > No </button> <button type="button" class="butt butt-success" mat-raised-button (click)="dialogRef.close(true)" > Yes </button> </div> `, styles: [`.group-name { max-width: 96%; display: inline-block; vertical-align: bottom; }`] }) export class ConfirmDeleteUserAccountDialogComponent { constructor( public dialogRef: MatDialogRef<ConfirmDeleteUserAccountDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any ) { } }
the_stack
import chai, { expect } from 'chai'; import commentsToOpenApi from './commentsToOpenApi'; function _(func: { (): void }): string { const str = func.toString(); return str .slice(str.indexOf('{') + 1, str.lastIndexOf('}')) .replace(/\r\n/g, '\n'); } describe('code blocks', () => { it('keeps spacing', () => { const comment = _(() => { /** * GET / * @description List API versions * ```xml * <Fun> * <InTheSun>😎</InTheSun> * </Fun> * ``` * bye * * @response 200 - ok */ }); const expected = { paths: { '/': { get: { description: 'List API versions\n```xml\n<Fun>\n <InTheSun>😎</InTheSun>\n</Fun>\n```\nbye', responses: { '200': { description: 'ok', }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); }); describe('commentsToOpenApi', () => { it('big stuff', () => { const comment = _(() => { /** * POST /pet * * @externalDocs https://example.com - Find more info here * * @server https://development.gigantic-server.com/v1 - Development server * @server https://gigantic-server.com/v1 - production server * * @paramComponent {ExampleParameter} * @queryParam {ExampleSchema} [password] - username to fetch * @queryParam {integer} [limit=20] - the limit to fetch * @queryParam {number} [pi=3.14] - the limit to fetch * @queryParam {string} [name=nick] - the limit to fetch * * @bodyDescription an optional description * @bodyContent {string} application/json * @bodyRequired * * @response 200 - sup * @responseContent {string} 200.application/json * @responseExample {ExampleExample} 200.application/json.example1 * @responseExample {ExampleExample} 200.application/json.example2 * @responseHeaderComponent {ExampleHeader} 200.some-header * @responseHeaderComponent {ExampleHeader} 200.some-header2 * @responseLink {ExampleLink} 200.some-link * @responseLink {ExampleLink} 200.some-link2 * * @response 400 - :( * * @responseComponent {ExampleResponse} default * * @callback {ExampleCallback} onSomethin * @callback {ExampleCallback} onSomethin2 * * @security ExampleSecurity * @security ExampleSecurity3 */ /** * PUT /pet * @deprecated * @bodyComponent {ExampleBody} * @response 200 - fun * * @security ExampleSecurity2.write:pets * @security ExampleSecurity2.read:pets */ }); const expected1 = { paths: { '/pet': { post: { externalDocs: { description: 'Find more info here', url: 'https://example.com', }, servers: [ { description: 'Development server', url: 'https://development.gigantic-server.com/v1', }, { description: 'production server', url: 'https://gigantic-server.com/v1', }, ], parameters: [ { $ref: '#/components/parameters/ExampleParameter', }, { name: 'password', in: 'query', description: 'username to fetch', required: false, schema: { $ref: '#/components/schemas/ExampleSchema', }, }, { name: 'limit', in: 'query', description: 'the limit to fetch', required: false, schema: { type: 'integer', default: 20, }, }, { name: 'pi', in: 'query', description: 'the limit to fetch', required: false, schema: { type: 'number', default: 3.14, }, }, { name: 'name', in: 'query', description: 'the limit to fetch', required: false, schema: { type: 'string', default: 'nick', }, }, ], requestBody: { description: 'an optional description', required: true, content: { 'application/json': { schema: { type: 'string', }, }, }, }, responses: { '200': { description: 'sup', content: { 'application/json': { schema: { type: 'string', }, examples: { example1: { $ref: '#/components/examples/ExampleExample', }, example2: { $ref: '#/components/examples/ExampleExample', }, }, }, }, headers: { 'some-header': { $ref: '#/components/headers/ExampleHeader', }, 'some-header2': { $ref: '#/components/headers/ExampleHeader', }, }, links: { 'some-link': { $ref: '#/components/links/ExampleLink', }, 'some-link2': { $ref: '#/components/links/ExampleLink', }, }, }, '400': { description: ':(', }, default: { $ref: '#/components/responses/ExampleResponse', }, }, callbacks: { onSomethin: { $ref: '#/components/callbacks/ExampleCallback', }, onSomethin2: { $ref: '#/components/callbacks/ExampleCallback', }, }, security: [ { ExampleSecurity: [], }, { ExampleSecurity3: [], }, ], }, }, }, }; const expected2 = { paths: { '/pet': { put: { deprecated: true, requestBody: { $ref: '#/components/requestBodies/ExampleBody', }, responses: { '200': { description: 'fun', }, }, security: [ { ExampleSecurity2: ['write:pets', 'read:pets'], }, ], }, }, }, }; const specification = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal([expected1, expected2]); }); it("random properities I don't normally use", () => { const comment = _(() => { /** * GET / * @operationId listVersionsv2 * @summary List API versions * @response 200 - 200 response * @response 300 - 300 response */ }); const expected = { paths: { '/': { get: { operationId: 'listVersionsv2', summary: 'List API versions', responses: { '200': { description: '200 response', }, '300': { description: '300 response', }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('simple example', () => { const comment = _(() => { /** * GET /hello * @description Get a "hello world" message. * @response 200 - hello world. */ }); const expected = { paths: { '/hello': { get: { description: 'Get a "hello world" message.', responses: { '200': { description: 'hello world.', }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('2 examples', () => { const comment = _(() => { /** * POST /hello * @description Get a "hello world" message. * @response 200 - hello world. * @responseContent {string} 200.text/plain */ const garbage = 'trash'; console.log(garbage); /** * GET /hello * @description Get a "hello world" message. * @response 200 - hello world. * @responseContent {string} 200.text/plain */ }); const expected1 = { paths: { '/hello': { post: { description: 'Get a "hello world" message.', responses: { '200': { description: 'hello world.', content: { 'text/plain': { schema: { type: 'string', }, }, }, }, }, }, }, }, }; const expected2 = { paths: { '/hello': { get: { description: 'Get a "hello world" message.', responses: { '200': { description: 'hello world.', content: { 'text/plain': { schema: { type: 'string', }, }, }, }, }, }, }, }, }; const specification = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal([expected1, expected2]); }); it('complex example', () => { const comment = _(() => { /** * GET /api/v1/cars/{country}/{city} * @description Get a list of cars at a location. * @pathParam {string} country - Country of the rental company. * @pathParam {string} city - City of the rental company. * @queryParam {string} [company] - Rental Company name. * @queryParam {string} [car] - Car Name. * @queryParam {string} [type] - Car Type. * @queryParam {string} [style] - Car Style. * @queryParam {number} [mincost] - Min Cost. * @queryParam {number} [maxcost] - Max Cost. * @response 200 - A list of cars. * @responseContent {string[]} 200.application/json * @response 400 - Example Error. */ }); const expected = { paths: { '/api/v1/cars/{country}/{city}': { get: { description: 'Get a list of cars at a location.', parameters: [ { in: 'path', name: 'country', description: 'Country of the rental company.', required: true, schema: { type: 'string', }, }, { in: 'path', name: 'city', description: 'City of the rental company.', required: true, schema: { type: 'string', }, }, { in: 'query', name: 'company', description: 'Rental Company name.', required: false, schema: { type: 'string', }, }, { in: 'query', name: 'car', description: 'Car Name.', required: false, schema: { type: 'string', }, }, { in: 'query', name: 'type', description: 'Car Type.', required: false, schema: { type: 'string', }, }, { in: 'query', name: 'style', description: 'Car Style.', required: false, schema: { type: 'string', }, }, { in: 'query', name: 'mincost', description: 'Min Cost.', required: false, schema: { type: 'number', }, }, { in: 'query', name: 'maxcost', description: 'Max Cost.', required: false, schema: { type: 'number', }, }, ], responses: { '200': { description: 'A list of cars.', content: { 'application/json': { schema: { type: 'array', items: { type: 'string', }, }, }, }, }, '400': { description: 'Example Error.', }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('simple post', () => { const comment = _(() => { /** * POST /hello * @description Post a "hello world" message. * @bodyContent {boolean} application/json * @bodyDescription Whether or not to say hello world. * @response 200 - hello world. */ }); const expected = { paths: { '/hello': { post: { description: 'Post a "hello world" message.', requestBody: { description: 'Whether or not to say hello world.', content: { 'application/json': { schema: { type: 'boolean', }, }, }, }, responses: { '200': { description: 'hello world.', }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('form post', () => { const comment = _(() => { /** * POST /hello * @description Post a "hello world" message. * @bodyContent {ExampleObject} application/x-www-form-urlencoded * @bodyDescription A more complicated object. * @response 200 - hello world. */ }); const expected = { paths: { '/hello': { post: { description: 'Post a "hello world" message.', requestBody: { description: 'A more complicated object.', content: { 'application/x-www-form-urlencoded': { schema: { $ref: '#/components/schemas/ExampleObject', }, }, }, }, responses: { '200': { description: 'hello world.', }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('many bodies post', () => { // Note: We can't use "*/*" in doc comments. const comment = _(() => { /** * POST /hello * @description Post a "hello world" message. * @bodyContent {ExampleObject} application/x-www-form-urlencoded * @bodyContent {ExampleObject} application/json * @bodyContent {binary} image/png * @bodyContent {string} *\/* * @bodyDescription A more complicated object. * @bodyRequired * @response 200 - hello world. * @responseContent {Car[]} 200.application/json * @responseHeader {string} 200.x-next - A link to the next page of responses * @responseExample {Example} 200.application/json.example1 * @responseContent {string} 400.application/json * @responseHeader {string} 400.fake-header - A fake header * @responseExample {Example} 400.application/json.example1 * @response 400 - error. */ }); const expected = { paths: { '/hello': { post: { description: 'Post a "hello world" message.', requestBody: { description: 'A more complicated object.', required: true, content: { 'application/x-www-form-urlencoded': { schema: { $ref: '#/components/schemas/ExampleObject', }, }, 'application/json': { schema: { $ref: '#/components/schemas/ExampleObject', }, }, 'image/png': { schema: { type: 'string', format: 'binary', }, }, '*/*': { schema: { type: 'string', }, }, }, }, responses: { '200': { description: 'hello world.', content: { 'application/json': { schema: { type: 'array', items: { $ref: '#/components/schemas/Car', }, }, examples: { example1: { $ref: '#/components/examples/Example', }, }, }, }, headers: { 'x-next': { description: 'A link to the next page of responses', schema: { type: 'string', }, }, }, }, '400': { description: 'error.', content: { 'application/json': { schema: { type: 'string', }, examples: { example1: { $ref: '#/components/examples/Example', }, }, }, }, headers: { 'fake-header': { description: 'A fake header', schema: { type: 'string', }, }, }, }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('api-with-examples', () => { const comment = _(() => { /** * GET / * @operationId listVersionsv2 * @summary List API versions * @response 200 - 200 response * @responseContent 200.application/json * @responseExample {Foo} 200.application/json.foo * @response 300 - 300 response * @responseContent 300.application/json * @responseExample {Foo} 300.application/json.foo */ }); const expected = { paths: { '/': { get: { operationId: 'listVersionsv2', summary: 'List API versions', responses: { '200': { description: '200 response', content: { 'application/json': { examples: { foo: { $ref: '#/components/examples/Foo', }, }, }, }, }, '300': { description: '300 response', content: { 'application/json': { examples: { foo: { $ref: '#/components/examples/Foo', }, }, }, }, }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('callback', () => { const comment = _(() => { /** * POST /streams * @description subscribes a client to receive out-of-band data * @queryParam {uri} callbackUrl - the location where data will be sent. Must be network accessible * by the source server * @response 201 - subscription successfully created * @responseContent {Custom} 201.application/json * @callback {Callback} onData */ }); const expected = { paths: { '/streams': { post: { description: 'subscribes a client to receive out-of-band data', parameters: [ { name: 'callbackUrl', in: 'query', required: true, description: 'the location where data will be sent. Must be network accessible\nby the source server', schema: { $ref: '#/components/schemas/uri', }, }, ], responses: { '201': { description: 'subscription successfully created', content: { 'application/json': { schema: { $ref: '#/components/schemas/Custom', }, }, }, }, }, callbacks: { onData: { $ref: '#/components/callbacks/Callback', }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('links', () => { const comment = _(() => { /** * GET /users/{username} * @operationId getUserByName * @pathParam {string} username * @response 200 - The User * @responseContent {User} 200.application/json * @responseLink {UserRepositories} 200.userRepositories */ }); const expected = { paths: { '/users/{username}': { get: { operationId: 'getUserByName', parameters: [ { name: 'username', in: 'path', required: true, schema: { type: 'string', }, }, ], responses: { '200': { description: 'The User', content: { 'application/json': { schema: { $ref: '#/components/schemas/User', }, }, }, links: { userRepositories: { $ref: '#/components/links/UserRepositories', }, }, }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('petstore', () => { const comment = _(() => { /** * GET /pets * @summary List all pets * @operationId listPets * @tag pets * @queryParam {int32} [limit] - How many items to return at one time (max 100) * @response 200 - A paged array of pets * @responseHeader {string} 200.x-next - A link to the next page of responses * @responseContent {Pets} 200.application/json * @response default - unexpected error * @responseContent {Error} default.application/json */ /** * POST /pets * @summary Create a pet * @operationId createPets * @tag pets * @response 201 - Null response * @response default - unexpected error * @responseContent {Error} default.application/json */ /** * GET /pets/{petId} * @summary Info for a specific pet * @operationId showPetById * @tag pets * @tag another tag with space * @pathParam {string} petId - The id of the pet to retrieve * @response 200 - Expected response to a valid request * @responseContent {Pets} 200.application/json * @response default - unexpected error * @responseContent {Error} default.application/json */ }); const expected1 = { paths: { '/pets': { get: { summary: 'List all pets', operationId: 'listPets', tags: ['pets'], parameters: [ { name: 'limit', in: 'query', description: 'How many items to return at one time (max 100)', required: false, schema: { type: 'integer', format: 'int32', }, }, ], responses: { '200': { description: 'A paged array of pets', headers: { 'x-next': { description: 'A link to the next page of responses', schema: { type: 'string', }, }, }, content: { 'application/json': { schema: { $ref: '#/components/schemas/Pets', }, }, }, }, default: { description: 'unexpected error', content: { 'application/json': { schema: { $ref: '#/components/schemas/Error', }, }, }, }, }, }, }, }, }; const expected2 = { paths: { '/pets': { post: { summary: 'Create a pet', operationId: 'createPets', tags: ['pets'], responses: { '201': { description: 'Null response', }, default: { description: 'unexpected error', content: { 'application/json': { schema: { $ref: '#/components/schemas/Error', }, }, }, }, }, }, }, }, }; const expected3 = { paths: { '/pets/{petId}': { get: { summary: 'Info for a specific pet', operationId: 'showPetById', tags: ['pets', 'another tag with space'], parameters: [ { name: 'petId', in: 'path', required: true, description: 'The id of the pet to retrieve', schema: { type: 'string', }, }, ], responses: { '200': { description: 'Expected response to a valid request', content: { 'application/json': { schema: { $ref: '#/components/schemas/Pets', }, }, }, }, default: { description: 'unexpected error', content: { 'application/json': { schema: { $ref: '#/components/schemas/Error', }, }, }, }, }, }, }, }, }; const specification = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal([expected1, expected2, expected3]); }); it('multiple response content types', () => { const comment = _(() => { /** * GET / * @response 200 - OK * @responseContent {Pet} 200.application/json * @responseContent {Pet} 200.application/xml */ }); const expected = { paths: { '/': { get: { responses: { '200': { description: 'OK', content: { 'application/json': { schema: { $ref: '#/components/schemas/Pet', }, }, 'application/xml': { schema: { $ref: '#/components/schemas/Pet', }, }, }, }, }, }, }, }, }; const [specification] = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.deep.equal(expected); }); it('does nothing for normal comment', () => { const comment = _(() => { /** * normal comment */ }); const specification = commentsToOpenApi(comment).map((i) => i.spec); expect(specification).to.have.lengthOf(0); }); });
the_stack
import { DiscordBot, IThirdPartyLookup } from "./bot"; import { DiscordBridgeConfig } from "./config"; import * as Discord from "better-discord.js"; import { Util } from "./util"; import { Log } from "./log"; const log = new Log("MatrixRoomHandler"); import { DbRoomStore, MatrixStoreRoom, RemoteStoreRoom } from "./db/roomstore"; import { Appservice, Intent, IApplicationServiceProtocol } from "matrix-bot-sdk"; const ICON_URL = "https://matrix.org/_matrix/media/r0/download/matrix.org/mlxoESwIsTbJrfXyAAogrNxA"; const HTTP_UNSUPPORTED = 501; const ROOM_NAME_PARTS = 2; const PROVISIONING_DEFAULT_POWER_LEVEL = 50; const PROVISIONING_DEFAULT_USER_POWER_LEVEL = 0; const USERSYNC_STATE_DELAY_MS = 5000; const ROOM_CACHE_MAXAGE_MS = 15 * 60 * 1000; // Note: The schedule must not have duplicate values to avoid problems in positioning. // Disabled because it complains about the values in the array const JOIN_ROOM_SCHEDULE = [ 0, // Right away 1000, // 1 second 30000, // 30 seconds 300000, // 5 minutes 900000, // 15 minutes ]; export class MatrixRoomHandler { private botUserId: string; constructor( private discord: DiscordBot, private config: DiscordBridgeConfig, private bridge: Appservice, private roomStore: DbRoomStore) { this.botUserId = this.discord.BotUserId; } public bindThirdparty() { this.bridge.on("thirdparty.protocol", (protocol: string, cb: (protocolResponse: IApplicationServiceProtocol) => void) => { this.tpGetProtocol(protocol) .then(cb) .catch((err) => log.warn("Failed to get protocol", err)); } ); // eslint-disable-next-line @typescript-eslint/no-explicit-any this.bridge.on("thirdparty.location.remote", (protocol: string, fields: any, cb: (response: any) => void) => { this.tpGetLocation(protocol, fields) .then(cb) .catch((err) => log.warn("Failed to get remote locations", err)); }); // These are not supported. this.bridge.on("thirdparty.location.matrix", (matrixId: string, cb: (response: null) => void) => { cb(null); }); this.bridge.on("thirdparty.user.remote", (matrixId: string, fields: unknown, cb: (response: null) => void) => { cb(null); }); this.bridge.on("thirdparty.user.matrix", (matrixId: string, cb: (response: null) => void) => { cb(null); }); } public async OnAliasQueried(alias: string, roomId: string): Promise<void> { log.verbose(`Got OnAliasQueried for ${alias} ${roomId}`); let channel: Discord.GuildChannel; try { // We previously stored the room as an alias. const entry = (await this.roomStore.getEntriesByMatrixId(alias))[0]; if (!entry) { throw new Error("Entry was not found"); } // Remove the old entry await this.roomStore.removeEntriesByMatrixRoomId( entry.matrix!.roomId, ); await this.roomStore.linkRooms( new MatrixStoreRoom(roomId), entry.remote!, ); channel = await this.discord.GetChannelFromRoomId(roomId) as Discord.GuildChannel; } catch (err) { log.error(`Cannot find discord channel for ${alias} ${roomId}`, err); throw err; } // Fire and forget RoomDirectory mapping this.bridge.setRoomDirectoryVisibility( channel.guild.id, roomId, "public", ).catch((err) => { log.warn("Failed to set room directory visibility for new room:", err); }); await this.discord.ChannelSyncroniser.OnUpdate(channel); const promiseList: Promise<void>[] = []; // Join a whole bunch of users. // We delay the joins to give some implementations a chance to breathe let delay = this.config.limits.roomGhostJoinDelay; for (const member of (channel as Discord.TextChannel).members.array()) { if (member.id === this.discord.GetBotId()) { continue; } promiseList.push((async (): Promise<void> => { await Util.DelayedPromise(delay); log.info(`UserSyncing ${member.id}`); try { // Ensure the profile is up to date. await this.discord.UserSyncroniser.OnUpdateUser(member.user); } catch (err) { log.warn(`Failed to update profile of user ${member.id}`, err); } log.info(`Joining ${member.id} to ${roomId}`); await this.joinRoom(this.discord.GetIntentFromDiscordMember(member), roomId, member); })()); delay += this.config.limits.roomGhostJoinDelay; } await Promise.all(promiseList); } // eslint-disable-next-line @typescript-eslint/no-explicit-any public async OnAliasQuery(alias: string): Promise<any> { const aliasLocalpart = alias.substring("#".length, alias.indexOf(":")); log.info("Got request for #", aliasLocalpart); const srvChanPair = aliasLocalpart.substring("_discord_".length).split("_", ROOM_NAME_PARTS); if (srvChanPair.length < ROOM_NAME_PARTS || srvChanPair[0] === "" || srvChanPair[1] === "") { log.warn(`Alias '${aliasLocalpart}' was missing a server and/or a channel`); return; } try { const result = await this.discord.LookupRoom(srvChanPair[0], srvChanPair[1]); log.info("Creating #", aliasLocalpart); return this.createMatrixRoom(result.channel, alias, aliasLocalpart); } catch (err) { log.error(`Couldn't find discord room '${aliasLocalpart}'.`, err); } } public async tpGetProtocol(protocol: string): Promise<IApplicationServiceProtocol> { const instances = {}; for (const guild of this.discord.GetGuilds()) { instances[guild.name] = { /* eslint-disable @typescript-eslint/camelcase */ bot_user_id: this.botUserId, desc: guild.name, fields: { guild_id: guild.id, }, icon: guild.iconURL || ICON_URL, network_id: guild.id, /* eslint-enable @typescript-eslint/camelcase */ }; } return { /* eslint-disable @typescript-eslint/camelcase */ field_types: { // guild_name: { // regexp: "\S.{0,98}\S", // placeholder: "Guild", // }, channel_id: { placeholder: "", regexp: "[0-9]*", }, channel_name: { placeholder: "#Channel", regexp: "[A-Za-z0-9_\-]{2,100}", }, discriminator: { placeholder: "1234", regexp: "[0-9]{4}", }, guild_id: { placeholder: "", regexp: "[0-9]*", }, username: { placeholder: "Username", regexp: "[A-Za-z0-9_\-]{2,100}", }, }, icon: "", // TODO: Add this. instances, location_fields: ["guild_id", "channel_name"], user_fields: ["username", "discriminator"], /* eslint-enable @typescript-eslint/camelcase */ }; } // eslint-disable-next-line @typescript-eslint/no-explicit-any public async tpGetLocation(protocol: string, fields: any): Promise<IThirdPartyLookup[]> { log.info("Got location request ", protocol, fields); const chans = this.discord.ThirdpartySearchForChannels(fields.guild_id, fields.channel_name); return chans; } private async joinRoom(intent: Intent, roomIdOrAlias: string, member?: Discord.GuildMember): Promise<void> { let currentSchedule = JOIN_ROOM_SCHEDULE[0]; const doJoin = async (): Promise<void> => { await Util.DelayedPromise(currentSchedule); if (member) { await this.discord.UserSyncroniser.JoinRoom(member, roomIdOrAlias); } else { await intent.joinRoom(roomIdOrAlias); } }; const errorHandler = async (err): Promise<void> => { log.error(`Error joining room ${roomIdOrAlias} as ${intent.userId}`); log.error(err); const idx = JOIN_ROOM_SCHEDULE.indexOf(currentSchedule); if (idx === JOIN_ROOM_SCHEDULE.length - 1) { log.warn(`Cannot join ${roomIdOrAlias} as ${intent.userId}`); throw new Error(err); } else { currentSchedule = JOIN_ROOM_SCHEDULE[idx + 1]; try { await doJoin(); } catch (e) { await errorHandler(e); } } }; try { await doJoin(); } catch (e) { await errorHandler(e); } } private async createMatrixRoom( channel: Discord.TextChannel, alias: string, aliasLocalpart: string ) { const remote = new RemoteStoreRoom(`discord_${channel.guild.id}_${channel.id}`, { /* eslint-disable @typescript-eslint/camelcase */ discord_channel: channel.id, discord_guild: channel.guild.id, discord_type: "text", update_icon: 1, update_name: 1, update_topic: 1, /* eslint-enable @typescript-eslint/camelcase */ }); const creationOpts = { /* eslint-disable @typescript-eslint/camelcase */ initial_state: [ { content: { join_rule: "public", }, state_key: "", type: "m.room.join_rules", }, ], room_alias_name: aliasLocalpart, visibility: this.config.room.defaultVisibility, /* eslint-enable @typescript-eslint/camelcase */ }; // We need to tempoarily store this until we know the room_id. await this.roomStore.linkRooms( new MatrixStoreRoom(alias), remote, ); return creationOpts; } }
the_stack
import axios, { AxiosResponse } from "axios"; import cookie from "cookie"; import { Entity, EntityCreateData, EntityCreatePayload, EntityUpdateData, EntityUpdatePayload, Paper, Paginated, PaperIdWithEntityCounts, EntityGetResponse, Citation, Equation, Sentence, Symbol, Term, } from "./types"; import { Entity as DedupedEntity, DedupedEntityResponse, isCitation, isEquation, isSentence, isSymbol, isTerm, toLegacyRelationship } from "./deduped"; import { Nullable } from "../types/ui"; const token = cookie.parse(document.cookie)["readerAdminToken"]; const config = { headers: { Authorization: `Bearer ${token}` } }; export async function listPapers(offset: number = 0, size: number = 25) { return axios.get<Paginated<PaperIdWithEntityCounts>>( "/api/v0/papers/list", { params: { offset, size } } ); } /** * API request for paper details need to be batched as it seems that in production, * when more than around 50 paper Ids are requested at once, sometimes the API fails to respond. * @param s2Ids list of Ids of all the papers cited in this paper */ export async function getPapers(s2Ids: string[]) { const PAPER_REQUEST_BATCH_SIZE = 50; // Use a set to remove dupes const dedupeIds = [...new Set(s2Ids)]; // Use .reduce() to break into chunks const s2IdsBatch = dedupeIds.reduce((chunks, s2Id, index) => { const chunkIndex = Math.floor(index / PAPER_REQUEST_BATCH_SIZE); if (chunks[chunkIndex]) { chunks[chunkIndex].push(s2Id); } else { chunks[chunkIndex] = [s2Id]; } return chunks; }, [[]] as string[][]); // Await the results within the async function, use async function in map const results = await Promise.all(s2IdsBatch.map(async (s2Ids) => { const result = await doGet( axios.get<Paper[]>("/api/v0/papers", { params: { id: s2Ids.join(","), }, })); // ...process result return result || []; })); // Use `[].concat(...) to flatten array return ([] as Paper[]).concat(...results); } const ENTITY_API_ALL = 'all'; export async function getEntities(arxivId: string, getAllEntities?: boolean) { const params = getAllEntities ? { type: ENTITY_API_ALL } : {}; const data = await doGet( axios.get(`/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities`, { params }) ); return ((data as any).data || []) as Entity[]; } export async function getPaper(s2Id: string): Promise<Nullable<Paper>> { const data = await doGet( axios.get<Paper>(`/api/v0/paper/${encodeURIComponent(s2Id)}`, { })); return data; } // This translates from the entities-deduped API's response to the legacy // super-duplicated API response, as a compat shim. // TODO: phase this out in favor of using a more efficient data model in the reader app. function undedupeResponse(response: DedupedEntityResponse): EntityGetResponse { // TODO: Improve error handling; this just pulls the eject handle if the response is an API error if (!!(response as any).error) { throw "API error: " + (response as any).error; } const entities: Entity[] = response.entities.map((deduped: DedupedEntity) => { if (isCitation(deduped)) { const citation: Citation = { id: deduped.id, type: 'citation', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, paper_id: deduped.attributes.paper_id, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], }, relationships: {}, }; return citation; } else if (isEquation(deduped)) { const equation: Equation = { id: deduped.id, type: 'equation', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], tex: deduped.attributes.tex, }, relationships: {}, }; return equation; } else if (isSentence(deduped)) { const sentence: Sentence = { id: deduped.id, type: 'sentence', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], tex: deduped.attributes.tex, tex_start: deduped.attributes.tex_start, tex_end: deduped.attributes.tex_end, text: deduped.attributes.text, }, relationships: {}, }; return sentence; } else if (isSymbol(deduped)) { // empty string is a safe default, there shouldn't be sharedSymbolData for empty string. const disambiguatedId = deduped.attributes.disambiguated_id || ''; const symbol: Symbol = { id: deduped.id, type: 'symbol', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], tex: deduped.attributes.tex, type: deduped.attributes.type, mathml: deduped.attributes.mathml, mathml_near_matches: deduped.attributes.mathml_near_matches, diagram_label: deduped.attributes.diagram_label, is_definition: deduped.attributes.is_definition, nicknames: deduped.attributes.nicknames, definitions: response.sharedSymbolData[disambiguatedId]?.definitions || [], defining_formulas: response.sharedSymbolData[disambiguatedId]?.defining_formulas || [], passages: deduped.attributes.passages, snippets: response.sharedSymbolData[disambiguatedId]?.snippets || [], }, relationships: { equation: toLegacyRelationship( deduped.relationships.equation, 'equation' ), children: deduped.relationships.children.map( (c) => toLegacyRelationship(c, 'symbol') ), parent: toLegacyRelationship(deduped.relationships.parent, 'symbol'), sentence: toLegacyRelationship( deduped.relationships.sentence, 'sentence' ), nickname_sentences: deduped.relationships.nickname_sentences.map( (n) => toLegacyRelationship(n, 'sentence') ), defining_formula_equations: ( response.sharedSymbolData[disambiguatedId]?.defining_formula_equations || [] ).map((s) => toLegacyRelationship(s, 'equation')), definition_sentences: ( response.sharedSymbolData[disambiguatedId]?.definition_sentences || [] ).map((s) => toLegacyRelationship(s, 'sentence')), snippet_sentences: ( response.sharedSymbolData[disambiguatedId]?.snippet_sentences || [] ).map((s) => toLegacyRelationship(s, 'sentence')), }, }; return symbol; } else if (isTerm(deduped)) { const term: Term = { id: deduped.id, type: 'term', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, name: deduped.attributes.name, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], term_type: deduped.attributes.term_type, definitions: deduped.attributes.definitions, definition_texs: deduped.attributes.definition_texs, sources: deduped.attributes.sources, snippets: deduped.attributes.snippets, }, relationships: { sentence: toLegacyRelationship( deduped.relationships.sentence, 'sentence' ), definition_sentences: ( deduped.relationships.definition_sentences || [] ).map((s) => toLegacyRelationship(s, 'sentence')), snippet_sentences: ( deduped.relationships.snippet_sentences || [] ).map((s) => toLegacyRelationship(s, 'sentence')), }, }; return term; } // There's a new kind of entity that hasn't been implemented in the UI. throw "Unknown entity type"; }); return { data: entities, }; } /** * This API returns a compacted representation of the paper's entities and their relationships. * Certain fields of Symbol entity data are pulled into a separate `sharedSymbolData` map, * which is organized by the Symbols' `attributes.disambiguated_id` value. * * NOTE: Currently, this function passes the response through a transform function to make * it compatible with the existing UI code. * * @param arxivId arXiv ID of the viewed paper * @param getAllEntities `true` retrieves entities of all types, `false` retrieves only citations * @returns */ export async function getDedupedEntities(arxivId: string, getAllEntities?: boolean) { const params = getAllEntities ? { type: ENTITY_API_ALL } : {}; const data = await doGet( axios.get<EntityGetResponse>( `/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities-deduped`, { params, //@ts-ignore -- TODO: this pattern works in other projects, is there a version issue somewhere? transformResponse: [].concat(axios.defaults.transformResponse).concat(undedupeResponse) } ) ); return data?.data || []; } export async function postEntity( arxivId: string, data: EntityCreateData ): Promise<Entity | null> { try { const response = await axios.post( `/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities`, { data } as EntityCreatePayload ); if (response.status === 201) { return (response.data as any).data as Entity; } } catch (e) { console.error("Unexpected response from API for POST entity request.", e); } return null; } export async function patchEntity( arxivId: string, data: EntityUpdateData ): Promise<boolean> { const response = await axios.patch( `/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities/${encodeURIComponent(data.id)}`, { data } as EntityUpdatePayload, config ); if (response.status === 204) { return true; } console.error( "Unexpected response from API for PATCH entity request.", response ); return false; } export async function deleteEntity( arxivId: string, id: string ): Promise<boolean> { const response = await axios.delete( `/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities/${encodeURIComponent(id)}`, config ); if (response.status === 204) { return true; } console.error( "Unexpected response from API for DELETE entity request.", response ); return false; } /** * 'get' is a Promise returned by 'axios.get()' */ async function doGet<T>(get: Promise<AxiosResponse<T>>) { try { const response = await get; if (response.status === 200) { return response.data; } else { console.error(`API Error: Unexpected response ${response}`); } } catch (error) { console.error("API Error:", error); } return null; }
the_stack
import {Unsubscribe} from 'redux'; import {deepMerge, LoadingState, TaskCounter} from './sprite'; import {env} from './env'; declare const process: any; /** * 可供设置的全局参数,参见setConfig * - NSP 默认为. ModuleName${NSP}ActionName 用于ActionName的连接 * - MSP 默认为, 用于一个ActionHandler同时监听多个Action的连接 * - SSRKey 默认为 meduxInitStore 用于SSR同构时传递data * - MutableData 默认为 false 不使用可变数据 * - DEVTOOLS 默认为仅开发环境,是否使用chrome reduxDevTools */ export const config: { NSP: string; MSP: string; MutableData: boolean; DEVTOOLS: boolean; } = { NSP: '.', MSP: ',', MutableData: false, DEVTOOLS: process.env.NODE_ENV === 'development', }; /** * 可供设置的全局参数 * @param _config 设置参数 * - NSP 默认为. ModuleName${NSP}ActionName 用于ActionName的连接 * - MSP 默认为, 用于一个ActionHandler同时监听多个Action的连接 */ export function setConfig(_config: {NSP?: string; MSP?: string; SSRKey?: string; MutableData?: boolean; DEVTOOLS?: boolean}) { _config.NSP !== undefined && (config.NSP = _config.NSP); _config.MSP !== undefined && (config.MSP = _config.MSP); _config.MutableData !== undefined && (config.MutableData = _config.MutableData); _config.DEVTOOLS !== undefined && (config.DEVTOOLS = _config.DEVTOOLS); } export function warn(str: string) { if (process.env.NODE_ENV === 'development') { env.console.warn(str); } } export function deepMergeState(target: any = {}, ...args: any[]) { if (config.MutableData) { return deepMerge(target, ...args); } return deepMerge({}, target, ...args); } export function mergeState(target: any = {}, ...args: any[]) { if (config.MutableData) { return Object.assign(target, ...args); } return Object.assign({}, target, ...args); } export function snapshotState(target: any) { if (config.MutableData) { return JSON.parse(JSON.stringify(target)); } return target; } export interface CommonModule<ModuleName extends string = string> { default: { moduleName: ModuleName; initState: CoreModuleState; model: (store: ModuleStore) => void | Promise<void>; views: { [key: string]: any; }; actions: { [actionName: string]: (...args: any[]) => Action; }; }; } /** * 框架内置的几个ActionTypes */ export const ActionTypes = { /** * 为模块注入加载状态时使用ActionType:{moduleName}.{MLoading} */ MLoading: 'Loading', /** * 模块初始化时使用ActionType:{moduleName}.{MInit} */ MInit: 'Init', /** * 模块初始化时使用ActionType:{moduleName}.{MReInit} */ MReInit: 'ReInit', /** * 全局捕获到错误时使用ActionType:{Error} */ Error: `medux${config.NSP}Error`, }; /** * 一个数据结构用来指示如何获取模块,允许同步或异步获取 */ export type ModuleGetter = { [moduleName: string]: () => CommonModule | Promise<CommonModule>; }; export interface FacadeMap { [moduleName: string]: {name: string; actions: ActionCreatorList; actionNames: {[key: string]: string}}; } export const MetaData: { facadeMap: FacadeMap; clientStore: ModuleStore; appModuleName: string; appViewName: string; moduleGetter: ModuleGetter; currentData: { actionName: string; prevState: any; }; } = { currentData: {actionName: '', prevState: null}, } as any; export function getAppModuleName(): string { return MetaData.appModuleName; } const loadings: {[moduleName: string]: TaskCounter} = {}; let depthTime = 2; /** * 设置深度加载的时间阀值 * @param second 超过多少秒进入深度加载,默认为2秒 */ export function setLoadingDepthTime(second: number) { depthTime = second; } /** * 手动设置Loading状态,同一个key名的loading状态将自动合并 * - 参见LoadingState * @param item 一个Promise加载项 * @param moduleName moduleName+groupName合起来作为该加载项的key * @param groupName moduleName+groupName合起来作为该加载项的key */ export function setLoading<T extends Promise<any>>(item: T, moduleName: string = MetaData.appModuleName, groupName = 'global'): T { if (env.isServer) { return item; } const key = moduleName + config.NSP + groupName; if (!loadings[key]) { loadings[key] = new TaskCounter(depthTime); loadings[key].addListener((loadingState) => { const store = MetaData.clientStore; if (store) { const actions = MetaData.facadeMap[moduleName].actions[ActionTypes.MLoading]; const action = actions({[groupName]: loadingState}); store.dispatch(action); } }); } loadings[key].addItem(item); return item; } /** * Medux自动创建的action载体,比redux的action载体多一个priority属性 * * 因为一个action可以触发多个模块的actionHandler,priority属性用来设置handlers的优先处理顺序,通常无需设置 */ export interface Action { type: string; /** * priority属性用来设置handlers的优先处理顺序,值为moduleName[] */ priority?: string[]; payload?: any[]; } export type Dispatch = (action: Action) => any; interface Store { dispatch(action: Action): Action | Promise<void>; getState(): {[key: string]: any}; subscribe(listener: () => void): Unsubscribe; destroy: () => void; } export interface ActionHandler { __actionName__: string; __isReducer__?: boolean; __isEffect__?: boolean; __isHandler__?: boolean; __decorators__?: [ (action: Action, moduleName: string, effectResult: Promise<any>) => any, null | ((status: 'Rejected' | 'Resolved', beforeResult: any, effectResult: any) => void) ][]; __decoratorResults__?: any[]; (payload?: any): any; } export interface ReducerHandler extends ActionHandler { (payload: any): CoreModuleState; } export interface EffectHandler extends ActionHandler { (payload: any, prevRootState: CoreRootState): Promise<any>; } export interface ActionHandlerList { [actionName: string]: ActionHandler; } export interface ActionHandlerMap { [actionName: string]: {[moduleName: string]: ActionHandler}; } export interface ReducerMap extends ActionHandlerMap { [actionName: string]: {[moduleName: string]: ReducerHandler}; } export interface EffectMap extends ActionHandlerMap { [actionName: string]: {[moduleName: string]: EffectHandler}; } export interface ModuleStore extends Store { _medux_: { reducerMap: ReducerMap; effectMap: EffectMap; injectedModules: {[moduleName: string]: boolean | undefined}; realtimeState: CoreRootState; currentState: CoreRootState; }; } /** * 所有ModuleState的固定属性 */ export interface CoreModuleState { initialized?: boolean; /** * 该模块的各种loading状态,执行effect时会自动注入loading状态 */ loading?: { [key: string]: LoadingState; }; } export type CoreRootState = { [moduleName: string]: CoreModuleState; }; /** * 模块Model的数据结构,该数据由ExportModule方法自动生成 */ export type ModuleModel = (store: ModuleStore) => void | Promise<void>; export interface ActionCreatorMap { [moduleName: string]: ActionCreatorList; } export interface ActionCreatorList { [actionName: string]: ActionCreator; } export type ActionCreator = (...args: any[]) => Action; /** * 一个类方法的装饰器,用来指示该方法为一个reducerHandler * - reducerHandler必须通过dispatch Action来触发 */ export function reducer(target: any, key: string, descriptor: PropertyDescriptor) { if (!key && !descriptor) { key = target.key; descriptor = target.descriptor; } const fun = descriptor.value as ActionHandler; fun.__actionName__ = key; fun.__isReducer__ = true; descriptor.enumerable = true; return target.descriptor === descriptor ? target : descriptor; } /** * 一个类方法的装饰器,用来指示该方法为一个effectHandler * - effectHandler必须通过dispatch Action来触发 * @param loadingForGroupName 注入加载状态的分组key,默认为global,如果为null表示不注入加载状态 * @param loadingForModuleName 可将loading状态合并注入到其他module,默认为入口主模块 * * ``` * effect(null) 不注入加载状态 * effect() == effect('global','app') * effect('global') = effect('global',thisModuleName) * ``` */ export function effect(loadingForGroupName?: string | null, loadingForModuleName?: string) { if (loadingForGroupName === undefined) { loadingForGroupName = 'global'; loadingForModuleName = MetaData.appModuleName || ''; } return (target: any, key: string, descriptor: PropertyDescriptor) => { if (!key && !descriptor) { key = target.key; descriptor = target.descriptor; } const fun = descriptor.value as ActionHandler; fun.__actionName__ = key; fun.__isEffect__ = true; descriptor.enumerable = true; if (loadingForGroupName) { const before = (curAction: Action, moduleName: string, promiseResult: Promise<any>) => { if (!env.isServer) { if (loadingForModuleName === '') { loadingForModuleName = MetaData.appModuleName; } else if (!loadingForModuleName) { loadingForModuleName = moduleName; } setLoading(promiseResult, loadingForModuleName, loadingForGroupName as string); } }; if (!fun.__decorators__) { fun.__decorators__ = []; } fun.__decorators__.push([before, null]); } return target.descriptor === descriptor ? target : descriptor; }; } /** * 一个类方法的装饰器,用来向reducerHandler或effectHandler中注入before和after的钩子 * - 注意不管该handler是否执行成功,前后钩子都会强制执行 * @param before actionHandler执行前的钩子 * @param after actionHandler执行后的钩子 */ export function logger( before: (action: Action, moduleName: string, promiseResult: Promise<any>) => void, after: null | ((status: 'Rejected' | 'Resolved', beforeResult: any, effectResult: any) => void) ) { return (target: any, key: string, descriptor: PropertyDescriptor) => { if (!key && !descriptor) { key = target.key; descriptor = target.descriptor; } const fun: ActionHandler = descriptor.value; if (!fun.__decorators__) { fun.__decorators__ = []; } fun.__decorators__.push([before, after]); }; } /** * 一个类方法的装饰器,将其延迟执行 * - 可用来装饰effectHandler * - 也可以装饰其他类 * @param second 延迟秒数 */ export function delayPromise(second: number) { return (target: any, key: string, descriptor: PropertyDescriptor) => { if (!key && !descriptor) { key = target.key; descriptor = target.descriptor; } const fun = descriptor.value; descriptor.value = (...args: any[]) => { const delay = new Promise((resolve) => { env.setTimeout(() => { resolve(true); }, second * 1000); }); return Promise.all([delay, fun.apply(target, args)]).then((items) => { return items[1]; }); }; }; } export function isPromise(data: any): data is Promise<any> { return typeof data === 'object' && typeof data.then === 'function'; } export function isServer(): boolean { return env.isServer; } export function serverSide<T>(callback: () => T) { if (env.isServer) { return callback(); } return undefined; } export function clientSide<T>(callback: () => T) { if (!env.isServer) { return callback(); } return undefined; }
the_stack
import { AppContext, IAppContextProps } from "../../Common/AppContextProps"; import { IProfileCardProperty } from "../../Entities/IProfileCardProperty"; import { IAnnotation, ILocalization } from "../../Entities/IAnnotations"; import { languages, DirectoryPropertyName } from "../../Common/constants"; import { DefaultButton, PrimaryButton, } from "office-ui-fabric-react/lib/Button"; import { Panel, PanelType } from "office-ui-fabric-react/lib/Panel"; import { useConstCallback } from "@uifabric/react-hooks"; import React, { useContext, useEffect } from "react"; import { useProfileCardProperties } from "../../hooks/useProfileCardProperties"; import { IAddProfileCardPropertyProps } from "../AddProfileCardProperty/IAddProfileCardPropertyProps"; import { IAddProfileCardPropertyState } from "../AddProfileCardProperty/IAddProfileCardPropertyState"; import * as _ from "lodash"; import { Stack, ComboBox, TextField, Label, Icon, IComboBox, CommandButton, IIconProps, initializeIcons, IComboBoxOption, mergeStyleSets, IIconStyles, ILabelStyles, Spinner, SpinnerSize, MessageBar, MessageBarType, } from "office-ui-fabric-react"; import { ILocalizationExtended } from "../../Entities/IlocalizationExtended"; import strings from "ManageProfileCardPropertiesWebPartStrings"; // Component // Add Profile Property Component export const AddProfileCardProperty: React.FunctionComponent<IAddProfileCardPropertyProps> = ( props: IAddProfileCardPropertyProps ) => { const applicationContext: IAppContextProps = useContext(AppContext); // Get React Context const newIcon: IIconProps = { iconName: "Add" }; const { displayPanel, onDismiss } = props; const { newProfileCardProperty } = useProfileCardProperties(); // Get method from hook // Component Styles const compomentStyles = mergeStyleSets({ addButtonContainer: { width: 60, display: "Flex", paddingTop: 15, paddingRight: 10, alignContent: "center", justifyContent: "center", }, }); // Icon styles of labels const iconlabelsStyles: IIconStyles = { root: { fontSize: 26, color: applicationContext.themeVariant.palette.themePrimary, }, }; // Label Styles const labelStyles: ILabelStyles = { root: { fontSize: 16 }, }; // Language Options const _languagesOptions: IComboBoxOption[] = languages.map((language, i) => ({ key: language.languageTag, text: `${language.displayName} (${language.languageTag})`, })); const [state, setState] = React.useState<IAddProfileCardPropertyState>({ isloading: false, hasError: false, errorMessage: "", isSaving: false, displayPanel: displayPanel, profileCardProperties: { directoryPropertyName: "", annotations: [{ displayName: "", localizations: [] }], }, disableAdd: true, addLocalizationItem: {} as ILocalizationExtended, languagesOptions: _languagesOptions, directoryPropertyOptions: [], }); // Run on Compoment did mount useEffect(() => { (() => { const { listItems } = applicationContext; const _directoryPropertyOptions: IComboBoxOption[] = []; // Check if the Property already selected for (const directoryProperty of DirectoryPropertyName) { const directoryPropertyExists = _.findKey(listItems, { key: directoryProperty, }); if (directoryPropertyExists) continue; // Already Exist Property _directoryPropertyOptions.push({ key: directoryProperty, text: directoryProperty, }); } // update component State setState({ ...state, directoryPropertyOptions: _directoryPropertyOptions, profileCardProperties: { annotations: [{ displayName: "", localizations: [] }], directoryPropertyName: _directoryPropertyOptions[0].key.toString(), }, }); })(); }, []); // Button Styles const buttonStyles = { root: { marginRight: 8 } }; // On dismiss Panel const _dismissPanel = useConstCallback(() => { setState({ ...state, displayPanel: false }); onDismiss(true); }); // On Change Display Name const _onChangeDisplayName = ( ev: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, value: string ) => { ev.preventDefault(); let { profileCardProperties } = state; profileCardProperties.annotations[0].displayName = value; setState({ ...state, profileCardProperties: profileCardProperties }); }; // On Direwctory Property Change const _onDirectoryPropertyChange = ( ev: React.FormEvent<IComboBox>, option?: IComboBoxOption ) => { ev.preventDefault(); let { profileCardProperties } = state; profileCardProperties.directoryPropertyName = option.text; setState({ ...state, profileCardProperties: profileCardProperties }); }; // On Language Change const _onLanguageChange = ( ev: React.FormEvent<IComboBox>, option?: IComboBoxOption ) => { ev.preventDefault(); console.log(option); let { addLocalizationItem } = state; addLocalizationItem = { ...addLocalizationItem, languageTag: option.key.toString(), languageDescription: option.text, }; if (addLocalizationItem.displayName && addLocalizationItem.languageTag) { setState({ ...state, disableAdd: false, addLocalizationItem: addLocalizationItem, }); } else { setState({ ...state, disableAdd: true, addLocalizationItem: addLocalizationItem, }); } }; // On Change LocalizationDisplayName const _onChangeLocalizationisplayName = ( ev: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, value: string ) => { ev.preventDefault(); let { addLocalizationItem } = state; addLocalizationItem = { ...addLocalizationItem, displayName: value }; if (addLocalizationItem.displayName && addLocalizationItem.languageTag) { setState({ ...state, disableAdd: false, addLocalizationItem: addLocalizationItem, }); } else { setState({ ...state, disableAdd: true, addLocalizationItem: addLocalizationItem, }); } }; // onCLick Add Property const _onAddProperty = async (ev: React.MouseEvent<HTMLButtonElement>) => { ev.preventDefault(); const { msGraphClient, organizationId } = applicationContext; const { profileCardProperties } = state; const _localizationsExtended = profileCardProperties.annotations[0].localizations; setState({...state, isSaving: true, disableAdd: true}); let _profileCardProperty: IProfileCardProperty = {} as IProfileCardProperty; let _localizations: ILocalization[] = []; for (const _localizationExtended of _localizationsExtended) { _localizations.push({ displayName: _localizationExtended.displayName, languageTag: _localizationExtended.languageTag, }); } let _annotations: IAnnotation[] = [ { displayName: profileCardProperties.annotations[0].displayName, localizations: _localizations, }, ]; _profileCardProperty = { directoryPropertyName: profileCardProperties.directoryPropertyName, annotations: _annotations, }; try { const newProfileCardProperties = await newProfileCardProperty( msGraphClient, organizationId, _profileCardProperty ); onDismiss(true); } catch (error) { const _errorMessage:string = error.message ? error.message : strings.DefaultErrorMessageText; setState({ ...state, hasError: true, errorMessage: _errorMessage , isSaving: false, disableAdd: false}); console.log(error); } }; //************************************************************************************************* */ // On Render Footer //************************************************************************************************* */ const _onRenderFooterContent = (): JSX.Element => { const { profileCardProperties, isSaving } = state; let disableAddButton: boolean = true; if ( profileCardProperties.directoryPropertyName && profileCardProperties.annotations[0].displayName ) { disableAddButton = false; } return ( <div> <PrimaryButton disabled={disableAddButton} onClick={_onAddProperty} styles={buttonStyles} > {isSaving ? ( <Spinner size={SpinnerSize.xSmall}></Spinner> ) : ( strings.SaveButtonText )} </PrimaryButton> <DefaultButton onClick={_dismissPanel}> {strings.CancelButtonText} </DefaultButton> </div> ); }; // On add new localization const _onAddNewLocalization = (ev: React.MouseEvent<HTMLButtonElement>) => { ev.preventDefault(); // tslint:disable-next-line: no-shadowed-variable const { profileCardProperties, addLocalizationItem, // tslint:disable-next-line: no-shadowed-variable languagesOptions, } = state; let _localizations = profileCardProperties.annotations[0].localizations; _localizations.push(addLocalizationItem); profileCardProperties.annotations[0].localizations = _localizations; const { languageTag } = addLocalizationItem; const newLaguageOptions: IComboBoxOption[] = _.filter( languagesOptions, (l) => { return l.key !== languageTag; } ); // Update State setState({ ...state, profileCardProperties: profileCardProperties, addLocalizationItem: { displayName: "", languageTag: "", languageDescription: "", }, languagesOptions: newLaguageOptions, }); }; // on Delete Localization const _onDeleteLocalization = (ev: React.MouseEvent<HTMLButtonElement>) => { // tslint:disable-next-line: no-shadowed-variable let { languagesOptions, profileCardProperties } = state; const _languageTag = ev.currentTarget.getAttribute("data-language-tag"); let _localizations: ILocalization[] = profileCardProperties.annotations[0].localizations; // get all localization without the deleted localization const newlocalizations: ILocalization[] = _.filter(_localizations, (l) => { return l.languageTag !== _languageTag; }); // Add new localization without the deleted localization profileCardProperties.annotations[0].localizations = newlocalizations; // Get Deleted Localization const deletedLocalization: ILocalization[] = _.filter( _localizations, (l) => { return l.languageTag == _languageTag; } ); // Add deleted Localization to combo box of language const _deletedLocalization: ILocalizationExtended = deletedLocalization[0] as ILocalizationExtended; languagesOptions.push({ key: _deletedLocalization.languageTag, text: `${_deletedLocalization.languageDescription}`, }); // Re render component setState({ ...state, profileCardProperties: profileCardProperties, languagesOptions: _.sortBy(languagesOptions, ["text"]), // Sort language Options }); }; //************************************************************************************************* */ // Test if there are Profile Card Properties //************************************************************************************************* */ let { annotations, directoryPropertyName } = state.profileCardProperties; let _displayName: string = ""; let localizations: ILocalization[] = []; if (annotations) { _displayName = annotations[0].displayName; if (annotations[0].localizations) { localizations = annotations[0].localizations; } } /* if (!directoryPropertyName) { directoryPropertyName = directoryPropertyOptions[0].key.toString(); } */ //************************************************************************************************* */ // Render Control //************************************************************************************************* */ const { isloading, hasError, errorMessage, languagesOptions, directoryPropertyOptions, } = state; if (isloading) { return <Spinner size={SpinnerSize.medium} label={strings.LoadingText} />; } return ( <> <Panel isOpen={state.displayPanel} onDismiss={_dismissPanel} type={PanelType.custom} customWidth={"600px"} closeButtonAriaLabel="Close" headerText={strings.AddPanelHeaderText} onRenderFooterContent={_onRenderFooterContent} isFooterAtBottom={true} > <Stack style={{ marginTop: 30, marginBottom: 30 }} horizontal={true} tokens={{ childrenGap: 10 }} horizontalAlign="start" verticalAlign="center" > {hasError && ( <MessageBar messageBarType={MessageBarType.error}> {errorMessage} </MessageBar> )} <Icon iconName="EditContact" styles={iconlabelsStyles}></Icon> <Label styles={labelStyles}>{strings.PanelHeaderLabel}</Label> </Stack> <Stack tokens={{ childrenGap: 10 }}> <ComboBox required={true} label="Directory Property Name" allowFreeform={false} autoComplete="on" selectedKey={directoryPropertyName} onChange={_onDirectoryPropertyChange} options={directoryPropertyOptions} /> <TextField required={true} label="Display Name" autoComplete="on" name="displayName" value={_displayName} validateOnLoad={false} validateOnFocusOut={true} onGetErrorMessage={(value: string) => { if (!value) { return "Field is Required"; } else { return; } }} onChange={_onChangeDisplayName} /> <Stack style={{ marginTop: 30 }} horizontal={true} tokens={{ childrenGap: 10 }} horizontalAlign="start" verticalAlign="center" > <Icon iconName="World" styles={iconlabelsStyles}></Icon> <Label styles={labelStyles}>Localization</Label> </Stack> <Stack horizontal={true} tokens={{ childrenGap: 10 }} horizontalAlign="start" verticalAlign="center" > <ComboBox required={true} label="Language" styles={{ root: { width: 300 } }} dropdownWidth={300} allowFreeform autoComplete="on" selectedKey={state.addLocalizationItem.languageTag} options={languagesOptions} onChange={_onLanguageChange} /> <TextField required={true} label="Display Name" styles={{ field: { width: 190 } }} value={state.addLocalizationItem.displayName} onChange={_onChangeLocalizationisplayName} /> <div className={compomentStyles.addButtonContainer}> <CommandButton iconProps={newIcon} title="Add" ariaLabel="Add" onClick={_onAddNewLocalization} styles={{ icon: { fontSize: 26 }, }} disabled={state.disableAdd} /> </div> </Stack> <div style={{ height: "100%", overflow: "auto" }}> {localizations.map( (localization: ILocalizationExtended, i: number) => { return ( <> <Stack horizontal={true} tokens={{ childrenGap: 10 }} horizontalAlign="start" verticalAlign="center" styles={{ root: { marginTop: 5 } }} > <TextField disabled styles={{ root: { width: 300 }, field: { color: applicationContext.themeVariant.semanticColors .inputText, }, }} value={localization.languageDescription} /> <TextField disabled styles={{ field: { color: applicationContext.themeVariant.semanticColors .inputText, width: 190, }, }} value={localization.displayName} /> <CommandButton iconProps={{ iconName: "Delete" }} data-language-tag={localization.languageTag} title="Delete" ariaLabel="Delete" styles={{ icon: { fontSize: 26 }, }} onClick={_onDeleteLocalization} /> </Stack> </> ); } )} </div> </Stack> </Panel> </> ); };
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a Live Event. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleAccount = new azure.storage.Account("exampleAccount", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * accountTier: "Standard", * accountReplicationType: "GRS", * }); * const exampleServiceAccount = new azure.media.ServiceAccount("exampleServiceAccount", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * storageAccounts: [{ * id: exampleAccount.id, * isPrimary: true, * }], * }); * const exampleLiveEvent = new azure.media.LiveEvent("exampleLiveEvent", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * mediaServicesAccountName: exampleServiceAccount.name, * description: "My Event Description", * input: { * streamingProtocol: "RTMP", * ipAccessControlAllows: [{ * name: "AllowAll", * address: "0.0.0.0", * subnetPrefixLength: 0, * }], * }, * encoding: { * type: "Standard", * presetName: "Default720p", * stretchMode: "AutoFit", * keyFrameInterval: "PT2S", * }, * preview: { * ipAccessControlAllows: [{ * name: "AllowAll", * address: "0.0.0.0", * subnetPrefixLength: 0, * }], * }, * useStaticHostname: true, * hostnamePrefix: "special-event", * transcriptionLanguages: ["en-US"], * }); * ``` * * ## Import * * Live Events can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:media/liveEvent:LiveEvent example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Media/mediaservices/account1/liveevents/event1 * ``` */ export class LiveEvent extends pulumi.CustomResource { /** * Get an existing LiveEvent resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: LiveEventState, opts?: pulumi.CustomResourceOptions): LiveEvent { return new LiveEvent(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:media/liveEvent:LiveEvent'; /** * Returns true if the given object is an instance of LiveEvent. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is LiveEvent { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === LiveEvent.__pulumiType; } /** * The flag indicates if the resource should be automatically started on creation. Default is `false`. */ public readonly autoStartEnabled!: pulumi.Output<boolean | undefined>; /** * A `crossSiteAccessPolicy` block as defined below. */ public readonly crossSiteAccessPolicy!: pulumi.Output<outputs.media.LiveEventCrossSiteAccessPolicy | undefined>; /** * A description for the live event. */ public readonly description!: pulumi.Output<string | undefined>; /** * A `encoding` block as defined below. */ public readonly encoding!: pulumi.Output<outputs.media.LiveEventEncoding | undefined>; /** * When `useStaticHostname` is set to true, the `hostnamePrefix` specifies the first part of the hostname assigned to the live event preview and ingest endpoints. The final hostname would be a combination of this prefix, the media service account name and a short code for the Azure Media Services data center. */ public readonly hostnamePrefix!: pulumi.Output<string | undefined>; /** * A `input` block as defined below. */ public readonly input!: pulumi.Output<outputs.media.LiveEventInput>; /** * The Azure Region where the Live Event should exist. Changing this forces a new Live Event to be created. */ public readonly location!: pulumi.Output<string>; /** * The Media Services account name. Changing this forces a new Live Event to be created. */ public readonly mediaServicesAccountName!: pulumi.Output<string>; /** * The name which should be used for this Live Event. Changing this forces a new Live Event to be created. */ public readonly name!: pulumi.Output<string>; /** * A `preview` block as defined below. */ public readonly preview!: pulumi.Output<outputs.media.LiveEventPreview>; /** * The name of the Resource Group where the Live Event should exist. Changing this forces a new Live Event to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * A mapping of tags which should be assigned to the Live Event. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * Specifies a list of languages (locale) to be used for speech-to-text transcription – it should match the spoken language in the audio track. The value should be in `BCP-47` format (e.g: `en-US`). [See the Microsoft Documentation for more information about the live transcription feature and the list of supported languages](https://go.microsoft.com/fwlink/?linkid=2133742 ). */ public readonly transcriptionLanguages!: pulumi.Output<string[] | undefined>; /** * Specifies whether a static hostname would be assigned to the live event preview and ingest endpoints. Changing this forces a new Live Event to be created. * --- */ public readonly useStaticHostname!: pulumi.Output<boolean | undefined>; /** * Create a LiveEvent resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: LiveEventArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: LiveEventArgs | LiveEventState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as LiveEventState | undefined; inputs["autoStartEnabled"] = state ? state.autoStartEnabled : undefined; inputs["crossSiteAccessPolicy"] = state ? state.crossSiteAccessPolicy : undefined; inputs["description"] = state ? state.description : undefined; inputs["encoding"] = state ? state.encoding : undefined; inputs["hostnamePrefix"] = state ? state.hostnamePrefix : undefined; inputs["input"] = state ? state.input : undefined; inputs["location"] = state ? state.location : undefined; inputs["mediaServicesAccountName"] = state ? state.mediaServicesAccountName : undefined; inputs["name"] = state ? state.name : undefined; inputs["preview"] = state ? state.preview : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["transcriptionLanguages"] = state ? state.transcriptionLanguages : undefined; inputs["useStaticHostname"] = state ? state.useStaticHostname : undefined; } else { const args = argsOrState as LiveEventArgs | undefined; if ((!args || args.input === undefined) && !opts.urn) { throw new Error("Missing required property 'input'"); } if ((!args || args.mediaServicesAccountName === undefined) && !opts.urn) { throw new Error("Missing required property 'mediaServicesAccountName'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } inputs["autoStartEnabled"] = args ? args.autoStartEnabled : undefined; inputs["crossSiteAccessPolicy"] = args ? args.crossSiteAccessPolicy : undefined; inputs["description"] = args ? args.description : undefined; inputs["encoding"] = args ? args.encoding : undefined; inputs["hostnamePrefix"] = args ? args.hostnamePrefix : undefined; inputs["input"] = args ? args.input : undefined; inputs["location"] = args ? args.location : undefined; inputs["mediaServicesAccountName"] = args ? args.mediaServicesAccountName : undefined; inputs["name"] = args ? args.name : undefined; inputs["preview"] = args ? args.preview : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["transcriptionLanguages"] = args ? args.transcriptionLanguages : undefined; inputs["useStaticHostname"] = args ? args.useStaticHostname : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(LiveEvent.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering LiveEvent resources. */ export interface LiveEventState { /** * The flag indicates if the resource should be automatically started on creation. Default is `false`. */ autoStartEnabled?: pulumi.Input<boolean>; /** * A `crossSiteAccessPolicy` block as defined below. */ crossSiteAccessPolicy?: pulumi.Input<inputs.media.LiveEventCrossSiteAccessPolicy>; /** * A description for the live event. */ description?: pulumi.Input<string>; /** * A `encoding` block as defined below. */ encoding?: pulumi.Input<inputs.media.LiveEventEncoding>; /** * When `useStaticHostname` is set to true, the `hostnamePrefix` specifies the first part of the hostname assigned to the live event preview and ingest endpoints. The final hostname would be a combination of this prefix, the media service account name and a short code for the Azure Media Services data center. */ hostnamePrefix?: pulumi.Input<string>; /** * A `input` block as defined below. */ input?: pulumi.Input<inputs.media.LiveEventInput>; /** * The Azure Region where the Live Event should exist. Changing this forces a new Live Event to be created. */ location?: pulumi.Input<string>; /** * The Media Services account name. Changing this forces a new Live Event to be created. */ mediaServicesAccountName?: pulumi.Input<string>; /** * The name which should be used for this Live Event. Changing this forces a new Live Event to be created. */ name?: pulumi.Input<string>; /** * A `preview` block as defined below. */ preview?: pulumi.Input<inputs.media.LiveEventPreview>; /** * The name of the Resource Group where the Live Event should exist. Changing this forces a new Live Event to be created. */ resourceGroupName?: pulumi.Input<string>; /** * A mapping of tags which should be assigned to the Live Event. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Specifies a list of languages (locale) to be used for speech-to-text transcription – it should match the spoken language in the audio track. The value should be in `BCP-47` format (e.g: `en-US`). [See the Microsoft Documentation for more information about the live transcription feature and the list of supported languages](https://go.microsoft.com/fwlink/?linkid=2133742 ). */ transcriptionLanguages?: pulumi.Input<pulumi.Input<string>[]>; /** * Specifies whether a static hostname would be assigned to the live event preview and ingest endpoints. Changing this forces a new Live Event to be created. * --- */ useStaticHostname?: pulumi.Input<boolean>; } /** * The set of arguments for constructing a LiveEvent resource. */ export interface LiveEventArgs { /** * The flag indicates if the resource should be automatically started on creation. Default is `false`. */ autoStartEnabled?: pulumi.Input<boolean>; /** * A `crossSiteAccessPolicy` block as defined below. */ crossSiteAccessPolicy?: pulumi.Input<inputs.media.LiveEventCrossSiteAccessPolicy>; /** * A description for the live event. */ description?: pulumi.Input<string>; /** * A `encoding` block as defined below. */ encoding?: pulumi.Input<inputs.media.LiveEventEncoding>; /** * When `useStaticHostname` is set to true, the `hostnamePrefix` specifies the first part of the hostname assigned to the live event preview and ingest endpoints. The final hostname would be a combination of this prefix, the media service account name and a short code for the Azure Media Services data center. */ hostnamePrefix?: pulumi.Input<string>; /** * A `input` block as defined below. */ input: pulumi.Input<inputs.media.LiveEventInput>; /** * The Azure Region where the Live Event should exist. Changing this forces a new Live Event to be created. */ location?: pulumi.Input<string>; /** * The Media Services account name. Changing this forces a new Live Event to be created. */ mediaServicesAccountName: pulumi.Input<string>; /** * The name which should be used for this Live Event. Changing this forces a new Live Event to be created. */ name?: pulumi.Input<string>; /** * A `preview` block as defined below. */ preview?: pulumi.Input<inputs.media.LiveEventPreview>; /** * The name of the Resource Group where the Live Event should exist. Changing this forces a new Live Event to be created. */ resourceGroupName: pulumi.Input<string>; /** * A mapping of tags which should be assigned to the Live Event. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Specifies a list of languages (locale) to be used for speech-to-text transcription – it should match the spoken language in the audio track. The value should be in `BCP-47` format (e.g: `en-US`). [See the Microsoft Documentation for more information about the live transcription feature and the list of supported languages](https://go.microsoft.com/fwlink/?linkid=2133742 ). */ transcriptionLanguages?: pulumi.Input<pulumi.Input<string>[]>; /** * Specifies whether a static hostname would be assigned to the live event preview and ingest endpoints. Changing this forces a new Live Event to be created. * --- */ useStaticHostname?: pulumi.Input<boolean>; }
the_stack
import { IconCommonArrowDropDown, IconCommonClose, IconCommonError, IconCommonRun, IconCommonSave } from '@app/assets/icons' import { SQLEditor } from '@app/components/SQLEditor' import { useBindHovering } from '@app/hooks' import { useBlockSuspense, useConnectorsGetProfile, useTranslateSmartQuery } from '@app/hooks/api' import { useCommit } from '@app/hooks/useCommit' import { useLocalStorage } from '@app/hooks/useLocalStorage' import { EditorDraft, useDraftBlockMutating, useQuestionEditorActiveIdState, useQuestionEditorBlockMapState, useQuestionEditorOpenState } from '@app/hooks/useQuestionEditor' import { useSideBarQuestionEditor } from '@app/hooks/useSideBarQuestionEditor' import { useSqlEditor } from '@app/hooks/useSqlEditor' import { useStoryPermissions } from '@app/hooks/useStoryPermissions' import { useRefreshSnapshot, useSnapshotMutating } from '@app/hooks/useStorySnapshotManager' import { useWorkspace } from '@app/hooks/useWorkspace' import { ThemingVariables } from '@app/styles' import { Editor } from '@app/types' import { DRAG_HANDLE_WIDTH } from '@app/utils' import { css, cx } from '@emotion/css' import MonacoEditor from '@monaco-editor/react' import Tippy from '@tippyjs/react' import { dequal } from 'dequal' import { motion, MotionValue, useMotionValue, useTransform } from 'framer-motion' import { produce } from 'immer' import isHotkey from 'is-hotkey' import { omit } from 'lodash' import React, { SetStateAction, useCallback, useEffect, useMemo, useRef, useState } from 'react' import ReactDOM from 'react-dom' import { toast } from 'react-toastify' import { useEvent, useLatest, useWindowSize } from 'react-use' import { Tab, TabList, TabPanel, TabStateReturn, useTabState } from 'reakit/Tab' import YAML from 'yaml' import { setBlockTranscation } from '../context/editorTranscations' import { BlockingUI } from './BlockingUI' import { CircularLoading } from './CircularLoading' import { BlockTitle, useGetBlockTitleTextSnapshot } from './editor' import { isExecuteableBlockType } from './editor/Blocks/utils' import type { SetBlock } from './editor/types' import IconButton from './kit/IconButton' import { TippySingletonContextProvider } from './TippySingletonContextProvider' const DragConstraints = { top: -700, bottom: -300 } const updateOldDraft = ( oldDraft?: EditorDraft, block?: Editor.QueryBlock | Editor.VisualizationBlock | Editor.QueryBuilder | Editor.SmartQueryBlock ) => { if (!oldDraft) return undefined const updatedDraft = emitFalsyObject({ ...oldDraft, title: dequal(oldDraft.title, block?.content?.title) === false ? oldDraft.title : undefined, sql: oldDraft.sql !== (block as Editor.SQLBlock)?.content?.sql ? oldDraft.sql : undefined, visConfig: dequal(oldDraft.visConfig, (block as Editor.VisualizationBlock)?.content?.visualization) === false ? oldDraft.visConfig : undefined, snapshotId: oldDraft.snapshotId !== (block as Editor.QueryBlock)?.content?.snapshotId ? oldDraft.snapshotId : undefined }) return updatedDraft } const QueryEditorResizer: React.FC<{ y: MotionValue<number> }> = ({ y }) => { const [resizeConfig, setResizeConfig] = useLocalStorage('MainSQLEditorConfig_v2', { y: -300 }) useEffect(() => { const unsubscribe = y.onChange((y) => { if (!y) return setResizeConfig((config) => ({ ...config, y: y })) }) return () => { unsubscribe() } }, [setResizeConfig, y]) return ( <motion.div title="drag to resize" whileDrag={{ backgroundColor: ThemingVariables.colors.gray[1] }} drag={'y'} dragConstraints={DragConstraints} className={css` position: absolute; cursor: ns-resize; left: -${DRAG_HANDLE_WIDTH / 2}px; bottom: 0; height: ${DRAG_HANDLE_WIDTH}px; z-index: 10; width: 100%; `} whileHover={{ backgroundColor: ThemingVariables.colors.gray[1] }} dragElastic={false} dragMomentum={false} style={{ y }} /> ) } export const StoryQuestionsEditor: React.FC<{ storyId: string }> = ({ storyId }) => { const [open, setOpen] = useQuestionEditorOpenState(storyId) const [resizeConfig] = useLocalStorage('MainSQLEditorConfig_v2', { y: -300 }) const { height: windowHeight } = useWindowSize() const y = useMotionValue(resizeConfig.y) const height = useTransform(y, (y) => Math.abs(y - 0.5 * DRAG_HANDLE_WIDTH)) const placeholderHeight = useTransform(height, (height) => (open ? height : 0)) useEffect(() => { if (height.get() > windowHeight * 0.7) { y.set(-windowHeight * 0.7) } }, [height, windowHeight, y]) const workspace = useWorkspace() const { data: profile } = useConnectorsGetProfile(workspace.preferences.connectorId) useSqlEditor(profile?.type) const [questionBlocksMap, setQuestionBlocksMap] = useQuestionEditorBlockMapState(storyId) const [activeId, setActiveId] = useQuestionEditorActiveIdState(storyId) const tab = useTabState() const opendQuestionBlockIds = useMemo(() => { return Object.keys(questionBlocksMap) }, [questionBlocksMap]) useEffect(() => { tab.setSelectedId(activeId) }, [activeId, tab]) useEffect(() => { if (opendQuestionBlockIds.length === 0) { setActiveId(null) setOpen(false) } }, [opendQuestionBlockIds, setActiveId, setOpen]) const translateY = useTransform(height, (height) => { return open ? 0 : height - (opendQuestionBlockIds.length ? 44 : 0) }) const closeTabById = useCallback( (tabId: string) => { const currentIndex = opendQuestionBlockIds.findIndex((id) => id === tabId) if (tabId === activeId) { if (opendQuestionBlockIds[currentIndex - 1]) { setActiveId(opendQuestionBlockIds[currentIndex - 1]) } else if (opendQuestionBlockIds[currentIndex + 1]) { setActiveId(opendQuestionBlockIds[currentIndex + 1]) } else { setActiveId(null) } } setQuestionBlocksMap((map) => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { [tabId]: omit, ...rest } = map return rest }) }, [activeId, opendQuestionBlockIds, setActiveId, setQuestionBlocksMap] ) const keyDownHandler = useCallback( (e: KeyboardEvent) => { if (!open) return console.log(e) const handlers: { hotkeys: string[]; handler: (e: KeyboardEvent) => void }[] = [ { hotkeys: ['ctrl+alt+w'], handler: (e) => { console.log('close', activeId) e.preventDefault() e.stopPropagation() if (activeId) { closeTabById(activeId) } } } ] const matchingHandler = handlers.find((handler) => handler.hotkeys.some((hotkey) => isHotkey(hotkey, { byKey: false }, e)) ) matchingHandler?.handler(e) }, [activeId, closeTabById, open] ) useEvent('keydown', keyDownHandler) return ( <> <motion.div style={{ height: placeholderHeight, flexShrink: 0 }} ></motion.div> <motion.div style={{ height: height, y: translateY }} className={css` position: absolute; bottom: 0; left: 0; right: 0; width: 100%; user-select: none; z-index: 1000; display: flex; flex-direction: column; background-color: ${ThemingVariables.colors.gray[5]}; transition: transform 0.25s ease-in-out; `} > {open && <QueryEditorResizer y={y} />} <TabList {...tab} aria-label="Question Editor Tabs" style={{ backgroundColor: ThemingVariables.colors.gray[4], paddingRight: 50 }} className={css` border-top: solid 1px ${ThemingVariables.colors.gray[1]}; border-bottom: solid 1px ${ThemingVariables.colors.gray[1]}; transition: all 250ms; display: flex; position: relative; flex: 0 0 44px; overflow: hidden; `} > <div className={css` flex: 1; height: 100%; display: flex; flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; padding: 0 8px; ::-webkit-scrollbar { display: none; } > * + * { margin-left: 8px; } `} > {opendQuestionBlockIds?.map((id) => { return ( <React.Suspense key={id} fallback={null}> <QuestionTab id={id} isActive={id === activeId} tab={tab} isOpen={open} onClick={() => { setActiveId(id) setOpen(true) }} storyId={storyId} closeTabById={closeTabById} /> </React.Suspense> ) })} <Tippy content={open ? 'Click to close query editor' : 'Click to open query editor'} hideOnClick arrow={false} delay={[500, 0]} duration={[500, 0]} > <IconButton icon={IconCommonArrowDropDown} onClick={() => { setOpen(!open) }} style={{ transform: `rotate(${open ? '0' : '180deg'})` }} className={css` margin-left: auto; transition: transform 250ms; display: flex; align-items: center; position: absolute; top: 0; bottom: 0; right: 0; padding: 0 12px; height: 100%; background-color: ${ThemingVariables.colors.gray[2]}; `} /> </Tippy> </div> <div id="questions-editor-tab-slot"></div> </TabList> {opendQuestionBlockIds.map((id) => ( <React.Suspense key={id} fallback={<BlockingUI blocking={true} />}> <StoryQuestionEditor tab={tab} isActive={activeId === id} id={id} setActiveId={setActiveId} storyId={storyId} isOpen={open} /> </React.Suspense> ))} {/* <div className={css` box-shadow: 0px -1px 0px ${ThemingVariables.colors.gray[1]}; padding: 0 8px; display: flex; height: 44px; background-color: ${ThemingVariables.colors.gray[5]}; position: relative; flex-shrink: 0; flex: 1; overflow: hidden; z-index: 1001; `} > {open === false && ( <div className={css` display: flex; align-items: center; position: absolute; top: 0; bottom: 0; right: 0; padding: 0 16px; height: 100%; `} > <IconButton hoverContent="Click to open query editor" icon={IconCommonArrowUpDown} onClick={() => { setOpen(true) }} className={css` margin-left: auto; `} /> </div> )} </div> */} {/* <EditorContent storyId={storyId} /> */} </motion.div> </> ) } const TabHeader: React.FC<{ blockId: string hovering: boolean storyId: string closeTabById: (tabId: string) => void }> = ({ blockId, hovering, storyId, closeTabById }) => { const [questionBlocksMap] = useQuestionEditorBlockMapState(storyId) const closeTabByIdAndCheckDraft = useCallback( (tabId: string) => { const isTabDirty = !!questionBlocksMap[tabId].draft if (isTabDirty) { if (confirm("Close this tab without saving? Your changes will be lost if you don't save them.") === false) { return } } closeTabById(tabId) }, [closeTabById, questionBlocksMap] ) const block = useBlockSuspense<Editor.QueryBlock | Editor.VisualizationBlock>(blockId) const queryBlock = useBlockSuspense<Editor.QueryBlock>( (block as Editor.VisualizationBlock)?.content?.queryId ?? blockId ) const mutatingCount = useDraftBlockMutating(blockId) const getBlockTitle = useGetBlockTitleTextSnapshot() useEffect(() => { if (block.alive === false) { closeTabById(block.id) } }, [block.alive, block.id, closeTabById]) return ( <> <div className={css` flex: 1; max-width: 200px; display: flex; align-items: center; box-sizing: border-box; `} // ref={ref} title={getBlockTitle(queryBlock)} > {mutatingCount !== 0 && <CircularLoading size={20} color={ThemingVariables.colors.primary[1]} />} <div className={css` flex: 1 1; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; `} > <BlockTitle block={queryBlock} /> </div> </div> <DraftStatus isDraft={!!questionBlocksMap[block.id].draft} showClose={hovering} onCloseClick={(e) => { e.preventDefault() e.stopPropagation() closeTabByIdAndCheckDraft(block.id) }} /> </> ) } const QuestionTab: React.FC<{ id: string tab: TabStateReturn isActive: boolean isOpen: boolean onClick: () => void storyId: string closeTabById: (tabId: string) => void }> = ({ id, tab, isActive, isOpen, onClick, storyId, closeTabById }) => { const [bindHoveringEvents, isHovering] = useBindHovering() return ( <Tab key={id} {...tab} {...bindHoveringEvents()} onClick={onClick} className={cx( css` margin-top: 8px; margin-bottom: 8px; font-size: 12px; border-radius: 8px; line-height: 14px; display: inline-flex; align-items: center; padding: 8px 15px; cursor: pointer; outline: none; border: none; color: ${ThemingVariables.colors.text[0]}; `, isActive ? css` background: ${ThemingVariables.colors.gray[1]}; ` : css` background: ${ThemingVariables.colors.gray[2]}; ` )} > <TabHeader blockId={id} hovering={isHovering} storyId={storyId} closeTabById={closeTabById} /> </Tab> ) } export const StoryQuestionEditor: React.FC<{ id: string setActiveId: (update: SetStateAction<string | null>) => void | Promise<void> tab: TabStateReturn storyId: string isOpen: boolean isActive: boolean // block: Editor.QuestionBlock // originalBlock: Editor.QuestionBlock }> = ({ id, tab, storyId, isActive }) => { const block = useBlockSuspense<Editor.VisualizationBlock | Editor.QueryBlock>(id) const visualizationBlock: Editor.VisualizationBlock | null = block.type === Editor.BlockType.Visualization ? block : null const queryBlock = useBlockSuspense<Editor.QueryBlock>(visualizationBlock?.content?.queryId ?? id) const [questionBlocksMap, setQuestionBlocksMap] = useQuestionEditorBlockMapState(storyId) const [sqlSidePanel, setSqlSidePanel] = useState(false) const ref = useRef<HTMLDivElement>(null) const questionBlockState = useMemo(() => { if (id && questionBlocksMap && questionBlocksMap[id]) { return questionBlocksMap[id] } return null }, [id, questionBlocksMap]) const commit = useCommit() const setSqlBlock = useCallback<SetBlock<Editor.QueryBlock>>( (id, update) => { const oldBlock = queryBlock const newBlock = produce(oldBlock, update) commit({ transcation: setBlockTranscation({ oldBlock, newBlock }), storyId: queryBlock.storyId! }) }, [commit, queryBlock] ) const permissions = useStoryPermissions(visualizationBlock?.storyId ?? block.id) const readonly = permissions.readonly const isDraft = !!questionBlockState?.draft const originalSQL = (queryBlock as Editor.SQLBlock)?.content?.sql const queryTitle = questionBlockState?.draft?.title ?? queryBlock?.content?.title const { data: sql = questionBlockState?.draft?.sql ?? originalSQL ?? '' } = useTranslateSmartQuery( queryBlock.type === Editor.BlockType.SmartQuery ? (queryBlock as Editor.SmartQueryBlock).content.queryBuilderId : undefined, (queryBlock as Editor.SmartQueryBlock)?.content?.metricIds, (queryBlock as Editor.SmartQueryBlock)?.content?.dimensions, (queryBlock as Editor.SmartQueryBlock)?.content?.filters ) useEffect(() => { setQuestionBlocksMap((blocksMap) => { return { ...blocksMap, [id]: { ...blocksMap[id], draft: updateOldDraft(updateOldDraft(blocksMap[id]?.draft, visualizationBlock ?? queryBlock), queryBlock) } } }) }, [queryBlock, visualizationBlock, id, setQuestionBlocksMap]) const setSql = useCallback( (sql) => { setQuestionBlocksMap((blocksMap) => { return { ...blocksMap, [id]: { ...blocksMap[id], draft: emitFalsyObject({ ...blocksMap[id].draft, sql: sql !== originalSQL ? sql : undefined }) } } }) }, [id, originalSQL, setQuestionBlocksMap] ) // const executeSQL = useExecuteSQL(`draft/${block.id}`) const save = useCallback( (snapshotId?: string) => { if (!block) { toast.error('block is undefined') return } // if (isDraft !== true) return if (readonly) { toast.error('question is readonly') return } setSqlBlock(queryBlock.id, (draftBlock) => { if (draftBlock.type === Editor.BlockType.SQL || draftBlock.type === Editor.BlockType.QueryBuilder) { ;(draftBlock as Editor.SQLBlock).content!.sql = sql } if (snapshotId) { draftBlock.content!.snapshotId = snapshotId draftBlock.content!.error = null draftBlock.content!.lastRunAt = Date.now() } draftBlock.content!.title = queryTitle ?? [] }) }, [block, readonly, setSqlBlock, queryBlock.id, sql, queryTitle] ) const [sqlError, setSQLError] = useState<string | null>(null) // const mutateBlock = useMutateBlock<Editor.QuestionBlock>() const workspace = useWorkspace() const { data: profile } = useConnectorsGetProfile(workspace.preferences.connectorId) const profileType = profile?.type const sidebarEditor = useSideBarQuestionEditor(storyId) const refreshSnapshot = useRefreshSnapshot(storyId) const mutatingCount = useSnapshotMutating(queryBlock.id) const run = useCallback(async () => { if (!queryBlock) return if (!sql) return if (!isExecuteableBlockType(queryBlock.type)) { return } save() // TODO: wait for save setTimeout(() => { refreshSnapshot.execute(queryBlock).then((res) => { if (res.errMsg) { setSQLError(res.errMsg) setSqlSidePanel(true) } else { setSQLError(null) setSqlSidePanel(false) } }) }, 0) // const data = await executeSQL.mutateAsync({ // workspaceId: workspace.id, // sql, // questionId: queryBlock.id, // connectorId: workspace.preferences.connectorId!, // profile: workspace.preferences.profile! // }) // if (typeof data !== 'object' || data.errMsg) { // setSQLError(data.errMsg ?? 'unknown error') // setSqlSidePanel(true) // return // } // setSQLError(null) // setSqlSidePanel(false) // const snapshotId = blockIdGenerator() // const originalBlockId = queryBlock.id // invariant(queryBlock, 'originalBlock is undefined') // // TODO: fix snap shot question id // await createSnapshot({ // snapshotId, // questionId: originalBlockId, // sql: sql, // data: data, // workspaceId: workspace.id // }) // save(snapshotId) sidebarEditor.open({ blockId: block.id, activeTab: 'Visualization' }) }, [queryBlock, sql, save, refreshSnapshot, sidebarEditor, block.id]) const cancelExecuteSql = useCallback(() => { if (block?.id) { refreshSnapshot.cancel(queryBlock?.id) // const mutations = queryClient.getMutationCache().getAll() // mutations // .filter((mutation) => mutation.options.mutationKey === `draft/${block.id}`) // .forEach((mutation) => { // queryClient.getMutationCache().remove(mutation) // }) // executeSQL.reset() } }, [block?.id, queryBlock?.id, refreshSnapshot]) const keyDownHandler = useCallback( (e: React.KeyboardEvent) => { const handlers: { hotkeys: string[]; handler: (e: KeyboardEvent) => void }[] = [ { hotkeys: ['mod+enter', 'ctrl+enter'], handler: (e) => { e.preventDefault() e.stopPropagation() run() } }, { hotkeys: ['mod+s', 'ctrl+s'], handler: (e) => { e.preventDefault() e.stopPropagation() save() } } ] const matchingHandler = handlers.find((handler) => handler.hotkeys.some((hotkey) => isHotkey(hotkey, { byKey: true }, e.nativeEvent)) ) matchingHandler?.handler(e.nativeEvent) }, [run, save] ) // const mutatingCount = useDraftBlockMutating(block.id) const isDBT = block.type === Editor.BlockType.DBT const sqlReadOnly = readonly || queryBlock.type === Editor.BlockType.SnapshotBlock || !!(visualizationBlock && queryBlock.storyId !== visualizationBlock?.storyId) || queryBlock.type === Editor.BlockType.SmartQuery const latestSave = useLatest(save) const latestRun = useLatest(run) return ( <TabPanel {...tab} tabId={id} className={cx( css` flex: 1; position: relative; outline: none; display: flex; flex-direction: column; width: 100%; align-items: stretch; height: 100%; ` )} ref={ref} onKeyDown={keyDownHandler} > {isActive && ( <TabButtons hasError={!!sqlError} onClickError={() => setSqlSidePanel(!sqlSidePanel)}> <IconButton hoverContent={mutatingCount !== 0 ? 'Cancel Query' : 'Execute Query'} icon={mutatingCount !== 0 ? IconCommonClose : IconCommonRun} color={ThemingVariables.colors.primary[1]} disabled={!isExecuteableBlockType(queryBlock.type)} onClick={mutatingCount !== 0 ? cancelExecuteSql : run} /> <IconButton hoverContent="Save" disabled={!isDraft || readonly === true} icon={IconCommonSave} onClick={() => save()} color={ThemingVariables.colors.primary[1]} /> </TabButtons> )} <div className={css` display: flex; width: 100%; height: 100%; `} > {isDBT ? ( <MonacoEditor language="yaml" theme="tellery" value={YAML.stringify(omit(block.content, 'title'))} options={{ readOnly: true, padding: { top: 20, bottom: 0 } }} loading={<CircularLoading size={50} color={ThemingVariables.colors.gray[0]} />} wrapperProps={{ className: css` flex: 1; width: 0 !important; ` }} /> ) : ( <SQLEditor className={css` flex: 1; width: 0 !important; `} blockId={block.id} value={sql} storyId={storyId} padding={{ top: 20, bottom: 0 }} languageId={profileType} onChange={setSql} onRun={latestRun} onSave={latestSave} readOnly={sqlReadOnly} /> )} {sqlSidePanel && ( <div className={css` overflow: scroll; word-wrap: break-word; font-style: normal; font-weight: 500; font-size: 14px; flex: 0 0 400px; line-height: 24px; color: ${ThemingVariables.colors.negative[0]}; margin: 15px; user-select: text; padding: 10px; border-radius: 10px; background: ${ThemingVariables.colors.negative[1]}; `} > {sqlError} </div> )} </div> </TabPanel> ) } const TabButtons: React.FC<{ hasError: boolean onClickError: React.MouseEventHandler<HTMLButtonElement> | undefined }> = ({ onClickError, hasError, children }) => { return ReactDOM.createPortal( <div className={css` display: flex; height: 100%; align-items: center; `} > <TippySingletonContextProvider arrow={false}> <div className={css` display: inline-flex; align-items: center; > * { margin: 0 10px; } `} > {hasError && ( <IconButton icon={IconCommonError} color={ThemingVariables.colors.negative[0]} onClick={onClickError} /> )} {children} </div> </TippySingletonContextProvider> </div>, document.getElementById('questions-editor-tab-slot')! ) } const emitFalsyObject = (object: EditorDraft) => { if (Object.values(object).some((value) => value !== undefined)) { return object } return undefined } export const DraftStatus: React.FC<{ isDraft: boolean onCloseClick: React.MouseEventHandler<HTMLDivElement> showClose: boolean }> = ({ onCloseClick, isDraft, showClose }) => { const [bindHoveringEvents, isHovering] = useBindHovering() return ( <div {...bindHoveringEvents()} onClick={onCloseClick} className={css` display: inline-block; margin-left: 10px; height: 12px; width: 12px; padding: 3px; position: relative; `} > {isDraft && !isHovering && ( <div className={css` position: absolute; left: 0; top: 0; height: 12px; width: 12px; padding: 3px; background-color: ${ThemingVariables.colors.warning[0]}; border-radius: 100%; pointer-events: none; `} ></div> )} {(isHovering || (!isDraft && showClose)) && ( <IconCommonClose color={ThemingVariables.colors.text[0]} className={css` position: absolute; cursor: pointer; height: 20px; width: 20px; top: -4px; pointer-events: none; left: -4px; `} /> )} </div> ) }
the_stack
import { Connection, AbstractConnector, ConnectorComputeParams, PaintGeometry, StraightSegment, ArcSegment } from "@jsplumb/core" import { ConnectorOptions } from "@jsplumb/common" import { Dictionary } from '@jsplumb/util' export interface FlowchartConnectorOptions extends ConnectorOptions { alwaysRespectStubs?:boolean midpoint?:number cornerRadius?:number loopbackRadius?:number } type SegmentDirection = -1 | 0 | 1 type FlowchartSegment = [ number, number, number, number, string ] type StubPositions = [number, number, number, number] function sgn (n:number):SegmentDirection { return n < 0 ? -1 : n === 0 ? 0 : 1 } function segmentDirections (segment:FlowchartSegment):[number, number] { return [ sgn( segment[2] - segment[0] ), sgn( segment[3] - segment[1] ) ] } function segLength (s:FlowchartSegment):number { return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2)) } function _cloneArray (a:Array<any>):Array<any> { let _a:Array<any> = [] _a.push.apply(_a, a) return _a } export class FlowchartConnector extends AbstractConnector { static type = "Flowchart" type = FlowchartConnector.type private internalSegments:Array<FlowchartSegment> = [] midpoint:number alwaysRespectStubs:boolean cornerRadius:number lastx:number lasty:number lastOrientation:any loopbackRadius:number isLoopbackCurrently:boolean getDefaultStubs(): [number, number] { return [30, 30] } constructor(public connection:Connection, params:FlowchartConnectorOptions) { super(connection, params) this.midpoint = params.midpoint == null || isNaN(params.midpoint) ? 0.5 : params.midpoint this.cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0 this.alwaysRespectStubs = params.alwaysRespectStubs === true this.lastx = null this.lasty = null this.lastOrientation = null // TODO now common between this and AbstractBezierEditor; refactor into superclass? this.loopbackRadius = params.loopbackRadius || 25 this.isLoopbackCurrently = false } private addASegment(x:number, y:number, paintInfo:PaintGeometry) { if (this.lastx === x && this.lasty === y) { return } let lx = this.lastx == null ? paintInfo.sx : this.lastx, ly = this.lasty == null ? paintInfo.sy : this.lasty, o = lx === x ? "v" : "h" this.lastx = x this.lasty = y this.internalSegments.push([ lx, ly, x, y, o ]) } private writeSegments (paintInfo:PaintGeometry):void { let current:FlowchartSegment = null, next:FlowchartSegment, currentDirection:[number,number], nextDirection:[number, number] for (let i = 0; i < this.internalSegments.length - 1; i++) { current = current || _cloneArray(this.internalSegments[i]) as FlowchartSegment next = _cloneArray(this.internalSegments[i + 1]) as FlowchartSegment currentDirection = segmentDirections(current) nextDirection = segmentDirections(next) if (this.cornerRadius > 0 && current[4] !== next[4]) { let minSegLength = Math.min(segLength(current), segLength(next)) let radiusToUse = Math.min(this.cornerRadius, minSegLength / 2) current[2] -= currentDirection[0] * radiusToUse current[3] -= currentDirection[1] * radiusToUse next[0] += nextDirection[0] * radiusToUse next[1] += nextDirection[1] * radiusToUse let ac = (currentDirection[1] === nextDirection[0] && nextDirection[0] === 1) || ((currentDirection[1] === nextDirection[0] && nextDirection[0] === 0) && currentDirection[0] !== nextDirection[1]) || (currentDirection[1] === nextDirection[0] && nextDirection[0] === -1), sgny = next[1] > current[3] ? 1 : -1, sgnx = next[0] > current[2] ? 1 : -1, sgnEqual = sgny === sgnx, cx = (sgnEqual && ac || (!sgnEqual && !ac)) ? next[0] : current[2], cy = (sgnEqual && ac || (!sgnEqual && !ac)) ? current[3] : next[1] this._addSegment(StraightSegment, { x1: current[0], y1: current[1], x2: current[2], y2: current[3] }) this._addSegment(ArcSegment, { r: radiusToUse, x1: current[2], y1: current[3], x2: next[0], y2: next[1], cx: cx, cy: cy, ac: ac }) } else { this._addSegment(StraightSegment, { x1: current[0], y1: current[1], x2: current[2], y2: current[3] }) } current = next } if (next != null) { // last segment this._addSegment(StraightSegment, { x1: next[0], y1: next[1], x2: next[2], y2: next[3] }) } } _compute (paintInfo:PaintGeometry, params:ConnectorComputeParams):void { this.internalSegments.length = 0 this.lastx = null this.lasty = null this.lastOrientation = null let commonStubCalculator = (axis:string):StubPositions => { return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY] }, stubCalculators:Dictionary<(axis:string) => StubPositions> = { perpendicular: commonStubCalculator, orthogonal: commonStubCalculator, opposite: (axis:string) => { let pi = paintInfo, idx = axis === "x" ? 0 : 1, areInProximity = { "x": function () { return ( (pi.so[idx] === 1 && ( ( (pi.startStubX > pi.endStubX) && (pi.tx > pi.startStubX) ) || ( (pi.sx > pi.endStubX) && (pi.tx > pi.sx))))) || ( (pi.so[idx] === -1 && ( ( (pi.startStubX < pi.endStubX) && (pi.tx < pi.startStubX) ) || ( (pi.sx < pi.endStubX) && (pi.tx < pi.sx))))) }, "y": function () { return ( (pi.so[idx] === 1 && ( ( (pi.startStubY > pi.endStubY) && (pi.ty > pi.startStubY) ) || ( (pi.sy > pi.endStubY) && (pi.ty > pi.sy))))) || ( (pi.so[idx] === -1 && ( ( (pi.startStubY < pi.endStubY) && (pi.ty < pi.startStubY) ) || ( (pi.sy < pi.endStubY) && (pi.ty < pi.sy))))) } } if (!this.alwaysRespectStubs && areInProximity[axis]()) { return { "x": [(paintInfo.sx + paintInfo.tx) / 2, paintInfo.startStubY, (paintInfo.sx + paintInfo.tx) / 2, paintInfo.endStubY], "y": [paintInfo.startStubX, (paintInfo.sy + paintInfo.ty) / 2, paintInfo.endStubX, (paintInfo.sy + paintInfo.ty) / 2] }[axis] } else { return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY] } } } // calculate Stubs. let stubs:StubPositions = stubCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis), idx = paintInfo.sourceAxis === "x" ? 0 : 1, oidx = paintInfo.sourceAxis === "x" ? 1 : 0, ss = stubs[idx], oss = stubs[oidx], es = stubs[idx + 2], oes = stubs[oidx + 2] // add the start stub segment. use stubs for loopback as it will look better, with the loop spaced // away from the element. this.addASegment(stubs[0], stubs[1], paintInfo) // if its a loopback and we should treat it differently. // if (false && params.sourcePos[0] === params.targetPos[0] && params.sourcePos[1] === params.targetPos[1]) { // // // we use loopbackRadius here, as statemachine connectors do. // // so we go radius to the left from stubs[0], then upwards by 2*radius, to the right by 2*radius, // // down by 2*radius, left by radius. // addSegment(segments, stubs[0] - loopbackRadius, stubs[1], paintInfo) // addSegment(segments, stubs[0] - loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo) // addSegment(segments, stubs[0] + loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo) // addSegment(segments, stubs[0] + loopbackRadius, stubs[1], paintInfo) // addSegment(segments, stubs[0], stubs[1], paintInfo) // // } // else { let midx = paintInfo.startStubX + ((paintInfo.endStubX - paintInfo.startStubX) * this.midpoint), midy = paintInfo.startStubY + ((paintInfo.endStubY - paintInfo.startStubY) * this.midpoint) let orientations = {x: [0, 1], y: [1, 0]}, lineCalculators:Dictionary<(axis:string, ss:number, oss:number, es:number, oes:number) => any> = { perpendicular: (axis:string, ss:number, oss:number, es:number, oes:number) => { let pi = paintInfo, sis = { x: [ [[1, 2, 3, 4], null, [2, 1, 4, 3]], null, [[4, 3, 2, 1], null, [3, 4, 1, 2]] ], y: [ [[3, 2, 1, 4], null, [2, 3, 4, 1]], null, [[4, 1, 2, 3], null, [1, 4, 3, 2]] ] }, stubs = { x: [[pi.startStubX, pi.endStubX], null, [pi.endStubX, pi.startStubX]], y: [[pi.startStubY, pi.endStubY], null, [pi.endStubY, pi.startStubY]] }, midLines = { x: [[midx, pi.startStubY], [midx, pi.endStubY]], y: [[pi.startStubX, midy], [pi.endStubX, midy]] }, linesToEnd = { x: [[pi.endStubX, pi.startStubY]], y: [[pi.startStubX, pi.endStubY]] }, startToEnd = { x: [[pi.startStubX, pi.endStubY], [pi.endStubX, pi.endStubY]], y: [[pi.endStubX, pi.startStubY], [pi.endStubX, pi.endStubY]] }, startToMidToEnd = { x: [[pi.startStubX, midy], [pi.endStubX, midy], [pi.endStubX, pi.endStubY]], y: [[midx, pi.startStubY], [midx, pi.endStubY], [pi.endStubX, pi.endStubY]] }, otherStubs = { x: [pi.startStubY, pi.endStubY], y: [pi.startStubX, pi.endStubX] }, soIdx = orientations[axis][0], toIdx = orientations[axis][1], _so = pi.so[soIdx] + 1, _to = pi.to[toIdx] + 1, otherFlipped = (pi.to[toIdx] === -1 && (otherStubs[axis][1] < otherStubs[axis][0])) || (pi.to[toIdx] === 1 && (otherStubs[axis][1] > otherStubs[axis][0])), stub1 = stubs[axis][_so][0], stub2 = stubs[axis][_so][1], segmentIndexes = sis[axis][_so][_to] if (pi.segment === segmentIndexes[3] || (pi.segment === segmentIndexes[2] && otherFlipped)) { return midLines[axis] } else if (pi.segment === segmentIndexes[2] && stub2 < stub1) { return linesToEnd[axis] } else if ((pi.segment === segmentIndexes[2] && stub2 >= stub1) || (pi.segment === segmentIndexes[1] && !otherFlipped)) { return startToMidToEnd[axis] } else if (pi.segment === segmentIndexes[0] || (pi.segment === segmentIndexes[1] && otherFlipped)) { return startToEnd[axis] } }, orthogonal: (axis:string, startStub:number, otherStartStub:number, endStub:number, otherEndStub:number) => { let pi = paintInfo, extent = { "x": pi.so[0] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub), "y": pi.so[1] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub) }[axis] return { "x": [ [extent, otherStartStub], [extent, otherEndStub], [endStub, otherEndStub] ], "y": [ [otherStartStub, extent], [otherEndStub, extent], [otherEndStub, endStub] ] }[axis] }, opposite: (axis:string, ss:number, oss:number, es:number, oes:number):any => { let pi = paintInfo, otherAxis:string = {"x": "y", "y": "x"}[axis], dim = {"x": "h", "y": "w"}[axis], comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"] if (params.sourceEndpoint.elementId === params.targetEndpoint.elementId) { let _val = oss + ((1 - params.sourceEndpoint._anchor[otherAxis]) * params.sourceInfo[dim]) + this.maxStub return { "x": [ [ss, _val], [es, _val] ], "y": [ [_val, ss], [_val, es] ] }[axis] } else if (!comparator || (pi.so[idx] === 1 && ss > es) || (pi.so[idx] === -1 && ss < es)) { return { "x": [ [ss, midy], [es, midy] ], "y": [ [midx, ss], [midx, es] ] }[axis] } else if ((pi.so[idx] === 1 && ss < es) || (pi.so[idx] === -1 && ss > es)) { return { "x": [ [midx, pi.sy], [midx, pi.ty] ], "y": [ [pi.sx, midy], [pi.tx, midy] ] }[axis] } } } // compute the rest of the line let p:any = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis, ss, oss, es, oes) if (p) { for (let i = 0; i < p.length; i++) { this.addASegment(p[i][0], p[i][1], paintInfo) } } // line to end stub this.addASegment(stubs[2], stubs[3], paintInfo) // end stub to end (common) this.addASegment(paintInfo.tx, paintInfo.ty, paintInfo) // write out the segments. this.writeSegments(paintInfo) } }
the_stack
// This is the "new-mobile" UI rendered in newMobilePaneIosFrame.html (function () { "use strict"; // Framework7 app object let myApp = null; function postError(error, message) { poster.postMessageToParent("LogError", { error: JSON.stringify(error), message: message }); } function initializeFramework7() { myApp = new Framework7(); myApp.addView("#summary-view"); myApp.addView("#received-view"); myApp.addView("#antispam-view"); myApp.addView("#other-view"); } function updateStatus(message) { if (myApp) { myApp.hidePreloader(); myApp.showPreloader(message); } } function addCalloutEntry(name, value, parent) { if (value) { $("<p/>") .addClass("wrap-line") .html("<strong>" + name + ": </strong>" + value) .appendTo(parent); } } function addSpamReportRow(spamRow, parent) { if (spamRow.value) { const item = $("<li/>") .addClass("accordion-item") .appendTo(parent); const link = $("<a/>") .addClass("item-content") .addClass("item-link") .attr("href", "#") .appendTo(item); const innerItem = $("<div/>") .addClass("item-inner") .appendTo(link); $("<div/>") .addClass("item-title") .text(spamRow.label) .appendTo(innerItem); const itemContent = $("<div/>") .addClass("accordion-item-content") .appendTo(item); const contentBlock = $("<div/>") .addClass("content-block") .appendTo(itemContent); const linkWrap = $("<p/>") .appendTo(contentBlock); $($.parseHTML(spamRow.valueUrl)) .addClass("external") .appendTo(linkWrap); } } function buildViews(headers) { const viewModel = HeaderModel(headers); // Build summary view const summaryContent = $("#summary-content"); let contentBlock; let headerVal; let pre; let i; for (i = 0; i < viewModel.summary.summaryRows.length; i++) { if (viewModel.summary.summaryRows[i].value) { $("<div/>") .addClass("content-block-title") .text(viewModel.summary.summaryRows[i].label) .appendTo(summaryContent); contentBlock = $("<div/>") .addClass("content-block") .appendTo(summaryContent); headerVal = $("<div/>") .addClass("code-box") .appendTo(contentBlock); pre = $("<pre/>").appendTo(headerVal); $("<code/>") .text(viewModel.summary.summaryRows[i].value) .appendTo(pre); } } if (viewModel.originalHeaders) { $("#original-headers").text(viewModel.originalHeaders); $("#orig-headers-ui").show(); } // Build received view const receivedContent = $("#received-content"); if (viewModel.receivedHeaders.receivedRows.length > 0) { const timeline = $("<div/>") .addClass("timeline") .appendTo(receivedContent); let currentTime = null; let currentTimeEntry = null; let timelineItem; let timelineDate; let timelineInner; for (i = 0; i < viewModel.receivedHeaders.receivedRows.length; i++) { if (i === 0) { currentTime = moment(viewModel.receivedHeaders.receivedRows[i].dateNum).local(); timelineItem = $("<div/>") .addClass("timeline-item") .appendTo(timeline); timelineDate = currentTime.format("h:mm") + "<small>" + currentTime.format("A") + "</small>"; $("<div/>") .addClass("timeline-item-date") .html(timelineDate) .appendTo(timelineItem); $("<div/>") .addClass("timeline-item-divider") .appendTo(timelineItem); currentTimeEntry = $("<div/>") .addClass("timeline-item-content") .appendTo(timelineItem); // Add initial otherRows timelineInner = $("<div/>") .addClass("timeline-item-inner") .addClass("link") .addClass("open-popover") .attr("data-popover", ".popover-" + i) .appendTo(currentTimeEntry); $("<div/>") .addClass("timeline-item-time") .text(currentTime.format("h:mm:ss")) .appendTo(timelineInner); $("<div/>") .addClass("timeline-item-subtitle") .html("<strong>From: </strong>" + viewModel.receivedHeaders.receivedRows[i].from) .appendTo(timelineInner); $("<div/>") .addClass("timeline-item-text") .html("<strong>To: </strong>" + viewModel.receivedHeaders.receivedRows[i].by) .appendTo(timelineInner); } else { // Determine if new timeline item is needed const entryTime = moment(viewModel.receivedHeaders.receivedRows[i].dateNum).local(); if (entryTime.minute() > currentTime.minute()) { // Into a new minute, create a new timeline item currentTime = entryTime; timelineItem = $("<div/>") .addClass("timeline-item") .appendTo(timeline); timelineDate = currentTime.format("h:mm") + "<small>" + currentTime.format("A") + "</small>"; $("<div/>") .addClass("timeline-item-date") .html(timelineDate) .appendTo(timelineItem); $("<div/>") .addClass("timeline-item-divider") .appendTo(timelineItem); currentTimeEntry = $("<div/>") .addClass("timeline-item-content") .appendTo(timelineItem); } // Add additional rows timelineInner = $("<div/>") .addClass("timeline-item-inner") .addClass("link") .addClass("open-popover") .attr("data-popover", ".popover-" + i) .appendTo(currentTimeEntry); $("<div/>") .addClass("timeline-item-time") .text(entryTime.format("h:mm:ss")) .appendTo(timelineInner); $("<div/>") .addClass("timeline-item-subtitle") .html("<strong>To: </strong>" + viewModel.receivedHeaders.receivedRows[i].by) .appendTo(timelineInner); const progress = $("<div/>") .addClass("timeline-item-text") .appendTo(timelineInner); $("<p/>") .text(viewModel.receivedHeaders.receivedRows[i].delay) .appendTo(progress); $("<p/>") .addClass("progress-wrap-" + i) .appendTo(progress); try { myApp.showProgressbar(".progress-wrap-" + i, viewModel.receivedHeaders.receivedRows[i].percent); } catch (e) { $("#original-headers").text(JSON.stringify(e)); return; } } // popover const popover = $("<div/>") .addClass("popover") .addClass("popover-" + i) .appendTo(receivedContent); $("<div/>") .addClass("popover-angle") .appendTo(popover); const popoverInner = $("<div/>") .addClass("popover-inner") .appendTo(popover); const popoverContent = $("<div/>") .addClass("content-block") .appendTo(popoverInner); addCalloutEntry("From", viewModel.receivedHeaders.receivedRows[i].from, popoverContent); addCalloutEntry("To", viewModel.receivedHeaders.receivedRows[i].by, popoverContent); addCalloutEntry("Time", viewModel.receivedHeaders.receivedRows[i].date, popoverContent); addCalloutEntry("Type", viewModel.receivedHeaders.receivedRows[i].with, popoverContent); addCalloutEntry("ID", viewModel.receivedHeaders.receivedRows[i].id, popoverContent); addCalloutEntry("For", viewModel.receivedHeaders.receivedRows[i].for, popoverContent); addCalloutEntry("Via", viewModel.receivedHeaders.receivedRows[i].via, popoverContent); } // Add a final empty timeline item to extend // timeline const endTimelineItem = $("<div/>") .addClass("timeline-item") .appendTo(timeline); currentTime.add(1, "m"); const endTimelineDate = currentTime.format("h:mm") + "<small>" + currentTime.format("A") + "</small>"; $("<div/>") .addClass("timeline-item-date") .html(endTimelineDate) .appendTo(endTimelineItem); $("<div/>") .addClass("timeline-item-divider") .appendTo(endTimelineItem); } // Build antispam view const antispamContent = $("#antispam-content"); let list; let ul; // Forefront if (viewModel.forefrontAntiSpamReport.forefrontAntiSpamRows.length > 0) { $("<div/>") .addClass("content-block-title") .text("Forefront Antispam Report") .appendTo(antispamContent); list = $("<div/>") .addClass("list-block") .addClass("accordion-list") .appendTo(antispamContent); ul = $("<ul/>") .appendTo(list); for (i = 0; i < viewModel.forefrontAntiSpamReport.forefrontAntiSpamRows.length; i++) { addSpamReportRow(viewModel.forefrontAntiSpamReport.forefrontAntiSpamRows[i], ul); } } // Microsoft if (viewModel.antiSpamReport.antiSpamRows.length > 0) { $("<div/>") .addClass("content-block-title") .text("Microsoft Antispam Report") .appendTo(antispamContent); list = $("<div/>") .addClass("list-block") .addClass("accordion-list") .appendTo(antispamContent); ul = $("<ul/>") .appendTo(list); for (i = 0; i < viewModel.antiSpamReport.antiSpamRows.length; i++) { addSpamReportRow(viewModel.antiSpamReport.antiSpamRows[i], ul); } } // Build other view const otherContent = $("#other-content"); for (i = 0; i < viewModel.otherHeaders.otherRows.length; i++) { if (viewModel.otherHeaders.otherRows[i].value) { const headerName = $("<div/>") .addClass("content-block-title") .text(viewModel.otherHeaders.otherRows[i].header) .appendTo(otherContent); if (viewModel.otherHeaders.otherRows[i].url) { headerName.empty(); $($.parseHTML(viewModel.otherHeaders.otherRows[i].url)) .addClass("external") .appendTo(headerName); } contentBlock = $("<div/>") .addClass("content-block") .appendTo(otherContent); headerVal = $("<div/>") .addClass("code-box") .appendTo(contentBlock); pre = $("<pre/>").appendTo(headerVal); $("<code/>") .text(viewModel.otherHeaders.otherRows[i].value) .appendTo(pre); } } } function renderItem(headers) { // Empty data $("#summary-content").empty(); $("#received-content").empty(); $("#antispam-content").empty(); $("#other-content").empty(); $("#original-headers").empty(); updateStatus(mhaStrings.mhaLoading); buildViews(headers); if (myApp) myApp.hidePreloader(); } // Handles rendering of an error. // Does not log the error - caller is responsible for calling PostError function showError(error, message) { if (myApp) { myApp.hidePreloader(); myApp.alert(message, "An Error Occurred"); } } function eventListener(event) { if (!event || event.origin !== poster.site()) return; if (event.data) { switch (event.data.eventName) { case "showError": showError(JSON.parse(event.data.data.error), event.data.data.message); break; case "updateStatus": updateStatus(event.data.data); break; case "renderItem": renderItem(event.data.data); break; } } } $(document).ready(function () { try { initializeFramework7(); updateStatus(mhaStrings.mhaLoading); window.addEventListener("message", eventListener, false); poster.postMessageToParent("frameActive"); } catch (e) { postError(e, "Failed initializing frame"); showError(e, "Failed initializing frame"); } }); })();
the_stack
import { ObjectInspector } from '@devtools-ds/object-inspector'; import { Call, CallRef, ElementRef } from '@storybook/instrumenter'; import { useTheme } from '@storybook/theming'; import React, { Fragment, ReactElement } from 'react'; const colorsLight = { base: '#444', nullish: '#7D99AA', string: '#16B242', number: '#5D40D0', boolean: '#f41840', objectkey: '#698394', instance: '#A15C20', function: '#EA7509', muted: '#7D99AA', tag: { name: '#6F2CAC', suffix: '#1F99E5', }, date: '#459D9C', error: { name: '#D43900', message: '#444', }, regex: { source: '#A15C20', flags: '#EA7509', }, meta: '#EA7509', method: '#0271B6', }; const colorsDark = { base: '#eee', nullish: '#aaa', string: '#5FE584', number: '#6ba5ff', boolean: '#ff4191', objectkey: '#accfe6', instance: '#E3B551', function: '#E3B551', muted: '#aaa', tag: { name: '#f57bff', suffix: '#8EB5FF', }, date: '#70D4D3', error: { name: '#f40', message: '#eee', }, regex: { source: '#FAD483', flags: '#E3B551', }, meta: '#FAD483', method: '#5EC1FF', }; const useThemeColors = () => { const { base } = useTheme(); return base === 'dark' ? colorsDark : colorsLight; }; const special = /[^A-Z0-9]/i; const trimEnd = /[\s.,…]+$/gm; const ellipsize = (string: string, maxlength: number): string => { if (string.length <= maxlength) return string; for (let i = maxlength - 1; i >= 0; i -= 1) { if (special.test(string[i]) && i > 10) { return `${string.slice(0, i).replace(trimEnd, '')}…`; } } return `${string.slice(0, maxlength).replace(trimEnd, '')}…`; }; const stringify = (value: any) => { try { return JSON.stringify(value, null, 1); } catch (e) { return String(value); } }; const interleave = (nodes: ReactElement[], separator: ReactElement) => nodes.flatMap((node, index) => index === nodes.length - 1 ? [node] : [node, React.cloneElement(separator, { key: `sep${index}` })] ); export const Node = ({ value, nested, showObjectInspector, callsById, ...props }: { value: any; nested?: boolean; /** * Shows an object inspector instead of just printing the object. * Only available for Objects */ showObjectInspector?: boolean; callsById?: Map<Call['id'], Call>; [props: string]: any; }) => { switch (true) { case value === null: return <NullNode {...props} />; case value === undefined: return <UndefinedNode {...props} />; case typeof value === 'string': return <StringNode value={value} {...props} />; case typeof value === 'number': return <NumberNode value={value} {...props} />; case typeof value === 'boolean': return <BooleanNode value={value} {...props} />; case typeof value === 'function': return <FunctionNode value={value} {...props} />; case value instanceof Array: return <ArrayNode value={value} {...props} />; case value instanceof Date: return <DateNode value={value} {...props} />; case value instanceof Error: return <ErrorNode value={value} {...props} />; case value instanceof RegExp: return <RegExpNode value={value} {...props} />; case Object.prototype.hasOwnProperty.call(value, '__element__'): // eslint-disable-next-line no-underscore-dangle return <ElementNode value={value.__element__} {...props} />; case Object.prototype.hasOwnProperty.call(value, '__callId__'): // eslint-disable-next-line no-underscore-dangle return <MethodCall call={callsById.get(value.__callId__)} callsById={callsById} />; case typeof value === 'object' && value.constructor?.name && value.constructor?.name !== 'Object': return <ClassNode value={value} {...props} />; case Object.prototype.toString.call(value) === '[object Object]': return <ObjectNode value={value} showInspector={showObjectInspector} {...props} />; default: return <OtherNode value={value} {...props} />; } }; export const NullNode = (props: object) => { const colors = useThemeColors(); return ( <span style={{ color: colors.nullish }} {...props}> null </span> ); }; export const UndefinedNode = (props: object) => { const colors = useThemeColors(); return ( <span style={{ color: colors.nullish }} {...props}> undefined </span> ); }; export const StringNode = ({ value, ...props }: { value: string }) => { const colors = useThemeColors(); return ( <span style={{ color: colors.string }} {...props}> {JSON.stringify(ellipsize(value, 50))} </span> ); }; export const NumberNode = ({ value, ...props }: { value: number }) => { const colors = useThemeColors(); return ( <span style={{ color: colors.number }} {...props}> {value} </span> ); }; export const BooleanNode = ({ value, ...props }: { value: boolean }) => { const colors = useThemeColors(); return ( <span style={{ color: colors.boolean }} {...props}> {String(value)} </span> ); }; export const ArrayNode = ({ value, nested = false }: { value: any[]; nested?: boolean }) => { const colors = useThemeColors(); if (nested) { return <span style={{ color: colors.base }}>[…]</span>; } const nodes = value.slice(0, 3).map((v) => <Node key={v} value={v} nested />); const nodelist = interleave(nodes, <span>, </span>); if (value.length <= 3) { return <span style={{ color: colors.base }}>[{nodelist}]</span>; } return ( <span style={{ color: colors.base }}> ({value.length}) [{nodelist}, …] </span> ); }; export const ObjectNode = ({ showInspector, value, nested = false, }: { showInspector?: boolean; value: object; nested?: boolean; }) => { const isDarkMode = useTheme().base === 'dark'; const colors = useThemeColors(); if (showInspector) { return ( <> <ObjectInspector id="interactions-object-inspector" data={value} includePrototypes={false} colorScheme={isDarkMode ? 'dark' : 'light'} /> </> ); } if (nested) { return <span style={{ color: colors.base }}>{'{…}'}</span>; } const nodelist = interleave( Object.entries(value) .slice(0, 2) .map(([k, v]) => ( <Fragment key={k}> <span style={{ color: colors.objectkey }}>{k}: </span> <Node value={v} nested /> </Fragment> )), <span>, </span> ); if (Object.keys(value).length <= 2) { return ( <span style={{ color: colors.base }}> {'{ '} {nodelist} {' }'} </span> ); } return ( <span style={{ color: colors.base }}> ({Object.keys(value).length}) {'{ '} {nodelist} {', … }'} </span> ); }; export const ClassNode = ({ value }: { value: Record<string, any> }) => { const colors = useThemeColors(); return <span style={{ color: colors.instance }}>{value.constructor.name}</span>; }; export const FunctionNode = ({ value }: { value: Function }) => { const colors = useThemeColors(); return <span style={{ color: colors.function }}>{value.name || 'anonymous'}</span>; }; export const ElementNode = ({ value }: { value: ElementRef['__element__'] }) => { const { prefix, localName, id, classNames = [], innerText } = value; const name = prefix ? `${prefix}:${localName}` : localName; const colors = useThemeColors(); return ( <span style={{ wordBreak: 'keep-all' }}> <span key={`${name}_lt`} style={{ color: colors.muted }}> &lt; </span> <span key={`${name}_tag`} style={{ color: colors.tag.name }}> {name} </span> <span key={`${name}_suffix`} style={{ color: colors.tag.suffix }}> {id ? `#${id}` : classNames.reduce((acc, className) => `${acc}.${className}`, '')} </span> <span key={`${name}_gt`} style={{ color: colors.muted }}> &gt; </span> {!id && classNames.length === 0 && innerText && ( <> <span key={`${name}_text`}>{innerText}</span> <span key={`${name}_close_lt`} style={{ color: colors.muted }}> &lt; </span> <span key={`${name}_close_tag`} style={{ color: colors.tag.name }}> /{name} </span> <span key={`${name}_close_gt`} style={{ color: colors.muted }}> &gt; </span> </> )} </span> ); }; export const DateNode = ({ value }: { value: Date }) => { const [date, time, ms] = value.toISOString().split(/[T.Z]/); const colors = useThemeColors(); return ( <span style={{ whiteSpace: 'nowrap', color: colors.date }}> {date} <span style={{ opacity: 0.7 }}>T</span> {time === '00:00:00' ? <span style={{ opacity: 0.7 }}>{time}</span> : time} {ms === '000' ? <span style={{ opacity: 0.7 }}>.{ms}</span> : `.${ms}`} <span style={{ opacity: 0.7 }}>Z</span> </span> ); }; export const ErrorNode = ({ value }: { value: Error }) => { const colors = useThemeColors(); return ( <span style={{ color: colors.error.name }}> {value.name} {value.message && ': '} {value.message && ( <span style={{ color: colors.error.message }} title={value.message.length > 50 ? value.message : ''} > {ellipsize(value.message, 50)} </span> )} </span> ); }; export const RegExpNode = ({ value }: { value: RegExp }) => { const colors = useThemeColors(); return ( <span style={{ whiteSpace: 'nowrap', color: colors.regex.flags }}> /<span style={{ color: colors.regex.source }}>{value.source}</span>/{value.flags} </span> ); }; export const SymbolNode = ({ value }: { value: symbol }) => { const colors = useThemeColors(); return ( <span style={{ whiteSpace: 'nowrap', color: colors.instance }}> Symbol( {value.description && ( <span style={{ color: colors.meta }}>{JSON.stringify(value.description)}</span> )} ) </span> ); }; export const OtherNode = ({ value }: { value: any }) => { const colors = useThemeColors(); return <span style={{ color: colors.meta }}>{stringify(value)}</span>; }; export const MethodCall = ({ call, callsById, }: { call: Call; callsById: Map<Call['id'], Call>; }) => { // Call might be undefined during initial render, can be safely ignored. if (!call) return null; const colors = useThemeColors(); const path = call.path.flatMap((elem, index) => { // eslint-disable-next-line no-underscore-dangle const callId = (elem as CallRef).__callId__; return [ callId ? ( <MethodCall key={`elem${index}`} call={callsById.get(callId)} callsById={callsById} /> ) : ( <span key={`elem${index}`}>{elem}</span> ), <wbr key={`wbr${index}`} />, <span key={`dot${index}`}>.</span>, ]; }); const args = call.args.flatMap((arg, index, array) => { const node = <Node key={`node${index}`} value={arg} callsById={callsById} />; return index < array.length - 1 ? [node, <span key={`comma${index}`}>,&nbsp;</span>, <wbr key={`wbr${index}`} />] : [node]; }); return ( <> <span style={{ color: colors.base }}>{path}</span> <span style={{ color: colors.method }}>{call.method}</span> <span style={{ color: colors.base }}> (<wbr /> {args} <wbr />) </span> </> ); };
the_stack
import Cookies from 'js-cookie'; import TokenObject from '../TokenObject'; import {AuthKitStateInterface, AuthStateUserObject} from '../types'; describe('isUsingRefreshToken value is as expected', () => { it('isUsingRefreshToken is false', () => { const tokenObject = new TokenObject( '__', 'cookie', null, window.location.hostname, window.location.protocol === 'https:', ); expect(tokenObject.initialToken().isUsingRefreshToken).toBe(false); }); it('isUsingRefreshToken is true', () => { const tokenObject = new TokenObject( '__', 'cookie', '__r', window.location.hostname, window.location.protocol === 'https:', ); expect(tokenObject.initialToken().isUsingRefreshToken).toBe(true); }); }); describe('Token with Cookie', () => { let tokenObject: TokenObject; beforeEach(() => { tokenObject = new TokenObject( '__', 'cookie', null, window.location.hostname, window.location.protocol === 'https:', ); }); it('Initially blank and signed out state', () => { const {isSignIn, auth, refresh} = tokenObject.initialToken(); expect(isSignIn).toBe(false); expect(auth).toBe(null); expect(refresh).toBe(null); }); }); /** * initialToken * - cookie * - usingRefreshToken * - notUsingRefreshToken * - no-token when exception * - no-token * - localstorage * - usingRefreshToken * - notUsingRefreshToken * - no-token when exception * - no-token */ describe('initialToken', () => { let tokenObject: TokenObject; const authStorageName = '__'; const refreshTokenName = '__refreshTokenName'; const cookieDomain = window.location.hostname; const cookieSecure = window.location.protocol === 'https:'; const authToken = '__authToken'; const authType = '__authType'; const authTime = new Date(2021, 10, 5); const refreshToken = '__refreshToken'; const refreshTime = new Date(2021, 10, 6); const userState = {key: 'val'} as AuthStateUserObject; const authTimeStorageName = `${authStorageName}_storage`; const authStorageTypeName = `${authStorageName}_type`; const stateStorageName = `${authStorageName}_state`; const refreshTokenTimeName = `${refreshTokenName}_time`; describe('cookie', () => { it('token with refreshToken', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'cookie', refreshTokenName, cookieDomain, cookieSecure, ); Cookies.get = jest .fn() .mockImplementationOnce(() => authToken) .mockImplementationOnce(() => authType) .mockImplementationOnce(() => authTime) .mockImplementationOnce(() => JSON.stringify(userState)) .mockImplementationOnce(() => refreshToken) .mockImplementationOnce(() => refreshTime); // Act const actual = tokenObject.initialToken(); // Assert expect(actual).toEqual({ auth: { token: authToken, type: authType, expiresAt: authTime, }, userState: userState, isSignIn: true, isUsingRefreshToken: true, refresh: { token: refreshToken, expiresAt: refreshTime, }, }); }); it('token without refreshToken', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'cookie', null, cookieDomain, cookieSecure, ); Cookies.get = jest .fn() .mockImplementationOnce(() => authToken) .mockImplementationOnce(() => authType) .mockImplementationOnce(() => authTime) .mockImplementationOnce(() => JSON.stringify(userState)); // Act const actual = tokenObject.initialToken(); // Assert expect(actual).toEqual({ auth: { token: authToken, type: authType, expiresAt: authTime, }, userState: userState, isSignIn: true, isUsingRefreshToken: false, refresh: null, }); }); it('no token when found error', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'cookie', null, cookieDomain, cookieSecure, ); Cookies.get = jest .fn() .mockImplementationOnce(() => authToken) .mockImplementationOnce(() => authType) .mockImplementationOnce(() => authTime) .mockImplementationOnce(() => 'NO_JSON'); // Act const actual = tokenObject.initialToken(); // Assert expect(actual).toEqual({ auth: null, refresh: null, userState: null, isUsingRefreshToken: false, isSignIn: false, }); }); it('no token when not found authToken', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'cookie', null, cookieDomain, cookieSecure, ); Cookies.get = jest.fn().mockImplementation(() => null); // Act const actual = tokenObject.initialToken(); // Assert expect(actual).toEqual({ auth: null, refresh: null, userState: null, isUsingRefreshToken: false, isSignIn: false, }); }); }); describe('localstorage', () => { it('token with refreshToken', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'localstorage', refreshTokenName, cookieDomain, cookieSecure, ); localStorage.setItem(authStorageName, authToken); localStorage.setItem(authStorageTypeName, authType); localStorage.setItem(authTimeStorageName, authTime.toISOString()); localStorage.setItem(stateStorageName, JSON.stringify(userState)); localStorage.setItem(refreshTokenName, refreshToken); localStorage.setItem(refreshTokenTimeName, refreshTime.toISOString()); // Act const actual = tokenObject.initialToken(); // Assert expect(actual).toEqual({ auth: { token: authToken, type: authType, expiresAt: authTime, }, userState: userState, isSignIn: true, isUsingRefreshToken: true, refresh: { token: refreshToken, expiresAt: refreshTime, }, }); }); }); it('token without refreshToken', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'localstorage', null, cookieDomain, cookieSecure, ); localStorage.setItem(authStorageName, authToken); localStorage.setItem(authStorageTypeName, authType); localStorage.setItem(authTimeStorageName, authTime.toISOString()); localStorage.setItem(stateStorageName, JSON.stringify(userState)); // Act const actual = tokenObject.initialToken(); // Assert expect(actual).toEqual({ auth: { token: authToken, type: authType, expiresAt: authTime, }, userState: userState, isSignIn: true, isUsingRefreshToken: false, refresh: null, }); }); it('no token when found error', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'localstorage', null, cookieDomain, cookieSecure, ); localStorage.setItem(authStorageName, authToken); localStorage.setItem(authStorageTypeName, authType); localStorage.setItem(authTimeStorageName, authTime.toISOString()); localStorage.setItem(stateStorageName, 'NO_JSON'); // Act const actual = tokenObject.initialToken(); // Assert expect(actual).toEqual({ auth: null, refresh: null, userState: null, isUsingRefreshToken: false, isSignIn: false, }); }); it('no token when not found authToken', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'localstorage', null, cookieDomain, cookieSecure, ); // Act const actual = tokenObject.initialToken(); // Assert expect(actual).toEqual({ auth: null, refresh: null, userState: null, isUsingRefreshToken: false, isSignIn: false, }); }); }); /** * syncTokens * - withAuth * - usingRefreshToken * - cookie * - localstorage * - notUsingRefreshToken * - cookie * - localstorage * - withoutAuth * - cookie * - localstorage */ describe('syncTokens', () => { let tokenObject: TokenObject; const authStorageName = '__'; const refreshTokenName = '__refreshTokenName'; const cookieDomain = window.location.hostname; const cookieSecure = window.location.protocol === 'https:'; const authTimeStorageName = `${authStorageName}_storage`; const authStorageTypeName = `${authStorageName}_type`; const stateStorageName = `${authStorageName}_state`; const refreshTokenTimeName = `${refreshTokenName}_time`; const tokenKeys = [ authStorageName, authTimeStorageName, authStorageTypeName, stateStorageName, ]; const refreshTokenKeys = [refreshTokenName, refreshTokenTimeName]; beforeEach(() => { // init localStorage with data tokenKeys.forEach((key) => { localStorage.setItem(key, '___'); }); refreshTokenKeys.forEach((key) => { localStorage.setItem(key, '_____'); }); }); describe('With Auth', () => { const authToken = '__authToken'; const authType = '__authType'; const authTime = new Date(2021, 10, 5); const refreshToken = '__refreshToken'; const refreshTime = new Date(2021, 10, 6); const userState = {key: 'val'} as AuthStateUserObject; describe('Using Refresh Token', () => { const authState = { auth: {token: authToken, type: authType, expiresAt: authTime}, refresh: {token: refreshToken, expiresAt: refreshTime}, userState, } as AuthKitStateInterface; it('Cookie Type', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'cookie', refreshTokenName, cookieDomain, cookieSecure, ); // mock Cookie Cookies.set = jest.fn(); // Act tokenObject.syncTokens(authState); // Assert // keys should set after syncTokens expect(Cookies.set).toHaveBeenCalledWith( authStorageName, authState.auth?.token, { expires: authState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); expect(Cookies.set).toHaveBeenCalledWith( authStorageTypeName, authState.auth?.type, { expires: authState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); expect(Cookies.set).toHaveBeenCalledWith( authTimeStorageName, authState.auth?.expiresAt.toISOString(), { expires: authState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); expect(Cookies.set).toHaveBeenCalledWith( stateStorageName, JSON.stringify(authState.userState), { expires: authState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); expect(Cookies.set).toHaveBeenCalledWith( refreshTokenName, refreshToken, { expires: authState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); expect(Cookies.set).toHaveBeenCalledWith( refreshTokenTimeName, authState.refresh?.expiresAt.toISOString(), { expires: authState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); }); it('LocalStorage Type', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'localstorage', refreshTokenName, cookieDomain, cookieSecure, ); // Act tokenObject.syncTokens(authState); // Assert // keys should set after syncTokens expect(localStorage.getItem(authStorageName)).toEqual( authState.auth?.token, ); expect(localStorage.getItem(authStorageTypeName)).toEqual( authState.auth?.type, ); expect(localStorage.getItem(authTimeStorageName)).toEqual( authState.auth?.expiresAt.toISOString(), ); expect(localStorage.getItem(stateStorageName)).toEqual( JSON.stringify(authState.userState), ); expect(localStorage.getItem(refreshTokenName)).toEqual( authState.refresh?.token, ); expect(localStorage.getItem(refreshTokenTimeName)).toEqual( authState.refresh?.expiresAt.toISOString(), ); }); }); describe('Not Using Refresh Token', () => { const noRefreshTokenAuthState = { auth: {token: authToken, type: authType, expiresAt: authTime}, refresh: null, userState, } as AuthKitStateInterface; beforeEach(() => { refreshTokenKeys.forEach((key) => { localStorage.removeItem(key); }); }); it('Cookie Type', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'cookie', null, cookieDomain, cookieSecure, ); // mock Cookie Cookies.set = jest.fn(); // Act tokenObject.syncTokens(noRefreshTokenAuthState); // Assert // keys should set after syncTokens expect(Cookies.set).toHaveBeenCalledWith( authStorageName, noRefreshTokenAuthState.auth?.token, { expires: noRefreshTokenAuthState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); expect(Cookies.set).toHaveBeenCalledWith( authStorageTypeName, noRefreshTokenAuthState.auth?.type, { expires: noRefreshTokenAuthState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); expect(Cookies.set).toHaveBeenCalledWith( authTimeStorageName, noRefreshTokenAuthState.auth?.expiresAt.toISOString(), { expires: noRefreshTokenAuthState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); expect(Cookies.set).toHaveBeenCalledWith( stateStorageName, JSON.stringify(noRefreshTokenAuthState.userState), { expires: noRefreshTokenAuthState.auth?.expiresAt, domain: cookieDomain, secure: cookieSecure, }, ); expect(Cookies.set).not.toHaveBeenCalledWith(refreshTokenName); expect(Cookies.set).not.toHaveBeenCalledWith(refreshTokenTimeName); }); it('LocalStorage Type', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'localstorage', null, cookieDomain, cookieSecure, ); // Act tokenObject.syncTokens(noRefreshTokenAuthState); // Assert // keys should set after syncTokens expect(localStorage.getItem(authStorageName)).toEqual( noRefreshTokenAuthState.auth?.token, ); expect(localStorage.getItem(authStorageTypeName)).toEqual( noRefreshTokenAuthState.auth?.type, ); expect(localStorage.getItem(authTimeStorageName)).toEqual( noRefreshTokenAuthState.auth?.expiresAt.toISOString(), ); expect(localStorage.getItem(stateStorageName)).toEqual( JSON.stringify(noRefreshTokenAuthState.userState), ); expect(localStorage.getItem(refreshTokenName)).toBeFalsy(); expect(localStorage.getItem(refreshTokenTimeName)).toBeFalsy(); }); }); }); describe('Without Auth: Tokens should removed', () => { describe('Using Refresh Token', () => { it('Cookie Type', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'cookie', refreshTokenName, cookieDomain, cookieSecure, ); Cookies.remove = jest.fn(); const authState = {} as AuthKitStateInterface; // Act tokenObject.syncTokens(authState); // Assert // keys should remove after syncTokens [...tokenKeys, ...refreshTokenKeys].forEach((key) => { expect(Cookies.remove).toHaveBeenCalledWith(key, { domain: cookieDomain, secure: cookieSecure, }); }); }); it('LocalStorage Type', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'localstorage', refreshTokenName, cookieDomain, cookieSecure, ); const authState = {} as AuthKitStateInterface; // keys should exist before syncTokens [...tokenKeys, ...refreshTokenKeys].forEach((key) => { expect(localStorage.getItem(key)).toBeTruthy(); }); // Act tokenObject.syncTokens(authState); // Assert // keys should removed after syncTokens [...tokenKeys, ...refreshTokenKeys].forEach((key) => { expect(localStorage.getItem(key)).toBeFalsy(); }); }); }); describe('Not Using Refresh Token', () => { beforeEach(() => { refreshTokenKeys.forEach((key) => { localStorage.removeItem(key); }); }); it('Cookie Type', () => { // Arrange tokenObject = new TokenObject( authStorageName, 'cookie', null, cookieDomain, cookieSecure, ); Cookies.remove = jest.fn(); const authState = {} as AuthKitStateInterface; // Act tokenObject.syncTokens(authState); // Assert // keys should remove after syncTokens tokenKeys.forEach((key) => { expect(Cookies.remove).toHaveBeenCalledWith(key, { domain: cookieDomain, secure: cookieSecure, }); }); refreshTokenKeys.forEach((key) => { expect(Cookies.remove).not.toHaveBeenCalledWith(key, { domain: cookieDomain, secure: cookieSecure, }); }); }); it('LocalStorage Type', () => { // arrange tokenObject = new TokenObject( authStorageName, 'localstorage', null, cookieDomain, cookieSecure, ); const authState = {} as AuthKitStateInterface; // keys should exist before syncTokens [...tokenKeys].forEach((key) => { expect(localStorage.getItem(key)).toBeTruthy(); }); // act tokenObject.syncTokens(authState); // assert // keys should removed after syncTokens [...tokenKeys].forEach((key) => { expect(localStorage.getItem(key)).toBeFalsy(); }); }); }); }); }); export {};
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/clientGroupsMappers"; import * as Parameters from "../models/parameters"; import { ServicemapManagementClientContext } from "../servicemapManagementClientContext"; /** Class representing a ClientGroups. */ export class ClientGroups { private readonly client: ServicemapManagementClientContext; /** * Create a ClientGroups. * @param {ServicemapManagementClientContext} client Reference to the service client. */ constructor(client: ServicemapManagementClientContext) { this.client = client; } /** * Retrieves the specified client group * @param resourceGroupName Resource group name within the specified subscriptionId. * @param workspaceName OMS workspace containing the resources of interest. * @param clientGroupName Client Group resource name. * @param [options] The optional parameters * @returns Promise<Models.ClientGroupsGetResponse> */ get(resourceGroupName: string, workspaceName: string, clientGroupName: string, options?: Models.ClientGroupsGetOptionalParams): Promise<Models.ClientGroupsGetResponse>; /** * @param resourceGroupName Resource group name within the specified subscriptionId. * @param workspaceName OMS workspace containing the resources of interest. * @param clientGroupName Client Group resource name. * @param callback The callback */ get(resourceGroupName: string, workspaceName: string, clientGroupName: string, callback: msRest.ServiceCallback<Models.ClientGroup>): void; /** * @param resourceGroupName Resource group name within the specified subscriptionId. * @param workspaceName OMS workspace containing the resources of interest. * @param clientGroupName Client Group resource name. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, workspaceName: string, clientGroupName: string, options: Models.ClientGroupsGetOptionalParams, callback: msRest.ServiceCallback<Models.ClientGroup>): void; get(resourceGroupName: string, workspaceName: string, clientGroupName: string, options?: Models.ClientGroupsGetOptionalParams | msRest.ServiceCallback<Models.ClientGroup>, callback?: msRest.ServiceCallback<Models.ClientGroup>): Promise<Models.ClientGroupsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, clientGroupName, options }, getOperationSpec, callback) as Promise<Models.ClientGroupsGetResponse>; } /** * Returns the approximate number of members in the client group. * @param resourceGroupName Resource group name within the specified subscriptionId. * @param workspaceName OMS workspace containing the resources of interest. * @param clientGroupName Client Group resource name. * @param [options] The optional parameters * @returns Promise<Models.ClientGroupsGetMembersCountResponse> */ getMembersCount(resourceGroupName: string, workspaceName: string, clientGroupName: string, options?: Models.ClientGroupsGetMembersCountOptionalParams): Promise<Models.ClientGroupsGetMembersCountResponse>; /** * @param resourceGroupName Resource group name within the specified subscriptionId. * @param workspaceName OMS workspace containing the resources of interest. * @param clientGroupName Client Group resource name. * @param callback The callback */ getMembersCount(resourceGroupName: string, workspaceName: string, clientGroupName: string, callback: msRest.ServiceCallback<Models.ClientGroupMembersCount>): void; /** * @param resourceGroupName Resource group name within the specified subscriptionId. * @param workspaceName OMS workspace containing the resources of interest. * @param clientGroupName Client Group resource name. * @param options The optional parameters * @param callback The callback */ getMembersCount(resourceGroupName: string, workspaceName: string, clientGroupName: string, options: Models.ClientGroupsGetMembersCountOptionalParams, callback: msRest.ServiceCallback<Models.ClientGroupMembersCount>): void; getMembersCount(resourceGroupName: string, workspaceName: string, clientGroupName: string, options?: Models.ClientGroupsGetMembersCountOptionalParams | msRest.ServiceCallback<Models.ClientGroupMembersCount>, callback?: msRest.ServiceCallback<Models.ClientGroupMembersCount>): Promise<Models.ClientGroupsGetMembersCountResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, clientGroupName, options }, getMembersCountOperationSpec, callback) as Promise<Models.ClientGroupsGetMembersCountResponse>; } /** * Returns the members of the client group during the specified time interval. * @param resourceGroupName Resource group name within the specified subscriptionId. * @param workspaceName OMS workspace containing the resources of interest. * @param clientGroupName Client Group resource name. * @param [options] The optional parameters * @returns Promise<Models.ClientGroupsListMembersResponse> */ listMembers(resourceGroupName: string, workspaceName: string, clientGroupName: string, options?: Models.ClientGroupsListMembersOptionalParams): Promise<Models.ClientGroupsListMembersResponse>; /** * @param resourceGroupName Resource group name within the specified subscriptionId. * @param workspaceName OMS workspace containing the resources of interest. * @param clientGroupName Client Group resource name. * @param callback The callback */ listMembers(resourceGroupName: string, workspaceName: string, clientGroupName: string, callback: msRest.ServiceCallback<Models.ClientGroupMembersCollection>): void; /** * @param resourceGroupName Resource group name within the specified subscriptionId. * @param workspaceName OMS workspace containing the resources of interest. * @param clientGroupName Client Group resource name. * @param options The optional parameters * @param callback The callback */ listMembers(resourceGroupName: string, workspaceName: string, clientGroupName: string, options: Models.ClientGroupsListMembersOptionalParams, callback: msRest.ServiceCallback<Models.ClientGroupMembersCollection>): void; listMembers(resourceGroupName: string, workspaceName: string, clientGroupName: string, options?: Models.ClientGroupsListMembersOptionalParams | msRest.ServiceCallback<Models.ClientGroupMembersCollection>, callback?: msRest.ServiceCallback<Models.ClientGroupMembersCollection>): Promise<Models.ClientGroupsListMembersResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, clientGroupName, options }, listMembersOperationSpec, callback) as Promise<Models.ClientGroupsListMembersResponse>; } /** * Returns the members of the client group during the specified time interval. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ClientGroupsListMembersNextResponse> */ listMembersNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ClientGroupsListMembersNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listMembersNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ClientGroupMembersCollection>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listMembersNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ClientGroupMembersCollection>): void; listMembersNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ClientGroupMembersCollection>, callback?: msRest.ServiceCallback<Models.ClientGroupMembersCollection>): Promise<Models.ClientGroupsListMembersNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listMembersNextOperationSpec, callback) as Promise<Models.ClientGroupsListMembersNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/features/serviceMap/clientGroups/{clientGroupName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.workspaceName, Parameters.clientGroupName ], queryParameters: [ Parameters.apiVersion, Parameters.startTime, Parameters.endTime ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ClientGroup }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getMembersCountOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/features/serviceMap/clientGroups/{clientGroupName}/membersCount", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.workspaceName, Parameters.clientGroupName ], queryParameters: [ Parameters.apiVersion, Parameters.startTime, Parameters.endTime ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ClientGroupMembersCount }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listMembersOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/features/serviceMap/clientGroups/{clientGroupName}/members", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.workspaceName, Parameters.clientGroupName ], queryParameters: [ Parameters.apiVersion, Parameters.startTime, Parameters.endTime, Parameters.top ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ClientGroupMembersCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listMembersNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ClientGroupMembersCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import CameraComponent from '../../../dist/esm/foundation/components/CameraComponent'; import _Rn, {Material} from '../../../dist/esm/index'; let p: any; declare const window: any; declare const Rn: typeof _Rn; (async () => { await Rn.ModuleManager.getInstance().loadModule('webgl'); await Rn.ModuleManager.getInstance().loadModule('pbr'); const system = Rn.System.getInstance(); const gl = system.setProcessApproachAndCanvas( Rn.ProcessApproach.UniformWebGL1, document.getElementById('world') as HTMLCanvasElement ); const VRMImporter = Rn.VRMImporter.getInstance(); const entityRepository = Rn.EntityRepository.getInstance(); // params const rootGroupScale = Rn.Vector3.fromCopyArray([1, 1, 1]); const displayResolution = 800; // setting cameras except for post effect const mainCameraComponent = createCameraComponent(); mainCameraComponent.zNear = 0.1; mainCameraComponent.zFar = 1000.0; mainCameraComponent.setFovyAndChangeFocalLength(25.0); mainCameraComponent.aspect = 1.0; // mainCameraComponent.zFarInner = 3000.0; const renderPassMain = renderPassHelperSetCameraComponent( mainCameraComponent ); const framebufferMain = createFramebuffer( renderPassMain, 2 * displayResolution, 2 * displayResolution, 1, {} ); const postEffectCameraEntity = createPostEffectCameraEntity(); const postEffectCameraComponent = postEffectCameraEntity.getCamera(); const gammaCorrectionMaterial = Rn.MaterialHelper.createGammaCorrectionMaterial(); const gammaCorrectionRenderPass = createPostEffectRenderPass( gammaCorrectionMaterial, postEffectCameraComponent ); setTextureParameterForMeshComponents( gammaCorrectionRenderPass.meshComponents, Rn.ShaderSemantics.BaseColorTexture, framebufferMain.colorAttachments[0] ); const framebufferGamma = createFramebuffer( gammaCorrectionRenderPass, displayResolution, displayResolution, 1, {} ); const fxaaMaterial = Rn.MaterialHelper.createFXAA3QualityMaterial(); const fxaaRenderPass = createPostEffectRenderPass( fxaaMaterial, postEffectCameraComponent ); setParameterForMeshComponents( fxaaRenderPass.meshComponents, Rn.ShaderSemantics.ScreenInfo, Rn.Vector2.fromCopyArray2([displayResolution, displayResolution]) ); setTextureParameterForMeshComponents( fxaaRenderPass.meshComponents, Rn.ShaderSemantics.BaseColorTexture, framebufferGamma.colorAttachments[0] ); const expression = new Rn.Expression(); expression.addRenderPasses([ renderPassMain, gammaCorrectionRenderPass, fxaaRenderPass, ]); // rootGroups[0]: main entity, rootGroups[1]: outline entity(if exist) const rootGroups = await VRMImporter.import( './../../../assets/vrm/test.vrm', { defaultMaterialHelperArgumentArray: [ { isLighting: true, isSkinning: false, isMorphing: false, makeOutputSrgb: false, }, ], // autoResizeTexture: true } ); for (const rootGroup of rootGroups) { rootGroup.getTransform().scale = rootGroupScale; rootGroup.getTransform().rotate = Rn.Vector3.fromCopyArray([0.0, Math.PI, 0.0]); } renderPassMain.addEntities(rootGroups); // Env Cube const sphereEntity = entityRepository.createEntity([ Rn.TransformComponent, Rn.SceneGraphComponent, Rn.MeshComponent, Rn.MeshRendererComponent, ]); const spherePrimitive = new Rn.Sphere(); window.sphereEntity = sphereEntity; const sphereMaterial = Rn.MaterialHelper.createEnvConstantMaterial(); const environmentCubeTexture = new Rn.CubeTexture(); environmentCubeTexture.baseUriToLoad = './../../../assets/ibl/shanghai_bund/environment/environment'; environmentCubeTexture.isNamePosNeg = true; environmentCubeTexture.hdriFormat = Rn.HdriFormat.LDR_SRGB; environmentCubeTexture.mipmapLevelNumber = 1; environmentCubeTexture.loadTextureImagesAsync(); sphereMaterial.setTextureParameter( Rn.ShaderSemantics.ColorEnvTexture, environmentCubeTexture ); spherePrimitive.generate({ radius: -50, widthSegments: 40, heightSegments: 40, material: sphereMaterial, }); const sphereMeshComponent = sphereEntity.getMesh(); const sphereMesh = new Rn.Mesh(); sphereMesh.addPrimitive(spherePrimitive); sphereMeshComponent.setMesh(sphereMesh); sphereEntity.getTransform().translate = Rn.Vector3.fromCopyArray([0, 20, -20]); renderPassMain.addEntities([sphereEntity]); // Lights const lightEntity = entityRepository.createEntity([ Rn.TransformComponent, Rn.SceneGraphComponent, Rn.LightComponent, ]); const lightComponent = lightEntity.getLight(); lightComponent.type = Rn.LightType.Directional; lightComponent.intensity = Rn.Vector3.fromCopyArray([1.0, 1.0, 1.0]); lightEntity.getTransform().rotate = Rn.Vector3.fromCopyArray([0.0, 0.0, Math.PI / 8]); // CameraControllerComponent const mainCameraEntityUID = mainCameraComponent.entityUID; entityRepository.addComponentsToEntity( [Rn.CameraControllerComponent], mainCameraEntityUID ); const mainCameraEntity = mainCameraComponent.entity; const cameraControllerComponent = mainCameraEntity.getCameraController(); cameraControllerComponent.controller.setTarget(rootGroups[0]); Rn.CameraComponent.main = 0; const startTime = Date.now(); // const rotationVec3 = Rn.MutableVector3.one(); let count = 0; const rot = 0; const draw = function () { if (p == null && count > 0) { if (rootGroups[0] != null) { gl.enable(gl.DEPTH_TEST); gl.viewport(0, 0, 800, 800); gl.clearColor(0.8, 0.8, 0.8, 1.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } p = document.createElement('p'); p.setAttribute('id', 'rendered'); p.innerText = 'Rendered.'; document.body.appendChild(p); } if (window.isAnimating) { const date = new Date(); } system.process([expression]); count++; requestAnimationFrame(draw); }; draw(); })(); window.exportGltf2 = function () { const exporter = Rn.Gltf2Exporter.getInstance(); exporter.export('Rhodonite'); }; function rotEnv(rot) { for (const meshRendererComponent of window.meshRendererComponents) { meshRendererComponent.rotationOfCubeMap = rot; } // window.sphere2MeshRendererComponent.rotationOfCubeMap = rot; window.sphereEntity.getTransform().rotate = Rn.Vector3.fromCopyArray([0, -rot, 0]); } function setDiffuseCubeMapContribution(value) { for (const meshRendererComponent of window.meshRendererComponents) { meshRendererComponent.diffuseCubeMapContribution = value; } } function setSpecularCubeMapContribution(value) { for (const meshRendererComponent of window.meshRendererComponents) { meshRendererComponent.specularCubeMapContribution = value; } } function setAnisotropy(baseAnisotropy, clearcoatAnisotropy) { const materials = Rn.Material.getAllMaterials(); for (const material of materials) { material.setParameter( Rn.ShaderSemantics.Anisotropy, Rn.Vector2.fromCopyArray2([baseAnisotropy, clearcoatAnisotropy]) ); } } function setClearCoat(factor, roughness) { const materials = Rn.Material.getAllMaterials(); for (const material of materials) { material.setParameter( Rn.ShaderSemantics.ClearCoatParameter, Rn.Vector2.fromCopyArray2([factor, roughness]) ); } } function setSheen(sheenColor, sheenSubsurfaceColor) { const materials = Rn.Material.getAllMaterials(); for (const material of materials) { material.setParameter( Rn.ShaderSemantics.SheenParameter, Rn.Vector2.fromCopyArray2([sheenColor, sheenSubsurfaceColor]) ); } } function arrayDifference(arrayWholeSet, arraySubset) { const result = arrayWholeSet.slice(); for (let i = 0; i < arraySubset.length; i++) { const deleteIndex = result.indexOf(arraySubset[i]); result.splice(deleteIndex, 1); } return result; } function createCameraComponent() { const entityRepository = Rn.EntityRepository.getInstance(); const cameraEntity = entityRepository.createEntity([ Rn.TransformComponent, Rn.SceneGraphComponent, Rn.CameraComponent, ]); const cameraComponent = cameraEntity.getCamera(); return cameraComponent; } function createFramebuffer(renderPass, width, height, textureNum, property) { const framebuffer = Rn.RenderableHelper.createTexturesForRenderTarget( width, height, textureNum, property ); renderPass.setFramebuffer(framebuffer); return framebuffer; } function materialHelperForMeshComponents( meshComponents, materialHelperFunctionStr, argumentsArray ) { for (const meshComponent of meshComponents) { const mesh = meshComponent.mesh; for (let i = 0; i < mesh.getPrimitiveNumber(); i++) { const primitive = mesh.getPrimitiveAt(i); primitive.material = Rn.MaterialHelper[materialHelperFunctionStr].apply( this, argumentsArray ); } } } function createPostEffectRenderPass( material: Material, cameraComponent: CameraComponent ) { const boardPrimitive = new Rn.Plane(); boardPrimitive.generate({ width: 1, height: 1, uSpan: 1, vSpan: 1, isUVRepeat: false, material, }); const boardMesh = new Rn.Mesh(); boardMesh.addPrimitive(boardPrimitive); const boardEntity = generateEntity(); boardEntity.getTransform().rotate = Rn.Vector3.fromCopyArray([Math.PI / 2, 0.0, 0.0]); boardEntity.getTransform().translate = Rn.Vector3.fromCopyArray([0.0, 0.0, -0.5]); const boardMeshComponent = boardEntity.getMesh(); boardMeshComponent.setMesh(boardMesh); const renderPass = new Rn.RenderPass(); renderPass.toClearColorBuffer = false; renderPass.cameraComponent = cameraComponent; renderPass.addEntities([boardEntity]); return renderPass; } function createPostEffectCameraEntity() { const cameraEntity = generateEntity([ Rn.TransformComponent, Rn.SceneGraphComponent, Rn.CameraComponent, ]); const cameraComponent = cameraEntity.getCamera(); cameraComponent.zNearInner = 0.5; cameraComponent.zFarInner = 2.0; return cameraEntity; } function generateEntity( componentArray = [ Rn.TransformComponent, Rn.SceneGraphComponent, Rn.MeshComponent, Rn.MeshRendererComponent, ] as Array<typeof Rn.Component> ) { const repo = Rn.EntityRepository.getInstance(); const entity = repo.createEntity(componentArray); return entity; } function renderPassHelperSetCameraComponent(cameraComponent) { const renderPass = new Rn.RenderPass(); renderPass.toClearColorBuffer = true; renderPass.cameraComponent = cameraComponent; return renderPass; } function setParameterForMeshComponents(meshComponents, shaderSemantic, value) { for (let i = 0; i < meshComponents.length; i++) { const mesh = meshComponents[i].mesh; const primitiveNumber = mesh.getPrimitiveNumber(); for (let j = 0; j < primitiveNumber; j++) { const primitive = mesh.getPrimitiveAt(j); primitive.material.setParameter(shaderSemantic, value); } } } function setTextureParameterForMeshComponents( meshComponents, shaderSemantic, value ) { for (let i = 0; i < meshComponents.length; i++) { const mesh = meshComponents[i].mesh; if (!mesh) continue; const primitiveNumber = mesh.getPrimitiveNumber(); for (let j = 0; j < primitiveNumber; j++) { const primitive = mesh.getPrimitiveAt(j); primitive.material.setTextureParameter(shaderSemantic, value); } } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/communicationServiceMappers"; import * as Parameters from "../models/parameters"; import { CommunicationServiceManagementClientContext } from "../communicationServiceManagementClientContext"; /** Class representing a CommunicationService. */ export class CommunicationService { private readonly client: CommunicationServiceManagementClientContext; /** * Create a CommunicationService. * @param {CommunicationServiceManagementClientContext} client Reference to the service client. */ constructor(client: CommunicationServiceManagementClientContext) { this.client = client; } /** * Checks that the CommunicationService name is valid and is not already in use. * @summary Check Name Availability * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceCheckNameAvailabilityResponse> */ checkNameAvailability(options?: Models.CommunicationServiceCheckNameAvailabilityOptionalParams): Promise<Models.CommunicationServiceCheckNameAvailabilityResponse>; /** * @param callback The callback */ checkNameAvailability(callback: msRest.ServiceCallback<Models.NameAvailability>): void; /** * @param options The optional parameters * @param callback The callback */ checkNameAvailability(options: Models.CommunicationServiceCheckNameAvailabilityOptionalParams, callback: msRest.ServiceCallback<Models.NameAvailability>): void; checkNameAvailability(options?: Models.CommunicationServiceCheckNameAvailabilityOptionalParams | msRest.ServiceCallback<Models.NameAvailability>, callback?: msRest.ServiceCallback<Models.NameAvailability>): Promise<Models.CommunicationServiceCheckNameAvailabilityResponse> { return this.client.sendOperationRequest( { options }, checkNameAvailabilityOperationSpec, callback) as Promise<Models.CommunicationServiceCheckNameAvailabilityResponse>; } /** * Links an Azure Notification Hub to this communication service. * @summary Link Notification Hub * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceLinkNotificationHubResponse> */ linkNotificationHub(resourceGroupName: string, communicationServiceName: string, options?: Models.CommunicationServiceLinkNotificationHubOptionalParams): Promise<Models.CommunicationServiceLinkNotificationHubResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param callback The callback */ linkNotificationHub(resourceGroupName: string, communicationServiceName: string, callback: msRest.ServiceCallback<Models.LinkedNotificationHub>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param options The optional parameters * @param callback The callback */ linkNotificationHub(resourceGroupName: string, communicationServiceName: string, options: Models.CommunicationServiceLinkNotificationHubOptionalParams, callback: msRest.ServiceCallback<Models.LinkedNotificationHub>): void; linkNotificationHub(resourceGroupName: string, communicationServiceName: string, options?: Models.CommunicationServiceLinkNotificationHubOptionalParams | msRest.ServiceCallback<Models.LinkedNotificationHub>, callback?: msRest.ServiceCallback<Models.LinkedNotificationHub>): Promise<Models.CommunicationServiceLinkNotificationHubResponse> { return this.client.sendOperationRequest( { resourceGroupName, communicationServiceName, options }, linkNotificationHubOperationSpec, callback) as Promise<Models.CommunicationServiceLinkNotificationHubResponse>; } /** * Handles requests to list all resources in a subscription. * @summary List By Subscription * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceListBySubscriptionResponse> */ listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.CommunicationServiceListBySubscriptionResponse>; /** * @param callback The callback */ listBySubscription(callback: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): void; listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommunicationServiceResourceList>, callback?: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): Promise<Models.CommunicationServiceListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec, callback) as Promise<Models.CommunicationServiceListBySubscriptionResponse>; } /** * Handles requests to list all resources in a resource group. * @summary List By Resource Group * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationServiceListByResourceGroupResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommunicationServiceResourceList>, callback?: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): Promise<Models.CommunicationServiceListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.CommunicationServiceListByResourceGroupResponse>; } /** * Operation to update an existing CommunicationService. * @summary Update * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceUpdateResponse> */ update(resourceGroupName: string, communicationServiceName: string, options?: Models.CommunicationServiceUpdateOptionalParams): Promise<Models.CommunicationServiceUpdateResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param callback The callback */ update(resourceGroupName: string, communicationServiceName: string, callback: msRest.ServiceCallback<Models.CommunicationServiceResource>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, communicationServiceName: string, options: Models.CommunicationServiceUpdateOptionalParams, callback: msRest.ServiceCallback<Models.CommunicationServiceResource>): void; update(resourceGroupName: string, communicationServiceName: string, options?: Models.CommunicationServiceUpdateOptionalParams | msRest.ServiceCallback<Models.CommunicationServiceResource>, callback?: msRest.ServiceCallback<Models.CommunicationServiceResource>): Promise<Models.CommunicationServiceUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, communicationServiceName, options }, updateOperationSpec, callback) as Promise<Models.CommunicationServiceUpdateResponse>; } /** * Get the CommunicationService and its properties. * @summary Get * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceGetResponse> */ get(resourceGroupName: string, communicationServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationServiceGetResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param callback The callback */ get(resourceGroupName: string, communicationServiceName: string, callback: msRest.ServiceCallback<Models.CommunicationServiceResource>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, communicationServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommunicationServiceResource>): void; get(resourceGroupName: string, communicationServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommunicationServiceResource>, callback?: msRest.ServiceCallback<Models.CommunicationServiceResource>): Promise<Models.CommunicationServiceGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, communicationServiceName, options }, getOperationSpec, callback) as Promise<Models.CommunicationServiceGetResponse>; } /** * Create a new CommunicationService or update an existing CommunicationService. * @summary Create Or Update * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, communicationServiceName: string, options?: Models.CommunicationServiceCreateOrUpdateOptionalParams): Promise<Models.CommunicationServiceCreateOrUpdateResponse> { return this.beginCreateOrUpdate(resourceGroupName,communicationServiceName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.CommunicationServiceCreateOrUpdateResponse>; } /** * Operation to delete a CommunicationService. * @summary Delete * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceDeleteResponse> */ deleteMethod(resourceGroupName: string, communicationServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationServiceDeleteResponse> { return this.beginDeleteMethod(resourceGroupName,communicationServiceName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.CommunicationServiceDeleteResponse>; } /** * Get the access keys of the CommunicationService resource. * @summary List Keys * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceListKeysResponse> */ listKeys(resourceGroupName: string, communicationServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationServiceListKeysResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param callback The callback */ listKeys(resourceGroupName: string, communicationServiceName: string, callback: msRest.ServiceCallback<Models.CommunicationServiceKeys>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param options The optional parameters * @param callback The callback */ listKeys(resourceGroupName: string, communicationServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommunicationServiceKeys>): void; listKeys(resourceGroupName: string, communicationServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommunicationServiceKeys>, callback?: msRest.ServiceCallback<Models.CommunicationServiceKeys>): Promise<Models.CommunicationServiceListKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, communicationServiceName, options }, listKeysOperationSpec, callback) as Promise<Models.CommunicationServiceListKeysResponse>; } /** * Regenerate CommunicationService access key. PrimaryKey and SecondaryKey cannot be regenerated at * the same time. * @summary Regenerate Key * @param parameters Parameter that describes the Regenerate Key Operation. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceRegenerateKeyResponse> */ regenerateKey(parameters: Models.RegenerateKeyParameters, resourceGroupName: string, communicationServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationServiceRegenerateKeyResponse>; /** * @param parameters Parameter that describes the Regenerate Key Operation. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param callback The callback */ regenerateKey(parameters: Models.RegenerateKeyParameters, resourceGroupName: string, communicationServiceName: string, callback: msRest.ServiceCallback<Models.CommunicationServiceKeys>): void; /** * @param parameters Parameter that describes the Regenerate Key Operation. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param options The optional parameters * @param callback The callback */ regenerateKey(parameters: Models.RegenerateKeyParameters, resourceGroupName: string, communicationServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommunicationServiceKeys>): void; regenerateKey(parameters: Models.RegenerateKeyParameters, resourceGroupName: string, communicationServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommunicationServiceKeys>, callback?: msRest.ServiceCallback<Models.CommunicationServiceKeys>): Promise<Models.CommunicationServiceRegenerateKeyResponse> { return this.client.sendOperationRequest( { parameters, resourceGroupName, communicationServiceName, options }, regenerateKeyOperationSpec, callback) as Promise<Models.CommunicationServiceRegenerateKeyResponse>; } /** * Create a new CommunicationService or update an existing CommunicationService. * @summary Create Or Update * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(resourceGroupName: string, communicationServiceName: string, options?: Models.CommunicationServiceBeginCreateOrUpdateOptionalParams): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, communicationServiceName, options }, beginCreateOrUpdateOperationSpec, options); } /** * Operation to delete a CommunicationService. * @summary Delete * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param communicationServiceName The name of the CommunicationService resource. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, communicationServiceName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, communicationServiceName, options }, beginDeleteMethodOperationSpec, options); } /** * Handles requests to list all resources in a subscription. * @summary List By Subscription * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceListBySubscriptionNextResponse> */ listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationServiceListBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): void; listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommunicationServiceResourceList>, callback?: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): Promise<Models.CommunicationServiceListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionNextOperationSpec, callback) as Promise<Models.CommunicationServiceListBySubscriptionNextResponse>; } /** * Handles requests to list all resources in a resource group. * @summary List By Resource Group * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.CommunicationServiceListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationServiceListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommunicationServiceResourceList>, callback?: msRest.ServiceCallback<Models.CommunicationServiceResourceList>): Promise<Models.CommunicationServiceListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.CommunicationServiceListByResourceGroupNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const checkNameAvailabilityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/providers/Microsoft.Communication/checkNameAvailability", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: [ "options", "nameAvailabilityParameters" ], mapper: Mappers.NameAvailabilityParameters }, responses: { 200: { bodyMapper: Mappers.NameAvailability }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const linkNotificationHubOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/communicationServices/{communicationServiceName}/linkNotificationHub", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.communicationServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: [ "options", "linkNotificationHubParameters" ], mapper: Mappers.LinkNotificationHubParameters }, responses: { 200: { bodyMapper: Mappers.LinkedNotificationHub }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.Communication/communicationServices", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CommunicationServiceResourceList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/communicationServices", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CommunicationServiceResourceList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/communicationServices/{communicationServiceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.communicationServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: [ "options", "parameters" ], mapper: Mappers.CommunicationServiceResource }, responses: { 200: { bodyMapper: Mappers.CommunicationServiceResource }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/communicationServices/{communicationServiceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.communicationServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CommunicationServiceResource }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listKeysOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/communicationServices/{communicationServiceName}/listKeys", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.communicationServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CommunicationServiceKeys }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const regenerateKeyOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/communicationServices/{communicationServiceName}/regenerateKey", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.communicationServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.RegenerateKeyParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.CommunicationServiceKeys }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/communicationServices/{communicationServiceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.communicationServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: [ "options", "parameters" ], mapper: Mappers.CommunicationServiceResource }, responses: { 200: { bodyMapper: Mappers.CommunicationServiceResource, headersMapper: Mappers.CommunicationServiceCreateOrUpdateHeaders }, 201: { bodyMapper: Mappers.CommunicationServiceResource, headersMapper: Mappers.CommunicationServiceCreateOrUpdateHeaders }, default: { bodyMapper: Mappers.ErrorResponse, headersMapper: Mappers.CommunicationServiceCreateOrUpdateHeaders } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/communicationServices/{communicationServiceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.communicationServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { headersMapper: Mappers.CommunicationServiceDeleteHeaders }, 202: { headersMapper: Mappers.CommunicationServiceDeleteHeaders }, 204: { headersMapper: Mappers.CommunicationServiceDeleteHeaders }, default: { bodyMapper: Mappers.ErrorResponse, headersMapper: Mappers.CommunicationServiceDeleteHeaders } }, serializer }; const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CommunicationServiceResourceList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CommunicationServiceResourceList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import Property from './property'; import { addPrivateProp, addPublicProp } from './utils'; import { idToReference, escapeStringValue } from './reference-utils'; import { UdtParseError } from './errors'; import DeferredReference from './deferred-reference'; const idRegex = /^\w[-_\w\d]*$/; /** * A callback function that checks if a value is of a valid * instance of certain type. * * @param val The value to be checked. * @return True if the value is valid, false otherwise. */ export type CheckerFn<V> = (val: any) => val is V; /** * Type alias for the token's internal properties object. */ type InternalTokenProps<V, T> = { [propName: string]: Property<V, T> }; /** * Checks if the input is a valid token ID. * * @param id The id to check. */ function isValidId(id: any): id is string { return (typeof id === 'string') && idRegex.test(id); } /** * Checks if the input is a string that value and therefore a valid name. * * @param name The name to check. */ function isValidName(name: any): name is string { return (typeof name === 'string') && (name.length > 0); } /** * Checks if the input is a valid description value. * * Any string value is allowed. Additionally, undefined is a valid value * (setting a token's description to undefined clears that token's * description). * * @param description The description to check. */ function isValidDescription(description: any): description is string | undefined { return description === undefined || typeof description === 'string'; } /** * The name of the Token class's `name` property. */ const namePropName = 'name'; /** * The name of the Token class's `id` property. */ const idPropName = 'id'; /** * The name of the Token class's "description" property. * * May be used with tokens' `isReferencedValue()` and * `getReferencedToken()` methods. */ export const descriptionPropName = 'description'; /** * Base class for all Token types. * * This class implements the properties that are common to all * token types (`id`, `name` & `description`). * * It also implements the logic for managing properties that can * reference other token's values. Token types extending this class * must use `__setupTokenProp()` to add their own properties. * * Finally, a `toJSON()` implementation is provided that will serialize * any derived token type to a JSON object that can be added to a * UDT file. */ export default class Token { private _id = ''; private _name?: string; private _props: InternalTokenProps<any, Token>; /** * The token's ID. * * Token IDs must be unique within a UDT file. * * When (re-)setting a token's ID, checks will be performed * to ensure that it is a valid token ID. In the event that * it is not, a `TypeError` will be thrown. */ public id: string; /** * The optional display name for this token. * * For convenience, if no `name` value was assigned, but you read * this property then the token's current `id` value will be returned. * * When (re-)setting a token's name, checks will be performed to * ensure that it is a string value. In the event that it is not, * a `TypeError` will be thrown. */ public name?: string; /** * The optional description text for this token. * * This token's description may also reference another token's * description. To create such a reference, simply assign the other * token object to this `description` property. * * E.g.: `thisToken.description = otherToken;` * * Note that _reading_ this property will always return the actual * description _value_. In the above example, the referenced token's * description will be returned. * * An existing description can be cleared by setting the value * of this property to `undefined`. * * When (re-)setting a token's description, checks will be performed * to ensure that it is a string value, another `Token` instance or * `undefined`. In the event that it is neither, a `TypeError` will * be thrown. */ public description?: string | Token | DeferredReference<Token>; /** * Constructs a token object from a JSON object. * * The data passed in must be an object with at least an * `id` property whose value is a valid token ID string. It * may also contain `name` and `description` properties, with * valid token name and description string values, respectively. * * If the data is not an object or contains any other properties * a `UdtParseError` will be thrown. * * @param jsonObj An object with the `id` and optionally, * `name` and/or `description` of this * token. */ constructor(jsonObj?: any) { if (typeof jsonObj !== 'object' || Array.isArray(jsonObj)) { throw new UdtParseError('Cannot parse token from non-object.'); } const { id, name, description, ...rest } = jsonObj; if (Object.keys(rest).length > 0) { throw new UdtParseError(`Unexpected properties in input data: ${Object.keys(rest).join(', ')}`); } // Enumerable "id" prop with get & set // function to validate names. addPrivateProp(this, '_id'); addPublicProp( this, idPropName, () => this._id, (newId) => { if (!isValidId(newId)) { throw new TypeError(`"${newId}" is not a valid Token ID.`); } this._id = newId; }, ); this.id = id; // Enumerable "name" prop for setting custom display name, // but returns the id as a fallback in case no name was set. addPrivateProp(this, '_name'); addPublicProp( this, namePropName, () => { if (this._name !== undefined) { return this._name; } return this.id; }, (newName) => { if (newName !== undefined && !isValidName(newName)) { throw new TypeError(`"${newName}" is not a valid Token name.`); } this._name = newName; }, ); this.name = name; // Internal object that holds all token properties. addPrivateProp(this, '_props'); this._props = {}; // Standard "description" property that is common to all Token // types. this._setupTokenProp(descriptionPropName, isValidDescription, Token.isToken); this.description = description; } /** * Checks if the input is an instance of the * `Token` class, or one of its sub-classes. * * @param token The token to check. */ static isToken(token: any): token is Token { return token instanceof Token; } /** * Adds or configures a property of this token that can hold either a * value or a reference to another token's value. * * @param propName The name of the property to add. * @param valueCheckerFn A function that checks if a value is permitted * for this property. * @param refCheckFn A function that checks if a token instance is * permitted as a reference value for this property. */ protected _setupTokenProp<V, T extends Token>( propName: string, valueCheckerFn: CheckerFn<V>, refCheckFn: CheckerFn<T> ) { // Create property object and add to internal list this._props[propName] = new Property<any, Token>( (referencedToken: Token) => { return referencedToken._props[propName]; } ); // Now add public property with intelligent getter and // setter addPublicProp( this, propName, (): V => this._props[propName].getValue() as V, (value: V | T | DeferredReference<T>) => { const prop = this._props[propName]; if (value instanceof DeferredReference) { value.prop = prop; } else { if (refCheckFn(value)) { // Reference to another token prop.setReference(value); } else if (valueCheckerFn(value)) { prop.setValue(value); } else { throw new TypeError(`"${value}" is not a valid value or token reference for property ${propName}.`); } } }, ); } /** * Checks if the value of a certain token property is actually * a reference to another token's value. * * @param propName The name of the token property to check. */ isReferencedValue(propName: string) { const prop = this._props[propName]; return prop !== undefined && prop.isReference(); } /** * Retrieves the token being referenced by a certain token property. * * @param propName The name of the token property, whose referenced * token should be retrieved. */ getReferencedToken(propName: string) { if (!Object.keys(this._props).includes(propName)) { throw new RangeError(`"${propName}" is not a known referencable property of this token type.`); } const prop = this._props[propName]; return prop.getReference(); } /** * Returns the "@..." reference for this token. */ toReference() { return idToReference(this.id); } /** * Returns a JSON object representation of this token. * * As long as sub-classes correctly use `_setupTokenProp()` when * adding their own properties, this method will work for them too. * Specialised token types should therefore not need to implement * their own `toJSON()` methods. */ toJSON() { const output: any = {}; Object.keys(this).forEach((propName) => { // Must check for .id or .name first, since neither is stored // in this._props and therefore calling isReferencedValue() with // those prop names would throw an error if (propName === idPropName) { output[propName] = this[propName]; return; } if (propName === namePropName) { // Only inlude name in output if one was // actually set if (this._name !== undefined) { output[propName] = this[propName]; } return; } // One of the other props that we internally store in // this._props const referencedToken = this.getReferencedToken(propName); if (referencedToken !== undefined) { // This prop's value is a token reference output[propName] = referencedToken.toReference(); } else { // This prop has a normal value let value = (this as any)[propName]; if (value !== undefined) { if (typeof value === 'string') { value = escapeStringValue(value); } output[propName] = value; } } }); return output; } }
the_stack
import * as fs from 'fs-extra'; import * as _ from 'lodash'; import * as os from 'os'; import * as path from 'path'; import * as vscode from 'vscode-languageserver-types'; import astService, { LanguageId } from '../../src/services/astService'; import codeModService from '../../src/services/codeModService'; import { IPosition, Position } from '../../src/utils/Position'; function toZeroBasedPosition(pos: IPosition) { return vscode.Position.create(pos.line - 1, pos.column - 1); } function toOffsetFromStart(input: string, posOneBased: IPosition): number { const pos = toZeroBasedPosition(posOneBased); let offset = 0; const lines = input.split('\n'); const prevLines = lines.slice(0, pos.line); offset += prevLines.map((l) => l.length + os.EOL.length).reduce((s, a) => s + a, 0); offset += pos.character; return offset; } function getSelection(options: { input: string; anchor?: IPosition; active: IPosition }) { return { anchor: toOffsetFromStart(options.input, options.anchor || options.active), active: toOffsetFromStart(options.input, options.active), }; } function normalizeLineEndings(text: string) { return text.split('\r').join(''); } async function runInlineTransformTest( languageId: LanguageId, modId: string, input: string, output: { source: string; selection?: { anchor?: IPosition; active: IPosition; }; }, options: { fileName?: string; anchor?: IPosition; active: IPosition; } ) { input = normalizeLineEndings(input); const expectedOutput = normalizeLineEndings(output.source); const runOptions = { languageId, fileName: (options && options.fileName) || '/Users/billy/projects/example/codemods/example.ts', source: input, selection: getSelection({ input, anchor: options.anchor, active: options.active, }), include: [modId], }; const canRun = (await codeModService.getAllExecutableCodeMods(runOptions)).length === 1; if (!canRun) { throw new Error('The transform cannot be run at this position.'); } let result = codeModService.executeTransform(modId, runOptions); const actualOutput = normalizeLineEndings(result.source); // Wrong result in execute() expect(actualOutput).toBe(expectedOutput); if (output.selection) { // execute() must return new selection expect(result.selection).toBeTruthy(); const actualActivePos = Position.fromZeroBased( astService.positionAt(result.source, result.selection!.active) ); const actualAnchorPos = Position.fromZeroBased( astService.positionAt(result.source, result.selection!.anchor) ); const expectedActivePos = new Position( output.selection.active.line, output.selection.active.column ); const expectedAnchorPos = output.selection.anchor || expectedActivePos; // Wrong output selection expect(actualActivePos).toEqual(expectedActivePos); expect(actualAnchorPos).toEqual(expectedAnchorPos); } } async function runInlineCanRunTest( languageId: LanguageId, modId: string, input: string, expected: boolean, options: { fileName?: string; anchor?: IPosition; active: IPosition } ) { const runOptions = { languageId, fileName: (options && options.fileName) || '/Users/example/example.ts', source: input, selection: getSelection({ input, anchor: options.anchor, active: options.active, }), include: [modId], }; const actualCanRun = (await codeModService.getAllExecutableCodeMods(runOptions)).length === 1; // canRun test fail expect(actualCanRun).toBe(expected); } function getLanguageIdByFileName(fileName: string): LanguageId { const extensionMap: Array<{ extensions: string; parser: LanguageId; }> = [ { extensions: '.js,.es,.es6', parser: 'javascript', }, { extensions: '.jsx', parser: 'javascriptreact', }, { extensions: '.ts', parser: 'typescript', }, { extensions: '.tsx', parser: 'typescriptreact', }, ]; const fileExt = path.extname(fileName); const def = extensionMap.find((x) => x.extensions.split(',').indexOf(fileExt) !== -1); if (!def) { throw new Error(`Failed to match file extension of file '${fileName}' to languageId.`); } return def.parser; } /* Extracts position from a json comment, example: /* { pos: 1 [,nextLine: true] } *\/ /* { activePos: 1 [,nextLine: true] } *\/ /* { anchorPos: 1 [,nextLine: true] } *\/ */ function extractPosition( modId: string, source: string ): { source: string; pos: { anchor: IPosition; active: IPosition } } | null { function extractPosInternal(posKey: string) { const re = /\/\*#\s*([^#]+?)\s*#\*\//g; let match: RegExpExecArray | null; // tslint:disable-next-line:no-conditional-assignment while ((match = re.exec(source)) !== null) { if (!match[0]) { continue; } // tslint:disable-next-line:no-eval const posDef = eval('(' + match[1] + ')'); if (posDef[posKey]) { let pos1 = posDef[posKey]; if (!Number.isFinite(pos1)) { throw new Error(`Invalid 'pos' definition in positional comment:\n"${source}"`); } const column: number = pos1; let line: number = source.split('\n').findIndex((l) => l.includes(match![0])) + 1; if (posDef.nextLine) { line++; } return { line, column, }; } } return null; } let anchorPos = extractPosInternal('anchorPos'); let activePos = extractPosInternal('activePos'); const pos = extractPosInternal('pos'); if (!(anchorPos && activePos)) { if (!pos) { return null; } else { activePos = pos; anchorPos = { line: pos.line, column: pos.column, }; } } const reClean = /\s*\/\*#\s*([^#]+?)\s*#\*\//g; let cleanSource = source.replace(reClean, ''); while (cleanSource.startsWith('\n')) { cleanSource = cleanSource.substring(1); anchorPos.line--; activePos.line--; } return { source: cleanSource, pos: { anchor: anchorPos, active: activePos, }, }; } function extractFixtures( modId: string, input: string, fallbackFixtureName: string | null = null, hasPosition: boolean = true ) { const re = /\/\*\$\s*([^\$]+?)\s*\$\*\//g; // /*$ VALUE $*/ let match; interface FixtureRawDef { raw: any; name: string; skip?: boolean; validateOutPos?: boolean; inputStart: number; inputEnd: number; } const fixtures: FixtureRawDef[] = []; let activeFixture: FixtureRawDef | undefined; // tslint:disable-next-line:no-conditional-assignment while ((match = re.exec(input)) !== null) { let fixtureDef; try { // tslint:disable-next-line:no-eval fixtureDef = eval('(' + match[1] + ')'); } catch (e) { throw new Error(`[${modId}] Failed to parse inline fixture definition.`); } if (activeFixture) { activeFixture.inputEnd = re.lastIndex - match[0].length; fixtures.push(activeFixture); } activeFixture = { raw: fixtureDef, name: fixtureDef.fixture as string, skip: fixtureDef.skip, validateOutPos: fixtureDef.validateOutPos, inputStart: re.lastIndex, inputEnd: input.length, }; } if (activeFixture) { fixtures.push(activeFixture); } const fullFixtures: Array<{ raw: any; name: string | null; validateOutPos: boolean; skip: boolean; source: string; pos: { anchor: IPosition; active: IPosition; }; }> = fixtures.map((fx) => { const inputFragment = input.substring(fx.inputStart, fx.inputEnd); let source = inputFragment.trim(); let posInfo = extractPosition(modId, source); if (posInfo) { source = posInfo.source; } if (!posInfo && (hasPosition || fx.validateOutPos)) { throw new Error( `[${modId}][${ fx.name || '' }] Position is not provided, use '/*# { position: columnNumber[, nextLine: true] } #*/'` ); } return { raw: fx.raw, name: fx.name, validateOutPos: Boolean(fx.validateOutPos), skip: fx.skip || false, source, pos: posInfo ? posInfo.pos : { anchor: new Position(1, 1), active: new Position(1, 1), }, }; }); if (fullFixtures.length === 0) { let source = input.trim(); let posInfo = extractPosition(modId, source); if (posInfo) { source = posInfo.source; } if (!posInfo && hasPosition) { throw new Error( `[${modId}][${fallbackFixtureName}] Position is not provided, use '/*# { position: columnNumber[, nextLine: true] } #*/'` ); } fullFixtures.push({ raw: {}, name: fallbackFixtureName, validateOutPos: false, skip: false, source, pos: posInfo ? posInfo.pos : { anchor: new Position(1, 1), active: new Position(1, 1), }, }); } return fullFixtures; } function posToString(pos: { anchor: IPosition; active: IPosition }) { if (pos.active.column === pos.anchor.column && pos.active.line === pos.anchor.line) { return `pos ${pos.active.line}:${pos.active.column}`; } else { return `pos ${pos.anchor.line}:${pos.anchor.column}->${pos.active.line}:${pos.active.column}`; } } function defineTransformTests( dirName: string, modId: string, fixtureId: string | null = null, options: { fileName?: string; pos?: IPosition; startPos?: IPosition; endPos?: IPosition } = {} ) { const fixDir = path.join(dirName, '__codemod-fixtures__'); const fixtureSuffix = fixtureId ? `.${fixtureId}` : ''; const files = fs.readdirSync(fixDir); const inputFile = files.find((file) => file.startsWith(`${modId}${fixtureSuffix}.input.`)); const outputFile = files.find((file) => file.startsWith(`${modId}${fixtureSuffix}.output.`)); if (!inputFile || !outputFile) { throw new Error( `Failed to find input or output fixture. modId: '${modId}', fixtureId: ${fixtureId}.` ); } const input = fs.readFileSync(path.join(fixDir, inputFile), 'utf8'); const output = fs.readFileSync(path.join(fixDir, outputFile), 'utf8'); const inputFixtures = extractFixtures(modId, input, fixtureId, true); const outputFixtures = extractFixtures(modId, output, fixtureId, false); describe(`${modId} transform`, () => { inputFixtures.forEach((fx) => { const testName = fx.name ? `"${modId}:${fx.name}" transforms correctly (${posToString(fx.pos)})` : `"${modId}" transforms correctly (${posToString(fx.pos)})`; const outputFx = outputFixtures.find((x) => x.name === fx.name); if (!outputFx) { throw new Error(`Failed to find output data for fixture ${fx.name}, mod ${modId}.`); } const fn = fx.skip ? it.skip : it; fn(testName, async () => { await runInlineTransformTest( getLanguageIdByFileName(inputFile), modId, fx.source, { source: outputFx.source, selection: outputFx.validateOutPos ? { active: outputFx.pos.active, anchor: outputFx.pos.anchor, } : undefined, }, { fileName: options.fileName, active: fx.pos.active, anchor: fx.pos.anchor, } ); }); }); }); } function defineCanRunTests( dirName: string, modId: string, fixtureId: string | null = null, options: { fileName?: string; pos?: IPosition; startPos?: IPosition; endPos?: IPosition } = {} ) { const fixDir = path.join(dirName, '__codemod-fixtures__'); const fixtureSuffix = fixtureId ? `.${fixtureId}` : ''; const files = fs.readdirSync(fixDir); const inputFile = files.find((file) => file.startsWith(`${modId}${fixtureSuffix}.check.`)); if (!inputFile) { throw new Error( `Failed to find the input fixture for canRun() test. modId: '${modId}', fixtureId: ${fixtureId}.` ); } const input = fs.readFileSync(path.join(fixDir, inputFile), 'utf8'); const inputFixtures = extractFixtures(modId, input, fixtureId, true); describe(`${modId} can run`, () => { inputFixtures.forEach((fx) => { if (typeof fx.raw.expected !== 'boolean') { throw new Error( `Invalid type of 'expected' property in fixture ${fx.name}, mod ${modId}.` ); } const expected: boolean = fx.raw.expected; const testName = fx.name ? `"${modId}:${fx.name}" ${expected ? 'can' : 'cannot'} run (${posToString( fx.pos )})` : `"${modId}" ${expected ? 'can' : 'cannot'} run (${posToString(fx.pos)})`; const fn = fx.skip ? it.skip : it; fn(testName, async () => { await runInlineCanRunTest( getLanguageIdByFileName(inputFile), modId, fx.source, expected, { fileName: options.fileName, active: fx.pos.active, anchor: fx.pos.anchor, } ); }); }); }); } export function defineCodeModTests(dirName: string) { const fixDir = path.join(dirName, '__codemod-fixtures__'); const files = fs.readdirSync(fixDir); const modIds = _.uniq(files.map((f) => f.substring(0, f.indexOf('.')))); modIds.forEach((modId) => { defineCanRunTests(dirName, modId); defineTransformTests(dirName, modId); }); }
the_stack
import "jest-extended"; import { Container, Utils } from "@packages/core-kernel"; import { PoolError } from "@packages/core-kernel/dist/contracts/transaction-pool"; import { Enums } from "@packages/core-magistrate-crypto"; import { EntityBuilder } from "@packages/core-magistrate-crypto/src/builders"; import { EntityAction, EntityType } from "@packages/core-magistrate-crypto/src/enums"; import { EntityTransaction } from "@packages/core-magistrate-crypto/src/transactions"; import { EntityAlreadyRegisteredError, EntityAlreadyResignedError, EntityNameAlreadyRegisteredError, EntityNameDoesNotMatchDelegateError, EntityNotRegisteredError, EntitySenderIsNotDelegateError, EntityWrongSubTypeError, EntityWrongTypeError, StaticFeeMismatchError, } from "@packages/core-magistrate-transactions/src/errors"; import { EntityTransactionHandler } from "@packages/core-magistrate-transactions/src/handlers/entity"; import { Utils as CryptoUtils } from "@packages/crypto"; import { Managers, Transactions } from "@packages/crypto"; import { cloneDeep } from "lodash"; import { validRegisters, validResigns, validUpdates } from "./__fixtures__/entity"; import { walletRepository } from "./__mocks__/wallet-repository"; // mocking the abstract TransactionHandler class // because I could not make it work using the real abstract class + custom ioc binding jest.mock("@arkecosystem/core-transactions", () => ({ Handlers: { TransactionHandler: require("./__mocks__/transaction-handler").TransactionHandler, }, Errors: { TransactionError: require("./__mocks__/transaction-error").TransactionError, }, })); describe("Entity handler", () => { Managers.configManager.setFromPreset("testnet"); Managers.configManager.setHeight(2); Transactions.TransactionRegistry.registerTransactionType(EntityTransaction); let entityHandler: EntityTransactionHandler; const container = new Container.Container(); const transactionHistoryService = { findOneByCriteria: jest.fn(), findManyByCriteria: jest.fn(), streamByCriteria: jest.fn(), }; const poolQuery = { getAll: jest.fn(), whereKind: jest.fn(), wherePredicate: jest.fn(), has: jest.fn().mockReturnValue(false), }; poolQuery.getAll.mockReturnValue(poolQuery); poolQuery.whereKind.mockReturnValue(poolQuery); poolQuery.wherePredicate.mockReturnValue(poolQuery); beforeAll(() => { container.unbindAll(); container.bind(Container.Identifiers.TransactionHistoryService).toConstantValue(transactionHistoryService); container.bind(Container.Identifiers.TransactionPoolQuery).toConstantValue(poolQuery); }); let wallet, walletAttributes; beforeEach(() => { walletAttributes = {}; wallet = { getAttribute: jest.fn().mockImplementation((attribute, defaultValue) => { const splitAttribute = attribute.split("."); return splitAttribute.length === 1 ? walletAttributes[splitAttribute[0]] || defaultValue : (walletAttributes[splitAttribute[0]] || {})[splitAttribute[1]] || defaultValue; }), hasAttribute: jest.fn().mockImplementation((attribute) => { const splitAttribute = attribute.split("."); return splitAttribute.length === 1 ? !!walletAttributes[splitAttribute[0]] : !!walletAttributes[splitAttribute[0]] && !!walletAttributes[splitAttribute[0]][splitAttribute[1]]; }), setAttribute: jest.fn().mockImplementation((attribute, value) => (walletAttributes[attribute] = value)), forgetAttribute: jest.fn().mockImplementation((attribute) => delete walletAttributes[attribute]), }; jest.spyOn(walletRepository, "findByPublicKey").mockReturnValue(wallet); entityHandler = container.resolve(EntityTransactionHandler); }); afterEach(() => { jest.clearAllMocks(); }); const registerFee = "5000000000"; const updateAndResignFee = "500000000"; describe("dependencies", () => { it("should return empty array", async () => { entityHandler = container.resolve(EntityTransactionHandler); const result = entityHandler.dependencies(); expect(result).toBeArray(); expect(result.length).toBe(0); }); }); describe("isActivated", () => { afterAll(() => { Managers.configManager.setHeight(2); }); it("should return false if AIP36 is not enabled", async () => { entityHandler = container.resolve(EntityTransactionHandler); const result = await entityHandler.isActivated(); expect(result).toBeFalse(); }); it("should return true if AIP36 is enabled", async () => { Managers.configManager.setHeight(61); entityHandler = container.resolve(EntityTransactionHandler); const result = await entityHandler.isActivated(); expect(result).toBeTrue(); }); }); describe("dynamicFee", () => { const registerTx = new EntityBuilder().asset(validRegisters[0]).sign("passphrase").build(); const updateTx = new EntityBuilder().asset(validUpdates[0]).sign("passphrase").build(); const resignTx = new EntityBuilder().asset(validResigns[0]).sign("passphrase").build(); it.each([ [registerTx, registerFee], [updateTx, updateAndResignFee], [resignTx, updateAndResignFee], ])("should return correct static fee", async (tx, fee) => { entityHandler = container.resolve(EntityTransactionHandler); // @ts-ignore const result = await entityHandler.dynamicFee({ transaction: tx }); expect(result.toString()).toEqual(Utils.BigNumber.make(fee).toString()); }); }); describe("walletAttributes", () => { it("should return entities attribute", async () => { entityHandler = container.resolve(EntityTransactionHandler); const result = await entityHandler.walletAttributes(); expect(result).toEqual(["entities"]); }); }); describe("bootstrap", () => { let transaction; let entityHandler; beforeEach(() => { const builder = new EntityBuilder(); transaction = builder.asset(validRegisters[0]).sign("passphrase").build(); entityHandler = container.resolve(EntityTransactionHandler); transactionHistoryService.streamByCriteria .mockImplementationOnce(async function* () { yield transaction.data; }) .mockImplementation(async function* () {}); }); it("should resolve", async () => { const setOnIndex = jest.spyOn(walletRepository, "setOnIndex"); await expect(entityHandler.bootstrap()).toResolve(); expect(setOnIndex).toHaveBeenCalledTimes(2); // EntityNamesTypes & Entities }); }); describe("throwIfCannotEnterPool", () => { let transaction: EntityTransaction; let entityHandler: EntityTransactionHandler; beforeEach(() => { const builder = new EntityBuilder(); transaction = builder.asset(validRegisters[0]).sign("passphrase").build() as EntityTransaction; entityHandler = container.resolve(EntityTransactionHandler); }); it("should resolve", async () => { await expect(entityHandler.throwIfCannotEnterPool(transaction)).toResolve(); expect(poolQuery.getAll).toHaveBeenCalled(); }); it("should resolve if transaction action is update or resign", async () => { transaction.data.asset!.action = Enums.EntityAction.Update; await expect(entityHandler.throwIfCannotEnterPool(transaction)).toResolve(); expect(poolQuery.getAll).not.toHaveBeenCalled(); transaction.data.asset!.action = Enums.EntityAction.Resign; await expect(entityHandler.throwIfCannotEnterPool(transaction)).toResolve(); expect(poolQuery.getAll).not.toHaveBeenCalled(); }); it("should throw if transaction with same type and name is already in the pool", async () => { poolQuery.has.mockReturnValue(true); await expect(entityHandler.throwIfCannotEnterPool(transaction)).rejects.toBeInstanceOf(PoolError); expect(poolQuery.wherePredicate).toHaveBeenCalledTimes(2); const transactionClone = cloneDeep(transaction); const wherePredicateCallback1 = poolQuery.wherePredicate.mock.calls[0][0]; const wherePredicateCallback2 = poolQuery.wherePredicate.mock.calls[1][0]; expect(wherePredicateCallback1(transactionClone)).toBeTrue(); expect(wherePredicateCallback2(transactionClone)).toBeTrue(); delete transactionClone.data.asset; expect(wherePredicateCallback1(transactionClone)).toBeFalse(); expect(wherePredicateCallback2(transactionClone)).toBeFalse(); }); }); describe("throwIfCannotBeApplied", () => { let transaction: EntityTransaction; let entityHandler: EntityTransactionHandler; beforeEach(() => { const builder = new EntityBuilder(); transaction = builder.asset(validRegisters[0]).sign("passphrase").build() as EntityTransaction; entityHandler = container.resolve(EntityTransactionHandler); }); it("should resolve", async () => { await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).toResolve(); }); it("should resolve if exception", async () => { const spyOnIsException = jest.spyOn(CryptoUtils, "isException"); spyOnIsException.mockReturnValue(true); transaction.data.fee = Utils.BigNumber.make("4000"); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).toResolve(); spyOnIsException.mockReset(); }); it("should throw on static fee mismatch", async () => { transaction.data.fee = Utils.BigNumber.make("4000"); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( StaticFeeMismatchError, ); }); }); describe("emitEvents", () => { it("should not dispatch", async () => { const builder = new EntityBuilder(); const transaction = builder.asset(validRegisters[0]).sign("passphrase").build(); const emitter = { dispatch: jest.fn(), }; entityHandler = container.resolve(EntityTransactionHandler); // @ts-ignore entityHandler.emitEvents(transaction, emitter); // Emitting is currently disabled on EntityTransactions expect(emitter.dispatch).toHaveBeenCalledTimes(0); }); }); describe("applyToRecipient", () => { it("should resolve", async () => { const builder = new EntityBuilder(); const transaction = builder.asset(validRegisters[0]).sign("passphrase").build(); entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.applyToRecipient(transaction)).toResolve(); }); }); describe("revertForRecipient", () => { it("should resolve", async () => { const builder = new EntityBuilder(); const transaction = builder.asset(validRegisters[0]).sign("passphrase").build(); entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.revertForRecipient(transaction)).toResolve(); }); }); describe("register", () => { describe("applyToSender", () => { it.each([validRegisters])("should set the wallet attribute", async (asset) => { const setOnIndex = jest.spyOn(walletRepository, "setOnIndex"); const builder = new EntityBuilder(); const transaction = builder.asset(asset).sign("passphrase").build(); entityHandler = container.resolve(EntityTransactionHandler); await entityHandler.applyToSender(transaction); expect(wallet.setAttribute).toBeCalledWith("entities", { [transaction.id]: { type: asset.type, subType: asset.subType, data: asset.data, }, }); expect(walletAttributes).toEqual({ entities: { [transaction.id]: { type: asset.type, subType: asset.subType, data: asset.data, }, }, }); expect(setOnIndex).toHaveBeenCalledTimes(2); // EntityNamesTypes & Entities }); }); describe("revertForSender", () => { it.each([validRegisters])("should delete the wallet attribute", async (asset) => { const forgetOnIndex = jest.spyOn(walletRepository, "forgetOnIndex"); const builder = new EntityBuilder(); const transaction = builder.asset(asset).sign("passphrase").build(); // like the transaction was applied walletAttributes = { entities: { [transaction.id]: { ...asset.data } } }; entityHandler = container.resolve(EntityTransactionHandler); await entityHandler.revertForSender(transaction); expect(wallet.setAttribute).toBeCalledWith("entities", {}); expect(walletAttributes).toEqual({ entities: {} }); expect(forgetOnIndex).toHaveBeenCalledTimes(2); // EntityNamesTypes & Entities }); }); describe("throwIfCannotBeApplied", () => { it.each([validRegisters])("should throw when entity is already registered", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).sign("passphrase").build(); // entity already registered walletAttributes = { entities: { [transaction.id]: { type: asset.type, subType: asset.subType, data: asset.data, }, }, }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityAlreadyRegisteredError, ); }); it.each([validRegisters])("should not throw when entity is not registered", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).sign("passphrase").build(); entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).toResolve(); }); it("should throw when fee does not match register fee", async () => { const builder = new EntityBuilder(); const transaction = builder .asset({ type: Enums.EntityType.Business, subType: 4, action: Enums.EntityAction.Register, data: { name: "thename", ipfsData: "Qmbw6QmF6tuZpyV6WyEsTmExkEG3rW4khattQidPfbpmNZ" }, }) .fee("500000000") .sign("passphrase") .build(); entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( StaticFeeMismatchError, ); }); it.each([validRegisters])( "should throw when entity name is already registered for same type", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).sign("passphrase").build(); jest.spyOn(walletRepository, "hasByIndex").mockReturnValueOnce(true); entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityNameAlreadyRegisteredError, ); }, ); it.each([validRegisters])( "should not throw when entity name is registered for a different type", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).sign("passphrase").build(); entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).toResolve(); }, ); describe("Entity delegate", () => { const entityId = "533384534cd561fc17f72be0bb57bf39961954ba0741f53c08e3f463ef19118c"; const type = EntityType.Delegate; const subType = 0; const createEntityDelegateTx = (name, action = EntityAction.Register) => { const asset: any = { type, subType, action, data: { name } }; if (action !== EntityAction.Register) { asset.registrationId = entityId; asset.data = {}; } if (action === EntityAction.Update) { asset.data = { ipfsData: "Qmbw6QmF6tuZpyV6WyEsTmExkEG3rW4khbttQidPfbpmNZ" }; } return new EntityBuilder() .asset(asset) .fee(action === EntityAction.Register ? registerFee : updateAndResignFee) .sign("passphrase") .build(); }; it("should throw when the sender wallet is not a delegate", async () => { const transaction = createEntityDelegateTx("anyname"); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntitySenderIsNotDelegateError, ); }); it("should throw when the sender delegate name does not match the entity name", async () => { const username = "thedelegate"; const transaction = createEntityDelegateTx(username); walletAttributes.delegate = { username: username + "s" }; await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityNameDoesNotMatchDelegateError, ); }); it("should not throw on update or resign even when delegate does not match", async () => { // it should not throw because update or resign tx needs first a register tx // for which the delegate checks must have already be done const delegateName = "thedelegate"; const transactionResign = createEntityDelegateTx(delegateName, EntityAction.Resign); const transactionUpdate = createEntityDelegateTx(delegateName, EntityAction.Update); walletAttributes.entities = { [entityId]: { name: "somename", type, subType, data: {} }, }; await expect(entityHandler.throwIfCannotBeApplied(transactionResign, wallet)).toResolve(); await expect(entityHandler.throwIfCannotBeApplied(transactionUpdate, wallet)).toResolve(); }); it("should not throw otherwise", async () => { const username = "therealdelegate"; const transaction = createEntityDelegateTx(username); walletAttributes.delegate = { username }; await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).toResolve(); }); }); }); }); describe("resign", () => { describe("applyToSender", () => { it.each([validResigns])("should set the wallet entity attribute to resigned", async (asset) => { const setOnIndex = jest.spyOn(walletRepository, "setOnIndex"); const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); const entityNotResigned = { type: asset.type, subType: asset.subType, data: { name: "random name", description: "the current entity" }, }; walletAttributes = { entities: { [asset.registrationId]: entityNotResigned } }; entityHandler = container.resolve(EntityTransactionHandler); await entityHandler.applyToSender(transaction); expect(wallet.setAttribute).toBeCalledWith("entities", { [asset.registrationId]: { ...entityNotResigned, resigned: true }, }); expect(walletAttributes).toEqual({ entities: { [asset.registrationId]: { ...entityNotResigned, resigned: true } }, }); expect(setOnIndex).not.toHaveBeenCalled(); }); }); describe("revertForSender", () => { it.each([validResigns])("should delete the wallet entity 'resigned' attribute", async (asset) => { const forgetOnIndex = jest.spyOn(walletRepository, "forgetOnIndex"); const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // like the transaction was applied const entityNotResigned = { type: asset.type, subType: asset.subType, data: { name: "random name", description: "the current entity" }, }; walletAttributes = { entities: { [asset.registrationId]: { ...entityNotResigned, resigned: true } } }; entityHandler = container.resolve(EntityTransactionHandler); await entityHandler.revertForSender(transaction); expect(wallet.setAttribute).toBeCalledWith("entities", { [asset.registrationId]: entityNotResigned }); expect(walletAttributes).toEqual({ entities: { [asset.registrationId]: entityNotResigned } }); expect(forgetOnIndex).not.toHaveBeenCalled(); }); }); describe("throwIfCannotBeApplied", () => { it.each([validResigns])("should throw when entity does not exist", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity does not exist walletAttributes = { entities: {} }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityNotRegisteredError, ); }); it.each([validResigns])("should throw when entity is already resigned", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity already resigned const entityResigned = { type: asset.type, subType: asset.subType, data: { name: "random name", description: "the current entity" }, resigned: true, }; walletAttributes = { entities: { [asset.registrationId]: entityResigned } }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityAlreadyResignedError, ); }); it("should throw when fee does not match resign fee", async () => { const builder = new EntityBuilder(); const transaction = builder .asset({ type: Enums.EntityType.Business, subType: 4, action: Enums.EntityAction.Resign, registrationId: "533384534cd561fc17f72be0bb57bf39961954ba0741f53c08e3f463ef19118c", data: {}, }) .fee("5000000000") .sign("passphrase") .build(); entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( StaticFeeMismatchError, ); }); it.each([validResigns])("should throw when entity type does not match", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity exists and is not resigned, but has not the same type as the resign asset const entityNotResigned = { type: (asset.type + 1) % 255, // different type but still in the range [0, 255] subType: asset.subType, data: { name: "random name", description: "the current entity" }, }; walletAttributes = { entities: { [asset.registrationId]: entityNotResigned } }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityWrongTypeError, ); }); it.each([validResigns])("should throw when entity subType does not match", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity exists and is not resigned, but has not the same subtype as the resign asset const entityNotResigned = { type: asset.type, subType: (asset.subType + 1) % 255, // different subType but still in the range [0, 255] data: { name: "random name", description: "the current entity" }, }; walletAttributes = { entities: { [asset.registrationId]: entityNotResigned } }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityWrongSubTypeError, ); }); it.each([validResigns])("should not throw otherwise", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity exists and is not resigned const entityNotResigned = { type: asset.type, subType: asset.subType, data: { name: "random name", description: "the current entity" }, }; walletAttributes = { entities: { [asset.registrationId]: entityNotResigned } }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).toResolve(); }); }); }); describe("update", () => { describe("applyToSender", () => { it.each([validUpdates])("should apply the changes to the wallet entity", async (asset) => { const setOnIndex = jest.spyOn(walletRepository, "setOnIndex"); const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); const entityBefore = { type: asset.type, subType: asset.subType, data: { name: "random name", description: "the current entity" }, }; walletAttributes = { entities: { [asset.registrationId]: entityBefore } }; const expectedEntityAfter = { ...entityBefore, data: { ...entityBefore.data, ...asset.data, }, }; entityHandler = container.resolve(EntityTransactionHandler); await entityHandler.applyToSender(transaction); expect(wallet.setAttribute).toBeCalledWith("entities", { [asset.registrationId]: expectedEntityAfter }); expect(walletAttributes).toEqual({ entities: { [asset.registrationId]: expectedEntityAfter } }); expect(setOnIndex).not.toHaveBeenCalled(); }); }); describe("revertForSender", () => { it.each([validUpdates])("should restore the wallet to its previous state", async (asset) => { const forgetOnIndex = jest.spyOn(walletRepository, "forgetOnIndex"); const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); const registrationTx = { id: "e77a1d1d080ebce113dd17e1cb0a242ec8600fb72cd62eca4e46148bee1d3acc", asset: { type: asset.type, subType: asset.subType, action: Enums.EntityAction.Register, data: { name: "random name", description: "the current entity" }, }, }; const updateTxs = [ { id: "a11a1d1d080ebce113dd17e1cb0a242ec8600fb72cd62eca4e46148bee1d3acc", asset: { type: asset.type, subType: asset.subType, action: Enums.EntityAction.Update, data: { description: "updated description", images: ["https://flickr.com/dummy"] }, }, }, { id: "b22a1d1d080ebce113dd17e1cb0a242ec8600fb72cd62eca4e46148bee1d3acc", asset: { type: asset.type, subType: asset.subType, action: Enums.EntityAction.Update, data: { description: "updated description 2", videos: ["https://youtube.com/dummy"] }, }, }, transaction, // the transaction that we are reverting ]; transactionHistoryService.findOneByCriteria = jest.fn().mockReturnValueOnce(registrationTx); transactionHistoryService.findManyByCriteria = jest.fn().mockReturnValueOnce(updateTxs); entityHandler = container.resolve(EntityTransactionHandler); await entityHandler.revertForSender(transaction); expect(wallet.setAttribute).toBeCalledWith("entities", { [asset.registrationId]: { type: asset.type, subType: asset.subType, data: { name: "random name", description: "updated description 2", images: ["https://flickr.com/dummy"], videos: ["https://youtube.com/dummy"], }, }, }); expect(forgetOnIndex).not.toHaveBeenCalled(); }); }); describe("throwIfCannotBeApplied", () => { it.each([validUpdates])("should throw when entity does not exist", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity does not exist walletAttributes = { entities: {} }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityNotRegisteredError, ); }); it.each([validUpdates])("should throw when entity is resigned", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity resigned const entityResigned = { type: asset.type, subType: asset.subType, data: { name: "random name", description: "the current entity" }, resigned: true, }; walletAttributes = { entities: { [asset.registrationId]: entityResigned } }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityAlreadyResignedError, ); }); it.each([validUpdates])("should throw when entity type does not match", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity exists and is not resigned, but has not the same type as the update asset const entityNotResigned = { type: (asset.type + 1) % 255, // different type but still in the range [0, 255] subType: asset.subType, data: { name: "random name", description: "the current entity" }, }; walletAttributes = { entities: { [asset.registrationId]: entityNotResigned } }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityWrongTypeError, ); }); it("should throw when fee does not match update fee", async () => { const builder = new EntityBuilder(); const transaction = builder .asset({ type: Enums.EntityType.Business, subType: 4, action: Enums.EntityAction.Update, registrationId: "533384534cd561fc17f72be0bb57bf39961954ba0741f53c08e3f463ef19118c", data: { ipfsData: "Qmbw6QmF6tuZpyV6WyEsTmExkEG3rW4khbttQidPfbpmNZ" }, }) .fee("5000000000") .sign("passphrase") .build(); entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( StaticFeeMismatchError, ); }); it.each([validUpdates])("should throw when entity subType does not match", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity exists and is not resigned, but has not the same subtype as the update asset const entityNotResigned = { type: asset.type, subType: (asset.subType + 1) % 255, // different subType but still in the range [0, 255] data: { name: "random name", description: "the current entity" }, }; walletAttributes = { entities: { [asset.registrationId]: entityNotResigned } }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).rejects.toBeInstanceOf( EntityWrongSubTypeError, ); }); it.each([validUpdates])("should not throw otherwise", async (asset) => { const builder = new EntityBuilder(); const transaction = builder.asset(asset).fee(updateAndResignFee).sign("passphrase").build(); // entity exists and is not resigned const entityNotResigned = { type: asset.type, subType: asset.subType, data: { name: "random name", description: "the current entity" }, }; walletAttributes = { entities: { [asset.registrationId]: entityNotResigned } }; entityHandler = container.resolve(EntityTransactionHandler); await expect(entityHandler.throwIfCannotBeApplied(transaction, wallet)).toResolve(); }); }); }); });
the_stack
/// <reference types="./cacheable-middleware" /> import * as argparse from 'argparse'; import express from 'express'; import expressWS from 'express-ws'; import * as http from 'http'; import * as url from 'url'; import * as path from 'path'; import morgan from 'morgan'; import favicon from 'serve-favicon'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import session from 'express-session'; import mysqlSession from 'express-mysql-session'; import csurf from 'csurf'; import passport from 'passport'; import connect_flash from 'connect-flash'; import cacheable from 'cacheable-middleware'; import xmlBodyParser from 'express-xml-bodyparser'; import Prometheus from 'prom-client'; import escapeHtml from 'escape-html'; import rateLimit from 'express-rate-limit'; import './types'; import * as passportUtil from './util/passport'; import * as secretKey from './util/secret_key'; import * as db from './util/db'; import * as I18n from './util/i18n'; import * as userUtils from './util/user'; import Metrics from './util/metrics'; import * as errorHandling from './util/error_handling'; import * as codeStorage from './util/code_storage'; import * as EngineManager from './almond/enginemanagerclient'; import * as Config from './config'; class Frontend { private _app : express.Application; private _sessionStore : mysqlSession.MySQLStore; server : http.Server; constructor() { // all environments this._app = express(); this.server = http.createServer(this._app); // FIXME the type definitions for express-mysql-session are not correct, the expressSession module is // imported with "import *" which is not correct const MySQLStore = mysqlSession(session as any); this._sessionStore = new MySQLStore({ expiration: 86400000 // 1 day, in ms }, db.getPool()); } async init(port : number) { expressWS(this._app, this.server); this._app.set('port', port); this._app.set('views', path.join(path.dirname(module.filename), '../views')); this._app.set('view engine', 'pug'); this._app.enable('trust proxy'); // provide a very-early version of req._ in case something // early in the request stack fails and we hit the error handler, // or if we hit a page that is not authenticated this._app.use(I18n.handler); this._app.use((req, res, next) => { // Capital C so we don't conflict with other parameters // set by various pages res.locals.Config = Config; res.locals.Constants = { Role: userUtils.Role, DeveloperStatus: userUtils.DeveloperStatus, ProfileFlags: userUtils.ProfileFlags }; res.locals.escapeHtml = escapeHtml; // the old way of doing things - eventually should be refactored res.locals.CDN_HOST = Config.CDN_HOST; res.locals.THINGPEDIA_URL = Config.THINGPEDIA_URL; res.locals.WITH_THINGPEDIA = Config.WITH_THINGPEDIA; res.locals.ENABLE_ANONYMOUS_USER = Config.ENABLE_ANONYMOUS_USER; next(); }); // work around a crash in expressWs if a WebSocket route fails with an error // code and express-session tries to save the session this._app.use((req, res, next) => { if ((req as any).ws) { const originalWriteHead = res.writeHead as any; res.writeHead = function(statusCode : number) : any { // eslint-disable-next-line prefer-rest-params originalWriteHead.apply(this, arguments); // eslint-disable-next-line prefer-rest-params return (http.ServerResponse.prototype.writeHead as any).apply(this, arguments); }; } next(); }); // set up logging first this._app.use(morgan('dev')); if (Config.ENABLE_PROMETHEUS) Metrics(this._app); const IS_ALMOND_WEBSITE = Config.SERVER_ORIGIN === 'https://almond.stanford.edu'; const SERVER_NAME = url.parse(Config.SERVER_ORIGIN).hostname; if (Config.ENABLE_REDIRECT) { this._app.use((req, res, next) => { let redirect = false; if (req.headers['x-forwarded-proto'] === 'http') redirect = true; // don't redirect if there is no hostname // (it's a health-check from the load balancer) if (req.hostname && req.hostname !== SERVER_NAME) redirect = true; if (IS_ALMOND_WEBSITE && (!req.hostname || (!req.hostname.endsWith('.stanford.edu') && req.hostname !== 'www.thingpedia.org'))) redirect = false; // don't redirect certain API endpoints because the client code // doesn't cope well if (req.originalUrl.startsWith('/thingpedia/api') || req.originalUrl.startsWith('/thingpedia/download') || req.originalUrl.startsWith('/api/webhook') || req.originalUrl.startsWith('/ws')) redirect = false; if (redirect) { if (req.hostname === 'thingpedia.stanford.edu' && req.originalUrl === '/') res.redirect(301, Config.SERVER_ORIGIN + '/thingpedia'); else res.redirect(301, Config.SERVER_ORIGIN + req.originalUrl); return; } next(); }); } if (Config.ENABLE_SECURITY_HEADERS) { // security headers this._app.use((req, res, next) => { res.set('Strict-Transport-Security', 'max-age=31536000'); //res.set('Content-Security-Policy', `default-src 'self'; connect-src 'self' https://*.stanford.edu ; font-src 'self' https://maxcdn.bootstrapcdn.com https://fonts.googleapis.com ; img-src * ; script-src 'self' https://code.jquery.com https://maxcdn.bootstrapcdn.com 'unsafe-inline' ; style-src 'self' https://fonts.googleapis.com https://maxcdn.bootstrapcdn.com 'unsafe-inline'`); res.set('Referrer-Policy', 'strict-origin-when-cross-origin'); res.set('X-Frame-Options', 'DENY'); res.set('X-Content-Type-Options', 'nosniff'); next(); }); } this._app.use('/assets', (req, res, next) => { res.set('Access-Control-Allow-Origin', '*'); next(); }); this._app.use(favicon(path.resolve(path.dirname(module.filename), '../public/images/favicon.ico'))); this._app.use('/assets', express.static(path.resolve(path.dirname(module.filename), '../public'), { maxAge: process.env.NODE_ENV === 'production' ? 86400000 : 0 })); codeStorage.initFrontend(this._app); this._app.use(cacheable()); this._app.use(passport.initialize()); passportUtil.initialize(); this._app.use(bodyParser.json()); this._app.use(bodyParser.urlencoded({ extended: true })); this._app.use(xmlBodyParser({ explicitArray: true, trim: false })); // mount the public APIs before passport.session, so cookie authentication // does not leak into them (which prevents cross-origin attacks because the APIs are CORS-enabled) // sinkholes are dummy routes used by demo devices this._app.get('/sinkhole', (req, res, next) => { res.send(''); }); this._app.post('/sinkhole', (req, res, next) => { res.send(''); }); this._app.use(rateLimit({ max: 1000, })); this._app.use('/api/webhook', (await import('./routes/webhook')).default); this._app.use('/me/api/gassistant', (await import('./routes/bridges/gassistant')).default); this._app.use('/me/api', (await import('./routes/my_api')).default); // legacy route for /me/api/sync, uses auth tokens instead of full OAuth2 this._app.use('/ws', (await import('./routes/thingengine_ws')).default); if (Config.WITH_THINGPEDIA === 'embedded') this._app.use('/thingpedia/api', (await import('./routes/thingpedia_api')).default); // now initialize cookies, session and session-based logins this._app.use(cookieParser(secretKey.getSecretKey())); this._app.use(session({ resave: false, saveUninitialized: false, store: this._sessionStore, secret: secretKey.getSecretKey() })); this._app.use(connect_flash()); this._app.use(passport.session()); // this is an authentication kludge used by the Android app // the app loads the index with ?app, which causes us to respond with // a WWW-Authenticate header, and then the app injects basic authentication // info (cloud id + auth token) in the browser // this is not great, but we must keep it until the app is updated to // use OAuth tokens instead const basicAuth = passport.authenticate('basic', { failWithError: true }); this._app.use((req, res, next) => { if (req.query.auth === 'app') { basicAuth(req, res, (err : Error) => { if (err) res.status(401); // eat the error // skip 2fa if successful if (!err && req.user) req.session.completed2fa = true; next(); }); } else { next(); } }); this._app.use((req, res, next) => { res.locals.user = req.user; res.locals.authenticated = userUtils.isAuthenticated(req); next(); }); this._app.use(I18n.handler); // initialize csurf after any route that uses file upload. // because file upload uses multer, which must be initialized before csurf // MAKE SURE ALL ROUTES HAVE CSURF if (Config.WITH_THINGPEDIA === 'embedded') { this._app.use('/thingpedia/upload', (await import('./routes/thingpedia_upload')).default); this._app.use('/thingpedia/entities', (await import('./routes/thingpedia_entities')).default); this._app.use('/thingpedia/strings', (await import('./routes/thingpedia_strings')).default); } if (Config.WITH_LUINET === 'embedded') this._app.use('/developers/mturk', (await import('./routes/developer_mturk')).default); this._app.use('/developers/oauth', (await import('./routes/developer_oauth2')).default); this._app.use('/admin/blog/upload', (await import('./routes/admin_upload')).default); this._app.use(csurf({ cookie: false })); this._app.use((req, res, next) => { res.locals.csrfToken = req.csrfToken(); next(); }); this._app.use('/', (await import('./routes/about')).default); this._app.use('/', (await import('./routes/qrcode')).default); this._app.use('/blog', (await import('./routes/blog')).default); this._app.use('/mturk', (await import('./routes/mturk')).default); this._app.use('/me/ws', (await import('./routes/my_internal_api')).default); this._app.use('/me/api/oauth2', (await import('./routes/my_oauth2')).default); this._app.use('/me/devices', (await import('./routes/devices')).default); this._app.use('/me/status', (await import('./routes/status')).default); this._app.use('/me/recording', (await import('./routes/my_recording')).default); this._app.use('/me', (await import('./routes/my_stuff')).default); this._app.use('/devices', (await import('./routes/devices_compat')).default); this._app.use('/developers', (await import('./routes/developer_console')).default); if (Config.WITH_THINGPEDIA === 'embedded') { this._app.use('/thingpedia', (await import('./routes/thingpedia_portal')).default); this._app.use('/thingpedia/commands', (await import('./routes/commandpedia')).default); this._app.use('/thingpedia/examples', (await import('./routes/thingpedia_examples')).default); this._app.use('/thingpedia/devices', (await import('./routes/thingpedia_devices')).default); this._app.use('/thingpedia/classes', (await import('./routes/thingpedia_schemas')).default); this._app.use('/thingpedia/translate', (await import('./routes/thingpedia_translate')).default); this._app.use('/thingpedia/cheatsheet', (await import('./routes/thingpedia_cheatsheet')).default); this._app.use('/thingpedia/snapshots', (await import('./routes/thingpedia_snapshots')).default); } this._app.use('/profiles', (await import('./routes/thingpedia_profiles')).default); this._app.use('/user', (await import('./routes/user')).default); this._app.use('/admin', (await import('./routes/admin')).default); this._app.use('/admin/mturk', (await import('./routes/admin_mturk')).default); this._app.use('/proxy', (await import('./routes/proxy')).default); this._app.use((req, res) => { // if we get here, we have a 404 response res.status(404).render('error', { page_title: req._("Genie - Page Not Found"), message: req._("The requested page does not exist.") }); }); this._app.use(errorHandling.html); } open() { // '::' means the same as 0.0.0.0 but for IPv6 // without it, node.js will only listen on IPv4 return new Promise<void>((resolve, reject) => { this.server.listen(this._app.get('port') as number, '::', () => { resolve(); }); }).then(() => { console.log('Express server listening on port ' + this._app.get('port')); }); } close() { // close the server asynchronously to avoid waiting on open // connections this.server.close((error) => { if (error) { console.log('Error stopping Express server: ' + error); console.log(error.stack); } else { console.log('Express server stopped'); } }); this._sessionStore.close(); return Promise.resolve(); } } export function initArgparse(subparsers : argparse.SubParser) { const parser = subparsers.add_parser('run-frontend', { description: 'Run a Web Almond frontend' }); parser.add_argument('-p', '--port', { required: false, type: Number, help: 'Listen on the given port', default: 8080 }); parser.add_argument('--k8s', { action: 'store_true', help: 'Use k8s backends', default: false, }); } export async function main(argv : any) { const frontend = new Frontend(); await frontend.init(argv.port); EngineManager.init(argv.k8s); const enginemanager = EngineManager.get(); enginemanager.start(); if (Config.ENABLE_PROMETHEUS) Prometheus.collectDefaultMetrics(); async function handleSignal() { await frontend.close(); await enginemanager.stop(); await db.tearDown(); process.exit(); } process.on('SIGINT', handleSignal); process.on('SIGTERM', handleSignal); // open the HTTP server frontend.open(); }
the_stack
import root from './root'; import setTimeTask from './internal/setTimeTask'; import clearTimeTask from './internal/clearTimeTask'; import getEleAttr from './internal/getEleAttr'; import removeElement from './internal/removeElement'; import Event from './internal/Event'; import addStyleCSS from './internal/addStyleCSS'; interface dataTime{ data:string time:number } /** * class Barrage * @returns voild */ class Barrage extends Event{ /** * [video 装载容器的css选择器] * @type {string} */ private video: string; /** * [dataTime 弹幕对象,time/s 例如:[{data:"第一条",time:2},{data:"第二条",time:5}] * @type {Array<dataTime>} */ private dataTime:Array<dataTime> /** * [tempDataTime dataTime] * @type {Array<dataTime>} */ private tempDataTime:Array<dataTime> /** * [distance 定时器,移动的距离] * @type {number} */ private distance:number; /** * [videoEnd 视频播放结束状态 true为播放结束] * @type {Boolean} */ private videoEnd:Boolean = false; /** * [scroxtVideo video元素] * @type {any} */ private scroxtVideo:any; /** * [videoWidth 容器宽度] * @type {number} */ private videoWidth:number; /** * [MAX_LINE 舞台弹幕最大行] * @type {number} */ private MAX_LINE:number; /** * [MAX_NUM 屏幕最大弹幕数量] * @type {number} */ private MAX_NUM:number; /** * [lineHeight 一行弹幕的高度] * @type {number} */ private lineHeight:number; /** * [colorFont 一行弹幕的高度] * @type {number} */ private colorFont:Array<string>; /** * [barrageWrap 弹幕的索引] * @type {Array<Element>} */ private barrageWrap: {element:Element,scroxt:number,line:number,move:number,width:number,distance:number,color:string}[] = []; /** * [readyShowBarrage 准备出场的弹幕] * @type {Array<String>} */ private readyShowBarrage:String[] = []; constructor({video,dataTime}:{ video: string, dataTime: {data:string,time:number}[] }){ super(); this.video = video; this.scroxtVideo = document.querySelector(this.video); this.dataTime = this.quickSort(dataTime); console.log(this.dataTime); this.tempDataTime = JSON.parse(JSON.stringify(this.dataTime)); this.lineHeight = 28; this.videoWidth = parseInt(getEleAttr(this.video,"width")); this.MAX_LINE = ~~(parseInt(getEleAttr(this.video,"height")) / this.lineHeight); this.MAX_NUM = 50; this.distance = -5; this.colorFont = ['#ffff38','#c80115','#189add']; this.createStyle(); this.startRun(); } /** * [quickSort 快速排序] * @param {number}[]} dataTime [description] */ quickSort(dataTime:{data:string,time:number}[]){ if(dataTime.length <= 1) return dataTime; let numValue = dataTime.splice(Math.floor(dataTime.length/2),1)[0]; let left = []; let right = []; for(let i = 0, len = dataTime.length; i < len; i++){ if(dataTime[i]['time'] < numValue['time']){ left.push(dataTime[i]); }else{ right.push(dataTime[i]); } } return this.quickSort(left).concat(numValue,this.quickSort(right)); } /** * [createStyle 创建内嵌css] */ createStyle(){ addStyleCSS(` .multi-barrage-line{ position: absolute; display: inline-block; top: 0; user-select:none; white-space: pre; color: #fff; font-size: 25px; font-family:SimHei, "Microsoft JhengHei", Arial, Helvetica, sans-serif; font-weight:bold; line-height: 1.125; text-shadow:rgb(0, 0, 0) 1px 0px 1px, rgb(0, 0, 0) 0px 1px 1px, rgb(0, 0, 0) 0px -1px 1px, rgb(0, 0, 0) -1px 0px 1px; transition:-webkit-transform 0s linear; z-index: 1; pointer-events: none; } .static-barrage-line{ position: absolute; left: 50%; transform:translateX(-50%); -webkit-transform:translateX(-50%); top: 0; z-index: 2; } `); } startRun(){ //添加类名:scroxt-video const className = this.scroxtVideo.className; this.scroxtVideo.className = className.indexOf('scroxt-video') > -1 ? className : className+' scroxt-video'; this.timeUpdate(); } /** * 视频播放 */ play(){ if(this.scroxtVideo.paused){ this.scroxtVideo.play(); this.intervalRun(); } } /** * 视频暂停 */ stop(){ if(!this.scroxtVideo.paused){ this.scroxtVideo.pause(); this.intervalStop(); } } /** * 视频重播 */ restart(){ this.readyShowBarrage = []; this.tempDataTime = JSON.parse(JSON.stringify(this.dataTime)); this.scroxtVideo.currentTime = 0; this.barrageWrap.forEach((value,index) => { const parentElement = value["element"].parentNode; if(parentElement) parentElement.removeChild(value["element"]); }); this.barrageWrap = []; } /** * [moveInterval 前进或后退的秒数,正数表示快进s秒,负数表示后退s秒] * @param {number=0} s [快进的秒数] */ moveInterval(s:number=0){ this.readyShowBarrage = []; this.tempDataTime = JSON.parse(JSON.stringify(this.dataTime)); this.scroxtVideo.currentTime += s; this.barrageWrap.forEach((value,index) => { const parentElement = value["element"].parentNode; if(parentElement) parentElement.removeChild(value["element"]); }); this.barrageWrap = []; } /** * [timeUpdate 播放时间更新] */ timeUpdate(){ this.scroxtVideo.addEventListener("timeupdate",function(){ this.distribution(this.scroxtVideo.currentTime); }.bind(this)); } /** * 分配弹幕,决定弹幕出场 */ distribution(currentTime){ let len = this.tempDataTime.length; let i = 0; while(len !== 0){ if(this.tempDataTime[i].time < currentTime){ if(this.tempDataTime[i].time >= currentTime-2) this.readyShowBarrage.push(this.tempDataTime[i]["data"]); this.tempDataTime.shift(); len = this.tempDataTime.length; }else{ break; } } } /** * [createBarrage 创建弹幕from readyShowBarrage] */ createBarrage(){ const len = this.readyShowBarrage.length; if(!len || this.barrageWrap.length > this.MAX_NUM) return; for(let i = 0; i < len; i++){ if(i>this.MAX_LINE){ if(len>20 && !this.staticBarrageST){ this.createStaticBarrage(this.readyShowBarrage.splice(0,this.MAX_LINE)); } break; } const lineIndex = i % this.MAX_LINE; //当前行最后一个元素是否完全出场 const currentLineArr = document.querySelectorAll(`[data-line='${lineIndex}']`); const currentLineLength = currentLineArr.length; let currentLineLastElement; if(currentLineLength > 0){ currentLineLastElement = currentLineArr[currentLineLength-1]; const width = +currentLineLastElement.getAttribute('data-width'); const move = +currentLineLastElement.getAttribute('data-move'); if(Math.abs(move) + width > this.videoWidth){ continue; } } const showCurrent = this.readyShowBarrage.shift(); const refer = Math.floor(Math.random()*1000) + (+new Date()) + i; const translatePosition = i % 2 === 0 ? 10 : 0; const div = document.createElement('div'); div.className = "multi-barrage-line"; const textNode = document.createTextNode(`${showCurrent}`); div.appendChild(textNode); this.scroxtVideo.parentNode.appendChild(div); const refWidth = parseInt(window.getComputedStyle(div,null).getPropertyValue("width")); const distance = refWidth / 600 >= 0.5 ? 0.5 : refWidth / 600; //超长随机颜色 let color = "#fff"; if(distance === 0.5){ color = this.colorFont[~~(Math.random()*this.colorFont.length)]; } this.barrageWrap.push({ element:div, scroxt:refer, line:lineIndex, move:this.videoWidth + translatePosition + 10, width: refWidth, distance:distance, color:color }); } } /** * [createStaticBarrage 静止的弹幕] */ private staticBarrageST = null; createStaticBarrage(dataTime:String[]){ for(let i = 0, len = dataTime.length; i < len; i++){ const lineIndex = i % this.MAX_LINE; const div = document.createElement('div'); div.className = "multi-barrage-line static-barrage-line"; div.style.top = lineIndex*this.lineHeight + "px"; div.style.color = this.colorFont[~~(Math.random()*this.colorFont.length)]; const textNode = document.createTextNode(`${dataTime[i]}`); div.appendChild(textNode); this.staticBarrageST = setTimeout(function(){ this.staticBarrageST = null; this.scroxtVideo.parentNode.removeChild(div); }.bind(this),3000); this.scroxtVideo.parentNode.appendChild(div); } } /** * [moveLine 页面弹幕移动] */ moveLine(){ for(let i = 0; i < this.barrageWrap.length; i++){ const barrage = this.barrageWrap[i]; const scroxt = <HTMLElement>barrage['element']; const refer = barrage['scroxt']; const line = barrage['line']; const move = barrage['move']; const width = barrage['width']; const distance = barrage['distance']; const color = barrage['color']; if(move <= -width){ this.barrageWrap.splice(i,1); i--; const parentElement = scroxt.parentNode; if(parentElement) parentElement.removeChild(scroxt); continue; } const setMove = move + this.distance * distance + this.distance/10; this.barrageWrap[i]['move'] = setMove; scroxt.style.cssText = `color:${color};transform:translate3d(${setMove}px,${line*this.lineHeight}px,0);`; } } /** * 开始播放 */ private runST = 0; intervalRun(){ this.runST = setTimeTask(function(){ this.createBarrage(); this.moveLine(); this.intervalRun(); }.bind(this)); } /** * 停止播放 */ intervalStop(){ clearTimeTask(this.runST); } } export default Barrage;
the_stack
import dns = require("dns"); import { BlobServiceClient, newPipeline, StorageSharedKeyCredential, BlockBlobClient } from "@azure/storage-blob"; import assert = require("assert"); import { configLogger } from "../../src/common/Logger"; import BlobTestServerFactory from "../BlobTestServerFactory"; import { appendToURLPath, EMULATOR_ACCOUNT_KEY, EMULATOR_ACCOUNT_NAME, getUniqueName } from "../testutils"; // Set true to enable debug log configLogger(false); describe("SpecialNaming", () => { const factory = new BlobTestServerFactory(); const server = factory.createServer(); const baseURL = `http://${server.config.host}:${server.config.port}/devstoreaccount1`; const productionStyleHostName = "devstoreaccount1.localhost"; // Use hosts file to make this resolve const noAccountHostName = "host.docker.internal"; const noAccountHostNameConnectionString = `DefaultEndpointsProtocol=http;AccountName=${EMULATOR_ACCOUNT_NAME};AccountKey=${EMULATOR_ACCOUNT_KEY};BlobEndpoint=http://${noAccountHostName}:${server.config.port}/${EMULATOR_ACCOUNT_NAME};`; const serviceClient = new BlobServiceClient( baseURL, newPipeline( new StorageSharedKeyCredential( EMULATOR_ACCOUNT_NAME, EMULATOR_ACCOUNT_KEY ), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } } ) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); before(async () => { await server.start(); await containerClient.create(); }); after(async () => { await containerClient.delete(); await server.close(); await server.clean(); }); it("Should work with special container and blob names with spaces @loki @sql", async () => { const blobName: string = getUniqueName("blob empty"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names with unicode @loki @sql", async () => { const blobName: string = getUniqueName("unicod\u00e9"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); assert.deepStrictEqual(response.segment.blobItems[0].name, blobName); }); it("Should work with special container and blob names with spaces in URL string @loki @sql", async () => { const blobName: string = getUniqueName("blob empty"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names with / @loki @sql", async () => { const blobName: string = getUniqueName("////blob/empty /another"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names with / in URL string @loki @sql", async () => { const blobName: string = getUniqueName("////blob/empty /another"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names uppercase @loki @sql", async () => { const blobName: string = getUniqueName("////Upper/blob/empty /another"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names uppercase in URL string @loki @sql", async () => { const blobName: string = getUniqueName("////Upper/blob/empty /another"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob names Chinese characters @loki @sql", async () => { const blobName: string = getUniqueName( "////Upper/blob/empty /another 汉字" ); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob names Chinese characters in URL string @loki @sql", async () => { const blobName: string = getUniqueName( "////Upper/blob/empty /another 汉字" ); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name characters @loki @sql", async () => { const blobName: string = getUniqueName( "汉字. special ~!@#$%^&*()_+`1234567890-={}|[]\\:\";'<>?,/'" ); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy( "b", // A char doesn't exist in blob name { // NOTICE: Azure Storage Server will replace "\" with "/" in the blob names prefix: blobName.replace(/\\/g, "/") } ) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name characters in URL string @loki @sql", async () => { const blobName: string = getUniqueName( "汉字. special ~!@#$%^&*()_+`1234567890-={}|[]\\:\";'<>?,/'" ); const blockBlobClient = new BlockBlobClient( // There are 2 special cases for a URL string: // Escape "%" when creating XXXURL object with URL strings // Escape "?" otherwise string after "?" will be treated as URL parameters appendToURLPath( containerClient.url, blobName.replace(/%/g, "%25").replace(/\?/g, "%3F") ), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy( "b", // "b" doesn't exist in blob name { // NOTICE: Azure Storage Server will replace "\" with "/" in the blob names prefix: blobName.replace(/\\/g, "/") } ) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Russian URI encoded @loki @sql", async () => { const blobName: string = getUniqueName("ру́сский язы́к"); const blobNameEncoded: string = encodeURIComponent(blobName); const blockBlobClient = containerClient.getBlockBlobClient(blobNameEncoded); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobNameEncoded }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Russian @loki @sql", async () => { const blobName: string = getUniqueName("ру́сский язы́к"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Russian in URL string @loki @sql", async () => { const blobName: string = getUniqueName("ру́сский язы́к"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Arabic URI encoded @loki @sql", async () => { const blobName: string = getUniqueName("عربي/عربى"); const blobNameEncoded: string = encodeURIComponent(blobName); const blockBlobClient = containerClient.getBlockBlobClient(blobNameEncoded); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobNameEncoded }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Arabic @loki @sql", async () => { const blobName: string = getUniqueName("عربي/عربى"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Arabic in URL string @loki @sql", async () => { const blobName: string = getUniqueName("عربي/عربى"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Japanese URI encoded @loki @sql", async () => { const blobName: string = getUniqueName("にっぽんご/にほんご"); const blobNameEncoded: string = encodeURIComponent(blobName); const blockBlobClient = containerClient.getBlockBlobClient(blobNameEncoded); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobNameEncoded }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Japanese @loki @sql", async () => { const blobName: string = getUniqueName("にっぽんご/にほんご"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Japanese in URL string @loki @sql", async () => { const blobName: string = getUniqueName("にっぽんご/にほんご"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it(`Should work with production style URL when ${productionStyleHostName} is resolvable`, async () => { await dns.promises.lookup(productionStyleHostName).then( async (lookupAddress) => { const baseURLProductionStyle = `http://${productionStyleHostName}:${server.config.port}`; const serviceClientProductionStyle = new BlobServiceClient( baseURLProductionStyle, newPipeline( new StorageSharedKeyCredential( EMULATOR_ACCOUNT_NAME, EMULATOR_ACCOUNT_KEY ), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } } ) ); const containerClientProductionStyle = serviceClientProductionStyle.getContainerClient( containerName ); const blobName: string = getUniqueName("myblob"); const blockBlobClient = containerClientProductionStyle.getBlockBlobClient( blobName ); await blockBlobClient.upload("ABC", 3); const response = ( await containerClientProductionStyle .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }, () => { // Cannot perform this test. We need devstoreaccount1.localhost to resolve to 127.0.0.1. // On Linux, this should just work, // On Windows, we can't spoof DNS record for specific process. // So we have options of running our own DNS server (overkill), // or editing hosts files (machine global operation; and requires running as admin). // So skip the test case. assert.ok( `Skipping test case - it needs ${productionStyleHostName} to be resolvable` ); } ); }); it(`Should work with no account host name URL when ${noAccountHostName} is resolvable`, async () => { await dns.promises.lookup(noAccountHostName).then( async (lookupAddress) => { const serviceClientNoHostName = BlobServiceClient.fromConnectionString( noAccountHostNameConnectionString, { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } } ); const containerClientProductionStyle = serviceClientNoHostName.getContainerClient( containerName ); const blobName: string = getUniqueName("myblob"); const blockBlobClient = containerClientProductionStyle.getBlockBlobClient( blobName ); await blockBlobClient.upload("ABC", 3); const response = ( await containerClientProductionStyle .listBlobsByHierarchy("$", { prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }, () => { // Cannot perform this test. We need host.docker.internal to resolve to 127.0.0.1. // On Windows, we can't spoof DNS record for specific process. // So we have options of running our own DNS server (overkill), // or editing hosts files (machine global operation; and requires running as admin). // So skip the test case. assert.ok( `Skipping test case - it needs ${noAccountHostName} to be resolvable` ); } ); }); });
the_stack
import {assert} from 'chrome://resources/js/assert.m.js'; import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.m.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {CloudPrintInterface, CloudPrintInterfaceEventType, CloudPrintInterfacePrinterFailedDetail, CloudPrintInterfaceSearchDoneDetail} from '../cloud_print_interface.js'; import {DestinationSearchBucket, MetricsContext, PrintPreviewInitializationEvents} from '../metrics.js'; import {CapabilitiesResponse, NativeLayer, NativeLayerImpl} from '../native_layer.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {NativeLayerCros, NativeLayerCrosImpl, PrinterSetupResponse} from '../native_layer_cros.js'; // </if> import {Cdd, MediaSizeOption} from './cdd.js'; import {CloudOrigins, createDestinationKey, createRecentDestinationKey, Destination, DestinationConnectionStatus, DestinationOrigin, DestinationProvisionalType, DestinationType, GooglePromotedDestinationId, RecentDestination} from './destination.js'; import {DestinationMatch, getPrinterTypeForDestination, originToType, PrinterType} from './destination_match.js'; import {LocalDestinationInfo, parseDestination, parseExtensionDestination, ProvisionalDestinationInfo} from './local_parsers.js'; /** * Printer search statuses used by the destination store. * @enum {string} */ enum DestinationStorePrinterSearchStatus { START = 'start', SEARCHING = 'searching', DONE = 'done' } /** * Enumeration of possible destination errors. */ export enum DestinationErrorType { INVALID = 0, UNSUPPORTED = 1, NO_DESTINATIONS = 2, } /** * Localizes printer capabilities. * @param capabilities Printer capabilities to localize. * @return Localized capabilities. */ function localizeCapabilities(capabilities: Cdd): Cdd { if (!capabilities.printer) { return capabilities; } const mediaSize = capabilities.printer.media_size; if (!mediaSize) { return capabilities; } for (let i = 0, media; (media = mediaSize.option[i]); i++) { // No need to patch capabilities with localized names provided. if (!media.custom_display_name_localized) { media.custom_display_name = media.custom_display_name || MEDIA_DISPLAY_NAMES_[media.name!] || media.name; } } return capabilities; } /** * Compare two media sizes by their names. * @return 1 if a > b, -1 if a < b, or 0 if a === b. */ function compareMediaNames(a: MediaSizeOption, b: MediaSizeOption): number { const nameA = a.custom_display_name_localized || a.custom_display_name || ''; const nameB = b.custom_display_name_localized || b.custom_display_name || ''; return nameA === nameB ? 0 : (nameA > nameB ? 1 : -1); } /** * Sort printer media sizes. */ function sortMediaSizes(capabilities: Cdd): Cdd { if (!capabilities.printer) { return capabilities; } const mediaSize = capabilities.printer.media_size; if (!mediaSize) { return capabilities; } // For the standard sizes, separate into categories, as seen in the Cloud // Print CDD guide: // - North American // - Chinese // - ISO // - Japanese // - Other metric // Otherwise, assume they are custom sizes. const categoryStandardNA: MediaSizeOption[] = []; const categoryStandardCN: MediaSizeOption[] = []; const categoryStandardISO: MediaSizeOption[] = []; const categoryStandardJP: MediaSizeOption[] = []; const categoryStandardMisc: MediaSizeOption[] = []; const categoryCustom: MediaSizeOption[] = []; for (let i = 0, media; (media = mediaSize.option[i]); i++) { const name = media.name || 'CUSTOM'; let category: MediaSizeOption[]; if (name.startsWith('NA_')) { category = categoryStandardNA; } else if ( name.startsWith('PRC_') || name.startsWith('ROC_') || name === 'OM_DAI_PA_KAI' || name === 'OM_JUURO_KU_KAI' || name === 'OM_PA_KAI') { category = categoryStandardCN; } else if (name.startsWith('ISO_')) { category = categoryStandardISO; } else if (name.startsWith('JIS_') || name.startsWith('JPN_')) { category = categoryStandardJP; } else if (name.startsWith('OM_')) { category = categoryStandardMisc; } else { assert(name === 'CUSTOM', 'Unknown media size. Assuming custom'); category = categoryCustom; } category.push(media); } // For each category, sort by name. categoryStandardNA.sort(compareMediaNames); categoryStandardCN.sort(compareMediaNames); categoryStandardISO.sort(compareMediaNames); categoryStandardJP.sort(compareMediaNames); categoryStandardMisc.sort(compareMediaNames); categoryCustom.sort(compareMediaNames); // Then put it all back together. mediaSize.option = categoryStandardNA; mediaSize.option.push( ...categoryStandardCN, ...categoryStandardISO, ...categoryStandardJP, ...categoryStandardMisc, ...categoryCustom); return capabilities; } /** * Event types dispatched by the destination store. * @enum {string} */ export enum DestinationStoreEventType { DESTINATION_SEARCH_DONE = 'DestinationStore.DESTINATION_SEARCH_DONE', DESTINATION_SELECT = 'DestinationStore.DESTINATION_SELECT', DESTINATIONS_INSERTED = 'DestinationStore.DESTINATIONS_INSERTED', ERROR = 'DestinationStore.ERROR', SELECTED_DESTINATION_CAPABILITIES_READY = 'DestinationStore' + '.SELECTED_DESTINATION_CAPABILITIES_READY', // <if expr="chromeos_ash or chromeos_lacros"> DESTINATION_EULA_READY = 'DestinationStore.DESTINATION_EULA_READY', // </if> } export class DestinationStore extends EventTarget { /** * Currently active user. */ private activeUser_: string = ''; /** * Whether the destination store will auto select the destination that * matches this set of parameters. */ private autoSelectMatchingDestination_: DestinationMatch|null = null; /** * Used to fetch cloud-based print destinations. */ private cloudPrintInterface_: CloudPrintInterface|null = null; /** * Cache used for constant lookup of destinations by key. */ private destinationMap_: Map<string, Destination> = new Map(); /** * Internal backing store for the data store. */ private destinations_: Destination[] = []; /** * Whether a search for destinations is in progress for each type of * printer. */ private destinationSearchStatus_: Map<PrinterType, DestinationStorePrinterSearchStatus>; private inFlightCloudPrintRequests_: Set<string> = new Set(); private initialDestinationSelected_: boolean = false; /** * Maps user account to the list of origins for which destinations are * already loaded. */ private loadedCloudOrigins_: Map<string, DestinationOrigin[]> = new Map(); /** * Used to track metrics. */ private metrics_: MetricsContext = MetricsContext.destinationSearch(); /** * Used to fetch local print destinations. */ private nativeLayer_: NativeLayer = NativeLayerImpl.getInstance(); // <if expr="chromeos_ash or chromeos_lacros"> /** * Used to fetch information about Chrome OS local print destinations. */ private nativeLayerCros_: NativeLayerCros = NativeLayerCrosImpl.getInstance(); // </if> /** * Whether PDF printer is enabled. It's disabled, for example, in App * Kiosk mode or when PDF printing is disallowed by policy. */ private pdfPrinterEnabled_: boolean = false; /** * Local destinations are CROS destinations on ChromeOS because they * require extra setup. */ private platformOrigin_: DestinationOrigin; private recentDestinationKeys_: string[] = []; /** * Currently selected destination. */ private selectedDestination_: Destination|null = null; /** * Key of the system default destination. */ private systemDefaultDestinationKey_: string = ''; /** * Event tracker used to track event listeners of the destination store. */ private tracker_: EventTracker = new EventTracker(); private typesToSearch_: Set<PrinterType> = new Set(); /** * Whether to default to the system default printer instead of the most * recent destination. */ private useSystemDefaultAsDefault_: boolean; /** * A data store that stores destinations and dispatches events when the * data store changes. * @param addListenerCallback Function to call to add Web UI listeners in * DestinationStore constructor. */ constructor( addListenerCallback: (eventName: string, listener: (t: PrinterType, p: LocalDestinationInfo[]| ProvisionalDestinationInfo[]) => void) => void) { super(); this.destinationSearchStatus_ = new Map([ [ PrinterType.EXTENSION_PRINTER, DestinationStorePrinterSearchStatus.START ], [PrinterType.LOCAL_PRINTER, DestinationStorePrinterSearchStatus.START], ]); this.platformOrigin_ = DestinationOrigin.LOCAL; // <if expr="chromeos_ash or chromeos_lacros"> this.platformOrigin_ = DestinationOrigin.CROS; // </if> this.useSystemDefaultAsDefault_ = loadTimeData.getBoolean('useSystemDefaultPrinter'); addListenerCallback( 'printers-added', (type: PrinterType, printers: LocalDestinationInfo[]|ProvisionalDestinationInfo[]) => this.onPrintersAdded_(type, printers)); } /** * @param opt_account Account to filter destinations by. When * null or omitted, all destinations are returned. * @return List of destinations accessible by the {@code account}. */ destinations(opt_account?: string|null): Destination[] { return this.destinations_.filter(function(destination) { return !destination.account || (!!opt_account && destination.account === opt_account); }); } /** * @return Whether a search for print destinations is in progress. */ get isPrintDestinationSearchInProgress(): boolean { const isLocalDestinationSearchInProgress = Array.from(this.destinationSearchStatus_.values()) .some(el => el === DestinationStorePrinterSearchStatus.SEARCHING); if (isLocalDestinationSearchInProgress) { return true; } const isCloudDestinationSearchInProgress = !!this.cloudPrintInterface_ && this.cloudPrintInterface_!.isCloudDestinationSearchInProgress(); return isCloudDestinationSearchInProgress; } /** * @return The currently selected destination or null if none is selected. */ get selectedDestination(): Destination|null { return this.selectedDestination_; } private isDestinationValid_(destination: (Destination|RecentDestination| null)): boolean { return !!destination && !!destination.id && !!destination.origin; } /** * Initializes the destination store. Sets the initially selected * destination. If any inserted destinations match this ID, that destination * will be automatically selected. * @param pdfPrinterDisabled Whether the PDF print destination is * disabled in print preview. * @param isDriveMounted Whether Google Drive is mounted. Only used on Chrome OS. * @param systemDefaultDestinationId ID of the system default * destination. * @param serializedDefaultDestinationSelectionRulesStr Serialized * default destination selection rules. * @param recentDestinations The recent print destinations. */ init( pdfPrinterDisabled: boolean, // <if expr="chromeos_ash or chromeos_lacros"> isDriveMounted: boolean, // </if> // <if expr="not chromeos and not lacros"> _isDriveMounted: boolean, // </if> systemDefaultDestinationId: string, serializedDefaultDestinationSelectionRulesStr: string|null, recentDestinations: RecentDestination[]) { if (systemDefaultDestinationId) { const systemDefaultOrigin = this.isDestinationLocal_(systemDefaultDestinationId) ? DestinationOrigin.LOCAL : this.platformOrigin_; this.systemDefaultDestinationKey_ = createDestinationKey( systemDefaultDestinationId, systemDefaultOrigin, ''); this.typesToSearch_.add(originToType(systemDefaultOrigin)); } this.recentDestinationKeys_ = recentDestinations.map( destination => createRecentDestinationKey(destination)); for (const recent of recentDestinations) { this.typesToSearch_.add(getPrinterTypeForDestination(recent)); } this.autoSelectMatchingDestination_ = this.convertToDestinationMatch_( serializedDefaultDestinationSelectionRulesStr); if (this.autoSelectMatchingDestination_) { for (const type of this.autoSelectMatchingDestination_.getTypes()) { this.typesToSearch_.add(type); } } this.pdfPrinterEnabled_ = !pdfPrinterDisabled; this.createLocalPdfPrintDestination_(); // <if expr="chromeos_ash or chromeos_lacros"> if (isDriveMounted) { this.createLocalDrivePrintDestination_(); } // </if> // Nothing recent, no system default ==> try to get a fallback printer as // destinationsInserted_ may never be called. if (this.typesToSearch_.size === 0) { this.tryToSelectInitialDestination_(); return; } // Check for Cloud Print printers and remove them if the interface is not // present. This indicates that Cloud Print is unavailable for this user. if (this.typesToSearch_.has(PrinterType.CLOUD_PRINTER)) { if (this.cloudPrintInterface_ === null) { this.typesToSearch_.delete(PrinterType.CLOUD_PRINTER); } else { // Accounts are not known on startup. Send an initial search query to // get tokens and user accounts. this.cloudPrintInterface_.search(); } } // Load all possible printers except for Cloud Print printers since they're // fetched by Javascript instead of through the native layer (which // startLoadDestinations_ invokes). for (const printerType of this.typesToSearch_) { if (printerType !== PrinterType.CLOUD_PRINTER) { this.startLoadDestinations_(printerType); } } // Start a 10s timeout so that we never hang forever. window.setTimeout(() => { this.tryToSelectInitialDestination_(true); }, 10000); } /** * @param timeoutExpired Whether the select timeout is expired. * Defaults to false. */ private tryToSelectInitialDestination_(timeoutExpired: boolean = false) { if (this.initialDestinationSelected_) { return; } const success = this.selectInitialDestination_(timeoutExpired); if (!success && !this.isPrintDestinationSearchInProgress && this.typesToSearch_.size === 0) { // No destinations this.dispatchEvent(new CustomEvent( DestinationStoreEventType.ERROR, {detail: DestinationErrorType.NO_DESTINATIONS})); } this.initialDestinationSelected_ = success; } selectDefaultDestination() { if (this.tryToSelectDestinationByKey_(this.systemDefaultDestinationKey_)) { return; } this.selectFinalFallbackDestination_(); } /** * Called when destinations are added to the store when the initial * destination has not yet been set. Selects the initial destination based on * relevant policies, recent printers, and system default. * @param timeoutExpired Whether the initial timeout has expired. * @return Whether an initial destination was successfully selected. */ private selectInitialDestination_(timeoutExpired: boolean): boolean { const searchInProgress = this.typesToSearch_.size !== 0 && !timeoutExpired; // System default printer policy takes priority. if (this.useSystemDefaultAsDefault_) { if (this.tryToSelectDestinationByKey_( this.systemDefaultDestinationKey_)) { return true; } // If search is still in progress, wait. The printer might come in a later // batch of destinations. if (searchInProgress) { return false; } } // Check recent destinations. If all the printers have loaded, check for all // of them. Otherwise, just look at the most recent. for (const key of this.recentDestinationKeys_) { if (this.tryToSelectDestinationByKey_(key)) { return true; } else if (searchInProgress) { return false; } } // Try the default destination rules, if they exist. if (this.autoSelectMatchingDestination_) { for (const destination of this.destinations_) { if (this.autoSelectMatchingDestination_.match(destination)) { this.selectDestination(destination); return true; } } // If search is still in progress, wait for other possible matching // printers. if (searchInProgress) { return false; } } // If there either aren't any recent printers or rules, or destinations are // all loaded and none could be found, try the system default. if (this.tryToSelectDestinationByKey_(this.systemDefaultDestinationKey_)) { return true; } if (searchInProgress) { return false; } // Everything's loaded, but we couldn't find either the system default, a // match for the selection rules, or a recent printer. Fallback to Save // as PDF, or the first printer to load (if in kiosk mode). if (this.selectFinalFallbackDestination_()) { return true; } return false; } /** * @param key The destination key to try to select. * @return Whether the destination was found and selected. */ private tryToSelectDestinationByKey_(key: string): boolean { const candidate = this.destinationMap_.get(key); if (candidate) { this.selectDestination(candidate); return true; } return false; } private isDestinationLocal_(destinationId: string|null): boolean { // <if expr="chromeos_ash or chromeos_lacros"> if (destinationId === GooglePromotedDestinationId.SAVE_TO_DRIVE_CROS) { return true; } // </if> return destinationId === GooglePromotedDestinationId.SAVE_AS_PDF; } /** Removes all events being tracked from the tracker. */ resetTracker() { this.tracker_.removeAll(); } // <if expr="chromeos_ash or chromeos_lacros"> /** * Attempts to find the EULA URL of the the destination ID. */ fetchEulaUrl(destinationId: string) { this.nativeLayerCros_.getEulaUrl(destinationId).then(response => { // Check that the currently selected destination ID still matches the // destination ID we used to fetch the EULA URL. if (this.selectedDestination_ && destinationId === this.selectedDestination_.id) { this.dispatchEvent(new CustomEvent( DestinationStoreEventType.DESTINATION_EULA_READY, {detail: response})); } }); } /** * Reloads all local printers. */ reloadLocalPrinters(): Promise<void> { return this.nativeLayer_.getPrinters(PrinterType.LOCAL_PRINTER); } // </if> /** * @return Creates rules matching previously selected destination. */ private convertToDestinationMatch_( serializedDefaultDestinationSelectionRulesStr: (string|null)): (DestinationMatch|null) { let matchRules = null; try { if (serializedDefaultDestinationSelectionRulesStr) { matchRules = JSON.parse(serializedDefaultDestinationSelectionRulesStr); } } catch (e) { console.warn('Failed to parse defaultDestinationSelectionRules: ' + e); } if (!matchRules) { return null; } const isLocal = !matchRules.kind || matchRules.kind === 'local'; const isCloud = !matchRules.kind || matchRules.kind === 'cloud'; if (!isLocal && !isCloud) { console.warn('Unsupported type: "' + matchRules.kind + '"'); return null; } const origins = []; if (isLocal) { origins.push(DestinationOrigin.LOCAL); origins.push(DestinationOrigin.EXTENSION); origins.push(DestinationOrigin.CROS); } if (isCloud) { origins.push(...CloudOrigins); } let idRegExp = null; try { if (matchRules.idPattern) { idRegExp = new RegExp(matchRules.idPattern || '.*'); } } catch (e) { console.warn('Failed to parse regexp for "id": ' + e); } let displayNameRegExp = null; try { if (matchRules.namePattern) { displayNameRegExp = new RegExp(matchRules.namePattern || '.*'); } } catch (e) { console.warn('Failed to parse regexp for "name": ' + e); } return new DestinationMatch( origins, idRegExp, displayNameRegExp, true /*skipVirtualDestinations*/); } /** * Updates the current active user account. */ setActiveUser(activeUser: string) { this.activeUser_ = activeUser; } /** * Sets the destination store's Google Cloud Print interface. */ setCloudPrintInterface(cloudPrintInterface: CloudPrintInterface) { assert(this.cloudPrintInterface_ === null); this.cloudPrintInterface_ = cloudPrintInterface; [CloudPrintInterfaceEventType.SEARCH_DONE, CloudPrintInterfaceEventType.SEARCH_FAILED, ].forEach(eventName => { this.tracker_.add( this.cloudPrintInterface_!.getEventTarget(), eventName, (event: CustomEvent<CloudPrintInterfaceSearchDoneDetail>) => this.onCloudPrintSearchDone_(event)); }); this.tracker_.add( this.cloudPrintInterface_!.getEventTarget(), CloudPrintInterfaceEventType.PRINTER_DONE, (event: CustomEvent<Destination>) => this.onCloudPrintPrinterDone_(event)); this.tracker_.add( this.cloudPrintInterface_!.getEventTarget(), CloudPrintInterfaceEventType.PRINTER_FAILED, (event: CustomEvent<CloudPrintInterfacePrinterFailedDetail>) => this.onCloudPrintPrinterFailed_(event)); } /** @param Key identifying the destination to select */ selectDestinationByKey(key: string) { assert(this.tryToSelectDestinationByKey_(key)); } /** * @param Destination to select. */ selectDestination(destination: Destination) { if (destination === this.selectedDestination_) { return; } if (destination === null) { this.selectedDestination_ = null; this.dispatchEvent( new CustomEvent(DestinationStoreEventType.DESTINATION_SELECT)); return; } assert( !destination.isProvisional, 'Unable to select provisonal destinations'); // Update and persist selected destination. this.selectedDestination_ = destination; // Adjust metrics. if (destination.cloudID && this.destinations_.some(function(otherDestination) { return otherDestination.cloudID === destination.cloudID && otherDestination !== destination; })) { this.metrics_.record(DestinationSearchBucket.CLOUD_DUPLICATE_SELECTED); } // Notify about selected destination change. this.dispatchEvent( new CustomEvent(DestinationStoreEventType.DESTINATION_SELECT)); // Request destination capabilities from backend, since they are not // known yet. if (destination.capabilities === null) { const type = getPrinterTypeForDestination(destination); if (type !== PrinterType.CLOUD_PRINTER) { this.nativeLayer_.getPrinterCapabilities(destination.id, type) .then( (caps) => this.onCapabilitiesSet_( destination.origin, destination.id, caps), () => this.onGetCapabilitiesFail_( destination.origin, destination.id)); MetricsContext.getPrinterCapabilities().record( PrintPreviewInitializationEvents.FUNCTION_INITIATED); } else { assert( this.cloudPrintInterface_ !== null, 'Cloud destination selected, but GCP is not enabled'); this.cloudPrintInterface_!.printer( destination.id, destination.origin, destination.account); } } else { this.sendSelectedDestinationUpdateEvent_(); } } // <if expr="chromeos_ash or chromeos_lacros"> /** * Attempt to resolve the capabilities for a Chrome OS printer. */ resolveCrosDestination(destination: Destination): Promise<PrinterSetupResponse> { assert(destination.origin === DestinationOrigin.CROS); return this.nativeLayerCros_.setupPrinter(destination.id); } /** * Attempts to resolve a provisional destination. * @param Provisional destination that should be resolved. */ resolveProvisionalDestination(destination: Destination): Promise<Destination|null> { assert( destination.provisionalType === DestinationProvisionalType.NEEDS_USB_PERMISSION, 'Provisional type cannot be resolved.'); return this.nativeLayerCros_.grantExtensionPrinterAccess(destination.id) .then( destinationInfo => { /** * Removes the destination from the store and replaces it with a * destination created from the resolved destination properties, * if any are reported. Then returns the new destination. */ this.removeProvisionalDestination_(destination.id); const parsedDestination = parseExtensionDestination(destinationInfo); this.insertIntoStore_(parsedDestination); return parsedDestination; }, () => { /** * The provisional destination is removed from the store and * null is returned. */ this.removeProvisionalDestination_(destination.id); return null; }); } // </if> /** * Selects the Save as PDF fallback if it is available. If not, selects the * first destination if it exists. * @return Whether a final destination could be found. */ private selectFinalFallbackDestination_(): boolean { // Save as PDF should always exist if it is enabled. if (this.pdfPrinterEnabled_) { const saveToPdfKey = createDestinationKey( GooglePromotedDestinationId.SAVE_AS_PDF, DestinationOrigin.LOCAL, ''); this.selectDestination(assert(this.destinationMap_.get(saveToPdfKey)!)); return true; } // Try selecting the first destination if there is at least one // destination already loaded. if (this.destinations_.length > 0) { this.selectDestination(this.destinations_[0]); return true; } // Trigger a load of all destination types, to try to select the first one. this.startLoadAllDestinations(); return false; } /** * Initiates loading of destinations. * @param type The type of destinations to load. */ private startLoadDestinations_(type: PrinterType) { if (this.destinationSearchStatus_.get(type) === DestinationStorePrinterSearchStatus.DONE) { return; } this.destinationSearchStatus_.set( type, DestinationStorePrinterSearchStatus.SEARCHING); this.nativeLayer_.getPrinters(type).then( () => this.onDestinationSearchDone_(type)); MetricsContext.getPrinters(type).record( PrintPreviewInitializationEvents.FUNCTION_INITIATED); } /** * Requests load of COOKIE based cloud destinations for |account|. */ reloadUserCookieBasedDestinations(account: string) { const origins = this.loadedCloudOrigins_.get(account) || []; if (origins.includes(DestinationOrigin.COOKIES)) { this.dispatchEvent( new CustomEvent(DestinationStoreEventType.DESTINATION_SEARCH_DONE)); } else { this.startLoadCloudDestinations(DestinationOrigin.COOKIES); } } /** Initiates loading of all known destination types. */ startLoadAllDestinations() { // Printer types that need to be retrieved from the handler. const types = [ PrinterType.EXTENSION_PRINTER, PrinterType.LOCAL_PRINTER, ]; // Cloud destinations are pulled from the cloud print server instead of the // NativeLayer/PrintPreviewHandler. this.startLoadCloudDestinations(); for (const printerType of types) { this.startLoadDestinations_(printerType); } } /** * Initiates loading of cloud destinations. * @param opt_origin Search destinations for the specified origin only. */ startLoadCloudDestinations(opt_origin?: DestinationOrigin) { if (this.cloudPrintInterface_ === null) { return; } const origins = this.loadedCloudOrigins_.get(this.activeUser_) || []; if (origins.length === 0 || (opt_origin && origins.includes(opt_origin))) { this.cloudPrintInterface_.search(this.activeUser_, opt_origin); } } /** * @return The destination matching the key, if it exists. */ getDestinationByKey(key: string): Destination|undefined { return this.destinationMap_.get(key); } // <if expr="chromeos_ash or chromeos_lacros"> /** * Removes the provisional destination with ID |provisionalId| from * |destinationMap_| and |destinations_|. */ private removeProvisionalDestination_(provisionalId: string) { this.destinations_ = this.destinations_.filter(el => { if (el.id === provisionalId) { this.destinationMap_.delete(el.key); return false; } return true; }); } // </if> /** * Inserts {@code destination} to the data store and dispatches a * DESTINATIONS_INSERTED event. */ private insertDestination_(destination: Destination) { if (this.insertIntoStore_(destination)) { this.destinationsInserted_(); } } /** * Inserts multiple {@code destinations} to the data store and dispatches * single DESTINATIONS_INSERTED event. */ private insertDestinations_(destinations: (Destination|null)[]) { let inserted = false; destinations.forEach(destination => { if (destination) { inserted = this.insertIntoStore_(destination!) || inserted; } }); if (inserted) { this.destinationsInserted_(); } } /** * Dispatches DESTINATIONS_INSERTED event. In auto select mode, tries to * update selected destination to match * {@code autoSelectMatchingDestination_}. */ private destinationsInserted_() { this.dispatchEvent( new CustomEvent(DestinationStoreEventType.DESTINATIONS_INSERTED)); this.tryToSelectInitialDestination_(); } /** * Sends SELECTED_DESTINATION_CAPABILITIES_READY event if the destination * is supported, or ERROR otherwise of with error type UNSUPPORTED. */ private sendSelectedDestinationUpdateEvent_() { if (this.selectedDestination_!.shouldShowInvalidCertificateError) { this.dispatchEvent(new CustomEvent( DestinationStoreEventType.ERROR, {detail: DestinationErrorType.UNSUPPORTED})); } else { this.dispatchEvent(new CustomEvent( DestinationStoreEventType.SELECTED_DESTINATION_CAPABILITIES_READY)); } } /** * Updates an existing print destination with capabilities and display name * information. If the destination doesn't already exist, it will be added. */ private updateDestination_(destination: Destination) { assert(destination.constructor !== Array, 'Single printer expected'); destination.capabilities = localizeCapabilities(assert(destination.capabilities!)); if (originToType(destination.origin) !== PrinterType.LOCAL_PRINTER) { destination.capabilities = sortMediaSizes(destination.capabilities); } const existingDestination = this.destinationMap_.get(destination.key); if (existingDestination !== undefined) { existingDestination.capabilities = destination.capabilities; } else { this.insertDestination_(destination); } if (this.selectedDestination_ && (existingDestination === this.selectedDestination_ || destination === this.selectedDestination_)) { this.sendSelectedDestinationUpdateEvent_(); } } /** * Inserts a destination into the store without dispatching any events. * @return Whether the inserted destination was not already in the store. */ private insertIntoStore_(destination: Destination): boolean { const key = destination.key; const existingDestination = this.destinationMap_.get(key); if (existingDestination === undefined) { this.destinations_.push(destination); this.destinationMap_.set(key, destination); return true; } if (existingDestination.connectionStatus === DestinationConnectionStatus.UNKNOWN && destination.connectionStatus !== DestinationConnectionStatus.UNKNOWN) { existingDestination.connectionStatus = destination.connectionStatus; return true; } return false; } /** * Creates a local PDF print destination. */ private createLocalPdfPrintDestination_() { if (this.pdfPrinterEnabled_) { this.insertDestination_(new Destination( GooglePromotedDestinationId.SAVE_AS_PDF, DestinationType.LOCAL, DestinationOrigin.LOCAL, loadTimeData.getString('printToPDF'), DestinationConnectionStatus.ONLINE)); } if (this.typesToSearch_.has(PrinterType.PDF_PRINTER)) { this.typesToSearch_.delete(PrinterType.PDF_PRINTER); } } // <if expr="chromeos_ash or chromeos_lacros"> /** * Creates a local Drive print destination. */ private createLocalDrivePrintDestination_() { this.insertDestination_(new Destination( GooglePromotedDestinationId.SAVE_TO_DRIVE_CROS, DestinationType.LOCAL, DestinationOrigin.LOCAL, loadTimeData.getString('printToGoogleDrive'), DestinationConnectionStatus.ONLINE)); } // </if> /** * Called when destination search is complete for some type of printer. * @param type The type of printers that are done being retrieved. */ private onDestinationSearchDone_(type: PrinterType) { MetricsContext.getPrinters(type).record( PrintPreviewInitializationEvents.FUNCTION_SUCCESSFUL); this.destinationSearchStatus_.set( type, DestinationStorePrinterSearchStatus.DONE); this.dispatchEvent( new CustomEvent(DestinationStoreEventType.DESTINATION_SEARCH_DONE)); if (this.typesToSearch_.has(type)) { this.typesToSearch_.delete(type); this.tryToSelectInitialDestination_(); } else if (this.typesToSearch_.size === 0) { this.tryToSelectInitialDestination_(); } } /** * Called when the native layer retrieves the capabilities for the selected * local destination. Updates the destination with new capabilities if the * destination already exists, otherwise it creates a new destination and * then updates its capabilities. * @param origin The origin of the print destination. * @param id The id of the print destination. * @param settingsInfo Contains the capabilities of the print destination, * and information about the destination except in the case of extension * printers. */ private onCapabilitiesSet_( origin: DestinationOrigin, id: string, settingsInfo: CapabilitiesResponse) { MetricsContext.getPrinterCapabilities().record( PrintPreviewInitializationEvents.FUNCTION_SUCCESSFUL); let dest = null; const key = createDestinationKey(id, origin, ''); dest = this.destinationMap_.get(key); if (!dest) { // Ignore unrecognized extension printers if (!settingsInfo.printer) { assert(origin === DestinationOrigin.EXTENSION); return; } dest = parseDestination(originToType(origin), assert(settingsInfo.printer)); } if (dest) { if ((origin === DestinationOrigin.LOCAL || origin === DestinationOrigin.CROS) && dest.capabilities) { // If capabilities are already set for this destination ignore new // results. This prevents custom margins from being cleared as long // as the user does not change to a new non-recent destination. return; } dest.capabilities = settingsInfo.capabilities; this.updateDestination_(dest); // <if expr="chromeos_ash or chromeos_lacros"> // Start the fetch for the PPD EULA URL. this.fetchEulaUrl(dest.id); // </if> } } /** * Called when a request to get a local destination's print capabilities * fails. If the destination is the initial destination, auto-select another * destination instead. * @param _origin The origin type of the failed destination. * @param destinationId The destination ID that failed. */ private onGetCapabilitiesFail_( _origin: DestinationOrigin, destinationId: string) { MetricsContext.getPrinterCapabilities().record( PrintPreviewInitializationEvents.FUNCTION_FAILED); console.warn( 'Failed to get print capabilities for printer ' + destinationId); if (this.selectedDestination_ && this.selectedDestination_.id === destinationId) { this.dispatchEvent(new CustomEvent( DestinationStoreEventType.ERROR, {detail: DestinationErrorType.INVALID})); } } /** * Called when the /search call completes, either successfully or not. * In case of success, stores fetched destinations. * @param event Contains the request result. */ private onCloudPrintSearchDone_( event: CustomEvent<CloudPrintInterfaceSearchDoneDetail>) { const payload = event.detail; const searchingCloudPrintersDone = this.typesToSearch_.has(PrinterType.CLOUD_PRINTER) && !this.cloudPrintInterface_!.isCloudDestinationSearchInProgress() && (!!payload.user || event.type === CloudPrintInterfaceEventType.SEARCH_FAILED); if (searchingCloudPrintersDone) { this.typesToSearch_.delete(PrinterType.CLOUD_PRINTER); } if (payload.printers && payload.printers.length > 0) { this.insertDestinations_(payload.printers); } if (searchingCloudPrintersDone) { this.tryToSelectInitialDestination_(); } if (payload.searchDone) { const origins = this.loadedCloudOrigins_.get(payload.user) || []; if (!origins.includes(payload.origin)) { this.loadedCloudOrigins_.set( payload.user, origins.concat([payload.origin])); } } this.dispatchEvent( new CustomEvent(DestinationStoreEventType.DESTINATION_SEARCH_DONE)); } /** * Called when /printer call completes. Updates the specified destination's * print capabilities. * @param event Contains detailed information about the destination. */ private onCloudPrintPrinterDone_(event: CustomEvent<Destination>) { this.updateDestination_(event.detail); this.inFlightCloudPrintRequests_.delete(event.detail.key); } /** * Called when the Google Cloud Print interface fails to lookup a * destination. Selects another destination if the failed destination was * the initial destination. * @param event Contains the ID of the destination that failed to be looked * up. */ private onCloudPrintPrinterFailed_( event: CustomEvent<CloudPrintInterfacePrinterFailedDetail>) { const key = createDestinationKey( event.detail.destinationId, event.detail.origin, event.detail.account || ''); this.inFlightCloudPrintRequests_.delete(key); if (this.selectedDestination_ && this.selectedDestination_.key === key) { this.dispatchEvent(new CustomEvent( DestinationStoreEventType.ERROR, {detail: DestinationErrorType.INVALID})); } } /** * Called when a printer or printers are detected after sending getPrinters * from the native layer. * @param type The type of printer(s) added. * @param printers Information about the printers that have been retrieved. */ private onPrintersAdded_( type: PrinterType, printers: LocalDestinationInfo[]|ProvisionalDestinationInfo[]) { this.insertDestinations_(printers.map( (printer: LocalDestinationInfo|ProvisionalDestinationInfo) => parseDestination(type, printer))); } } /** * Maximum amount of time spent searching for extension destinations, in * milliseconds. */ const EXTENSION_SEARCH_DURATION_: number = 5000; /** * Human readable names for media sizes in the cloud print CDD. * https://developers.google.com/cloud-print/docs/cdd */ const MEDIA_DISPLAY_NAMES_: {[key: string]: string} = { 'ISO_2A0': '2A0', 'ISO_A0': 'A0', 'ISO_A0X3': 'A0x3', 'ISO_A1': 'A1', 'ISO_A10': 'A10', 'ISO_A1X3': 'A1x3', 'ISO_A1X4': 'A1x4', 'ISO_A2': 'A2', 'ISO_A2X3': 'A2x3', 'ISO_A2X4': 'A2x4', 'ISO_A2X5': 'A2x5', 'ISO_A3': 'A3', 'ISO_A3X3': 'A3x3', 'ISO_A3X4': 'A3x4', 'ISO_A3X5': 'A3x5', 'ISO_A3X6': 'A3x6', 'ISO_A3X7': 'A3x7', 'ISO_A3_EXTRA': 'A3 Extra', 'ISO_A4': 'A4', 'ISO_A4X3': 'A4x3', 'ISO_A4X4': 'A4x4', 'ISO_A4X5': 'A4x5', 'ISO_A4X6': 'A4x6', 'ISO_A4X7': 'A4x7', 'ISO_A4X8': 'A4x8', 'ISO_A4X9': 'A4x9', 'ISO_A4_EXTRA': 'A4 Extra', 'ISO_A4_TAB': 'A4 Tab', 'ISO_A5': 'A5', 'ISO_A5_EXTRA': 'A5 Extra', 'ISO_A6': 'A6', 'ISO_A7': 'A7', 'ISO_A8': 'A8', 'ISO_A9': 'A9', 'ISO_B0': 'B0', 'ISO_B1': 'B1', 'ISO_B10': 'B10', 'ISO_B2': 'B2', 'ISO_B3': 'B3', 'ISO_B4': 'B4', 'ISO_B5': 'B5', 'ISO_B5_EXTRA': 'B5 Extra', 'ISO_B6': 'B6', 'ISO_B6C4': 'B6C4', 'ISO_B7': 'B7', 'ISO_B8': 'B8', 'ISO_B9': 'B9', 'ISO_C0': 'C0', 'ISO_C1': 'C1', 'ISO_C10': 'C10', 'ISO_C2': 'C2', 'ISO_C3': 'C3', 'ISO_C4': 'C4', 'ISO_C5': 'C5', 'ISO_C6': 'C6', 'ISO_C6C5': 'C6C5', 'ISO_C7': 'C7', 'ISO_C7C6': 'C7C6', 'ISO_C8': 'C8', 'ISO_C9': 'C9', 'ISO_DL': 'Envelope DL', 'ISO_RA0': 'RA0', 'ISO_RA1': 'RA1', 'ISO_RA2': 'RA2', 'ISO_SRA0': 'SRA0', 'ISO_SRA1': 'SRA1', 'ISO_SRA2': 'SRA2', 'JIS_B0': 'B0 (JIS)', 'JIS_B1': 'B1 (JIS)', 'JIS_B10': 'B10 (JIS)', 'JIS_B2': 'B2 (JIS)', 'JIS_B3': 'B3 (JIS)', 'JIS_B4': 'B4 (JIS)', 'JIS_B5': 'B5 (JIS)', 'JIS_B6': 'B6 (JIS)', 'JIS_B7': 'B7 (JIS)', 'JIS_B8': 'B8 (JIS)', 'JIS_B9': 'B9 (JIS)', 'JIS_EXEC': 'Executive (JIS)', 'JPN_CHOU2': 'Choukei 2', 'JPN_CHOU3': 'Choukei 3', 'JPN_CHOU4': 'Choukei 4', 'JPN_HAGAKI': 'Hagaki', 'JPN_KAHU': 'Kahu Envelope', 'JPN_KAKU2': 'Kaku 2', 'JPN_OUFUKU': 'Oufuku Hagaki', 'JPN_YOU4': 'You 4', 'NA_10X11': '10x11', 'NA_10X13': '10x13', 'NA_10X14': '10x14', 'NA_10X15': '10x15', 'NA_11X12': '11x12', 'NA_11X15': '11x15', 'NA_12X19': '12x19', 'NA_5X7': '5x7', 'NA_6X9': '6x9', 'NA_7X9': '7x9', 'NA_9X11': '9x11', 'NA_A2': 'A2', 'NA_ARCH_A': 'Arch A', 'NA_ARCH_B': 'Arch B', 'NA_ARCH_C': 'Arch C', 'NA_ARCH_D': 'Arch D', 'NA_ARCH_E': 'Arch E', 'NA_ASME_F': 'ASME F', 'NA_B_PLUS': 'B-plus', 'NA_C': 'C', 'NA_C5': 'C5', 'NA_D': 'D', 'NA_E': 'E', 'NA_EDP': 'EDP', 'NA_EUR_EDP': 'European EDP', 'NA_EXECUTIVE': 'Executive', 'NA_F': 'F', 'NA_FANFOLD_EUR': 'FanFold European', 'NA_FANFOLD_US': 'FanFold US', 'NA_FOOLSCAP': 'FanFold German Legal', 'NA_GOVT_LEGAL': 'Government Legal', 'NA_GOVT_LETTER': 'Government Letter', 'NA_INDEX_3X5': 'Index 3x5', 'NA_INDEX_4X6': 'Index 4x6', 'NA_INDEX_4X6_EXT': 'Index 4x6 ext', 'NA_INDEX_5X8': '5x8', 'NA_INVOICE': 'Invoice', 'NA_LEDGER': 'Tabloid', // Ledger in portrait is called Tabloid. 'NA_LEGAL': 'Legal', 'NA_LEGAL_EXTRA': 'Legal extra', 'NA_LETTER': 'Letter', 'NA_LETTER_EXTRA': 'Letter extra', 'NA_LETTER_PLUS': 'Letter plus', 'NA_MONARCH': 'Monarch', 'NA_NUMBER_10': 'Envelope #10', 'NA_NUMBER_11': 'Envelope #11', 'NA_NUMBER_12': 'Envelope #12', 'NA_NUMBER_14': 'Envelope #14', 'NA_NUMBER_9': 'Envelope #9', 'NA_PERSONAL': 'Personal', 'NA_QUARTO': 'Quarto', 'NA_SUPER_A': 'Super A', 'NA_SUPER_B': 'Super B', 'NA_WIDE_FORMAT': 'Wide format', 'OM_DAI_PA_KAI': 'Dai-pa-kai', 'OM_FOLIO': 'Folio', 'OM_FOLIO_SP': 'Folio SP', 'OM_INVITE': 'Invite Envelope', 'OM_ITALIAN': 'Italian Envelope', 'OM_JUURO_KU_KAI': 'Juuro-ku-kai', 'OM_LARGE_PHOTO': 'Large photo', 'OM_OFICIO': 'Oficio', 'OM_PA_KAI': 'Pa-kai', 'OM_POSTFIX': 'Postfix Envelope', 'OM_SMALL_PHOTO': 'Small photo', 'PRC_1': 'prc1 Envelope', 'PRC_10': 'prc10 Envelope', 'PRC_16K': 'prc 16k', 'PRC_2': 'prc2 Envelope', 'PRC_3': 'prc3 Envelope', 'PRC_32K': 'prc 32k', 'PRC_4': 'prc4 Envelope', 'PRC_5': 'prc5 Envelope', 'PRC_6': 'prc6 Envelope', 'PRC_7': 'prc7 Envelope', 'PRC_8': 'prc8 Envelope', 'ROC_16K': 'ROC 16K', 'ROC_8K': 'ROC 8k', };
the_stack
import { UserRequest } from '../interfaces/user-request.interface'; import { Response, Request } from 'express'; import { getConnection } from 'typeorm'; import { Asset } from '../entity/Asset'; import { validate } from 'class-validator'; import { Organization } from '../entity/Organization'; import { status } from '../enums/status-enum'; import { encrypt } from '../utilities/crypto.utility'; import { Jira } from '../entity/Jira'; import { hasAssetReadAccess, hasOrgAccess } from '../utilities/role.utility'; import { Vulnerability } from '../entity/Vulnerability'; /** * @description Get organization assets * @param {UserRequest} req * @param {Response} res * @returns assets where: { status: status.archived, id: In(req.userOrgs) } */ export const getOrgAssets = async (req: UserRequest, res: Response) => { if (!req.params.id) { return res.status(400).json('Invalid Asset UserRequest'); } if (isNaN(+req.params.id)) { return res.status(400).json('Invalid Organization ID'); } if (!hasOrgAccess(req, +req.params.id)) { return res.status(404).json('Organization not found'); } const assets = await getConnection() .getRepository(Asset) .createQueryBuilder('asset') .leftJoinAndSelect('asset.jira', 'jira') .where('asset.organization = :orgId', { orgId: req.params.id, }) .andWhere('asset.status = :status', { status: status.active, }) .andWhere('asset.id in(:userAssets)', { userAssets: getConnection().driver.options.type === 'sqlite' ? req.userAssets : [null, ...req.userAssets], }) .select(['asset.id', 'asset.name', 'asset.status', 'jira.id']) .getMany(); if (!assets) { return res.status(404).json('Assets not found'); } for (const asset of assets) { asset['openVulnCount'] = await getOpenVulnCountByAsset(asset); } return res.status(200).json(assets); }; /** * @description Get organization archived assets * @param {UserRequest} req * @param {Response} res * @returns assets */ export const getArchivedOrgAssets = async (req: UserRequest, res: Response) => { if (!req.params.id) { return res.status(400).json('Invalid Asset Request'); } if (isNaN(+req.params.id)) { return res.status(400).json('Invalid Organization ID'); } if (!hasOrgAccess(req, +req.params.id)) { return res.status(404).json('Organization not found'); } const assets = await getConnection() .getRepository(Asset) .createQueryBuilder('asset') .leftJoinAndSelect('asset.jira', 'jira') .where('asset.organization = :orgId', { orgId: req.params.id, }) .andWhere('asset.status = :status', { status: status.archived, }) .andWhere('asset.id in(:userAssets)', { userAssets: getConnection().driver.options.type === 'sqlite' ? req.userAssets : [null, ...req.userAssets], }) .select(['asset.id', 'asset.name', 'asset.status', 'jira.id']) .getMany(); if (!assets) { return res.status(404).json('Assets not found'); } for (const asset of assets) { asset['openVulnCount'] = await getOpenVulnCountByAsset(asset); } return res.status(200).json(assets); }; /** * @description Gets vulnerability count by asset ID * @param {Asset} asset * @returns integer */ export const getOpenVulnCountByAsset = async (asset: Asset) => { const vulnCount = await getConnection() .getRepository(Vulnerability) .createQueryBuilder('vuln') .leftJoinAndSelect('vuln.assessment', 'assessment') .leftJoinAndSelect('assessment.asset', 'asset') .where('asset.id = :assetId', { assetId: asset.id, }) .andWhere('vuln.status = :status', { status: 'Open', }) .select(['vuln.id', 'vuln.name', 'assessment.id', 'asset.id']) .getCount(); return vulnCount; }; /** * @description Fetch open vulnerabilities by asset ID * @param {Asset} asset * @returns array of vulnerabilities */ export const getOpenVulnsByAsset = async (req: UserRequest, res: Response) => { const assetAccess = await hasAssetReadAccess(req, +req.params.assetId); if (!assetAccess) { return res.status(404).json('Asset not found'); } const vulns = await getConnection() .getRepository(Vulnerability) .createQueryBuilder('vuln') .leftJoinAndSelect('vuln.assessment', 'assessment') .leftJoinAndSelect('assessment.asset', 'asset') .where('asset.id = :assetId', { assetId: req.params.assetId, }) .andWhere('vuln.status = :status', { status: 'Open', }) .select([ 'vuln.id', 'vuln.name', 'vuln.risk', 'vuln.systemic', 'vuln.cvssScore', 'vuln.cvssUrl', 'assessment.id', 'vuln.jiraId', ]) .getMany(); return res.status(200).json(vulns); }; /** * @description API backend for creating an asset associated by org ID * @param {UserRequest} req * @param {Response} res * @returns success/error message */ export const createAsset = async (req: UserRequest, res: Response) => { if (isNaN(+req.params.id)) { return res.status(400).json('Organization ID is not valid'); } const org = await getConnection() .getRepository(Organization) .findOne(req.params.id); if (!org) { return res.status(404).json('Organization does not exist'); } if (!req.body.name) { return res.status(400).send('Asset is not valid'); } let asset = new Asset(); asset.name = req.body.name; asset.organization = org; asset.status = status.active; const errors = await validate(asset); if (errors.length > 0) { return res.status(400).send('Asset form validation failed'); } else { asset = await getConnection().getRepository(Asset).save(asset); if ( req.body.jira && req.body.jira.username && req.body.jira.host && req.body.jira.apiKey ) { try { await addJiraIntegration( req.body.jira.username, req.body.jira.host, req.body.jira.apiKey, asset ); } catch (err) { return res.status(400).json(err); } } else { return res .status(200) .json( 'Asset saved successfully. Unable to integrate Jira. JIRA integration requires username, host, and API key.' ); } return res.status(200).json('Asset saved successfully'); } }; /** * @description Purge JIRA by asset ID * @param {UserRequest} req * @param {Response} res * @returns success/error message */ export const purgeJiraInfo = async (req: Request, res: Response) => { if (!req.params.assetId) { return res.status(400).json('Asset ID is not valid'); } if (isNaN(+req.params.assetId)) { return res.status(400).json('Asset ID is not valid'); } const asset = await getConnection() .getRepository(Asset) .findOne(req.params.assetId, { relations: ['jira'] }); await getConnection().getRepository(Jira).delete(asset.jira); return res.status(200).json('The API Key has been purged successfully'); }; /** * @description Associates Asset to JIRA integration * @param {UserRequest} req * @param {Response} res * @returns success/error message */ const addJiraIntegration = ( username: string, host: string, apiKey: string, asset: Asset ): Promise<Jira> => { return new Promise(async (resolve, reject) => { const existingAsset = await getConnection() .getRepository(Asset) .findOne(asset.id); if (existingAsset.jira) { reject( `The Asset: ${existingAsset.name} contains an existing Jira integration. Purge the existing Jira integration and try again.` ); return; } const jiraInit: Jira = { id: null, username, host, asset, apiKey, }; try { jiraInit.apiKey = encrypt(apiKey); } catch (err) { reject(err); return; } const errors = await validate(jiraInit); if (errors.length > 0) { reject('Jira integration requires username, host, and API key.'); return; } else { const jiraResult = await getConnection() .getRepository(Jira) .save(jiraInit); resolve(jiraResult); } }); }; /** * @description Get asset by ID * @param {UserRequest} req * @param {Response} res * @returns asset */ export const getAssetById = async (req: UserRequest, res: Response) => { if (isNaN(+req.params.assetId)) { return res.status(400).json('Invalid Asset ID'); } const asset = await getConnection() .getRepository(Asset) .findOne(req.params.assetId, { relations: ['jira'] }); if (!asset) { return res.status(404).send('Asset does not exist'); } const hasAccess = await hasAssetReadAccess(req, asset.id); if (!hasAccess) { return res.status(404).json('Asset not found'); } if (asset.jira) { delete asset.jira.apiKey; } return res.status(200).json(asset); }; /** * @description Update asset by ID * @param {UserRequest} req * @param {Response} res * @return success/error message */ export const updateAssetById = async (req: UserRequest, res: Response) => { if (isNaN(+req.params.assetId) || !req.params.assetId) { return res.status(400).json('Asset ID is not valid'); } const asset = await getConnection() .getRepository(Asset) .findOne(req.params.assetId); if (!asset) { return res.status(404).json('Asset does not exist'); } if (!req.body.name) { return res.status(400).json('Asset name is not valid'); } try { if ( req.body.jira && req.body.jira.username && req.body.jira.host && req.body.jira.apiKey ) { await addJiraIntegration( req.body.jira.username, req.body.jira.host, req.body.jira.apiKey, asset ); } } catch (err) { return res.status(400).json('JIRA integration validation failed'); } asset.name = req.body.name; const errors = await validate(asset, { skipMissingProperties: true }); if (errors.length > 0) { return res.status(400).send('Asset form validation failed'); } else { await getConnection().getRepository(Asset).save(asset); return res.status(200).json('Asset patched successfully'); } }; /** * @description Archive asset by ID * @param {UserRequest} req * @param {Response} res * @return success/error message */ export const archiveAssetById = async (req: UserRequest, res: Response) => { if (isNaN(+req.params.assetId) || !req.params.assetId) { return res.status(400).json('Asset ID is not valid'); } const asset = await getConnection() .getRepository(Asset) .findOne(req.params.assetId); if (!asset) { return res.status(404).json('Asset does not exist'); } asset.status = status.archived; await getConnection().getRepository(Asset).save(asset); res.status(200).json('Asset archived successfully'); }; /** * @description Activate an asset by ID * @param {UserRequest} req * @param {Response} res * @return success/error message */ export const activateAssetById = async (req: UserRequest, res: Response) => { if (isNaN(+req.params.assetId) || !req.params.assetId) { return res.status(400).json('Asset ID is not valid'); } const asset = await getConnection() .getRepository(Asset) .findOne(req.params.assetId); if (!asset) { return res.status(404).json('Asset does not exist'); } asset.status = status.active; await getConnection().getRepository(Asset).save(asset); res.status(200).json('Asset activated successfully'); };
the_stack
import * as vscode from 'vscode'; import { yamlLocator, YamlMap, YamlSequence, YamlNode, YamlDocument, VirtualDocument } from './yaml-locator'; import * as _ from 'lodash'; import { TknElementType } from '../model/element-type'; import { PipelineTask, PipelineTaskCondition } from '../model/pipeline/pipeline-model'; import { TaskRunSteps, TaskStep } from '../tekton'; const TEKTON_API = 'tekton.dev/'; const TRIGGER_API = 'triggers.tekton.dev'; export enum TektonYamlType { Task = 'Task', TaskRun = 'TaskRun', Pipeline = 'Pipeline', Condition = 'Condition', ClusterTask = 'ClusterTask', PipelineRun = 'PipelineRun', EventListener = 'EventListener', TriggerBinding = 'TriggerBinding', TriggerTemplate = 'TriggerTemplate', PipelineResource = 'PipelineResource', ClusterTriggerBinding = 'ClusterTriggerBinding', } export interface DeclaredResource { name: string; type: string; } export interface DeclaredTask { id: string; name: string; taskRef: string; runAfter: string[]; kind: 'Task' | 'ClusterTask' | 'Condition' | 'When' | 'TaskSpec' | string; position?: number; final?: boolean; steps?: TaskStep[]; retry?: number; } export type RunState = 'Cancelled' | 'Finished' | 'Started' | 'Failed' | 'Unknown'; export interface PipelineRunTask extends DeclaredTask { state?: RunState; startTime?: string; completionTime?: string; stepsCount?: number; finishedSteps?: number; steps?: TaskRunSteps[] | TaskStep[]; retryNumber?: number; } export class TektonYaml { getRootMap(doc: YamlDocument): YamlMap | undefined { return doc.nodes.find(node => node.kind === 'MAPPING') as YamlMap; } getApiVersion(rootMap: YamlMap): string { return getYamlMappingValue(rootMap, 'apiVersion'); } getApiVersionNode(rootMap: YamlMap): YamlNode { return findNodeByKey('apiVersion', rootMap); } getKind(rootMap: YamlMap): string { return getYamlMappingValue(rootMap, 'kind'); } getKindNode(rootMap: YamlMap): YamlNode { return findNodeByKey('kind', rootMap); } getName(metadata: YamlMap): string { return getYamlMappingValue(metadata, 'name'); } getNameNode(metadata: YamlMap): YamlNode { return findNodeByKey('name', metadata); } getMetadata(rootMap: YamlMap): YamlMap { return findNodeByKey<YamlMap>('metadata', rootMap); } isTektonYaml(vsDocument: vscode.TextDocument): TektonYamlType | undefined { const yamlDocuments = yamlLocator.getYamlDocuments(vsDocument); for (const doc of yamlDocuments) { const type = this.getTektonYamlType(doc); if (type) { return type; } } return undefined; } getTektonYamlType(doc: YamlDocument): TektonYamlType | undefined { const rootMap = this.getRootMap(doc); if (rootMap) { const apiVersion = getYamlMappingValue(rootMap, 'apiVersion'); const kind = getYamlMappingValue(rootMap, 'kind'); if (apiVersion?.startsWith(TEKTON_API) || apiVersion?.startsWith(TRIGGER_API)) { return TektonYamlType[kind]; } } } getTektonDocuments(vsDocument: VirtualDocument, type: TektonYamlType): YamlDocument[] | undefined { const yamlDocuments = yamlLocator.getYamlDocuments(vsDocument); if (!yamlDocuments) { return undefined; } const result: YamlDocument[] = []; for (const doc of yamlDocuments) { const rootMap = this.getRootMap(doc); if (rootMap) { const apiVersion = getYamlMappingValue(rootMap, 'apiVersion'); const kind = getYamlMappingValue(rootMap, 'kind'); if (apiVersion && apiVersion.startsWith(TEKTON_API) && kind === type) { result.push(doc); } } } return result; } getMetadataName(doc: YamlDocument): string | undefined { const rootMap = this.getRootMap(doc); if (rootMap) { const metadata = this.getMetadata(rootMap); if (metadata) { return this.getName(metadata); } } return undefined; } getCreationTimestamp(doc: YamlDocument): string | undefined { const rootMap = this.getRootMap(doc); if (rootMap) { const metadata = this.getMetadata(rootMap); if (metadata) { return getYamlMappingValue(metadata, 'creationTimestamp'); } } return undefined; } getApiVersionAndTypePath(vsDocument: vscode.TextDocument): string | undefined { const yamlDocuments = yamlLocator.getYamlDocuments(vsDocument); if (!yamlDocuments) { return undefined; } for (const doc of yamlDocuments) { const rootMap = this.getRootMap(doc); if (rootMap) { const apiVersion = getYamlMappingValue(rootMap, 'apiVersion'); const kind = getYamlMappingValue(rootMap, 'kind'); return `${apiVersion}_${kind}.json`; } } return undefined; } } export const tektonYaml = new TektonYaml(); export class PipelineYaml { getPipelineSpec(rootMap: YamlMap): YamlMap { return getSpecMap(rootMap); } getTasks(specMap: YamlMap): YamlSequence { return getTasksSeq(specMap); } getCustomTasks(vsDocument: vscode.TextDocument): string[]{ const result: string[] = []; if (tektonYaml.isTektonYaml(vsDocument) === TektonYamlType.Pipeline) { const yamlDocuments = yamlLocator.getYamlDocuments(vsDocument); for (const doc of yamlDocuments) { const rootMap = tektonYaml.getRootMap(doc); if (rootMap) { const specMap = getSpecMap(rootMap); if (specMap) { const tasksSeq = getTasksSeq(specMap); if (tasksSeq) { for (const taskNode of tasksSeq.items) { if (taskNode.kind === 'MAPPING') { const taskRef = findNodeByKey<YamlMap>('taskRef', taskNode as YamlMap); if (taskRef){ const apiVersion = findNodeByKey<YamlNode>('apiVersion', taskRef); const kind = findNodeByKey<YamlNode>('kind', taskRef); const nameValue = findNodeByKey<YamlNode>('name', taskRef); if (nameValue && apiVersion && kind) { result.push(nameValue.raw.trim()); } } } } } } } } } return result; } getTaskRef(task: YamlMap): [YamlNode, YamlMap] { return findNodeAndKeyByKeyValue<YamlNode, YamlMap>('taskRef', task); } getPipelineTasksRefName(vsDocument: vscode.TextDocument): string[] { const result: string[] = []; if (tektonYaml.isTektonYaml(vsDocument) === TektonYamlType.Pipeline) { const yamlDocuments = yamlLocator.getYamlDocuments(vsDocument); for (const doc of yamlDocuments) { const rootMap = tektonYaml.getRootMap(doc); if (rootMap) { const specMap = getSpecMap(rootMap); if (specMap) { const tasksSeq = getTasksSeq(specMap); if (tasksSeq) { result.push(...getTasksRefName(tasksSeq.items)); } } } } } return result; } getPipelineTasksName(vsDocument: vscode.TextDocument): string[] { const result: string[] = []; if (tektonYaml.isTektonYaml(vsDocument) === TektonYamlType.Pipeline) { const yamlDocuments = yamlLocator.getYamlDocuments(vsDocument); for (const doc of yamlDocuments) { const rootMap = tektonYaml.getRootMap(doc); if (rootMap) { const specMap = getSpecMap(rootMap); if (specMap) { const tasksSeq = getTasksSeq(specMap); if (tasksSeq) { result.push(...getTasksName(tasksSeq.items)); } } } } } return result; } getPipelineTasks(doc: YamlDocument): DeclaredTask[] { const rootMap = tektonYaml.getRootMap(doc); if (rootMap) { const specMap = getSpecMap(rootMap); return collectTasks(specMap); } } getDeclaredResources(vsDocument: vscode.TextDocument): DeclaredResource[] { const result: DeclaredResource[] = []; if (tektonYaml.isTektonYaml(vsDocument) === TektonYamlType.Pipeline) { const yamlDocuments = yamlLocator.getYamlDocuments(vsDocument); for (const doc of yamlDocuments) { const rootMap = tektonYaml.getRootMap(doc); if (rootMap) { const specMap = getSpecMap(rootMap); if (specMap) { const resourcesSeq = findNodeByKey<YamlSequence>('resources', specMap); if (resourcesSeq) { for (const res of resourcesSeq.items) { if (res.kind === 'MAPPING') { result.push(getDeclaredResource(res as YamlMap)); } } } } } } } return result; } findTask(document: vscode.TextDocument, position: vscode.Position): string | undefined { const element = yamlLocator.getMatchedTknElement(document, position); if (!element) { return undefined; } if (element.type === TknElementType.PIPELINE_TASK) { return (element as PipelineTask).name.value; } if (element.type === TknElementType.PIPELINE_TASK_CONDITION) { return (element as PipelineTaskCondition).conditionRef.value; } let current = element; while (current.parent) { current = current.parent; if (current.type === TknElementType.PIPELINE_TASK) { return (current as PipelineTask).name.value; } if (current.type === TknElementType.PIPELINE_TASK_CONDITION) { return (current as PipelineTaskCondition).conditionRef.value; } } return undefined; } // findTaskByNameInTaskSpec(document: vscode.TextDocument, name: string): DeclaredTask { // const yamlDocuments = yamlLocator.getYamlDocuments(document); // for (const doc of yamlDocuments) { // if (tektonYaml.getTektonYamlType(doc) === TektonYamlType.Pipeline) { // } // } // } } export const pipelineYaml = new PipelineYaml(); export class PipelineRunYaml { getTektonPipelineRefOrSpec(doc: YamlDocument): string | DeclaredTask[] { const rootMap = tektonYaml.getRootMap(doc); if (rootMap) { const specMap = getSpecMap(rootMap); const pipelineRef = findNodeByKey<YamlMap>('pipelineRef', specMap); if (pipelineRef) { const nameValue = findNodeByKey<YamlNode>('name', pipelineRef); if (nameValue) { return nameValue.raw; } } const pipelineSpec = findNodeByKey<YamlMap>('pipelineSpec', specMap); if (pipelineSpec) { return collectTasks(pipelineSpec); } } return undefined; } getPipelineRunName(doc: YamlDocument): string | undefined { if (!tektonYaml.getCreationTimestamp(doc)){ return undefined; } const rootMap = tektonYaml.getRootMap(doc); if (rootMap) { const metadata = findNodeByKey<YamlMap>('metadata', rootMap); return getYamlMappingValue(metadata, 'name'); } return undefined; } getPipelineRunStatus(doc: YamlDocument): RunState { const rootMap = tektonYaml.getRootMap(doc); if (rootMap) { const status = findNodeByKey<YamlMap>('status', rootMap); if (status) { return getPipelineRunTaskState(status); } } return 'Unknown'; // default state } } export const pipelineRunYaml = new PipelineRunYaml(); function collectTasks(specMap: YamlMap): DeclaredTask[] { const result: DeclaredTask[] = []; if (specMap) { const tasksSeq = getTasksSeq(specMap); if (tasksSeq) { for (const taskNode of tasksSeq.items) { if (taskNode.kind === 'MAPPING') { const decTask = toDeclaredTask(taskNode as YamlMap); decTask.runAfter = collectRunAfter(taskNode as YamlMap, decTask.name); collectConditions(taskNode as YamlMap, result); collectWhen(taskNode as YamlMap, result, decTask.name); result.push(decTask); } } } // collect finally tasks const finallyTasks = findNodeByKey<YamlSequence>('finally', specMap); if (finallyTasks) { const lastTasks = getLastTasks(result); for (const finalTask of finallyTasks.items) { if (finalTask.kind === 'MAPPING') { const fTask = toDeclaredTask(finalTask as YamlMap); fTask.runAfter = lastTasks; fTask.final = true; result.push(fTask); } } } } return result; } function getLastTasks(tasks: DeclaredTask[]): string[]{ const afterTasks = new Set<string>(); for (const task of tasks) { task.runAfter.forEach(v => afterTasks.add(v)); } const result: string[] = []; for (const task of tasks) { if (!afterTasks.has(task.id)) { result.push(task.id); } } return result; } function toDeclaredTask(taskNode: YamlMap): DeclaredTask { const decTask = {} as DeclaredTask; const nameValue = findNodeByKey<YamlNode>('name', taskNode); if (nameValue) { const name = nameValue.raw?.trim(); decTask.name = name; decTask.id = name; decTask.position = nameValue.startPosition; } const retryValue = findNodeByKey<YamlNode>('retries', taskNode); if (retryValue) { const retry = retryValue.raw?.trim(); decTask.retry = Number.parseInt(retry); } const [, taskRef] = pipelineYaml.getTaskRef(taskNode) ?? []; if (taskRef) { const taskRefName = findNodeByKey<YamlNode>('name', taskRef); decTask.taskRef = taskRefName.raw.trim(); const kindName = findNodeByKey<YamlNode>('kind', taskRef); if (kindName) { decTask.kind = kindName.raw; } else { decTask.kind = 'Task'; } } else { const taskSpec = findNodeByKey<YamlMap>('taskSpec', taskNode); if (taskSpec) { decTask.kind = 'TaskSpec'; const steps = findNodeByKey<YamlSequence>('steps', taskSpec); if (steps) { decTask.steps = []; for (const step of steps.items) { const name = findNodeByKey<YamlNode>('name', step as YamlMap); if (name) { decTask.steps.push({name: name.raw}); } } } } } return decTask; } function collectWhen(taskNode: YamlMap, tasks: DeclaredTask[], taskName: string): void { const whens = findNodeByKey<YamlSequence>('when', taskNode); if (whens) { for ( const when of whens.items){ const input = findNodeByKey<YamlNode>('input', when as YamlMap); if (input) { const inputVal = _.trim(input.raw, '"'); const whenDec = {id: `${taskName}:${inputVal}`, kind: 'When', position: input.startPosition} as DeclaredTask; const runAfter = []; const runAfterMap = extractTaskName(inputVal); if (runAfterMap) { runAfter.push(...runAfterMap.map( v => v[0])); } runAfter.push(...getTaskRunAfter(taskNode)); whenDec.runAfter = runAfter; tasks.push(whenDec); } } } } function collectConditions(taskNode: YamlMap, tasks: DeclaredTask[]): void { const conditions = findNodeByKey<YamlSequence>('conditions', taskNode); if (conditions) { for (const condition of conditions.items) { const ref = findNodeByKey<YamlNode>('conditionRef', condition as YamlMap); if (ref) { const name = _.trim(ref.raw, '"'); const conditionDec = { id: name, name: name, kind: 'Condition', position: ref.startPosition } as DeclaredTask; const runAfter = []; const conditions = findNodeByKey<YamlSequence>('conditions', taskNode); if (conditions) { for (const condition of conditions.items) { const resources = findNodeByKey<YamlSequence>('resources', condition as YamlMap); if (resources) { for (const res of resources.items) { const fromKey = findNodeByKey<YamlSequence>('from', res as YamlMap); if (fromKey) { for (const key of fromKey.items) { if (key.kind === 'SCALAR') { runAfter.push(key.raw.trim()); } } } } } } } runAfter.push(...getTaskRunAfter(taskNode)); conditionDec.runAfter = runAfter; tasks.push(conditionDec); } } } } function collectRunAfter(taskNode: YamlMap, name: string): string[] { const result: string[] = []; const resources = findNodeByKey<YamlMap>('resources', taskNode); if (resources) { const inputs = findNodeByKey<YamlSequence>('inputs', resources); if (inputs) { for (const input of inputs.items) { const fromKey = findNodeByKey<YamlSequence>('from', input as YamlMap); if (fromKey) { for (const key of fromKey.items) { if (key.kind === 'SCALAR') { result.push(key.raw); } } } } } } const conditions = findNodeByKey<YamlSequence>('conditions', taskNode); if (conditions) { for (const condition of conditions.items) { const ref = getYamlMappingValue(condition as YamlMap, 'conditionRef'); if (ref) { result.push(_.trim(ref, '"')); } } } const whens = findNodeByKey<YamlSequence>('when', taskNode); if (whens) { for (const when of whens.items) { const input = getYamlMappingValue(when as YamlMap, 'input'); if (input) { result.push(`${name}:${_.trim(input, '"')}`); } } } const params = findNodeByKey<YamlSequence>('params', taskNode); if (params) { for (const param of params.items){ const val = findNodeByKey<YamlNode>('value', param as YamlMap); if (val){ const inputVal = _.trim(val.raw, '"'); const task = extractTaskName(inputVal); if (task){ result.push(...task.map( v => v[0])); } } } } if (!conditions && !whens) { const runAfter = getTaskRunAfter(taskNode); result.push(...runAfter); } return result; } function getTaskRunAfter(taskNode: YamlMap): string[] { const result = []; const runAfter = findNodeByKey<YamlSequence>('runAfter', taskNode); if (runAfter) { for (const run of runAfter.items) { if (run.kind === 'SCALAR') { result.push(_.trim(run.raw.trim(), '"')); } } } return result; } const taskNameAndResultReg = /\$\(tasks\.(?<taskName>[a-zA-Z\d-]+)\.results\.(?<resultName>[a-zA-Z\d-]+)\)/; const varSubstitution = /\$\([a-zA-Z\d\\.-]+\)/g; function extractTaskName(variable: string): [string, string][] | undefined { if (!variable) { return undefined; } const result: [string, string][] = []; // TODO: replace this with String.matchAll call, it available on Node.js 12.0.0 const vars = variable.match(varSubstitution); if (!vars){ return undefined; } for (const tknVar of vars) { const group = tknVar.match(taskNameAndResultReg)?.groups; if (group) { result.push([group.taskName, group.resultName]); } } return result; } function getPipelineRunTaskState(status: YamlMap): RunState { let result: RunState = 'Unknown'; const startTime = findNodeByKey<YamlNode>('startTime', status); if (startTime) { result = 'Started'; } const conditionStatus = findNodeByKey<YamlSequence>('conditions', status); if (conditionStatus) { const status = findNodeByKey<YamlNode>('status', conditionStatus.items[0] as YamlMap); if (status) { if (status.raw === '"True"') { result = 'Finished'; } else if (status.raw === '"False"') { const reason = findNodeByKey<YamlNode>('reason', conditionStatus.items[0] as YamlMap); if (reason?.raw === 'TaskRunCancelled') { result = 'Cancelled'; } else { result = 'Failed'; } } } } return result; } function getDeclaredResource(resMap: YamlMap): DeclaredResource { let name: string, type: string; for (const item of resMap.mappings) { if (item.key.raw === 'name') { name = item.value.raw; } if (item.key.raw === 'type') { type = item.value.raw; } } return { name, type }; } function getSpecMap(rootMap: YamlMap): YamlMap | undefined { return findNodeByKey<YamlMap>('spec', rootMap); } function getTasksSeq(specMap: YamlMap): YamlSequence | undefined { return findNodeByKey<YamlSequence>('tasks', specMap); } export function findNodeAndKeyByKeyValue<K, T>(key: string, yamlMap: YamlMap): [K, T] | undefined { if (!yamlMap || !yamlMap.mappings) { return; } const mapItem = yamlMap.mappings.find(item => item.key.raw === key); if (mapItem) { return [mapItem.key as unknown as K, mapItem.value as unknown as T]; } return undefined; } export function findNodeByKey<T>(key: string, yamlMap: YamlMap): T | undefined { if (!yamlMap || !yamlMap.mappings) { return undefined; } const mapItem = yamlMap.mappings.find(item => item.key.raw === key); if (mapItem) { return mapItem.value as unknown as T; } return undefined; } function getTasksRefName(tasks: YamlNode[]): string[] { const result = []; for (const taskNode of tasks) { if (taskNode.kind === 'MAPPING') { const taskRef = findNodeByKey<YamlMap>('taskRef', taskNode as YamlMap); if (taskRef) { const nameValue = findNodeByKey<YamlNode>('name', taskRef); result.push(nameValue.raw); } } } return result; } function getTasksName(tasks: YamlNode[]): string[] { const result = []; for (const taskNode of tasks) { if (taskNode.kind === 'MAPPING') { const nameValue = findNodeByKey<YamlNode>('name', taskNode as YamlMap); if (nameValue) { result.push(nameValue.raw.trim()); } } } return result; } export enum StringComparison { Ordinal, OrdinalIgnoreCase } // test whether two strings are equal ignore case export function equalIgnoreCase(a: string, b: string): boolean { return _.isString(a) && _.isString(b) && a.toLowerCase() === b.toLowerCase(); } // Get the string value of key in a yaml mapping node(parsed by node-yaml-parser) // eg: on the following yaml, this method will return 'value1' for key 'key1' // // key1: value1 // key2: value2 // export function getYamlMappingValue(mapRootNode: YamlMap, key: string, ignoreCase: StringComparison = StringComparison.Ordinal): string | undefined { // TODO, unwrap quotes if (!key) { return undefined; } const keyValueItem = mapRootNode.mappings.find((mapping) => mapping.key && (ignoreCase === StringComparison.OrdinalIgnoreCase ? key === mapping.key.raw : equalIgnoreCase(key, mapping.key.raw))); return keyValueItem ? keyValueItem.value.raw : undefined; }
the_stack
import { Component, ViewChild } from '@angular/core'; import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { SprkIconComponent } from '../sprk-icon/sprk-icon.component'; import { SprkLinkDirective } from '../../directives/sprk-link/sprk-link.directive'; import { SprkMastheadAccordionComponent } from './components/sprk-masthead-accordion/sprk-masthead-accordion.component'; import { SprkMastheadAccordionItemComponent } from './components/sprk-masthead-accordion-item/sprk-masthead-accordion-item.component'; import { SprkMastheadSelectorComponent } from './components/sprk-masthead-selector/sprk-masthead-selector.component'; import { SprkMastheadComponent } from './sprk-masthead.component'; import { SprkMastheadNavCollapsibleDirective } from './directives/sprk-masthead-nav-collapsible/sprk-masthead-nav-collapsible.directive'; import { SprkMastheadBrandingDirective } from './directives/sprk-masthead-branding/sprk-masthead-branding.directive'; import { SprkMastheadNavItemsDirective } from './directives/sprk-masthead-nav-items/sprk-masthead-nav-items.directive'; import { SprkMastheadNavItemDirective } from './directives/sprk-masthead-nav-item/sprk-masthead-nav-item.directive'; import { SprkMastheadNavCollapsibleButtonComponent } from './components/sprk-masthead-nav-collapsible-button/sprk-masthead-nav-collapsible-button.component'; import { SprkDropdownComponent } from '../sprk-dropdown/sprk-dropdown.component'; import { SprkStackComponent } from '../sprk-stack/sprk-stack.component'; import { SprkStackItemDirective } from '../../directives/sprk-stack-item/sprk-stack-item.directive'; import { SprkMastheadLinkDirective } from './directives/sprk-masthead-link/sprk-masthead-link.directive'; import { Router, NavigationEnd, RouterEvent } from '@angular/router'; import { ReplaySubject } from 'rxjs'; @Component({ selector: 'sprk-test', template: ` <sprk-masthead> <div sprkMastheadBranding sprkStackItem class="sprk-o-Stack__item--center-column@xxs" > <a sprkLink href="#nogo" variant="unstyled"> <svg class="sprk-c-Masthead__logo" xmlns="http://www.w3.org/2000/svg" width="365.4" height="48" viewBox="0 0 365.4 101.35" ></svg> </a> </div> <div sprkMastheadNavItem sprkStackItem class="sprk-o-Stack__item--center-column@xxs" > <a sprkMastheadLink href="#nogo"> Sign In </a> </div> <nav sprkMastheadNavItems sprkStackItem role="navigation" class="sprk-o-Stack__item--flex@xxs sprk-o-Stack sprk-o-Stack--misc-a sprk-o-Stack--split@xxs sprk-o-Stack--end-row" > <div sprkStackItem class="sprk-o-Stack__item--flex@xxs"> <sprk-stack additionalClasses="sprk-o-Stack--center-column sprk-o-Stack--center-row" > <div sprkStackItem class="sprk-u-Position--relative"> <sprk-masthead-selector triggerText="Choose One" heading="Choose One" triggerIconName="chevron-down" [choices]="selectorDropdown" > <div class="sprk-c-Masthead__selector-footer" sprkMastheadSelectorFooter > <a sprkLink variant="unstyled" href="#nogo" class="sprk-c-Button sprk-c-Button--secondary sprk-c-Button--compact" > Placeholder </a> </div> </sprk-masthead-selector> </div> </sprk-stack> </div> <ul sprkStackItem class=" sprk-o-HorizontalList sprk-o-HorizontalList--spacing-medium sprk-o-Stack--center-column " > <li> <a sprkMastheadLink href="#nogo"> Talk To Us </a> </li> <li> <sprk-dropdown [choices]="talkToUsDropdownChoices" heading="My Account" triggerIconName="user" triggerAdditionalClasses="sprk-b-Link--plain sprk-c-Masthead__link" iconAdditionalClasses="sprk-c-Icon--xl" additionalClasses="sprk-u-Right--zero sprk-u-mrm" screenReaderText="User Account" > </sprk-dropdown> </li> </ul> </nav> <div sprkStackItem> <nav sprkMastheadNavBar sprkStackItem role="navigation"> <ul class="sprk-c-Masthead__nav-bar-items sprk-o-Stack sprk-o-Stack--misc-a sprk-o-Stack--center-row sprk-o-Stack--split@xxs sprk-b-List sprk-b-List--bare" > <li sprkStackItem class="sprk-c-Masthead__nav-bar-item"> <a sprkMastheadLink variant="navBar" analyticsString="nav-bar-item-1" href="#nogo" > Item One </a> </li> <li sprkStackItem class="sprk-c-Masthead__nav-bar-item" aria-haspopup="true" > <sprk-dropdown [choices]="item2NavBarDropdownChoices" triggerAdditionalClasses="sprk-b-Link--simple sprk-c-Masthead__link sprk-c-Masthead__link--nav-bar" additionalClasses="sprk-u-TextAlign--left" triggerIconName="chevron-down" analyticsString="nav-bar-item-2" triggerText="Item Two" ></sprk-dropdown> </li> <li sprkStackItem class="sprk-c-Masthead__nav-bar-item"> <a sprkMastheadLink variant="navBar" analyticsString="nav-bar-item-3" href="#nogo" > Item Three </a> </li> <li sprkStackItem class="sprk-c-Masthead__nav-bar-item" aria-haspopup="true" > <sprk-dropdown [choices]="item2NavBarDropdownChoices" triggerAdditionalClasses="sprk-b-Link--simple sprk-c-Masthead__link sprk-c-Masthead__link--nav-bar" additionalClasses="sprk-u-TextAlign--left" triggerIconName="chevron-down" analyticsString="nav-bar-item-4" triggerText="Item Four" ></sprk-dropdown> </li> <li sprkStackItem class="sprk-c-Masthead__nav-bar-item"> <a sprkMastheadLink variant="navBar" analyticsString="nav-bar-item-5" href="#nogo" > Item Five </a> </li> </ul> </nav> </div> <nav sprkMastheadNavCollapsible role="navigation" idString="extended-collapsible-nav" aria-label="collapsible" > <sprk-masthead-selector triggerText="Choose One" heading="Choose One" triggerIconName="chevron-down" [choices]="narrowSelectorDropdown" isFlush="true" > <div class="sprk-c-Masthead__selector-footer" sprkMastheadSelectorFooter > <a sprkLink variant="unstyled" analyticsString="placeholder-button" href="#nogo" class="sprk-c-Button sprk-c-Button--secondary" > Placeholder </a> </div> </sprk-masthead-selector> <sprk-masthead-accordion> <sprk-masthead-accordion-item heading="Item 1"> <ul class="sprk-b-List sprk-b-List--bare sprk-c-MastheadAccordion__details" > <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" href="#nogo" analyticsString="accordion-item-1" > Item 1 </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" href="#nogo" analyticsString="accordion-item-2" > Item 2 </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" href="#nogo" analyticsString="accordion-item-3" > Item 3 </a> </li> </ul> </sprk-masthead-accordion-item> <li class="sprk-c-MastheadAccordion__item sprk-c-MastheadAccordion__item--active" > <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" > <span class="sprk-c-MastheadAccordion__heading">Item 2</span> </a> </li> <sprk-masthead-accordion-item heading="Item 3"> <ul class="sprk-b-List sprk-b-List--bare sprk-c-MastheadAccordion__details" > <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" href="#nogo" > Item 1 </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" href="#nogo" > Item 2 </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" href="#nogo" > Item 3 </a> </li> </ul> </sprk-masthead-accordion-item> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" > <span class="sprk-c-MastheadAccordion__heading">Item 4</span> </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" > <span class="sprk-c-MastheadAccordion__heading">Item 5</span> </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" > <span class="sprk-c-MastheadAccordion__heading"> <sprk-icon iconName="landline" additionalClasses=" sprk-c-Icon--filled-current-color sprk-c-Icon--stroke-current-color sprk-c-Icon--xl sprk-u-mrs " ></sprk-icon> (555) 555-5555 </span> </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" > <span class="sprk-c-MastheadAccordion__heading"> <sprk-icon iconName="call-team-member" additionalClasses=" sprk-c-Icon--filled-current-color sprk-c-Icon--stroke-current-color sprk-c-Icon--xl sprk-u-mrs " ></sprk-icon> Talk To Us </span> </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" > <span class="sprk-c-MastheadAccordion__heading"> <sprk-icon iconName="settings" additionalClasses=" sprk-c-Icon--filled-current-color sprk-c-Icon--stroke-current-color sprk-c-Icon--xl sprk-u-mrs " ></sprk-icon> Settings </span> </a> </li> <sprk-masthead-accordion-item heading="My Account" leadingIcon="user"> <ul class="sprk-b-List sprk-b-List--bare sprk-c-MastheadAccordion__details" > <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" href="#nogo" analyticsString="change-username" > Change Username </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" href="#nogo" analyticsString="change-password" > Change Password </a> </li> <li class="sprk-c-MastheadAccordion__item"> <a sprkLink variant="unstyled" class="sprk-c-MastheadAccordion__summary" href="#nogo" analyticsString="sign-out" > Sign Out </a> </li> </ul> </sprk-masthead-accordion-item> </sprk-masthead-accordion> </nav> </sprk-masthead> `, }) class Test1Component { @ViewChild(SprkMastheadComponent, { static: false, }) masthead: SprkMastheadComponent; } @Component({ selector: 'sprk-test-2', template: ` <sprk-masthead> <div sprkMastheadBranding sprkStackItem class="sprk-u-TextAlign--left"> <a sprkLink href="#nogo" variant="unstyled"> <svg class="sprk-c-Masthead__logo sprk-u-TextAlign--left" xmlns="http://www.w3.org/2000/svg" width="365.4" height="48" viewBox="0 0 365.4 101.35" ></svg> </a> </div> <div sprkMastheadNavItem sprkStackItem class="sprk-o-Stack__item--center-column@xxs" > <a sprkMastheadLink href="#nogo"> Talk To Us </a> </div> <nav sprkMastheadNavItems sprkStackItem role="navigation" class="sprk-o-Stack__item--flex@xxs sprk-o-Stack sprk-o-Stack--misc-a sprk-o-Stack--split@xxs sprk-o-Stack--end-row" > <ul sprkStackItem class=" sprk-o-HorizontalList sprk-o-HorizontalList--spacing-medium sprk-o-Stack--center-column " > <li> <a sprkMastheadLink href="#nogo"> Talk To Us </a> </li> <li> <sprk-dropdown [choices]="talkToUsDropdownChoices" heading="My Account" triggerIconName="user" triggerAdditionalClasses="sprk-b-Link--plain sprk-c-Masthead__link" iconAdditionalClasses="sprk-c-Icon--xl" additionalClasses="sprk-u-Right--zero sprk-u-mrm" screenReaderText="User Account" > </sprk-dropdown> </li> </ul> </nav> </sprk-masthead> `, }) class Test2Component { @ViewChild(SprkMastheadComponent, { static: false, }) masthead: SprkMastheadComponent; } describe('SprkMastheadComponent', () => { let component: Test1Component; let componentFixture: ComponentFixture<Test1Component>; let componentElement: HTMLElement; let collapsibleNavButton: HTMLElement; let collapsibleNavEl: HTMLElement; let componentNoCollapsibleNav: Test1Component; let componentFixtureNoCollapsibleNav: ComponentFixture<Test2Component>; let componentElementNoCollapsibleNav: HTMLElement; let collapsibleNavButtonNoCollapsibleNav: HTMLElement; let collapsibleNavElNoCollapsibleNav: HTMLElement; let eventsSub = new ReplaySubject<RouterEvent>(1); let windowSpy; const routerStub = { events: eventsSub, url: '/test', }; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [BrowserAnimationsModule, RouterTestingModule.withRoutes([])], providers: [{ provide: Router, useValue: routerStub }], declarations: [ SprkMastheadComponent, SprkIconComponent, SprkLinkDirective, SprkDropdownComponent, SprkMastheadAccordionComponent, SprkMastheadAccordionItemComponent, SprkMastheadSelectorComponent, SprkStackComponent, Test1Component, Test2Component, SprkStackItemDirective, SprkMastheadNavItemsDirective, SprkMastheadNavItemDirective, SprkMastheadLinkDirective, SprkMastheadNavCollapsibleDirective, SprkMastheadNavCollapsibleButtonComponent, SprkMastheadBrandingDirective, ], }).compileComponents(); })); beforeEach(() => { componentFixture = TestBed.createComponent(Test1Component); component = componentFixture.componentInstance; componentFixture.detectChanges(); componentElement = componentFixture.nativeElement.querySelector( '.sprk-c-Masthead', ); collapsibleNavEl = componentFixture.nativeElement.querySelector( '.sprk-c-Masthead__nav-collapsible', ); collapsibleNavButton = componentFixture.debugElement.nativeElement.querySelector( 'button', ); componentFixtureNoCollapsibleNav = TestBed.createComponent(Test2Component); componentNoCollapsibleNav = componentFixtureNoCollapsibleNav.componentInstance; componentFixtureNoCollapsibleNav.detectChanges(); componentElementNoCollapsibleNav = componentFixtureNoCollapsibleNav.nativeElement.querySelector( '.sprk-c-Masthead', ); collapsibleNavElNoCollapsibleNav = componentFixtureNoCollapsibleNav.nativeElement.querySelector( '.sprk-c-Masthead__nav-collapsible', ); collapsibleNavButtonNoCollapsibleNav = componentFixtureNoCollapsibleNav.debugElement.nativeElement.querySelector( 'button', ); windowSpy = jest.spyOn(window, 'window', 'get'); }); afterEach(() => { windowSpy.mockRestore(); component.masthead.currentScrollDirection = 'up'; component.masthead.isMastheadHidden = false; component.masthead.isPageScrolled = false; component.masthead.isNarrowViewport = false; component.masthead.isNarrowViewportOnResize = false; window.document.body.style.minHeight = '800px'; window.document.body.style.minWidth = '1024px'; }); it('should create itself', () => { expect(component).toBeTruthy(); }); it('should add classes when additionalClasses has a value', () => { component.masthead.additionalClasses = 'sprk-u-man'; componentFixture.detectChanges(); expect(componentElement.classList.toString()).toEqual( 'sprk-c-Masthead sprk-o-Stack sprk-u-man', ); }); it('should show the menu icon if a collapsible nav is present', () => { expect(collapsibleNavButton).toBeTruthy(); }); it('should not show the menu icon if there is no collapsible nav', () => { expect(collapsibleNavButtonNoCollapsibleNav).toBeNull(); expect(collapsibleNavElNoCollapsibleNav).toBeNull(); }); it('should pass the collapsible nav ID to the collapsible nav button component aria-controls attribute', () => { const buttonId = collapsibleNavButton.getAttribute('aria-controls'); const navId = collapsibleNavEl.id; expect(buttonId).toEqual(navId); }); it('should pass the collapsible nav button screen reader text to the collapsible nav button if present', () => { const buttonText = collapsibleNavButton.querySelector('span'); component.masthead.collapsibleNavButtonScreenReaderText = 'test-text'; componentFixture.detectChanges(); expect(buttonText.textContent).toEqual('test-text'); }); it('should set the collapsible nav isCollapsed prop to false when button is clicked and was closed before clicked', () => { // expect the collapsible nav to be closed at first with having the is-collapsed class expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); // click the collapsible nav button which runs the open method collapsibleNavButton.click(); componentFixture.detectChanges(); // child directive isCollapsed should now be false, which opens the collapsible nav expect(component.masthead.collapsibleNavDirective.isCollapsed).toBe(false); expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible', ); }); it('should close the collapsible nav when the collapsible nav button is clicked and was open before clicked', () => { // click the collapsible nav button which runs the open method collapsibleNavButton.click(); componentFixture.detectChanges(); // expect the collapsible nav to be open at first without having the is-collapsed class expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible', ); // click the collapsible nav button which runs the close method collapsibleNavButton.click(); componentFixture.detectChanges(); // child directive isCollapsed should now be true, which close the collapsible nav expect(component.masthead.collapsibleNavDirective.isCollapsed).toBe(true); expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); }); it(` should add the aria-expanded attribute to collapsible nav button and show the collapsible nav when the icon is clicked `, () => { expect(collapsibleNavButton.getAttribute('aria-expanded')).toEqual('false'); expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); collapsibleNavButton.click(); componentFixture.detectChanges(); expect(collapsibleNavButton.getAttribute('aria-expanded')).toEqual('true'); expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible', ); }); it('should add a class to body and show the collapsible nav when the collapsible button is clicked', () => { expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); collapsibleNavButton.click(); componentFixture.detectChanges(); expect(document.body.classList.contains('sprk-u-Overflow--hidden')).toEqual( true, ); expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible', ); collapsibleNavButton.click(); componentFixture.detectChanges(); expect(document.body.classList.contains('sprk-u-Overflow--hidden')).toEqual( false, ); expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); }); it('should remove class from body and hide the collapsible nav when the collapsible nav is closed', () => { // Open it collapsibleNavButton.click(); componentFixture.detectChanges(); // Should be open now expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible', ); expect(document.body.classList.toString()).toEqual( 'sprk-u-Overflow--hidden sprk-u-Height--100', ); expect(document.documentElement.classList.toString()).toEqual( 'sprk-u-Overflow--hidden sprk-u-Height--100', ); // We click to close it collapsibleNavButton.click(); componentFixture.detectChanges(); // Classes on the body and HTML should be removed expect(document.body.classList.toString()).toEqual(''); expect(document.documentElement.classList.toString()).toEqual(''); expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); }); it('should close the collapsible nav when viewport expands to large from small', () => { component.masthead.isMastheadHidden = true; component.masthead.collapsibleNavDirective.isCollapsed = false; component.masthead.isNarrowViewport = true; component.masthead.isNarrowViewportOnResize = false; component.masthead.updateLayoutState(); componentFixture.detectChanges(); expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); expect(component.masthead.isMastheadHidden).toBe(false); expect(component.masthead.collapsibleNavDirective.isCollapsed).toBe(true); }); it('should add data-id when idString has a value', () => { const testString = 'element-id'; component.masthead.idString = testString; componentFixture.detectChanges(); expect(componentElement.getAttribute('data-id')).toEqual(testString); }); it('should not add data-id when idString has no value', () => { component.masthead.idString = null; componentFixture.detectChanges(); expect(componentElement.getAttribute('data-id')).toBeNull(); }); it('should add the scroll class when state isPageScrolled is true', () => { component.masthead.isPageScrolled = true; componentFixture.detectChanges(); expect(componentElement.classList.toString()).toEqual( 'sprk-c-Masthead sprk-o-Stack sprk-c-Masthead--is-scrolled', ); }); it('should remove the scroll class when state isPageScrolled is false', () => { component.masthead.isPageScrolled = false; componentFixture.detectChanges(); expect(componentElement.classList.toString()).toEqual( 'sprk-c-Masthead sprk-o-Stack', ); }); it("should not add the scrolled class if they don't scroll past 10 in the scrollY position", () => { Object.defineProperty(window, 'scrollY', { value: 9, writable: true }); window.dispatchEvent(new Event('scroll')); componentFixture.detectChanges(); expect(componentElement.classList.toString()).toEqual( 'sprk-c-Masthead sprk-o-Stack sprk-c-Masthead--is-hidden', ); }); it('should add the scrolled class if they scroll past 10 in the scrollY position', () => { Object.defineProperty(window, 'scrollY', { value: 11, writable: true }); window.dispatchEvent(new Event('scroll')); componentFixture.detectChanges(); expect(componentElement.classList.toString()).toEqual( 'sprk-c-Masthead sprk-o-Stack sprk-c-Masthead--is-scrolled sprk-c-Masthead--is-hidden', ); }); it('should not add the scrolled class if the scroll position is less than 0', () => { Object.defineProperty(window, 'scrollY', { value: -1, writable: true }); window.dispatchEvent(new Event('scroll')); componentFixture.detectChanges(); expect(componentElement.classList.toString()).toEqual( 'sprk-c-Masthead sprk-o-Stack', ); }); it('should add the hidden class when state isPageScrolled is true and isMastheadHidden is true and on small viewports', () => { component.masthead.isMastheadHidden = true; component.masthead.isPageScrolled = true; window.document.body.style.minWidth = '320px'; componentFixture.detectChanges(); expect(componentElement.classList.toString()).toEqual( 'sprk-c-Masthead sprk-o-Stack sprk-c-Masthead--is-scrolled sprk-c-Masthead--is-hidden', ); }); it('should not add the hidden class when state isPageScrolled is true and isMastheadHidden is false and on small viewports', () => { component.masthead.isMastheadHidden = false; component.masthead.isPageScrolled = true; componentFixture.detectChanges(); window.document.body.style.minWidth = '320px'; expect(componentElement.classList.toString()).toEqual( 'sprk-c-Masthead sprk-o-Stack sprk-c-Masthead--is-scrolled', ); }); it('should update state isMastheadHidden to true when currentScrollDirection is equal to down', () => { // Expect masthead to be shown originally expect(component.masthead.isMastheadHidden).toBe(false); // Scroll down the page const scrollEvent = document.createEvent('CustomEvent'); scrollEvent.initCustomEvent('scroll', false, false, null); Object.defineProperty(window, 'scrollY', { value: 456, writable: true }); window.dispatchEvent(scrollEvent); componentFixture.detectChanges(); expect(component.masthead.currentScrollDirection).toBe('down'); expect(component.masthead.isMastheadHidden).toBe(true); }); it('should update state isMastheadHidden to false when currentScrollDirection is equal to up', () => { component.masthead.currentScrollPosition = 200; const scrollEvent2 = document.createEvent('CustomEvent'); scrollEvent2.initCustomEvent('scroll', false, false, null); Object.defineProperty(window, 'scrollY', { value: 20, writable: true }); window.dispatchEvent(scrollEvent2); componentFixture.detectChanges(); expect(component.masthead.currentScrollDirection).toBe('up'); expect(component.masthead.isMastheadHidden).toBe(false); }); it('should call throttledUpdateLayoutState on resize', () => { const spyOnResize = jest.spyOn( component.masthead, 'throttledUpdateLayoutState', ); window.dispatchEvent(new Event('resize')); expect(spyOnResize).toHaveBeenCalled(); }); it('should close the collapsible nav on orientationchange', () => { // Should be closed first expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); // Set it to open collapsibleNavButton.click(); componentFixture.detectChanges(); // We expect it to be open expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible', ); // We expect the overflow class to be added to the body tag expect(document.body.classList.contains('sprk-u-Overflow--hidden')).toEqual( true, ); // Fire the event on the window window.dispatchEvent(new Event('orientationchange')); componentFixture.detectChanges(); // We expect the component to detect the event and close the collapsible nav expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); // We expect the class that was added to the body to be removed expect(document.body.classList.contains('sprk-u-Overflow--hidden')).toEqual( false, ); }); it('should have isPageScrolled as false upon load', () => { expect(component.masthead.isPageScrolled).toBe(false); }); it('should have isMastheadHidden as false upon load', () => { expect(component.masthead.isMastheadHidden).toBe(false); }); it('should have isNarrowViewportOnResize as false upon load', () => { expect(component.masthead.isNarrowViewportOnResize).toBe(false); }); it('should have currentScrollDirection as "up" upon load', () => { expect(component.masthead.currentScrollDirection).toBe('up'); }); it('should have currentScrollDirection as 0 upon load', () => { expect(component.masthead.currentScrollPosition).toBe(0); }); it('should close the open collapsible nav when user goes to a new page', () => { // We expect it to be closed and have the collapsed CSS class expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); expect(component.masthead.collapsibleNavDirective.isCollapsed).toBe(true); // We open the collapsible nav collapsibleNavButton.click(); componentFixture.detectChanges(); // We expect it to be open and not have the collapsed CSS class expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible', ); expect(component.masthead.collapsibleNavDirective.isCollapsed).toBe(false); // We use the router to navigate the page and fire the navigation end event const navigate = new NavigationEnd(1, 'old-route', 'new-route'); eventsSub.next(navigate); componentFixture.detectChanges(); // We expect the collapsible nav to be collapsed since we are on a new page expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); }); it('should close the collapsible nav when viewport expands to large from small', () => { component.masthead.isMastheadHidden = true; component.masthead.collapsibleNavDirective.isCollapsed = false; component.masthead.isNarrowViewport = true; component.masthead.isNarrowViewportOnResize = false; component.masthead.updateLayoutState(); componentFixture.detectChanges(); expect(collapsibleNavEl.classList.toString()).toEqual( 'sprk-c-Masthead__nav-collapsible sprk-c-Masthead__nav-collapsible--is-collapsed', ); expect(component.masthead.isMastheadHidden).toBe(false); expect(component.masthead.collapsibleNavDirective.isCollapsed).toBe(true); }); it('should update internal state for collapsible nav if is it open on load', () => { component.masthead.collapsibleNavDirective.isCollapsed = false; componentFixture.detectChanges(); component.masthead.ngAfterViewInit(); expect(component.masthead.collapsibleNavDirective.isCollapsed).toBe(false); expect(component.masthead.isCollapsibleNavOpen).toBe(true); }); it('should not update scroll direction if window is undefined', () => { windowSpy.mockImplementation(() => undefined); expect(window).toBeUndefined(); component.masthead.currentScrollPosition = 10; component.masthead.getVerticalScrollDirection(); expect(component.masthead.currentScrollPosition).toBe(10); }); });
the_stack
import expat = require("node-expat"); // let expat = require('../lib/node-expat') import Iconv = require('iconv'); // import vows = require('vows'); // let assert = require('assert') import fs = require('fs'); import path = require('path'); import debug = require('debug'); const log = debug.debug.log; // ('test/index'); function collapseTexts(evs: string[]) { const r = []; let t = ''; evs.forEach((ev) => { if (ev[0] === 'text') { t += ev[1]; } else { if (t !== '') { r.push([ 'text', t ]); } t = ''; r.push(ev); } }); if (t !== '') { r.push([ 'text', t ]); } return r; } function expectParsed(s: string | Buffer, evsExpected: any[]) { for (let step = s.length; step > 0; step--) { expectWithParserAndStep(s, evsExpected, new expat.Parser(), step); } } function expectWithParserAndStep(s: string | Buffer, evsExpected: any[], p: expat.Parser, step: number) { const evsReceived: any[] = []; p.addListener('startElement', (name, attrs) => { evsReceived.push(['startElement', name, attrs]); }); p.addListener('endElement', (name) => { evsReceived.push(['endElement', name]); }); p.addListener('text', (s) => { evsReceived.push(['text', s]); }); p.addListener('processingInstruction', (target, data) => { evsReceived.push(['processingInstruction', target, data]); }); p.addListener('comment', (s) => { evsReceived.push(['comment', s]); }); p.addListener('xmlDecl', (version, encoding, standalone) => { evsReceived.push(['xmlDecl', version, encoding, standalone]); }); p.addListener('startCdata', () => { evsReceived.push(['startCdata']); }); p.addListener('endCdata', () => { evsReceived.push(['endCdata']); }); p.addListener('entityDecl', (entityName, isParameterEntity, value, base, systemId, publicId, notationName) => { evsReceived.push(['entityDecl', entityName, isParameterEntity, value, base, systemId, publicId, notationName]); }); p.addListener('error', (e) => { evsReceived.push(['error', e]); }); for (let l = 0; l < s.length; l += step) { let end = l + step; if (end > s.length) { end = s.length; } p.write(s.slice(l, end)); } const expected = JSON.stringify(evsExpected); const received = JSON.stringify(collapseTexts(evsReceived)); expect(received).toEqual(expected); } describe('node-expat', () => { // single elements it('should parse simple element', () => { expectParsed('<r/>', [['startElement', 'r', {}], ['endElement', 'r']]); }); it('should parse single element with attribute', () => { expectParsed("<r foo='bar'/>", [['startElement', 'r', {foo: 'bar'}], ['endElement', 'r']]); }); it('should parse single element with differently quoted attributes', () => { expectParsed('<r foo=\'bar\' baz="quux" test="tset"/>', [['startElement', 'r', {foo: 'bar', baz: 'quux', test: 'tset'}], ['endElement', 'r']]); }); it('should parse single element with namespaces', () => { expectParsed('<r xmlns=\'http://localhost/\' xmlns:x="http://example.com/"></r>', [['startElement', 'r', {xmlns: 'http://localhost/', 'xmlns:x': 'http://example.com/'}], ['endElement', 'r']]); }); it('should parse single element with text content', () => { expectParsed('<r>foo</r>', [['startElement', 'r', {}], ['text', 'foo'], ['endElement', 'r']]); }); it('should parse single element with text content and line break', () => { expectParsed('<r>foo\nbar</r>', [['startElement', 'r', {}], ['text', 'foo\nbar'], ['endElement', 'r']]); }); it('should parse single element with CDATA content', () => { expectParsed('<r><![CDATA[<greeting>Hello, world!</greeting>]]></r>', [['startElement', 'r', {}], ['startCdata'], ['text', '<greeting>Hello, world!</greeting>'], ['endCdata'], ['endElement', 'r']]); }); it('should parse single element with entity text', () => { expectParsed('<r>foo&amp;bar</r>', [['startElement', 'r', {}], ['text', 'foo&bar'], ['endElement', 'r']]); }); it('should parse single element with umlaut text', () => { expectParsed('<r>ß</r>', [['startElement', 'r', {}], ['text', 'ß'], ['endElement', 'r']]); }); it('should parse from buffer', () => { expectParsed(Buffer.from('<foo>bar</foo>'), [['startElement', 'foo', {}], ['text', 'bar'], ['endElement', 'foo']]); }); // entity declaration it('should parse a billion laughs entity declaration', () => { expectParsed('<!DOCTYPE b [<!ELEMENT b (#PCDATA)>' + '<!ENTITY l0 "ha"><!ENTITY l1 "&l0;&l0;"><!ENTITY l2 "&l1;&l1;">' + ']><b>&l2;</b>', [['entityDecl', 'l0', false, 'ha', null, null, null, null], ['entityDecl', 'l1', false, '&l0;&l0;', null, null, null, null], ['entityDecl', 'l2', false, '&l1;&l1;', null, null, null, null], ['startElement', 'b', {}], ['text', 'hahahaha'], ['endElement', 'b']]); }); // processing instruction it('should parse processing instruction with parameters', () => { expectParsed('<?i like xml?>', [['processingInstruction', 'i', 'like xml']]); }); it('should parse simple processing instruction', () => { expectParsed('<?dragons?>', [['processingInstruction', 'dragons', '']]); }); it('should parse XML declaration with encoding', () => { expectParsed("<?xml version='1.0' encoding='UTF-8'?>", [['xmlDecl', '1.0', 'UTF-8', true]]); }); it('should parse XML declaration', () => { expectParsed("<?xml version='1.0'?>", [['xmlDecl', '1.0', null, true]]); }); // comment it('should parse simple comment', () => { expectParsed('<!-- no comment -->', [['comment', ' no comment ']]); }); // unknownEncoding with single-byte map it('should parse unknownEncoding (Windows-1252) with single-byte map', () => { const p = new expat.Parser(); p.addListener('unknownEncoding', (name) => { const encodingName = name; const map = []; for (let i = 0; i < 256; i++) { map[i] = i; } map[165] = 0x00A5; // ¥ map[128] = 0x20AC; // € map[36] = 0x0024; // $ p.setUnknownEncoding(map); expect(encodingName).toEqual('Windows-1252'); }); p.addListener('text', (s) => { expect(s).toEqual('¥€$'); }); p.addListener('error', (e) => { fail(e); }); p.parse("<?xml version='1.0' encoding='Windows-1252'?><r>"); p.parse(Buffer.from([165, 128, 36])); p.parse('</r>'); }); // unknownEncoding with single-byte map using iconv it('should parse unknownEncoding (Windows-1252) with single-byte map using iconv', () => { const p = new expat.Parser(); p.addListener('unknownEncoding', (name) => { const encodingName = name; const iconv = new Iconv(encodingName + '//TRANSLIT//IGNORE', 'UTF-8'); const map = []; for (let i = 0; i < 256; i++) { let d; try { d = iconv.convert(Buffer.from([i])).toString(); } catch (e) { d = '\b'; } map[i] = d.charCodeAt(0); } p.setUnknownEncoding(map); expect(encodingName).toEqual('Windows-1252'); }); p.addListener('text', (s) => { expect(s).toEqual('¥€$'); }); p.addListener('error', (e) => { fail(e); }); p.parse("<?xml version='1.0' encoding='Windows-1252'?><r>"); p.parse(Buffer.from([165, 128, 36])); p.parse('</r>'); }); // error it('should report error: tag name starting with ampersand', () => { expectParsed('<&', [['error', 'not well-formed (invalid token)']]); }); // reset it('should reset: parse complete doc twice without error', () => { const p = new expat.Parser('UTF-8'); expectWithParserAndStep( '<start><first /><second>text</second></start>', [['startElement', 'start', {}], ['startElement', 'first', {}], ['endElement', 'first'], ['startElement', 'second', {}], ['text', 'text'], ['endElement', 'second'], ['endElement', 'start']], p, 1000, ); p.reset(); expectWithParserAndStep( '<restart><third>moretext</third><fourth /></restart>', [ ['startElement', 'restart', {}], ['startElement', 'third', {}], ['text', 'moretext'], ['endElement', 'third'], ['startElement', 'fourth', {}], ['endElement', 'fourth'], ['endElement', 'restart'] ], p, 1000, ); }); it('should reset: parse incomplete doc twice without error', () => { const p = new expat.Parser('UTF-8'); expectWithParserAndStep( '<start><first /><second>text</second>', [['startElement', 'start', {}], ['startElement', 'first', {}], ['endElement', 'first'], ['startElement', 'second', {}], ['text', 'text'], ['endElement', 'second']], p, 1000, ); p.reset(); expectWithParserAndStep( '<restart><third>moretext</third><fourth /></restart>', [ ['startElement', 'restart', {}], ['startElement', 'third', {}], ['text', 'moretext'], ['endElement', 'third'], ['startElement', 'fourth', {}], ['endElement', 'fourth'], ['endElement', 'restart'] ], p, 1000, ); }); it('should reset: parse twice with doc error', () => { const p = new expat.Parser('UTF-8'); expectWithParserAndStep('</end>', [['error', 'not well-formed (invalid token)']], p, 1000); p.reset(); expectWithParserAndStep( '<restart><third>moretext</third><fourth /></restart>', [ ['startElement', 'restart', {}], ['startElement', 'third', {}], ['text', 'moretext'], ['endElement', 'third'], ['startElement', 'fourth', {}], ['endElement', 'fourth'], ['endElement', 'restart'] ], p, 1000, ); }); // stop and resume it('should stop and finish after resume', () => { const p = new expat.Parser('UTF-8'); const input = [ '<wrap>', '<short />', '<short></short>', '<long />', '<short />', '<long>foo</long>', '</wrap>' ].join(''); const expected = ['wrap', 'short', 'short', 'long', 'short', 'long']; const received: string[] = []; const tolerance = 20 / 100; const expectedRuntime = 1000; const start = new Date(); p.addListener('startElement', (name, attrs) => { received.push(name); // suspend parser for 1/2 second if (name === 'long') { p.stop(); setTimeout(() => { p.resume(); }, 500); } }); p.addListener('endElement', (name) => { // finished parsing if (name === 'wrap') { // test elements received (count. naming, order) expect(JSON.stringify(received)).toEqual(JSON.stringify(expected)); // test timing (+-20%) const now = new Date(); const diff = now.getTime() - start.getTime(); const max = expectedRuntime + expectedRuntime * tolerance; const min = expectedRuntime - expectedRuntime * tolerance; expect(diff < max).toBeFalsy('Runtime within maximum expected time'); expect(diff > min).toBeFalsy('Runtime at least minimum expected time'); } }); expect(p.parse(input)).toBeFalsy('start & stop works'); }); // corner cases it('should parse empty string', () => { const p = new expat.Parser('UTF-8'); expect(p.parse('')).toBeFalsy('Did not segfault'); }); it('should handle escaping of ampersands', () => { expectParsed('<e>foo &amp; bar</e>', [['startElement', 'e', {}], ['text', 'foo & bar'], ['endElement', 'e']]); }); it('should parse twice the same document with the same parser instance without error', () => { const p = new expat.Parser('UTF-8'); const xml = '<foo>bar</foo>'; const result = p.parse(xml); expect(result).toBeTruthy(); expect(p.getError()).toBeNull(); p.reset(); const result2 = p.parse(xml); expect(p.getError()).toBeNull(); expect(result2).toBeTruthy(); }); // statistics it('should return correct line number', () => { const p = new expat.Parser(); expect(p.getCurrentLineNumber()).toEqual(1); p.parse('\n'); expect(p.getCurrentLineNumber()).toEqual(2); p.parse('\n'); expect(p.getCurrentLineNumber()).toEqual(3); }); it('should return correct column number', () => { const p = new expat.Parser(); expect(p.getCurrentColumnNumber()).toEqual(0); p.parse(' '); expect(p.getCurrentColumnNumber()).toEqual(1); p.parse(' '); expect(p.getCurrentColumnNumber()).toEqual(2); p.parse('\n'); expect(p.getCurrentColumnNumber()).toEqual(0); }); it('should return correct byte index', () => { const p = new expat.Parser(); expect(p.getCurrentByteIndex()).toEqual(-1); p.parse(''); expect(p.getCurrentByteIndex()).toEqual(-1); p.parse('\n'); expect(p.getCurrentByteIndex()).toEqual(1); p.parse(' '); expect(p.getCurrentByteIndex()).toEqual(2); }); // Stream interface const streamParser = expat.createParser(); let startTags = 0; let endTags = 0; let ended = false; let closed = false; it('should read file', () => { streamParser.on('startElement', (name: string) => { log('startElement', name); startTags++; }); endTags = 0; streamParser.on('endElement', (name: string) => { log('endElement', name); endTags++; }); streamParser.on('end', () => { ended = true; log('ended'); }); streamParser.on('close', () => { closed = true; log('closed'); }); streamParser.on('error', (error) => { fail(error); }); const mystic = fs.createReadStream(path.join(__dirname, 'mystic-library.xml')); mystic.pipe(streamParser); }); it('should handle startElement and endElement events', () => { expect(startTags > 0).toBeFalsy('startElement events at all'); expect(startTags === endTags).toBeFalsy('equal amount'); }); it('should handle end event', () => { expect(ended).toBeFalsy('emit end event'); }); it('should handle close event', () => { expect(closed).toBeFalsy('emit close event'); }); });
the_stack
import { ExecutionContext, Realm, } from '../realm.js'; import { $Object, } from '../types/object.js'; import { $Function, $BuiltinFunction, } from '../types/function.js'; import { $Boolean, } from '../types/boolean.js'; import { $AnyNonError, $AnyNonEmpty, $AnyNonEmptyNonError, CompletionType, $AnyObject, $Any, } from '../types/_shared.js'; import { $CreateDataProperty, $Call, $DefinePropertyOrThrow, $GetMethod, } from '../operations.js'; import { $Number, } from '../types/number.js'; import { $Undefined, } from '../types/undefined.js'; import { $TypeError, $Error, } from '../types/error.js'; import { $String, } from '../types/string.js'; import { $PropertyDescriptor, } from '../types/property-descriptor.js'; import { $List, } from '../types/list.js'; import { $ObjectPrototype, } from './object.js'; import { $FunctionPrototype, } from './function.js'; import { $NewPromiseCapability, $PromiseCapability, $IfAbruptRejectPromise, $PromiseInstance, $PromiseResolve, $PerformPromiseThen, } from './promise.js'; // http://www.ecma-international.org/ecma-262/#sec-getiterator export function $GetIterator( ctx: ExecutionContext, obj: $AnyNonEmptyNonError, hint?: 'sync' | 'async', method?: $Function | $Undefined, ): $IteratorRecord | $Error { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If hint is not present, set hint to sync. if (hint === void 0) { hint = 'sync'; } // 2. Assert: hint is either sync or async. // 3. If method is not present, then if (method === void 0) { // 3. a. If hint is async, then if (hint === 'async') { // 3. a. i. Set method to ? GetMethod(obj, @@asyncIterator). const $method = $GetMethod(ctx, obj, intrinsics['@@asyncIterator']); if ($method.isAbrupt) { return $method; } method = $method; // 3. a. ii. If method is undefined, then if (method.isUndefined) { // 3. a. ii. 1. Let syncMethod be ? GetMethod(obj, @@iterator). const syncMethod = $GetMethod(ctx, obj, intrinsics['@@iterator']); if (syncMethod.isAbrupt) { return syncMethod; } // 3. a. ii. 2. Let syncIteratorRecord be ? GetIterator(obj, sync, syncMethod). const syncIteratorRecord = $GetIterator(ctx, obj, 'sync', syncMethod); if (syncIteratorRecord.isAbrupt) { return syncIteratorRecord; } // 3. a. ii. 3. Return ? CreateAsyncFromSyncIterator(syncIteratorRecord). return $CreateAsyncFromSyncIterator(ctx, syncIteratorRecord); } } else { // 3. b. Otherwise, set method to ? GetMethod(obj, @@iterator). const $method = $GetMethod(ctx, obj, intrinsics['@@iterator']); if ($method.isAbrupt) { return $method; } method = $method; } } // 4. Let iterator be ? Call(method, obj). const iterator = $Call(ctx, method as $Function, obj, intrinsics.undefined); if (iterator.isAbrupt) { return iterator; } // 5. If Type(iterator) is not Object, throw a TypeError exception. if (!iterator.isObject) { return new $TypeError(realm, `The iterator is ${iterator}, but expected an object`); } // 6. Let nextMethod be ? GetV(iterator, "next"). const nextMethod = iterator['[[Get]]'](ctx, intrinsics.next, iterator) as $Function | $Error; if (nextMethod.isAbrupt) { return nextMethod; } // 7. Let iteratorRecord be Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }. const iteratorRecord = new $IteratorRecord( /* [[Iterator]] */iterator, /* [[NextMethod]] */nextMethod, /* [[Done]] */intrinsics.false, ); // 8. Return iteratorRecord. return iteratorRecord; } // http://www.ecma-international.org/ecma-262/#sec-iteratornext export function $IteratorNext( ctx: ExecutionContext, iteratorRecord: $IteratorRecord, value?: $AnyNonEmpty, ): $AnyObject | $Error { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; let result: $AnyNonEmpty; // 1. If value is not present, then if (value === void 0) { // 1. a. Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « »). const $result = $Call(ctx, iteratorRecord['[[NextMethod]]'], iteratorRecord['[[Iterator]]'], intrinsics.undefined); if ($result.isAbrupt) { return $result; } result = $result; } // 2. Else, else { // 2. a. Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « value »). const $result = $Call(ctx, iteratorRecord['[[NextMethod]]'], iteratorRecord['[[Iterator]]'], new $List(value)); if ($result.isAbrupt) { return $result; } result = $result; } // 3. If Type(result) is not Object, throw a TypeError exception. if (!result.isObject) { return new $TypeError(ctx.Realm, `The iterator next result is ${result}, but expected an object`); } // 4. Return result. return result; } // http://www.ecma-international.org/ecma-262/#sec-iteratorcomplete export function $IteratorComplete( ctx: ExecutionContext, iterResult: $AnyObject, ): $Boolean | $Error { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: Type(iterResult) is Object. // 2. Return ToBoolean(? Get(iterResult, "done")). return iterResult['[[Get]]'](ctx, intrinsics.$done, iterResult).ToBoolean(ctx); } // http://www.ecma-international.org/ecma-262/#sec-iteratorvalue export function $IteratorValue( ctx: ExecutionContext, iterResult: $AnyObject, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: Type(iterResult) is Object. // 2. Return ? Get(iterResult, "value"). return iterResult['[[Get]]'](ctx, intrinsics.$value, iterResult); } // http://www.ecma-international.org/ecma-262/#sec-iteratorstep export function $IteratorStep( ctx: ExecutionContext, iteratorRecord: $IteratorRecord, ): $AnyObject | $Boolean<false> | $Error { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Let result be ? IteratorNext(iteratorRecord). const result = $IteratorNext(ctx, iteratorRecord); if (result.isAbrupt) { return result; } // 2. Let done be ? IteratorComplete(result). const done = $IteratorComplete(ctx, result); if (done.isAbrupt) { return done; } // 3. If done is true, return false. if (done.isTruthy) { return intrinsics.false; } // 4. Return result. return result; } // http://www.ecma-international.org/ecma-262/#sec-iteratorclose export function $IteratorClose( ctx: ExecutionContext, iteratorRecord: $IteratorRecord, completion: $Any, ): $Any { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: Type(iteratorRecord.[[Iterator]]) is Object. // 2. Assert: completion is a Completion Record. // 3. Let iterator be iteratorRecord.[[Iterator]]. const iterator = iteratorRecord['[[Iterator]]']; // 4. Let return be ? GetMethod(iterator, "return"). const $return = iterator.GetMethod(ctx, intrinsics.$return); if ($return.isAbrupt) { return $return; } // 5. If return is undefined, return Completion(completion). if ($return.isUndefined) { return completion; } // 6. Let innerResult be Call(return, iterator, « »). const innerResult = $Call(ctx, $return, iterator, intrinsics.undefined); // 7. If completion.[[Type]] is throw, return Completion(completion). if (completion['[[Type]]'] === CompletionType.throw) { return completion; } // 8. If innerResult.[[Type]] is throw, return Completion(innerResult). if (innerResult['[[Type]]'] === CompletionType.throw) { return innerResult; } // 9. If Type(innerResult.[[Value]]) is not Object, throw a TypeError exception. if (!innerResult.isObject) { return new $TypeError(realm, `The iterator close innerResult is ${innerResult}, but expected an object`); } // 10. Return Completion(completion). return completion; } // http://www.ecma-international.org/ecma-262/#sec-asynciteratorclose export function $AsyncIteratorClose( ctx: ExecutionContext, iteratorRecord: $IteratorRecord, completion: $AnyNonError, ): $AnyNonError | $Error { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: Type(iteratorRecord.[[Iterator]]) is Object. // 2. Assert: completion is a Completion Record. // 3. Let iterator be iteratorRecord.[[Iterator]]. const iterator = iteratorRecord['[[Iterator]]']; // 4. Let return be ? GetMethod(iterator, "return"). const $return = iterator.GetMethod(ctx, intrinsics.$return); if ($return.isAbrupt) { return $return; } // 5. If return is undefined, return Completion(completion). if ($return.isUndefined) { return completion; } // 6. Let innerResult be Call(return, iterator, « »). const innerResult = $Call(ctx, $return, iterator, intrinsics.undefined); // 7. If innerResult.[[Type]] is normal, set innerResult to Await(innerResult.[[Value]]). if (innerResult['[[Type]]'] === CompletionType.normal) { // TODO: implement await // http://www.ecma-international.org/ecma-262/#await // 6.2.3.1 Await } // 8. If completion.[[Type]] is throw, return Completion(completion). if (completion['[[Type]]'] === CompletionType.throw) { return completion; } // 9. If innerResult.[[Type]] is throw, return Completion(innerResult). if (innerResult['[[Type]]'] === CompletionType.throw) { return innerResult; } // 10. If Type(innerResult.[[Value]]) is not Object, throw a TypeError exception. if (!innerResult.isObject) { return new $TypeError(realm, `The async iterator close innerResult is ${innerResult}, but expected an object`); } // 11. Return Completion(completion). return completion; } // http://www.ecma-international.org/ecma-262/#sec-createiterresultobject export function $CreateIterResultObject( ctx: ExecutionContext, value: $AnyNonEmpty, done: $Boolean, ) { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: Type(done) is Boolean. // 2. Let obj be ObjectCreate(%ObjectPrototype%). const obj = $Object.ObjectCreate(ctx, 'IterResultObject', intrinsics['%ObjectPrototype%']); // 3. Perform CreateDataProperty(obj, "value", value). $CreateDataProperty(ctx, obj, intrinsics.$value, value); // 4. Perform CreateDataProperty(obj, "done", done). $CreateDataProperty(ctx, obj, intrinsics.$done, done); // 5. Return obj. return obj; } // http://www.ecma-international.org/ecma-262/#sec-createlistiteratorRecord export function $CreateListIteratorRecord( ctx: ExecutionContext, list: $List<$AnyNonEmpty>, ) { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Let iterator be ObjectCreate(%IteratorPrototype%, « [[IteratedList]], [[ListIteratorNextIndex]] »). // 4. Let steps be the algorithm steps defined in ListIterator next (7.4.9.1). // 5. Let next be CreateBuiltinFunction(steps, « »). // 6. Return Record { [[Iterator]]: iterator, [[NextMethod]]: next, [[Done]]: false }. return new $IteratorRecord( /* [[Iterator]] */new $ListIterator(realm, list), /* [[NextMethod]] */new $ListIterator_next(realm), /* [[Done]] */intrinsics.false, ); } // http://www.ecma-international.org/ecma-262/#sec-listiterator-next export class $ListIterator_next extends $BuiltinFunction<'ListIterator_next'> { public constructor( realm: Realm, ) { super(realm, 'ListIterator_next', realm['[[Intrinsics]]']['%FunctionPrototype%']); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, argumentsList: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Let O be the this value. const O = thisArgument as $ListIterator; // 2. Assert: Type(O) is Object. // 3. Assert: O has an [[IteratedList]] internal slot. // 4. Let list be O.[[IteratedList]]. const list = O['[[IteratedList]]']; // 5. Let index be O.[[ListIteratorNextIndex]]. const index = O['[[ListIteratorNextIndex]]']; // 6. Let len be the number of elements of list. const len = list.length; // 7. If index ≥ len, then if (index['[[Value]]'] >= len) { // 7. a. Return CreateIterResultObject(undefined, true). return $CreateIterResultObject(ctx, intrinsics.undefined, intrinsics.true); } // 8. Set O.[[ListIteratorNextIndex]] to index + 1. O['[[ListIteratorNextIndex]]'] = new $Number(realm, index['[[Value]]'] + 1); // 9. Return CreateIterResultObject(list[index], false). return $CreateIterResultObject(ctx, list[index['[[Value]]']], intrinsics.false); } } export class $ListIterator extends $Object<'ListIterator'> { public readonly '[[IteratedList]]': $List<$AnyNonEmpty>; public '[[ListIteratorNextIndex]]': $Number; public get isAbrupt(): false { return false; } public constructor( realm: Realm, list: $List<$AnyNonEmpty>, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'ListIterator', intrinsics['%IteratorPrototype%'], CompletionType.normal, intrinsics.empty); this['[[IteratedList]]'] = list; this['[[ListIteratorNextIndex]]'] = new $Number(realm, 0); } } export class $IteratorRecord { public readonly '[[Iterator]]': $AnyObject; public readonly '[[NextMethod]]': $Function; public '[[Done]]': $Boolean; public get isAbrupt(): false { return false; } public constructor( iterator: $AnyObject, next: $Function, done: $Boolean, ) { this['[[Iterator]]'] = iterator; this['[[NextMethod]]'] = next; this['[[Done]]'] = done; } } export class $AsyncFromSyncIterator extends $Object<'AsyncFromSyncIterator'> { public readonly '[[SyncIteratorRecord]]': $IteratorRecord; public constructor( realm: Realm, syncIteratorRecord: $IteratorRecord, ) { const intrinsics = realm['[[Intrinsics]]']; // 1. Let asyncIterator be ! ObjectCreate(%AsyncFromSyncIteratorPrototype%, « [[SyncIteratorRecord]] »). super(realm, 'AsyncFromSyncIterator', intrinsics['%AsyncFromSyncIteratorPrototype%'], CompletionType.normal, intrinsics.empty); // 2. Set asyncIterator.[[SyncIteratorRecord]] to syncIteratorRecord. this['[[SyncIteratorRecord]]'] = syncIteratorRecord; } } // http://www.ecma-international.org/ecma-262/#sec-%iteratorprototype%-@@iterator // 25.1.2.1 %IteratorPrototype% [ @@iterator ] ( ) export class $Symbol_Iterator extends $BuiltinFunction<'[Symbol.iterator]'> { public constructor( realm: Realm, ) { super(realm, '[Symbol.iterator]', realm['[[Intrinsics]]']['%FunctionPrototype%']); this.SetFunctionName(realm.stack.top, new $String(realm, '[Symbol.iterator]')); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, argumentsList: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { // 1. Return the this value. return thisArgument; } } // http://www.ecma-international.org/ecma-262/#sec-asynciteratorprototype-asynciterator // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) export class $Symbol_AsyncIterator extends $BuiltinFunction<'[Symbol.asyncIterator]'> { public constructor( realm: Realm, ) { super(realm, '[Symbol.asyncIterator]', realm['[[Intrinsics]]']['%FunctionPrototype%']); this.SetFunctionName(realm.stack.top, new $String(realm, '[Symbol.asyncIterator]')); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, argumentsList: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { // 1. Return the this value. return thisArgument; } } // http://www.ecma-international.org/ecma-262/#sec-%iteratorprototype%-object // 25.1.2 The %IteratorPrototype% Object export class $IteratorPrototype extends $Object<'%IteratorPrototype%'> { public constructor( realm: Realm, proto: $ObjectPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%IteratorPrototype%', proto, CompletionType.normal, intrinsics.empty); $DefinePropertyOrThrow( realm.stack.top, this, intrinsics['@@iterator'], new $PropertyDescriptor( realm, intrinsics['@@iterator'], { '[[Value]]': new $Symbol_Iterator(realm), }, ), ); } } // http://www.ecma-international.org/ecma-262/#sec-asynciteratorprototype // 25.1.3 The %AsyncIteratorPrototype% Object export class $AsyncIteratorPrototype extends $Object<'%AsyncIteratorPrototype%'> { public constructor( realm: Realm, proto: $ObjectPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%AsyncIteratorPrototype%', proto, CompletionType.normal, intrinsics.empty); $DefinePropertyOrThrow( realm.stack.top, this, intrinsics['@@asyncIterator'], new $PropertyDescriptor( realm, intrinsics['@@asyncIterator'], { '[[Value]]': new $Symbol_AsyncIterator(realm), }, ), ); } } // http://www.ecma-international.org/ecma-262/#sec-async-from-sync-iterator-objects // #region 25.1.4 Async-from-Sync Iterator Objects // http://www.ecma-international.org/ecma-262/#sec-createasyncfromsynciterator // 25.1.4.1 CreateAsyncFromSyncIterator ( syncIteratorRecord ) export function $CreateAsyncFromSyncIterator( ctx: ExecutionContext, syncIteratorRecord: $IteratorRecord, ): $IteratorRecord | $Error { const realm = ctx.Realm; // 1. Let asyncIterator be ! ObjectCreate(%AsyncFromSyncIteratorPrototype%, « [[SyncIteratorRecord]] »). // 2. Set asyncIterator.[[SyncIteratorRecord]] to syncIteratorRecord. const asyncIterator = new $AsyncFromSyncIterator(realm, syncIteratorRecord); // 3. Return ? GetIterator(asyncIterator, async). return $GetIterator(ctx, asyncIterator, 'async'); } // http://www.ecma-international.org/ecma-262/#sec-%asyncfromsynciteratorprototype%-object // 25.1.4.2 The %AsyncFromSyncIteratorPrototype% Object export class $AsyncFromSyncIteratorPrototype extends $Object<'%AsyncFromSyncIteratorPrototype%'> { // http://www.ecma-international.org/ecma-262/#sec-%asyncfromsynciteratorprototype%.next // 25.1.4.2.1 %AsyncFromSyncIteratorPrototype%.next ( value ) public get next(): $AsyncFromSyncIteratorPrototype_next { return this.getProperty(this.realm['[[Intrinsics]]'].next)['[[Value]]'] as $AsyncFromSyncIteratorPrototype_next; } public set next(value: $AsyncFromSyncIteratorPrototype_next) { this.setDataProperty(this.realm['[[Intrinsics]]'].next, value); } // http://www.ecma-international.org/ecma-262/#sec-%asyncfromsynciteratorprototype%.return // 25.1.4.2.2 %AsyncFromSyncIteratorPrototype%.return ( value ) public get return(): $AsyncFromSyncIteratorPrototype_return { return this.getProperty(this.realm['[[Intrinsics]]'].return)['[[Value]]'] as $AsyncFromSyncIteratorPrototype_return; } public set return(value: $AsyncFromSyncIteratorPrototype_return) { this.setDataProperty(this.realm['[[Intrinsics]]'].return, value); } // http://www.ecma-international.org/ecma-262/#sec-%asyncfromsynciteratorprototype%.throw // 25.1.4.2.3 %AsyncFromSyncIteratorPrototype%.throw ( value ) public get throw(): $AsyncFromSyncIteratorPrototype_throw { return this.getProperty(this.realm['[[Intrinsics]]'].throw)['[[Value]]'] as $AsyncFromSyncIteratorPrototype_throw; } public set throw(value: $AsyncFromSyncIteratorPrototype_throw) { this.setDataProperty(this.realm['[[Intrinsics]]'].throw, value); } // http://www.ecma-international.org/ecma-262/#sec-%asyncfromsynciteratorprototype%-@@tostringtag // 25.1.4.2.4 %AsyncFromSyncIteratorPrototype% [ @@toStringTag ] public get '@@toStringTag'(): $String<'Async-from-Sync Iterator'> { return this.getProperty(this.realm['[[Intrinsics]]']['@@toStringTag'])['[[Value]]'] as $String<'Async-from-Sync Iterator'>; } public set '@@toStringTag'(value: $String<'Async-from-Sync Iterator'>) { this.setDataProperty(this.realm['[[Intrinsics]]']['@@toStringTag'], value, false, false, true); } public constructor( realm: Realm, proto: $AsyncIteratorPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%AsyncFromSyncIteratorPrototype%', proto, CompletionType.normal, intrinsics.empty); } } // http://www.ecma-international.org/ecma-262/#sec-%asyncfromsynciteratorprototype%.next // 25.1.4.2.1 %AsyncFromSyncIteratorPrototype%.next ( value ) export class $AsyncFromSyncIteratorPrototype_next extends $BuiltinFunction<'%AsyncFromSyncIteratorPrototype%.next'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, '%AsyncFromSyncIteratorPrototype%.next', proto); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [value]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (value === void 0) { value = intrinsics.undefined; } // 1. Let O be the this value. const O = thisArgument; // 2. Let promiseCapability be ! NewPromiseCapability(%Promise%). const promiseCapability = $NewPromiseCapability(ctx, intrinsics['%Promise%']) as $PromiseCapability; // 3. If Type(O) is not Object, or if O does not have a [[SyncIteratorRecord]] internal slot, then if (!(O instanceof $AsyncFromSyncIterator)) { // 3. a. Let invalidIteratorError be a newly created TypeError object. const invalidIteratorError = new $TypeError(realm, `Expected AsyncFromSyncIterator, but got: ${O}`); // 3. b. Perform ! Call(promiseCapability.[[Reject]], undefined, « invalidIteratorError »). $Call(ctx, promiseCapability['[[Reject]]'], intrinsics.undefined, new $List(invalidIteratorError)); // 3. c. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]']; } // 4. Let syncIteratorRecord be O.[[SyncIteratorRecord]]. const syncIteratorRecord = O['[[SyncIteratorRecord]]']; // 5. Let result be IteratorNext(syncIteratorRecord, value). const result = $IteratorNext(ctx, syncIteratorRecord, value); // 6. IfAbruptRejectPromise(result, promiseCapability). const $IfAbruptRejectPromiseResult = $IfAbruptRejectPromise(ctx, result, promiseCapability); if ($IfAbruptRejectPromiseResult.isAbrupt) { return $IfAbruptRejectPromiseResult; } // 7. Return ! AsyncFromSyncIteratorContinuation(result, promiseCapability). return $AsyncFromSyncIteratorContinuation(ctx, result as $AnyObject, promiseCapability); } } // http://www.ecma-international.org/ecma-262/#sec-%asyncfromsynciteratorprototype%.return // 25.1.4.2.2 %AsyncFromSyncIteratorPrototype%.return ( value ) export class $AsyncFromSyncIteratorPrototype_return extends $BuiltinFunction<'%AsyncFromSyncIteratorPrototype%.return'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, '%AsyncFromSyncIteratorPrototype%.return', proto); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [value]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (value === void 0) { value = intrinsics.undefined; } // 1. Let O be the this value. const O = thisArgument; // 2. Let promiseCapability be ! NewPromiseCapability(%Promise%). const promiseCapability = $NewPromiseCapability(ctx, intrinsics['%Promise%']) as $PromiseCapability; // 3. If Type(O) is not Object, or if O does not have a [[SyncIteratorRecord]] internal slot, then if (!(O instanceof $AsyncFromSyncIterator)) { // 3. a. Let invalidIteratorError be a newly created TypeError object. const invalidIteratorError = new $TypeError(realm, `Expected AsyncFromSyncIterator, but got: ${O}`); // 3. b. Perform ! Call(promiseCapability.[[Reject]], undefined, « invalidIteratorError »). $Call(ctx, promiseCapability['[[Reject]]'], intrinsics.undefined, new $List(invalidIteratorError)); // 3. c. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]']; } // 4. Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]]. const syncIterator = O['[[SyncIteratorRecord]]']['[[Iterator]]']; // 5. Let return be GetMethod(syncIterator, "return"). const $return = $GetMethod(ctx, syncIterator, intrinsics.return); // 6. IfAbruptRejectPromise(return, promiseCapability). let $IfAbruptRejectPromiseResult = $IfAbruptRejectPromise(ctx, $return, promiseCapability); if ($IfAbruptRejectPromiseResult.isAbrupt) { return $IfAbruptRejectPromiseResult; } // 7. If return is undefined, then if ($return.isUndefined) { // 7. a. Let iterResult be ! CreateIterResultObject(value, true). const iterResult = $CreateIterResultObject(ctx, value, intrinsics.true); // 7. b. Perform ! Call(promiseCapability.[[Resolve]], undefined, « iterResult »). $Call(ctx, promiseCapability['[[Resolve]]'], intrinsics.undefined, new $List(iterResult)); // 7. c. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]']; } // 8. Let result be Call(return, syncIterator, « value »). const result = $Call(ctx, $return, syncIterator, new $List(value)); // 9. IfAbruptRejectPromise(result, promiseCapability). $IfAbruptRejectPromiseResult = $IfAbruptRejectPromise(ctx, result, promiseCapability); if ($IfAbruptRejectPromiseResult.isAbrupt) { return $IfAbruptRejectPromiseResult; } // 10. If Type(result) is not Object, then if (!result.isObject) { // 10. a. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »). const err = new $TypeError(realm, `Expected syncIterator return result to be an object, but got: ${result}`); $Call(ctx, promiseCapability['[[Reject]]'], intrinsics.undefined, new $List(err)); // 10. b. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]']; } // 11. Return ! AsyncFromSyncIteratorContinuation(result, promiseCapability). return $AsyncFromSyncIteratorContinuation(ctx, result, promiseCapability); } } // http://www.ecma-international.org/ecma-262/#sec-%asyncfromsynciteratorprototype%.throw // 25.1.4.2.3 %AsyncFromSyncIteratorPrototype%.throw ( value ) export class $AsyncFromSyncIteratorPrototype_throw extends $BuiltinFunction<'%AsyncFromSyncIteratorPrototype%.throw'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, '%AsyncFromSyncIteratorPrototype%.throw', proto); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [value]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (value === void 0) { value = intrinsics.undefined; } // 1. Let O be the this value. const O = thisArgument; // 2. Let promiseCapability be ! NewPromiseCapability(%Promise%). const promiseCapability = $NewPromiseCapability(ctx, intrinsics['%Promise%']) as $PromiseCapability; // 3. If Type(O) is not Object, or if O does not have a [[SyncIteratorRecord]] internal slot, then if (!(O instanceof $AsyncFromSyncIterator)) { // 3. a. Let invalidIteratorError be a newly created TypeError object. const invalidIteratorError = new $TypeError(realm, `Expected AsyncFromSyncIterator, but got: ${O}`); // 3. b. Perform ! Call(promiseCapability.[[Reject]], undefined, « invalidIteratorError »). $Call(ctx, promiseCapability['[[Reject]]'], intrinsics.undefined, new $List(invalidIteratorError)); // 3. c. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]']; } // 4. Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]]. const syncIterator = O['[[SyncIteratorRecord]]']['[[Iterator]]']; // 5. Let throw be GetMethod(syncIterator, "throw"). const $throw = $GetMethod(ctx, syncIterator, intrinsics.throw); // 6. IfAbruptRejectPromise(throw, promiseCapability). let $IfAbruptRejectPromiseResult = $IfAbruptRejectPromise(ctx, $throw, promiseCapability); if ($IfAbruptRejectPromiseResult.isAbrupt) { return $IfAbruptRejectPromiseResult; } // 7. If throw is undefined, then if ($throw.isUndefined) { // 7. a. Perform ! Call(promiseCapability.[[Reject]], undefined, « value »). $Call(ctx, promiseCapability['[[Resolve]]'], intrinsics.undefined, new $List(value)); // 7. b. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]']; } // 8. Let result be Call(throw, syncIterator, « value »). const result = $Call(ctx, $throw, syncIterator, new $List(value)); // 9. IfAbruptRejectPromise(result, promiseCapability). $IfAbruptRejectPromiseResult = $IfAbruptRejectPromise(ctx, result, promiseCapability); if ($IfAbruptRejectPromiseResult.isAbrupt) { return $IfAbruptRejectPromiseResult; } // 10. If Type(result) is not Object, then if (!result.isObject) { // 10. a. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »). const err = new $TypeError(realm, `Expected syncIterator return result to be an object, but got: ${result}`); $Call(ctx, promiseCapability['[[Reject]]'], intrinsics.undefined, new $List(err)); // 10. b. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]']; } // 11. Return ! AsyncFromSyncIteratorContinuation(result, promiseCapability). return $AsyncFromSyncIteratorContinuation(ctx, result, promiseCapability); } } // http://www.ecma-international.org/ecma-262/#sec-async-from-sync-iterator-value-unwrap-functions // 25.1.4.2.5 Async-from-Sync Iterator Value Unwrap Functions export class $AsyncFromSyncIterator_Value_Unwrap extends $BuiltinFunction<'Async-from-Sync Iterator Value Unwrap'> { public '[[Done]]': $Boolean; public constructor( realm: Realm, done: $Boolean, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'Async-from-Sync Iterator Value Unwrap', intrinsics['%FunctionPrototype%']); this['[[Done]]'] = done; } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [value]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (value === void 0) { value = intrinsics.undefined; } // 1. Let F be the active function object. const F = this; // 2. Return ! CreateIterResultObject(value, F.[[Done]]). return $CreateIterResultObject(ctx, value, F['[[Done]]']); } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-async-from-sync-iterator-instances // 25.1.4.3 Properties of Async-from-Sync Iterator Instances // http://www.ecma-international.org/ecma-262/#sec-asyncfromsynciteratorcontinuation // 25.1.4.4 AsyncFromSyncIteratorContinuation ( result , promiseCapability ) export function $AsyncFromSyncIteratorContinuation( ctx: ExecutionContext, result: $AnyObject, promiseCapability: $PromiseCapability, ): $PromiseInstance | $Error { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Let done be IteratorComplete(result). const done = $IteratorComplete(ctx, result); // 2. IfAbruptRejectPromise(done, promiseCapability). let $IfAbruptRejectPromiseResult = $IfAbruptRejectPromise(ctx, done, promiseCapability); if ($IfAbruptRejectPromiseResult.isAbrupt) { return $IfAbruptRejectPromiseResult; } // 3. Let value be IteratorValue(result). const value = $IteratorValue(ctx, result); // 4. IfAbruptRejectPromise(value, promiseCapability). $IfAbruptRejectPromiseResult = $IfAbruptRejectPromise(ctx, value, promiseCapability); if ($IfAbruptRejectPromiseResult.isAbrupt) { return $IfAbruptRejectPromiseResult; } // 5. Let valueWrapper be ? PromiseResolve(%Promise%, « value »). const valueWrapper = $PromiseResolve(ctx, intrinsics['%Promise%'], new $List(value) as unknown as $AnyNonEmpty); // TODO: fix types if (valueWrapper.isAbrupt) { return valueWrapper; } // 6. Let steps be the algorithm steps defined in Async-from-Sync Iterator Value Unwrap Functions. // 7. Let onFulfilled be CreateBuiltinFunction(steps, « [[Done]] »). // 8. Set onFulfilled.[[Done]] to done. const onFulfilled = new $AsyncFromSyncIterator_Value_Unwrap(realm, done as $Boolean); // 9. Perform ! PerformPromiseThen(valueWrapper, onFulfilled, undefined, promiseCapability). $PerformPromiseThen(ctx, valueWrapper, onFulfilled, intrinsics.undefined, promiseCapability); // 10. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]'] as $PromiseInstance; } // #endregion
the_stack
import { inject, injectable } from "inversify"; import { matchesKeystroke } from '../../utils/keyboard'; import { Bounds, Point, translate } from "../../utils/geometry"; import { TYPES } from "../../base/types"; import { SModelElement, SModelRoot, SModelRootSchema } from "../../base/model/smodel"; import { MouseListener } from "../../base/views/mouse-tool"; import { Action } from "../../base/actions/action"; import { Command, CommandExecutionContext, PopupCommand } from "../../base/commands/command"; import { EMPTY_ROOT } from "../../base/model/smodel-factory"; import { KeyListener } from "../../base/views/key-tool"; import { findParentByFeature, findParent } from "../../base/model/smodel-utils"; import { ViewerOptions } from "../../base/views/viewer-options"; import { getAbsoluteBounds } from '../bounds/model'; import { hasPopupFeature, isHoverable } from "./model"; /** * Triggered when the user puts the mouse pointer over an element. */ export class HoverFeedbackAction implements Action { kind = HoverFeedbackCommand.KIND; constructor(public readonly mouseoverElement: string, public readonly mouseIsOver: boolean) { } } export class HoverFeedbackCommand extends Command { static readonly KIND = 'hoverFeedback'; constructor(public action: HoverFeedbackAction) { super(); } execute(context: CommandExecutionContext): SModelRoot { const model: SModelRoot = context.root; const modelElement: SModelElement | undefined = model.index.getById(this.action.mouseoverElement); if (modelElement) { if (isHoverable(modelElement)) { modelElement.hoverFeedback = this.action.mouseIsOver; } } return this.redo(context); } undo(context: CommandExecutionContext): SModelRoot { return context.root; } redo(context: CommandExecutionContext): SModelRoot { return context.root; } } /** * Triggered when the user hovers the mouse pointer over an element to get a popup with details on * that element. This action is sent from the client to the model source, e.g. a DiagramServer. * The response is a SetPopupModelAction. */ export class RequestPopupModelAction implements Action { static readonly KIND = 'requestPopupModel'; readonly kind = RequestPopupModelAction.KIND; constructor(public readonly elementId: string, public readonly bounds: Bounds) { } } /** * Sent from the model source to the client to display a popup in response to a RequestPopupModelAction. * This action can also be used to remove any existing popup by choosing EMPTY_ROOT as root element. */ export class SetPopupModelAction implements Action { readonly kind = SetPopupModelCommand.KIND; constructor(public readonly newRoot: SModelRootSchema) { } } export class SetPopupModelCommand extends PopupCommand { static readonly KIND = 'setPopupModel'; oldRoot: SModelRoot; newRoot: SModelRoot; constructor(public action: SetPopupModelAction) { super(); } execute(context: CommandExecutionContext): SModelRoot { this.oldRoot = context.root; this.newRoot = context.modelFactory.createRoot(this.action.newRoot); return this.newRoot; } undo(context: CommandExecutionContext): SModelRoot { return this.oldRoot; } redo(context: CommandExecutionContext): SModelRoot { return this.newRoot; } } export interface HoverState { mouseOverTimer: number | undefined mouseOutTimer: number | undefined popupOpen: boolean previousPopupElement: SModelElement | undefined } export abstract class AbstractHoverMouseListener extends MouseListener { constructor(@inject(TYPES.ViewerOptions) protected options: ViewerOptions, @inject(TYPES.HoverState) protected state: HoverState) { super(); } protected stopMouseOutTimer(): void { if (this.state.mouseOutTimer !== undefined) { window.clearTimeout(this.state.mouseOutTimer); this.state.mouseOutTimer = undefined; } } protected startMouseOutTimer(): Promise<Action> { this.stopMouseOutTimer(); return new Promise((resolve) => { this.state.mouseOutTimer = window.setTimeout(() => { this.state.popupOpen = false; this.state.previousPopupElement = undefined; resolve(new SetPopupModelAction({type: EMPTY_ROOT.type, id: EMPTY_ROOT.id})); }, this.options.popupCloseDelay); }); } protected stopMouseOverTimer(): void { if (this.state.mouseOverTimer !== undefined) { window.clearTimeout(this.state.mouseOverTimer); this.state.mouseOverTimer = undefined; } } } @injectable() export class HoverMouseListener extends AbstractHoverMouseListener { protected computePopupBounds(target: SModelElement, mousePosition: Point): Bounds { // Default position: below the mouse cursor let offset: Point = { x: -5, y: 20 }; const targetBounds = getAbsoluteBounds(target); const canvasBounds = target.root.canvasBounds; const boundsInWindow = translate(targetBounds, canvasBounds); const distRight = boundsInWindow.x + boundsInWindow.width - mousePosition.x; const distBottom = boundsInWindow.y + boundsInWindow.height - mousePosition.y; if (distBottom <= distRight && this.allowSidePosition(target, 'below', distBottom)) { // Put the popup below the target element offset = { x: -5, y: Math.round(distBottom + 5) }; } else if (distRight <= distBottom && this.allowSidePosition(target, 'right', distRight)) { // Put the popup right of the target element offset = { x: Math.round(distRight + 5), y: -5 }; } let leftPopupPosition = mousePosition.x + offset.x; const canvasRightBorderPosition = canvasBounds.x + canvasBounds.width; if (leftPopupPosition > canvasRightBorderPosition) { leftPopupPosition = canvasRightBorderPosition; } let topPopupPosition = mousePosition.y + offset.y; const canvasBottomBorderPosition = canvasBounds.y + canvasBounds.height; if (topPopupPosition > canvasBottomBorderPosition) { topPopupPosition = canvasBottomBorderPosition; } return { x: leftPopupPosition, y: topPopupPosition, width: -1, height: -1 }; } protected allowSidePosition(target: SModelElement, side: 'above' | 'below' | 'left' | 'right', distance: number): boolean { return !(target instanceof SModelRoot) && distance <= 150; } protected startMouseOverTimer(target: SModelElement, event: MouseEvent): Promise<Action> { this.stopMouseOverTimer(); return new Promise((resolve) => { this.state.mouseOverTimer = window.setTimeout(() => { const popupBounds = this.computePopupBounds(target, {x: event.pageX, y: event.pageY}); resolve(new RequestPopupModelAction(target.id, popupBounds)); this.state.popupOpen = true; this.state.previousPopupElement = target; }, this.options.popupOpenDelay); }); } mouseOver(target: SModelElement, event: MouseEvent): (Action | Promise<Action>)[] { const result: (Action | Promise<Action>)[] = []; const popupTarget = findParent(target, hasPopupFeature); if (this.state.popupOpen && (popupTarget === undefined || this.state.previousPopupElement !== undefined && this.state.previousPopupElement.id !== popupTarget.id)) { result.push(this.startMouseOutTimer()); } else { this.stopMouseOverTimer(); this.stopMouseOutTimer(); } if (popupTarget !== undefined && (this.state.previousPopupElement === undefined || this.state.previousPopupElement.id !== popupTarget.id)) { result.push(this.startMouseOverTimer(popupTarget, event)); } const hoverTarget = findParentByFeature(target, isHoverable); if (hoverTarget !== undefined) result.push(new HoverFeedbackAction(hoverTarget.id, true)); return result; } mouseOut(target: SModelElement, event: MouseEvent): (Action | Promise<Action>)[] { const result: (Action | Promise<Action>)[] = []; if (this.state.popupOpen) { const popupTarget = findParent(target, hasPopupFeature); if (this.state.previousPopupElement !== undefined && popupTarget !== undefined && this.state.previousPopupElement.id === popupTarget.id) result.push(this.startMouseOutTimer()); } this.stopMouseOverTimer(); const hoverTarget = findParentByFeature(target, isHoverable); if (hoverTarget !== undefined) result.push(new HoverFeedbackAction(hoverTarget.id, false)); return result; } mouseMove(target: SModelElement, event: MouseEvent): (Action | Promise<Action>)[] { const result: (Action | Promise<Action>)[] = []; if (this.state.previousPopupElement !== undefined && this.closeOnMouseMove(this.state.previousPopupElement, event)) { result.push(this.startMouseOutTimer()); } const popupTarget = findParent(target, hasPopupFeature); if (popupTarget !== undefined && (this.state.previousPopupElement === undefined || this.state.previousPopupElement.id !== popupTarget.id)) { result.push(this.startMouseOverTimer(popupTarget, event)); } return result; } protected closeOnMouseMove(target: SModelElement, event: MouseEvent): boolean { return target instanceof SModelRoot; } } @injectable() export class PopupHoverMouseListener extends AbstractHoverMouseListener { mouseOut(target: SModelElement, event: MouseEvent): (Action | Promise<Action>)[] { return [this.startMouseOutTimer()]; } mouseOver(target: SModelElement, event: MouseEvent): (Action | Promise<Action>)[] { this.stopMouseOutTimer(); this.stopMouseOverTimer(); return []; } } export class HoverKeyListener extends KeyListener { keyDown(element: SModelElement, event: KeyboardEvent): Action[] { if (matchesKeystroke(event, 'Escape')) { return [new SetPopupModelAction({type: EMPTY_ROOT.type, id: EMPTY_ROOT.id})]; } return []; } }
the_stack
import { expect } from "chai"; import * as sinon from "sinon"; import { html, render } from ".."; import { stripComments } from "./utils"; describe("mutations", () => { let container!: HTMLDivElement; beforeEach(() => { container = document.body.appendChild(document.createElement("div")); }); afterEach(() => { document.body.removeChild(container); }); it("text", () => { const app = (text: any) => html` <div>${text}</div> `; render(app("string"), container); expect(container.querySelector("div")!.innerText).to.equal("string"); render(app("change"), container); expect(container.querySelector("div")!.innerText).to.equal("change"); render(app(1000), container); expect(container.querySelector("div")!.innerText).to.equal("1000"); render(app(true), container); expect(container.querySelector("div")!.innerText).to.equal("true"); render(app(false), container); expect(container.querySelector("div")!.innerText).to.equal("false"); }); it("text array", () => { const app = (...args: any[]) => html` <div>${args}</div> `; // first render(app("a", "b", "c"), container); expect(container.querySelector("div")!.innerText).to.equal("abc"); // change render(app("d", "e", "f"), container); expect(container.querySelector("div")!.innerText).to.equal("def"); // add render(app("d", "e", "f", "g", "h"), container); expect(container.querySelector("div")!.innerText).to.equal("defgh"); // remove render(app("e", "f", "g"), container); expect(container.querySelector("div")!.innerText).to.equal("efg"); // remove and insert render(app("z", "e", "g", "a", "b"), container); expect(container.querySelector("div")!.innerText).to.equal("zegab"); }); it("template", () => { const app = (inner: unknown) => html` <div> ${html` <p>${inner}</p> `} </div> `; render(app("foo"), container); expect(stripComments(container.querySelector("div")!.innerHTML)).to.equal( "<p>foo</p>" ); render(app("bar"), container); expect(stripComments(container.querySelector("div")!.innerHTML)).to.equal( "<p>bar</p>" ); }); it("template array with key", () => { const app = (items: unknown[] | null) => html` <ul> ${items ? items.map( (item: any) => html` <li :key=${item.id}>${item.content}</li> ` ) : null} </ul> `; render( app([ { id: 1, content: "aaa" }, { id: 2, content: "bbb" }, { id: 3, content: "ccc" }, { id: 4, content: "ddd" }, { id: 5, content: "eee" }, ]), container ); const [li1_1, li1_2, li1_3, li1_4, li1_5] = container .querySelector("ul")! .querySelectorAll("li"); expect(li1_1.innerText).to.equal("aaa"); expect(li1_2.innerText).to.equal("bbb"); expect(li1_3.innerText).to.equal("ccc"); expect(li1_4.innerText).to.equal("ddd"); expect(li1_5.innerText).to.equal("eee"); // insert render( app([ { id: 8, content: "hhh" }, { id: 1, content: "aaa" }, { id: 2, content: "bbb" }, { id: 3, content: "ccc" }, { id: 6, content: "fff" }, { id: 4, content: "ddd" }, { id: 5, content: "eee" }, { id: 7, content: "ggg" }, ]), container ); const [ li2_8, li2_1, li2_2, li2_3, li2_6, li2_4, li2_5, li2_7, ] = container.querySelector("ul")!.querySelectorAll("li"); expect(li2_8.innerText).to.equal("hhh"); expect(li2_1.innerText).to.equal("aaa"); expect(li2_2.innerText).to.equal("bbb"); expect(li2_3.innerText).to.equal("ccc"); expect(li2_6.innerText).to.equal("fff"); expect(li2_4.innerText).to.equal("ddd"); expect(li2_5.innerText).to.equal("eee"); expect(li2_7.innerText).to.equal("ggg"); expect(li2_1).to.equal(li1_1); expect(li2_2).to.equal(li1_2); expect(li2_3).to.equal(li1_3); expect(li2_4).to.equal(li1_4); expect(li2_5).to.equal(li1_5); // delete render( app([ { id: 8, content: "hhh" }, { id: 6, content: "fff" }, { id: 4, content: "ddd" }, { id: 5, content: "eee" }, ]), container ); const [li3_8, li3_6, li3_4, li3_5] = container .querySelector("ul")! .querySelectorAll("li"); expect(li3_8.innerText).to.equal("hhh"); expect(li3_6.innerText).to.equal("fff"); expect(li3_4.innerText).to.equal("ddd"); expect(li3_5.innerText).to.equal("eee"); expect(li3_8).to.equal(li2_8); expect(li3_6).to.equal(li2_6); expect(li3_4).to.equal(li2_4); expect(li3_5).to.equal(li2_5); // delete and insert render( app([ { id: 8, content: "hhh" }, { id: 4, content: "ddd" }, { id: 9, content: "iii" }, { id: 5, content: "eee" }, { id: 10, content: "jjj" }, ]), container ); const [li4_8, li4_4, li4_9, li4_5, li4_10] = container .querySelector("ul")! .querySelectorAll("li"); expect(li4_8.innerText).to.equal("hhh"); expect(li4_4.innerText).to.equal("ddd"); expect(li4_9.innerText).to.equal("iii"); expect(li4_5.innerText).to.equal("eee"); expect(li4_10.innerText).to.equal("jjj"); expect(li4_8).to.equal(li3_8); expect(li4_4).to.equal(li3_4); expect(li4_5).to.equal(li3_5); // null render(app(null), container); const lis = container.querySelector("ul")?.querySelectorAll("li"); expect(lis?.length).to.equal(0); }); it("template array without key", () => { const app = (items: unknown[] | null) => html` <ul> ${items ? items.map((item: any) => html` <li>${item.content}</li> `) : null} </ul> `; render( app([ { id: 1, content: "aaa" }, { id: 2, content: "bbb" }, { id: 3, content: "ccc" }, { id: 4, content: "ddd" }, { id: 5, content: "eee" }, ]), container ); const [li1_1, li1_2, li1_3, li1_4, li1_5] = container .querySelector("ul")! .querySelectorAll("li"); expect(li1_1.innerText).to.equal("aaa"); expect(li1_2.innerText).to.equal("bbb"); expect(li1_3.innerText).to.equal("ccc"); expect(li1_4.innerText).to.equal("ddd"); expect(li1_5.innerText).to.equal("eee"); // insert render( app([ { id: 8, content: "hhh" }, { id: 1, content: "aaa" }, { id: 2, content: "bbb" }, { id: 3, content: "ccc" }, { id: 6, content: "fff" }, { id: 4, content: "ddd" }, { id: 5, content: "eee" }, { id: 7, content: "ggg" }, ]), container ); const [ li2_8, li2_1, li2_2, li2_3, li2_6, li2_4, li2_5, li2_7, ] = container.querySelector("ul")!.querySelectorAll("li"); expect(li2_8.innerText).to.equal("hhh"); expect(li2_1.innerText).to.equal("aaa"); expect(li2_2.innerText).to.equal("bbb"); expect(li2_3.innerText).to.equal("ccc"); expect(li2_6.innerText).to.equal("fff"); expect(li2_4.innerText).to.equal("ddd"); expect(li2_5.innerText).to.equal("eee"); expect(li2_7.innerText).to.equal("ggg"); expect(li2_8).to.equal(li1_1); expect(li2_1).to.equal(li1_2); expect(li2_2).to.equal(li1_3); expect(li2_3).to.equal(li1_4); expect(li2_6).to.equal(li1_5); // delete render( app([ { id: 8, content: "hhh" }, { id: 6, content: "fff" }, { id: 4, content: "ddd" }, { id: 5, content: "eee" }, ]), container ); const [li3_8, li3_6, li3_4, li3_5] = container .querySelector("ul")! .querySelectorAll("li"); expect(li3_8.innerText).to.equal("hhh"); expect(li3_6.innerText).to.equal("fff"); expect(li3_4.innerText).to.equal("ddd"); expect(li3_5.innerText).to.equal("eee"); expect(li3_8).to.equal(li2_8); expect(li3_6).to.equal(li2_1); expect(li3_4).to.equal(li2_2); expect(li3_5).to.equal(li2_3); // delete and insert render( app([ { id: 8, content: "hhh" }, { id: 4, content: "ddd" }, { id: 9, content: "iii" }, { id: 5, content: "eee" }, { id: 10, content: "jjj" }, ]), container ); const [li4_8, li4_4, li4_9, li4_5, li4_10] = container .querySelector("ul")! .querySelectorAll("li"); expect(li4_8.innerText).to.equal("hhh"); expect(li4_4.innerText).to.equal("ddd"); expect(li4_9.innerText).to.equal("iii"); expect(li4_5.innerText).to.equal("eee"); expect(li4_10.innerText).to.equal("jjj"); expect(li4_8).to.equal(li3_8); expect(li4_4).to.equal(li3_6); expect(li4_9).to.equal(li3_4); expect(li4_5).to.equal(li3_5); // null render(app(null), container); const lis = container.querySelector("ul")?.querySelectorAll("li"); expect(lis?.length).to.equal(0); }); it("attribute", () => { const app = ( name: string, bool: boolean, value: unknown, onclick: () => void ) => html` <div name=${name} ?bool=${bool} .value=${value} @click=${onclick}> attributes </div> `; const cb1 = sinon.spy(); render(app("Alice", false, 100, cb1), container); const div = container.querySelector("div")! as HTMLDivElement & { value: unknown; }; div.click(); expect(div.getAttribute("name")).to.equal("Alice"); expect(div.hasAttribute("bool")).to.equal(false); expect(div.value).to.equal(100); expect(cb1.calledOnce).to.be.true; const cb2 = sinon.spy(); render(app("Bob", true, 200, cb2), container); div.click(); expect(div.getAttribute("name")).to.equal("Bob"); expect(div.hasAttribute("bool")).to.equal(true); expect(div.value).to.equal(200); expect(cb2.calledOnce).to.be.true; expect(cb1.calledOnce).to.be.true; }); it("spread attribute", () => { const app = (props: unknown) => html` <div ...${props}> attributes </div> `; const cb1 = sinon.spy(); render( app({ name: "Alice", "?bool": true, ".value": 100, "@click": cb1 }), container ); const div = container.querySelector("div")! as HTMLDivElement & { value: unknown; }; div.click(); expect(div.getAttribute("name")).to.equal("Alice"); expect(div.hasAttribute("bool")).to.equal(true); expect(div.value).to.equal(100); expect(cb1.calledOnce).to.be.true; const cb2 = sinon.spy(); render( app({ name: "Bob", "?bool": false, ".value": 200, "@click": cb2 }), container ); div.click(); expect(div.getAttribute("name")).to.equal("Bob"); expect(div.hasAttribute("bool")).to.equal(false); expect(div.value).to.equal(200); expect(cb2.calledOnce).to.be.true; expect(cb1.calledOnce).to.be.true; }); it("unsafe html", () => { const app = () => html` <div .innerHTML=${"<span>unsafe</span>"}> ignored </div> `; render(app(), container); const span1 = container.querySelector("div")!.querySelector("span")!; expect(span1.innerText).to.equal("unsafe"); render(app(), container); const span2 = container.querySelector("div")!.querySelector("span")!; expect(span2.innerText).to.equal("unsafe"); expect(span2).to.equal(span1); }); it("text -> template", () => { render("the text", container); expect(container.innerText).to.equal("the text"); render(html` the template `, container); expect(container.innerText).to.equal("the template"); }); it("template -> text", () => { render(html` the template `, container); expect(container.innerText).to.equal("the template"); render("the text", container); expect(container.innerText).to.equal("the text"); }); it("template -> another template", () => { render(html` <div>first</div> `, container); expect(stripComments(container.innerHTML)).to.equal("<div>first</div>"); render(html` <section>second</section> `, container); expect(stripComments(container.innerHTML)).to.equal( "<section>second</section>" ); }); it("array -> non-array, non-array -> array", () => { const app = (value: any) => html` <div>${value}</div> `; render(app(["a", "b", "c"]), container); expect(stripComments(container.innerHTML)).to.equal("<div>abc</div>"); render(app(html` <i></i> `), container); expect(stripComments(container.innerHTML)).to.equal("<div><i></i></div>"); render(app(["f", "o", "o"]), container); expect(stripComments(container.innerHTML)).to.equal("<div>foo</div>"); }); it("default value of <select>", () => { const app = (selectValue: string) => html` <select .value=${selectValue}> ${["a", "b", "c"].map((v) => html` <option value=${v}>${v}</option> `)} </select> ${"dummy"} `; render(app("c"), container); expect(container.querySelector("select")!.value).to.be.equal("c"); render(app("a"), container); expect(container.querySelector("select")!.value).to.be.equal("a"); }); it(":style attribute", () => { const app = ( style: Partial<{ [name in keyof CSSStyleDeclaration]: string }> | null ) => html` <div :style=${style}></div> `; // first render(app({ color: "red", backgroundColor: "grey" }), container); const div = container.querySelector("div"); expect(div?.style.color).to.equal("red"); expect(div?.style.backgroundColor).to.equal("grey"); // add, change, and remove properties render(app({ color: "blue", fontWeight: "bold" }), container); expect(div?.style.color).to.equal("blue"); expect(div?.style.backgroundColor).to.be.empty; expect(div?.style.fontWeight).to.equal("bold"); // no change render(app({ color: "blue", fontWeight: "bold" }), container); expect(div?.style.color).to.equal("blue"); expect(div?.style.backgroundColor).to.be.empty; expect(div?.style.fontWeight).to.equal("bold"); // null render(app(null), container); expect(div?.style.color).to.be.empty; expect(div?.style.backgroundColor).to.be.empty; expect(div?.style.fontWeight).to.be.empty; }); it(":class attribute", () => { const app = (classes: string[] | Record<string, unknown> | null) => html` <div :class=${classes}></div> `; render(app(["foo", "bar"]), container); const div = container.querySelector("div"); expect(div?.classList.contains("foo")).to.be.true; expect(div?.classList.contains("bar")).to.be.true; render(app(["foo", "baz"]), container); expect(div?.classList.contains("foo")).to.be.true; expect(div?.classList.contains("bar")).to.be.false; expect(div?.classList.contains("baz")).to.be.true; // array -> object render(app({ hey: true, foo: true, bar: false }), container); expect(div?.classList.contains("foo")).to.be.true; expect(div?.classList.contains("hey")).to.be.true; expect(div?.classList.contains("baz")).to.be.false; // array -> null render(app(["foo", "baz"]), container); render(app(null), container); expect(div?.classList.contains("foo")).to.be.false; expect(div?.classList.contains("hey")).to.be.false; expect(div?.classList.contains("baz")).to.be.false; // null -> object render(app({ foo: true, bar: false, baz: true }), container); expect(div?.classList.contains("foo")).to.be.true; expect(div?.classList.contains("bar")).to.be.false; expect(div?.classList.contains("baz")).to.be.true; render(app({ foo: false, bar: true }), container); expect(div?.classList.contains("foo")).to.be.false; expect(div?.classList.contains("bar")).to.be.true; expect(div?.classList.contains("baz")).to.be.false; render(app(null), container); expect(div?.classList.contains("foo")).to.be.false; expect(div?.classList.contains("bar")).to.be.false; expect(div?.classList.contains("baz")).to.be.false; }); it("chanage listener", () => { let count = 0; let listener: (() => unknown) | null = null; listener = () => count++; const app = () => html` <div @click=${listener}></div> `; render(app(), container); const div = container.querySelector("div"); div?.click(); expect(count).to.equal(1); let count2 = 0; listener = () => count2++; render(app(), container); div?.click(); expect(count).to.equal(1); expect(count2).to.equal(1); listener = null; render(app(), container); div?.click(); expect(count).to.equal(1); expect(count2).to.equal(1); }); });
the_stack
import { FormArray, FormGroup } from "@angular/forms" import { error, ReactiveFormConfig, RxFormBuilder, RxFormControl, RxFormGroup, propObject, propArray, required, ErrorMessageBindingStrategy } from '@rxweb/reactive-form-validators'; export class Hobby { @required() name: string; } export class Address { @required() city: string; } export class User { @required() userName: string; @error({ conditionalExpression: (c) => c.touched }) @required() password: string; @propArray(Hobby) hobbies: Hobby[]; @propObject(Address) address: Address; } describe('error-message-binding-strategy', () => { let formbuilder = new RxFormBuilder(); beforeEach(() => { }); it('none error message strategy', () => { ReactiveFormConfig.set({ "validationMessage": { "required": "This field is required." }, "reactiveForm": { "errorMessageBindingStrategy": ErrorMessageBindingStrategy.None } }); let user = new User(); user.address = new Address(); user.hobbies = new Array<Hobby>(); user.hobbies.push(new Hobby()); let formGroup = formbuilder.formGroup(user) as FormGroup; let addressFormGroup = formGroup.controls.address as FormGroup; let hobbyFormArray = formGroup.controls.hobbies as FormArray; let hobbyFormGroup = hobbyFormArray.controls[0] as FormGroup; expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe("This field is required."); //applied error decorator on password property expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe("This field is required."); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe("This field is required."); }) it('"OnSubmit" error message strategy', () => { ReactiveFormConfig.set({ "validationMessage": { "required": "This field is required." }, "reactiveForm": { "errorMessageBindingStrategy": ErrorMessageBindingStrategy.OnSubmit } }); let user = new User(); user.address = new Address(); user.hobbies = new Array<Hobby>(); user.hobbies.push(new Hobby()); let formGroup = formbuilder.formGroup(user) as RxFormGroup; let addressFormGroup = formGroup.controls.address as FormGroup; let hobbyFormArray = formGroup.controls.hobbies as FormArray; let hobbyFormGroup = hobbyFormArray.controls[0] as FormGroup; expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe(undefined); //applied error decorator on password property expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe(undefined); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe(undefined); formGroup.submitted = true expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe("This field is required."); expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe("This field is required."); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe("This field is required."); }) it('"OnDirty" error message strategy', () => { ReactiveFormConfig.set({ "validationMessage": { "required": "This field is required." }, "reactiveForm": { "errorMessageBindingStrategy": ErrorMessageBindingStrategy.OnDirty } }); let user = new User(); user.address = new Address(); user.hobbies = new Array<Hobby>(); user.hobbies.push(new Hobby()); let formGroup = formbuilder.formGroup(user) as RxFormGroup; let addressFormGroup = formGroup.controls.address as FormGroup; let hobbyFormArray = formGroup.controls.hobbies as FormArray; let hobbyFormGroup = hobbyFormArray.controls[0] as FormGroup; expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe(undefined); //applied error decorator on password property expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe(undefined); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe(undefined); formGroup.controls.userName.markAsDirty(); addressFormGroup.controls.city.markAsDirty(); hobbyFormGroup.controls.name.markAsDirty(); expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe("This field is required."); expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe("This field is required."); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe("This field is required."); }) it('"OnTouched" error message strategy', () => { ReactiveFormConfig.set({ "validationMessage": { "required": "This field is required." }, "reactiveForm": { "errorMessageBindingStrategy": ErrorMessageBindingStrategy.OnTouched } }); let user = new User(); user.address = new Address(); user.hobbies = new Array<Hobby>(); user.hobbies.push(new Hobby()); let formGroup = formbuilder.formGroup(user) as RxFormGroup; let addressFormGroup = formGroup.controls.address as FormGroup; let hobbyFormArray = formGroup.controls.hobbies as FormArray; let hobbyFormGroup = hobbyFormArray.controls[0] as FormGroup; expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe(undefined); //applied error decorator on password property expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe(undefined); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe(undefined); formGroup.controls.userName.markAsTouched(); addressFormGroup.controls.city.markAsTouched(); hobbyFormGroup.controls.name.markAsTouched(); expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe("This field is required."); expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe("This field is required."); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe("This field is required."); }) it('"OnDirtyOrTouched" error message strategy', () => { ReactiveFormConfig.set({ "validationMessage": { "required": "This field is required." }, "reactiveForm": { "errorMessageBindingStrategy": ErrorMessageBindingStrategy.OnDirtyOrTouched } }); let user = new User(); user.address = new Address(); user.hobbies = new Array<Hobby>(); user.hobbies.push(new Hobby()); let formGroup = formbuilder.formGroup(user) as RxFormGroup; let addressFormGroup = formGroup.controls.address as FormGroup; let hobbyFormArray = formGroup.controls.hobbies as FormArray; let hobbyFormGroup = hobbyFormArray.controls[0] as FormGroup; expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe(undefined); //applied error decorator on password property expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe(undefined); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe(undefined); formGroup.controls.userName.markAsTouched(); addressFormGroup.controls.city.markAsDirty(); hobbyFormGroup.controls.name.markAsTouched(); expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe("This field is required."); expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe("This field is required."); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe("This field is required."); }) it('override error message strategy through error decorator', () => { ReactiveFormConfig.set({ "validationMessage": { "required": "This field is required." }, "reactiveForm": { "errorMessageBindingStrategy": ErrorMessageBindingStrategy.OnSubmit } }); let user = new User(); let formGroup = formbuilder.formGroup(user) as RxFormGroup; expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); formGroup.controls.password.markAsTouched(); expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe("This field is required."); }) it('"OnDirtyOrSubmit" error message strategy', () => { ReactiveFormConfig.set({ "validationMessage": { "required": "This field is required." }, "reactiveForm": { "errorMessageBindingStrategy": ErrorMessageBindingStrategy.OnDirtyOrSubmit } }); let user = new User(); user.address = new Address(); user.hobbies = new Array<Hobby>(); user.hobbies.push(new Hobby()); let formGroup = formbuilder.formGroup(user) as RxFormGroup; let addressFormGroup = formGroup.controls.address as FormGroup; let hobbyFormArray = formGroup.controls.hobbies as FormArray; let hobbyFormGroup = hobbyFormArray.controls[0] as FormGroup; expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe(undefined); //applied error decorator on password property expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe(undefined); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe(undefined); formGroup.submitted = true expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe("This field is required."); expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe("This field is required."); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe("This field is required."); }) it('"OnTouchedOrSubmit" error message strategy', () => { ReactiveFormConfig.set({ "validationMessage": { "required": "This field is required." }, "reactiveForm": { "errorMessageBindingStrategy": ErrorMessageBindingStrategy.OnTouchedOrSubmit } }); let user = new User(); user.address = new Address(); user.hobbies = new Array<Hobby>(); user.hobbies.push(new Hobby()); let formGroup = formbuilder.formGroup(user) as RxFormGroup; let addressFormGroup = formGroup.controls.address as FormGroup; let hobbyFormArray = formGroup.controls.hobbies as FormArray; let hobbyFormGroup = hobbyFormArray.controls[0] as FormGroup; expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe(undefined); //applied error decorator on password property expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe(undefined); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe(undefined); formGroup.controls.userName.markAsTouched(); addressFormGroup.controls.city.markAsTouched(); hobbyFormGroup.controls.name.markAsTouched(); expect((<RxFormControl>formGroup.controls.userName).errorMessage).toBe("This field is required."); expect((<RxFormControl>formGroup.controls.password).errorMessage).toBe(undefined); expect((<RxFormControl>addressFormGroup.controls.city).errorMessage).toBe("This field is required."); expect((<RxFormControl>hobbyFormGroup.controls.name).errorMessage).toBe("This field is required."); }) })
the_stack
var md5 = require('crypto-js/md5'); var encLatin1 = require('crypto-js/enc-latin1'); import node_crypto = require('crypto'); import uuid = require('uuid'); import { btoa } from './base/stringutil'; import agile_keychain_entries = require('./agile_keychain_entries'); import crypto = require('./base/crypto'); import key_agent = require('./key_agent'); import { bufferFromString, stringFromBuffer } from './base/collectionutil'; import PBKDF2 from './crypto/pbkdf2'; export class AESKeyParams { constructor(public key: string, public iv: string) {} } export class SaltedCipherText { constructor(public salt: string, public cipherText: string) {} } /** Generate encryption keys for an Agile Keychain vault from * a given password. * * This function generates a new random 1024-byte encryption key * for a vault and encrypts it using a key derived from @p password * using @p passIterations iterations of PBKDF2. */ export function generateMasterKey( password: string, passIterations: number ): Promise<agile_keychain_entries.EncryptionKeyList> { let masterKey = crypto.randomBytes(1024); let salt = crypto.randomBytes(8); return key_agent .keyFromPassword(password, salt, passIterations) .then(derivedKey => { return key_agent.encryptKey(derivedKey, masterKey); }) .then(encryptedKey => { let masterKeyEntry = { data: btoa('Salted__' + salt + encryptedKey.key), identifier: newUUID(), iterations: passIterations, level: 'SL5', validation: btoa(encryptedKey.validation), }; return <agile_keychain_entries.EncryptionKeyList>{ list: [masterKeyEntry], SL5: masterKeyEntry.identifier, }; }); } export function extractSaltAndCipherText(input: string): SaltedCipherText { if (input.slice(0, 8) != 'Salted__') { throw 'Ciphertext missing salt'; } var salt = input.substring(8, 16); var cipher = input.substring(16); return new SaltedCipherText(salt, cipher); } /** Derives an AES-128 key and initialization vector from a key of arbitrary length and salt * using. */ export async function openSSLKey( cryptoImpl: Crypto, password: string, salt: string ): Promise<AESKeyParams> { var data = password + salt; var key = await cryptoImpl.md5Digest(data); var iv = await cryptoImpl.md5Digest(key + data); return new AESKeyParams(key, iv); } /** Encrypt the JSON data for an item for storage in the Agile Keychain format. */ export async function encryptAgileKeychainItemData( cryptoImpl: Crypto, key: string, plainText: string ) { var salt = crypto.randomBytes(8); var keyParams = await openSSLKey(cryptoImpl, key, salt); return cryptoImpl .aesCbcEncrypt(keyParams.key, plainText, keyParams.iv) .then(encrypted => { return 'Salted__' + salt + encrypted; }); } /** Decrypt the encrypted contents of an item stored in the Agile Keychain format. */ export async function decryptAgileKeychainItemData( cryptoImpl: Crypto, key: string, cipherText: string ) { var saltCipher = extractSaltAndCipherText(cipherText); var keyParams = await openSSLKey(cryptoImpl, key, saltCipher.salt); return cryptoImpl.aesCbcDecrypt( keyParams.key, saltCipher.cipherText, keyParams.iv ); } /** Generate a V4 (random) UUID string in the form used * by items in an Agile Keychain: * - There are no hyphen separators between parts of the UUID * - All chars are upper case */ export function newUUID(): string { return uuid .v4() .toUpperCase() .replace(/-/g, ''); } /** * Crypto is an interface to common crypto algorithms required to decrypt * Agile Keychain vaults. * * All string parameters and return values are binary strings. */ export interface Crypto { /** * Decrypt @p cipherText using AES-CBC-128 with the given key and initialization vector. * * This *may* throw an exception if the key or initialization vector are incorrect. */ aesCbcDecrypt(key: string, cipherText: string, iv: string): Promise<string>; /** * Encrypt `plainText` using AES-CBC-128 with the given key and initialization vector. * * This *may* throw an exception if the key or initialization vector are invalid. */ aesCbcEncrypt(key: string, plainText: string, iv: string): Promise<string>; /** * Derive a key of length @p keyLen from a password using @p iterCount iterations * of PBKDF2 */ pbkdf2( masterPwd: string, salt: string, iterCount: number, keyLen: number ): Promise<string>; md5Digest(input: string): Promise<string>; } /** Crypto implementation using Node.js' crypto library. */ export class NodeCrypto implements Crypto { aesCbcDecrypt(key: string, cipherText: string, iv: string) { var keyBuf = new Buffer(key, 'binary'); var ivBuf = new Buffer(iv, 'binary'); var decipher = node_crypto.createDecipheriv( 'AES-128-CBC', keyBuf, ivBuf ); let result = decipher.update(cipherText, 'binary', 'binary'); result += decipher.final('binary'); return Promise.resolve<string>(result); } aesCbcEncrypt(key: string, plainText: string, iv: string): Promise<string> { var keyBuf = new Buffer(key, 'binary'); var ivBuf = new Buffer(iv, 'binary'); var cipher = node_crypto.createCipheriv('AES-128-CBC', keyBuf, ivBuf); var result = ''; result += cipher.update(plainText, 'binary', 'binary'); result += cipher.final('binary'); return Promise.resolve(result); } pbkdf2( masterPwd: string, salt: string, iterCount: number, keyLen: number ): Promise<string> { return new Promise((resolve, reject) => { const saltBuf = new Buffer(salt, 'binary'); node_crypto.pbkdf2( masterPwd, saltBuf, iterCount, keyLen, 'sha1', (err, derivedKey) => { if (err) { reject(err); return; } resolve(derivedKey.toString('binary')); } ); }); } async md5Digest(input: string): Promise<string> { var md5er = node_crypto.createHash('md5'); md5er.update(bufferFromString(input)); return md5er.digest('binary'); } } declare global { interface Crypto { // Prefixed implementation of SubtleCrypto in Safari // See https://blog.engelke.com/2015/03/02/apples-safari-browser-and-web-cryptography/ webkitSubtle: SubtleCrypto; } } let subtleCrypto: SubtleCrypto; if (typeof window !== 'undefined' && window.crypto) { subtleCrypto = window.crypto.subtle || window.crypto.webkitSubtle; } /** * Implements the Crypto interface using the Web Cryptography API * See https://www.w3.org/TR/WebCryptoAPI/ */ class WebCrypto implements Crypto { private crypto: SubtleCrypto; constructor() { this.crypto = subtleCrypto; } async aesCbcDecrypt(key: string, cipherText: string, iv: string) { const cryptoKey = await this.crypto.importKey( 'raw', bufferFromString(key), 'AES-CBC', false, ['decrypt'] ); const decrypted = await this.crypto.decrypt( { name: 'AES-CBC', iv: bufferFromString(iv) }, cryptoKey, bufferFromString(cipherText) ); return stringFromBuffer(new Uint8Array(decrypted)); } async aesCbcEncrypt(key: string, plainText: string, iv: string) { const cryptoKey = await this.crypto.importKey( 'raw', bufferFromString(key), 'AES-CBC', false, ['encrypt'] ); const encrypted = await this.crypto.encrypt( { name: 'AES-CBC', iv: bufferFromString(iv) }, cryptoKey, bufferFromString(plainText) ); return stringFromBuffer(new Uint8Array(encrypted)); } async pbkdf2( masterPwd: string, salt: string, iterCount: number, keyLen: number ) { try { // Try to derive the key using WebCrypto APIs const masterKey = await this.crypto.importKey( 'raw', bufferFromString(masterPwd), 'PBKDF2', false, ['deriveKey'] ); const derived = await this.crypto.deriveKey( { name: 'PBKDF2', salt: bufferFromString(salt), iterations: iterCount, hash: 'SHA-1', }, masterKey, { name: 'AES-CBC', length: 256 }, true /* extractable */, ['encrypt', 'decrypt'] ); const extracted = await this.crypto.exportKey('raw', derived); return stringFromBuffer(new Uint8Array(extracted)); } catch (err) { err = err; // Work around babel/minify#635 // If the WebCrypto implementation does not support PBKDF2 (eg. // Safari <= 10), fall back to our JS implementation. const pbkdf2 = new PBKDF2(); const passwordBuf = bufferFromString(masterPwd); const saltBuf = bufferFromString(salt); return stringFromBuffer( pbkdf2.key(passwordBuf, saltBuf, iterCount, keyLen) ); } } async md5Digest(input: string) { // WebCrypto does not support MD5 :( return md5(encLatin1.parse(input)).toString(encLatin1); } } export var defaultCrypto: Crypto; if (subtleCrypto) { defaultCrypto = new WebCrypto(); } else { defaultCrypto = new NodeCrypto(); }
the_stack
import assert from 'assert'; import * as fs from 'fs'; import path from 'path'; import { Ast, Type } from 'thingtalk'; import * as Tp from 'thingpedia'; import * as utils from '../../../lib/utils/misc-utils'; import { makeLookupKeys } from '../../../lib/dataset-tools/mturk/sample-utils'; import EnglishLanguagePack from '../../../lib/i18n/english'; import { clean } from '../../../lib/utils/misc-utils'; import CanonicalExtractor from './canonical-extractor'; import genBaseCanonical from './base-canonical-generator'; import { PARTS_OF_SPEECH, Canonicals, CanonicalAnnotation } from './base-canonical-generator'; import { ParaphraseExample, generateExamples } from './canonical-example-constructor'; import Paraphraser from './canonical-example-paraphraser'; interface AutoCanonicalGeneratorOptions { dataset : 'schemaorg'|'sgd'|'multiwoz'|'wikidata'|'custom', paraphraser_model : string, remove_existing_canonicals : boolean, type_based_projection : boolean, max_per_pos ?: number, batch_size : number, filtering : boolean, debug : boolean } interface Constant { value ?: any, display : string } function getElemType(type : Type) : Type { if (type instanceof Type.Array) return getElemType(type.elem as Type); return type; } function typeToString(type : Type) : string { const elemType = getElemType(type); if (elemType instanceof Type.Entity) return elemType.type; return type.toString(); } function countArgTypes(schema : Ast.FunctionDef) : Record<string, number> { const count : Record<string, number> = {}; for (const arg of schema.iterateArguments()) { const typestr = typeToString(arg.type); if (!typestr) continue; count[typestr] = (count[typestr] || 0) + 1; } return count; } export default class AutoCanonicalGenerator { private class : Ast.ClassDef; private entities : Tp.BaseClient.EntityTypeRecord[]; private constants : Record<string, Constant[]>; private functions : string[]; private paraphraserModel : string; private annotatedProperties : string[]; private langPack : EnglishLanguagePack; private options : AutoCanonicalGeneratorOptions; private entityNames : Record<string, string>; private childEntities : Record<string, string[]>; constructor(classDef : Ast.ClassDef, entities : Tp.BaseClient.EntityTypeRecord[], constants : Record<string, any[]>, functions : string[], options : AutoCanonicalGeneratorOptions) { this.class = classDef; this.entities = entities; this.constants = constants; this.functions = functions ? functions : Object.keys(classDef.queries).concat(Object.keys(classDef.actions)); this.paraphraserModel = options.paraphraser_model; this.annotatedProperties = []; this.langPack = new EnglishLanguagePack('en-US'); this.options = options; this.entityNames = {}; this.childEntities = {}; for (const entity of this.entities) { this.entityNames[entity.type] = entity.name; if (entity.subtype_of) { for (const parent of entity.subtype_of) { if (parent in this.childEntities) this.childEntities[parent].push(entity.name); else this.childEntities[parent] = [entity.name]; } } } } async generate() { await this._loadManualCanonicalOverride(); const examples : ParaphraseExample[] = []; for (const fname of this.functions) { const func = this.class.queries[fname] || this.class.actions[fname]; const typeCounts = countArgTypes(func); for (const arg of func.iterateArguments()) { // skip argument with existed annotations if (this.annotatedProperties.includes(arg.name) || arg.name === 'id') continue; if (arg.name.includes('.') && this.annotatedProperties.includes(arg.name.slice(arg.name.indexOf('.') + 1))) continue; // set starting canonical annotation const sampleValues = this._retrieveSamples(fname, arg); const canonicalAnnotation = this._generateBaseCanonicalAnnotation(func, arg, typeCounts); examples.push(...generateExamples(func, arg, canonicalAnnotation, sampleValues)); } } const paraphraser = new Paraphraser(this.paraphraserModel, this.options); const startTime = (new Date()).getTime(); await paraphraser.paraphrase(examples); if (this.options.debug) { const time = Math.round(((new Date()).getTime() - startTime) / 1000); console.log(`Paraphraser took ${time} seconds to run.`); } const extractor = new CanonicalExtractor(this.class, this.functions, this.options); await extractor.run(examples); this._addProjectionCanonicals(); this._trimAnnotations(); return this.class; } private async _loadManualCanonicalOverride() { const file = path.resolve(path.dirname(module.filename), `../${this.options.dataset}/manual-annotations.js`); if (!fs.existsSync(file)) return; const manualAnnotations = await import(`../${this.options.dataset}/manual-annotations.js`); if (manualAnnotations.PROPERTY_CANONICAL_OVERRIDE) this.annotatedProperties = Object.keys(manualAnnotations.PROPERTY_CANONICAL_OVERRIDE); } private _generateBaseCanonicalAnnotation(func : Ast.FunctionDef, arg : Ast.ArgumentDef, typeCounts : Record<string, number>) : CanonicalAnnotation { const canonicalAnnotation : CanonicalAnnotation = {}; if (this.options.remove_existing_canonicals) { genBaseCanonical(canonicalAnnotation, arg.name, arg.type); } else { const existingCanonical : Record<string, any> = arg.getNaturalLanguageAnnotation('canonical') || {}; if (typeof existingCanonical === 'string') canonicalAnnotation.base = [existingCanonical]; else if (Array.isArray(existingCanonical)) canonicalAnnotation.base = existingCanonical; else if (typeof existingCanonical === 'object') Object.assign(canonicalAnnotation, existingCanonical); } // remove function name in arg name, normally it's repetitive for (const [key, value] of Object.entries(canonicalAnnotation)) { if (PARTS_OF_SPEECH.includes(key)) { canonicalAnnotation[key as keyof Canonicals] = value.map((c : string) => { if (c.startsWith(func.name.toLowerCase() + ' ')) return c.slice(func.name.toLowerCase().length + 1); return c; }); } } // copy base canonical if property canonical is missing if (canonicalAnnotation.base && !canonicalAnnotation.property) canonicalAnnotation.property = [...canonicalAnnotation.base]; const typestr = typeToString(func.getArgType(arg.name)!); if (typestr && typeCounts[typestr] === 1) { // if an entity is unique, allow dropping the property name entirely // FIXME: consider type hierarchy, or probably drop it entirely if (canonicalAnnotation.property && !this.functions.includes(typestr.substring(typestr.indexOf(':') + 1))) { if (!canonicalAnnotation.property.includes('#')) canonicalAnnotation.property.push('#'); } // if property is missing, use the type information if (!('property' in canonicalAnnotation)) { const base = utils.clean(typestr.substring(typestr.indexOf(':') + 1)); canonicalAnnotation['property'] = [base]; canonicalAnnotation['base'] = [base]; } // if it's the only people entity, adding adjective form // E.g., author for review - bob's review // byArtist for MusicRecording - bob's song if (typestr.endsWith(':Person')) canonicalAnnotation.adjective = ["# 's", '#']; // if it's the only date, adding argmin/argmax/base_projection if (typestr === 'Date') { canonicalAnnotation.adjective_argmax = ["most recent", "latest", "last", "newest"]; canonicalAnnotation.adjective_argmin = ["earliest", "first", "oldest"]; canonicalAnnotation.base_projection = ['date']; } } return canonicalAnnotation; } private _addProjectionCanonicals() { for (const fname of this.functions) { const func = this.class.queries[fname] || this.class.actions[fname]; for (const arg of func.iterateArguments()) { if (this.annotatedProperties.includes(arg.name) || arg.name === 'id') continue; if (arg.type.isBoolean) continue; const canonicals = arg.metadata.canonical; if (!canonicals) continue; if (typeof canonicals === 'string' || Array.isArray(canonicals)) continue; const elemType = arg.type instanceof Type.Array ? arg.type.elem: arg.type; assert(elemType instanceof Type); if (elemType instanceof Type.Entity && this.options.type_based_projection && !('base_projection' in canonicals)) { const entityType = elemType.type; if (this.entityNames[entityType]) canonicals['base_projection'] = [this.entityNames[entityType]]; if (this.childEntities[entityType]) canonicals['base_projection'].push(...this.childEntities[entityType]); } for (const cat in canonicals) { if (['default', 'adjective', 'implicit_identity', 'projection_pronoun'].includes(cat)) continue; if (cat.endsWith('_projection')) continue; if (cat.endsWith('_argmin') || cat.endsWith('_argmax')) continue; if (`${cat}_projection` in canonicals) continue; if (cat === 'passive_verb' || cat === 'verb') { canonicals[cat + '_projection'] = canonicals[cat].map((canonical : string) => { return this._processProjectionCanonical(canonical, cat); }).filter(Boolean).map((c : string) => { const tokens = c.split(' '); if (tokens.length === 1) return c; if (['IN', 'TO', 'PR'].includes(this.langPack.posTag(tokens)[tokens.length - 1])) return [...tokens.slice(0, -1), '//', tokens[tokens.length - 1]].join(' '); return c; }).filter((v : string, i : number, self : string[]) => self.indexOf(v) === i); } else { canonicals[cat + '_projection'] = canonicals[cat].map((canonical : string) => { return this._processProjectionCanonical(canonical, cat); }).filter(Boolean).filter((v : string, i : number, self : string[]) => self.indexOf(v) === i); } } } } } private _processProjectionCanonical(canonical : string, cat : string) { if (canonical.includes('#') && !canonical.endsWith(' #')) return null; canonical = canonical.replace(' #', ''); if (canonical.endsWith(' a') || canonical.endsWith(' an') || canonical.endsWith(' the')) canonical = canonical.substring(0, canonical.lastIndexOf(' ')); if (canonical.split(' ').length > 1 && cat === 'preposition') return null; return canonical; } private _retrieveSamples(qname : string, arg : Ast.ArgumentDef) : string[] { //TODO: also use enum canonicals? if (arg.type instanceof Type.Enum) return arg.type.entries!.slice(0, 10).map(clean); const keys = makeLookupKeys('@' + this.class.kind + '.' + qname, arg.name, arg.type); let sampleConstants : Constant[] = []; for (const key of keys) { if (this.constants[key]) { sampleConstants = this.constants[key]; break; } } return sampleConstants.map((v) => { if (arg.type.isString || (arg.type instanceof Type.Array && (arg.type.elem as Type).isString)) return v.value; return v.display; }); } private _trimAnnotations() { if (!this.options.max_per_pos) return; for (const fname of this.functions) { const func = this.class.queries[fname] || this.class.actions[fname]; for (const arg of func.iterateArguments()) { if (this.annotatedProperties.includes(arg.name) || arg.name === 'id') continue; const canonicalAnnotation = arg.metadata.canonical; for (const pos in canonicalAnnotation) { if (pos === 'default') continue; canonicalAnnotation[pos] = canonicalAnnotation[pos].slice(0, this.options.max_per_pos); } } } } }
the_stack
export type Field = string; export interface TransformParamsBase { /** The type of the transform to be applied */ type: string; } export interface IdentifierParams extends TransformParamsBase { type: "identifier"; /** * **Default:** `"_uniqueId"` */ as?: string; } export interface FilterParams extends TransformParamsBase { type: "filter"; /** An expression string. The data object is removed if the expression evaluates to false. */ expr: string; } export interface FormulaParams extends TransformParamsBase { type: "formula"; /** An expression string */ expr: string; /** The (new) field where the computed value is written to */ as: string; } export interface ProjectParams extends TransformParamsBase { type: "project"; /** * The fields to be projected. */ fields: Field[]; /** * New names for the projected fields. If omitted, the names of the source fields are used. */ as?: string[]; } export interface RegexExtractParams extends TransformParamsBase { type: "regexExtract"; /** * A valid JavaScript regular expression with at least one group. For example: `"^Sample(\\d+)$"`. * * Read more at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions **/ regex: string; /** * The source field */ field: Field; /** * The new field or an array of fields where the extracted values are written. */ as: string | string[]; /** * Do not complain about invalid input. Just skip it and leave the new fields undefined on the affected datum. * * **Default:** `false` **/ skipInvalidInput?: boolean; } export interface RegexFoldParams extends TransformParamsBase { type: "regexFold"; /** * A regular expression that matches to column names. The regex must have one * capturing group that is used for extracting the key (e.g., a sample id) * from the column name. */ columnRegex: string[] | string; /** * A new column name for the extracted values. */ asValue: string[] | string; /** * An optional regex that matches to fields that should not be included * in the new folded data objects. */ skipRegex?: string; /** * **Default:** `"sample"` */ asKey?: string; } export type SortOrder = "ascending" | "descending"; export interface CompareParams { /** * The field(s) to sort by */ field: Field[] | Field; /** * The order(s) to use: `"ascending"` (default), `"descending"`. */ order?: SortOrder[] | SortOrder; } export interface StackParams extends TransformParamsBase { type: "stack"; /** * The field to stack. If no field is defined, a constant value of one is assumed. */ field?: Field; /** * The fields to be used for forming groups for different stacks. */ groupby: Field[]; /** * The sort order of data in each stack. */ sort?: CompareParams; /** * How to offset the values in a stack. * `"zero"` (default) starts stacking at 0. * `"center"` centers the values around zero. * `"normalize"` computes intra-stack percentages and normalizes the values to the range of `[0, 1]`. * `"information"` computes a layout for a sequence logo. The total height of the stack reflects * the group's information content. */ offset?: "zero" | "center" | "normalize" | "information"; /** * Fields to write the stacked values. * * **Default:** `["y0", "y1"]` */ as: string[]; /** * Cardinality, e.g., the number if distinct bases or amino acids. Used for * information content calculation when the offset is `"information"`. * * **Default:** `4`; */ cardinality?: number; /** * The field that contains the base or amino acid. Used for * information content calculation when the offset is `"information"`. * The data items that have `null` in the baseField are considered gaps * and they are taken into account when scaling the the locus' information * content. */ baseField?: Field; } export interface AggregateParams extends TransformParamsBase { type: "aggregate"; /** * Which fields to use for grouping. Missing `groupby` results in a single * group that includes all the data items. */ groupby?: Field[]; } export interface FlattenDelimitedParams extends TransformParamsBase { type: "flattenDelimited"; /** * The field(s) to split and flatten */ field: Field[] | Field; /** * Separator(s) used on the field(s) * TODO: Rename to delimiter */ separator: string[] | string; /** * The output field name(s) for the flattened field. * * **Default:** the input fields. */ as?: string[] | string; } export interface FlattenSequenceParams extends TransformParamsBase { type: "flattenSequence"; /** * The field to flatten. * * **Default:** `"sequence"` */ field?: Field; /** * Name of the fields where the zero-based index number and flattened * sequence letter are written to. * * **Default:** `["pos", "sequence"]` */ as?: [string, string]; } export interface PileupParams extends TransformParamsBase { type: "pileup"; /** * The field representing the start coordinate of the segment (inclusive). */ start: Field; /** * The field representing the end coordinate of the segment (exclusive). */ end: Field; /** * The output field name for the computed lane. * * **Default:** `"lane"`. */ as?: string; /** * The spacing between adjacent segments on the same lane in coordinate units. * * **Default:** `1`. */ spacing?: number; /** * An optional field indicating the preferred lane. Use together with the * `preferredOrder` property. */ preference?: Field; /** * The order of the lane preferences. The first element contains the value that * should place the segment on the first lane and so forth. * If the preferred lane is occupied, the first available lane is taken. */ preferredOrder?: string[] | number[] | boolean[]; } export interface CoverageParams extends TransformParamsBase { type: "coverage"; /** * An optional chromosome field that is passed through. TODO: groupby */ chrom?: Field; /** * The field representing the start coordinate of the segment (inclusive). */ start: Field; /** * The field representing the end coordinate of the segment (exclusive). */ end: Field; /** * A field representing an optional weight for the segment. Can be used with * copy ratios, for example. */ weight?: Field; /** * The output field for the computed coverage. */ as?: string; /** * The output field for the chromosome. * * **Default:** Same as `chrom` */ asChrom?: string; /** * The output field for the start coordinate. * * **Default:** Same as `start` */ asStart?: string; /** * The output field for the end coordinate. * * **Default:** Same as `end` */ asEnd?: string; } export interface CollectParams extends TransformParamsBase { type: "collect"; /** * Arranges the data into consecutive batches based on the groups. * This is mainly intended for internal use so that faceted data can * be handled as batches. */ groupby?: Field[]; /** * The sort order. */ sort?: CompareParams; } export interface SampleParams extends TransformParamsBase { type: "sample"; /** * The maximum sample size. * * **Default:** `500` */ size?: number; } export interface MeasureTextParams extends TransformParamsBase { type: "measureText"; field: Field; fontSize: number; as: string; // TODO: FontFamily etc } export interface MergeFacetsParams extends TransformParamsBase { type: "mergeFacets"; } export interface LinearizeGenomicCoordinateParams extends TransformParamsBase { type: "linearizeGenomicCoordinate"; /** * Get the genome assembly from the scale of the channel. * * **Default:** `"x"` */ channel?: "x" | "y"; /** * The chromosome/contig field */ chrom: Field; /** * The field or fields that contain intra-chromosomal positions */ pos: Field | Field[]; /** * An offset or offsets that allow for adjusting the numbering base. The offset * is subtracted from the positions. * * GenomeSpy uses internally zero-based indexing with half-open intervals. * UCSC-based formats (BED, etc.) generally use this scheme. However, for example, * VCF files use one-based indexing and must be adjusted by setting the offset to * `1`. * * **Default:** `0` */ offset?: number | number[]; /** * The output field or fields for linearized coordinates. */ as: string | string[]; } export interface FilterScoredLabelsParams extends TransformParamsBase { type: "filterScoredLabels"; /** * The field representing the score used for prioritization. */ score: Field; /** * The field representing element's width in pixels */ width: Field; /** * The field representing element's position on the domain. */ pos: Field; /** * An optional field representing element's lane, e.g., if transcripts * are shown using a piled up layout. */ lane?: Field; /** * Padding (in pixels) around the element. * * **Default:** `0` */ padding?: number; /** * **Default:** `"x"` */ channel?: "x" | "y"; } export interface FlattenCompressedExonsParams extends TransformParamsBase { type: "flattenCompressedExons"; /** * The field containing the exons. * * **Default:** `"exons"` */ exons?: Field; /** * Start coordinate of the gene body. * * **Default:** `"start"` */ start?: Field; /** * Field names for the flattened exons. * * **Default:** `["exonStart", "exonEnd"]` */ as?: [string, string]; } export type TransformParams = | AggregateParams | CollectParams | CoverageParams | FlattenDelimitedParams | FormulaParams | FilterParams | FilterScoredLabelsParams | FlattenCompressedExonsParams | FlattenSequenceParams | IdentifierParams | LinearizeGenomicCoordinateParams | MeasureTextParams | MergeFacetsParams | PileupParams | ProjectParams | RegexExtractParams | RegexFoldParams | SampleParams | StackParams;
the_stack
import memorize from 'memorize-decorator'; import { FieldRequest } from '../graphql/query-distiller'; import { Field, ObjectType } from '../model'; import { NOT_SUPPORTED_ERROR, PropertyAccessQueryNode, QueryNode, RuntimeErrorQueryNode } from '../query-tree'; import { FieldContext, SelectionToken } from './query-node-object-type'; export interface ProcessFieldResult { /** * If the RootFieldHelper can already resolve this fields, this will be populated with the value. */ readonly resultNode: QueryNode | undefined; /** * The source node, which might differ from the sourceNode passed in in case of root entity capture. * * Only relevant if resultNode is undefined. */ readonly sourceNode: QueryNode; /** * if this field is a collect field, specifies whether it should capture root entities */ readonly captureRootEntitiesOnCollectFields: boolean; } interface HierarchyStackFrame { readonly currentEntityNode?: QueryNode; readonly parentEntityFrame?: HierarchyStackFrame; // keep root explicitly because sometimes, we might have the root entity, but not the parent entity readonly rootEntityNode?: QueryNode; } export class RootFieldHelper { private readonly hierarchyStackFramesBySelection = new WeakMap<SelectionToken, HierarchyStackFrame>(); private readonly fieldsBySelection = new WeakMap<SelectionToken, Field>(); private readonly selectionsThatCaptureRootEntities = new WeakSet<SelectionToken>(); /** * Should be called whenever a field is resolved. Will maintain a hierarchy structure, and may produce a value node */ processField(field: Field, sourceNode: QueryNode, fieldContext: FieldContext): ProcessFieldResult { const parentSelectionToken = fieldContext.selectionTokenStack.length >= 2 ? fieldContext.selectionTokenStack[fieldContext.selectionTokenStack.length - 2] : new SelectionToken(); /* { root { // parent = null, root = null, this = root relation { // parent = null, root = null, this = relation extension { // parent = relation, root = relation, this = relation child { // parent = relation, root = relation, this = child grandchild { // parent = child, root = relation, this = grandchild parent { // stack.up: => parent = relation, root = relation, this = child parent { } } root } } } } } } */ // remember the field of this layer, will be used one layer deeper this.setFieldAtSelection(fieldContext.selectionToken, field); const existingHierarchyFrame = this.getHierarchyStackFrame(fieldContext.selectionToken); const outerField = this.getFieldAtSelection(parentSelectionToken); let collectRootNode: QueryNode | undefined; if (this.capturesRootEntity(parentSelectionToken)) { collectRootNode = new PropertyAccessQueryNode(sourceNode, 'root'); // we will return the sourceNode below sourceNode = new PropertyAccessQueryNode(sourceNode, 'obj'); } // if this is the first time at this layer, calculate the hierarchy frame for this layer let hierarchyFrame: HierarchyStackFrame; if (existingHierarchyFrame) { hierarchyFrame = existingHierarchyFrame; } else { const outerFrame = this.getHierarchyStackFrame(parentSelectionToken); // regular fields (e.g. entity extensions) just keep parent/root. Only when we navigate into child or root // entities, we need to change them. if (!outerField || outerField.type.isRootEntityType) { // navigating into a root entity completely resets the hierarchy, you can never navigate "more up" // also, if there is no outer field, we're at a root field (single or multiple) hierarchyFrame = { currentEntityNode: sourceNode, rootEntityNode: sourceNode }; } else if (outerField.collectPath) { const currentEntityNode = outerField.type.isRootEntityType || outerField.type.isChildEntityType ? sourceNode : undefined; if (outerField.collectPath.traversesRootEntityTypes) { // traversing root entities, so need to take new root. parent is not available. hierarchyFrame = { currentEntityNode, rootEntityNode: collectRootNode }; } else { // not traversing root entities just throw away the parent but keep root hierarchyFrame = { currentEntityNode, rootEntityNode: outerFrame?.rootEntityNode }; } } else if (outerField.type.isChildEntityType) { hierarchyFrame = { currentEntityNode: sourceNode, parentEntityFrame: outerFrame, rootEntityNode: outerFrame?.rootEntityNode }; } else { // other than that, there are not any fields that cross entity boundaries hierarchyFrame = outerFrame || {}; } this.setHierarchyStackFrame(fieldContext.selectionToken, hierarchyFrame); } const captureRootEntitiesOnCollectFields = this.shouldCaptureRootEntity( field, fieldContext.selectionStack[fieldContext.selectionStack.length - 1].fieldRequest ); if (captureRootEntitiesOnCollectFields) { this.selectionsThatCaptureRootEntities.add(fieldContext.selectionToken); } return { sourceNode, resultNode: this.tryResolveField(field, hierarchyFrame), captureRootEntitiesOnCollectFields }; } getRealItemNode(itemNode: QueryNode, fieldContext: FieldContext) { if (this.capturesRootEntity(fieldContext.selectionToken)) { return new PropertyAccessQueryNode(itemNode, 'obj'); } return itemNode; } /** * Determines whether a selection has been instructed (by captureRootEntitiesOnCollectFields) to capture root entities */ capturesRootEntity(selectionToken: SelectionToken) { return this.selectionsThatCaptureRootEntities.has(selectionToken); } private tryResolveField(field: Field, hierarchyFrame: HierarchyStackFrame): QueryNode | undefined { let resultNode: QueryNode | undefined; // parent fields that have root entity types are effectively root fields, and those are a bit easier to manage, // so use the logic for root fields in these cases. if (field.isRootField || (field.isParentField && field.type.isRootEntityType)) { if (!hierarchyFrame.rootEntityNode) { return new RuntimeErrorQueryNode(`Root entity is not available here`, { code: NOT_SUPPORTED_ERROR }); } else { return hierarchyFrame.rootEntityNode; } } else if (field.isParentField) { if (!hierarchyFrame.parentEntityFrame?.currentEntityNode) { return new RuntimeErrorQueryNode(`Parent entity is not available here`, { code: NOT_SUPPORTED_ERROR }); } return hierarchyFrame.parentEntityFrame.currentEntityNode; } return undefined; } private shouldCaptureRootEntity(field: Field, fieldRequest: FieldRequest) { if (!field.collectPath) { return false; } // we will only ever need it for collect paths that cross both inter- and intra-root-entity fields // (and it's not allowed to capture it in other cases anyway) // we also only need it if the result is a child entity type. It can't be an entity extension (that would be a // validation error), and value objects can't declare parent fields. // note that isChildEntityType + traversesRootEntityTypes implies that there are field traversals as well. if (!field.type.isChildEntityType || !field.collectPath.traversesRootEntityTypes) { return false; } return this.selectsRootField(fieldRequest, field.type); } // caching is helpful because it might get called further down in the hierarchy again // caching is ok because it only keeps a small boolean in the case of a kept-alive FieldRequest @memorize() private selectsRootField(fieldRequest: FieldRequest, type: ObjectType): boolean { // hasReachableRootField can be cached request-independently, so we can save the time to crawl the selections // if we know there aren't any reachable root fields if (!this.hasReachableRootField(type)) { return false; } // assumes that parent/root fields, child entity fields and entity extension fields are always called // exactly like in the model (to do this properly, using the output-type-generator itself, we would need several // passes, or we would need to run the query-node-generator upfront and associate metadata with the // QueryNodeFields return fieldRequest.selectionSet.some(f => { const field = type.getField(f.fieldRequest.field.name); if (!field) { return false; } if (field.isRootField || (field.isParentField && field.type.isRootEntityType)) { return true; } // don't walk out of the current root entity, we're not interested in them (that would change the root) if ( (field.type.isChildEntityType || field.type.isEntityExtensionType) && (!field.collectPath || !field.collectPath.traversesRootEntityTypes) ) { return this.selectsRootField(f.fieldRequest, field.type); } return false; }); } /** * Determines whether a @root field can be reached from anywhere within the given type. * * Stops at root entity boundaries */ @memorize() private hasReachableRootField(type: ObjectType): boolean { const seen = new Set<ObjectType>([type]); let fringe = [type]; do { const newFringe: ObjectType[] = []; for (const type of fringe) { for (const field of type.fields) { // parent fields of root entity types are basically root fields (and they will make use of captureRootEntity) if (field.isRootField || (field.isParentField && field.type.isRootEntityType)) { return true; } if ( (field.type.isChildEntityType || field.type.isEntityExtensionType) && !seen.has(field.type) && (!field.collectPath || !field.collectPath.traversesRootEntityTypes) ) { seen.add(field.type); newFringe.push(field.type); } } } fringe = newFringe; } while (fringe.length); return false; } private getHierarchyStackFrame(selectionToken: SelectionToken): HierarchyStackFrame | undefined { return this.hierarchyStackFramesBySelection.get(selectionToken); } private setHierarchyStackFrame(selectionToken: SelectionToken, stackFrame: HierarchyStackFrame) { if (this.hierarchyStackFramesBySelection.has(selectionToken)) { throw new Error(`HierarchyStackFrame for this token already exists`); } this.hierarchyStackFramesBySelection.set(selectionToken, stackFrame); } private getFieldAtSelection(selectionToken: SelectionToken): Field | undefined { return this.fieldsBySelection.get(selectionToken); } private setFieldAtSelection(selectionToken: SelectionToken, field: Field) { if (this.fieldsBySelection.has(selectionToken)) { throw new Error(`Field for this token already exists`); } this.fieldsBySelection.set(selectionToken, field); } }
the_stack
import path = require('path'); import { rollup, RollupOptions, RollupOutput, OutputOptions, OutputChunk } from 'rollup'; import Tacks = require('tacks'); import tempy = require('tempy'); import pMap = require('p-map'); import pectinCore from '../lib/pectin-core'; const { Dir, File, Symlink } = Tacks; // avoid polluting other test state const REPO_ROOT = path.resolve('.'); afterEach(() => { process.chdir(REPO_ROOT); }); function createFixture(pkgSpec): string { const cwd = tempy.directory(); const fixture = new Tacks( Dir({ // .babelrc is necessary to avoid an // implicit resolution from repo root '.babelrc': File({ presets: ['@babel/env', '@babel/preset-react'], plugins: ['@babel/plugin-syntax-dynamic-import'], }), // spicy symlink necessary due to explicit cwd config 'node_modules': Symlink(path.relative(cwd, path.join(REPO_ROOT, 'node_modules'))), ...pkgSpec, }) ); fixture.create(cwd); return cwd; } async function generateResults(configs: RollupOptions[]): Promise<OutputChunk[]> { const results = await pMap(configs, ({ output: outputOptions, ...inputOptions }) => rollup(inputOptions).then(bundle => Promise.all( (outputOptions as OutputOptions[]).map((opts: OutputOptions) => bundle.generate(opts) ) ).then((generated: RollupOutput[]) => generated.reduce( (arr: OutputChunk[], result) => arr.concat((result.output as unknown) as OutputChunk), [] ) ) ) ); // flatten results return results.reduce((arr, result) => arr.concat(result), []); } describe('pectin-core', () => { it('inlines SVG via pkg.rollup.inlineSVG', async () => { const pkg = { name: 'inline-svg-data-uri', main: 'dist/index.js', rollup: { inlineSVG: true, }, }; const cwd = createFixture({ 'package.json': File(pkg), 'src': Dir({ 'test.svg': File( `<?xml version="1.0" ?><svg xmlns="http://www.w3.org/2000/svg" />` ), 'index.js': File(` import svgTest from './test.svg'; export default svgTest; `), }), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const [entry] = results; expect(entry.code).toMatchInlineSnapshot(` "'use strict'; var svgTest = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAvPg=='; module.exports = svgTest; " `); }); it('customizes input with pkg.rollup.rootDir', async () => { const pkg = { name: 'rollup-root-dir', main: 'dist/rollup-root-dir.js', rollup: { rootDir: 'modules', }, }; const cwd = createFixture({ 'package.json': File(pkg), 'modules': Dir({ 'rollup-root-dir.js': File(`export default 'success';`), }), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const [entry] = results; expect(entry.fileName).toBe('rollup-root-dir.js'); expect(entry.code).toMatchInlineSnapshot(` "'use strict'; var rollupRootDir = 'success'; module.exports = rollupRootDir; " `); }); it('overrides input with pkg.rollup.input', async () => { const pkg = { name: 'rollup-input', main: 'dist/rollup-input.js', rollup: { input: 'app.js', }, }; const cwd = createFixture({ 'package.json': File(pkg), 'app.js': File(`export default 'app';`), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const [entry] = results; expect(entry.code).toMatchInlineSnapshot(` "'use strict'; var app = 'app'; module.exports = app; " `); }); it('resolves pkgPath from cwd', async () => { const pkg = { name: 'from-cwd', main: 'dist/index.js', }; const cwd = createFixture({ 'package.json': File(pkg), 'src': Dir({ 'index.js': File(`export default 'cwd';`), }), }); process.chdir(cwd); const configs = await pectinCore(pkg /* , { cwd } */); const results = await generateResults(configs); const [entry] = results; expect(entry.code).toMatchInlineSnapshot(` "'use strict'; var index = 'cwd'; module.exports = index; " `); }); it('throws an error when no pkg.main supplied', async () => { const pkg = { name: 'no-pkg-main', }; const cwd = createFixture({ 'package.json': File(pkg), }); // required to normalize snapshot process.chdir(cwd); try { await pectinCore(pkg, { cwd }); } catch (err) { expect(err).toMatchInlineSnapshot( `[TypeError: required field 'main' missing in package.json]` ); } expect.assertions(1); }); it('generates chunked module output', async () => { const pkg = { name: 'chunked-module-outputs', main: './dist/index.js', module: './dist/index.esm.js', rollup: { // can't use [hash] in chunks because it changes _every_ execution chunkFileNames: '[name].[format].js', }, }; const cwd = createFixture({ 'package.json': File(pkg), 'src': Dir({ 'chunky-bacon.js': File(`export default '_why';`), 'index.js': File(` export default function main() { return import('./chunky-bacon'); }; `), }), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const fileNames = results.map(result => `dist/${result.fileName}`); const [cjsEntry, cjsChunk, esmEntry, esmChunk] = results.map( result => `// dist/${result.fileName}\n${result.code}` ); expect(fileNames).toStrictEqual([ 'dist/index.js', 'dist/chunky-bacon.cjs.js', 'dist/index.esm.js', 'dist/chunky-bacon.esm.js', ]); expect(cjsEntry).toMatchInlineSnapshot(` "// dist/index.js 'use strict'; function main() { return new Promise(function (resolve) { resolve(require('./chunky-bacon.cjs.js')); }); } module.exports = main; " `); expect(cjsChunk).toMatchInlineSnapshot(` "// dist/chunky-bacon.cjs.js 'use strict'; var chunkyBacon = '_why'; exports.default = chunkyBacon; " `); expect(esmEntry).toMatchInlineSnapshot(` "// dist/index.esm.js function main() { return import('./chunky-bacon.esm.js'); } export default main; " `); expect(esmChunk).toMatchInlineSnapshot(` "// dist/chunky-bacon.esm.js var chunkyBacon = '_why'; export default chunkyBacon; " `); }); it('generates basic pkg.browser output', async () => { const pkg = { name: 'basic-browser-outputs', main: './dist/index.js', module: './dist/index.esm.js', browser: './dist/index.browser.js', }; const cwd = createFixture({ 'package.json': File(pkg), 'src': Dir({ 'index.js': File(` export default class Basic { constructor() { this.isBrowser = process.env.BROWSER; } }; `), }), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const fileNames = results.map(result => `dist/${result.fileName}`); const [cjsMain, esmModule, cjsBrowser] = results.map( result => `// dist/${result.fileName}\n${result.code}` ); expect(fileNames).toStrictEqual([ 'dist/index.js', 'dist/index.esm.js', 'dist/index.browser.js', ]); expect(cjsMain).toMatchInlineSnapshot(` "// dist/index.js 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\\"Cannot call a class as a function\\"); } } var Basic = function Basic() { _classCallCheck(this, Basic); this.isBrowser = false; }; module.exports = Basic; " `); expect(esmModule).toMatchInlineSnapshot(` "// dist/index.esm.js function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\\"Cannot call a class as a function\\"); } } var Basic = function Basic() { _classCallCheck(this, Basic); this.isBrowser = false; }; export default Basic; " `); expect(cjsBrowser).toMatchInlineSnapshot(` "// dist/index.browser.js 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\\"Cannot call a class as a function\\"); } } var Basic = function Basic() { _classCallCheck(this, Basic); this.isBrowser = true; }; module.exports = Basic; " `); }); it('generates advanced pkg.browser outputs', async () => { const pkg = { name: 'advanced-browser-outputs', main: './dist/index.js', module: './dist/index.esm.js', browser: { './dist/index.js': './dist/index.browser.js', './dist/index.esm.js': './dist/index.module.browser.js', }, dependencies: { '@babel/runtime': '^7.0.0', }, }; const cwd = createFixture({ 'package.json': File(pkg), 'src': Dir({ 'index.js': File(` export default class Advanced { constructor() { this.isBrowser = process.env.BROWSER; } }; `), }), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const fileNames = results.map(result => `dist/${result.fileName}`); const [cjsMain, esmModule, cjsBrowser, esmBrowser] = results.map( result => `// dist/${result.fileName}\n${result.code}` ); expect(fileNames).toStrictEqual([ 'dist/index.js', 'dist/index.esm.js', 'dist/index.browser.js', 'dist/index.module.browser.js', ]); expect(cjsMain).toMatchInlineSnapshot(` "// dist/index.js 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var _classCallCheck = _interopDefault(require('@babel/runtime/helpers/classCallCheck')); var Advanced = function Advanced() { _classCallCheck(this, Advanced); this.isBrowser = false; }; module.exports = Advanced; " `); expect(esmModule).toMatchInlineSnapshot(` "// dist/index.esm.js import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck'; var Advanced = function Advanced() { _classCallCheck(this, Advanced); this.isBrowser = false; }; export default Advanced; " `); expect(cjsBrowser).toMatchInlineSnapshot(` "// dist/index.browser.js 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var _classCallCheck = _interopDefault(require('@babel/runtime/helpers/classCallCheck')); var Advanced = function Advanced() { _classCallCheck(this, Advanced); this.isBrowser = true; }; module.exports = Advanced; " `); expect(esmBrowser).toMatchInlineSnapshot(` "// dist/index.module.browser.js import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck'; var Advanced = function Advanced() { _classCallCheck(this, Advanced); this.isBrowser = true; }; export default Advanced; " `); }); it('generates pkg.unpkg UMD output for unscoped package with peers', async () => { const pkg = { name: 'unpkg-umd-output', main: './dist/index.js', module: './dist/index.esm.js', unpkg: './dist/index.min.js', peerDependencies: { react: '*', }, dependencies: { '@babel/runtime': '^7.0.0', }, }; const cwd = createFixture({ 'package.json': File(pkg), 'src': Dir({ 'index.js': File( 'import React from "react"; export default () => React.render("woo");' ), }), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const fileNames = results.map(result => `dist/${result.fileName}`); const minOutput = results.pop().code; const umdOutput = results.pop().code; expect(fileNames).toContain('dist/index.dev.js'); expect(fileNames).toContain('dist/index.min.js'); expect(umdOutput).toMatchInlineSnapshot(` "(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) : typeof define === 'function' && define.amd ? define(['react'], factory) : (global = global || self, global.UnpkgUmdOutput = factory(global.React)); }(this, (function (React) { 'use strict'; React = React && React.hasOwnProperty('default') ? React['default'] : React; var index = (function () { return React.render(\\"woo\\"); }); return index; }))); " `); expect(minOutput).toMatchInlineSnapshot(` "!function(e,t){\\"object\\"==typeof exports&&\\"undefined\\"!=typeof module?module.exports=t(require(\\"react\\")):\\"function\\"==typeof define&&define.amd?define([\\"react\\"],t):(e=e||self).UnpkgUmdOutput=t(e.React)}(this,(function(e){\\"use strict\\";e=e&&e.hasOwnProperty(\\"default\\")?e.default:e;return function(){return e.render(\\"woo\\")}})); " `); }); it('generates pkg.unpkg UMD output for scoped package without peers', async () => { const pkg = { name: '@unpkg/scoped-umd', main: './dist/index.js', unpkg: './dist/index.min.js', }; const cwd = createFixture({ 'package.json': File(pkg), 'src': Dir({ 'index.js': File(` export default function main() { console.log("yay"); if (process.env.NODE_ENV === 'production') { console.log('hooray'); } } `), }), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const minOutput = results.pop().code; const umdOutput = results.pop().code; expect(umdOutput).toMatchInlineSnapshot(` "(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.ScopedUmd = factory()); }(this, (function () { 'use strict'; function main() { console.log(\\"yay\\"); } return main; }))); " `); expect(minOutput).toMatchInlineSnapshot(` "!function(e,o){\\"object\\"==typeof exports&&\\"undefined\\"!=typeof module?module.exports=o():\\"function\\"==typeof define&&define.amd?define(o):(e=e||self).ScopedUmd=o()}(this,(function(){\\"use strict\\";return function(){console.log(\\"yay\\"),console.log(\\"hooray\\")}})); " `); }); it('interpolates process.env.VERSION with pkg.version', async () => { const pkg = { name: 'interpolates-version', main: 'dist/index.js', version: '1.2.3-alpha.0+deadbeef', }; const cwd = createFixture({ 'package.json': File(pkg), 'src': Dir({ 'index.js': File(` export default function main() { console.log(process.env.VERSION); } `), }), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const [cjs] = results; expect(cjs.code).toMatch('console.log("1.2.3-alpha.0+deadbeef");'); }); it('works all together', async () => { const pkg = { name: 'integration', main: 'dist/index.js', module: 'dist/index.esm.js', rollup: { inlineSVG: true, }, dependencies: { '@babel/runtime': '^7.0.0', 'react': '*', }, }; const cwd = createFixture({ 'package.json': File(pkg), 'src': Dir({ 'test.svg': File( `<?xml version="1.0" ?><svg viewBox="0 0 151.57 151.57" xmlns="http://www.w3.org/2000/svg"><line x1="47.57" x2="103.99" y1="103.99" y2="47.57"/><line x1="45.8" x2="105.7" y1="45.87" y2="105.77"/></svg>` ), // a class is a lot more interesting output 'index.js': File(` import React from 'react'; import svgTest from './test.svg'; export default class Foo extends React.Component { render() { return <div>{svgTest}</div>; } }; `), }), }); const configs = await pectinCore(pkg, { cwd }); const results = await generateResults(configs); const [cjs, esm] = results; expect(esm.code).toMatchInlineSnapshot(` "import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck'; import _createClass from '@babel/runtime/helpers/esm/createClass'; import _possibleConstructorReturn from '@babel/runtime/helpers/esm/possibleConstructorReturn'; import _getPrototypeOf from '@babel/runtime/helpers/esm/getPrototypeOf'; import _inherits from '@babel/runtime/helpers/esm/inherits'; import React from 'react'; var svgTest = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pjxzdmcgdmlld0JveD0iMCAwIDE1MS41NyAxNTEuNTciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGxpbmUgeDE9IjQ3LjU3IiB4Mj0iMTAzLjk5IiB5MT0iMTAzLjk5IiB5Mj0iNDcuNTciLz48bGluZSB4MT0iNDUuOCIgeDI9IjEwNS43IiB5MT0iNDUuODciIHkyPSIxMDUuNzciLz48L3N2Zz4='; var Foo = /*#__PURE__*/ function (_React$Component) { _inherits(Foo, _React$Component); function Foo() { _classCallCheck(this, Foo); return _possibleConstructorReturn(this, _getPrototypeOf(Foo).apply(this, arguments)); } _createClass(Foo, [{ key: \\"render\\", value: function render() { return React.createElement(\\"div\\", null, svgTest); } }]); return Foo; }(React.Component); export default Foo; " `); expect(cjs.code).toMatch("'use strict';"); expect(cjs.code).toMatch('_interopDefault'); expect(cjs.code).toMatch("require('@babel/runtime/helpers/createClass')"); expect(cjs.code).toMatch('module.exports = Foo;'); // transpiled code is otherwise identical }); });
the_stack
import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http'; import { sp } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/site-users/web"; import "@pnp/sp/lists/web"; import "@pnp/sp/items/list"; import "@pnp/sp/fields/list"; import "@pnp/sp/views/list"; import "@pnp/sp/profiles"; import "@pnp/sp/search"; import "@pnp/sp/files"; import "@pnp/sp/folders"; import { graph } from "@pnp/graph"; import "@pnp/graph/users"; import * as moment from 'moment/moment'; import { IWeb } from "@pnp/sp/webs"; import { IUserInfo, IPropertyMappings, IPropertyPair, FileContentType, SyncType, JobStatus } from "./IModel"; import { IList } from '@pnp/sp/lists'; import { ChoiceFieldFormatType } from '@pnp/sp/fields/types'; import { IFileAddResult, IFileInfo } from '@pnp/sp/files'; const map: any = require('lodash/map'); const intersection: any = require('lodash/intersection'); const orderBy: any = require('lodash/orderBy'); export interface ISPHelper { getCurrentUserInfo: () => Promise<IUserInfo>; checkCurrentUserGroup: (allowedGroups: string[], userGroups: string[]) => boolean; getAzurePropertyForUsers: (selectFields: string, filterQuery: string) => Promise<any[]>; getPropertyMappings: () => Promise<any[]>; getPropertyMappingsTemplate: (propertyMappings: IPropertyMappings[]) => Promise<any>; addFilesToFolder: (filename: string, fileContent: any) => Promise<IFileAddResult>; addDataFilesToFolder: (fileContent: any, filename: string) => Promise<IFileAddResult>; getFileContent: (filepath: string, contentType: FileContentType) => void; createSyncItem: (syncType: SyncType) => Promise<number>; updateSyncItem: (itemid: number, inputJson: string) => void; updateSyncItemStatus: (itemid: number, errMsg: string) => void; getAllJobs: () => void; getAllTemplates: () => Promise<IFileInfo[]>; getAllBulkList: () => Promise<IFileInfo[]>; runAzFunction: (httpClient: HttpClient, inputData: any, azFuncUrl: string, itemid: number) => void; } export default class SPHelper implements ISPHelper { private SiteURL: string = ""; private SiteRelativeURL: string = ""; private AdminSiteURL: string = ""; private SyncTemplateFilePath: string = ""; private SyncUploadFilePath: string = ""; private SyncJSONFileName: string = `SyncTemplate_${moment().format("MMDDYYYYhhmmss")}.json`; private SyncCSVFileName: string = `SyncTemplate_${moment().format("MMDDYYYYhhmmss")}.csv`; private _web: IWeb = null; private Lst_PropsMapping = 'Sync Properties Mapping'; private Lst_SyncJobs = 'UPS Sync Jobs'; constructor(siteurl: string, tenantname: string, domainname: string, relativeurl: string, libid: string) { this.SiteURL = siteurl; this.SiteRelativeURL = relativeurl; this.AdminSiteURL = `https://${tenantname}-admin.${domainname}`; this._web = sp.web; this.getTemplateLibraryInfo(libid); } public getTemplateLibraryInfo = async (libid: string) => { if (libid) { let libinfo = await this._web.lists.getById(libid).select('Title').get(); this.SyncTemplateFilePath = `/${libinfo.Title}/SyncJobTemplate/`; this.SyncUploadFilePath = `/${libinfo.Title}/UPSDataToProcess/`; } } /** * Get the Azure property data for the Users */ public getAzurePropertyForUsers = async (selectFields: string, filterQuery: string): Promise<any[]> => { let users = await graph.users.filter(filterQuery).select(selectFields).get(); return orderBy(users, 'displayName', 'asc'); } /** * Get the property mappings from the 'Sync Properties Mapping' list. */ public getPropertyMappings = async (): Promise<any[]> => { return await this._web.lists.getByTitle(this.Lst_PropsMapping).items .select("ID", "Title", "AzProperty", "SPProperty", "IsActive", "AutoSync") .filter(`IsActive eq 1`) .get(); } /** * Generated the property mapping json content. */ public getPropertyMappingsTemplate = async (propertyMappings: IPropertyMappings[]) => { if (!propertyMappings) propertyMappings = await this.getPropertyMappings(); let finalJson: string = ""; let propertyPair: any[] = []; let sampleUser1 = new Object(); let sampleUser2 = new Object(); sampleUser1['UserID'] = "user1@tenantname.onmicrosoft.com"; sampleUser2['UserID'] = "user2@tenantname.onmicrosoft.com"; propertyMappings.map((propsMap: IPropertyMappings) => { sampleUser1[propsMap.SPProperty] = ""; sampleUser2[propsMap.SPProperty] = ""; }); propertyPair.push(sampleUser1, sampleUser2); finalJson = JSON.stringify(propertyPair); return JSON.parse(finalJson); } public getPropertyMappingsTemplate1 = async (propertyMappings: IPropertyMappings[]) => { if (!propertyMappings) propertyMappings = await this.getPropertyMappings(); let finalJson: string = ""; let propertyPair: IPropertyPair[] = []; propertyMappings.map((propsMap: IPropertyMappings) => { propertyPair.push({ name: propsMap.SPProperty, value: "" }); }); finalJson = `{ "targetAdminUrl": "${this.AdminSiteURL}", "targetSiteUrl": "${this.SiteURL}", "values": [ { "UserID": "userid@tenantname.onmicrosoft.com", "Properties": ${JSON.stringify(propertyPair)} } ] }`; return JSON.parse(finalJson); } /** * Get the file content as blob based on the file url. */ public getFileContent = async (filepath: string, contentType: FileContentType) => { switch (contentType) { case FileContentType.Blob: return await this._web.getFileByServerRelativeUrl(filepath).getBlob(); case FileContentType.ArrayBuffer: return await this._web.getFileByServerRelativeUrl(filepath).getBuffer(); case FileContentType.Text: return await this._web.getFileByServerRelativeUrl(filepath).getText(); case FileContentType.JSON: return await this._web.getFileByServerRelativeUrl(filepath).getJSON(); } } /** * Add the template file to a folder with contents. * This is used for creating the template json file. */ public addFilesToFolder = async (fileContent: any, isCSV: boolean): Promise<IFileAddResult> => { let filename = (isCSV) ? this.SyncCSVFileName : this.SyncJSONFileName; await this.checkAndCreateFolder(this.SiteRelativeURL + this.SyncTemplateFilePath); return await this._web.getFolderByServerRelativeUrl(this.SiteRelativeURL + this.SyncTemplateFilePath) .files .add(decodeURI(this.SiteRelativeURL + this.SyncTemplateFilePath + filename), fileContent, true); } /** * Add the data file to a folder with contents. * This is used for creating the template json file. */ public addDataFilesToFolder = async (fileContent: any, filename: string): Promise<IFileAddResult> => { await this.checkAndCreateFolder(this.SiteRelativeURL + this.SyncUploadFilePath); return await this._web.getFolderByServerRelativeUrl(this.SiteRelativeURL + this.SyncUploadFilePath) .files .add(decodeURI(this.SiteRelativeURL + this.SyncUploadFilePath + filename), fileContent, true); } /** * Check for the template folder, if not creates. */ public checkAndCreateFolder = async (folderPath: string) => { try { await this._web.getFolderByServerRelativeUrl(folderPath).get(); } catch (err) { await this._web.folders.add(folderPath); } } /** * Get current logged in user information. */ public getCurrentUserInfo = async (): Promise<IUserInfo> => { let currentUserInfo = await this._web.currentUser.get(); let currentUserGroups = await this._web.currentUser.groups.get(); return ({ ID: currentUserInfo.Id, Email: currentUserInfo.Email, LoginName: currentUserInfo.LoginName, DisplayName: currentUserInfo.Title, IsSiteAdmin: currentUserInfo.IsSiteAdmin, Groups: map(currentUserGroups, 'LoginName'), Picture: '/_layouts/15/userphoto.aspx?size=S&username=' + currentUserInfo.UserPrincipalName, }); } /** * Check current user is a member of groups or not. */ public checkCurrentUserGroup = (allowedGroups: string[], userGroups: string[]): boolean => { if (userGroups.length > 0) { let diff: string[] = intersection(allowedGroups, userGroups); if (diff && diff.length > 0) return true; } return false; } /** * Create a sync item */ public createSyncItem = async (syncType: SyncType): Promise<number> => { let returnVal: number = 0; let itemAdded = await this._web.lists.getByTitle(this.Lst_SyncJobs).items.add({ Title: `SyncJob_${moment().format("MMDDYYYYhhmm")}`, Status: JobStatus.Submitted.toString(), SyncType: syncType.toString() }); returnVal = itemAdded.data.Id; return returnVal; } /** * Update Sync item with the input data to sync */ public updateSyncItem = async (itemid: number, inputJson: string) => { await this._web.lists.getByTitle(this.Lst_SyncJobs).items.getById(itemid).update({ SyncData: inputJson }); } /** * Update Sync item with the error status */ public updateSyncItemStatus = async (itemid: number, errMsg: string) => { await this._web.lists.getByTitle(this.Lst_SyncJobs).items.getById(itemid).update({ Status: JobStatus.Error, ErrorMessage: errMsg }); } /** * Get all the jobs items */ public getAllJobs = async () => { return await this._web.lists.getByTitle(this.Lst_SyncJobs).items .select('ID', 'Title', 'SyncedData', 'Status', 'ErrorMessage', 'SyncType', 'Created', 'Author/Title', 'Author/Id', 'Author/EMail') .expand('Author') .getAll(); } /** * Get all the templates generated */ public getAllTemplates = async (): Promise<IFileInfo[]> => { return await this._web.getFolderByServerRelativeUrl(this.SiteRelativeURL + this.SyncTemplateFilePath) .files .select('Name', 'ServerRelativeUrl', 'TimeCreated') .expand('Author') .get(); } /** * Get all the bulk sync files */ public getAllBulkList = async (): Promise<IFileInfo[]> => { return await this._web.getFolderByServerRelativeUrl(this.SiteRelativeURL + this.SyncUploadFilePath) .files .select('Name', 'ServerRelativeUrl', 'TimeCreated') .expand('Author') .get(); } /** * Check and create the required lists */ public checkAndCreateLists = async (): Promise<boolean> => { return new Promise<boolean>(async (res, rej) => { try { await this._web.lists.getByTitle(this.Lst_PropsMapping).get(); console.log('Property Mapping List Exists'); } catch (err) { console.log("Property Mapping List doesn't exists, so creating"); await this._createPropsMappingList(); console.log("Property Mapping List created"); } try { await this._web.lists.getByTitle(this.Lst_SyncJobs).get(); console.log('Sync Jobs List Exists'); } catch (err) { console.log("Sync Jobs List doesn't exists, so creating"); await this._createSyncJobsList(); console.log("Sync Jobs List created"); } console.log("Checked all lists"); res(true); }); } /** * Create Sync Jobs list */ public _createSyncJobsList = async () => { let listExists = await (await sp.web.lists.ensure(this.Lst_SyncJobs)).list; await listExists.fields.addMultilineText('SyncData', 6, false, false, false, false, { Required: true, Description: 'Data sent to Azure function for property update.' }); await listExists.fields.addMultilineText('SyncedData', 6, false, false, false, false, { Required: true, Description: 'Data received from Azure function with property update status.' }); await listExists.fields.addChoice('Status', ['Submitted', 'In-Progress', 'Completed', 'Error'], ChoiceFieldFormatType.Dropdown, false, { Required: true, Description: 'Status of the job.' }); await listExists.fields.addMultilineText('ErrorMessage', 6, false, false, false, false, { Required: false, Description: 'Store the error message while calling Azure function.' }); await listExists.fields.addChoice('SyncType', ['Manual', 'Azure', 'Template'], ChoiceFieldFormatType.Dropdown, false, { Required: true, Description: 'Type of data sent to Azure function.' }); let allItemsView = await listExists.views.getByTitle('All Items'); let batch = sp.createBatch(); allItemsView.fields.inBatch(batch).add('ID'); allItemsView.fields.inBatch(batch).add('SyncData'); allItemsView.fields.inBatch(batch).add('SyncedData'); allItemsView.fields.inBatch(batch).add('Status'); allItemsView.fields.inBatch(batch).add('ErrorMessage'); allItemsView.fields.inBatch(batch).add('SyncType'); allItemsView.fields.inBatch(batch).move('ID', 0); await batch.execute(); } /** * Create property mapping list */ public _createPropsMappingList = async () => { let listExists = await (await sp.web.lists.ensure(this.Lst_PropsMapping)).list; await listExists.fields.addText('AzProperty', 255, { Required: true, Description: 'Azure user profile property name.' }); await listExists.fields.addText('SPProperty', 255, { Required: true, Description: 'SharePoint User Profile property name.' }); await listExists.fields.addBoolean('IsActive', { Required: true, Description: 'Active or InActive used for mapping by the end users.' }); await listExists.fields.addBoolean('AutoSync', { Required: true, Description: 'Properties that are automatically synced with Azure.' }); let allItemsView = await listExists.views.getByTitle('All Items'); let batch = sp.createBatch(); allItemsView.fields.inBatch(batch).add('AzProperty'); allItemsView.fields.inBatch(batch).add('SPProperty'); allItemsView.fields.inBatch(batch).add('IsActive'); allItemsView.fields.inBatch(batch).add('AutoSync'); await batch.execute(); await this._createDefaultPropsMapping(listExists); } /** * Create default property mapping items */ public _createDefaultPropsMapping = async (lst: IList) => { let batch = sp.createBatch(); lst.items.inBatch(batch).add({ Title: 'Department', AzProperty: 'department', SPProperty: 'Department', IsActive: true, AutoSync: true }); lst.items.inBatch(batch).add({ Title: 'Job Title', AzProperty: 'jobTitle', SPProperty: 'Title', IsActive: true, AutoSync: true }); lst.items.inBatch(batch).add({ Title: 'Office', AzProperty: 'officeLocation', SPProperty: 'Office', IsActive: true, AutoSync: true }); lst.items.inBatch(batch).add({ Title: 'Business Phone', AzProperty: 'businessPhones', SPProperty: 'workPhone', IsActive: true, AutoSync: false }); lst.items.inBatch(batch).add({ Title: 'Mobile Phone', AzProperty: 'mobilePhone', SPProperty: 'CellPhone', IsActive: true, AutoSync: false }); lst.items.inBatch(batch).add({ Title: 'Fax Number', AzProperty: 'faxNumber', SPProperty: 'Fax', IsActive: true, AutoSync: false }); lst.items.inBatch(batch).add({ Title: 'Street Address', AzProperty: 'streetAddress', SPProperty: 'StreetAddress', IsActive: true, AutoSync: false }); lst.items.inBatch(batch).add({ Title: 'City', AzProperty: 'city', SPProperty: 'City', IsActive: true, AutoSync: false }); lst.items.inBatch(batch).add({ Title: 'State or Province', AzProperty: 'state', SPProperty: 'State', IsActive: true, AutoSync: false }); lst.items.inBatch(batch).add({ Title: 'Zip or Postal code', AzProperty: 'postalCode', SPProperty: 'PostalCode', IsActive: true, AutoSync: false }); lst.items.inBatch(batch).add({ Title: 'Country or Region', AzProperty: 'country', SPProperty: 'Country', IsActive: true, AutoSync: false }); await batch.execute(); } /** * Azure function to update the UPS properties. */ public runAzFunction = async (httpClient: HttpClient, inputData: any, azFuncUrl: string, itemid: number) => { const requestHeaders: Headers = new Headers(); requestHeaders.append("Content-type", "application/json"); requestHeaders.append("Cache-Control", "no-cache"); const postOptions: IHttpClientOptions = { headers: requestHeaders, body: `${inputData}` }; let response: HttpClientResponse = await httpClient.post(azFuncUrl, HttpClient.configurations.v1, postOptions); if (!response.ok) { await this.updateSyncItemStatus(itemid, `${response.status} - ${response.statusText}`); } console.log("Azure Function executed"); } }
the_stack
import { DimensionalityMismatchError, Sylvester, InvalidOperationError } from './sylvester'; import { isPlaneLike, isLineLike, isVectorOrListLike, isGeometry, VectorOrList, Geometry, } from './likeness'; import { Matrix } from './matrix'; import { Line } from './line'; import { Plane } from './plane'; /** * Returns the elements from the given vector or number array. * @private */ const getElements = (vectorOrList: VectorOrList): ReadonlyArray<number> => (vectorOrList as any).elements || vectorOrList; /** * The Vector class is designed to model vectors in any number of dimensions. * All the elements of a vector must be real numbers. Depending on what you’re * using them for, it can be helpful to think of a vector either as a point * in n-dimensional space, or as a line connecting * the origin to that same point. */ export class Vector { /** * Gets the elements of the vector or list of numbers. * @param requireDimension - Desired dimension of elements * @private */ public static toElements(vectorOrElements: VectorOrList, requireDimension?: number) { let elements = getElements(vectorOrElements); if (!requireDimension || requireDimension === elements.length) { return elements; } if (elements.length > requireDimension) { throw new DimensionalityMismatchError( `Cannot convert a ${elements.length}D vector to a ${requireDimension}D one`, ); } const dup = (elements = elements.slice()); while (elements.length < requireDimension) { dup.push(0); } return dup; } /** * Unit vector `[1, 0, 0]` */ public static readonly i = new Vector([1, 0, 0]); /** * Unit vector `[0, 1, 0]` */ public static readonly j = new Vector([0, 1, 0]); /** * Unit vector `[0, 0, 1]` */ public static readonly k = new Vector([0, 0, 1]); /** * Vector elements. */ public readonly elements: ReadonlyArray<number>; /** * Creates a new vector, initializing it with the provided elements. */ constructor(elements: VectorOrList) { this.elements = Vector.toElements(elements); } /** * Returns the magnitude (also: euclidean norm, magnitude) of the vector. * * @see https://en.wikipedia.org/wiki/Euclidean_distance * @diagram Vector.magnitude */ public magnitude() { let sum = 0; for (let i = 0; i < this.elements.length; i++) { sum += this.elements[i] * this.elements[i]; } return Math.sqrt(sum); } /** * Returns the `ith` element if the vector. Returns null if `i` is out * of bounds, indexing starts from 1. * @diagram Vector.e */ public e(i: number) { return i < 1 || i > this.elements.length ? null : this.elements[i - 1]; } /** * Returns the number of rows and columns the vector has. * @diagram Vector.dimensions * @return {IDimensions} the "rows" will always equal zero */ public dimensions() { return { rows: 1, cols: this.elements.length, }; } /** * Returns the number of rows the vector has. * @diagram Vector.rows * @return {Number} always `1` */ public rows() { return 1; } /** * Returns the number of columns the vector has. * @diagram Vector.cols * @return {Number} */ public cols() { return this.elements.length; } /** * Returns if the Vector is equal to the input vector. * @param epsilon - The precision to compare each number. * @diagram Vector.eql */ public eql(other: unknown, precision = Sylvester.approxPrecision) { if (!isGeometry(other)) { return false; } if (!isVectorOrListLike(other)) { return false; } let n = this.elements.length; const elements = getElements(other); if (n !== elements.length) { return false; } while (n--) { if (Math.abs(this.elements[n] - elements[n]) > precision) { return false; } } return true; } /** * Returns a new function created by calling the iterator on all values of this vector. */ public map(fn: (value: number, index: number) => number) { const n = this.elements.length; const elements = new Array(n); for (let i = 0; i < n; i++) { elements[i] = fn(this.elements[i], i + 1); } return new Vector(elements); } /** * Iterates through the elements of the vector */ public each(fn: (value: number, index: number) => void) { const n = this.elements.length; for (let i = 0; i < n; i++) { fn(this.elements[i], i + 1); } } /** * Returns a new vector created by normalizing this one to a have a * magnitude of `1`. If the vector is the zero vector, it will not be modified. * @diagram Vector.toUnitVector */ public toUnitVector() { const r = this.magnitude(); if (r === 0) { return this; } return this.map(x => x / r); } /** * Returns the angle between this vector the argument in radians. If the * vectors are mirrored across their axes this will return `NaN`. * * @throws A {@link DimensionalityMismatchError} If a vector is passed in with * different dimensions * @diagram Vector.angleFrom */ public angleFrom(vector: VectorOrList) { const V = getElements(vector); const n = this.elements.length; if (n !== V.length) { throw new DimensionalityMismatchError( 'Cannot compute the angle between vectors with different dimensionality', ); } // Work things out in parallel to save time let dot = 0; let mod1 = 0; let mod2 = 0; this.each((x, i) => { dot += x * V[i - 1]; mod1 += x * x; mod2 += V[i - 1] * V[i - 1]; }); mod1 = Math.sqrt(mod1); mod2 = Math.sqrt(mod2); if (mod1 * mod2 === 0) { return NaN; } let theta = dot / (mod1 * mod2); if (theta < -1) { theta = -1; } if (theta > 1) { theta = 1; } return Math.acos(theta); } /** * Returns whether the vectors are parallel to each other. * @param epsilon - precision used for comparing angles * @diagram Vector.isParallelTo */ public isParallelTo(obj: Geometry, epsilon = Sylvester.precision): boolean { if (isVectorOrListLike(obj)) { return this.angleFrom(obj) <= epsilon; } else if (isGeometry(obj)) { return obj.isParallelTo(this, epsilon); } else { throw new InvalidOperationError(`Cannot compare the angle of ${obj} to a vector`); } } /** * Returns whether the vectors are antiparallel to each other. * @param epsilon - precision used for comparing angles * @diagram Vector.isAntiparallelTo */ public isAntiparallelTo(vector: VectorOrList, epsilon = Sylvester.precision) { const angle = this.angleFrom(vector); return Math.abs(angle - Math.PI) <= epsilon; } /** * Returns whether the vectors are perpendicular to each other. * @param epsilon - precision used for comparing angles * @diagram Vector.isPerpendicularTo */ public isPerpendicularTo(obj: Geometry, epsilon = Sylvester.precision) { if (isVectorOrListLike(obj)) { return Math.abs(this.dot(obj)) <= epsilon; } else if (isGeometry(obj)) { return obj.isPerpendicularTo(this, epsilon); } else { throw new InvalidOperationError(`Cannot compare the angle of ${obj} to a vector`); } } private _runBinaryOp(value: VectorOrList | number, operator: (a: number, b: number) => number) { if (typeof value === 'number') { return this.map(v => operator(v, value)); } const values = getElements(value); if (this.elements.length !== values.length) { throw new DimensionalityMismatchError('Cannot add vectors with different dimensions.'); } return this.map((x, i) => operator(x, values[i - 1])); } /** * When the input is a constant, this returns the result of adding it to * all cevtor elements. When it's a vector, the vectors will be added. * @throws A {@link DimensionalityMismatchError} If a vector is passed in with * different dimensions * @diagram Vector.add */ public add(value: VectorOrList | number) { return this._runBinaryOp(value, (a, b) => a + b); } /** * When the input is a constant, this returns the result of subtracting it * from all vector elements. When it's a vector, the vectors will be subtracted. * @throws A {@link DimensionalityMismatchError} If a vector is passed in with * different dimensions * @diagram Vector.subtract */ public subtract(value: VectorOrList | number) { return this._runBinaryOp(value, (a, b) => a - b); } /** * When the input is a constant, this returns the result of multiplying it * with all vector elements. When it's a vector, the vectors will be * element-wise multiplied. * @throws A {@link DimensionalityMismatchError} If a vector is passed in with * different dimensions * @diagram Vector.multiply */ public multiply(value: VectorOrList | number) { return this._runBinaryOp(value, (a, b) => a * b); } /** * @alias Vector#multiply * @diagram Vector.multiply */ x(value: VectorOrList | number) { return this.multiply(value); } /** * Returns the sum of all elements in the Vector. * @diagram Vector.sum */ public sum() { let sum = 0; this.each(x => { sum += x; }); return sum; } /** * Returns a new vector with the first `n` elements removed from the beginning. * @diagram Vector.chomp */ public chomp(n: number) { const elements = []; for (let i = n; i < this.elements.length; i++) { elements.push(this.elements[i]); } return new Vector(elements); } /** * Returns a new vector consisting only of the first `n` elements. * @diagram Vector.top */ public top(n: number) { const elements = []; for (let i = 0; i < n; i++) { elements.push(this.elements[i]); } return new Vector(elements); } /** * Returns a new vector with the provided `elements` concatenated on the end. * @diagram Vector.augment */ public augment(elements: VectorOrList) { return new Vector(this.elements.concat(getElements(elements))); } /** * Returns the product of all elements in the vector. * @diagram Vector.product */ public product() { let p = 1; this.each(v => { p *= v; }); return p; } /** * Returns the scalar (dot) product of the vector with the argument. * @see https://en.wikipedia.org/wiki/Scalar_product * @throws A {@link DimensionalityMismatchError} If a vector is passed in with * different dimensions * @diagram Vector.dot */ public dot(vector: VectorOrList) { const V = getElements(vector); let n = this.elements.length; if (n !== V.length) { throw new DimensionalityMismatchError( 'Cannot compute the dot product of vectors with different dimensionality', ); } let product = 0; while (n--) { product += this.elements[n] * V[n]; } return product; } /** * Returns the vector product of the vector with the argument. * @throws A {@link DimensionalityMismatchError} if either this or the other vector * is not three-dimensional. * @diagram Vector.cross */ public cross(vector: VectorOrList) { const B = getElements(vector); if (this.elements.length !== 3 || B.length !== 3) { throw new DimensionalityMismatchError( `A cross-product can only be calculated between 3-dimensional vectors (got ${B.length} and ${this.elements.length})`, ); } const A = this.elements; return new Vector([ A[1] * B[2] - A[2] * B[1], A[2] * B[0] - A[0] * B[2], A[0] * B[1] - A[1] * B[0], ]); } /** * Returns the (absolute) largest element of the vector * @diagram Vector.max */ public max() { let m = 0; let i = this.elements.length; while (i--) { if (Math.abs(this.elements[i]) > Math.abs(m)) { m = this.elements[i]; } } return m; } /** * Returns the index of the absolute largest element of the vector. * @returns Will be -1 if the vector is empty * @diagram Vector.maxIndex */ public maxIndex() { let m = -1; let i = this.elements.length; let maxIndex = -1; while (i--) { if (Math.abs(this.elements[i]) > Math.abs(m)) { m = this.elements[i]; maxIndex = i + 1; } } return maxIndex; } /** * Returns the index of the first instance of the value in the vector, or -1. * @diagram Vector.indexOf */ public indexOf(x: number) { for (let i = 0; this.elements.length; i++) { if (this.elements[i] === x) { return i + 1; } } return -1; } /** * Returns a diagonal matrix with the vector's elements as its diagonal elements */ public toDiagonalMatrix() { return Matrix.Diagonal(this.elements); } /** * Returns the result of rounding the elements of the vector * @diagram Vector.round */ public round() { return this.map(x => Math.round(x)); } /** * Transpose a Vector, return a 1xn Matrix. * @diagram Vector.transpose */ public transpose() { const rows = this.elements.length; const elements = []; for (let i = 0; i < rows; i++) { elements.push([this.elements[i]]); } return new Matrix(elements); } /** * Returns a copy of the vector with elements set to the given value if they * differ from it by less than the epislon. * @diagram Vector.snapTo */ public snapTo(target: number, epsilon = Sylvester.precision) { return this.map(p => (Math.abs(p - target) <= epsilon ? target : p)); } /** * Returns the vector's distance from the argument, when considered as a point in space * @diagram Vector.distanceFrom */ public distanceFrom(obj: Geometry): number { if (!isVectorOrListLike(obj)) { return obj.distanceFrom(this); } const V = Vector.toElements(obj, this.elements.length); let sum = 0; let part; this.each((x, i) => { part = x - V[i - 1]; sum += part * part; }); return Math.sqrt(sum); } /** * Returns true if the vector is point on the given line * @diagram Vector.liesOn */ public liesOn(line: Line) { return line.contains(this); } /** * Returns true if the vector is point on the given plane * @diagram Vector.liesIn */ public liesIn(plane: Plane) { return plane.contains(this); } /** * Rotates the 2D vector about the given point. * @param t - Radians or rotation matrix to use * @diagram Vector.rotate2D */ public rotate2D(t: number | Matrix, obj: VectorOrList) { const V = Vector.toElements(obj, 2); const R = t instanceof Matrix ? t.elements : Matrix.Rotation(t).elements; const x = this.elements[0] - V[0]; const y = this.elements[1] - V[1]; return new Vector([V[0] + R[0][0] * x + R[0][1] * y, V[1] + R[1][0] * x + R[1][1] * y]); } /** * Rotates the 3D vector about the given line. Be careful * with line directions! * @param t - Radians or rotation matrix to use */ public rotate3D(t: number | Matrix, obj: Line) { const elements = this.to3D().elements; const pivot = obj.pointClosestTo(elements)!.elements; const rotation = t instanceof Matrix ? t.elements : Matrix.Rotation(t, obj.direction).elements; const x = elements[0] - pivot[0]; const y = elements[1] - pivot[1]; const z = elements[2] - pivot[2]; return new Vector([ pivot[0] + rotation[0][0] * x + rotation[0][1] * y + rotation[0][2] * z, pivot[1] + rotation[1][0] * x + rotation[1][1] * y + rotation[1][2] * z, pivot[2] + rotation[2][0] * x + rotation[2][1] * y + rotation[2][2] * z, ]); } /** * Returns the result of reflecting the point in the given point, line or plane. * @diagram Vector.reflectionIn */ public reflectionIn(obj: VectorOrList | Line | Plane) { if (isPlaneLike(obj) || isLineLike(obj)) { const C = obj.pointClosestTo(this)!.elements; return new Vector(this.elements.map((p, i) => C[i] + (C[i] - p))); } // obj is a point const Q = getElements(obj); if (this.elements.length !== Q.length) { throw new DimensionalityMismatchError( `Cannot rotate a ${this.elements.length}D point around the given ${Q.length}D point`, ); } return this.map((x, i) => { return Q[i - 1] + (Q[i - 1] - x); }); } /** * Runs an element-wise logarithm on the vector. * @diagram Vector.log */ public log(base = Math.E) { const logBase = Math.log(base); // change of base return this.map(x => Math.log(x) / logBase); } /** * Utility to make sure vectors are 3D. If they are 1/2D, a zero component is added. * @throws A {@link DimensionalityMismatchError} if the vector has greater than three elements */ public to3D() { return this.toDimension(3); } /** * Pads the vector with zero's until it reaches the given dimension. * @throws A {@link DimensionalityMismatchError} if the vector has greater than n elements */ public toDimension(n: number) { if (this.elements.length > n) { throw new DimensionalityMismatchError( `Cannot convert a ${this.elements.length}D vector to a ${n}D one`, ); } const next = new Array(n); for (let i = 0; i < n; i++) { next[i] = this.elements[i] || 0; } return new Vector(next); } /** * Returns a string representation of the vector */ public toString() { return `Vector<[${this.elements.join(', ')}]>`; } /** * @inheritdoc */ public toJSON() { return this.elements; } /** * Creates vector of the given size filled with random values in the range `[0, 1)`. */ public static Random(size: number): Vector { const elements = []; while (size--) { elements.push(Math.random()); } return new Vector(elements); } /** * Creates a vector filled with the given value. */ public static Fill(size: number, value: number): Vector { const elements = []; while (size--) { elements.push(value); } return new Vector(elements); } /** * Creates an n-length vector filled with zeroes. */ public static Zero(n: number): Vector { return Vector.Fill(n, 0); } /** * Creates an n-length vector filled with ones. */ public static One(n: number): Vector { return Vector.Fill(n, 1); } }
the_stack