text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import i18next from 'i18next'; import { ControlInput } from '../../controls/ControlInput'; import { AplContent, QuestionnaireControl } from './QuestionnaireControl'; export namespace QuestionnaireControlAPLPropsBuiltIns { export interface QuestionnaireChoice { ordinalText: string; selectedText: string; color: string; selectedIndex: number; //unselectedText: string; //selectedTextColor: string, } export interface QuestionnaireControlAPLContent { caption: string; questionCaptions: string[]; choices: QuestionnaireChoice[]; } export interface DefaultAskQuestionProps { /** * Default: 'Please answer the following..' */ title?: string; /** * Default (en-*): 'Submit >' */ submitButtonText?: string; /** * Default: '' */ subtitle?: string; /** * Whether debug information is displayed * * Default: false */ debug?: boolean; /** * Whether the Radio buttons have blocking behavior. * * *Default: true* * * When true, all UI buttons are disabled (blocked) until processing of preceding * radio button press is complete. If the processing takes significant time, a * busy indicator is shown. * * Purpose: * * Alexa does not serialize UserEvents and so there is a risk of UserEvents * racing if the user presses multiple buttons in quick succession, where "quick * succession" means "significantly faster than the UserEvent round-trip * processing latency". Racing UserEvents can cause dropped state and/or * out-of-order event processing. This property provides the option to use * client-side-blocking to avoid the risks and costs of UserEvent races at the * expense of disabling and re-enabling the user input buttons. * * Pros and cons of blocking behavior: * * Pros: the user-interface is disabled which prevents users pressing more * buttons until the server is ready to accept them. This removes the * possibility of race-conditions. * * Cons: causes the input elements to be disabled (shown in grey and inactive) * for a short duration which may be distracting to the user. * * When to use? * * Consider using this if the latency for a UserEvent round trip is high, e.g. * greater than 400ms. * * Consider using this if the cost of dropped inputs is high compared to the UI * friction of disabling/enabling buttons. * * Additional notes: * * The Done button always uses blocking behavior. */ radioButtonPressesBlockUI?: boolean; } export function DefaultAskQuestion( props: DefaultAskQuestionProps, ): (control: QuestionnaireControl, input: ControlInput) => AplContent { return (control: QuestionnaireControl, input: ControlInput) => { return { document: aplDocumentCore(control, input, props.radioButtonPressesBlockUI ?? true), dataSource: questionnaireDataSourceGenerator(control, input, props), }; }; } /** * The APL dataSource to use when requesting a value * * Default: A TextListLayout data source to bind to an APL document. * See * https://developer.amazon.com/en-US/docs/alexa/alexa-presentation-language/apl-data-source.html */ export function questionnaireDataSourceGenerator( control: QuestionnaireControl, input: ControlInput, contentProps: DefaultAskQuestionProps, ) { const content = control.getQuestionnaireContent(input); const questionItems = []; for (const [index, question] of content.questions.entries()) { questionItems.push({ primaryText: question.visualLabel, questionId: question.id, selectedIndex: control.getChoiceIndexById(content, control.state.value[question.id]?.choiceId) ?? '-1', }); } return { wrapper: { general: { controlId: control.id, dataVersion: 1, radioButtonSize: '85', buttonColumnWidth: '124', headerTitle: contentProps.title ?? i18next.t('QUESTIONNAIRE_CONTROL_DEFAULT_APL_HEADER_TITLE'), headerSubtitle: contentProps.subtitle ?? '', headerBackButton: false, nextButtonText: contentProps.submitButtonText ?? i18next.t('QUESTIONNAIRE_CONTROL_DEFAULT_APL_SUBMIT_TEXT'), debug: contentProps.debug ?? false, }, questionData: questionItems, }, }; } } /** * An APL document generator to use when requesting a value * Can produce both "blocking style" and "non-blocking style". */ function aplDocumentCore(control: QuestionnaireControl, input: ControlInput, blocking: boolean) { const content = control.getQuestionnaireContent(input); return { type: 'APL', version: '1.5', import: [ { name: 'alexa-layouts', version: '1.2.0', }, ], layouts: { AnswerButton: { parameters: [ { name: 'idx', description: 'Index of this button within the group', type: 'number', default: 0, }, ], items: { type: 'AlexaRadioButton', checked: '${idx == selectedIndex}', disabled: '${disableContent}', theme: '${theme}', accessibilityLabel: '${accessibilityLabel}', radioButtonHeight: '${radioButtonHeight}', radioButtonWidth: '${radioButtonWidth}', radioButtonColor: '${radioButtonColor}', onPress: [ { type: 'Sequential', /* Note: all multi-command actions should go on custom sequencer, else commands can be lost on user press. * https://developer.amazon.com/en-US/docs/alexa/alexa-presentation-language/apl-commands.html#normal-mode */ sequencer: 'CustomSequencer', commands: [ { type: 'SetValue', property: 'selectedIndex', value: '${selectedIndex == idx ? -1 : idx}', }, { type: 'SetValue', componentId: 'debugText', property: 'text', value: 'Question: ${questionId} Selected:${selectedIndex}', }, blocking ? { type: 'SetValue', componentId: 'root', property: 'disableContent', value: true, } : undefined, blocking ? { type: 'SetValue', componentId: 'root', property: 'enableWaitIndicator', value: true, delay: 1370, } : undefined, { type: 'SendEvent', arguments: [ '${wrapper.general.controlId}', 'radioClick', '${questionId}', '${selectedIndex}', ], }, ], }, ], }, }, QuestionRow: { parameters: [ { name: 'primaryText', description: 'Label', type: 'string', default: 'none', }, { name: 'selectedIndex', description: 'Which choice is selected', type: 'number', default: -1, }, { name: 'questionId', description: 'Which question does this row represent', type: 'string', default: 'none', }, { name: 'theme', description: 'Colors will be changed depending on the specified theme (light/dark). Defaults to dark theme.', type: 'string', default: 'dark', }, { name: 'radioButtonHeight', description: 'Height of the radioButton', type: 'dimension', default: '@radioButtonDefaultHeight', }, { name: 'radioButtonWidth', description: 'Width of the radioButton', type: 'dimension', default: '@radioButtonDefaultWidth', }, { name: 'buttonColumnWidth', description: 'Width of the radioButton columns', type: 'dimension', default: '@radioButtonDefaultWidth', }, { name: 'radioButtonColor', description: 'Selected color of the radioButton', type: 'color', default: "${theme != 'light' ? @colorAccent : '#1CA0CE'}", }, ], items: [ { type: 'Container', direction: 'row', items: [ { type: 'Container', width: '${buttonColumnWidth}', items: { type: 'AnswerButton', width: '${radioButtonWidth}', height: '${radioButtonHeight}', alignSelf: 'center', idx: 0, questionId: '${id}', }, }, { type: 'Container', width: '${buttonColumnWidth}', items: { type: 'AnswerButton', width: '${radioButtonWidth}', height: '${radioButtonHeight}', alignSelf: 'center', idx: 1, questionId: '${id}', }, }, { type: 'Text', text: '${primaryText}', textAlignVertical: 'center', }, ], }, ], }, }, mainTemplate: { parameters: ['wrapper'], item: { id: 'root', type: 'Container', width: '100vw', height: '100vh', disabled: '${disableContent}', bind: [ { name: 'disableContent', value: false, type: 'boolean', }, { name: 'enableWaitIndicator', value: false, type: 'boolean', }, ], items: [ { type: 'AlexaBackground', }, { type: 'AlexaHeader', id: 'heading1', headerDivider: true, headerBackButton: '${wrapper.general.headerBackButton}', headerBackButtonCommand: { type: 'SendEvent', arguments: ['goBack'], }, headerTitle: '${wrapper.general.headerTitle}', headerSubtitle: '${wrapper.general.headerSubtitle}', }, { type: 'Container', paddingLeft: '@spacingMedium', direction: 'row', items: [ { type: 'Text', style: 'textStyleHint', width: '${wrapper.general.buttonColumnWidth}', text: 'Yes', textAlign: 'center', }, { type: 'Text', style: 'textStyleHint', width: '${wrapper.general.buttonColumnWidth}', text: 'No', textAlign: 'center', }, { type: 'Text', text: '${primaryText}', textAlignVertical: 'center', }, ], }, { type: 'ScrollView', shrink: 1, grow: 1, items: [ { type: 'Sequence', width: '100vw', height: '80vh', paddingLeft: '@spacingMedium', data: '${wrapper.questionData}', items: { type: 'QuestionRow', primaryText: '${data.primaryText}', questionId: '${data.questionId}', selectedIndex: '${data.selectedIndex}', radioButtonColor: '${wrapper.general.radioButtonColor}', radioButtonHeight: '${wrapper.general.radioButtonSize}', radioButtonWidth: '${wrapper.general.radioButtonSize}', buttonColumnWidth: '${wrapper.general.buttonColumnWidth}', }, }, ], }, { when: '${wrapper.general.debug}', position: 'absolute', bottom: '0vh', }, { type: 'AlexaButton', id: 'nextButton', disabled: '${disableContent}', buttonText: '${wrapper.general.nextButtonText}', position: 'absolute', top: '10', right: '10', primaryAction: { type: 'Sequential', commands: [ { type: 'Sequential', /* Note: all multi-command actions should go on custom sequencer, else commands can be lost on user press. * https://developer.amazon.com/en-US/docs/alexa/alexa-presentation-language/apl-commands.html#normal-mode */ sequencer: 'CustomSequencer', commands: [ { type: 'SetValue', componentId: 'debugText', property: 'text', value: 'Complete', }, { type: 'SetValue', componentId: 'root', property: 'disableContent', value: true, }, { type: 'SendEvent', arguments: ['${wrapper.general.controlId}', 'complete'], }, { type: 'SetValue', componentId: 'root', property: 'enableWaitIndicator', value: true, delay: 1370, }, ], }, ], }, }, { type: 'AlexaProgressDots', position: 'absolute', display: "${enableWaitIndicator ? 'normal' : 'invisible'}", top: '50vh', right: '20dp', dotSize: '12dp', componentId: 'largeDotsId', spacing: '@spacingMedium', }, ], }, }, }; }
the_stack
import { Manager } from "./Manager"; import { Node, NodeStats } from "./Node"; import { Player, Track, UnresolvedTrack } from "./Player"; import { Queue } from "./Queue"; /** @hidden */ const TRACK_SYMBOL = Symbol("track"), /** @hidden */ UNRESOLVED_TRACK_SYMBOL = Symbol("unresolved"), SIZES = [ "0", "1", "2", "3", "default", "mqdefault", "hqdefault", "maxresdefault", ]; /** @hidden */ const escapeRegExp = (str: string): string => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); export abstract class TrackUtils { static trackPartial: string[] | null = null; private static manager: Manager; /** @hidden */ public static init(manager: Manager): void { this.manager = manager; } static setTrackPartial(partial: string[]): void { if (!Array.isArray(partial) || !partial.every(str => typeof str === "string")) throw new Error("Provided partial is not an array or not a string array."); if (!partial.includes("track")) partial.unshift("track"); this.trackPartial = partial; } /** * Checks if the provided argument is a valid Track or UnresolvedTrack, if provided an array then every element will be checked. * @param trackOrTracks */ static validate(trackOrTracks: unknown): boolean { if (typeof trackOrTracks === "undefined") throw new RangeError("Provided argument must be present."); if (Array.isArray(trackOrTracks) && trackOrTracks.length) { for (const track of trackOrTracks) { if (!(track[TRACK_SYMBOL] || track[UNRESOLVED_TRACK_SYMBOL])) return false } return true; } return ( trackOrTracks[TRACK_SYMBOL] || trackOrTracks[UNRESOLVED_TRACK_SYMBOL] ) === true; } /** * Checks if the provided argument is a valid UnresolvedTrack. * @param track */ static isUnresolvedTrack(track: unknown): boolean { if (typeof track === "undefined") throw new RangeError("Provided argument must be present."); return track[UNRESOLVED_TRACK_SYMBOL] === true; } /** * Checks if the provided argument is a valid Track. * @param track */ static isTrack(track: unknown): boolean { if (typeof track === "undefined") throw new RangeError("Provided argument must be present."); return track[TRACK_SYMBOL] === true; } /** * Builds a Track from the raw data from Lavalink and a optional requester. * @param data * @param requester */ static build(data: TrackData, requester?: unknown): Track { if (typeof data === "undefined") throw new RangeError('Argument "data" must be present.'); try { const track: Track = { track: data.track, title: data.info.title, identifier: data.info.identifier, author: data.info.author, duration: data.info.length, isSeekable: data.info.isSeekable, isStream: data.info.isStream, uri: data.info.uri, thumbnail: data.info.uri.includes("youtube") ? `https://img.youtube.com/vi/${data.info.identifier}/default.jpg` : null, displayThumbnail(size = "default"): string | null { const finalSize = SIZES.find((s) => s === size) ?? "default"; return this.uri.includes("youtube") ? `https://img.youtube.com/vi/${data.info.identifier}/${finalSize}.jpg` : null; }, requester, }; track.displayThumbnail = track.displayThumbnail.bind(track); if (this.trackPartial) { for (const key of Object.keys(track)) { if (this.trackPartial.includes(key)) continue; delete track[key]; } } Object.defineProperty(track, TRACK_SYMBOL, { configurable: true, value: true }); return track; } catch (error) { throw new RangeError(`Argument "data" is not a valid track: ${error.message}`); } } /** * Builds a UnresolvedTrack to be resolved before being played . * @param query * @param requester */ static buildUnresolved(query: string | UnresolvedQuery, requester?: unknown): UnresolvedTrack { if (typeof query === "undefined") throw new RangeError('Argument "query" must be present.'); let unresolvedTrack: Partial<UnresolvedTrack> = { requester, async resolve(): Promise<void> { const resolved = await TrackUtils.getClosestTrack(this) Object.getOwnPropertyNames(this).forEach(prop => delete this[prop]); Object.assign(this, resolved); } }; if (typeof query === "string") unresolvedTrack.title = query; else unresolvedTrack = { ...unresolvedTrack, ...query } Object.defineProperty(unresolvedTrack, UNRESOLVED_TRACK_SYMBOL, { configurable: true, value: true }); return unresolvedTrack as UnresolvedTrack; } static async getClosestTrack( unresolvedTrack: UnresolvedTrack ): Promise<Track> { if (!TrackUtils.manager) throw new RangeError("Manager has not been initiated."); if (!TrackUtils.isUnresolvedTrack(unresolvedTrack)) throw new RangeError("Provided track is not a UnresolvedTrack."); const query = [unresolvedTrack.author, unresolvedTrack.title].filter(str => !!str).join(" - "); const res = await TrackUtils.manager.search(query, unresolvedTrack.requester); if (res.loadType !== "SEARCH_RESULT") throw res.exception ?? { message: "No tracks found.", severity: "COMMON", }; if (unresolvedTrack.author) { const channelNames = [unresolvedTrack.author, `${unresolvedTrack.author} - Topic`]; const originalAudio = res.tracks.find(track => { return ( channelNames.some(name => new RegExp(`^${escapeRegExp(name)}$`, "i").test(track.author)) || new RegExp(`^${escapeRegExp(unresolvedTrack.title)}$`, "i").test(track.title) ); }); if (originalAudio) return originalAudio; } if (unresolvedTrack.duration) { const sameDuration = res.tracks.find(track => (track.duration >= (unresolvedTrack.duration - 1500)) && (track.duration <= (unresolvedTrack.duration + 1500)) ); if (sameDuration) return sameDuration; } return res.tracks[0]; } } /** Gets or extends structures to extend the built in, or already extended, classes to add more functionality. */ export abstract class Structure { /** * Extends a class. * @param name * @param extender */ public static extend<K extends keyof Extendable, T extends Extendable[K]>( name: K, extender: (target: Extendable[K]) => T ): T { if (!structures[name]) throw new TypeError(`"${name} is not a valid structure`); const extended = extender(structures[name]); structures[name] = extended; return extended; } /** * Get a structure from available structures by name. * @param name */ public static get<K extends keyof Extendable>(name: K): Extendable[K] { const structure = structures[name]; if (!structure) throw new TypeError('"structure" must be provided.'); return structure; } } export class Plugin { public load(manager: Manager): void {} public unload(manager: Manager): void {} } const structures = { Player: require("./Player").Player, Queue: require("./Queue").Queue, Node: require("./Node").Node, }; export interface UnresolvedQuery { /** The title of the unresolved track. */ title: string; /** The author of the unresolved track. If provided it will have a more precise search. */ author?: string; /** The duration of the unresolved track. If provided it will have a more precise search. */ duration?: number; } export type Sizes = | "0" | "1" | "2" | "3" | "default" | "mqdefault" | "hqdefault" | "maxresdefault"; export type LoadType = | "TRACK_LOADED" | "PLAYLIST_LOADED" | "SEARCH_RESULT" | "LOAD_FAILED" | "NO_MATCHES"; export type State = | "CONNECTED" | "CONNECTING" | "DISCONNECTED" | "DISCONNECTING" | "DESTROYING"; export type PlayerEvents = | TrackStartEvent | TrackEndEvent | TrackStuckEvent | TrackExceptionEvent | WebSocketClosedEvent; export type PlayerEventType = | "TrackStartEvent" | "TrackEndEvent" | "TrackExceptionEvent" | "TrackStuckEvent" | "WebSocketClosedEvent"; export type TrackEndReason = | "FINISHED" | "LOAD_FAILED" | "STOPPED" | "REPLACED" | "CLEANUP"; export type Severity = "COMMON" | "SUSPICIOUS" | "FAULT"; export interface TrackData { track: string; info: TrackDataInfo; } export interface TrackDataInfo { title: string; identifier: string; author: string; length: number; isSeekable: boolean; isStream: boolean; uri: string; } export interface Extendable { Player: typeof Player; Queue: typeof Queue; Node: typeof Node; } export interface VoiceState { op: "voiceUpdate"; guildId: string; event: VoiceEvent; sessionId?: string; } export interface VoiceEvent { token: string; guild_id: string; endpoint: string; } export interface VoicePacket { t?: string; d: Partial<{ guild_id: string; user_id: string; session_id: string; channel_id: string; }> & VoiceEvent; } export interface NodeMessage extends NodeStats { type: PlayerEventType; op: "stats" | "playerUpdate" | "event"; guildId: string; } export interface PlayerEvent { op: "event"; type: PlayerEventType; guildId: string; } export interface Exception { severity: Severity; message: string; cause: string; } export interface TrackStartEvent extends PlayerEvent { type: "TrackStartEvent"; track: string; } export interface TrackEndEvent extends PlayerEvent { type: "TrackEndEvent"; track: string; reason: TrackEndReason; } export interface TrackExceptionEvent extends PlayerEvent { type: "TrackExceptionEvent"; exception?: Exception; error: string; } export interface TrackStuckEvent extends PlayerEvent { type: "TrackStuckEvent"; thresholdMs: number; } export interface WebSocketClosedEvent extends PlayerEvent { type: "WebSocketClosedEvent"; code: number; byRemote: boolean; reason: string; } export interface PlayerUpdate { op: "playerUpdate"; state: { position: number; time: number; }; guildId: string; }
the_stack
// clang-format off import {isChromeOS, webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; import {listenOnce} from 'chrome://resources/js/util.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {ChooserType, ContentSetting, ContentSettingsTypes, SiteDetailsElement, SiteSettingSource, SiteSettingsPrefsBrowserProxyImpl, WebsiteUsageBrowserProxy, WebsiteUsageBrowserProxyImpl} from 'chrome://settings/lazy_load.js'; import {MetricsBrowserProxyImpl, PrivacyElementInteractions, Router, routes} from 'chrome://settings/settings.js'; import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {TestBrowserProxy} from 'chrome://webui-test/test_browser_proxy.js'; import {TestMetricsBrowserProxy} from './test_metrics_browser_proxy.js'; import {TestSiteSettingsPrefsBrowserProxy} from './test_site_settings_prefs_browser_proxy.js'; import {createContentSettingTypeToValuePair, createRawChooserException, createRawSiteException, createSiteSettingsPrefs, SiteSettingsPref} from './test_util.js'; // clang-format on class TestWebsiteUsageBrowserProxy extends TestBrowserProxy implements WebsiteUsageBrowserProxy { constructor() { super(['clearUsage', 'fetchUsageTotal']); } fetchUsageTotal(host: string) { this.methodCalled('fetchUsageTotal', host); } clearUsage(origin: string) { this.methodCalled('clearUsage', origin); } } /** @fileoverview Suite of tests for site-details. */ suite('SiteDetails', function() { /** * A site list element created before each test. */ let testElement: SiteDetailsElement; /** * An example pref with 1 pref in each category. */ let prefs: SiteSettingsPref; /** * The mock site settings prefs proxy object to use during test. */ let browserProxy: TestSiteSettingsPrefsBrowserProxy; let testMetricsBrowserProxy: TestMetricsBrowserProxy; /** * The mock website usage proxy object to use during test. */ let websiteUsageProxy: TestWebsiteUsageBrowserProxy; // Initialize a site-details before each test. setup(function() { prefs = createSiteSettingsPrefs( [], [ createContentSettingTypeToValuePair( ContentSettingsTypes.COOKIES, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.IMAGES, [createRawSiteException('https://foo.com:443', { source: SiteSettingSource.DEFAULT, })]), createContentSettingTypeToValuePair( ContentSettingsTypes.JAVASCRIPT, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.SOUND, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.POPUPS, [createRawSiteException('https://foo.com:443', { setting: ContentSetting.BLOCK, source: SiteSettingSource.DEFAULT, })]), createContentSettingTypeToValuePair( ContentSettingsTypes.GEOLOCATION, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.NOTIFICATIONS, [createRawSiteException('https://foo.com:443', { setting: ContentSetting.ASK, source: SiteSettingSource.POLICY, })]), createContentSettingTypeToValuePair( ContentSettingsTypes.MIC, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.CAMERA, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.AUTOMATIC_DOWNLOADS, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.BACKGROUND_SYNC, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.MIDI_DEVICES, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.PROTECTED_CONTENT, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.ADS, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.CLIPBOARD, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.SENSORS, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.PAYMENT_HANDLER, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.SERIAL_PORTS, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.BLUETOOTH_SCANNING, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.FILE_SYSTEM_WRITE, [createRawSiteException('https://foo.com:443', { setting: ContentSetting.BLOCK, })]), createContentSettingTypeToValuePair( ContentSettingsTypes.MIXEDSCRIPT, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.HID_DEVICES, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.BLUETOOTH_DEVICES, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.AR, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.VR, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.WINDOW_PLACEMENT, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.FONT_ACCESS, [createRawSiteException('https://foo.com:443')]), createContentSettingTypeToValuePair( ContentSettingsTypes.IDLE_DETECTION, [createRawSiteException('https://foo.com:443')]), ], [ createContentSettingTypeToValuePair( ContentSettingsTypes.USB_DEVICES, [createRawChooserException( ChooserType.USB_DEVICES, [createRawSiteException('https://foo.com:443')])]), createContentSettingTypeToValuePair( ContentSettingsTypes.BLUETOOTH_DEVICES, [createRawChooserException( ChooserType.BLUETOOTH_DEVICES, [createRawSiteException('https://foo.com:443')])]), ]); browserProxy = new TestSiteSettingsPrefsBrowserProxy(); SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy); testMetricsBrowserProxy = new TestMetricsBrowserProxy(); MetricsBrowserProxyImpl.setInstance(testMetricsBrowserProxy); websiteUsageProxy = new TestWebsiteUsageBrowserProxy(); WebsiteUsageBrowserProxyImpl.setInstance(websiteUsageProxy); document.body.innerHTML = ''; }); function createSiteDetails(origin: string) { const siteDetailsElement = document.createElement('site-details'); document.body.appendChild(siteDetailsElement); Router.getInstance().navigateTo( routes.SITE_SETTINGS_SITE_DETAILS, new URLSearchParams('site=' + origin)); return siteDetailsElement; } test('usage heading shows properly', async function() { browserProxy.setPrefs(prefs); testElement = createSiteDetails('https://foo.com:443'); await websiteUsageProxy.whenCalled('fetchUsageTotal'); assertTrue(!!testElement.$.usage); // When there's no usage, there should be a string that says so. assertEquals( '', testElement.shadowRoot!.querySelector( '#storedData')!.textContent!.trim()); assertFalse(testElement.$.noStorage.hidden); assertTrue(testElement.$.storage.hidden); assertTrue(testElement.$.usage.textContent!.includes('No usage data')); // If there is, check the correct amount of usage is specified. const usage = '1 KB'; webUIListenerCallback( 'usage-total-changed', 'foo.com', usage, '10 cookies'); assertTrue(testElement.$.noStorage.hidden); assertFalse(testElement.$.storage.hidden); assertTrue(testElement.$.usage.textContent!.includes(usage)); }); test('storage gets trashed properly', function() { const origin = 'https://foo.com:443'; browserProxy.setPrefs(prefs); testElement = createSiteDetails(origin); flush(); return Promise .all([ browserProxy.whenCalled('getOriginPermissions'), websiteUsageProxy.whenCalled('fetchUsageTotal'), ]) .then(results => { const hostRequested = results[1]; assertEquals('foo.com', hostRequested); webUIListenerCallback( 'usage-total-changed', hostRequested, '1 KB', '10 cookies'); assertEquals( '1 KB', testElement.shadowRoot!.querySelector( '#storedData')!.textContent!.trim()); assertTrue(testElement.$.noStorage.hidden); assertFalse(testElement.$.storage.hidden); testElement.shadowRoot! .querySelector<HTMLElement>( '#confirmClearStorage .action-button')!.click(); return websiteUsageProxy.whenCalled('clearUsage'); }) .then(originCleared => { assertEquals('https://foo.com/', originCleared); }); }); test('cookies gets deleted properly', function() { const origin = 'https://foo.com:443'; browserProxy.setPrefs(prefs); testElement = createSiteDetails(origin); return Promise .all([ browserProxy.whenCalled('getOriginPermissions'), websiteUsageProxy.whenCalled('fetchUsageTotal'), ]) .then(results => { // Ensure the mock's methods were called and check usage was cleared // on clicking the trash button. const hostRequested = results[1]; assertEquals('foo.com', hostRequested); webUIListenerCallback( 'usage-total-changed', hostRequested, '1 KB', '10 cookies'); assertEquals( '10 cookies', testElement.shadowRoot!.querySelector( '#numCookies')!.textContent!.trim()); assertTrue(testElement.$.noStorage.hidden); assertFalse(testElement.$.storage.hidden); testElement.shadowRoot! .querySelector<HTMLElement>( '#confirmClearStorage .action-button')!.click(); return websiteUsageProxy.whenCalled('clearUsage'); }) .then(originCleared => { assertEquals('https://foo.com/', originCleared); return testMetricsBrowserProxy.whenCalled( 'recordSettingsPageHistogram'); }) .then(metric => { assertEquals( PrivacyElementInteractions.SITE_DETAILS_CLEAR_DATA, metric); }); }); test('correct pref settings are shown', function() { browserProxy.setPrefs(prefs); testElement = createSiteDetails('https://foo.com:443'); return browserProxy.whenCalled('isOriginValid') .then(() => { return browserProxy.whenCalled('getOriginPermissions'); }) .then(() => { testElement.shadowRoot!.querySelectorAll('site-details-permission') .forEach((siteDetailsPermission) => { if (!isChromeOS && siteDetailsPermission.category === ContentSettingsTypes.PROTECTED_CONTENT) { return; } // Verify settings match the values specified in |prefs|. let expectedSetting = ContentSetting.ALLOW; let expectedSource = SiteSettingSource.PREFERENCE; let expectedMenuValue = ContentSetting.ALLOW; // For all the categories with non-user-set 'Allow' preferences, // update expected values. if (siteDetailsPermission.category === ContentSettingsTypes.NOTIFICATIONS || siteDetailsPermission.category === ContentSettingsTypes.JAVASCRIPT || siteDetailsPermission.category === ContentSettingsTypes.IMAGES || siteDetailsPermission.category === ContentSettingsTypes.POPUPS || siteDetailsPermission.category === ContentSettingsTypes.FILE_SYSTEM_WRITE) { expectedSetting = prefs.exceptions[siteDetailsPermission.category][0]! .setting; expectedSource = prefs.exceptions[siteDetailsPermission.category][0]! .source; expectedMenuValue = (expectedSource === SiteSettingSource.DEFAULT) ? ContentSetting.DEFAULT : expectedSetting; } assertEquals( expectedSetting, siteDetailsPermission.site.setting); assertEquals(expectedSource, siteDetailsPermission.site.source); assertEquals( expectedMenuValue, siteDetailsPermission.$.permission.value); }); }); }); test('categories can be hidden', function() { browserProxy.setPrefs(prefs); // Only the categories in this list should be visible to the user. browserProxy.setCategoryList( [ContentSettingsTypes.NOTIFICATIONS, ContentSettingsTypes.GEOLOCATION]); testElement = createSiteDetails('https://foo.com:443'); return browserProxy.whenCalled('isOriginValid') .then(() => { return browserProxy.whenCalled('getOriginPermissions'); }) .then(() => { testElement.shadowRoot!.querySelectorAll('site-details-permission') .forEach((siteDetailsPermission) => { const shouldBeVisible = siteDetailsPermission.category === ContentSettingsTypes.NOTIFICATIONS || siteDetailsPermission.category === ContentSettingsTypes.GEOLOCATION; assertEquals( !shouldBeVisible, siteDetailsPermission.$.details.hidden); }); }); }); test('show confirmation dialog on reset settings', function() { browserProxy.setPrefs(prefs); const origin = 'https://foo.com:443'; testElement = createSiteDetails(origin); flush(); // Check both cancelling and accepting the dialog closes it. ['cancel-button', 'action-button'].forEach(buttonType => { testElement.shadowRoot! .querySelector<HTMLElement>('#resetSettingsButton')!.click(); assertTrue(testElement.$.confirmResetSettings.open); const actionButtonList = testElement.shadowRoot!.querySelectorAll<HTMLElement>( `#confirmResetSettings .${buttonType}`); assertEquals(1, actionButtonList.length); actionButtonList[0]!.click(); assertFalse(testElement.$.confirmResetSettings.open); }); // Accepting the dialog will make a call to setOriginPermissions. return browserProxy.whenCalled('setOriginPermissions').then((args) => { assertEquals(origin, args[0]); assertDeepEquals(null, args[1]); assertEquals(ContentSetting.DEFAULT, args[2]); }); }); test('show confirmation dialog on clear storage', function() { browserProxy.setPrefs(prefs); testElement = createSiteDetails('https://foo.com:443'); flush(); // Check both cancelling and accepting the dialog closes it. ['cancel-button', 'action-button'].forEach(buttonType => { testElement.shadowRoot!.querySelector<HTMLElement>( '#usage cr-button')!.click(); assertTrue(testElement.$.confirmClearStorage.open); const actionButtonList = testElement.shadowRoot!.querySelectorAll<HTMLElement>( `#confirmClearStorage .${buttonType}`); assertEquals(1, actionButtonList.length); actionButtonList[0]!.click(); assertFalse(testElement.$.confirmClearStorage.open); }); }); test('permissions update dynamically', function() { browserProxy.setPrefs(prefs); const origin = 'https://foo.com:443'; testElement = createSiteDetails(origin); const elems = testElement.shadowRoot!.querySelectorAll('site-details-permission'); const notificationPermission = Array.from(elems).find( elem => elem.category === ContentSettingsTypes.NOTIFICATIONS)!; // Wait for all the permissions to be populated initially. return browserProxy.whenCalled('isOriginValid') .then(() => { return browserProxy.whenCalled('getOriginPermissions'); }) .then(() => { // Make sure initial state is as expected. assertEquals(ContentSetting.ASK, notificationPermission.site.setting); assertEquals( SiteSettingSource.POLICY, notificationPermission.site.source); assertEquals( ContentSetting.ASK, notificationPermission.$.permission.value); // Set new prefs and make sure only that permission is updated. const newException = createRawSiteException(origin, { embeddingOrigin: origin, origin: origin, setting: ContentSetting.BLOCK, source: SiteSettingSource.DEFAULT, }); browserProxy.resetResolver('getOriginPermissions'); browserProxy.setSingleException( ContentSettingsTypes.NOTIFICATIONS, newException); return browserProxy.whenCalled('getOriginPermissions'); }) .then((args) => { // The notification pref was just updated, so make sure the call to // getOriginPermissions was to check notifications. assertTrue(args[1].includes(ContentSettingsTypes.NOTIFICATIONS)); // Check |notificationPermission| now shows the new permission value. assertEquals( ContentSetting.BLOCK, notificationPermission.site.setting); assertEquals( SiteSettingSource.DEFAULT, notificationPermission.site.source); assertEquals( ContentSetting.DEFAULT, notificationPermission.$.permission.value); }); }); test('invalid origins navigate back', function() { const invalid_url = 'invalid url'; browserProxy.setIsOriginValid(false); Router.getInstance().navigateTo(routes.SITE_SETTINGS); testElement = createSiteDetails(invalid_url); assertEquals( routes.SITE_SETTINGS_SITE_DETAILS.path, Router.getInstance().getCurrentRoute().path); return browserProxy.whenCalled('isOriginValid') .then((args) => { assertEquals(invalid_url, args); return new Promise((resolve) => { listenOnce(window, 'popstate', resolve); }); }) .then(() => { assertEquals( routes.SITE_SETTINGS.path, Router.getInstance().getCurrentRoute().path); }); }); test('call fetch block autoplay status', function() { const origin = 'https://foo.com:443'; browserProxy.setPrefs(prefs); testElement = createSiteDetails(origin); return browserProxy.whenCalled('fetchBlockAutoplayStatus'); }); });
the_stack
import { getSupportedInterfaces } from 'ask-sdk-core'; import { Intent, IntentRequest, interfaces } from 'ask-sdk-model'; import i18next from 'i18next'; import _ from 'lodash'; import { AmazonBuiltInSlotType, DeepRequired, falseIfGuardFailed, InputUtil, ModelData, okIf, unpackValueControlIntent, ValueControlIntent, } from '../..'; import { Strings as $ } from '../../constants/Strings'; import { Control, ControlInitiativeHandler, ControlInputHandler, ControlInputHandlingProps, ControlProps, ControlState, } from '../../controls/Control'; import { ControlInput } from '../../controls/ControlInput'; import { ControlResultBuilder } from '../../controls/ControlResult'; import { ControlServices, ControlServicesProps } from '../../controls/ControlServices'; import { ILogger } from '../../controls/interfaces/ILogger'; import { InteractionModelContributor } from '../../controls/mixins/InteractionModelContributor'; import { evaluateValidationProp, StateValidationFunction, ValidationFailure, } from '../../controls/Validation'; import { GeneralControlIntent, unpackGeneralControlIntent } from '../../intents/GeneralControlIntent'; import { ControlInteractionModelGenerator } from '../../interactionModelGeneration/ControlInteractionModelGenerator'; import { ModalityEvaluationDefaults, ResponseStyleEvaluator } from '../../modality/ModalityEvaluation'; import { APLMode } from '../../responseGeneration/AplMode'; import { ControlResponseBuilder } from '../../responseGeneration/ControlResponseBuilder'; import { InvalidValueAct, ValueChangedAct, ValueClearedAct, ValueConfirmedAct, ValueDisconfirmedAct, ValueSetAct, } from '../../systemActs/ContentActs'; import { ConfirmValueAct, InitiativeAct, RequestValueAct, SuggestValueAct, } from '../../systemActs/InitiativeActs'; import { SystemAct } from '../../systemActs/SystemAct'; import { StringOrList } from '../../utils/BasicTypes'; import { evaluateInputHandlers } from '../../utils/ControlUtils'; import { addFragmentsForResponseStyle, getDeterminateResponseStyle } from '../../utils/ResponseUtils'; import { NumberControlAPLComponentBuiltIns, NumberControlAPLPropsBuiltIns } from './NumberControlAPL'; import { NumberControlBuiltIns } from './NumberControlBuiltIns'; const MODULE_NAME = 'AskSdkControls:NumberControl'; /** * Props for a NumberControl. */ export interface NumberControlProps extends ControlProps { /** * Unique identifier for control instance */ id: string; /** * Function(s) that determine if the value is valid. * * Default: `true`, i.e. any value is valid. * * Usage: * - Validation functions return either `true` or a `ValidationResult` to * describe what validation failed. */ validation?: | StateValidationFunction<NumberControlState> | Array<StateValidationFunction<NumberControlState>>; /** * Determines if the Control must obtain a value. * * - If `true` the Control will take initiative to elicit a value. * - If `false` the Control will not take initiative to elicit a value, but the user * can provide one if they wish, e.g. "U: I would three of those". */ required?: boolean | ((input: ControlInput) => boolean); /** * Props to customize the prompt fragments that will be added by `this.renderAct()`. */ prompts?: NumberControlPromptsProps; /** * Props to customize the reprompt fragments that will be added by `this.renderAct()`. */ reprompts?: NumberControlPromptsProps; /** * Whether the Control has to obtain explicit confirmation of the value. * * If `true`: * - the Control will take initiative to explicitly confirm the value with a yes/no * question. * * Default: false * * Usage: * * 1) Use pre-defined built-ins under NumberControlBuiltIns.* namespace which provides few * default implementations. * * e.g: NumberControlBuiltIns.confirmMostLikelyMisunderstandingInputs returns `true` whenever * an input has a most-likely misunderstanding value defined on the function * NumberControlBuiltIns.defaultMostLikelyMisunderstandingFunc. */ confirmationRequired?: boolean | ((state: NumberControlState, input: ControlInput) => boolean); /** * Function that returns the single most likely misunderstanding for a given value, or undefined if none is known. * * Default: `NumberControlBuiltIns.defaultMostLikelyMisunderstandingFunc(value)` * * Control behavior: * - If the user disaffirms a value the most likely misunderstood value is suggested to the user. * e.g: * * A: What number? * U: Fourteen * A: Was the fourteen? * U: No * A: My mistake. Did you perhaps say forty? * U: Yes * A: Great. 40. */ mostLikelyMisunderstanding?: (value: number, input: ControlInput) => number | undefined; /** * Props to customize the relationship between the control and the * interaction model. */ interactionModel?: NumberControlInteractionModelProps; /** * Props to configure input handling. */ inputHandling?: ControlInputHandlingProps; /** * Props to customize the APL generated by this control. */ apl?: NumberControlAPLProps; /** * Function that maps the NumberControlState.value to rendered value that * will be presented to the user as a list. * * Default: returns the value unchanged in string format. */ valueRenderer?: (value: number, input: ControlInput) => string; /** * Props to customize services used by the control. */ services?: ControlServicesProps; /** * Function that determines the preferred response style based on input * and input modality history. * * Default: Function always returns indeterminate response style, which * causes the decision to be deferred to the function configured in ControlManager. */ responseStyleEvaluator?: ResponseStyleEvaluator; } /** * Mapping of action slot values to the capability that this control supports. * * Behavior: * - This control will not handle an input if the action-slot is filled with an * value whose ID is not associated with a capability. */ export type NumberControlActionProps = { /** * Action slot value IDs that are associated with the "set value" capability. * * Default: ['builtin_set'] */ set?: string[]; /** * Action slot value IDs that are associated with the "change value" capability. * * Default ['builtin_change'] */ change?: string[]; /** * Action slot value IDs that are associated with the "clear value" capability. * * Default ['builtin_clear', builtin_remove'] */ clear?: string[]; }; /** * Props associated with the interaction model. */ export interface NumberControlInteractionModelProps { /** * Target-slot values associated with this Control. * * Targets associate utterances to a control. For example, if the user says * "change the time", it is parsed as a `GeneralControlIntent` with slot * values `action = change` and `target = time`. Only controls that are * registered with the `time` target should offer to handle this intent. * * Default: ['builtin_it'] * * Usage: * - If this prop is defined, it replaces the default; it is not additive to * the defaults. To add an additional target to the defaults, copy the * defaults and amend. * - A control can be associated with many target-slot-values, eg ['date', * 'startDate', 'eventStartDate', 'vacationStart'] * - It is a good idea to associate with general targets (e.g. date) and * also with specific targets (e.g. vacationStart) so that the user can * say either general or specific things. e.g. 'change the date to * Tuesday', or 'I want my vacation to start on Tuesday'. * - The association does not have to be exclusive, and general target slot * values will often be associated with many controls. In situations where * there is ambiguity about what the user is referring to, the parent * controls must resolve the confusion. * - The 'builtin_*' IDs are associated with default interaction model data * (which can be extended as desired). Any other IDs will require a full * definition of the allowed synonyms in the interaction model. * * Control behavior: * - A control will not handle an input that mentions a target that is not * registered by this prop. * */ targets?: string[]; /** * Action slot-values associated to the control's capabilities. * * Action slot-values associate utterances to a control. For example, if the * user says "change the time", it is parsed as a `GeneralControlIntent` * with slot values `action = change` and `target = time`. Only controls * that are registered with the `change` action should offer to handle this * intent. * * Usage: * - This allows users to refer to an action using more domain-appropriate * words. For example, a user might like to say 'show two items' rather * that 'set item count to two'. To achieve this, include the * slot-value-id 'show' in the list associated with the 'set' capability * and ensure the interaction-model includes an action slot value with * id=show and appropriate synonyms. * - The 'builtin_*' IDs are associated with default interaction model data * (which can be extended as desired). Any other IDs will require a full * definition of the allowed synonyms in the interaction model. */ actions?: NumberControlActionProps; } /** * Props to customize the prompt fragments that will be added by `this.renderAct()`. */ export interface NumberControlPromptsProps { requestValue?: StringOrList | ((act: RequestValueAct, input: ControlInput) => StringOrList); valueSet?: StringOrList | ((act: ValueSetAct<number>, input: ControlInput) => StringOrList); valueChanged?: StringOrList | ((act: ValueChangedAct<number>, input: ControlInput) => StringOrList); confirmValue?: StringOrList | ((act: ConfirmValueAct<number>, input: ControlInput) => StringOrList); valueConfirmed?: StringOrList | ((act: ValueConfirmedAct<number>, input: ControlInput) => StringOrList); valueDisconfirmed?: | StringOrList | ((act: ValueDisconfirmedAct<number>, input: ControlInput) => StringOrList); valueCleared?: StringOrList | ((act: ValueClearedAct<number>, input: ControlInput) => StringOrList); invalidValue?: StringOrList | ((act: InvalidValueAct<number>, input: ControlInput) => StringOrList); suggestValue?: StringOrList | ((act: SuggestValueAct<number>, input: ControlInput) => StringOrList); } export type AplContent = { document: { [key: string]: any }; dataSource: { [key: string]: any } }; export type AplContentFunc = ( control: NumberControl, input: ControlInput, ) => AplContent | Promise<AplContent>; export type AplDocumentPropNewStyle = AplContent | AplContentFunc; export type NumberControlAplRenderComponentFunc = ( control: NumberControl, props: NumberControlAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) => { [key: string]: any }; /** * Props associated with the APL produced by NumberControl. */ export class NumberControlAPLProps { /** * Determines if APL should be produced. * * Default: true */ enabled?: boolean | ((input: ControlInput) => boolean); /** * Defines the APL to use when requesting a value. */ requestValue?: AplDocumentPropNewStyle; /** * Tracks the text to be displayed for invalid input values. */ validationFailedMessage?: string | ((value?: number) => string); /** * Determines the APL Component rendering mode. * * Usage: * * 1) Use pre-defined built-ins under ListControlComponentAPLBuiltIns.* namespace which provides both default * implementations and customization of props(NumberControlAPLComponentProps) to render an APL component. * * e.g renderComponent: NumberControlAPLComponentBuiltIns.ModalKeyPadRender.default --- Default Implementation * renderComponent: NumberControlAPLComponentBuiltIns.ModalKeyPadRender.default.of(props: NumberControlAPLComponentProps) --- Override few properties * * 2) Provide a custom function which returns an APL component. * * Default: NumberControlAPLComponentBuiltIns.ModalKeyPadRender.default */ renderComponent?: NumberControlAplRenderComponentFunc; } /** * Tracks the last act initiated from the control. */ interface LastInitiativeState { /** * Control act name. */ actName?: string; } /** * Props to customize NumberControl APLComponent rendering. */ export interface NumberControlAPLComponentProps { /** * Tracks the text to be displayed for invalid input values * when control renders APL in Component Mode. */ validationFailedMessage?: string | ((value?: number) => string); /** * Function that maps the NumberControlState.value to rendered value that * will be presented to the user. * * Default: returns the value unchanged */ valueRenderer?: (value: number, input: ControlInput) => string; } /** * State tracked by a NumberControl. */ export class NumberControlState implements ControlState { /** * The value, an integer. */ value: number; /** * Tracks whether the value has been explicitly confirmed by the user. */ confirmed?: boolean; /** * Tracks the last initiative act from the control */ lastInitiative: LastInitiativeState; /** * Tracks the most recent elicitation action. * * Note: this isn't cleared immediate after user provides a value as the * value maybe be invalid and has to be re-elicited. Use * state.lastInitiative to test if the most recent turn was a direct elicitation. */ elicitationAction?: string; } const FEEDBACK_TYPES = [$.Feedback.Affirm, $.Feedback.Disaffirm]; /** * A Control that obtains a single integer from the user. * * Capabilities: * - Request a value * - Change a value * - Validate the value * - Confirm the value * - Suggest a value, if the user disconfirms and we know a good alternative to suggest. * * Intents that can be handled: * - `GeneralControlIntent`: E.g. `"yes, update my age"` * - `AMAZON_NUMBER_ValueControlIntent`: E.g. "no change it to three". * - `AMAZON.YesIntent`, `AMAZON.NoIntent` * * APL events that can be handled: * - touch events indicating number value input. */ export class NumberControl extends Control implements InteractionModelContributor { state: NumberControlState = new NumberControlState(); private rawProps: NumberControlProps; private props: DeepRequired<NumberControlProps>; private handleFunc?: (input: ControlInput, resultBuilder: ControlResultBuilder) => void | Promise<void>; private initiativeFunc?: ( input: ControlInput, resultBuilder: ControlResultBuilder, ) => void | Promise<void>; private log: ILogger; constructor(props: NumberControlProps) { super(props.id); this.rawProps = props; this.props = NumberControl.mergeWithDefaultProps(props); this.state.lastInitiative = {}; this.log = this.props.services.logger.getLogger(MODULE_NAME); } /** * Merges the user-provided props with the default props. * * Any property defined by the user-provided data overrides the defaults. */ static mergeWithDefaultProps(props: NumberControlProps): DeepRequired<NumberControlProps> { const defaults: DeepRequired<NumberControlProps> = { id: 'placeholder', interactionModel: { actions: { set: [$.Action.Set], change: [$.Action.Change], clear: [$.Action.Clear, $.Action.Remove], }, targets: [$.Target.Number, $.Target.It], }, prompts: { requestValue: i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_REQUEST_VALUE'), valueChanged: (act) => i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_CHANGED', { value: act.payload.renderedValue, }), confirmValue: (act) => i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_CONFIRM_VALUE', { value: act.payload.renderedValue, }), valueConfirmed: i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_CONFIRMED'), valueDisconfirmed: i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_DISAFFIRMED'), valueSet: (act) => i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_SET', { value: act.payload.renderedValue, }), valueCleared: i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_CLEARED'), invalidValue: (act) => { if (act.payload.renderedReason !== undefined) { return i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_INVALID_VALUE_WITH_REASON', { value: act.payload.renderedValue, reason: act.payload.renderedReason, }); } return i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_GENERAL_INVALID_VALUE', { value: act.payload.renderedValue, }); }, suggestValue: (act) => i18next.t('NUMBER_CONTROL_DEFAULT_PROMPT_SUGGEST_VALUE', { value: act.payload.renderedValue, }), }, reprompts: { requestValue: i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_REQUEST_VALUE'), valueChanged: (act) => i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_CHANGED', { value: act.payload.renderedValue, }), confirmValue: (act) => i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_CONFIRM_VALUE', { value: act.payload.renderedValue, }), valueDisconfirmed: i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_DISAFFIRMED'), valueSet: (act) => i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_SET', { value: act.payload.renderedValue, }), valueConfirmed: i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_CONFIRMED'), valueCleared: (act) => i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_CLEARED', { value: act.payload.renderedValue, }), invalidValue: (act) => { if (act.payload.renderedReason !== undefined) { return i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_INVALID_VALUE_WITH_REASON', { value: act.payload.renderedValue, reason: act.payload.renderedReason, }); } return i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_GENERAL_INVALID_VALUE', { value: act.payload.renderedValue, }); }, suggestValue: (act) => i18next.t('NUMBER_CONTROL_DEFAULT_REPROMPT_SUGGEST_VALUE', { value: act.payload.renderedValue, }), }, validation: [], confirmationRequired: false, required: true, apl: { enabled: true, validationFailedMessage: NumberControlBuiltIns.defaultValidationFailureText(), requestValue: NumberControlAPLPropsBuiltIns.defaultSelectValueAPLContent({ validationFailedMessage: props.apl?.validationFailedMessage, }), renderComponent: NumberControlAPLComponentBuiltIns.ModalKeyPadRender.default, }, inputHandling: { customHandlingFuncs: [], }, mostLikelyMisunderstanding: NumberControlBuiltIns.defaultMostLikelyMisunderstandingFunc, valueRenderer: (value: number, input) => value.toString(), services: props.services ?? ControlServices.getDefaults(), responseStyleEvaluator: ModalityEvaluationDefaults.indeterminateResponseStyleEvaluator, }; return _.merge(defaults, props); } standardInputHandlers: ControlInputHandler[] = [ { name: 'SetWithValue (built-in)', canHandle: this.isSetWithValue, handle: this.handleSetWithValue, }, { name: 'SetWithoutValue (built-in)', canHandle: this.isSetWithoutValue, handle: this.handleSetWithoutValue, }, { name: 'ChangeWithValue (built-in)', canHandle: this.isChangeWithValue, handle: this.handleChangeWithValue, }, { name: 'ChangeWithoutValue (built-in)', canHandle: this.isChangeWithoutValue, handle: this.handleChangeWithoutValue, }, { name: 'BareValue (built-in)', canHandle: this.isBareValue, handle: this.handleBareValue, }, { name: 'ConfirmationAffirmed (built-in)', canHandle: this.isConfirmationAffirmed, handle: this.handleConfirmationAffirmed, }, { name: 'ConfirmationDisaffirmed (built-in)', canHandle: this.isConfirmationDisaffirmed, handle: this.handleConfirmationDisaffirmed, }, { name: 'isAffirmWithValue (built-in)', canHandle: this.isAffirmWithValue, handle: this.handleAffirmWithValue, }, { name: 'isDisaffirmWithValue (built-in)', canHandle: this.isDisaffirmWithValue, handle: this.handleDisaffirmWithValue, }, { name: 'ClearValue (builtin)', canHandle: this.isClearValue, handle: this.handleClearValue, }, { name: 'SelectChoiceByTouch (built-in)', canHandle: this.isSelectChoiceByTouch, handle: this.handleSelectChoiceByTouch, }, { name: 'SuggestionAccepted (built-in)', canHandle: this.isSuggestionAccepted, handle: this.handleSuggestionAccepted, }, ]; // tsDoc - see Control async canHandle(input: ControlInput): Promise<boolean> { return evaluateInputHandlers(this, input); } // tsDoc - see Control async handle(input: ControlInput, resultBuilder: ControlResultBuilder): Promise<void> { this.log.debug(`NumberControl[${this.id}]: handle(). Entering`); const intent: Intent = (input.request as IntentRequest).intent; if (this.handleFunc === undefined) { throw new Error(`${intent.name} can not be handled by ${this.constructor.name}.`); } await this.handleFunc(input, resultBuilder); if (!resultBuilder.hasInitiativeAct() && (await this.canTakeInitiative(input))) { return this.takeInitiative(input, resultBuilder); } } /** * Determine if the input is an implicit or explicit "set" with a value provided. * * Example utterance: "Set my age to six" * * @param input - Input */ private isSetWithValue(input: ControlInput): boolean { try { okIf(InputUtil.isValueControlIntent(input, AmazonBuiltInSlotType.NUMBER)); const { action, target, feedback, values } = unpackValueControlIntent( (input.request as IntentRequest).intent, ); const valueStr = values[0].slotValue; okIf(InputUtil.targetIsMatchOrUndefined(target, this.props.interactionModel.targets)); okIf(InputUtil.valueStrDefined(valueStr)); okIf(InputUtil.feedbackIsMatchOrUndefined(feedback, FEEDBACK_TYPES)); okIf(InputUtil.actionIsMatch(action, this.props.interactionModel.actions.set)); return true; } catch (e) { return falseIfGuardFailed(e); } } /** * Handle an implicit or explicit "set" with a value provided. * * @param input - Input * @param resultBuilder - ResultBuilder */ private async handleSetWithValue( input: ControlInput, resultBuilder: ControlResultBuilder, ): Promise<void> { const { valueStr } = InputUtil.getValueResolution(input); this.setValue(valueStr); if (this.isConfirmationRequired(input) === true) { this.addInitiativeAct( new ConfirmValueAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), resultBuilder, ); } else { await this.validateAndAddCommonFeedbackActs(input, resultBuilder, $.Action.Set); } return; } private isSetWithoutValue(input: ControlInput): boolean { try { okIf(InputUtil.isIntent(input, GeneralControlIntent.name)); const { feedback, action, target } = unpackGeneralControlIntent( (input.request as IntentRequest).intent, ); okIf(InputUtil.targetIsMatchOrUndefined(target, this.props.interactionModel.targets)); okIf(InputUtil.feedbackIsMatchOrUndefined(feedback, FEEDBACK_TYPES)); okIf(InputUtil.actionIsMatch(action, this.props.interactionModel.actions.set)); return true; } catch (e) { return falseIfGuardFailed(e); } } private handleSetWithoutValue(input: ControlInput, resultBuilder: ControlResultBuilder): void { this.askElicitationQuestion(input, resultBuilder, $.Action.Set); return; } private isChangeWithValue(input: ControlInput): boolean { try { okIf(InputUtil.isValueControlIntent(input, AmazonBuiltInSlotType.NUMBER)); const { feedback, action, target, values, valueType } = unpackValueControlIntent( (input.request as IntentRequest).intent, ); const valueStr = values[0].slotValue; okIf(InputUtil.targetIsMatchOrUndefined(target, this.props.interactionModel.targets)); okIf(InputUtil.valueStrDefined(valueStr)); okIf(InputUtil.feedbackIsMatchOrUndefined(feedback, FEEDBACK_TYPES)); okIf(InputUtil.actionIsMatch(action, this.props.interactionModel.actions.change)); return true; } catch (e) { return falseIfGuardFailed(e); } } private async handleChangeWithValue( input: ControlInput, resultBuilder: ControlResultBuilder, ): Promise<void> { const { valueStr } = InputUtil.getValueResolution(input); this.setValue(valueStr); if (this.isConfirmationRequired(input) === true) { this.addInitiativeAct( new ConfirmValueAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), resultBuilder, ); } else { await this.validateAndAddCommonFeedbackActs(input, resultBuilder, $.Action.Change); } return; } private isChangeWithoutValue(input: ControlInput): boolean { try { okIf(InputUtil.isIntent(input, GeneralControlIntent.name)); const { feedback, action, target } = unpackGeneralControlIntent( (input.request as IntentRequest).intent, ); okIf(InputUtil.targetIsMatchOrUndefined(target, this.props.interactionModel.targets)); okIf(InputUtil.feedbackIsMatchOrUndefined(feedback, FEEDBACK_TYPES)); okIf(InputUtil.actionIsMatch(action, this.props.interactionModel.actions.change)); return true; } catch (e) { return falseIfGuardFailed(e); } } private handleChangeWithoutValue(input: ControlInput, resultBuilder: ControlResultBuilder): void { this.askElicitationQuestion(input, resultBuilder, $.Action.Change); return; } private isBareValue(input: ControlInput): boolean { try { okIf(InputUtil.isValueControlIntent(input, AmazonBuiltInSlotType.NUMBER)); const { feedback, action, target, values } = unpackValueControlIntent( (input.request as IntentRequest).intent, ); const valueStr = values[0].slotValue; okIf(InputUtil.feedbackIsUndefined(feedback)); okIf(InputUtil.actionIsUndefined(action)); okIf(InputUtil.targetIsMatchOrUndefined(target, this.props.interactionModel.targets)); okIf(InputUtil.valueStrDefined(valueStr)); return true; } catch (e) { return falseIfGuardFailed(e); } } private async handleBareValue(input: ControlInput, resultBuilder: ControlResultBuilder): Promise<void> { const { valueStr } = InputUtil.getValueResolution(input); this.setValue(valueStr); if (this.isConfirmationRequired(input) === true) { this.addInitiativeAct( new ConfirmValueAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), resultBuilder, ); } else { await this.validateAndAddCommonFeedbackActs( input, resultBuilder, this.state.elicitationAction ?? $.Action.Set, ); } return; } private isConfirmationAffirmed(input: ControlInput): boolean { try { okIf(InputUtil.isBareYes(input)); okIf(this.state.lastInitiative.actName === ConfirmValueAct.name); return true; } catch (e) { return falseIfGuardFailed(e); } } private async handleConfirmationAffirmed( input: ControlInput, resultBuilder: ControlResultBuilder, ): Promise<void> { const validationResult: true | ValidationFailure = await evaluateValidationProp( this.props.validation, this.state, input, ); if (validationResult === true) { this.state.confirmed = true; this.state.lastInitiative.actName = undefined; resultBuilder.addAct( new ValueConfirmedAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), ); } else { resultBuilder.addAct( new InvalidValueAct<number>(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value!, input), reasonCode: validationResult.reasonCode, renderedReason: validationResult.renderedReason, }), ); this.askElicitationQuestion(input, resultBuilder, $.Action.Set); } } private isSuggestionAccepted(input: ControlInput): boolean { try { okIf(InputUtil.isBareYes(input)); okIf(this.state.lastInitiative.actName === SuggestValueAct.name); return true; } catch (e) { return falseIfGuardFailed(e); } } private async handleSuggestionAccepted( input: ControlInput, resultBuilder: ControlResultBuilder, ): Promise<void> { const validationResult: true | ValidationFailure = await evaluateValidationProp( this.props.validation, this.state, input, ); if (validationResult === true) { this.state.confirmed = true; this.state.lastInitiative.actName = undefined; resultBuilder.addAct( new ValueConfirmedAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), ); } else { resultBuilder.addAct( new InvalidValueAct<number>(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value!, input), reasonCode: validationResult.reasonCode, renderedReason: validationResult.renderedReason, }), ); this.askElicitationQuestion(input, resultBuilder, $.Action.Set); } } private isConfirmationDisaffirmed(input: ControlInput): boolean { try { okIf(InputUtil.isBareNo(input)); okIf( this.state.lastInitiative.actName === ConfirmValueAct.name || this.state.lastInitiative.actName === SuggestValueAct.name, ); return true; } catch (e) { return falseIfGuardFailed(e); } } private handleConfirmationDisaffirmed(input: ControlInput, resultBuilder: ControlResultBuilder): void { resultBuilder.addAct( new ValueDisconfirmedAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), ); const suggestValue = this.getSuggestionForMisunderstoodValue(this.state.value, input); if ( suggestValue !== undefined && suggestValue !== this.state.value && this.state.lastInitiative.actName !== SuggestValueAct.name ) { this.setValue(suggestValue); this.addInitiativeAct( new SuggestValueAct(this, { value: suggestValue, renderedValue: this.props.valueRenderer(suggestValue!, input), }), resultBuilder, ); } else { // Discard the stored input this.clear(); this.addInitiativeAct(new RequestValueAct(this), resultBuilder); } } private isAffirmWithValue(input: ControlInput): boolean { try { okIf(InputUtil.isValueControlIntent(input, AmazonBuiltInSlotType.NUMBER)); const { feedback, action, target, values } = unpackValueControlIntent( (input.request as IntentRequest).intent, ); const valueStr = values[0].slotValue; okIf(InputUtil.feedbackIsMatch(feedback, [$.Feedback.Affirm])); okIf(InputUtil.actionIsUndefined(action)); okIf(InputUtil.targetIsMatchOrUndefined(target, this.props.interactionModel.targets)); okIf(InputUtil.valueStrDefined(valueStr)); return true; } catch (e) { return falseIfGuardFailed(e); } } private handleAffirmWithValue(input: ControlInput, resultBuilder: ControlResultBuilder): void { const { valueStr } = InputUtil.getValueResolution(input); const suggestValue = Number.parseInt(valueStr, 10); if (suggestValue !== this.state.value) { this.setValue(suggestValue); this.addInitiativeAct( new ConfirmValueAct(this, { value: suggestValue, renderedValue: this.props.valueRenderer(suggestValue!, input), }), resultBuilder, ); } else { this.state.confirmed = true; this.state.lastInitiative.actName = undefined; resultBuilder.addAct( new ValueConfirmedAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), ); } } private isDisaffirmWithValue(input: ControlInput): boolean { try { okIf(InputUtil.isValueControlIntent(input, AmazonBuiltInSlotType.NUMBER)); const { feedback, action, target, values } = unpackValueControlIntent( (input.request as IntentRequest).intent, ); const valueStr = values[0].slotValue; okIf(InputUtil.feedbackIsMatch(feedback, [$.Feedback.Disaffirm])); okIf(InputUtil.actionIsUndefined(action)); okIf(InputUtil.targetIsMatchOrUndefined(target, this.props.interactionModel.targets)); okIf(InputUtil.valueStrDefined(valueStr)); return true; } catch (e) { return falseIfGuardFailed(e); } } private handleDisaffirmWithValue(input: ControlInput, resultBuilder: ControlResultBuilder): void { resultBuilder.addAct( new ValueDisconfirmedAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), ); const { valueStr } = InputUtil.getValueResolution(input); const suggestValue = Number.parseInt(valueStr, 10); if (suggestValue !== this.state.value) { this.setValue(suggestValue); this.addInitiativeAct( new ConfirmValueAct(this, { value: suggestValue, renderedValue: this.props.valueRenderer(suggestValue!, input), }), resultBuilder, ); } else { // Discard the stored input this.clear(); this.addInitiativeAct(new RequestValueAct(this), resultBuilder); } } private isClearValue(input: ControlInput): boolean { try { okIf(InputUtil.isIntent(input, GeneralControlIntent.name)); const { feedback, action, target } = unpackGeneralControlIntent( (input.request as IntentRequest).intent, ); okIf(InputUtil.feedbackIsMatchOrUndefined(feedback, FEEDBACK_TYPES)); okIf(InputUtil.actionIsMatch(action, this.props.interactionModel.actions.clear)); okIf(InputUtil.targetIsMatchOrUndefined(target, this.props.interactionModel.targets)); return true; } catch (e) { return falseIfGuardFailed(e); } } private handleClearValue(input: ControlInput, resultBuilder: ControlResultBuilder) { resultBuilder.addAct( new ValueClearedAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), ); this.clear(); return; } private isSelectChoiceByTouch(input: ControlInput): boolean { try { okIf(InputUtil.isAPLUserEventWithMatchingControlId(input, this.id)); const userEvent = input.request as interfaces.alexa.presentation.apl.UserEvent; okIf(userEvent.arguments !== undefined); okIf(userEvent.arguments.length === 2); const controlId = (input.request as interfaces.alexa.presentation.apl.UserEvent) .arguments![0] as string; okIf(controlId === this.id); return true; } catch (e) { return falseIfGuardFailed(e); } } private async handleSelectChoiceByTouch(input: ControlInput, resultBuilder: ControlResultBuilder) { const valueStr = (input.request as interfaces.alexa.presentation.apl.UserEvent) .arguments![1] as string; this.setValue(valueStr); this.state.confirmed = true; await this.validateAndAddCommonFeedbackActs(input, resultBuilder, $.Action.Set); return; } async validateAndAddCommonFeedbackActs( input: ControlInput, resultBuilder: ControlResultBuilder, elicitationAction: string, ): Promise<void> { const validationResult: true | ValidationFailure = await evaluateValidationProp( this.props.validation, this.state, input, ); if (validationResult === true) { if (elicitationAction === $.Action.Set) { resultBuilder.addAct( new ValueSetAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), ); } else if (elicitationAction === $.Action.Change) { resultBuilder.addAct( new ValueChangedAct(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value, input), }), ); } else { throw new Error('Invalid elicitation Action'); } } else { this.state.confirmed = false; resultBuilder.addAct( new InvalidValueAct<number>(this, { value: this.state.value, renderedValue: this.props.valueRenderer(this.state.value!, input), reasonCode: validationResult.reasonCode, renderedReason: validationResult.renderedReason, }), ); this.askElicitationQuestion(input, resultBuilder, elicitationAction); } } private askElicitationQuestion( input: ControlInput, resultBuilder: ControlResultBuilder, elicitationAction: string, ) { this.state.elicitationAction = elicitationAction; this.addInitiativeAct(new RequestValueAct(this), resultBuilder); } addInitiativeAct(initiativeAct: InitiativeAct, resultBuilder: ControlResultBuilder) { this.state.lastInitiative.actName = initiativeAct.constructor.name; resultBuilder.addAct(initiativeAct); } isConfirmationRequired(input: ControlInput): boolean { if (this.state.value === undefined) { return false; } if (this.state.confirmed === true) { return false; } const propValue = this.props.confirmationRequired; return typeof propValue === 'function' ? propValue.call(this, this.state, input) : propValue; } private confirmValue(input: ControlInput, resultBuilder: ControlResultBuilder): void { this.addInitiativeAct( new ConfirmValueAct(this, { value: this.state.value, renderedValue: this.state.value !== undefined ? this.props.valueRenderer(this.state.value, input) : '', }), resultBuilder, ); } standardInitiativeHandlers: ControlInitiativeHandler[] = [ { name: 'ElicitValue (built-in)', canTakeInitiative: this.wantsToElicitValue, takeInitiative: this.elicitValue, }, { name: 'RequestReplacementForInvalidValue (built-in)', canTakeInitiative: this.wantsToRequestReplacementForInvalidValue, takeInitiative: this.requestReplacementForInvalidValue, }, { name: 'ConfirmValue (built-in)', canTakeInitiative: this.wantsToConfirmValue, takeInitiative: this.confirmValue, }, ]; // tsDoc - see Control async canTakeInitiative(input: ControlInput): Promise<boolean> { const stdHandlers = this.standardInitiativeHandlers; const matches = []; for (const handler of stdHandlers) { if (await handler.canTakeInitiative.call(this, input)) { matches.push(handler); } } if (matches.length > 1) { this.log.error( `More than one handler matched. Initiative Handlers in a single control should be mutually exclusive. ` + `Defaulting to the first. Initiative handlers: ${JSON.stringify( matches.map((x) => x.name), )}`, ); } if (matches.length >= 1) { this.initiativeFunc = matches[0].takeInitiative.bind(this); return true; } else { return false; } } // tsDoc - see Control async takeInitiative(input: ControlInput, resultBuilder: ControlResultBuilder): Promise<void> { if (this.initiativeFunc === undefined) { const errorMsg = 'NumberControl: takeInitiative called but this.initiativeFunc is not set. canTakeInitiative() should be called first to set this.initiativeFunc.'; this.log.error(errorMsg); throw new Error(errorMsg); } await this.initiativeFunc(input, resultBuilder); return; } private wantsToElicitValue(input: ControlInput): boolean { if (this.state.value === undefined && this.evaluateBooleanProp(this.props.required, input)) { return true; } return false; } private elicitValue(input: ControlInput, resultBuilder: ControlResultBuilder): void { this.askElicitationQuestion(input, resultBuilder, $.Action.Set); } private async wantsToRequestReplacementForInvalidValue(input: ControlInput): Promise<boolean> { if ( this.state.value !== undefined && (await evaluateValidationProp(this.props.validation, this.state, input)) !== true ) { return true; } return false; } private async requestReplacementForInvalidValue( input: ControlInput, resultBuilder: ControlResultBuilder, ): Promise<void> { await this.validateAndAddCommonFeedbackActs(input, resultBuilder, $.Action.Change); } private wantsToConfirmValue(input: ControlInput): boolean { return this.isConfirmationRequired(input); } // tsDoc - see Control async renderAct(act: SystemAct, input: ControlInput, builder: ControlResponseBuilder) { const responseStyle = getDeterminateResponseStyle(this.props.responseStyleEvaluator, input); if (act instanceof RequestValueAct) { addFragmentsForResponseStyle({ responseStyle, voicePrompt: this.evaluatePromptProp(act, this.props.prompts.requestValue, input), voiceReprompt: this.evaluatePromptProp(act, this.props.reprompts.requestValue, input), builder, }); const slotElicitation = generateSlotElicitation(); builder.addElicitSlotDirective(slotElicitation.slotName, slotElicitation.intent); // Check APL mode to prevent addition of APL Directive. if (builder.aplMode === APLMode.DIRECT) { await this.addStandardAPL(input, builder); // re-render APL Screen } } else if (act instanceof ConfirmValueAct) { addFragmentsForResponseStyle({ responseStyle, voicePrompt: this.evaluatePromptProp(act, this.props.prompts.confirmValue, input), voiceReprompt: this.evaluatePromptProp(act, this.props.reprompts.confirmValue, input), builder, }); // Check APL mode to prevent addition of APL Directive. if (builder.aplMode === APLMode.DIRECT) { await this.addStandardAPL(input, builder); // re-render APL Screen } } else if (act instanceof ValueDisconfirmedAct) { addFragmentsForResponseStyle({ responseStyle, voicePrompt: this.evaluatePromptProp(act, this.props.prompts.valueDisconfirmed, input), voiceReprompt: this.evaluatePromptProp(act, this.props.reprompts.valueDisconfirmed, input), builder, }); } else if (act instanceof ValueSetAct) { addFragmentsForResponseStyle({ responseStyle, voicePrompt: this.evaluatePromptProp(act, this.props.prompts.valueSet, input), voiceReprompt: this.evaluatePromptProp(act, this.props.reprompts.valueSet, input), builder, }); } else if (act instanceof ValueChangedAct) { addFragmentsForResponseStyle({ responseStyle, voicePrompt: this.evaluatePromptProp(act, this.props.prompts.valueChanged, input), voiceReprompt: this.evaluatePromptProp(act, this.props.reprompts.valueChanged, input), builder, }); } else if (act instanceof ValueConfirmedAct) { addFragmentsForResponseStyle({ responseStyle, voicePrompt: this.evaluatePromptProp(act, this.props.prompts.valueConfirmed, input), voiceReprompt: this.evaluatePromptProp(act, this.props.reprompts.valueConfirmed, input), builder, }); } else if (act instanceof ValueClearedAct) { addFragmentsForResponseStyle({ responseStyle, voicePrompt: this.evaluatePromptProp(act, this.props.prompts.valueCleared, input), voiceReprompt: this.evaluatePromptProp(act, this.props.reprompts.valueCleared, input), builder, }); } else if (act instanceof InvalidValueAct) { addFragmentsForResponseStyle({ responseStyle, voicePrompt: this.evaluatePromptProp(act, this.props.prompts.invalidValue, input), voiceReprompt: this.evaluatePromptProp(act, this.props.reprompts.invalidValue, input), builder, }); } else if (act instanceof SuggestValueAct) { addFragmentsForResponseStyle({ responseStyle, voicePrompt: this.evaluatePromptProp(act, this.props.prompts.suggestValue, input), voiceReprompt: this.evaluatePromptProp(act, this.props.reprompts.suggestValue, input), builder, }); } else { this.throwUnhandledActError(act); } } private async addStandardAPL(input: ControlInput, builder: ControlResponseBuilder) { if ( this.evaluateBooleanProp(this.props.apl.enabled, input) === true && getSupportedInterfaces(input.handlerInput.requestEnvelope)['Alexa.Presentation.APL'] ) { const renderedAPL = await this.evaluateAPLPropNewStyle(this.props.apl.requestValue, input); builder.addAPLRenderDocumentDirective(this.id, renderedAPL.document, renderedAPL.dataSource); } } // tsDoc - see Control updateInteractionModel(generator: ControlInteractionModelGenerator, imData: ModelData) { generator.addControlIntent(new GeneralControlIntent(), imData); generator.addControlIntent(new ValueControlIntent(AmazonBuiltInSlotType.NUMBER), imData); generator.addYesAndNoIntents(); for (const [capability, actionSlotIds] of Object.entries(this.props.interactionModel.actions)) { generator.ensureSlotValueIDsAreDefined(this.id, 'action', actionSlotIds); } generator.ensureSlotValueIDsAreDefined(this.id, 'target', this.props.interactionModel.targets); } /** * Directly set the value. * * @param value - Value, either an integer or a string that can be parsed as a integer. */ setValue(value: string | number) { this.state.value = typeof value === 'string' ? Number.parseInt(value, 10) : value; } /** * Clear the state of this control. */ clear() { this.state = new NumberControlState(); this.state.lastInitiative = {}; } async renderAPLComponent( input: ControlInput, resultBuilder: ControlResponseBuilder, ): Promise<{ [key: string]: any }> { const aplRenderFunc = this.props.apl.renderComponent; const defaultProps: NumberControlAPLComponentProps = { validationFailedMessage: (value?: number) => i18next.t('NUMBER_CONTROL_DEFAULT_APL_INVALID_VALUE', { value }), valueRenderer: this.props.valueRenderer, }; return aplRenderFunc.call(this, this, defaultProps, input, resultBuilder); } private getSuggestionForMisunderstoodValue(value: number, input: ControlInput): number | undefined { return this.props.mostLikelyMisunderstanding(value, input); } private async evaluateAPLPropNewStyle( prop: AplDocumentPropNewStyle, input: ControlInput, ): Promise<AplContent> { return typeof prop === 'function' ? (prop as AplContentFunc).call(this, this, input) : prop; } async evaluateAPLValidationFailedMessage( prop: string | ((value?: number) => string), input: ControlInput, ): Promise<string> { if (this.state.value === undefined) { return ''; } const validationResult: true | ValidationFailure = await evaluateValidationProp( this.props.validation, this.state, input, ); if (validationResult !== true) { if (typeof prop === 'function') { return prop(this.state.value); } return prop; } return ''; } } /** * Creates an elicit-slot directive for the provided slotType. * * - The intent specified is a `AMAZON_NUMBER_ValueControlIntent` * - The slot specified is the `slotType` slot. * * @param slotType - Slot type */ function generateSlotElicitation(): { intent: Intent; slotName: string } { const intent: Intent = { name: ValueControlIntent.intentName(AmazonBuiltInSlotType.NUMBER), slots: { 'AMAZON.NUMBER': { name: 'AMAZON.NUMBER', value: '', confirmationStatus: 'NONE' }, feedback: { name: 'feedback', value: '', confirmationStatus: 'NONE' }, action: { name: 'action', value: '', confirmationStatus: 'NONE' }, target: { name: 'target', value: '', confirmationStatus: 'NONE' }, head: { name: 'head', value: '', confirmationStatus: 'NONE' }, tail: { name: 'tail', value: '', confirmationStatus: 'NONE' }, preposition: { name: 'preposition', value: '', confirmationStatus: 'NONE' }, __Conjunction: { name: '__Conjunction', value: '', confirmationStatus: 'NONE' }, }, confirmationStatus: 'NONE', }; return { intent, slotName: AmazonBuiltInSlotType.NUMBER, }; }
the_stack
import { ColorEntry, ColorReason } from "./ColorEntry"; import { injectable } from "../Utils/DI"; import { BaseColorProcessor, SchemeResponse } from "./BaseColorProcessor"; import { IApplicationSettings } from "../Settings/IApplicationSettings"; import { IBaseSettingsManager } from "../Settings/BaseSettingsManager"; import { IHighlightedBackgroundColorProcessor } from "./ForegroundColorProcessor"; import { Component, ComponentShift } from "./ComponentShift"; import { HslaColor } from "./HslaColor"; import { RgbaColor } from "./RgbaColor"; import { IDynamicSettingsManager } from "../Settings/DynamicSettingsManager"; export abstract class IBackgroundColorProcessor { abstract clear(): void; abstract changeColor(rgbaString: string | null, increaseContrast: boolean, tag: any, getParentBackground?: (tag: any) => ColorEntry, ignoreBlueFilter?: boolean): ColorEntry; abstract isDark(rgbaString: string | null): boolean; } export abstract class ISvgBackgroundColorProcessor extends IBackgroundColorProcessor { } export abstract class IDynamicBackgroundColorProcessor extends IBackgroundColorProcessor { } export abstract class ITextSelectionColorProcessor extends IBackgroundColorProcessor { } export abstract class IDynamicTextSelectionColorProcessor extends ITextSelectionColorProcessor { } /** BackgroundColorProcessor */ @injectable(IBackgroundColorProcessor) class BackgroundColorProcessor extends BaseColorProcessor implements IBackgroundColorProcessor { protected readonly _colors = new Map<string, ColorEntry>(); protected readonly _lights = new Map<number, number>(); protected readonly _lightAreas = new Map<number, number>(); protected readonly _lightCounts = new Map<number, number>(); /** BackgroundColorProcessor constructor */ constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager, protected readonly highlightedBackgroundColorProcessor: IHighlightedBackgroundColorProcessor) { super(app, settingsManager); this._component = Component.Background; } protected onSettingsChanged(response: SchemeResponse, newSettings: ComponentShift): void { super.onSettingsChanged(response, newSettings); this.clear(); } public clear(): void { this._colors.clear(); this._lights.clear(); this._lightAreas.clear(); this._lightCounts.clear(); } public isDark(rgbaString: string | null): boolean { if (!rgbaString || rgbaString === RgbaColor.Transparent || rgbaString === RgbaColor.White || rgbaString.startsWith("rgb(") && rgbaString.length === 18) { return false; } if (rgbaString === RgbaColor.Black) { return true; } const hsla = RgbaColor.toHslaColor(RgbaColor.parse(rgbaString)); return hsla.alpha > 0 && (hsla.lightness || 0.01) / hsla.alpha <= 0.4; } protected tryGetTagArea(tag: Element) { if (tag.mlArea === undefined) { tag.mlComputedStyle = tag.mlComputedStyle || tag.ownerDocument!.defaultView!.getComputedStyle(tag as Element, ""); if (tag.mlComputedStyle && tag.mlComputedStyle.width && tag.mlComputedStyle.width.endsWith("px") && tag.mlComputedStyle.height && tag.mlComputedStyle.height.endsWith("px")) { let width = parseInt(tag.mlComputedStyle.width), height = parseInt(tag.mlComputedStyle.height); if (!isNaN(width) && !isNaN(height)) { tag.mlArea = width * height; } } } return tag.mlArea; } protected getTagArea(tag: Element) { if (tag.mlArea === undefined) { if (this.tryGetTagArea(tag) === undefined) { tag.mlRect = tag.mlRect || tag.getBoundingClientRect(); tag.mlArea = tag.mlRect.width * tag.mlRect.height; } } return tag.mlArea!; } protected tryUpdateLightArea(tag: Element, lightness: number) { let lightCount = this._lightCounts.get(lightness) || 0; this._lightCounts.set(lightness, ++lightCount); if (lightCount < 10) { let area = this.tryGetTagArea(tag); if (area !== undefined) { let oldArea = this._lightAreas.get(lightness); if (oldArea && oldArea < area || !oldArea) { this._lightAreas.set(lightness, area); } } } } protected changeHslaColor(hsla: HslaColor, increaseContrast: boolean, tag: Element): void { const shift = this._colorShift; if (shift.replaceAllHues || hsla.saturation < 0.1 && shift.graySaturation !== 0) { hsla.hue = shift.grayHue; hsla.saturation = shift.graySaturation; } else { if (shift.hueGravity) { hsla.hue = this.shiftHue(hsla.hue, shift.grayHue, shift.hueGravity); } hsla.saturation = this.scaleValue(hsla.saturation, shift.saturationLimit); } let light = hsla.lightness; if (increaseContrast) { let oldLight = this._lights.get(hsla.lightness); if (oldLight !== undefined) { light = oldLight; this.tryUpdateLightArea(tag, hsla.lightness); } else { const minLightDiff = shift.contrast * Math.atan(-shift.lightnessLimit * Math.PI / 2) + shift.contrast / 0.9; let thisTagArea = this.getTagArea(tag); if (this._lights.size > 0 && minLightDiff > 0) { let prevLight = -1, nextLight = +2, prevOrigin = 0, nextOrigin = 1; for (let [originalLight, otherLight] of this._lights) { if (otherLight < light && otherLight > prevLight) { prevLight = otherLight; prevOrigin = originalLight; } if (otherLight > light && otherLight < nextLight) { nextLight = otherLight; nextOrigin = originalLight; } } let prevArea = this._lightAreas.get(prevOrigin), nextArea = this._lightAreas.get(nextOrigin); let deflect = 0; if (prevArea !== undefined && nextArea !== undefined && prevArea !== nextArea) { deflect = (nextLight - prevLight) * ( prevArea > nextArea ? 0.5 - nextArea / prevArea : prevArea / nextArea - 0.5 ); } if (nextLight - prevLight < minLightDiff * 2) light = (prevLight + nextLight) / 2 + deflect; else if (light - prevLight < minLightDiff) light = prevLight + minLightDiff; else if (nextLight - light < minLightDiff) light = nextLight - minLightDiff; light = Math.max(Math.min(light, 1), 0); } this._lights.set(hsla.lightness, light); this._lightAreas.set(hsla.lightness, thisTagArea); this._lightCounts.set(hsla.lightness, 1); } } hsla.lightness = this.scaleValue(light, shift.lightnessLimit); } public changeColor(rgbaString: string | null, increaseContrast: boolean, tag: Element, getParentBackground?: (tag: any) => ColorEntry, ignoreBlueFilter?: boolean): ColorEntry { rgbaString = !rgbaString || rgbaString === "none" ? RgbaColor.Transparent : rgbaString; let prevColor = increaseContrast ? this._colors.get(rgbaString) : null; if (prevColor) { if (prevColor.role === this._component) { this.tryUpdateLightArea(tag, prevColor.originalLight); } let newColor = Object.assign({}, prevColor); newColor.reason = ColorReason.Previous; newColor.originalColor = rgbaString; newColor.owner = this._app.isDebug ? tag : null; newColor.base = this._app.isDebug ? prevColor : null; return newColor; } else { let rgba = RgbaColor.parse(rgbaString); if (tag instanceof HTMLBodyElement && rgba.alpha === 0) { rgbaString = "body-trans"; if (window.top === window.self) { rgba = { red: 255, green: 255, blue: 255, alpha: 1 }; } else { return { role: this._component, color: null, light: this._colorShift.lightnessLimit, originalLight: 1, originalColor: rgbaString, alpha: 0, isUpToDate: true, reason: ColorReason.Transparent, owner: this._app.isDebug ? tag : null, } as ColorEntry; } } if (tag instanceof HTMLOptionElement || tag instanceof HTMLOptGroupElement) { // if parent element is transparent - options will be white by default if (tag.parentElement && tag.parentElement.mlBgColor && !tag.parentElement.mlBgColor.color) { rgbaString = "option-trans"; rgba = { red: 255, green: 255, blue: 255, alpha: 1 }; } } if (rgba.alpha === 0 && getParentBackground) { let parentBgColor = getParentBackground(tag); increaseContrast && this.tryUpdateLightArea(tag, parentBgColor.originalLight); let newColor = Object.assign({}, parentBgColor); newColor.color = null; newColor.reason = ColorReason.Parent; newColor.originalColor = rgbaString; newColor.owner = this._app.isDebug ? tag : null; newColor.base = this._app.isDebug ? parentBgColor : null; return newColor; } else { let hsla = RgbaColor.toHslaColor(rgba); if (this._component === Component.Background && increaseContrast && hsla.saturation > 0.39 && hsla.lightness < 0.86 && (this.getTagArea(tag) ? tag.mlArea! < 16000 : false)) { const result = this.highlightedBackgroundColorProcessor.changeColor( rgbaString, getParentBackground ? getParentBackground(tag).light : this._colorShift.lightnessLimit, tag); increaseContrast && this._colors.set(rgbaString!, result); return result; } else { const originalLight = hsla.lightness; this.changeHslaColor(hsla, increaseContrast, tag); const newRgbColor = ignoreBlueFilter ? HslaColor.toRgbaColor(hsla) : this.applyBlueFilter(HslaColor.toRgbaColor(hsla)); const result = { role: this._component, color: newRgbColor.toString(), light: hsla.lightness, originalLight: originalLight, originalColor: rgbaString, alpha: rgba.alpha, reason: ColorReason.Ok, isUpToDate: true, owner: this._app.isDebug ? tag : null }; increaseContrast && this._colors.set(rgbaString!, result); return result; } } } } } @injectable(ISvgBackgroundColorProcessor) class SvgBackgroundColorProcessor extends BackgroundColorProcessor implements ISvgBackgroundColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager, null as any); this._component = Component.SvgBackground; } } @injectable(ITextSelectionColorProcessor) class TextSelectionColorProcessor extends BackgroundColorProcessor implements ITextSelectionColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager, null as any); this._component = Component.TextSelection; } } @injectable(IDynamicBackgroundColorProcessor) class DynamicBackgroundColorProcessor extends BackgroundColorProcessor implements IDynamicBackgroundColorProcessor { constructor( app: IApplicationSettings, settingsManager: IDynamicSettingsManager) { super(app, settingsManager, null as any); this._component = Component.Background; } } @injectable(IDynamicTextSelectionColorProcessor) class DynamicTextSelectionColorProcessor extends TextSelectionColorProcessor implements IDynamicTextSelectionColorProcessor { constructor( app: IApplicationSettings, settingsManager: IDynamicSettingsManager) { super(app, settingsManager); this._component = Component.TextSelection; } }
the_stack
import { browser, element, by, protractor, $ } from 'protractor'; import { Jazz } from '../page-objects/jazzservices.po'; import { Timeouts, Browser } from 'selenium-webdriver'; import { SSL_OP_SSLEAY_080_CLIENT_DH_BUG, SSL_OP_TLS_BLOCK_PADDING_BUG } from 'constants'; import { Common } from '../common/commontest'; describe('Overview', () => { let jazzServices_po: Jazz; let commonUtils: Common; let found = 1; let flag = 1; const EC = protractor.ExpectedConditions; let winhandle; let servicename; beforeAll(() => { jazzServices_po = new Jazz(); commonUtils = new Common(); browser.driver.sleep(Common.miniWait); commonUtils.Login(); }); beforeEach(() => { if (flag == 0) { pending(); } if (found == 0) { pending(); } }); afterAll(() => { jazzServices_po = new Jazz(); commonUtils = new Common(); browser.driver.sleep(Common.miniWait); jazzServices_po.logoutIcon().click(); jazzServices_po.logout().click(); }); function createservice(servicename) { jazzServices_po.getServiceName().sendKeys(servicename); jazzServices_po.getNameSpace().sendKeys('jazztest'); jazzServices_po.getServiceDescription().sendKeys('Testing'); } function serviceapprover() { browser.driver.sleep(Common.miniWait); jazzServices_po.getSubmit().click(); commonUtils.fluentwaittry(jazzServices_po.getDone(), Common.shortWait); jazzServices_po.getDone().click(); } function waitforskiptest(ele, t) { browser.manage().timeouts().implicitlyWait(0); browser.wait(function () { browser.sleep(t); return ele.isDisplayed() .then( function (text) { flag = 1; return text; }, function (error) { browser.refresh(); flag = 0; return false; }); }, 300 * 1000); } it('Create Service for second account with east region', function () { browser.driver.sleep(Common.miniWait); browser.wait(EC.visibilityOf(jazzServices_po.getCreateService()), Common.timeOutHigh).then(null, function (err) { console.log(err); flag = 0; browser.refresh(); }); browser.wait(EC.elementToBeClickable(jazzServices_po.getCreateService()), Common.timeOutHigh); jazzServices_po.getCreateService().click(); browser.driver.switchTo().activeElement(); var min = 111111; var max = 999999; var randomNum = Math.floor(Math.random() * (max - min + 1)) + min; servicename = 'secondeast' + randomNum; // First Account with east Region createservice(servicename); jazzServices_po.accountSelect().click(); jazzServices_po.secountAccount().click().then(null, function (err) { console.log(err); flag = 0; });; jazzServices_po.regionSelect().click(); jazzServices_po.eastRegion().click(); serviceapprover(); browser.driver.sleep(Common.mediumWait); //Assert-Verifying the created service,Type and Status of the API expect(jazzServices_po.getService(servicename).getText()).toEqual(servicename); commonUtils.fluentwaittry(jazzServices_po.getAPIType(servicename), Common.shortWait); expect(jazzServices_po.getAPIType(servicename).getText()).toEqual('api'); expect(jazzServices_po.getAPIStatus(servicename).getText()).toEqual('creation started'); waitforskiptest(jazzServices_po.serviceStatus(servicename), Common.xxlWait); }); it('Verify Service and Navigation for second account with east region', () => { browser.driver.sleep(Common.microWait); commonUtils.fluentwaittry(jazzServices_po.getService(servicename), Common.miniWait); browser.wait(EC.elementToBeClickable(jazzServices_po.getService(servicename)), Common.timeOutHigh); //To Navigate to the particular service and verifying the Page jazzServices_po.getService(servicename).click(); commonUtils.waitForSpinnerDisappear(); expect(jazzServices_po.eastRegionVerify().getText()).toEqual('us-east-1'); waitforskiptest(jazzServices_po.getProdName(), Common.xxlWait); jazzServices_po.getProdName().click(); commonUtils.waitForSpinnerDisappear(); commonUtils.elementPresent(jazzServices_po.getDeploymentStatus(), Common.shortWait); //Verifying the browser id at the Deployment Tab expect(jazzServices_po.getDeploymentStatus().getText()).toEqual('DEPLOYMENTS'); browser.driver.switchTo().activeElement(); }); it('Verify METRICS Navigation for second account with east region', () => { browser.sleep(Common.microWait); jazzServices_po.getTestAPI().click().then(null, function (err) { console.log("the error occurred is : " + err.name); expect(jazzServices_po.getTestAPI().getText()).toEqual('Failed Test API'); browser.sleep(Common.miniWait); }); browser.getAllWindowHandles().then(function (handles) { browser.switchTo().window(handles[1]).then(function () { browser.driver.sleep(Common.shortWait); commonUtils.fluentwaittry(jazzServices_po.getAPIGET(), Common.mediumWait); jazzServices_po.getAPIGET().click().then(null, function (err) { console.log("Swagger Page is Failed to upload : " + err.name); }); browser.sleep(Common.microWait); jazzServices_po.getTryOut().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getStringA().sendKeys('Testing').then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getStringB().sendKeys('Jazz').then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getExecute().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getAPIGET().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getAPIPOST().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getTryOut().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getExecute().click().then(null, function (err) { console.log(err.name); if (jazzServices_po.SwaggerFailed()) { expect(jazzServices_po.SwaggerFailed().getText()).toEqual('Failed test'); } else if (jazzServices_po.getAPIGET()) { expect(jazzServices_po.getAPIGET().getText()).toEqual('GETT'); } else { browser.sleep(Common.longWait); browser.close(); } }); browser.sleep(Common.miniWait); browser.close(); }); browser.switchTo().window(handles[0]).then(function () { browser.sleep(Common.miniWait); commonUtils.elementPresent(jazzServices_po.getMetrices(), Common.miniWait); jazzServices_po.getMetrices().click(); commonUtils.waitForMetricsSpinner(); }); }); }); it('Verify Deployment for second account with east region', () => { commonUtils.verifyDelpoyment(); }); it('Verify Asset for second account with east region', () => { commonUtils.verifyAsset(); }); it('Verify Logs for second account with east region', () => { commonUtils.verifyLogs(); }); it('Verify METRICS COUNT for second account with east region', () => { browser.sleep(Common.miniWait); commonUtils.fluentwaittry(jazzServices_po.getMetrices(), Common.shortWait); jazzServices_po.getMetrices().click(); commonUtils.waitForMetricsSpinner(); browser.sleep(Common.shortWait); commonUtils.refreshbutton(jazzServices_po.getMetricesCount(), Common.mediumWait); expect(jazzServices_po.getMetricesCount().getText()).toEqual('1'); }); it('Identifying Environment and Navigation for second account with east region', () => { browser.driver.sleep(Common.microWait); commonUtils.fluentwaittry(jazzServices_po.getServiceHomePage(), Common.mediumWait); jazzServices_po.getServiceHomePage().click(); browser.driver.sleep(Common.microWait); commonUtils.fluentwaittry(jazzServices_po.getService(servicename), Common.miniWait); browser.wait(EC.elementToBeClickable(jazzServices_po.getService(servicename)), Common.timeOutHigh); //To Navigate to the particular service and verifying the Page jazzServices_po.getService(servicename).click(); expect(jazzServices_po.getRepo().getText()).toEqual('Repository'); browser.wait(EC.visibilityOf(jazzServices_po.getRepository()), Common.timeOutHigh); jazzServices_po.getRepository().click(); browser.sleep(Common.miniWait); }); it('Create the Test Branch for second account with east region', () => { browser.getAllWindowHandles().then(function (handles) { browser.sleep(Common.microWait); var min = 11; var max = 99; var randomNum = Math.floor(Math.random() * (max - min + 1)) + min; var test = 'TEST' + randomNum; browser.switchTo().window(handles[1]).then(function () { browser.sleep(Common.microWait); var some_name = browser.getTitle().then(function (webpagetitle) { if (webpagetitle === 'Sign in · GitLab') { expect(webpagetitle).toEqual('Sign in · GitLab'); jazzServices_po.gitUsername().sendKeys(Common.config.SCM_USERNAME).then(null, function (err) { console.log("Invalid Username"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.gitPassword().sendKeys(Common.config.SCM_PASSWORD).then(null, function (err) { console.log("Invalid Password"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.gitLogin().click().then(null, function (err) { console.log("Login Button is not visible"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.drpGitBranchType().click().then(null, function (err) { console.log("Branch drop not is not working"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.selectGitBranchType().click().then(null, function (err) { console.log("Feature type is not available"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.gitBranchName().sendKeys(test).then(null, function (err) { console.log("Branch name text box is not visible"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.btnGitCreateBranch().click().then(null, function (err) { console.log("Create branch button is not working"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.getGitLogoutIcon().click().then(null, function (err) { console.log("Unable to locate Logout Icon"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.getGitLogout().click().then(null, function (err) { console.log("Unable to locate Logout link"+err.name); flag = 0; browser.sleep(Common.longWait); browser.close(); }); browser.sleep(Common.microWait); browser.close(); } else { expect(webpagetitle).not.toEqual('Sign in · GitLab'); jazzServices_po.bitUsername().sendKeys(Common.config.SCM_USERNAME).then(null, function (err) { console.log("Invalid Username"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.bitPassword().sendKeys(Common.config.SCM_PASSWORD).then(null, function (err) { console.log("Invalid Password"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.bitLogin().click().then(null, function (err) { console.log("Unable to locate Login button"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.createBranch().click().then(null, function (err) { console.log("Unable to locate create branch button"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.drp_BranchType().click().then(null, function (err) { console.log("Unable to locate branch type dropdown"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.select_BranchType().click().then(null, function (err) { console.log("Unable to locate branch type"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.branchName().sendKeys(test).then(null, function (err) { console.log("Unable to locate create branch textbox"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.btn_CreateBranch().click().then(null, function (err) { console.log("Unable to locate submit button"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.getBitLogoutIcon().click().then(null, function (err) { console.log("Unable to locate bitbucket logout icon"+err.name); }); browser.sleep(Common.microWait); jazzServices_po.getBitLogout().click().then(null, function (err) { console.log("Unable to locate bitbucket logout button"+err.name); flag = 0; browser.sleep(Common.longWait); browser.close(); }); browser.sleep(Common.microWait); browser.close(); } }); }); browser.switchTo().window(handles[0]).then(function () { browser.sleep(Common.microWait); waitforskiptest(jazzServices_po.activeTestBranch(), Common.xxlWait); jazzServices_po.activeTestBranch().click(). then(null, function (err) { console.log("the error occurred is : " + err.name); }); commonUtils.waitForSpinnerDisappear(); browser.sleep(Common.miniWait); }); }); }); it('Verify METRICS Navigation Test Branch for second account with east region', () => { commonUtils.fluentwaittry(jazzServices_po.getTestAPI(), Common.mediumWait); expect(jazzServices_po.getTestAPI().getText()).toEqual('TEST API'); browser.wait(EC.elementToBeClickable(jazzServices_po.getTestAPI()), Common.timeOutHigh); jazzServices_po.getTestAPI().click(); browser.getAllWindowHandles().then(function (handles) { browser.switchTo().window(handles[1]).then(function () { browser.driver.sleep(Common.shortWait); commonUtils.fluentwaittry(jazzServices_po.getAPIGET(), Common.mediumWait); jazzServices_po.getAPIGET().click().then(null, function (err) { console.log("Swagger Page is Failed to upload : " + err.name); }); browser.sleep(Common.microWait); jazzServices_po.getTryOut().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getStringA().sendKeys('Testing').then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getStringB().sendKeys('Jazz').then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getExecute().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getAPIGET().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getAPIPOST().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getTryOut().click().then(null, function (err) { console.log(err.name); }); browser.sleep(Common.microWait); jazzServices_po.getExecute().click().then(null, function (err) { console.log(err.name); if (jazzServices_po.SwaggerFailed()) { expect(jazzServices_po.SwaggerFailed().getText()).toEqual('Failed test'); } else if (jazzServices_po.getAPIGET()) { expect(jazzServices_po.getAPIGET().getText()).toEqual('GETT'); } else { browser.sleep(Common.longWait); browser.close(); } }); browser.sleep(Common.miniWait); browser.close(); }); browser.switchTo().window(handles[0]).then(function () { browser.sleep(Common.miniWait); commonUtils.elementPresent(jazzServices_po.getMetrices(), Common.miniWait); jazzServices_po.getMetrices().click(); commonUtils.waitForMetricsSpinner(); }); }); }); it('Verify Deployments for Test Branch for second account with east region', () => { commonUtils.verifyDelpoyment(); }); it('Verify Asset for Test Branch for second account with east region', () => { commonUtils.verifyAsset(); }); it('Verify Logs for Test Branch for second account with east region', () => { commonUtils.verifyLogs(); }); it('Verify METRICS COUNT Test Branch for second account with east region', () => { browser.driver.sleep(Common.microWait); commonUtils.fluentwaittry(jazzServices_po.getMetrices(), Common.mediumWait); jazzServices_po.getMetrices().click(); commonUtils.waitForMetricsSpinner(); browser.sleep(Common.miniWait); commonUtils.refreshbutton(jazzServices_po.getMetricesCount(), Common.mediumWait); expect(jazzServices_po.getMetricesCount().getText()).toEqual('1'); browser.sleep(Common.microWait); }); });
the_stack
import * as Statements from "../2_statements/statements"; import * as Structures from "../3_structures/structures"; import {Issue} from "../../issue"; import {Token} from "../1_lexer/tokens/_token"; import {StatementNode, StructureNode} from "../nodes"; import {IRegistry} from "../../_iregistry"; import {ABAPObject} from "../../objects/_abap_object"; import {CurrentScope} from "./_current_scope"; import {ScopeType} from "./_scope_type"; import {ObjectOriented} from "./_object_oriented"; import {Procedural} from "./_procedural"; import {FunctionGroup, Program} from "../../objects"; import {Position} from "../../position"; import {Data as DataStructure} from "./structures/data"; import {TypeEnum} from "./structures/type_enum"; import {Types} from "./structures/types"; import {Statics} from "./structures/statics"; import {Constants} from "./structures/constants"; import {ClassDefinition} from "../types/class_definition"; import {InterfaceDefinition} from "../types/interface_definition"; import {ISyntaxResult} from "./_spaghetti_scope"; import {Perform} from "./statements/perform"; import {Type} from "./statements/type"; import {Constant} from "./statements/constant"; import {Static} from "./statements/static"; import {Data as DataStatement} from "./statements/data"; import {Parameter} from "./statements/parameter"; import {FieldSymbol} from "./statements/fieldsymbol"; import {Tables} from "./statements/tables"; import {SelectOption} from "./statements/selectoption"; import {InterfaceDeferred} from "./statements/interface_deferred"; import {ClassDeferred} from "./statements/class_deferred"; import {Call} from "./statements/call"; import {ClassImplementation} from "./statements/class_implementation"; import {MethodImplementation} from "./statements/method_implementation"; import {Move} from "./statements/move"; import {MoveCorresponding} from "./statements/move_corresponding"; import {Catch} from "./statements/catch"; import {Loop} from "./statements/loop"; import {ReadTable} from "./statements/read_table"; import {Select} from "./statements/select"; import {InsertInternal} from "./statements/insert_internal"; import {Split} from "./statements/split"; import {Assign} from "./statements/assign"; import {Convert} from "./statements/convert"; import {Describe} from "./statements/describe"; import {Find} from "./statements/find"; import {Message} from "./statements/message"; import {GetTime} from "./statements/get_time"; import {GetParameter} from "./statements/get_parameter"; import {WhenType} from "./statements/when_type"; import {If} from "./statements/if"; import {ElseIf} from "./statements/else_if"; import {Append} from "./statements/append"; import {SelectionScreen} from "./statements/selection_screen"; import {Ranges} from "./statements/ranges"; import {Write} from "./statements/write"; import {Case} from "./statements/case"; import {CreateObject} from "./statements/create_object"; import {Do} from "./statements/do"; import {Concatenate} from "./statements/concatenate"; import {CallFunction} from "./statements/call_function"; import {Clear} from "./statements/clear"; import {Replace} from "./statements/replace"; import {GetBit} from "./statements/get_bit"; import {Raise} from "./statements/raise"; import {DeleteInternal} from "./statements/delete_internal"; import {Receive} from "./statements/receive"; import {When} from "./statements/when"; import {CreateData} from "./statements/create_data"; import {CallTransformation} from "./statements/call_transformation"; import {GetLocale} from "./statements/get_locale"; import {SetLocale} from "./statements/set_locale"; import {Sort} from "./statements/sort"; import {ReadReport} from "./statements/read_report"; import {AuthorityCheck} from "./statements/authority_check"; import {InsertReport} from "./statements/insert_report"; import {GetReference} from "./statements/get_reference"; import {InsertDatabase} from "./statements/insert_database"; import {DeleteDatabase} from "./statements/delete_database"; import {ImportDynpro} from "./statements/import_dynpro"; import {SyntaxCheck} from "./statements/syntax_check"; import {Import} from "./statements/import"; import {Export} from "./statements/export"; import {Scan} from "./statements/scan"; import {Submit} from "./statements/submit"; import {OpenDataset} from "./statements/open_dataset"; import {CloseDataset} from "./statements/close_dataset"; import {GetRunTime} from "./statements/get_run_time"; import {UpdateDatabase} from "./statements/update_database"; import {Add} from "./statements/add"; import {Subtract} from "./statements/subtract"; import {AddCorresponding} from "./statements/add_corresponding"; import {SubtractCorresponding} from "./statements/subtract_corresponding"; import {Multiply} from "./statements/multiply"; import {Divide} from "./statements/divide"; import {Condense} from "./statements/condense"; import {Controls} from "./statements/controls"; import {While} from "./statements/while"; import {SelectLoop} from "./statements/select_loop"; import {Check} from "./statements/check"; import {LogPoint} from "./statements/log_point"; import {Severity} from "../../severity"; import {RaiseEvent} from "./statements/raise_event"; import {Form} from "./statements/form"; import {ABAPFile} from "../abap_file"; import {Assert} from "./statements/assert"; import {SetParameter} from "./statements/set_parameter"; import {ClassLocalFriends} from "./statements/class_local_friends"; import {GetBadi} from "./statements/get_badi"; import {With} from "./statements/with"; import {WithLoop} from "./statements/with_loop"; import {SystemCall} from "./statements/system_call"; import {Collect} from "./statements/collect"; import {Transfer} from "./statements/transfer"; import {ModifyDatabase} from "./statements/modify_database"; import {TruncateDataset} from "./statements/truncate_dataset"; import {CallBadi} from "./statements/call_badi"; import {Pack} from "./statements/pack"; import {Unpack} from "./statements/unpack"; import {Format} from "./statements/format"; import {SetPFStatus} from "./statements/set_pf_status"; import {SetTitlebar} from "./statements/set_titlebar"; import {StatementSyntax} from "./_statement_syntax"; import {CallTransaction} from "./statements/call_transaction"; import {SetHandler} from "./statements/set_handler"; import {Wait} from "./statements/wait"; import {DeleteReport} from "./statements/delete_report"; import {Shift} from "./statements/shift"; import {SetBit} from "./statements/set_bit"; import {ModifyScreen} from "./statements/modify_screen"; import {DeleteCluster} from "./statements/delete_cluster"; import {Unassign} from "./statements/unassign"; import {InsertTextpool} from "./statements/insert_textpool"; import {GetCursor} from "./statements/get_cursor"; // ----------------------------------- const map: {[name: string]: StatementSyntax} = {}; function addToMap(handler: StatementSyntax) { if (map[handler.constructor.name] !== undefined) { throw new Error("syntax.ts duplicate statement syntax handler"); } map[handler.constructor.name] = handler; } if (Object.keys(map).length === 0) { addToMap(new InterfaceDeferred()); addToMap(new Perform()); addToMap(new ClassDeferred()); addToMap(new Call()); addToMap(new SetHandler()); addToMap(new ClassImplementation()); addToMap(new MethodImplementation()); addToMap(new Move()); addToMap(new GetBadi()); addToMap(new CallBadi()); addToMap(new GetCursor()); addToMap(new Replace()); addToMap(new TruncateDataset()); addToMap(new Assert()); addToMap(new Catch()); addToMap(new Loop()); addToMap(new SetPFStatus()); addToMap(new SetTitlebar()); addToMap(new Submit()); addToMap(new InsertTextpool()); addToMap(new ReadTable()); addToMap(new SyntaxCheck()); addToMap(new DeleteReport()); addToMap(new Import()); addToMap(new Collect()); addToMap(new Export()); addToMap(new Scan()); addToMap(new Transfer()); addToMap(new Split()); addToMap(new CallFunction()); addToMap(new DeleteInternal()); addToMap(new DeleteCluster()); addToMap(new Clear()); addToMap(new Receive()); addToMap(new GetBit()); addToMap(new ClassLocalFriends()); addToMap(new Select()); addToMap(new ModifyScreen()); addToMap(new InsertInternal()); addToMap(new Pack()); addToMap(new Unpack()); addToMap(new Assign()); addToMap(new SetLocale()); addToMap(new SetParameter()); addToMap(new Convert()); addToMap(new Controls()); addToMap(new When()); addToMap(new InsertDatabase()); addToMap(new DeleteDatabase()); addToMap(new UpdateDatabase()); addToMap(new Sort()); addToMap(new Wait()); addToMap(new Condense()); addToMap(new SetBit()); addToMap(new OpenDataset()); addToMap(new CloseDataset()); addToMap(new ReadReport()); addToMap(new Do()); addToMap(new Describe()); addToMap(new Find()); addToMap(new Message()); addToMap(new SystemCall()); addToMap(new GetTime()); addToMap(new Unassign()); addToMap(new GetParameter()); addToMap(new Format()); addToMap(new WhenType()); addToMap(new If()); addToMap(new LogPoint()); addToMap(new While()); addToMap(new With()); addToMap(new WithLoop()); addToMap(new CallTransformation()); addToMap(new CallTransaction()); addToMap(new GetLocale()); addToMap(new GetReference()); addToMap(new ElseIf()); addToMap(new GetRunTime()); addToMap(new CreateObject()); addToMap(new ImportDynpro()); addToMap(new CreateData()); addToMap(new Case()); addToMap(new Shift()); addToMap(new Raise()); addToMap(new Concatenate()); addToMap(new Append()); addToMap(new SelectLoop()); addToMap(new Write()); addToMap(new MoveCorresponding()); addToMap(new AuthorityCheck()); addToMap(new InsertReport()); addToMap(new SelectionScreen()); addToMap(new Ranges()); addToMap(new Add()); addToMap(new RaiseEvent()); addToMap(new Subtract()); addToMap(new AddCorresponding()); addToMap(new SubtractCorresponding()); addToMap(new Multiply()); addToMap(new Divide()); addToMap(new Check()); addToMap(new ModifyDatabase()); addToMap(new Form()); addToMap(new SelectOption()); addToMap(new Tables()); addToMap(new Parameter()); addToMap(new FieldSymbol()); } // ----------------------------------- export class SyntaxLogic { private currentFile: ABAPFile; private issues: Issue[]; private readonly object: ABAPObject; private readonly reg: IRegistry; private readonly scope: CurrentScope; private readonly helpers: { oooc: ObjectOriented, proc: Procedural, }; public constructor(reg: IRegistry, object: ABAPObject) { this.reg = reg; this.issues = []; this.object = object; this.scope = CurrentScope.buildDefault(this.reg, object); this.helpers = { oooc: new ObjectOriented(this.scope), proc: new Procedural(this.reg, this.scope), }; } public run(): ISyntaxResult { if (this.object.syntaxResult !== undefined) { return this.object.syntaxResult; } this.issues = []; this.reg.getDDICReferences().clear(this.object); if (this.object instanceof Program && this.object.isInclude()) { // todo, show some kind of error? return {issues: [], spaghetti: this.scope.pop(new Position(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER))}; } this.traverseObject(); for (;;) { const spaghetti = this.scope.pop(new Position(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)); // pop built-in scopes if (spaghetti.getTop().getIdentifier().stype === ScopeType.BuiltIn) { const result: ISyntaxResult = {issues: this.issues, spaghetti}; this.object.syntaxResult = result; return result; } } } ///////////////////////////// private traverseObject(): CurrentScope { const traversal = this.object.getSequencedFiles(); if (this.object instanceof Program || this.object instanceof FunctionGroup) { for (const f of this.object.getSequencedFiles()) { // add FORM defintions to the _global object scope this.helpers.proc.addAllFormDefinitions(f, this.object); } const main = this.object.getMainABAPFile(); if (main !== undefined) { let stype = ScopeType.Program; if (this.object instanceof FunctionGroup) { stype = ScopeType.FunctionGroup; } this.scope.push(stype, this.object.getName(), new Position(1, 1), main.getFilename()); } } for (const file of traversal) { this.currentFile = file; const structure = this.currentFile.getStructure(); if (structure === undefined) { return this.scope; } else { this.traverse(structure); } } return this.scope; } private newIssue(token: Token, message: string): void { const issue = Issue.atToken(this.currentFile, token, message, "check_syntax", Severity.Error); this.issues.push(issue); } private traverse(node: StructureNode | StatementNode): void { for (const child of node.getChildren()) { const isStructure = child instanceof StructureNode; const isStatement = child instanceof StatementNode; try { if (isStructure) { const gotoNext = this.updateScopeStructure(child as StructureNode); if (gotoNext === true) { continue; } } else if (isStatement) { this.updateScopeStatement(child as StatementNode); } } catch (e) { this.newIssue(child.getFirstToken(), e.message); break; } // walk into INCLUDEs if (isStatement && child.get() instanceof Statements.Include) { const file = this.helpers.proc.findInclude(child as StatementNode, this.object); if (file !== undefined && file.getStructure() !== undefined) { const old = this.currentFile; this.currentFile = file; this.traverse(file.getStructure()!); this.currentFile = old; } } if (isStructure || isStatement) { this.traverse(child as StatementNode | StructureNode); } } } // if this returns true, then the traversal should continue with next child private updateScopeStructure(node: StructureNode): boolean { const filename = this.currentFile.getFilename(); const stru = node.get(); if (stru instanceof Structures.ClassDefinition) { new ClassDefinition(node, filename, this.scope); return true; } else if (stru instanceof Structures.Interface) { new InterfaceDefinition(node, filename, this.scope); return true; } else if (stru instanceof Structures.Types) { this.scope.addType(new Types().runSyntax(node, this.scope, filename)); return true; } else if (stru instanceof Structures.Constants) { this.scope.addIdentifier(new Constants().runSyntax(node, this.scope, filename).type); return true; } else if (stru instanceof Structures.Data) { this.scope.addIdentifier(new DataStructure().runSyntax(node, this.scope, filename)); return true; } else if (stru instanceof Structures.Statics) { this.scope.addIdentifier(new Statics().runSyntax(node, this.scope, filename)); return true; } else if (stru instanceof Structures.TypeEnum) { const values = new TypeEnum().runSyntax(node, this.scope, filename).values; this.scope.addList(values); return true; } return false; } private updateScopeStatement(node: StatementNode): void { const filename = this.currentFile.getFilename(); const s = node.get(); // todo, refactor if (s instanceof Statements.Type) { this.scope.addType(new Type().runSyntax(node, this.scope, filename)); return; } else if (s instanceof Statements.Constant) { this.scope.addIdentifier(new Constant().runSyntax(node, this.scope, filename)); return; } else if (s instanceof Statements.Static) { this.scope.addIdentifier(new Static().runSyntax(node, this.scope, filename)); return; } else if (s instanceof Statements.Data) { this.scope.addIdentifier(new DataStatement().runSyntax(node, this.scope, filename)); return; } const name = s.constructor.name; if (map[name]) { map[name].runSyntax(node, this.scope, filename); return; } if (s instanceof Statements.FunctionModule) { this.helpers.proc.findFunctionScope(this.object, node, filename); } else if (s instanceof Statements.EndForm || s instanceof Statements.EndFunction || s instanceof Statements.EndClass || s instanceof Statements.EndInterface) { this.scope.pop(node.getLastToken().getEnd()); } else if (s instanceof Statements.EndMethod) { this.scope.pop(node.getLastToken().getEnd()); if (this.scope.getType() === ScopeType.MethodInstance) { this.scope.pop(node.getLastToken().getEnd()); } } } }
the_stack
import * as stream from 'stream'; import * as http from 'http'; export { IncomingMessage } from 'http'; /** * REST request options * * @property {object.<string, string>} customHeaders - Any additional HTTP headers to be added to the request * @proprerty {boolean} [jar] - If true, remember cookies for future use */ export interface RequestOptions { customHeaders?: { [headerName: string]: string; }; } export interface ClientRequestOptions extends RequestOptions { jar?: boolean; } /** * HttpOperationResponse wrapper that provides the raw request, raw response and the deserialized response body. * * @property {WebResource} request - The raw request object * @property {http.IncomingMessage} response - The response from the http call * @property {T} body - The deserialized response body of the expected type. */ export interface HttpOperationResponse<T> { request: WebResource; response: http.IncomingMessage; body: T; } /** * Service client options, used for all REST requests initiated by the service client. * * @property {Array} [filters] - Filters to be added to the request pipeline * @property {ClientRequestOptions} requestOptions - Default ClientRequestOptions to use for requests * @property {boolean} noRetryPolicy - If set to true, turn off default retry policy */ export interface ServiceClientOptions { filters?: any[]; requestOptions?: ClientRequestOptions; noRetryPolicy?: boolean; } export class ServiceClient { /** * Initializes a new instance of the ServiceClient class. * * @param {ServiceClientCredentials} [credentials] - BasicAuthenticationCredentials or * TokenCredentials object used for authentication. * @param {ServiceClientOptions} [options] The parameter options */ constructor(credentials?: ServiceClientCredentials, options?: ServiceClientOptions); /** * Attempts to find package.json for the given azure nodejs package. * If found, returns the name and version of the package by reading the package.json * If package.json is not found, returns a default value. * @param {string} managementClientDir - pass the directory of the specific azure management client. * @returns {object} packageJsonInfo - "name" and "version" of the desired package. */ getPackageJsonInfo(managementClientDir: string): { name: string, version: string }; /** * Adds custom information to user agent header * @param {any} additionalUserAgentInfo - information to be added to user agent header, as string. */ addUserAgentInfo(additionalUserAgentInfo: any): void; sendRequest<TResult>(options: PathTemplateBasedRequestPrepareOptions | UrlBasedRequestPrepareOptions, callback: ServiceCallback<TResult>): void; sendRequest<TResult>(options: PathTemplateBasedRequestPrepareOptions | UrlBasedRequestPrepareOptions): Promise<TResult>; sendRequestWithHttpOperationResponse<TResult>(options: PathTemplateBasedRequestPrepareOptions | UrlBasedRequestPrepareOptions): Promise<HttpOperationResponse<TResult>>; } /** * Service Error that is returned when an error occurrs in executing the REST request initiated by the service client. * * @property {number} [statusCode] - The response status code received from the server as a result of making the request. * @property {WebResource} request - The raw/actual request sent to the server. * @property {http.IncomingMessage} response - The raw/actual response from the server. * @property {any} body - The response body. */ export interface ServiceError extends Error { statusCode: number; request: WebResource; response: http.IncomingMessage; body: any; } /** * Service callback that is returned for REST requests initiated by the service client. * * @property {Error|ServiceError} err - The error occurred if any, while executing the request; otherwise null * @property {TResult} result - The deserialized response body if an error did not occur. * @property {WebResource} request - The raw/actual request sent to the server if an error did not occur. * @property {http.IncomingMessage} response - The raw/actual response from the server if an error did not occur. */ export interface ServiceCallback<TResult> { (err: Error | ServiceError, result?: TResult, request?: WebResource, response?: http.IncomingMessage): void } /** * Creates a new 'ExponentialRetryPolicyFilter' instance. * * @constructor * @param {number} retryCount The client retry count. * @param {number} retryInterval The client retry interval, in milliseconds. * @param {number} minRetryInterval The minimum retry interval, in milliseconds. * @param {number} maxRetryInterval The maximum retry interval, in milliseconds. */ export class ExponentialRetryPolicyFilter { constructor(retryCount: number, retryInterval: number, minRetryInterval: number, maxRetryInterval: number); } export enum MapperType { Base64Url, Boolean, ByteArray, Composite, Date, DateTime, DateTimeRfc1123, Dictionary, Enum, Number, Object, Sequence, String, Stream, TimeSpan, UnixTime } export interface BaseMapperType { name: MapperType } export interface DictionaryType extends BaseMapperType { type: { name: MapperType; value: Mapper; } } export interface Mapper extends BaseMapperType { readOnly?: boolean; isConstant?: boolean; nullable?: boolean; required: boolean; serializedName: string; type: BaseMapperType; } export interface CompositeType extends Mapper { type: { name: MapperType; className: string; modelProperties?: { [propertyName: string]: Mapper }; } } export interface SequenceType extends Mapper { type: { name: MapperType; element: Mapper; } } export interface UrlParameterValue { value: any, skipUrlEncoding: boolean; } /** * Defines the options that can be specified for preparing the Request (WebResource) that is given to the request pipeline. * * @property {string} method The HTTP request method. Valid values are 'GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'POST', 'PATCH'. * * @property {string} [url] The request url. It may or may not have query parameters in it. * Either provide the 'url' or provide the 'pathTemplate' in the options object. Both the options are mutually exclusive. * * @property {object} [queryParameters] A dictionary of query parameters to be appended to the url, where * the 'key' is the 'query-parameter-name' and the 'value' is the 'query-parameter-value'. * The 'query-parameter-value' can be of type 'string' or it can be of type 'object'. * The 'object' format should be used when you want to skip url encoding. While using the object format, * the object must have a property named value which provides the 'query-parameter-value'. * Example: * - query-parameter-value in 'object' format: { 'query-parameter-name': { value: 'query-parameter-value', skipUrlEncoding: true } } * - query-parameter-value in 'string' format: { 'query-parameter-name': 'query-parameter-value'}. * Note: 'If url already has some query parameters, then the value provided in queryParameters will be appended to the url. * * @property {string} [pathTemplate] The path template of the request url. Either provide the 'url' or provide the 'pathTemplate' * in the options object. Both the options are mutually exclusive. * Example: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' * * @property {string} [baseUrl] The base url of the request. Default value is: 'https://management.azure.com'. This is applicable only with * pathTemplate. If you are providing url then it is expected that you provide the complete url. * * @property {object} [pathParameters] A dictionary of path parameters that need to be replaced with actual values in the pathTemplate. * Here the key is the 'path-parameter-name' and the value is the 'path-parameter-value'. * The 'path-parameter-value' can be of type 'string' or it can be of type 'object'. * The 'object' format should be used when you want to skip url encoding. While using the object format, * the object must have a property named value which provides the 'path-parameter-value'. * Example: * - path-parameter-value in 'object' format: { 'path-parameter-name': { value: 'path-parameter-value', skipUrlEncoding: true } } * - path-parameter-value in 'string' format: { 'path-parameter-name': 'path-parameter-value' }. * * @param {object} [options.formData] A dictionary of key-value pairs for the formData object. * If the expected 'Content-Type' to be set is 'application/x-www-form-urlencoded' then please set it in the options.headers object else the * 'Content-Type' header will be set to 'multipart/form-data'. * * @property {object} [headers] A dictionary of request headers that need to be applied to the request. * Here the key is the 'header-name' and the value is the 'header-value'. The header-value MUST be of type string. * - ContentType must be provided with the key name as 'Content-Type'. Default value 'application/json; charset=utf-8'. * - 'Transfer-Encoding' is set to 'chunked' by default if 'bodyIsStream' is set to true. * - 'Content-Type' is set to 'application/octet-stream' by default if 'bodyIsStream' is set to true. * - 'accept-language' by default is set to 'en-US' * - 'x-ms-client-request-id' by default is set to a new Guid. To not generate a guid for the request, please set disableClientRequestId to true * * @property {boolean} [disableClientRequestId] When set to true, instructs the client to not set 'x-ms-client-request-id' header to a new Guid(). * * @property {object|string|boolean|array|number|null|undefined} [body] - The request body. It can be of any type. This method will JSON.stringify() the request body. * * @property {object|string|boolean|array|number|null|undefined} [options.body] - The request body. It can be of any type. This method will JSON.stringify() the request body. * * @property {object} [options.serializationMapper] - Provides information on how to serialize the request body. * * @property {object} [options.deserializationMapper] - Provides information on how to deserialize the response body. * * @property {boolean} [disableJsonStringifyOnBody] - Indicates whether this method should JSON.stringify() the request body. Default value: false. * * @property {boolean} [bodyIsStream] - Indicates whether the request body is a stream (useful for file upload scenarios). */ export interface RequestPrepareOptions { method: string; queryParameters?: { [propertyName: string]: any | UrlParameterValue }; baseUrl?: string; pathParameters?: { [propertyName: string]: any | UrlParameterValue }; formData?: { [propertyName: string]: any }; headers?: { [propertyName: string]: any }; disableClientRequestId?: boolean; body?: any; disableJsonStringifyOnBody?: boolean; serializationMapper: Mapper; deserializationMapper: Mapper; bodyIsStream?: boolean; } export interface PathTemplateBasedRequestPrepareOptions extends RequestPrepareOptions { pathTemplate: string; } export interface UrlBasedRequestPrepareOptions extends RequestPrepareOptions { url: string; } export declare type HttpMethods = "GET" | "PUT" | "POST" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | "TRACE"; /** * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary * properties to initiate a request. */ export class WebResource { /** * Access to raw request headers for requests. Useful when you need to set a header * on every request (like in a credential object) where the prepare method does * far too much work. */ public headers: { [key: string]: string; }; /** * @property {string} url The request url */ public url: string; /** * @property {string} method The request method */ public method: HttpMethods; /** * @property {any} [body] The request body */ public body?: any; /** * @property {boolean} rawResponse Indicates whether the client should give back the response as-is. (Useful for streaming scenarios). */ public rawResponse?: boolean; /** * @property {any} [formData] Formdata parameters. */ public formData?: any; /** * @property {any} [query] Query parameters */ public query?: { [key: string]: any; }; /** * Hook up the given input stream to a destination output stream if the WebResource method * requires a request body and a body is not already set. * * @param {Stream} inputStream the stream to pipe from * @param {Stream} outputStream the stream to pipe to * * @return destStream */ pipeInput(inputStream: stream.Readable, destStream: stream.Writable): stream.Writable; /** * Validates that the required properties such as method, url, headers['Content-Type'], * headers['accept-language'] are defined. It will throw an error if one of the above * mentioned properties are not defined. */ validateRequestProperties(): void; /** * Prepares the request. * * @param {object} options The request options that should be provided to send a request successfully * * @param {string} options.method The HTTP request method. Valid values are 'GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'POST', 'PATCH'. * * @param {string} [options.url] The request url. It may or may not have query parameters in it. * Either provide the 'url' or provide the 'pathTemplate' in the options object. Both the options are mutually exclusive. * * @param {object} [options.queryParameters] A dictionary of query parameters to be appended to the url, where * the 'key' is the 'query-parameter-name' and the 'value' is the 'query-parameter-value'. * The 'query-parameter-value' can be of type 'string' or it can be of type 'object'. * The 'object' format should be used when you want to skip url encoding. While using the object format, * the object must have a property named value which provides the 'query-parameter-value'. * Example: * - query-parameter-value in 'object' format: { 'query-parameter-name': { value: 'query-parameter-value', skipUrlEncoding: true } } * - query-parameter-value in 'string' format: { 'query-parameter-name': 'query-parameter-value'}. * Note: 'If options.url already has some query parameters, then the value provided in options.queryParameters will be appended to the url. * * @param {string} [options.pathTemplate] The path template of the request url. Either provide the 'url' or provide the 'pathTemplate' * in the options object. Both the options are mutually exclusive. * Example: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' * * @param {string} [options.baseUrl] The base url of the request. Default value is: 'https://management.azure.com'. This is applicable only with * options.pathTemplate. If you are providing options.url then it is expected that you provide the complete url. * * @param {object} [options.pathParameters] A dictionary of path parameters that need to be replaced with actual values in the pathTemplate. * Here the key is the 'path-parameter-name' and the value is the 'path-parameter-value'. * The 'path-parameter-value' can be of type 'string' or it can be of type 'object'. * The 'object' format should be used when you want to skip url encoding. While using the object format, * the object must have a property named value which provides the 'path-parameter-value'. * Example: * - path-parameter-value in 'object' format: { 'path-parameter-name': { value: 'path-parameter-value', skipUrlEncoding: true } } * - path-parameter-value in 'string' format: { 'path-parameter-name': 'path-parameter-value' }. * * @param {object} [options.headers] A dictionary of request headers that need to be applied to the request. * Here the key is the 'header-name' and the value is the 'header-value'. The header-value MUST be of type string. * - ContentType must be provided with the key name as 'Content-Type'. Default value 'application/json; charset=utf-8'. * - 'Transfer-Encoding' is set to 'chunked' by default if 'options.bodyIsStream' is set to true. * - 'Content-Type' is set to 'application/octet-stream' by default if 'options.bodyIsStream' is set to true. * - 'accept-language' by default is set to 'en-US' * - 'x-ms-client-request-id' by default is set to a new Guid. To not generate a guid for the request, please set options.disableClientRequestId to true * * @param {boolean} [options.disableClientRequestId] When set to true, instructs the client to not set 'x-ms-client-request-id' header to a new Guid(). * * @param {object|string|boolean|array|number|null|undefined} [options.body] - The request body. It can be of any type. This method will JSON.stringify() the request body. * * @param {boolean} [options.disableJsonStringifyOnBody] - Indicates whether this method should JSON.stringify() the request body. Default value: false. * * @param {boolean} [options.bodyIsStream] - Indicates whether the request body is a stream (useful for file upload scenarios). * * @returns {object} WebResource Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. */ prepare(options?: PathTemplateBasedRequestPrepareOptions | UrlBasedRequestPrepareOptions): WebResource; } /** * Defines the ServiceClientCredentials. It is the base interface which enforces that the signRequest method needs to be implemented. * * @property {string} token The token. * @property {string} [authorizationScheme] The authorization scheme. If not specified, the default of 'Bearer" is used. */ export interface ServiceClientCredentials { /** * Signs a request with the Authentication header. * * @param {WebResource} The WebResource to be signed. * @param {function(error)} callback The callback function. */ signRequest(webResource: WebResource, callback: { (err: Error): void }): void; } /** * Defines the TokenCredentials. * * @property {string} token The token. * @property {string} [authorizationScheme] The authorization scheme. If not specified, the default of 'Bearer" is used. */ export class TokenCredentials implements ServiceClientCredentials { constructor(token: string, authorizationScheme?: string); signRequest(webResource: WebResource, callback: { (err: Error): void }): void; } /** * Defines the BasicAuthenticationCredentials. * * @property {string} userName User name. * @property {string} password Password. * @property {string} [authorizationScheme] The authorization scheme. Default ('Basic') */ export class BasicAuthenticationCredentials implements ServiceClientCredentials { constructor(userName: string, password: string, authorizationScheme?: string); signRequest(webResource: WebResource, callback: { (err: Error): void }): void; } /** * @interface ApiKeyCredentialOptions * Describes the options to be provided while creating an instance of ApiKeyCredentials */ export interface ApiKeyCredentialOptions { /** * @property {object} [inHeader] A key value pair of the header parameters that need to be applied to the request. */ inHeader?: { [x: string]: any }; /** * @property {object} [inQuery] A key value pair of the query parameters that need to be applied to the request. */ inQuery?: { [x: string]: any }; } /** * Creates a new ApiKeyCredentials instance. */ export class ApiKeyCredentials implements ServiceClientCredentials { /** * @constructor * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided. * @param {object} [inHeader] A key value pair of the header parameters that need to be applied to the request. * @param {object} [inQuery] A key value pair of the query parameters that need to be applied to the request. */ constructor(options?: ApiKeyCredentialOptions); signRequest(webResource: WebResource, callback: { (err: Error): void }): void; }
the_stack
import * as Clutter from 'clutter'; import { Actor } from 'clutter'; import * as Gio from 'gio'; import * as Meta from 'meta'; import { KeyBindingAction, KeyBindingFlags, KeyHandlerFunc, ModalOptions, Rectangle, WindowType, Workspace, } from 'meta'; import { ActionMode } from 'shell'; import { IntroducedInGnome, RemovedInGnome } from 'src/utils/shellVersionMatch'; import * as St from 'st'; import { Widget } from 'st'; import { GObject } from './mod'; declare module 'meta' { // Expose some additional "private" fields of the Workspace class interface Workspace { _lastRemovedWindow: Meta.Window; _keepAliveId: number | undefined; } } declare module 'ui' { export namespace messageTray { interface NotificationParams { gicon?: Gio.Icon; } class Notification { title: string; content: string; bannerBodyText: string; bannerBodyMarkup?: boolean; constructor( source: Source, title: string, text: string, params: NotificationParams ); activate(): void; } class Source { constructor(name: string); getIcon(): Gio.Icon; showNotification(notification: Notification): void; } class MessageTray extends Widget { add(source: any): void; } } export namespace Overview {} export namespace layout { const STARTUP_ANIMATION_TIME: number; export class Monitor { readonly index: number; readonly x: number; readonly y: number; readonly width: number; readonly height: number; readonly geometry_scale: any; } class MonitorConstraint extends Clutter.Constraint { constructor( props: Partial<{ primary: boolean; workArea: boolean; index: number; }> ); get primary(): boolean; set primary(v: boolean); get workArea(): boolean; set workArea(v: boolean); get index(): number; set index(v: number); } export class UiActor extends St.Widget {} export class LayoutManager extends GObject.Object { monitors: Monitor[]; /// The primary monitor. Can be null if there are no monitors. primaryMonitor: Monitor | null; get currentMonitor(): Monitor; get keyboardMonitor(): Monitor; // Note: can be -1 get focusIndex(): number; get focusMonitor(): Monitor | null; primaryIndex: number; hotCorners: any[]; _startingUp: boolean; overviewGroup: St.Widget; uiGroup: UiActor; removeChrome(actor: Actor): void; addChrome(actor: Actor): void; _findActor(actor: Actor): number; _trackActor( actor: Actor, params: { trackFullscreen?: boolean; affectsStruts?: boolean; affectsInputRegion?: boolean; } ): void; _untrackActor(actor: Actor): void; getWorkAreaForMonitor(monitorIndex: number): Rectangle; findMonitorForActor(actor: Actor): Monitor | null; showOverview(): void; } } export const main: { layoutManager: layout.LayoutManager; wm: windowManager.WindowManager; sessionMode: sessionMode.SessionMode; overview: overview.Overview; panel: panel.Panel; messageTray: messageTray.MessageTray; uiGroup: layout.UiActor; extensionManager: extensionSystem.ExtensionManager; pushModal( actor: Actor, options?: { timestamp?: number; options?: ModalOptions; actionMode?: ActionMode; } ): void; popModal(actor: Actor): void; _findModal(grab: any): number; loadTheme(): void; reloadThemeResource(): void; }; export namespace extensionSystem { class ExtensionManager { lookup( uuid: string ): { uuid: string; stateObj: extension.Extension } | undefined; disableExtension(uuid: string): boolean; } } export namespace extension { class Extension { enable(): void; disable(): void; } } export namespace panel { class Panel extends St.Widget { _leftBox: St.BoxLayout; _centerBox: St.BoxLayout; _rightBox: St.BoxLayout; menuManager: popupMenu.PopupMenuManager; statusArea: { // TODO: Make all optional? activities: any; // ActivitiesButton, aggregateMenu: any; // AggregateMenu, appMenu: any; // AppMenuButton, dateMenu: dateMenu.DateMenuButton; a11y: any; // imports.ui.status.accessibility.ATIndicator, keyboard: any; // imports.ui.status.keyboard.InputSourceIndicator, dwellClick: any; // imports.ui.status.dwellClick.DwellClickIndicator, screenRecording: any; // imports.ui.status.remoteAccess.ScreenRecordingIndicator, }; } } export namespace dateMenu { class DateMenuButton extends panelMenu.Button { _clockDisplay: St.Label; _indicator: MessagesIndicator; } class MessagesIndicator extends St.Icon {} } export namespace panelMenu { class ButtonBox extends St.Widget {} class Button extends ButtonBox {} } export namespace popupMenu { class PopupMenuManager { constructor(owner: any, params?: any); _menus: ( | (PopupMenu & IntroducedInGnome<'42.0'> & RemovedInGnome<'never'>) | ({ menu: PopupMenu } & IntroducedInGnome<'ancient'> & RemovedInGnome<'42.0'>) )[]; addMenu(menu: PopupMenu, position?: number): void; removeMenu(menu: PopupMenu): void; } interface PopupBaseMenuItemParams { reactive?: boolean; activate?: boolean; hover?: boolean; style_class?: string | null; can_focus?: boolean; } class PopupBaseMenuItem extends St.BoxLayout { _icon?: St.Icon; _parent: PopupMenuBase | null; toggle(): void; activate(event: Clutter.Event): void; } class PopupSeparatorMenuItem extends PopupBaseMenuItem { constructor(text?: string); } class PopupImageMenuItem extends PopupBaseMenuItem { label: St.Label; _icon: St.Icon; constructor( text: string, icon: Gio.Icon | string, params?: PopupBaseMenuItemParams ); } class PopupSubMenuMenuItem extends PopupBaseMenuItem { constructor(text: string, wantIcon?: boolean); menu: PopupSubMenu; } class PopupSwitchMenuItem extends PopupBaseMenuItem { _statusBin: St.Bin; get state(): boolean; constructor( text: string, active: boolean, params?: PopupBaseMenuItemParams ); } class PopupMenuBase { actor: St.Widget; sourceActor: Clutter.Actor; toggle(): void; destroy(): void; removeAll(): void; addMenuItem( menuItem: | PopupMenuSection | PopupSubMenuMenuItem | PopupSeparatorMenuItem | PopupBaseMenuItem, position?: number ): void; addAction( title: string, callback: (event: any) => void, icon?: Gio.IconPrototype ): PopupBaseMenuItem; _getMenuItems(): (PopupBaseMenuItem | PopupMenuSection)[]; get numMenuItems(): number; } class PopupMenuSection extends PopupMenuBase {} class PopupSubMenu extends PopupMenuBase {} class PopupMenu extends PopupMenuBase { constructor( sourceActor: Actor, arrowAlignment: number, arrowSide: St.Side ); menu: PopupMenu | undefined; _boxPointer: boxPointer.BoxPointer; } } export namespace boxPointer { class BoxPointer extends St.Widget { _calculateArrowSide(arrowSide: St.Side): St.Side; } } export namespace appDisplay { class BaseAppView extends St.Widget {} class AppDisplay extends BaseAppView { constructor(); } interface SearchProvider { isRemoteProvider: boolean; id: string; canLaunchSearch: boolean; searchInProgress?: boolean; display: search.SearchResult | null | undefined; getInitialResultSet( terms: string[], callback: (results: string[]) => void, _cancellable: Gio.Cancellable ): void; getSubsearchResultSet( previousResults: string[], terms: string[], callback: (results: string[]) => void, _cancellable: Gio.Cancellable ): void; activateResult(id: string, terms: string[]): void; getResultMetas( identifiers: string[], callback: ( metas: { id: string; name: string; createIcon: (size: number) => St.Icon; }[] ) => void ): void; } class AppIcon extends GObject.Object {} class AppSearchProvider implements SearchProvider { isRemoteProvider: false; id: string; canLaunchSearch: boolean; searchInProgress?: boolean; display: search.SearchResult | null | undefined; getInitialResultSet( terms: string[], callback: (results: string[]) => void, _cancellable: Gio.Cancellable ): void; getSubsearchResultSet( previousResults: string[], terms: string[], callback: (results: string[]) => void, _cancellable: Gio.Cancellable ): void; activateResult(id: string, terms: string[]): void; getResultMetas( identifiers: string[], callback: ( metas: { id: string; name: string; createIcon: (size: number) => St.Icon; }[] ) => void ): void; } } export namespace search { class SearchResult extends St.Button {} } export namespace remoteSearch { class RemoteSearchProvider implements appDisplay.SearchProvider { isRemoteProvider: true; id: string; canLaunchSearch: boolean; searchInProgress?: boolean; display: search.SearchResult | null | undefined; getInitialResultSet( terms: string[], callback: (results: string[]) => void, _cancellable: Gio.Cancellable ): void; getSubsearchResultSet( previousResults: string[], terms: string[], callback: (results: string[]) => void, _cancellable: Gio.Cancellable ): void; activateResult(id: string, terms: string[]): void; getResultMetas( identifiers: string[], callback: ( metas: { id: string; name: string; description: string; createIcon: (size: number) => St.Icon; }[] ) => void, cancellable?: Gio.Cancellable ): void; appInfo: Gio.DesktopAppInfo; } function loadRemoteSearchProviders( searchSettings: Gio.Settings, callback: (providers: remoteSearch.RemoteSearchProvider[]) => void ): void; } export namespace sessionMode { class SessionMode { pushMode(mode: string): void; popMode(mode: string): void; switchMode(mode: string): void; get currentMode(): string; } } export namespace overview { class OverviewActor extends St.BoxLayout { _delegate: any; } class ShellInfo { constructor(); } class Overview { _initCalled: boolean; _visible: boolean; _shellInfo: ShellInfo; _swipeTracker: swipeTracker.SwipeTracker; isDummy: boolean; _overview: OverviewActor; init(): void; toggle(): void; _relayout(): void; _gestureBegin(tracker: swipeTracker.SwipeTracker): void; _gestureUpdate( tracker: swipeTracker.SwipeTracker, progress: number ): void; _gestureEnd( tracker: swipeTracker.SwipeTracker, duration: number, endProgress: number ): void; get visible(): boolean; } } export namespace swipeTracker { class SwipeTracker extends GObject.Object { orientation: Clutter.Orientation; constructor( actor: Actor, orientation: Clutter.Orientation, allowedModes: ActionMode, params: { allowDrag: boolean; allowScroll: boolean } ); } } export namespace overviewControls { export enum ControlsState { HIDDEN = 0, WINDOW_PICKER = 1, APP_GRID = 2, } } export namespace windowManager { export const SHELL_KEYBINDINGS_SCHEMA: string; export class WindowManager { _workspaceTracker: WorkspaceTracker; _shouldAnimate(actor: Actor, types: WindowType[]): void; removeKeybinding(name: string): void; addKeybinding( name: string, settings: Gio.Settings, flags: KeyBindingFlags, modes: ActionMode, handler: KeyHandlerFunc ): number | KeyBindingAction.NONE; } export class WorkspaceTracker { _workspaces: Workspace[]; _checkWorkspacesId: number; _queueCheckWorkspaces(): void; _checkWorkspaces(): void; } } export namespace searchController { class SearchController extends St.Widget { constructor(searchEntry: St.Entry, showAppsButton: St.Button); prepareToEnterOverview(): void; get searchActive(): boolean; visible: boolean; } } export namespace dash { class Dash extends St.Widget { constructor(); showAppsButton: St.Button; } } }
the_stack
import './MatchMediaMock'; import { ControlElement, DispatchCellProps, JsonSchema } from '@jsonforms/core'; import * as React from 'react'; import MaterialArrayControlRenderer from '../../src/complex/MaterialArrayControlRenderer'; import { materialCells, materialRenderers } from '../../src'; import Enzyme, { mount, ReactWrapper } from 'enzyme'; import Adapter from '@wojtekmaj/enzyme-adapter-react-17'; import { JsonFormsStateProvider, StatelessRenderer } from '@jsonforms/react'; import { initCore, TestEmitter } from './util'; Enzyme.configure({ adapter: new Adapter() }); const fixture: { data: any; schema: JsonSchema; uischema: ControlElement; } = { data: [ { message: 'El Barto was here', done: true }, { message: 'Yolo' } ], schema: { type: 'array', items: { type: 'object', properties: { message: { type: 'string', maxLength: 3 }, done: { type: 'boolean' } } } }, uischema: { type: 'Control', scope: '#' } }; const fixture2: { data: any; schema: JsonSchema; uischema: ControlElement; } = { data: { test: ['foo', 'baz', 'bar'] }, schema: { type: 'object', properties: { test: { type: 'array', items: { type: 'string' } } } }, uischema: { type: 'Control', scope: '#/properties/test', options: { showSortButtons: true } } }; describe('Material array control', () => { let wrapper: ReactWrapper; afterEach(() => wrapper.unmount()); it('should render', () => { const core = initCore(fixture.schema, fixture.uischema, fixture.data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={fixture.schema} uischema={fixture.uischema} /> </JsonFormsStateProvider> ); const rows = wrapper.find('tr'); // 2 header rows + 2 data entries expect(rows.length).toBe(4); }); it('should render empty', () => { const core = initCore(fixture.schema, fixture.uischema); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={fixture.schema} uischema={fixture.uischema} /> </JsonFormsStateProvider> ); const rows = wrapper.find('tr'); // two header rows + no data row expect(rows.length).toBe(3); const headerColumns = rows.at(1).children(); // 3 columns: message & done properties + column for delete button expect(headerColumns).toHaveLength(3); }); it('should render even without properties', () => { // re-init const data: any = { test: [] }; const schema: JsonSchema = { type: 'object', properties: { test: { type: 'array', items: { type: 'object' } } } }; const uischema: ControlElement = { type: 'Control', scope: '#/properties/test' }; const core = initCore(schema, uischema, data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={schema} uischema={uischema} /> </JsonFormsStateProvider> ); const rows = wrapper.find('tr'); // two header rows + no data row expect(rows.length).toBe(3); const headerColumns = rows.at(1).children(); // 2 columns: content + buttons expect(headerColumns).toHaveLength(2); }); it('should use title as a header if it exists', () => { // re-init const data: any = { test: [] }; const schema: JsonSchema = { type: 'object', properties: { test: { type: 'array', items: { type: 'object', properties: { test1: { type: 'string', title: 'first test' }, test_2: { type: 'string', } } } } } }; const uischema: ControlElement = { type: 'Control', scope: '#/properties/test' }; const core = initCore(schema, uischema, data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={schema} uischema={uischema} /> </JsonFormsStateProvider> ); // column headings are in the second row of the table, wrapped in <th> const headers = wrapper.find('tr').at(1).find('th'); // the first property has a title, so we expect it to be rendered as the first column heading expect(headers.at(0).text()).toEqual('first test'); // the second property has no title, so we expect to see the property name in start case expect(headers.at(1).text()).toEqual('Test 2'); }); it('should render empty primitives', () => { // re-init const data: any = { test: [] }; const schema: JsonSchema = { type: 'object', properties: { test: { type: 'array', items: { type: 'string' } } } }; const uischema: ControlElement = { type: 'Control', scope: '#/properties/test' }; const core = initCore(schema, uischema, data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={schema} uischema={uischema} /> </JsonFormsStateProvider> ); const rows = wrapper.find('tr'); // header + no data row expect(rows).toHaveLength(2); const emptyDataCol = rows.at(1).find('td'); expect(emptyDataCol).toHaveLength(1); // selection column + 1 data column expect(emptyDataCol.first().props().colSpan).toBe(2); }); it('should render primitives', () => { // re-init const data = { test: ['foo', 'bar'] }; const schema = { type: 'object', properties: { test: { type: 'array', items: { type: 'string' } } } }; const uischema: ControlElement = { type: 'Control', scope: '#/properties/test' }; const core = initCore(schema, uischema, data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={schema} uischema={uischema} /> </JsonFormsStateProvider> ); const rows = wrapper.find('tr'); // header + 2 data entries expect(rows).toHaveLength(3); }); it('should delete an item', () => { const core = initCore(fixture.schema, fixture.uischema, fixture.data); const onChangeData: any = { data: undefined }; wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, cells: materialCells, core }}> <TestEmitter onChange={({ data }) => { onChangeData.data = data; }} /> <MaterialArrayControlRenderer schema={fixture.schema} uischema={fixture.uischema} /> </JsonFormsStateProvider> ); const buttons = wrapper.find('button'); // 7 buttons // add row // clear string // delete row // clear string // delete row // two dialog buttons (no + yes) const nrOfRowsBeforeDelete = wrapper.find('tr').length; const deleteButton = buttons.at(2); deleteButton.simulate('click'); const confirmButton = buttons.at(6); confirmButton.simulate('click'); const nrOfRowsAfterDelete = wrapper.find('tr').length; expect(nrOfRowsBeforeDelete).toBe(4); expect(nrOfRowsAfterDelete).toBe(3); expect(onChangeData.data.length).toBe(1); }); const CellRenderer1: StatelessRenderer<DispatchCellProps> = () => ( <div className='cell test 1' /> ); const CellRenderer2: StatelessRenderer<DispatchCellProps> = () => ( <div className='cell test 2' /> ); it('should use cells from store', () => { const core = initCore(fixture.schema, fixture.uischema, fixture.data); const cells = [ { tester: () => 50, cell: CellRenderer1 }, { tester: () => 51, cell: CellRenderer2 } ]; wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={fixture.schema} uischema={fixture.uischema} cells={cells} /> </JsonFormsStateProvider> ); const rows = wrapper.find({ className: 'cell test 2' }); // 2 header rows + 2 data entries expect(rows.length).toBe(4); }); it('should use cells from own props', () => { const core = initCore(fixture.schema, fixture.uischema, fixture.data); const cell = { tester: () => 50, cell: CellRenderer1 }; wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={fixture.schema} uischema={fixture.uischema} cells={[ cell, { tester: () => 60, cell: CellRenderer2 }]} /> </JsonFormsStateProvider> ); const rows = wrapper.find({ className: 'cell test 2' }); // 2 header rows + 2 data entries expect(rows.length).toBe(4); }); it('should support adding rows that contain enums', () => { const schema = { type: 'object', properties: { things: { type: 'array', items: { type: 'object', properties: { somethingElse: { type: 'string' }, thing: { type: 'string', enum: ['thing'] } } } } } }; const uischema: ControlElement = { type: 'Control', scope: '#/properties/things' }; const core = initCore(schema, uischema, {}); const onChangeData: any = { data: undefined }; wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <TestEmitter onChange={({ data }) => { onChangeData.data = data; }} /> <MaterialArrayControlRenderer schema={schema} uischema={uischema} /> </JsonFormsStateProvider> ); const buttons = wrapper.find('button'); // 3 buttons // add row // two dialog buttons (no + yes) const nrOfRowsBeforeAdd = wrapper.find('tr').length; const addButton = buttons.at(0); addButton.simulate('click'); addButton.simulate('click'); wrapper.update(); const nrOfRowsAfterAdd = wrapper.find('tr').length; // 2 header rows + 'no data' row expect(nrOfRowsBeforeAdd).toBe(3); expect(nrOfRowsAfterAdd).toBe(4); expect(onChangeData.data).toEqual({ things: [{}, {}] }); }); it('should be hideable', () => { const schema = { type: 'object', properties: { things: { type: 'array', items: { type: 'object', properties: { somethingElse: { type: 'string' }, thing: { type: 'string', enum: ['thing'] } } } } } }; const uischema: ControlElement = { type: 'Control', scope: '#/properties/things' }; const core = initCore(schema, uischema, {}); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={schema} uischema={uischema} visible={false} /> </JsonFormsStateProvider> ); const nrOfButtons = wrapper.find('button').length; expect(nrOfButtons).toBe(0); const nrOfRows = wrapper.find('tr').length; expect(nrOfRows).toBe(0); }); it('should render sort buttons if showSortButtons is true', () => { const data = { test: ['foo'] }; const core = initCore(fixture2.schema, fixture2.uischema, data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={fixture2.schema} uischema={fixture2.uischema} /> </JsonFormsStateProvider> ); // up button expect( wrapper.find('button').find({ 'aria-label': 'Move up' }).length ).toBe(1); // down button expect( wrapper.find('button').find({ 'aria-label': 'Move down' }).length ).toBe(1); }); it('should be able to move item down if down button is clicked', () => { const core = initCore(fixture2.schema, fixture2.uischema, fixture2.data); const onChangeData: any = { data: undefined }; wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <TestEmitter onChange={({ data }) => { onChangeData.data = data; }} /> <MaterialArrayControlRenderer schema={fixture2.schema} uischema={fixture2.uischema} /> </JsonFormsStateProvider> ); // first row is header in table const downButton = wrapper .find('tr') .at(1) .find('button') .find({ 'aria-label': 'Move down' }); downButton.simulate('click'); expect(onChangeData.data).toEqual({ test: ['baz', 'foo', 'bar'] }); }); it('should be able to move item up if up button is clicked', () => { const core = initCore(fixture2.schema, fixture2.uischema, fixture2.data); const onChangeData: any = { data: undefined }; wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <TestEmitter onChange={({ data }) => { onChangeData.data = data; }} /> <MaterialArrayControlRenderer schema={fixture2.schema} uischema={fixture2.uischema} /> </JsonFormsStateProvider> ); // first row is header in table const upButton = wrapper .find('tr') .at(3) .find('button') .find({ 'aria-label': 'Move up' }); upButton.simulate('click'); expect(onChangeData.data).toEqual({ test: ['foo', 'bar', 'baz'] }); }); it('should have up button disabled for first element', () => { const core = initCore(fixture2.schema, fixture2.uischema, fixture2.data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={fixture2.schema} uischema={fixture2.uischema} /> </JsonFormsStateProvider> ); // first row is header in table const upButton = wrapper .find('tr') .at(1) .find('button') .find({ 'aria-label': 'Move up' }); expect(upButton.is('[disabled]')).toBe(true); }); it('should have fields enabled', () => { const core = initCore(fixture2.schema, fixture2.uischema, fixture2.data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, cells: materialCells, core }}> <MaterialArrayControlRenderer schema={fixture2.schema} uischema={fixture2.uischema} enabled={true} /> </JsonFormsStateProvider> ); // first row is header in table const input = wrapper .find('tr') .at(1) .find('input') .first(); expect(input.props().disabled).toBe(false); }); it('should have fields disabled', () => { const core = initCore(fixture2.schema, fixture2.uischema, fixture2.data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, cells: materialCells, core }}> <MaterialArrayControlRenderer schema={fixture2.schema} uischema={fixture2.uischema} enabled={false} /> </JsonFormsStateProvider> ); // first row is header in table const input = wrapper .find('tr') .at(1) .find('input') .first(); expect(input.props().disabled).toBe(true); }); it('should have down button disabled for last element', () => { const core = initCore(fixture2.schema, fixture2.uischema, fixture2.data); wrapper = mount( <JsonFormsStateProvider initState={{ renderers: materialRenderers, core }}> <MaterialArrayControlRenderer schema={fixture2.schema} uischema={fixture2.uischema} /> </JsonFormsStateProvider> ); // first row is header in table // first buttton is up arrow, second button is down arrow const downButton = wrapper .find('tr') .at(3) .find('button') .find({ 'aria-label': 'Move down' }); expect(downButton.is('[disabled]')).toBe(true); }); });
the_stack
import { assert } from "chai"; import { debug } from "../debug"; import { CCounter, LWWCVariable, OptionalLWWCVariable, CRDTApp, TestingCRDTAppGenerator, ResettableCCounter, } from "../../src"; import { Pre, Optional } from "@collabs/core"; import seedrandom = require("seedrandom"); import { AddComponent, CNumberState, MultComponent, } from "../../src/number/number"; describe("basic_crdts", () => { let appGen: TestingCRDTAppGenerator; let alice: CRDTApp; let bob: CRDTApp; let rng: seedrandom.prng; beforeEach(() => { rng = seedrandom("42"); appGen = new TestingCRDTAppGenerator(); alice = appGen.newApp(undefined, rng); bob = appGen.newApp(undefined, rng); }); describe("AddComponent", () => { let aliceCounter: AddComponent; let bobCounter: AddComponent; beforeEach(() => { aliceCounter = alice.registerCollab( "counterId", Pre(AddComponent)(new CNumberState(0)) ); bobCounter = bob.registerCollab( "counterId", Pre(AddComponent)(new CNumberState(0)) ); alice.load(Optional.empty()); bob.load(Optional.empty()); if (debug) { addEventListeners(aliceCounter, "Alice"); addEventListeners(bobCounter, "Bob"); } }); function addEventListeners(counter: AddComponent, name: string): void { counter.on("Add", (event) => console.log(`${name}: ${event.meta.sender} added ${event.arg}`) ); } it("is initially 0", () => { assert.strictEqual(aliceCounter.state.value, 0); assert.strictEqual(bobCounter.state.value, 0); }); describe("add", () => { it("works for non-concurrent updates", () => { aliceCounter.add(3); appGen.releaseAll(); assert.strictEqual(aliceCounter.state.value, 3); assert.strictEqual(bobCounter.state.value, 3); bobCounter.add(-4); appGen.releaseAll(); assert.strictEqual(aliceCounter.state.value, -1); assert.strictEqual(bobCounter.state.value, -1); aliceCounter.add(12); appGen.releaseAll(); assert.strictEqual(aliceCounter.state.value, 11); assert.strictEqual(bobCounter.state.value, 11); }); it("works for concurrent updates", () => { aliceCounter.add(2); assert.strictEqual(aliceCounter.state.value, 2); assert.strictEqual(bobCounter.state.value, 0); bobCounter.add(-5); assert.strictEqual(aliceCounter.state.value, 2); assert.strictEqual(bobCounter.state.value, -5); appGen.releaseAll(); assert.strictEqual(aliceCounter.state.value, -3); assert.strictEqual(bobCounter.state.value, -3); }); }); }); describe("CCounter", () => { let aliceCounter: CCounter; let bobCounter: CCounter; beforeEach(() => { aliceCounter = alice.registerCollab("counterId", Pre(CCounter)()); bobCounter = bob.registerCollab("counterId", Pre(CCounter)()); alice.load(Optional.empty()); bob.load(Optional.empty()); if (debug) { addEventListeners(aliceCounter, "Alice"); addEventListeners(bobCounter, "Bob"); } }); function addEventListeners(counter: CCounter, name: string): void { counter.on("Add", (event) => console.log(`${name}: ${event.meta.sender} added ${event.added}`) ); } it("is initially 0", () => { assert.strictEqual(aliceCounter.value, 0); assert.strictEqual(bobCounter.value, 0); }); describe("add", () => { it("works for non-concurrent updates", () => { aliceCounter.add(3); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 3); assert.strictEqual(bobCounter.value, 3); bobCounter.add(-4); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, -1); assert.strictEqual(bobCounter.value, -1); aliceCounter.add(-3); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, -4); assert.strictEqual(bobCounter.value, -4); bobCounter.add(4); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 0); assert.strictEqual(bobCounter.value, 0); }); it("works for concurrent updates", () => { aliceCounter.add(2); aliceCounter.add(-7); assert.strictEqual(aliceCounter.value, -5); assert.strictEqual(bobCounter.value, 0); bobCounter.add(-5); bobCounter.add(4); assert.strictEqual(aliceCounter.value, -5); assert.strictEqual(bobCounter.value, -1); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, -6); assert.strictEqual(bobCounter.value, -6); }); }); }); describe("ResettableCCounter", () => { let aliceCounter: ResettableCCounter; let bobCounter: ResettableCCounter; beforeEach(() => { aliceCounter = alice.registerCollab( "resettableCounterId", Pre(ResettableCCounter)() ); bobCounter = bob.registerCollab( "resettableCounterId", Pre(ResettableCCounter)() ); alice.load(Optional.empty()); bob.load(Optional.empty()); if (debug) { addEventListeners(aliceCounter, "Alice"); addEventListeners(bobCounter, "Bob"); } }); function addEventListeners( counter: ResettableCCounter, name: string ): void { counter.on("Add", (event) => console.log(`${name}: ${event.meta.sender} added ${event.arg}`) ); counter.on("Reset", (event) => console.log(`${name}: ${event.meta.sender} reset`) ); } it("is initially 0", () => { assert.strictEqual(aliceCounter.value, 0); assert.strictEqual(bobCounter.value, 0); }); describe("add", () => { it("works for non-concurrent updates", () => { aliceCounter.add(3); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 3); assert.strictEqual(bobCounter.value, 3); bobCounter.add(-4); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, -1); assert.strictEqual(bobCounter.value, -1); aliceCounter.add(-3); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, -4); assert.strictEqual(bobCounter.value, -4); bobCounter.add(4); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 0); assert.strictEqual(bobCounter.value, 0); }); it("works for concurrent updates", () => { aliceCounter.add(2); aliceCounter.add(-7); assert.strictEqual(aliceCounter.value, -5); assert.strictEqual(bobCounter.value, 0); bobCounter.add(-5); bobCounter.add(4); assert.strictEqual(aliceCounter.value, -5); assert.strictEqual(bobCounter.value, -1); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, -6); assert.strictEqual(bobCounter.value, -6); }); }); describe("reset", () => { it("works for non-concurrent updates", () => { bobCounter.add(20); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 20); assert.strictEqual(bobCounter.value, 20); aliceCounter.reset(); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 0); assert.strictEqual(bobCounter.value, 0); bobCounter.add(7); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 7); assert.strictEqual(bobCounter.value, 7); }); it("works for non-concurrent reset followed by add", () => { aliceCounter.add(-1); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, -1); assert.strictEqual(bobCounter.value, -1); aliceCounter.reset(); assert.strictEqual(aliceCounter.value, 0); assert.strictEqual(bobCounter.value, -1); aliceCounter.add(11); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 11); assert.strictEqual(bobCounter.value, 11); }); it("lets concurrent adds survive", () => { aliceCounter.add(10); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 10); assert.strictEqual(bobCounter.value, 10); aliceCounter.reset(); bobCounter.add(10); appGen.releaseAll(); assert.strictEqual(aliceCounter.value, 10); assert.strictEqual(bobCounter.value, 10); }); }); describe("gc", () => { it("allows garbage collection when reset", () => { aliceCounter.add(10); aliceCounter.add(-1); bobCounter.add(11); bobCounter.add(-2); appGen.releaseAll(); aliceCounter.reset(); appGen.releaseAll(); assert.isTrue(aliceCounter.canGC()); assert.isTrue(bobCounter.canGC()); }); it("does not allow garbage collection when not reset", () => { aliceCounter.add(10); aliceCounter.add(-1); aliceCounter.reset(); bobCounter.add(11); bobCounter.add(-2); appGen.releaseAll(); assert.isFalse(aliceCounter.canGC()); assert.isFalse(bobCounter.canGC()); }); it.skip("works with recreating gc'd Counter", () => { // TODO }); }); it("works with lots of concurrency", () => { aliceCounter.add(3); bobCounter.add(7); aliceCounter.reset(); appGen.release(bob); assert.strictEqual(aliceCounter.value, 7); assert.strictEqual(bobCounter.value, 7); }); }); describe("MultComponent", () => { let aliceVariable: MultComponent; let bobVariable: MultComponent; beforeEach(() => { aliceVariable = alice.registerCollab( "multId", Pre(MultComponent)(new CNumberState(2)) ); bobVariable = bob.registerCollab( "multId", Pre(MultComponent)(new CNumberState(2)) ); alice.load(Optional.empty()); bob.load(Optional.empty()); if (debug) { addEventListeners(aliceVariable, "Alice"); addEventListeners(bobVariable, "Bob"); } }); function addEventListeners(comp: MultComponent, name: string): void { comp.on("Mult", (event) => console.log(`${name}: ${event.meta.sender} multed ${event.arg}`) ); } it("is initially 2", () => { assert.strictEqual(aliceVariable.state.value, 2); assert.strictEqual(bobVariable.state.value, 2); }); describe("mult", () => { it("works for non-concurrent updates", () => { aliceVariable.mult(3); appGen.releaseAll(); assert.strictEqual(aliceVariable.state.value, 6); assert.strictEqual(bobVariable.state.value, 6); bobVariable.mult(-4); appGen.releaseAll(); assert.strictEqual(aliceVariable.state.value, -24); assert.strictEqual(bobVariable.state.value, -24); }); it("works with concurrent updates", () => { aliceVariable.mult(2); assert.strictEqual(aliceVariable.state.value, 4); assert.strictEqual(bobVariable.state.value, 2); bobVariable.mult(-8); assert.strictEqual(aliceVariable.state.value, 4); assert.strictEqual(bobVariable.state.value, -16); appGen.releaseAll(); assert.strictEqual(aliceVariable.state.value, -32); assert.strictEqual(bobVariable.state.value, -32); }); }); describe("reset", () => { // TODO: implement these. it("works with concurrent updates"); it("works with non-concurrent updates"); it("lets concurrent mults survive"); }); }); // // describe("GPlainSet", () => { // let aliceGPlainSet: GPlainSet<any>; // let bobGPlainSet: GPlainSet<any>; // // beforeEach(() => { // aliceGPlainSet = alice.registerCollab("gsetId", new GPlainSet()); // bobGPlainSet = bob.registerCollab("gsetId", new GPlainSet()); // alice.load(Optional.empty()); // bob.load(Optional.empty()); // if (debug) { // addEventListeners(aliceGPlainSet, "Alice"); // addEventListeners(bobGPlainSet, "Bob"); // } // }); // // function addEventListeners<T>(gSet: GPlainSet<T>, name: string): void { // gSet.on("Add", (event) => // console.log( // `${name}: ${event.meta.sender} added ${event.value}` // ) // ); // } // // it("is initially empty", () => { // assert.isEmpty(new Set(aliceGPlainSet)); // assert.isEmpty(new Set(bobGPlainSet)); // }); // // describe("add", () => { // it("works with non-concurrent updates", () => { // aliceGPlainSet.add("element"); // appGen.releaseAll(); // assert.deepStrictEqual(new Set(aliceGPlainSet), new Set(["element"])); // assert.deepStrictEqual(new Set(bobGPlainSet), new Set(["element"])); // // bobGPlainSet.add(7); // appGen.releaseAll(); // assert.deepStrictEqual( // new Set(aliceGPlainSet), // new Set(["element", 7]) // ); // assert.deepStrictEqual(new Set(bobGPlainSet), new Set(["element", 7])); // // aliceGPlainSet.add(7); // appGen.releaseAll(); // assert.deepStrictEqual( // new Set(aliceGPlainSet), // new Set(["element", 7]) // ); // assert.deepStrictEqual(new Set(bobGPlainSet), new Set(["element", 7])); // }); // // it("works with concurrent updates", () => { // aliceGPlainSet.add("first"); // assert.deepStrictEqual(new Set(aliceGPlainSet), new Set(["first"])); // assert.deepStrictEqual(new Set(bobGPlainSet), new Set()); // // bobGPlainSet.add("second"); // assert.deepStrictEqual(new Set(aliceGPlainSet), new Set(["first"])); // assert.deepStrictEqual(new Set(bobGPlainSet), new Set(["second"])); // // appGen.releaseAll(); // assert.deepStrictEqual( // new Set(aliceGPlainSet), // new Set(["first", "second"]) // ); // assert.deepStrictEqual( // new Set(bobGPlainSet), // new Set(["first", "second"]) // ); // }); // }); // }); describe("OptionalLWWCVariable", () => { let aliceMvr: OptionalLWWCVariable<string>; let bobMvr: OptionalLWWCVariable<string>; beforeEach(() => { aliceMvr = alice.registerCollab("mvrId", Pre(OptionalLWWCVariable)()); bobMvr = bob.registerCollab("mvrId", Pre(OptionalLWWCVariable)()); alice.load(Optional.empty()); bob.load(Optional.empty()); if (debug) { addEventListeners(aliceMvr, "Alice"); addEventListeners(bobMvr, "Bob"); } }); function addEventListeners<T>( mvr: OptionalLWWCVariable<T>, name: string ): void { mvr.on("Set", (event) => console.log(`${name}: ${event.meta.sender} set`) ); } it("initially is empty", () => { assert.deepStrictEqual(new Set(aliceMvr.conflicts()), new Set([])); assert.deepStrictEqual(new Set(bobMvr.conflicts()), new Set([])); }); describe("setter", () => { it("works with non-concurrent updates", () => { aliceMvr.set("second"); appGen.releaseAll(); assert.deepStrictEqual( new Set(aliceMvr.conflicts()), new Set(["second"]) ); assert.deepStrictEqual( new Set(bobMvr.conflicts()), new Set(["second"]) ); aliceMvr.set("third"); appGen.releaseAll(); assert.deepStrictEqual( new Set(aliceMvr.conflicts()), new Set(["third"]) ); assert.deepStrictEqual(new Set(bobMvr.conflicts()), new Set(["third"])); bobMvr.set("bob's"); appGen.releaseAll(); assert.deepStrictEqual( new Set(aliceMvr.conflicts()), new Set(["bob's"]) ); assert.deepStrictEqual(new Set(bobMvr.conflicts()), new Set(["bob's"])); }); it("works with concurrent updates", () => { aliceMvr.set("concA"); bobMvr.set("concB"); appGen.releaseAll(); assert.deepStrictEqual( new Set(aliceMvr.conflicts()), new Set(["concA", "concB"]) ); assert.deepStrictEqual( new Set(bobMvr.conflicts()), new Set(["concB", "concA"]) ); aliceMvr.set("concA2"); assert.deepStrictEqual( new Set(aliceMvr.conflicts()), new Set(["concA2"]) ); bobMvr.set("concB2"); assert.deepStrictEqual( new Set(bobMvr.conflicts()), new Set(["concB2"]) ); appGen.releaseAll(); assert.deepStrictEqual( new Set(aliceMvr.conflicts()), new Set(["concA2", "concB2"]) ); assert.deepStrictEqual( new Set(bobMvr.conflicts()), new Set(["concB2", "concA2"]) ); }); it("merges redundant writes", () => { aliceMvr.set("redundant"); bobMvr.set("redundant"); appGen.releaseAll(); assert.deepStrictEqual( new Set(aliceMvr.conflicts()), new Set(["redundant"]) ); assert.deepStrictEqual( new Set(bobMvr.conflicts()), new Set(["redundant"]) ); }); it("keeps overwrites of redundant writes", () => { aliceMvr.set("redundant"); bobMvr.set("redundant"); aliceMvr.set("overwrite"); appGen.releaseAll(); assert.deepStrictEqual( new Set(aliceMvr.conflicts()), new Set(["redundant", "overwrite"]) ); assert.deepStrictEqual( new Set(bobMvr.conflicts()), new Set(["redundant", "overwrite"]) ); }); }); describe("clear", () => { it("works with concurrent updates", () => { aliceMvr.clear(); assert.deepStrictEqual(new Set(aliceMvr.conflicts()), new Set([])); bobMvr.set("conc"); appGen.releaseAll(); assert.deepStrictEqual( new Set(aliceMvr.conflicts()), new Set(["conc"]) ); assert.deepStrictEqual(new Set(bobMvr.conflicts()), new Set(["conc"])); }); // TODO it.skip("works with concurrent clears"); it.skip("lets concurrent writes survive"); }); }); describe("LWWCVariable", () => { let aliceLWW: LWWCVariable<string>; let bobLWW: LWWCVariable<string>; beforeEach(() => { aliceLWW = alice.registerCollab("lwwId", Pre(LWWCVariable)("initial")); bobLWW = bob.registerCollab("lwwId", Pre(LWWCVariable)("initial")); alice.load(Optional.empty()); bob.load(Optional.empty()); if (debug) { addEventListeners(aliceLWW, "Alice"); addEventListeners(bobLWW, "Bob"); } }); function addEventListeners<T>(lww: LWWCVariable<T>, name: string): void { // TODO // lww.on("LWW", (event) => // console.log( // `${name}: ${event.meta.sender} set to ${event.value}` // ) // ); } it('is initially "initial"', () => { assert.strictEqual(aliceLWW.value, "initial"); assert.strictEqual(bobLWW.value, "initial"); }); describe("setter", () => { it("works with non-concurrent updates", () => { aliceLWW.value = "second"; appGen.releaseAll(); assert.strictEqual(aliceLWW.value, "second"); assert.strictEqual(bobLWW.value, "second"); aliceLWW.value = "third"; appGen.releaseAll(); assert.strictEqual(aliceLWW.value, "third"); assert.strictEqual(bobLWW.value, "third"); aliceLWW.value = "third"; appGen.releaseAll(); assert.strictEqual(aliceLWW.value, "third"); assert.strictEqual(bobLWW.value, "third"); bobLWW.value = "bob's"; appGen.releaseAll(); assert.strictEqual(aliceLWW.value, "bob's"); assert.strictEqual(bobLWW.value, "bob's"); }); it("works with concurrent updates", () => { aliceLWW.value = "concA"; let now = new Date().getTime(); while (new Date().getTime() <= now) { // Loop; Bob will have a later time than now } bobLWW.value = "concB"; appGen.releaseAll(); assert.strictEqual(aliceLWW.value, "concB"); assert.strictEqual(bobLWW.value, "concB"); aliceLWW.value = "concA2"; assert.strictEqual(aliceLWW.value, "concA2"); now = new Date().getTime(); while (new Date().getTime() <= now) { // Loop; Bob will have a later time than now } bobLWW.value = "concB2"; assert.strictEqual(bobLWW.value, "concB2"); appGen.releaseAll(); assert.strictEqual(aliceLWW.value, "concB2"); assert.strictEqual(bobLWW.value, "concB2"); }); it("works with redundant writes", () => { aliceLWW.value = "redundant"; bobLWW.value = "redundant"; appGen.releaseAll(); assert.strictEqual(aliceLWW.value, "redundant"); assert.strictEqual(bobLWW.value, "redundant"); }); it("works with overwrites", () => { aliceLWW.value = "redundant"; aliceLWW.value = "overwrite"; appGen.releaseAll(); assert.strictEqual(aliceLWW.value, "overwrite"); assert.strictEqual(bobLWW.value, "overwrite"); }); }); describe("clear", () => { it("works with concurrent clear", () => { aliceLWW.clear(); assert.strictEqual(aliceLWW.value, "initial"); bobLWW.value = "conc"; appGen.releaseAll(); assert.strictEqual(aliceLWW.value, "conc"); assert.strictEqual(bobLWW.value, "conc"); }); }); }); });
the_stack
import delay from 'delay'; import { of } from "rxjs"; import { take, map, combineLatest } from "rxjs/operators"; import { marbles } from "rxjs-marbles/jest"; import { makeExecutableSchema } from "graphql-tools"; import { graphql } from "../"; const typeDefs = ` type Shuttle { name: String! firstFlight: Int } type Query { launched(name: String): [Shuttle!]! } type Mutation { createShuttle(name: String): Shuttle! createShuttleList(name: String): [Shuttle!]! } `; const mockResolvers = { Query: { launched: (parent, args, ctx) => { const { name } = args; // act according with the type of filter if (name === undefined) { // When no filter is passed if (!parent) { return ctx.query; } return ctx.query.pipe( map((shuttles: any[]) => shuttles.map(shuttle => ({ ...shuttle, name: shuttle.name + parent.shuttleSuffix })) ) ); } else if (typeof name === "string") { // When the filter is a value return ctx.query.pipe( map(els => (els as any[]).filter(el => el.name === name)) ); } else { // when the filter is an observable return ctx.query.pipe( combineLatest(name, (res, name) => [res, name]), map(els => els[0].filter(el => el.name === els[1])) ); } } }, Mutation: { createShuttle: (_, args, ctx) => { return ctx.mutation.pipe( map(() => ({ name: args.name })) ); }, createShuttleList: (_, args, ctx) => { return ctx.mutation.pipe( map(() => [ { name: "discovery" }, { name: "challenger" }, { name: args.name } ]) ); } } }; const schema = makeExecutableSchema({ typeDefs, resolvers: mockResolvers }); const fieldResolverSchema = makeExecutableSchema({ typeDefs: ` type Plain { noFieldResolver: String! fieldResolver: String! fieldResolvesUndefined: String! giveMeTheParentFieldResolver: String! giveMeTheArgsFieldResolver(arg: String!): String! giveMeTheContextFieldResolver: String! } type ObjectValue { value: String! } type Item { nodeFieldResolver: ObjectValue! nullableNodeFieldResolver: ObjectValue giveMeTheParentFieldResolver: ObjectValue! giveMeTheArgsFieldResolver(arg: String!): ObjectValue! giveMeTheContextFieldResolver: ObjectValue! } type Nested { firstFieldResolver: Nesting! } type Nesting { noFieldResolverValue: String! secondFieldResolver: String! } type Query { plain: Plain! item: Item! nested: Nested! throwingResolver: String } `, resolvers: { Plain: { fieldResolver() { return of("I am a field resolver"); }, fieldResolvesUndefined() { return of(undefined); }, giveMeTheParentFieldResolver(parent) { return of(JSON.stringify(parent)); }, giveMeTheArgsFieldResolver(_parent, args) { return of(JSON.stringify(args)); }, giveMeTheContextFieldResolver(_parent, _args, context) { return of(context.newValue); } }, Item: { nodeFieldResolver() { return of({ value: "I am a node field resolver" }); }, nullableNodeFieldResolver() { return null; }, giveMeTheParentFieldResolver(parent) { return of({ value: JSON.stringify(parent) }); }, giveMeTheArgsFieldResolver(_parent, args) { return of({ value: JSON.stringify(args) }); }, giveMeTheContextFieldResolver(_parent, _args, context) { return of({ value: context.newValue }); } }, Nested: { firstFieldResolver(_parent, _args, ctx) { ctx.contextValue = " resolvers are great"; return of({ noFieldResolverValue: "nested" }); } }, Nesting: { secondFieldResolver({ noFieldResolverValue }, _, { contextValue }) { return of(noFieldResolverValue.toLocaleUpperCase() + contextValue); } }, Query: { plain(_parent, _args, ctx) { ctx.newValue = "ContextValue"; return of({ noFieldResolver: "Yes" }); }, item(_parent, _args, ctx) { ctx.newValue = "NodeContextValue"; return of({ thisIsANodeFieldResolver: "Yes" }); }, nested() { return of({}); }, throwingResolver() { throw new Error("my personal error"); } } } }); // jest helper who binds the marbles for you const itMarbles = (title, test) => { return it(title, marbles(test)); }; itMarbles.only = (title, test) => { return it.only(title, marbles(test)); }; describe("graphqlObservable", function() { describe("Query", function() { itMarbles("solves listing all fields", function(m) { const query = ` query { launched { name } } `; const expectedData = [{ name: "discovery" }]; const dataSource = of(expectedData); const expected = m.cold("(a|)", { a: { data: { launched: expectedData } } }); const result = graphql(schema, query, null, { query: dataSource }); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("solves listing all fields with string query", function(m) { const query = ` query { launched { name } } `; const expectedData = [{ name: "discovery" }]; const dataSource = of(expectedData); const expected = m.cold("(a|)", { a: { data: { launched: expectedData } } }); const result = graphql(schema, query, null, { query: dataSource }); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("filters by variable argument", function(m) { const query = ` query($nameFilter: String) { launched(name: $nameFilter) { name firstFlight } } `; const expectedData = [{ name: "apollo11", firstFlight: null }, { name: "challenger", firstFlight: null }]; const dataSource = of(expectedData); const expected = m.cold("(a|)", { a: { data: { launched: [expectedData[0]] } } }); const nameFilter = "apollo11"; const result = graphql( schema, query, null, { query: dataSource }, { nameFilter } ); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("filters by static argument", function(m) { const query = ` query { launched(name: "apollo13") { name firstFlight } } `; const expectedData = [{ name: "apollo13", firstFlight: null }, { name: "challenger", firstFlight: null }]; const dataSource = of(expectedData); const expected = m.cold("(a|)", { a: { data: { launched: [expectedData[0]] } } }); const result = graphql(schema, query, null, { query: dataSource }); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("filters out fields", function(m) { const query = ` query { launched { name } } `; const expectedData = [{ name: "discovery", firstFlight: 1984 }]; const dataSource = of(expectedData); const expected = m.cold("(a|)", { a: { data: { launched: [{ name: "discovery" }] } } }); const result = graphql(schema, query, null, { query: dataSource }); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("resolve with name alias", function(m) { const query = ` query { launched { title: name } } `; const expectedData = [{ name: "challenger", firstFlight: 1984 }]; const dataSource = of(expectedData); const expected = m.cold("(a|)", { a: { data: { launched: [{ title: "challenger" }] } } }); const result = graphql(schema, query, null, { query: dataSource }); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("resolves using root value", function(m) { const query = ` query { launched { name } } `; const expectedData = [{ name: "challenger", firstFlight: 1984 }]; const dataSource = of(expectedData); const expected = m.cold("(a|)", { a: { data: { launched: [{ name: "challenger-nasa" }] } } }); const result = graphql( schema, query, { shuttleSuffix: "-nasa" }, { query: dataSource } ); m.expect(result.pipe(take(1))).toBeObservable(expected); }); describe("Field Resolvers", function() { describe("Leafs", function() { itMarbles("defaults to return the property on the object", function(m) { const query = ` query { plain { noFieldResolver } } `; const expected = m.cold("(a|)", { a: { data: { plain: { noFieldResolver: "Yes" } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("if defined it executes the field resolver", function(m) { const query = ` query { plain { fieldResolver } } `; const expected = m.cold("(a|)", { a: { data: { plain: { fieldResolver: "I am a field resolver" } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("if defined but returns undefined, field is null", function (m) { const query = ` query { plain { fieldResolvesUndefined } } `; const expected = m.cold("(a|)", { a: { data: { plain: { fieldResolvesUndefined: null } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("the field resolvers 1st argument is parent", function(m) { const query = ` query { plain { giveMeTheParentFieldResolver } } `; const expected = m.cold("(a|)", { a: { data: { plain: { giveMeTheParentFieldResolver: JSON.stringify({ noFieldResolver: "Yes" }) } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("the field resolvers 2nd argument is arguments", function(m) { const query = ` query { plain { giveMeTheArgsFieldResolver(arg: "My passed arg") } } `; const expected = m.cold("(a|)", { a: { data: { plain: { giveMeTheArgsFieldResolver: JSON.stringify({ arg: "My passed arg" }) } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("the field resolvers 3rd argument is context", function(m) { const query = ` query { plain { giveMeTheContextFieldResolver } } `; const expected = m.cold("(a|)", { a: { data: { plain: { giveMeTheContextFieldResolver: "ContextValue" } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); }); describe("Nodes", function() { itMarbles("if defined it executes the field resolver", function(m) { const query = ` query { item { nodeFieldResolver { value } } } `; const expected = m.cold("(a|)", { a: { data: { item: { nodeFieldResolver: { value: "I am a node field resolver" } } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("if nullable field resolver returns null, it resolves null", function(m) { const query = ` query { item { nullableNodeFieldResolver { value } } } `; const expected = m.cold("(a|)", { a: { data: { item: { nullableNodeFieldResolver: null } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("the field resolvers 1st argument is parent", function(m) { const query = ` query { item { giveMeTheParentFieldResolver { value } } } `; const expected = m.cold("(a|)", { a: { data: { item: { giveMeTheParentFieldResolver: { value: JSON.stringify({ thisIsANodeFieldResolver: "Yes" }) } } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("the field resolvers 2nd argument is arguments", function(m) { const query = ` query { item { giveMeTheArgsFieldResolver(arg: "My passed arg") { value } } } `; const expected = m.cold("(a|)", { a: { data: { item: { giveMeTheArgsFieldResolver: { value: JSON.stringify({ arg: "My passed arg" }) } } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); itMarbles("the field resolvers 3rd argument is context", function(m) { const query = ` query { item { giveMeTheContextFieldResolver { value } } } `; const expected = m.cold("(a|)", { a: { data: { item: { giveMeTheContextFieldResolver: { value: "NodeContextValue" } } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); }); itMarbles("nested resolvers pass down the context and parent", function( m ) { const query = ` query { nested { firstFieldResolver { noFieldResolverValue secondFieldResolver } } } `; const expected = m.cold("(a|)", { a: { data: { nested: { firstFieldResolver: { noFieldResolverValue: "nested", secondFieldResolver: "NESTED resolvers are great" } } } } }); const result = graphql(fieldResolverSchema, query, null, {}); m.expect(result.pipe(take(1))).toBeObservable(expected); }); }); it("throwing an error results in an error in execution result", async function() { const query = ` query { throwingResolver } `; const result = await graphql(fieldResolverSchema, query, null, {}).pipe(take(1)).toPromise(); expect(result).toHaveProperty('errors'); expect(result.errors![0].message).toBe('my personal error'); expect(result.errors![0].path).toEqual(['throwingResolver']); }); it( "accessing an unknown query field results in an error in execution result", async function() { const query = ` query { youDontKnowMe } `; const result = await graphql(fieldResolverSchema, query, null, {}).pipe(take(1)).toPromise(); expect(result).toHaveProperty('errors'); expect(result.errors![0].message).toBe('Cannot query field \"youDontKnowMe\" on type \"Query\".') } ); }); describe("Mutation", function() { itMarbles("createShuttle adds a shuttle and return its name", function(m) { const mutation = ` mutation { createShuttle(name: "RocketShip") { name } } `; const fakeRequest = { name: "RocketShip" }; const commandContext = of(fakeRequest); const result = graphql(schema, mutation, null, { mutation: commandContext }); const expected = m.cold("(a|)", { a: { data: { createShuttle: { name: "RocketShip" } } } }); m.expect(result).toBeObservable(expected); }); itMarbles( "createShuttleList adds a shuttle and return all shuttles", function(m) { const mutation = ` mutation { createShuttleList(name: "RocketShip") { name } } `; const commandContext = of("a request"); const result = graphql(schema, mutation, null, { mutation: commandContext }); const expected = m.cold("(a|)", { a: { data: { createShuttleList: [ { name: "discovery" }, { name: "challenger" }, { name: "RocketShip" } ] } } }); m.expect(result).toBeObservable(expected); } ); itMarbles("accept alias name", function(m) { const mutation = ` mutation ($name: String){ shut: createShuttle(name: $name) { name } } `; const commandContext = of("a resquest"); const variables = { name: "RocketShip" }; const result = graphql( schema, mutation, null, { mutation: commandContext }, variables ); const expected = m.cold("(a|)", { a: { data: { shut: { name: "RocketShip" } } } }); m.expect(result).toBeObservable(expected); }); it('respects serial execution of resolvers', async () => { let theNumber = 0; const schema = makeExecutableSchema({ typeDefs: ` type Mutation { increment: Int! } type Query { theNumber: Int! } `, resolvers: { Mutation: { // atomic resolver increment: async () => { const _theNumber = theNumber; await delay(100); theNumber = _theNumber + 1; return theNumber; } }, } }); const result$ = graphql({ schema, source: ` mutation { first: increment, second: increment, third: increment, } `, }) const result = await result$.pipe(take(1)).toPromise(); expect(result).toEqual({ data: { first: 1, second: 2, // 1 if not serial third: 3, // 1 if not serial } }) }) }); });
the_stack
import {escapeRegExp} from '@angular/compiler/src/util'; import {serializeNodes} from '../../../src/i18n/digest'; import {MessageBundle} from '../../../src/i18n/message_bundle'; import {Xliff2} from '../../../src/i18n/serializers/xliff2'; import {HtmlParser} from '../../../src/ml_parser/html_parser'; import {DEFAULT_INTERPOLATION_CONFIG} from '../../../src/ml_parser/interpolation_config'; const HTML = ` <p i18n-title title="translatable attribute">not translatable</p> <p i18n>translatable element <b>with placeholders</b> {{ interpolation}}</p> <!-- i18n -->{ count, plural, =0 {<p>test</p>}}<!-- /i18n --> <p i18n="m|d@@i">foo</p> <p i18n="nested"><b><u>{{interpolation}} Text</u></b></p> <p i18n="ph names"><br><img src="1.jpg"><img src="2.jpg"></p> <p i18n="empty element">hello <span></span></p> <p i18n="@@baz">{ count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} }}</p> <p i18n>Test: { count, plural, =0 { { sex, select, other {<p>deeply nested</p>}} } =other {a lot}}</p> <p i18n>multi lines</p> `; const WRITE_XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en"> <file original="ng.template" id="ngi18n"> <unit id="1933478729560469763"> <notes> <note category="location">file.ts:2</note> </notes> <segment> <source>translatable attribute</source> </segment> </unit> <unit id="7056919470098446707"> <notes> <note category="location">file.ts:3</note> </notes> <segment> <source>translatable element <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;">with placeholders</pc> <ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/></source> </segment> </unit> <unit id="2981514368455622387"> <notes> <note category="location">file.ts:4</note> </notes> <segment> <source>{VAR_PLURAL, plural, =0 {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">test</pc>} }</source> </segment> </unit> <unit id="i"> <notes> <note category="description">d</note> <note category="meaning">m</note> <note category="location">file.ts:5</note> </notes> <segment> <source>foo</source> </segment> </unit> <unit id="6440235004920703622"> <notes> <note category="description">nested</note> <note category="location">file.ts:6</note> </notes> <segment> <source><pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;"><pc id="1" equivStart="START_UNDERLINED_TEXT" equivEnd="CLOSE_UNDERLINED_TEXT" type="fmt" dispStart="&lt;u&gt;" dispEnd="&lt;/u&gt;"><ph id="2" equiv="INTERPOLATION" disp="{{interpolation}}"/> Text</pc></pc></source> </segment> </unit> <unit id="8779402634269838862"> <notes> <note category="description">ph names</note> <note category="location">file.ts:7</note> </notes> <segment> <source><ph id="0" equiv="LINE_BREAK" type="fmt" disp="&lt;br/&gt;"/><ph id="1" equiv="TAG_IMG" type="image" disp="&lt;img/&gt;"/><ph id="2" equiv="TAG_IMG_1" type="image" disp="&lt;img/&gt;"/></source> </segment> </unit> <unit id="6536355551500405293"> <notes> <note category="description">empty element</note> <note category="location">file.ts:8</note> </notes> <segment> <source>hello <pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other" dispStart="&lt;span&gt;" dispEnd="&lt;/span&gt;"></pc></source> </segment> </unit> <unit id="baz"> <notes> <note category="location">file.ts:9</note> </notes> <segment> <source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">deeply nested</pc>} } } }</source> </segment> </unit> <unit id="6997386649824869937"> <notes> <note category="location">file.ts:10</note> </notes> <segment> <source>Test: <ph id="0" equiv="ICU" disp="{ count, plural, =0 {...} =other {...}}"/></source> </segment> </unit> <unit id="5229984852258993423"> <notes> <note category="location">file.ts:10</note> </notes> <segment> <source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">deeply nested</pc>} } } =other {a lot} }</source> </segment> </unit> <unit id="2340165783990709777"> <notes> <note category="location">file.ts:11,12</note> </notes> <segment> <source>multi lines</source> </segment> </unit> </file> </xliff> `; const LOAD_XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en" trgLang="fr"> <file original="ng.template" id="ngi18n"> <unit id="1933478729560469763"> <notes> <note category="location">file.ts:2</note> </notes> <segment> <source>translatable attribute</source> <target>etubirtta elbatalsnart</target> </segment> </unit> <unit id="7056919470098446707"> <notes> <note category="location">file.ts:3</note> </notes> <segment> <source>translatable element <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;">with placeholders</pc> <ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/></source> <target><ph id="1" equiv="INTERPOLATION" disp="{{ interpolation}}"/> <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;">sredlohecalp htiw</pc> tnemele elbatalsnart</target> </segment> </unit> <unit id="2981514368455622387"> <notes> <note category="location">file.ts:4</note> </notes> <segment> <source>{VAR_PLURAL, plural, =0 {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">test</pc>} }</source> <target>{VAR_PLURAL, plural, =0 {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">TEST</pc>} }</target> </segment> </unit> <unit id="i"> <notes> <note category="description">d</note> <note category="meaning">m</note> <note category="location">file.ts:5</note> </notes> <segment> <source>foo</source> <target>oof</target> </segment> </unit> <unit id="6440235004920703622"> <notes> <note category="description">nested</note> <note category="location">file.ts:6</note> </notes> <segment> <source><pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;"><pc id="1" equivStart="START_UNDERLINED_TEXT" equivEnd="CLOSE_UNDERLINED_TEXT" type="fmt" dispStart="&lt;u&gt;" dispEnd="&lt;/u&gt;"><ph id="2" equiv="INTERPOLATION" disp="{{interpolation}}"/> Text</pc></pc></source> <target><pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;"><pc id="1" equivStart="START_UNDERLINED_TEXT" equivEnd="CLOSE_UNDERLINED_TEXT" type="fmt" dispStart="&lt;u&gt;" dispEnd="&lt;/u&gt;">txeT <ph id="2" equiv="INTERPOLATION" disp="{{interpolation}}"/></pc></pc></target> </segment> </unit> <unit id="8779402634269838862"> <notes> <note category="description">ph names</note> <note category="location">file.ts:7</note> </notes> <segment> <source><ph id="0" equiv="LINE_BREAK" type="fmt" disp="&lt;br/&gt;"/><ph id="1" equiv="TAG_IMG" type="image" disp="&lt;img/&gt;"/><ph id="2" equiv="TAG_IMG_1" type="image" disp="&lt;img/&gt;"/></source> <target><ph id="2" equiv="TAG_IMG_1" type="image" disp="&lt;img/&gt;"/><ph id="1" equiv="TAG_IMG" type="image" disp="&lt;img/&gt;"/><ph id="0" equiv="LINE_BREAK" type="fmt" disp="&lt;br/&gt;"/></target> </segment> </unit> <unit id="6536355551500405293"> <notes> <note category="description">empty element</note> <note category="location">file.ts:8</note> </notes> <segment> <source>hello <pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other" dispStart="&lt;span&gt;" dispEnd="&lt;/span&gt;"></pc></source> <target><pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other" dispStart="&lt;span&gt;" dispEnd="&lt;/span&gt;"></pc> olleh</target> </segment> </unit> <unit id="baz"> <notes> <note category="location">file.ts:9</note> </notes> <segment> <source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">deeply nested</pc>} } } }</source> <target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">profondément imbriqué</pc>} } } }</target> </segment> </unit> <unit id="6997386649824869937"> <notes> <note category="location">file.ts:10</note> </notes> <segment> <source>Test: <ph id="0" equiv="ICU" disp="{ count, plural, =0 {...} =other {...}}"/></source> <target>Test: <ph id="0" equiv="ICU" disp="{ count, plural, =0 {...} =other {...}}"/></target> </segment> </unit> <unit id="5229984852258993423"> <notes> <note category="location">file.ts:10</note> </notes> <segment> <source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">deeply nested</pc>} } } =other {a lot} }</source> <target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<pc id="0" equivStart="START_PARAGRAPH" equivEnd="CLOSE_PARAGRAPH" type="other" dispStart="&lt;p&gt;" dispEnd="&lt;/p&gt;">profondément imbriqué</pc>} } } =other {beaucoup} }</target> </segment> </unit> <unit id="2340165783990709777"> <notes> <note category="location">file.ts:11,12</note> </notes> <segment> <source>multi lines</source> <target>multi lignes</target> </segment> </unit> <unit id="mrk-test"> <notes> <note id="n1" appliesTo="target">Please check the translation for 'namespace'. On also can use 'espace de nom',but I think most technical manuals use the English term.</note> </notes> <segment> <source>You use your own namespace.</source> <target>Vous pouvez utiliser votre propre <mrk id="m1" type="comment" ref="#n1">namespace</mrk>.</target> </segment> </unit> <unit id="mrk-test2"> <notes> <note id="n1" appliesTo="target">Please check the translation for 'namespace'. On also can use 'espace de nom',but I think most technical manuals use the English term.</note> </notes> <segment> <source>You use your own namespace.</source> <target>Vous pouvez utiliser <mrk id="m1" type="comment" ref="#n1">votre propre <mrk id="m2" type="comment" ref="#n1">namespace</mrk></mrk>.</target> </segment> </unit> </file> </xliff> `; (function() { const serializer = new Xliff2(); function toXliff(html: string, locale: string|null = null): string { const catalog = new MessageBundle(new HtmlParser, [], {}, locale); catalog.updateFromTemplate(html, 'file.ts', DEFAULT_INTERPOLATION_CONFIG); return catalog.write(serializer); } function loadAsMap(xliff: string): {[id: string]: string} { const {i18nNodesByMsgId} = serializer.load(xliff, 'url'); const msgMap: {[id: string]: string} = {}; Object.keys(i18nNodesByMsgId) .forEach(id => msgMap[id] = serializeNodes(i18nNodesByMsgId[id]).join('')); return msgMap; } describe('XLIFF 2.0 serializer', () => { describe('write', () => { it('should write a valid xliff 2.0 file', () => { expect(toXliff(HTML)).toEqual(WRITE_XLIFF); }); it('should write a valid xliff 2.0 file with a source language', () => { expect(toXliff(HTML, 'fr')).toContain('srcLang="fr"'); }); }); describe('load', () => { it('should load XLIFF files', () => { expect(loadAsMap(LOAD_XLIFF)).toEqual({ '1933478729560469763': 'etubirtta elbatalsnart', '7056919470098446707': '<ph name="INTERPOLATION"/> <ph name="START_BOLD_TEXT"/>sredlohecalp htiw<ph name="CLOSE_BOLD_TEXT"/> tnemele elbatalsnart', '2981514368455622387': '{VAR_PLURAL, plural, =0 {[<ph name="START_PARAGRAPH"/>, TEST, <ph name="CLOSE_PARAGRAPH"/>]}}', 'i': 'oof', '6440235004920703622': '<ph name="START_BOLD_TEXT"/><ph name="START_UNDERLINED_TEXT"/>txeT <ph name="INTERPOLATION"/><ph name="CLOSE_UNDERLINED_TEXT"/><ph name="CLOSE_BOLD_TEXT"/>', '8779402634269838862': '<ph name="TAG_IMG_1"/><ph name="TAG_IMG"/><ph name="LINE_BREAK"/>', '6536355551500405293': '<ph name="START_TAG_SPAN"/><ph name="CLOSE_TAG_SPAN"/> olleh', 'baz': '{VAR_PLURAL, plural, =0 {[{VAR_SELECT, select, other {[<ph name="START_PARAGRAPH"/>, profondément imbriqué, <ph name="CLOSE_PARAGRAPH"/>]}}, ]}}', '6997386649824869937': 'Test: <ph name="ICU"/>', '5229984852258993423': '{VAR_PLURAL, plural, =0 {[{VAR_SELECT, select, other {[<ph' + ' name="START_PARAGRAPH"/>, profondément imbriqué, <ph name="CLOSE_PARAGRAPH"/>]}}, ]}, =other {[beaucoup]}}', '2340165783990709777': `multi lignes`, 'mrk-test': 'Vous pouvez utiliser votre propre namespace.', 'mrk-test2': 'Vous pouvez utiliser votre propre namespace.' }); }); it('should return the target locale', () => { expect(serializer.load(LOAD_XLIFF, 'url').locale).toEqual('fr'); }); }); describe('structure errors', () => { it('should throw when a wrong xliff version is used', () => { const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="deadbeef"> <source/> <target/> </trans-unit> </body> </file> </xliff>`; expect(() => { loadAsMap(XLIFF); }).toThrowError(/The XLIFF file version 1.2 is not compatible with XLIFF 2.0 serializer/); }); it('should throw when an unit has no translation', () => { const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en"> <file original="ng.template" id="ngi18n"> <unit id="missingtarget"> <segment> <source/> </segment> </unit> </file> </xliff>`; expect(() => { loadAsMap(XLIFF); }).toThrowError(/Message missingtarget misses a translation/); }); it('should throw when an unit has no id attribute', () => { const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en"> <file original="ng.template" id="ngi18n"> <unit> <segment> <source/> <target/> </segment> </unit> </file> </xliff>`; expect(() => { loadAsMap(XLIFF); }).toThrowError(/<unit> misses the "id" attribute/); }); it('should throw on duplicate unit id', () => { const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en"> <file original="ng.template" id="ngi18n"> <unit id="deadbeef"> <segment> <source/> <target/> </segment> </unit> <unit id="deadbeef"> <segment> <source/> <target/> </segment> </unit> </file> </xliff>`; expect(() => { loadAsMap(XLIFF); }).toThrowError(/Duplicated translations for msg deadbeef/); }); }); describe('message errors', () => { it('should throw on unknown message tags', () => { const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en"> <file original="ng.template" id="ngi18n"> <unit id="deadbeef"> <segment> <source/> <target><b>msg should contain only ph and pc tags</b></target> </segment> </unit> </file> </xliff>`; expect(() => { loadAsMap(XLIFF); }) .toThrowError( new RegExp(escapeRegExp(`[ERROR ->]<b>msg should contain only ph and pc tags</b>`))); }); it('should throw when a placeholder misses an id attribute', () => { const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en"> <file original="ng.template" id="ngi18n"> <unit id="deadbeef"> <segment> <source/> <target><ph/></target> </segment> </unit> </file> </xliff>`; expect(() => { loadAsMap(XLIFF); }).toThrowError(new RegExp(escapeRegExp(`<ph> misses the "equiv" attribute`))); }); }); }); })();
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/variableOperationsMappers"; import * as Parameters from "../models/parameters"; import { AutomationClientContext } from "../automationClientContext"; /** Class representing a VariableOperations. */ export class VariableOperations { private readonly client: AutomationClientContext; /** * Create a VariableOperations. * @param {AutomationClientContext} client Reference to the service client. */ constructor(client: AutomationClientContext) { this.client = client; } /** * Create a variable. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The variable name. * @param parameters The parameters supplied to the create or update variable operation. * @param [options] The optional parameters * @returns Promise<Models.VariableCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, automationAccountName: string, variableName: string, parameters: Models.VariableCreateOrUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.VariableCreateOrUpdateResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The variable name. * @param parameters The parameters supplied to the create or update variable operation. * @param callback The callback */ createOrUpdate(resourceGroupName: string, automationAccountName: string, variableName: string, parameters: Models.VariableCreateOrUpdateParameters, callback: msRest.ServiceCallback<Models.Variable>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The variable name. * @param parameters The parameters supplied to the create or update variable operation. * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, automationAccountName: string, variableName: string, parameters: Models.VariableCreateOrUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Variable>): void; createOrUpdate(resourceGroupName: string, automationAccountName: string, variableName: string, parameters: Models.VariableCreateOrUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Variable>, callback?: msRest.ServiceCallback<Models.Variable>): Promise<Models.VariableCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, variableName, parameters, options }, createOrUpdateOperationSpec, callback) as Promise<Models.VariableCreateOrUpdateResponse>; } /** * Update a variable. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The variable name. * @param parameters The parameters supplied to the update variable operation. * @param [options] The optional parameters * @returns Promise<Models.VariableUpdateResponse> */ update(resourceGroupName: string, automationAccountName: string, variableName: string, parameters: Models.VariableUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.VariableUpdateResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The variable name. * @param parameters The parameters supplied to the update variable operation. * @param callback The callback */ update(resourceGroupName: string, automationAccountName: string, variableName: string, parameters: Models.VariableUpdateParameters, callback: msRest.ServiceCallback<Models.Variable>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The variable name. * @param parameters The parameters supplied to the update variable operation. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, automationAccountName: string, variableName: string, parameters: Models.VariableUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Variable>): void; update(resourceGroupName: string, automationAccountName: string, variableName: string, parameters: Models.VariableUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Variable>, callback?: msRest.ServiceCallback<Models.Variable>): Promise<Models.VariableUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, variableName, parameters, options }, updateOperationSpec, callback) as Promise<Models.VariableUpdateResponse>; } /** * Delete the variable. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The name of variable. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, automationAccountName: string, variableName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The name of variable. * @param callback The callback */ deleteMethod(resourceGroupName: string, automationAccountName: string, variableName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The name of variable. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, automationAccountName: string, variableName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, automationAccountName: string, variableName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, variableName, options }, deleteMethodOperationSpec, callback); } /** * Retrieve the variable identified by variable name. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The name of variable. * @param [options] The optional parameters * @returns Promise<Models.VariableGetResponse> */ get(resourceGroupName: string, automationAccountName: string, variableName: string, options?: msRest.RequestOptionsBase): Promise<Models.VariableGetResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The name of variable. * @param callback The callback */ get(resourceGroupName: string, automationAccountName: string, variableName: string, callback: msRest.ServiceCallback<Models.Variable>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param variableName The name of variable. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, automationAccountName: string, variableName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Variable>): void; get(resourceGroupName: string, automationAccountName: string, variableName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Variable>, callback?: msRest.ServiceCallback<Models.Variable>): Promise<Models.VariableGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, variableName, options }, getOperationSpec, callback) as Promise<Models.VariableGetResponse>; } /** * Retrieve a list of variables. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param [options] The optional parameters * @returns Promise<Models.VariableListByAutomationAccountResponse> */ listByAutomationAccount(resourceGroupName: string, automationAccountName: string, options?: msRest.RequestOptionsBase): Promise<Models.VariableListByAutomationAccountResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param callback The callback */ listByAutomationAccount(resourceGroupName: string, automationAccountName: string, callback: msRest.ServiceCallback<Models.VariableListResult>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param options The optional parameters * @param callback The callback */ listByAutomationAccount(resourceGroupName: string, automationAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VariableListResult>): void; listByAutomationAccount(resourceGroupName: string, automationAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VariableListResult>, callback?: msRest.ServiceCallback<Models.VariableListResult>): Promise<Models.VariableListByAutomationAccountResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, options }, listByAutomationAccountOperationSpec, callback) as Promise<Models.VariableListByAutomationAccountResponse>; } /** * Retrieve a list of variables. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.VariableListByAutomationAccountNextResponse> */ listByAutomationAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.VariableListByAutomationAccountNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByAutomationAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.VariableListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByAutomationAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VariableListResult>): void; listByAutomationAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VariableListResult>, callback?: msRest.ServiceCallback<Models.VariableListResult>): Promise<Models.VariableListByAutomationAccountNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByAutomationAccountNextOperationSpec, callback) as Promise<Models.VariableListByAutomationAccountNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/variables/{variableName}", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.variableName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.VariableCreateOrUpdateParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.Variable }, 201: { bodyMapper: Mappers.Variable }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/variables/{variableName}", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.variableName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.VariableUpdateParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.Variable }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/variables/{variableName}", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.variableName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/variables/{variableName}", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.variableName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Variable }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByAutomationAccountOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/variables", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.VariableListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByAutomationAccountNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.VariableListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import { assert } from "chai"; import * as path from "path"; import { AccessToken, DbResult, GuidString, Id64, Id64String, PerfLogger } from "@itwin/core-bentley"; import { ChangedValueState, ChangeOpCode, ColorDef, IModel, IModelError, IModelVersion, QueryBinder, QueryRowFormat, SubCategoryAppearance, } from "@itwin/core-common"; import { BriefcaseDb, BriefcaseManager, ChangeSummary, ChangeSummaryManager, ECSqlStatement, ElementOwnsChildElements, IModelHost, IModelJsFs, SpatialCategory, } from "@itwin/core-backend"; import { HubWrappers, IModelTestUtils, KnownTestLocations, TestChangeSetUtility } from "@itwin/core-backend/lib/cjs/test/index"; import { HubUtility, TestUserType } from "../HubUtility"; function setupTest(iModelId: string): void { const cacheFilePath: string = BriefcaseManager.getChangeCachePathName(iModelId); if (IModelJsFs.existsSync(cacheFilePath)) IModelJsFs.removeSync(cacheFilePath); } function getChangeSummaryAsJson(iModel: BriefcaseDb, changeSummaryId: string) { const changeSummary: ChangeSummary = ChangeSummaryManager.queryChangeSummary(iModel, changeSummaryId); const content = { id: changeSummary.id, changeSet: changeSummary.changeSet, instanceChanges: new Array<any>() }; iModel.withPreparedStatement("SELECT ECInstanceId FROM ecchange.change.InstanceChange WHERE Summary.Id=? ORDER BY ECInstanceId", (stmt) => { stmt.bindId(1, changeSummary.id); while (stmt.step() === DbResult.BE_SQLITE_ROW) { const row = stmt.getRow(); const instanceChange: any = ChangeSummaryManager.queryInstanceChange(iModel, Id64.fromJSON(row.id)); switch (instanceChange.opCode) { case ChangeOpCode.Insert: { const rows: any[] = IModelTestUtils.executeQuery(iModel, ChangeSummaryManager.buildPropertyValueChangesECSql(iModel, instanceChange, ChangedValueState.AfterInsert)); assert.equal(rows.length, 1); instanceChange.after = rows[0]; break; } case ChangeOpCode.Update: { let rows: any[] = IModelTestUtils.executeQuery(iModel, ChangeSummaryManager.buildPropertyValueChangesECSql(iModel, instanceChange, ChangedValueState.BeforeUpdate)); assert.equal(rows.length, 1); instanceChange.before = rows[0]; rows = IModelTestUtils.executeQuery(iModel, ChangeSummaryManager.buildPropertyValueChangesECSql(iModel, instanceChange, ChangedValueState.AfterUpdate)); assert.equal(rows.length, 1); instanceChange.after = rows[0]; break; } case ChangeOpCode.Delete: { const rows: any[] = IModelTestUtils.executeQuery(iModel, ChangeSummaryManager.buildPropertyValueChangesECSql(iModel, instanceChange, ChangedValueState.BeforeDelete)); assert.equal(rows.length, 1); instanceChange.before = rows[0]; break; } default: throw new Error(`Unexpected ChangedOpCode ${instanceChange.opCode}`); } content.instanceChanges.push(instanceChange); } }); return content; } describe("ChangeSummary", () => { let accessToken: AccessToken; let iTwinId: string; let iModelId: GuidString; before(async () => { accessToken = await HubUtility.getAccessToken(TestUserType.Regular); iTwinId = await HubUtility.getTestITwinId(accessToken); iModelId = await HubUtility.getTestIModelId(accessToken, HubUtility.testIModelNames.readOnly); await HubWrappers.purgeAcquiredBriefcasesById(accessToken, iModelId); // Purge briefcases that are close to reaching the acquire limit const managerRequestContext = await HubUtility.getAccessToken(TestUserType.Manager); await HubWrappers.purgeAcquiredBriefcasesById(managerRequestContext, iModelId); }); it("Attach / Detach ChangeCache file to closed imodel", async () => { setupTest(iModelId); const iModel = await HubWrappers.downloadAndOpenCheckpoint({ accessToken, iTwinId, iModelId }); iModel.close(); assert.exists(iModel); assert.throw(() => ChangeSummaryManager.isChangeCacheAttached(iModel)); assert.throw(() => ChangeSummaryManager.attachChangeCache(iModel)); }); it("Extract ChangeSummaries", async () => { setupTest(iModelId); const summaryIds = await ChangeSummaryManager.createChangeSummaries({ accessToken, iTwinId, iModelId, range: { first: 0 } }); const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId }); assert.exists(iModel); try { ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); iModel.withPreparedStatement("SELECT ECInstanceId,ECClassId,ExtendedProperties FROM change.ChangeSummary ORDER BY ECInstanceId", (myStmt) => { let rowCount: number = 0; while (myStmt.step() === DbResult.BE_SQLITE_ROW) { rowCount++; const row: any = myStmt.getRow(); assert.equal(row.className, "ECDbChange.ChangeSummary"); assert.isUndefined(row.extendedProperties, "ChangeSummary.ExtendedProperties is not expected to be populated when change summaries are extracted."); } assert.isAtLeast(rowCount, 3); }); iModel.withPreparedStatement("SELECT ECClassId,Summary,WsgId,ParentWsgId,Description,PushDate,UserCreated FROM imodelchange.ChangeSet ORDER BY Summary.Id", (myStmt) => { let rowCount: number = 0; while (myStmt.step() === DbResult.BE_SQLITE_ROW) { rowCount++; const row: any = myStmt.getRow(); assert.equal(row.className, "IModelChange.ChangeSet"); assert.equal(row.summary.id, summaryIds[rowCount - 1]); assert.equal(row.summary.relClassName, "IModelChange.ChangeSummaryIsExtractedFromChangeset"); assert.isDefined(row.pushDate, "IModelChange.ChangeSet.PushDate is expected to be set for the changesets used in this test."); assert.isDefined(row.userCreated, "IModelChange.ChangeSet.UserCreated is expected to be set for the changesets used in this test."); // the other properties are not used, but using them in the ECSQL is important to verify preparation works } assert.isAtLeast(rowCount, 3); }); } finally { await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); } }); it("Extract ChangeSummary for single changeset", async () => { setupTest(iModelId); const changeSets = await IModelHost.hubAccess.queryChangesets({ accessToken, iModelId }); assert.isAtLeast(changeSets.length, 3); // extract summary for second changeset const changesetId = changeSets[1].id; const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId }); try { assert.exists(iModel); await iModel.pullChanges({ accessToken, toIndex: changeSets[1].index }); // now extract change summary for that one changeset const summaryId = await ChangeSummaryManager.createChangeSummary(accessToken, iModel); assert.isTrue(Id64.isValidId64(summaryId)); assert.isTrue(IModelJsFs.existsSync(BriefcaseManager.getChangeCachePathName(iModelId))); assert.exists(iModel); ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); iModel.withPreparedStatement("SELECT WsgId, Summary, ParentWsgId, Description, PushDate, UserCreated FROM imodelchange.ChangeSet", (myStmt) => { assert.equal(myStmt.step(), DbResult.BE_SQLITE_ROW); const row: any = myStmt.getRow(); assert.isDefined(row.wsgId); assert.equal(row.wsgId, changesetId); assert.isDefined(row.summary); assert.equal(row.summary.id, summaryId); assert.isDefined(row.pushDate, "IModelChange.ChangeSet.PushDate is expected to be set for the changesets used in this test."); assert.isDefined(row.userCreated, "IModelChange.ChangeSet.UserCreated is expected to be set for the changesets used in this test."); // the other properties are not used, but using them in the ECSQL is important to verify preparation works assert.equal(myStmt.step(), DbResult.BE_SQLITE_DONE); }); } finally { await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); } }); it("Extracting ChangeSummaries for a range of changesets", async () => { setupTest(iModelId); const changesets = await IModelHost.hubAccess.queryChangesets({ accessToken, iModelId }); assert.isAtLeast(changesets.length, 3); const firstChangeSet = changesets[0]; const lastChangeSet = changesets[1]; const summaryIds = await ChangeSummaryManager.createChangeSummaries({ accessToken, iTwinId, iModelId, range: { first: firstChangeSet.index, end: lastChangeSet.index } }); assert.equal(summaryIds.length, 2); assert.isTrue(IModelJsFs.existsSync(BriefcaseManager.getChangeCachePathName(iModelId))); const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId, asOf: IModelVersion.asOfChangeSet(lastChangeSet.id).toJSON() }); try { assert.exists(iModel); ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); iModel.withPreparedStatement("SELECT WsgId, Summary, ParentWsgId, Description, PushDate, UserCreated FROM imodelchange.ChangeSet ORDER BY Summary.Id", (myStmt) => { assert.equal(myStmt.step(), DbResult.BE_SQLITE_ROW); let row: any = myStmt.getRow(); assert.isDefined(row.wsgId); // Change summaries are extracted from end to start, so order is inverse of changesets assert.equal(row.wsgId, firstChangeSet.id); assert.isDefined(row.summary); assert.equal(row.summary.id, summaryIds[0]); assert.isDefined(row.pushDate, "IModelChange.ChangeSet.PushDate is expected to be set for the changesets used in this test."); assert.isDefined(row.userCreated, "IModelChange.ChangeSet.UserCreated is expected to be set for the changesets used in this test."); // the other properties are not used, but using them in the ECSQL is important to verify preparation works assert.equal(myStmt.step(), DbResult.BE_SQLITE_ROW); row = myStmt.getRow(); assert.isDefined(row.wsgId); assert.equal(row.wsgId, lastChangeSet.id); assert.isDefined(row.summary); assert.equal(row.summary.id, summaryIds[1]); assert.isDefined(row.pushDate, "IModelChange.ChangeSet.PushDate is expected to be set for the changesets used in this test."); assert.isDefined(row.userCreated, "IModelChange.ChangeSet.UserCreated is expected to be set for the changesets used in this test."); }); } finally { await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); } }); it("Subsequent ChangeSummary extractions", async () => { setupTest(iModelId); const changesets = await IModelHost.hubAccess.queryChangesets({ accessToken, iModelId }); assert.isAtLeast(changesets.length, 3); // first extraction: just first changeset const firstChangesetId = changesets[0].id; let iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId }); try { assert.exists(iModel); await iModel.pullChanges({ accessToken, toIndex: changesets[0].index }); // now extract change summary for that one changeset const summaryId = await ChangeSummaryManager.createChangeSummary(accessToken, iModel); assert.isTrue(IModelJsFs.existsSync(BriefcaseManager.getChangeCachePathName(iModelId))); assert.exists(iModel); ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); iModel.withPreparedStatement("SELECT WsgId, Summary, ParentWsgId, Description, PushDate, UserCreated FROM imodelchange.ChangeSet", (myStmt) => { assert.equal(myStmt.step(), DbResult.BE_SQLITE_ROW); const row: any = myStmt.getRow(); assert.isDefined(row.wsgId); assert.equal(row.wsgId, firstChangesetId); assert.isDefined(row.summary); assert.equal(row.summary.id, summaryId); assert.isDefined(row.pushDate, "IModelChange.ChangeSet.PushDate is expected to be set for the changesets used in this test."); assert.isDefined(row.userCreated, "IModelChange.ChangeSet.UserCreated is expected to be set for the changesets used in this test."); // the other properties are not used, but using them in the ECSQL is important to verify preparation works assert.equal(myStmt.step(), DbResult.BE_SQLITE_DONE); }); // now do second extraction for last changeset const lastChangesetId: string = changesets[changesets.length - 1].id; await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId, asOf: IModelVersion.asOfChangeSet(lastChangesetId).toJSON() }); // WIP not working yet until cache can be detached. // await iModel.pullChanges(accessToken, IModelVersion.asOfChangeSet(lastChangesetId)); await ChangeSummaryManager.createChangeSummary(accessToken, iModel); // WIP ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); iModel.withPreparedStatement("SELECT cset.WsgId changesetId FROM change.ChangeSummary csum JOIN imodelchange.ChangeSet cset ON csum.ECInstanceId=cset.Summary.Id ORDER BY csum.ECInstanceId", (myStmt) => { let rowCount: number = 0; while (myStmt.step() === DbResult.BE_SQLITE_ROW) { rowCount++; const row: any = myStmt.getRow(); assert.isDefined(row.changesetId); if (rowCount === 1) assert.equal(row.changesetId, firstChangesetId); else if (rowCount === 2) assert.equal(row.changesetId, lastChangesetId); } assert.equal(rowCount, 2); }); } finally { iModel.close(); } }); it("Query ChangeSummary content", async () => { const testIModelId: string = iModelId; setupTest(testIModelId); let perfLogger = new PerfLogger("CreateChangeSummaries"); await ChangeSummaryManager.createChangeSummaries({ accessToken, iTwinId, iModelId, range: { first: 0 } }); perfLogger.dispose(); perfLogger = new PerfLogger("IModelDb.open"); const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId }); perfLogger.dispose(); try { assert.exists(iModel); ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); const outDir = KnownTestLocations.outputDir; if (!IModelJsFs.existsSync(outDir)) IModelJsFs.mkdirSync(outDir); const changeSummaries = new Array<ChangeSummary>(); iModel.withPreparedStatement("SELECT ECInstanceId FROM ecchange.change.ChangeSummary ORDER BY ECInstanceId", (stmt) => { perfLogger = new PerfLogger("ChangeSummaryManager.queryChangeSummary"); while (stmt.step() === DbResult.BE_SQLITE_ROW) { const row = stmt.getRow(); const csum: ChangeSummary = ChangeSummaryManager.queryChangeSummary(iModel, Id64.fromJSON(row.id)); changeSummaries.push(csum); } perfLogger.dispose(); }); for (const changeSummary of changeSummaries) { const filePath = path.join(outDir, `imodelid_${iModelId}_changesummaryid_${changeSummary.id}.changesummary.json`); if (IModelJsFs.existsSync(filePath)) IModelJsFs.unlinkSync(filePath); const content = { id: changeSummary.id, changeSet: changeSummary.changeSet, instanceChanges: new Array<any>() }; iModel.withPreparedStatement("SELECT ECInstanceId FROM ecchange.change.InstanceChange WHERE Summary.Id=? ORDER BY ECInstanceId", (stmt) => { stmt.bindId(1, changeSummary.id); perfLogger = new PerfLogger(`ChangeSummaryManager.queryInstanceChange for all instances in ChangeSummary ${changeSummary.id}`); while (stmt.step() === DbResult.BE_SQLITE_ROW) { const row = stmt.getRow(); const instanceChange: any = ChangeSummaryManager.queryInstanceChange(iModel, Id64.fromJSON(row.id)); switch (instanceChange.opCode) { case ChangeOpCode.Insert: { const rows: any[] = IModelTestUtils.executeQuery(iModel, ChangeSummaryManager.buildPropertyValueChangesECSql(iModel, instanceChange, ChangedValueState.AfterInsert)); assert.equal(rows.length, 1); instanceChange.after = rows[0]; break; } case ChangeOpCode.Update: { let rows: any[] = IModelTestUtils.executeQuery(iModel, ChangeSummaryManager.buildPropertyValueChangesECSql(iModel, instanceChange, ChangedValueState.BeforeUpdate)); assert.equal(rows.length, 1); instanceChange.before = rows[0]; rows = IModelTestUtils.executeQuery(iModel, ChangeSummaryManager.buildPropertyValueChangesECSql(iModel, instanceChange, ChangedValueState.BeforeUpdate)); assert.equal(rows.length, 1); instanceChange.after = rows[0]; break; } case ChangeOpCode.Delete: { const rows: any[] = IModelTestUtils.executeQuery(iModel, ChangeSummaryManager.buildPropertyValueChangesECSql(iModel, instanceChange, ChangedValueState.BeforeDelete)); assert.equal(rows.length, 1); instanceChange.before = rows[0]; break; } default: throw new Error(`Unexpected ChangedOpCode ${instanceChange.opCode}`); } content.instanceChanges.push(instanceChange); } perfLogger.dispose(); }); IModelJsFs.writeFileSync(filePath, JSON.stringify(content)); } } finally { await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); } }); it.skip("Create ChangeSummaries for changes to parent elements", async () => { // Generate a unique name for the iModel (so that this test can be run simultaneously by multiple users+hosts simultaneously) const iModelName = IModelTestUtils.generateUniqueName("ParentElementChangeTest"); // Recreate iModel const managerRequestContext = await HubUtility.getAccessToken(TestUserType.Manager); const testITwinId = await HubUtility.getTestITwinId(managerRequestContext); const testIModelId = await HubWrappers.recreateIModel({ accessToken: managerRequestContext, iTwinId: testITwinId, iModelName, noLocks: true }); // Cleanup local cache setupTest(testIModelId); // Populate the iModel with 3 elements const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken: managerRequestContext, iTwinId: testITwinId, iModelId: testIModelId }); const [, modelId] = IModelTestUtils.createAndInsertPhysicalPartitionAndModel(iModel, IModelTestUtils.getUniqueModelCode(iModel, "TestPhysicalModel"), true); iModel.saveChanges("Added test model"); const categoryId = SpatialCategory.insert(iModel, IModel.dictionaryId, "TestSpatialCategory", new SubCategoryAppearance({ color: ColorDef.fromString("rgb(255,0,0)").toJSON() })); iModel.saveChanges("Added test category"); const elementId1: Id64String = iModel.elements.insertElement(IModelTestUtils.createPhysicalObject(iModel, modelId, categoryId)); const elementId2: Id64String = iModel.elements.insertElement(IModelTestUtils.createPhysicalObject(iModel, modelId, categoryId)); const elementId3: Id64String = iModel.elements.insertElement(IModelTestUtils.createPhysicalObject(iModel, modelId, categoryId)); iModel.saveChanges("Added test elements"); // Setup the hierarchy as element3 -> element1 const element3 = iModel.elements.getElement(elementId3); element3.parent = new ElementOwnsChildElements(elementId1); iModel.elements.updateElement(element3); iModel.saveChanges("Updated element1 as the parent of element3"); // Push changes to the hub await iModel.pushChanges({ accessToken: managerRequestContext, description: "Setup test model" }); // Modify the hierarchy to element3 -> element2 element3.parent = new ElementOwnsChildElements(elementId2); iModel.elements.updateElement(element3); iModel.saveChanges("Updated element2 as the parent of element3"); // Push changes to the hub await iModel.pushChanges({ accessToken: managerRequestContext, description: "Updated parent element" }); // Validate that the second change summary captures the change to the parent correctly try { const changeSummaryIds = await ChangeSummaryManager.extractChangeSummaries(accessToken, iModel); // eslint-disable-line deprecation/deprecation assert.strictEqual(2, changeSummaryIds.length); ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); const changeSummaryJson = getChangeSummaryAsJson(iModel, changeSummaryIds[0]); // console.log(JSON.stringify(changeSummaryJson, undefined, 2)); assert.strictEqual(changeSummaryJson.instanceChanges.length, 3); const instanceChange = changeSummaryJson.instanceChanges[0]; assert.strictEqual(instanceChange.changedInstance.id, elementId3); assert.strictEqual(instanceChange.changedInstance.className, "[Generic].[PhysicalObject]"); assert.strictEqual(instanceChange.before["parent.id"], elementId1); assert.strictEqual(instanceChange.after["parent.id"], elementId2); const modelChange = changeSummaryJson.instanceChanges[1]; assert.strictEqual(modelChange.changedInstance.id, modelId); assert.strictEqual(modelChange.changedInstance.className, "[BisCore].[PhysicalModel]"); assert.exists(modelChange.before.lastMod); assert.exists(modelChange.after.lastMod); const relInstanceChange = changeSummaryJson.instanceChanges[2]; assert.strictEqual(relInstanceChange.changedInstance.className, "[BisCore].[ElementOwnsChildElements]"); assert.strictEqual(relInstanceChange.before.sourceId, elementId1); assert.strictEqual(relInstanceChange.before.targetId, elementId3); assert.strictEqual(relInstanceChange.after.sourceId, elementId2); assert.strictEqual(relInstanceChange.after.targetId, elementId3); } finally { await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); } await IModelHost.hubAccess.deleteIModel({ accessToken, iTwinId: testITwinId, iModelId: testIModelId }); }); it.skip("should be able to extract the last change summary right after applying a change set", async () => { const userContext1 = await HubUtility.getAccessToken(TestUserType.Manager); const userContext2 = await HubUtility.getAccessToken(TestUserType.SuperManager); // User1 creates an iModel (on the Hub) const testUtility = new TestChangeSetUtility(userContext1, "ChangeSummaryTest"); await testUtility.createTestIModel(); // User2 opens the iModel const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken: userContext2, iTwinId: testUtility.iTwinId, iModelId: testUtility.iModelId }); // Attach change cache ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); // User1 pushes a change set await testUtility.pushTestChangeSet(); // User2 applies the change set and extracts the change summary await iModel.pullChanges({ accessToken: userContext2 }); const changeSummariesIds = await ChangeSummaryManager.extractChangeSummaries(userContext2, iModel, { currentVersionOnly: true }); // eslint-disable-line deprecation/deprecation if (changeSummariesIds.length !== 1) throw new Error("ChangeSet summary extraction returned invalid ChangeSet summary IDs."); const changeSummaryId = changeSummariesIds[0]; // const changeSummaryJson = getChangeSummaryAsJson(iModel, changeSummaryId); // console.log(JSON.stringify(changeSummaryJson, undefined, 2)); // eslint-disable-line iModel.withPreparedStatement( "SELECT ECInstanceId FROM ecchange.change.InstanceChange WHERE Summary.Id=? ORDER BY ECInstanceId", (sqlStatement: ECSqlStatement) => { sqlStatement.bindId(1, changeSummaryId); while (sqlStatement.step() === DbResult.BE_SQLITE_ROW) { const instanceChangeId = Id64.fromJSON(sqlStatement.getRow().id); const instanceChange = ChangeSummaryManager.queryInstanceChange(iModel, instanceChangeId); const changedInstanceClass = instanceChange.changedInstance.className; const isModelChange = changedInstanceClass === "[BisCore].[PhysicalModel]"; const changedInstanceOp = instanceChange.opCode; const changedPropertyValueNames = ChangeSummaryManager.getChangedPropertyValueNames(iModel, instanceChangeId); assert.isNotEmpty(changedInstanceClass); assert.strictEqual(isModelChange ? ChangeOpCode.Update : ChangeOpCode.Insert, changedInstanceOp); assert.isAbove(changedPropertyValueNames.length, 0); } }); }); it("Detaching and reattaching change cache", async () => { setupTest(iModelId); const changesets = await IModelHost.hubAccess.queryChangesets({ accessToken, iModelId }); const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId, asOf: IModelVersion.first().toJSON(), briefcaseId: 0 }); try { for (const changeset of changesets) { await iModel.pullChanges({ accessToken, toIndex: changeset.index }); const changeSummaryId = await ChangeSummaryManager.createChangeSummary(accessToken, iModel); ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); iModel.withPreparedStatement("SELECT WsgId, Summary FROM imodelchange.ChangeSet WHERE Summary.Id=?", (myStmt) => { myStmt.bindId(1, changeSummaryId); assert.equal(myStmt.step(), DbResult.BE_SQLITE_ROW); const row: any = myStmt.getRow(); assert.isDefined(row.wsgId); assert.equal(row.wsgId, changeset.id); assert.isDefined(row.summary); assert.equal(row.summary.id, changeSummaryId); }); for await (const row of iModel.query("SELECT WsgId, Summary FROM imodelchange.ChangeSet WHERE Summary.Id=?", QueryBinder.from([changeSummaryId]), QueryRowFormat.UseJsPropertyNames)) { assert.isDefined(row.wsgId); assert.equal(row.wsgId, changeset.id); assert.isDefined(row.summary); assert.equal(row.summary.id, changeSummaryId); } // Reattach caches and try queries again ChangeSummaryManager.detachChangeCache(iModel); assert.isFalse(ChangeSummaryManager.isChangeCacheAttached(iModel)); ChangeSummaryManager.attachChangeCache(iModel); assert.isTrue(ChangeSummaryManager.isChangeCacheAttached(iModel)); iModel.withPreparedStatement("SELECT WsgId, Summary FROM imodelchange.ChangeSet WHERE Summary.Id=?", (myStmt) => { myStmt.bindId(1, changeSummaryId); assert.equal(myStmt.step(), DbResult.BE_SQLITE_ROW); const row: any = myStmt.getRow(); assert.isDefined(row.wsgId); assert.equal(row.wsgId, changeset.id); assert.isDefined(row.summary); assert.equal(row.summary.id, changeSummaryId); }); for await (const row of iModel.query("SELECT WsgId, Summary FROM imodelchange.ChangeSet WHERE Summary.Id=?", QueryBinder.from([changeSummaryId]), QueryRowFormat.UseJsPropertyNames)) { assert.isDefined(row.wsgId); assert.equal(row.wsgId, changeset.id); assert.isDefined(row.summary); assert.equal(row.summary.id, changeSummaryId); } // Detach before the next creation ChangeSummaryManager.detachChangeCache(iModel); assert.isFalse(ChangeSummaryManager.isChangeCacheAttached(iModel)); } } finally { await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); } }); it("Create change summaries for all change sets", async () => { setupTest(iModelId); const summaryIds = await ChangeSummaryManager.createChangeSummaries({ accessToken, iTwinId, iModelId, range: { first: 0 } }); const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId }); try { ChangeSummaryManager.attachChangeCache(iModel); iModel.withPreparedStatement("SELECT ECInstanceId,ECClassId,ExtendedProperties FROM change.ChangeSummary ORDER BY ECInstanceId", (myStmt) => { let rowCount: number = 0; while (myStmt.step() === DbResult.BE_SQLITE_ROW) { rowCount++; const row: any = myStmt.getRow(); assert.equal(row.className, "ECDbChange.ChangeSummary"); } assert.isAtLeast(rowCount, 4); }); iModel.withPreparedStatement("SELECT ECClassId,Summary,WsgId,ParentWsgId,Description,PushDate,UserCreated FROM imodelchange.ChangeSet ORDER BY Summary.Id", (myStmt) => { let rowCount: number = 0; while (myStmt.step() === DbResult.BE_SQLITE_ROW) { rowCount++; const row: any = myStmt.getRow(); assert.equal(row.className, "IModelChange.ChangeSet"); assert.equal(row.summary.id, summaryIds[rowCount - 1]); assert.equal(row.summary.relClassName, "IModelChange.ChangeSummaryIsExtractedFromChangeset"); } assert.isAtLeast(rowCount, 4); }); } finally { ChangeSummaryManager.detachChangeCache(iModel); await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); } }); it("Create change summaries for just the latest change set", async () => { setupTest(iModelId); const first = (await IModelHost.hubAccess.getChangesetFromVersion({ accessToken, iModelId, version: IModelVersion.latest() })).index; const summaryIds = await ChangeSummaryManager.createChangeSummaries({ accessToken, iTwinId, iModelId, range: { first } }); const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken, iTwinId, iModelId }); try { ChangeSummaryManager.attachChangeCache(iModel); iModel.withPreparedStatement("SELECT ECInstanceId,ECClassId,ExtendedProperties FROM change.ChangeSummary ORDER BY ECInstanceId", (myStmt) => { let rowCount: number = 0; while (myStmt.step() === DbResult.BE_SQLITE_ROW) { rowCount++; const row: any = myStmt.getRow(); assert.equal(row.className, "ECDbChange.ChangeSummary"); } assert.strictEqual(rowCount, 1); }); iModel.withPreparedStatement("SELECT ECClassId,Summary,WsgId,ParentWsgId,Description,PushDate,UserCreated FROM imodelchange.ChangeSet ORDER BY Summary.Id", (myStmt) => { let rowCount: number = 0; while (myStmt.step() === DbResult.BE_SQLITE_ROW) { rowCount++; const row: any = myStmt.getRow(); assert.equal(row.className, "IModelChange.ChangeSet"); assert.equal(row.summary.id, summaryIds[rowCount - 1]); } assert.strictEqual(rowCount, 1); }); } finally { ChangeSummaryManager.detachChangeCache(iModel); await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); } }); it("Create change summaries for an invalid range of change sets", async () => { setupTest(iModelId); let errorThrown = false; const first = (await IModelHost.hubAccess.getChangesetFromVersion({ accessToken, iModelId, version: IModelVersion.latest() })).index; try { await ChangeSummaryManager.createChangeSummaries({ accessToken, iTwinId, iModelId, range: { first, end: 0 } }); } catch (err) { errorThrown = true; assert.isTrue(err instanceof IModelError); } assert.isTrue(errorThrown); }); });
the_stack
import { SharePointQueryable, SharePointQueryableCollection, SharePointQueryableInstance } from "./sharepointqueryable"; import { TextFileParser, BlobFileParser, JSONFileParser, BufferFileParser } from "../odata/parsers"; import { Util } from "../utils/util"; import { MaxCommentLengthException } from "../utils/exceptions"; import { LimitedWebPartManager } from "./webparts"; import { Item } from "./items"; import { SharePointQueryableShareableFile } from "./sharepointqueryableshareable"; import { spGetEntityUrl } from "./odata"; export interface ChunkedFileUploadProgressData { uploadId: string; stage: "starting" | "continue" | "finishing"; blockNumber: number; totalBlocks: number; chunkSize: number; currentPointer: number; fileSize: number; } /** * Describes a collection of File objects * */ export class Files extends SharePointQueryableCollection { /** * Creates a new instance of the Files class * * @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection */ constructor(baseUrl: string | SharePointQueryable, path = "files") { super(baseUrl, path); } /** * Gets a File by filename * * @param name The name of the file, including extension. */ public getByName(name: string): File { const f = new File(this); f.concat(`('${name}')`); return f; } /** * Uploads a file. Not supported for batching * * @param url The folder-relative url of the file. * @param content The file contents blob. * @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true) * @returns The new File and the raw response. */ public add(url: string, content: string | ArrayBuffer | Blob, shouldOverWrite = true): Promise<FileAddResult> { return new Files(this, `add(overwrite=${shouldOverWrite},url='${url}')`) .postCore({ body: content, }).then((response) => { return { data: response, file: this.getByName(url), }; }); } /** * Uploads a file. Not supported for batching * * @param url The folder-relative url of the file. * @param content The Blob file content to add * @param progress A callback function which can be used to track the progress of the upload * @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true) * @param chunkSize The size of each file slice, in bytes (default: 10485760) * @returns The new File and the raw response. */ public addChunked( url: string, content: Blob, progress?: (data: ChunkedFileUploadProgressData) => void, shouldOverWrite = true, chunkSize = 10485760, ): Promise<FileAddResult> { const adder = this.clone(Files, `add(overwrite=${shouldOverWrite},url='${url}')`, false); return adder.postCore() .then(() => this.getByName(url)) .then(file => file.setContentChunked(content, progress, chunkSize)); } /** * Adds a ghosted file to an existing list or document library. Not supported for batching. * * @param fileUrl The server-relative url where you want to save the file. * @param templateFileType The type of use to create the file. * @returns The template file that was added and the raw response. */ public addTemplateFile(fileUrl: string, templateFileType: TemplateFileType): Promise<FileAddResult> { return this.clone(Files, `addTemplateFile(urloffile='${fileUrl}',templatefiletype=${templateFileType})`, false) .postCore().then((response) => { return { data: response, file: this.getByName(fileUrl), }; }); } } /** * Describes a single File instance * */ export class File extends SharePointQueryableShareableFile { /** * Gets a value that specifies the list item field values for the list item corresponding to the file. * */ public get listItemAllFields(): SharePointQueryableCollection { return new SharePointQueryableCollection(this, "listItemAllFields"); } /** * Gets a collection of versions * */ public get versions(): Versions { return new Versions(this); } /** * Approves the file submitted for content approval with the specified comment. * Only documents in lists that are enabled for content approval can be approved. * * @param comment The comment for the approval. */ public approve(comment = ""): Promise<void> { return this.clone(File, `approve(comment='${comment}')`).postCore(); } /** * Stops the chunk upload session without saving the uploaded data. Does not support batching. * If the file doesn’t already exist in the library, the partially uploaded file will be deleted. * Use this in response to user action (as in a request to cancel an upload) or an error or exception. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. */ public cancelUpload(uploadId: string): Promise<void> { return this.clone(File, `cancelUpload(uploadId=guid'${uploadId}')`, false).postCore(); } /** * Checks the file in to a document library based on the check-in type. * * @param comment A comment for the check-in. Its length must be <= 1023. * @param checkinType The check-in type for the file. */ public checkin(comment = "", checkinType = CheckinType.Major): Promise<void> { if (comment.length > 1023) { throw new MaxCommentLengthException(); } return this.clone(File, `checkin(comment='${comment}',checkintype=${checkinType})`).postCore(); } /** * Checks out the file from a document library. */ public checkout(): Promise<void> { return this.clone(File, "checkout").postCore(); } /** * Copies the file to the destination url. * * @param url The absolute url or server relative url of the destination file path to copy to. * @param shouldOverWrite Should a file with the same name in the same location be overwritten? */ public copyTo(url: string, shouldOverWrite = true): Promise<void> { return this.clone(File, `copyTo(strnewurl='${url}',boverwrite=${shouldOverWrite})`).postCore(); } /** * Delete this file. * * @param eTag Value used in the IF-Match header, by default "*" */ public delete(eTag = "*"): Promise<void> { return this.clone(File, null).postCore({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); } /** * Denies approval for a file that was submitted for content approval. * Only documents in lists that are enabled for content approval can be denied. * * @param comment The comment for the denial. */ public deny(comment = ""): Promise<void> { if (comment.length > 1023) { throw new MaxCommentLengthException(); } return this.clone(File, `deny(comment='${comment}')`).postCore(); } /** * Specifies the control set used to access, modify, or add Web Parts associated with this Web Part Page and view. * An exception is thrown if the file is not an ASPX page. * * @param scope The WebPartsPersonalizationScope view on the Web Parts page. */ public getLimitedWebPartManager(scope = WebPartsPersonalizationScope.Shared): LimitedWebPartManager { return new LimitedWebPartManager(this, `getLimitedWebPartManager(scope=${scope})`); } /** * Moves the file to the specified destination url. * * @param url The absolute url or server relative url of the destination file path to move to. * @param moveOperations The bitwise MoveOperations value for how to move the file. */ public moveTo(url: string, moveOperations = MoveOperations.Overwrite): Promise<void> { return this.clone(File, `moveTo(newurl='${url}',flags=${moveOperations})`).postCore(); } /** * Submits the file for content approval with the specified comment. * * @param comment The comment for the published file. Its length must be <= 1023. */ public publish(comment = ""): Promise<void> { if (comment.length > 1023) { throw new MaxCommentLengthException(); } return this.clone(File, `publish(comment='${comment}')`).postCore(); } /** * Moves the file to the Recycle Bin and returns the identifier of the new Recycle Bin item. * * @returns The GUID of the recycled file. */ public recycle(): Promise<string> { return this.clone(File, "recycle").postCore(); } /** * Reverts an existing checkout for the file. * */ public undoCheckout(): Promise<void> { return this.clone(File, "undoCheckout").postCore(); } /** * Removes the file from content approval or unpublish a major version. * * @param comment The comment for the unpublish operation. Its length must be <= 1023. */ public unpublish(comment = ""): Promise<void> { if (comment.length > 1023) { throw new MaxCommentLengthException(); } return this.clone(File, `unpublish(comment='${comment}')`).postCore(); } /** * Gets the contents of the file as text. Not supported in batching. * */ public getText(): Promise<string> { return this.clone(File, "$value", false).get(new TextFileParser(), { headers: { "binaryStringResponseBody": "true" } }); } /** * Gets the contents of the file as a blob, does not work in Node.js. Not supported in batching. * */ public getBlob(): Promise<Blob> { return this.clone(File, "$value", false).get(new BlobFileParser(), { headers: { "binaryStringResponseBody": "true" } }); } /** * Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching. */ public getBuffer(): Promise<ArrayBuffer> { return this.clone(File, "$value", false).get(new BufferFileParser(), { headers: { "binaryStringResponseBody": "true" } }); } /** * Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching. */ public getJSON(): Promise<any> { return this.clone(File, "$value", false).get(new JSONFileParser(), { headers: { "binaryStringResponseBody": "true" } }); } /** * Sets the content of a file, for large files use setContentChunked. Not supported in batching. * * @param content The file content * */ public setContent(content: string | ArrayBuffer | Blob): Promise<File> { return this.clone(File, "$value", false).postCore({ body: content, headers: { "X-HTTP-Method": "PUT", }, }).then(_ => new File(this)); } /** * Gets the associated list item for this folder, loading the default properties */ public getItem<T>(...selects: string[]): Promise<Item & T> { const q = this.listItemAllFields; return q.select.apply(q, selects).get().then((d: any) => { return Util.extend(new Item(spGetEntityUrl(d)), d); }); } /** * Sets the contents of a file using a chunked upload approach. Not supported in batching. * * @param file The file to upload * @param progress A callback function which can be used to track the progress of the upload * @param chunkSize The size of each file slice, in bytes (default: 10485760) */ public setContentChunked( file: Blob, progress?: (data: ChunkedFileUploadProgressData) => void, chunkSize = 10485760, ): Promise<FileAddResult> { if (typeof progress === "undefined") { progress = () => null; } const fileSize = file.size; const blockCount = parseInt((file.size / chunkSize).toString(), 10) + ((file.size % chunkSize === 0) ? 1 : 0); const uploadId = Util.getGUID(); // start the chain with the first fragment progress({ uploadId, blockNumber: 1, chunkSize, currentPointer: 0, fileSize: fileSize, stage: "starting", totalBlocks: blockCount }); let chain = this.startUpload(uploadId, file.slice(0, chunkSize)); // skip the first and last blocks for (let i = 2; i < blockCount; i++) { chain = chain.then(pointer => { progress({ uploadId, blockNumber: i, chunkSize, currentPointer: pointer, fileSize, stage: "continue", totalBlocks: blockCount }); return this.continueUpload(uploadId, pointer, file.slice(pointer, pointer + chunkSize)); }); } return chain.then(pointer => { progress({ uploadId, blockNumber: blockCount, chunkSize, currentPointer: pointer, fileSize, stage: "finishing", totalBlocks: blockCount }); return this.finishUpload(uploadId, pointer, file.slice(pointer)); }); } /** * Starts a new chunk upload session and uploads the first fragment. * The current file content is not changed when this method completes. * The method is idempotent (and therefore does not change the result) as long as you use the same values for uploadId and stream. * The upload session ends either when you use the CancelUpload method or when you successfully * complete the upload session by passing the rest of the file contents through the ContinueUpload and FinishUpload methods. * The StartUpload and ContinueUpload methods return the size of the running total of uploaded data in bytes, * so you can pass those return values to subsequent uses of ContinueUpload and FinishUpload. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fragment The file contents. * @returns The size of the total uploaded data in bytes. */ protected startUpload(uploadId: string, fragment: ArrayBuffer | Blob): Promise<number> { return this.clone(File, `startUpload(uploadId=guid'${uploadId}')`, false) .postAsCore<string>({ body: fragment }) .then(n => { // When OData=verbose the payload has the following shape: // { StartUpload: "10485760" } if (typeof n === "object") { n = (n as any).StartUpload; } return parseFloat(n); }); } /** * Continues the chunk upload session with an additional fragment. * The current file content is not changed. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fileOffset The size of the offset into the file where the fragment starts. * @param fragment The file contents. * @returns The size of the total uploaded data in bytes. */ protected continueUpload(uploadId: string, fileOffset: number, fragment: ArrayBuffer | Blob): Promise<number> { return this.clone(File, `continueUpload(uploadId=guid'${uploadId}',fileOffset=${fileOffset})`, false) .postAsCore<string>({ body: fragment }) .then(n => { // When OData=verbose the payload has the following shape: // { ContinueUpload: "20971520" } if (typeof n === "object") { n = (n as any).ContinueUpload; } return parseFloat(n); }); } /** * Uploads the last file fragment and commits the file. The current file content is changed when this method completes. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fileOffset The size of the offset into the file where the fragment starts. * @param fragment The file contents. * @returns The newly uploaded file. */ protected finishUpload(uploadId: string, fileOffset: number, fragment: ArrayBuffer | Blob): Promise<FileAddResult> { return this.clone(File, `finishUpload(uploadId=guid'${uploadId}',fileOffset=${fileOffset})`, false) .postAsCore<{ ServerRelativeUrl: string }>({ body: fragment }) .then(response => { return { data: response, file: new File(response.ServerRelativeUrl), }; }); } } /** * Describes a collection of Version objects * */ export class Versions extends SharePointQueryableCollection { /** * Creates a new instance of the File class * * @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection */ constructor(baseUrl: string | SharePointQueryable, path = "versions") { super(baseUrl, path); } /** * Gets a version by id * * @param versionId The id of the version to retrieve */ public getById(versionId: number): Version { const v = new Version(this); v.concat(`(${versionId})`); return v; } /** * Deletes all the file version objects in the collection. * */ public deleteAll(): Promise<void> { return new Versions(this, "deleteAll").postCore(); } /** * Deletes the specified version of the file. * * @param versionId The ID of the file version to delete. */ public deleteById(versionId: number): Promise<void> { return this.clone(Versions, `deleteById(vid=${versionId})`).postCore(); } /** * Recycles the specified version of the file. * * @param versionId The ID of the file version to delete. */ public recycleByID(versionId: number): Promise<void> { return this.clone(Versions, `recycleByID(vid=${versionId})`).postCore(); } /** * Deletes the file version object with the specified version label. * * @param label The version label of the file version to delete, for example: 1.2 */ public deleteByLabel(label: string): Promise<void> { return this.clone(Versions, `deleteByLabel(versionlabel='${label}')`).postCore(); } /** * REcycles the file version object with the specified version label. * * @param label The version label of the file version to delete, for example: 1.2 */ public recycleByLabel(label: string): Promise<void> { return this.clone(Versions, `recycleByLabel(versionlabel='${label}')`).postCore(); } /** * Creates a new file version from the file specified by the version label. * * @param label The version label of the file version to restore, for example: 1.2 */ public restoreByLabel(label: string): Promise<void> { return this.clone(Versions, `restoreByLabel(versionlabel='${label}')`).postCore(); } } /** * Describes a single Version instance * */ export class Version extends SharePointQueryableInstance { /** * Delete a specific version of a file. * * @param eTag Value used in the IF-Match header, by default "*" */ public delete(eTag = "*"): Promise<void> { return this.postCore({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); } /** * Opens the file as a stream. */ public openBinaryStream(): Promise<string> { return this.clone(Version, "openBinaryStream").postCore(); } } export enum CheckinType { Minor = 0, Major = 1, Overwrite = 2, } export interface FileAddResult { file: File; data: any; } export enum WebPartsPersonalizationScope { User = 0, Shared = 1, } export enum MoveOperations { Overwrite = 1, AllowBrokenThickets = 8, } export enum TemplateFileType { StandardPage = 0, WikiPage = 1, FormPage = 2, ClientSidePage = 3, }
the_stack
import { Component, OnDestroy, OnInit } from '@angular/core'; import { AddonMessagesProvider, AddonMessagesMessagePreferences, AddonMessagesMessagePreferencesNotification, AddonMessagesMessagePreferencesNotificationProcessor, AddonMessages, } from '../../services/messages'; import { CoreUser } from '@features/user/services/user'; import { CoreApp } from '@services/app'; import { CoreConfig } from '@services/config'; import { CoreEvents } from '@singletons/events'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreConstants } from '@/core/constants'; import { IonRefresher } from '@ionic/angular'; /** * Page that displays the messages settings page. */ @Component({ selector: 'page-addon-messages-settings', templateUrl: 'settings.html', }) export class AddonMessagesSettingsPage implements OnInit, OnDestroy { protected updateTimeout?: number; preferences?: AddonMessagesMessagePreferences; preferencesLoaded = false; contactablePrivacy?: number | boolean; advancedContactable = false; // Whether the site supports "advanced" contactable privacy. allowSiteMessaging = false; onlyContactsValue = AddonMessagesProvider.MESSAGE_PRIVACY_ONLYCONTACTS; courseMemberValue = AddonMessagesProvider.MESSAGE_PRIVACY_COURSEMEMBER; siteValue = AddonMessagesProvider.MESSAGE_PRIVACY_SITE; groupMessagingEnabled = false; sendOnEnter = false; protected previousContactableValue?: number | boolean; constructor() { const currentSite = CoreSites.getCurrentSite(); this.advancedContactable = !!currentSite?.isVersionGreaterEqualThan('3.6'); this.allowSiteMessaging = !!currentSite?.canUseAdvancedFeature('messagingallusers'); this.groupMessagingEnabled = AddonMessages.isGroupMessagingEnabled(); this.asyncInit(); } protected async asyncInit(): Promise<void> { this.sendOnEnter = !!(await CoreConfig.get(CoreConstants.SETTINGS_SEND_ON_ENTER, !CoreApp.isMobile())); } /** * Runs when the page has loaded. This event only happens once per page being created. * If a page leaves but is cached, then this event will not fire again on a subsequent viewing. * Setup code for the page. */ ngOnInit(): void { this.fetchPreferences(); } /** * Fetches preference data. * * @return Promise resolved when done. */ protected async fetchPreferences(): Promise<void> { try { const preferences = await AddonMessages.getMessagePreferences(); if (this.groupMessagingEnabled) { // Simplify the preferences. for (const component of preferences.components) { // Only display get the notification preferences. component.notifications = component.notifications.filter((notification) => notification.preferencekey == AddonMessagesProvider.NOTIFICATION_PREFERENCES_KEY); component.notifications.forEach((notification) => { notification.processors.forEach( (processor: AddonMessagesMessagePreferencesNotificationProcessorFormatted) => { processor.checked = processor.loggedin.checked || processor.loggedoff.checked; }, ); }); } } this.preferences = preferences; this.contactablePrivacy = preferences.blocknoncontacts; this.previousContactableValue = this.contactablePrivacy; } catch (error) { CoreDomUtils.showErrorModal(error); } finally { this.preferencesLoaded = true; } } /** * Update preferences. The purpose is to store the updated data, it won't be reflected in the view. */ protected updatePreferences(): void { AddonMessages.invalidateMessagePreferences().finally(() => { this.fetchPreferences(); }); } /** * Update preferences after a certain time. The purpose is to store the updated data, it won't be reflected in the view. */ protected updatePreferencesAfterDelay(): void { // Cancel pending updates. clearTimeout(this.updateTimeout); this.updateTimeout = window.setTimeout(() => { this.updateTimeout = undefined; this.updatePreferences(); }, 5000); } /** * Save the contactable privacy setting.. * * @param value The value to set. */ async saveContactablePrivacy(value?: number | boolean): Promise<void> { if (this.contactablePrivacy == this.previousContactableValue) { // Value hasn't changed from previous, it probably means that we just fetched the value from the server. return; } const modal = await CoreDomUtils.showModalLoading('core.sending', true); if (!this.advancedContactable) { // Convert from boolean to number. value = value ? 1 : 0; } try { await CoreUser.updateUserPreference('message_blocknoncontacts', String(value)); // Update the preferences since they were modified. this.updatePreferencesAfterDelay(); this.previousContactableValue = this.contactablePrivacy; } catch (message) { // Show error and revert change. CoreDomUtils.showErrorModal(message); this.contactablePrivacy = this.previousContactableValue; } finally { modal.dismiss(); } } /** * Change the value of a certain preference. * * @param notification Notification object. * @param state State name, ['loggedin', 'loggedoff']. * @param processor Notification processor. */ async changePreference( notification: AddonMessagesMessagePreferencesNotificationFormatted, state: string, processor: AddonMessagesMessagePreferencesNotificationProcessorFormatted, ): Promise<void> { const valueArray: string[] = []; let value = 'none'; if (this.groupMessagingEnabled) { // Update both states at the same time. const promises: Promise<void>[] = []; notification.processors.forEach((processor: AddonMessagesMessagePreferencesNotificationProcessorFormatted) => { if (processor.checked) { valueArray.push(processor.name); } }); if (value.length > 0) { value = valueArray.join(','); } notification.updating = true; promises.push(CoreUser.updateUserPreference(notification.preferencekey + '_loggedin', value)); promises.push(CoreUser.updateUserPreference(notification.preferencekey + '_loggedoff', value)); try { await Promise.all(promises); // Update the preferences since they were modified. this.updatePreferencesAfterDelay(); } catch (error) { // Show error and revert change. CoreDomUtils.showErrorModal(error); processor.checked = !processor.checked; } finally { notification.updating = false; } return; } // Update only the specified state. const processorState = processor[state]; const preferenceName = notification.preferencekey + '_' + processorState.name; notification.processors.forEach((processor) => { if (processor[state].checked) { valueArray.push(processor.name); } }); if (value.length > 0) { value = valueArray.join(','); } if (!notification.updating) { notification.updating = {}; } notification.updating[state] = true; try { await CoreUser.updateUserPreference(preferenceName, value); // Update the preferences since they were modified. this.updatePreferencesAfterDelay(); } catch (error) { // Show error and revert change. CoreDomUtils.showErrorModal(error); processorState.checked = !processorState.checked; } finally { notification.updating[state] = false; } } /** * Refresh the list of preferences. * * @param refresher Refresher. */ refreshPreferences(refresher?: IonRefresher): void { AddonMessages.invalidateMessagePreferences().finally(() => { this.fetchPreferences().finally(() => { refresher?.complete(); }); }); } sendOnEnterChanged(): void { // Save the value. CoreConfig.set(CoreConstants.SETTINGS_SEND_ON_ENTER, this.sendOnEnter ? 1 : 0); // Notify the app. CoreEvents.trigger( CoreEvents.SEND_ON_ENTER_CHANGED, { sendOnEnter: !!this.sendOnEnter }, CoreSites.getCurrentSiteId(), ); } /** * Page destroyed. */ ngOnDestroy(): void { // If there is a pending action to update preferences, execute it right now. if (this.updateTimeout) { clearTimeout(this.updateTimeout); this.updatePreferences(); } } } /** * Message preferences notification with some caclulated data. */ type AddonMessagesMessagePreferencesNotificationFormatted = AddonMessagesMessagePreferencesNotification & { updating?: boolean | {[state: string]: boolean}; // Calculated in the app. Whether the notification is being updated. }; /** * Message preferences notification processor with some caclulated data. */ type AddonMessagesMessagePreferencesNotificationProcessorFormatted = AddonMessagesMessagePreferencesNotificationProcessor & { checked?: boolean; // Calculated in the app. Whether the processor is checked either for loggedin or loggedoff. };
the_stack
import * as z from 'zod'; import { Activity } from 'botframework-schema'; import { Configuration } from 'botbuilder-dialogs-adaptive-runtime-core'; import { AuthenticateRequestResult, AuthenticationConfiguration, AuthenticationConstants, BotFrameworkAuthentication, BotFrameworkAuthenticationFactory, BotFrameworkClient, ClaimsIdentity, ConnectorClientOptions, ConnectorFactory, ServiceClientCredentialsFactory, UserTokenClient, } from 'botframework-connector'; import { ConfigurationServiceClientCredentialFactory, ConfigurationServiceClientCredentialFactoryOptions, } from './configurationServiceClientCredentialFactory'; const TypedOptions = z .object({ /** * (Optional) The OAuth URL used to get a token from OAuthApiClient. The "OAuthUrl" member takes precedence over this value. */ [AuthenticationConstants.OAuthUrlKey]: z.string(), /** * (Optional) The OpenID metadata document used for authenticating tokens coming from the channel. The "ToBotFromChannelOpenIdMetadataUrl" member takes precedence over this value. */ [AuthenticationConstants.BotOpenIdMetadataKey]: z.string().nullable(), /** * A string used to indicate if which cloud the bot is operating in (e.g. Public Azure or US Government). * * @remarks * A `null` or `''` value indicates Public Azure, whereas [GovernmentConstants.ChannelService](xref:botframework-connector.GovernmentConstants.ChannelService) indicates the bot is operating in the US Government cloud. * * Other values result in a custom authentication configuration derived from the values passed in on the [ConfigurationBotFrameworkAuthenticationOptions](xef:botbuilder-core.ConfigurationBotFrameworkAuthenticationOptions) instance. */ [AuthenticationConstants.ChannelService]: z.string(), /** * Flag indicating whether or not to validate the address. */ ValidateAuthority: z.union([z.string(), z.boolean()]), /** * The Login URL used to specify the tenant from which the bot should obtain access tokens from. */ ToChannelFromBotLoginUrl: z.string(), /** * The Oauth scope to request. * * @remarks * This value is used when fetching a token to indicate the ultimate recipient or `audience` of an activity sent using these credentials. */ ToChannelFromBotOAuthScope: z.string(), /** * The Token issuer for signed requests to the channel. */ ToBotFromChannelTokenIssuer: z.string(), /** * The OAuth URL used to get a token from OAuthApiClient. */ OAuthUrl: z.string(), /** * The OpenID metadata document used for authenticating tokens coming from the channel. */ ToBotFromChannelOpenIdMetadataUrl: z.string(), /** * The The OpenID metadata document used for authenticating tokens coming from the Emulator. */ ToBotFromEmulatorOpenIdMetadataUrl: z.string(), /** * A value for the CallerId. */ CallerId: z.string(), }) .partial(); /** * Contains settings used to configure a [ConfigurationBotFrameworkAuthentication](xref:botbuilder-core.ConfigurationBotFrameworkAuthentication) instance. */ export type ConfigurationBotFrameworkAuthenticationOptions = z.infer<typeof TypedOptions>; /** * Creates a [BotFrameworkAuthentication](xref:botframework-connector.BotFrameworkAuthentication) instance from an object with the authentication values or a [Configuration](xref:botbuilder-dialogs-adaptive-runtime-core.Configuration) instance. */ export class ConfigurationBotFrameworkAuthentication extends BotFrameworkAuthentication { private readonly inner: BotFrameworkAuthentication; /** * Initializes a new instance of the [ConfigurationBotFrameworkAuthentication](xref:botbuilder-core.ConfigurationBotFrameworkAuthentication) class. * * @param botFrameworkAuthConfig A [ConfigurationBotFrameworkAuthenticationOptions](xref:botbuilder-core.ConfigurationBotFrameworkAuthenticationOptions) object. * @param credentialsFactory A [ServiceClientCredentialsFactory](xref:botframework-connector.ServiceClientCredentialsFactory) instance. * @param authConfiguration A [Configuration](xref:botframework-connector.AuthenticationConfiguration) object. * @param botFrameworkClientFetch A custom Fetch implementation to be used in the [BotFrameworkClient](xref:botframework-connector.BotFrameworkClient). * @param connectorClientOptions A [ConnectorClientOptions](xref:botframework-connector.ConnectorClientOptions) object. */ constructor( botFrameworkAuthConfig: ConfigurationBotFrameworkAuthenticationOptions = {}, credentialsFactory?: ServiceClientCredentialsFactory, authConfiguration?: AuthenticationConfiguration, botFrameworkClientFetch?: (input: RequestInfo, init?: RequestInit) => Promise<Response>, connectorClientOptions: ConnectorClientOptions = {} ) { super(); try { const typedBotFrameworkAuthConfig = TypedOptions.nonstrict().parse(botFrameworkAuthConfig); const { CallerId, ChannelService, OAuthUrl = typedBotFrameworkAuthConfig[AuthenticationConstants.OAuthUrlKey], ToBotFromChannelOpenIdMetadataUrl = typedBotFrameworkAuthConfig[ AuthenticationConstants.BotOpenIdMetadataKey ], ToBotFromChannelTokenIssuer, ToBotFromEmulatorOpenIdMetadataUrl, ToChannelFromBotLoginUrl, ToChannelFromBotOAuthScope, } = typedBotFrameworkAuthConfig; let ValidateAuthority = true; try { ValidateAuthority = Boolean(JSON.parse(`${typedBotFrameworkAuthConfig.ValidateAuthority ?? true}`)); } catch (_err) { // no-op } this.inner = BotFrameworkAuthenticationFactory.create( ChannelService, ValidateAuthority, ToChannelFromBotLoginUrl, ToChannelFromBotOAuthScope, ToBotFromChannelTokenIssuer, OAuthUrl, ToBotFromChannelOpenIdMetadataUrl, ToBotFromEmulatorOpenIdMetadataUrl, CallerId, credentialsFactory ?? new ConfigurationServiceClientCredentialFactory( typedBotFrameworkAuthConfig as ConfigurationServiceClientCredentialFactoryOptions ), authConfiguration ?? { requiredEndorsements: [] }, botFrameworkClientFetch, connectorClientOptions ); } catch (err) { // Throw a new error with the validation details prominently featured. if (z.instanceof(z.ZodError).check(err)) { throw new Error(JSON.stringify(err.errors, null, 2)); } throw err; } } authenticateChannelRequest(authHeader: string): Promise<ClaimsIdentity> { return this.inner.authenticateChannelRequest(authHeader); } authenticateRequest(activity: Activity, authHeader: string): Promise<AuthenticateRequestResult> { return this.inner.authenticateRequest(activity, authHeader); } authenticateStreamingRequest(authHeader: string, channelIdHeader: string): Promise<AuthenticateRequestResult> { return this.inner.authenticateStreamingRequest(authHeader, channelIdHeader); } createBotFrameworkClient(): BotFrameworkClient { return this.inner.createBotFrameworkClient(); } createConnectorFactory(claimsIdentity: ClaimsIdentity): ConnectorFactory { return this.inner.createConnectorFactory(claimsIdentity); } createUserTokenClient(claimsIdentity: ClaimsIdentity): Promise<UserTokenClient> { return this.inner.createUserTokenClient(claimsIdentity); } } /** * Creates a new instance of the [ConfigurationBotFrameworkAuthentication](xref:botbuilder-core.ConfigurationBotFrameworkAuthentication) class. * * @remarks * The [Configuration](xref:botbuilder-dialogs-adaptive-runtime-core.Configuration) instance provided to the constructor should * have the desired authentication values available at the root, using the properties of [ConfigurationBotFrameworkAuthenticationOptions](xref:botbuilder-core.ConfigurationBotFrameworkAuthenticationOptions) as its keys. * @param configuration A [Configuration](xref:botbuilder-dialogs-adaptive-runtime-core.Configuration) instance. * @param credentialsFactory A [ServiceClientCredentialsFactory](xref:botframework-connector.ServiceClientCredentialsFactory) instance. * @param authConfiguration A [Configuration](xref:botframework-connector.AuthenticationConfiguration) object. * @param botFrameworkClientFetch A custom Fetch implementation to be used in the [BotFrameworkClient](xref:botframework-connector.BotFrameworkClient). * @param connectorClientOptions A [ConnectorClientOptions](xref:botframework-connector.ConnectorClientOptions) object. * @returns A [ConfigurationBotFrameworkAuthentication](xref:botbuilder-core.ConfigurationBotFrameworkAuthentication) instance. */ export function createBotFrameworkAuthenticationFromConfiguration( configuration: Configuration, credentialsFactory?: ServiceClientCredentialsFactory, authConfiguration?: AuthenticationConfiguration, botFrameworkClientFetch?: (input: RequestInfo, init?: RequestInit) => Promise<Response>, connectorClientOptions: ConnectorClientOptions = {} ): BotFrameworkAuthentication { const botFrameworkAuthConfig = configuration?.get<ConfigurationBotFrameworkAuthenticationOptions>(); return new ConfigurationBotFrameworkAuthentication( botFrameworkAuthConfig, credentialsFactory, authConfiguration, botFrameworkClientFetch, connectorClientOptions ); }
the_stack
import { nextTick } from 'vue' import GlobalConfig from '../../v-x-e-table/src/conf' import XEUtils from 'xe-utils' import { getFuncText, eqEmptyValue } from '../../tools/utils' import { scrollToView } from '../../tools/dom' import { VxeGlobalHooksHandles, TableValidatorMethods, TableValidatorPrivateMethods, VxeTableDefines } from '../../../types/all' /** * 校验规则 */ class Rule { constructor (rule: any) { Object.assign(this, { $options: rule, required: rule.required, min: rule.min, max: rule.max, type: rule.type, pattern: rule.pattern, validator: rule.validator, trigger: rule.trigger, maxWidth: rule.maxWidth }) } /** * 获取校验不通过的消息 * 支持国际化翻译 */ get content () { return getFuncText(this.$options.content || this.$options.message) } get message () { return this.content } [key: string]: any } const tableValidatorMethodKeys: (keyof TableValidatorMethods)[] = ['fullValidate', 'validate', 'clearValidate'] const validatorHook: VxeGlobalHooksHandles.HookOptions = { setupTable ($xetable) { const { props, reactData, internalData } = $xetable const { refValidTooltip } = $xetable.getRefMaps() const { computeValidOpts, computeTreeOpts, computeEditOpts } = $xetable.getComputeMaps() let validatorMethods = {} as TableValidatorMethods let validatorPrivateMethods = {} as TableValidatorPrivateMethods let validRuleErr: boolean /** * 聚焦到校验通过的单元格并弹出校验错误提示 */ const handleValidError = (params: any): Promise<void> => { return new Promise(resolve => { const validOpts = computeValidOpts.value if (validOpts.autoPos === false) { $xetable.dispatchEvent('valid-error', params, null) resolve() } else { $xetable.handleActived(params, { type: 'valid-error', trigger: 'call' }).then(() => { setTimeout(() => { resolve(validatorPrivateMethods.showValidTooltip(params)) }, 10) }) } }) } /** * 对表格数据进行校验 * 如果不指定数据,则默认只校验临时变动的数据,例如新增或修改 * 如果传 true 则校验当前表格数据 * 如果传 row 指定行记录,则只验证传入的行 * 如果传 rows 为多行记录,则只验证传入的行 * 如果只传 callback 否则默认验证整个表格数据 * 返回 Promise 对象,或者使用回调方式 */ const beginValidate = (rows: any, cb: any, isFull?: boolean): Promise<any> => { const validRest: any = {} const { editRules, treeConfig } = props const { afterFullData } = internalData const treeOpts = computeTreeOpts.value const validOpts = computeValidOpts.value let vaildDatas if (rows === true) { vaildDatas = afterFullData } else if (rows) { if (XEUtils.isFunction(rows)) { cb = rows } else { vaildDatas = XEUtils.isArray(rows) ? rows : [rows] } } if (!vaildDatas) { if ($xetable.getInsertRecords) { vaildDatas = $xetable.getInsertRecords().concat($xetable.getUpdateRecords()) } else { vaildDatas = [] } } const rowValids: any = [] internalData._lastCallTime = Date.now() validRuleErr = false // 如果为快速校验,当存在某列校验不通过时将终止执行 validatorMethods.clearValidate() if (editRules) { const columns = $xetable.getColumns() const handleVaild = (row: any) => { if (isFull || !validRuleErr) { const colVailds: any[] = [] columns.forEach((column: any) => { if ((isFull || !validRuleErr) && XEUtils.has(editRules, column.property)) { colVailds.push( validatorPrivateMethods.validCellRules('all', row, column) .catch(({ rule, rules }: any) => { const rest = { rule, rules, rowIndex: $xetable.getRowIndex(row), row, columnIndex: $xetable.getColumnIndex(column), column, field: column.property, $table: $xetable } if (!validRest[column.property]) { validRest[column.property] = [] } validRest[column.property].push(rest) if (!isFull) { validRuleErr = true return Promise.reject(rest) } }) ) } }) rowValids.push(Promise.all(colVailds)) } } if (treeConfig) { XEUtils.eachTree(vaildDatas, handleVaild, treeOpts) } else { vaildDatas.forEach(handleVaild) } return Promise.all(rowValids).then(() => { const ruleProps = Object.keys(validRest) return nextTick().then(() => { if (ruleProps.length) { return Promise.reject(validRest[ruleProps[0]][0]) } if (cb) { cb() } }) }).catch(firstErrParams => { return new Promise<void>((resolve, reject) => { const finish = () => { nextTick(() => { if (cb) { cb(validRest) resolve() } else { if (GlobalConfig.validToReject === 'obsolete') { // 已废弃,校验失败将不会执行catch reject(validRest) } else { resolve(validRest) } } }) } const posAndFinish = () => { firstErrParams.cell = $xetable.getCell(firstErrParams.row, firstErrParams.column) scrollToView(firstErrParams.cell) handleValidError(firstErrParams).then(finish) } /** * 当校验不通过时 * 将表格滚动到可视区 * 由于提示信息至少需要占一行,定位向上偏移一行 */ const row = firstErrParams.row const rowIndex = afterFullData.indexOf(row) const locatRow = rowIndex > 0 ? afterFullData[rowIndex - 1] : row if (validOpts.autoPos === false) { finish() } else { if (treeConfig) { $xetable.scrollToTreeRow(locatRow).then(posAndFinish) } else { $xetable.scrollToRow(locatRow).then(posAndFinish) } } }) }) } return nextTick().then(() => { if (cb) { cb() } }) } validatorMethods = { /** * 完整校验,和 validate 的区别就是会给有效数据中的每一行进行校验 */ fullValidate (rows, cb) { return beginValidate(rows, cb, true) }, /** * 快速校验,如果存在记录不通过的记录,则返回不再继续校验(异步校验除外) */ validate (rows, cb) { return beginValidate(rows, cb) }, clearValidate () { const { validStore } = reactData const validTip = refValidTooltip.value Object.assign(validStore, { visible: false, row: null, column: null, content: '', rule: null }) if (validTip && validTip.reactData.visible) { validTip.close() } return nextTick() } } const validErrorRuleValue = (rule: VxeTableDefines.ValidatorRule, val: any) => { const { type, min, max, pattern } = rule const isNumType = type === 'number' const numVal = isNumType ? XEUtils.toNumber(val) : XEUtils.getSize(val) // 判断数值 if (isNumType && isNaN(val)) { return true } // 如果存在 min,判断最小值 if (!XEUtils.eqNull(min) && numVal < XEUtils.toNumber(min)) { return true } // 如果存在 max,判断最大值 if (!XEUtils.eqNull(max) && numVal > XEUtils.toNumber(max)) { return true } // 如果存在 pattern,正则校验 if (pattern && !(XEUtils.isRegExp(pattern) ? pattern : new RegExp(pattern)).test(val)) { return true } return false } validatorPrivateMethods = { /** * 校验数据 * 按表格行、列顺序依次校验(同步或异步) * 校验规则根据索引顺序依次校验,如果是异步则会等待校验完成才会继续校验下一列 * 如果校验失败则,触发回调或者Promise<不通过列的错误消息> * 如果是传回调方式这返回一个校验不通过列的错误消息 * * rule 配置: * required=Boolean 是否必填 * min=Number 最小长度 * max=Number 最大长度 * validator=Function({ cellValue, rule, rules, row, column, rowIndex, columnIndex }) 自定义校验,接收一个 Promise * trigger=blur|change 触发方式(除非特殊场景,否则默认为空就行) */ validCellRules (validType, row, column, val) { const { editRules } = props const { property } = column const errorRules: Rule[] = [] const syncVailds: Promise<any>[] = [] if (property && editRules) { const rules = XEUtils.get(editRules, property) if (rules) { const cellValue = XEUtils.isUndefined(val) ? XEUtils.get(row, property) : val rules.forEach((rule) => { const { type, trigger, required } = rule if (validType === 'all' || !trigger || validType === trigger) { if (XEUtils.isFunction(rule.validator)) { const customValid = rule.validator({ cellValue, rule, rules, row, rowIndex: $xetable.getRowIndex(row), column, columnIndex: $xetable.getColumnIndex(column), field: column.property, $table: $xetable }) if (customValid) { if (XEUtils.isError(customValid)) { validRuleErr = true errorRules.push(new Rule({ type: 'custom', trigger, content: customValid.message, rule: new Rule(rule) })) } else if (customValid.catch) { // 如果为异步校验(注:异步校验是并发无序的) syncVailds.push( customValid.catch((e: any) => { validRuleErr = true errorRules.push(new Rule({ type: 'custom', trigger, content: e && e.message ? e.message : (rule.content || rule.message), rule: new Rule(rule) })) }) ) } } } else { const isArrType = type === 'array' const hasEmpty = isArrType || XEUtils.isArray(cellValue) ? (!XEUtils.isArray(cellValue) || !cellValue.length) : eqEmptyValue(cellValue) if (required ? (hasEmpty || validErrorRuleValue(rule, cellValue)) : (!hasEmpty && validErrorRuleValue(rule, cellValue))) { validRuleErr = true errorRules.push(new Rule(rule)) } } } }) } } return Promise.all(syncVailds).then(() => { if (errorRules.length) { const rest = { rules: errorRules, rule: errorRules[0] } return Promise.reject(rest) } }) }, hasCellRules (type, row, column) { const { editRules } = props const { property } = column if (property && editRules) { const rules = XEUtils.get(editRules, property) return rules && !!XEUtils.find(rules, rule => type === 'all' || !rule.trigger || type === rule.trigger) } return false }, /** * 触发校验 */ triggerValidate (type) { const { editConfig, editRules } = props const { editStore, validStore } = reactData const { actived } = editStore const editOpts = computeEditOpts.value if (editConfig && editRules && actived.row) { const { row, column, cell } = actived.args if (validatorPrivateMethods.hasCellRules(type, row, column)) { return validatorPrivateMethods.validCellRules(type, row, column).then(() => { if (editOpts.mode === 'row') { if (validStore.visible && validStore.row === row && validStore.column === column) { validatorMethods.clearValidate() } } }).catch(({ rule }: any) => { // 如果校验不通过与触发方式一致,则聚焦提示错误,否则跳过并不作任何处理 if (!rule.trigger || type === rule.trigger) { const rest = { rule, row, column, cell } validatorPrivateMethods.showValidTooltip(rest) return Promise.reject(rest) } return Promise.resolve() }) } } return Promise.resolve() }, /** * 弹出校验错误提示 */ showValidTooltip (params) { const { height } = props const { tableData, validStore } = reactData const validOpts = computeValidOpts.value const { rule, row, column, cell } = params const validTip = refValidTooltip.value const content = rule.content return nextTick().then(() => { Object.assign(validStore, { row, column, rule, content, visible: true }) $xetable.dispatchEvent('valid-error', params, null) if (validTip && (validOpts.message === 'tooltip' || (validOpts.message === 'default' && !height && tableData.length < 2))) { return validTip.open(cell, content) } }) } } return { ...validatorMethods, ...validatorPrivateMethods } }, setupGrid ($xegrid) { return $xegrid.extendTableMethods(tableValidatorMethodKeys) } } export default validatorHook
the_stack
import type { DeepPath, Event, Listener, OptPathVal, Path, Path0, Path1, Path2, Path3, Path4, Path5, Path6, Path7, Path8, PathVal, Predicate2, Watch, } from "@thi.ng/api"; import { INotifyMixin } from "@thi.ng/api/mixins/inotify"; import { equiv } from "@thi.ng/equiv"; import { defGetterUnsafe } from "@thi.ng/paths/getter"; import { setInUnsafe } from "@thi.ng/paths/set-in"; import { updateInUnsafe } from "@thi.ng/paths/update-in"; import type { IAtom, IHistory, SwapFn } from "./api.js"; export const defHistory = <T>( state: IAtom<T>, maxLen?: number, changed?: Predicate2<T> ) => new History(state, maxLen, changed); /** * Undo/redo history stack wrapper for atoms and cursors. Implements * {@link IAtom} interface and so can be used directly in place and * delegates to wrapped atom/cursor. * * @remarks * Value changes are only recorded in history if `changed` predicate * returns truthy value, or else by calling {@link History.record} * directly. This class too implements the {@link @thi.ng/api#INotify} * interface to support event listeners for {@link History.undo}, * {@link History.redo} and {@link History.record}. */ @INotifyMixin export class History<T> implements IHistory<T> { static readonly EVENT_UNDO = "undo"; static readonly EVENT_REDO = "redo"; static readonly EVENT_RECORD = "record"; state: IAtom<T>; maxLen: number; changed: Predicate2<T>; history!: T[]; future!: T[]; /** * @param state - parent state * @param maxLen - max size of undo stack * @param changed - predicate to determine changed values (default `!equiv(a,b)`) */ constructor(state: IAtom<T>, maxLen = 100, changed?: Predicate2<T>) { this.state = state; this.maxLen = maxLen; this.changed = changed || ((a: T, b: T) => !equiv(a, b)); this.clear(); } get value() { return this.deref(); } set value(val: T) { this.reset(val); } canUndo() { return this.history.length > 0; } canRedo() { return this.future.length > 0; } /** * Clears history & future stacks */ clear() { this.history = []; this.future = []; } /** * Attempts to re-apply most recent historical value to atom and * returns it if successful (i.e. there's a history). * * @remarks * Before the switch, first records the atom's current value into * the future stack (to enable {@link History.redo} feature). * Returns `undefined` if there's no history. * * If undo was possible, the `History.EVENT_UNDO` event is emitted * after the restoration with both the `prev` and `curr` (restored) * states provided as event value (and object with these two keys). * This allows for additional state handling to be executed, e.g. * application of the "Command pattern". See * {@link History.addListener} for registering event listeners. */ undo() { if (this.history.length) { const prev = this.state.deref(); this.future.push(prev); const curr = this.state.reset(this.history.pop()!); this.notify({ id: History.EVENT_UNDO, value: { prev, curr } }); return curr; } } /** * Attempts to re-apply most recent value from future stack to atom * and returns it if successful (i.e. there's a future). * * @remarks * Before the switch, first records the atom's current value into * the history stack (to enable {@link History.undo} feature). * Returns `undefined` if there's no future (so sad!). * * If redo was possible, the `History.EVENT_REDO` event is emitted * after the restoration with both the `prev` and `curr` (restored) * states provided as event value (and object with these two keys). * This allows for additional state handling to be executed, e.g. * application of the "Command pattern". See * {@link History.addListener} for registering event listeners. */ redo() { if (this.future.length) { const prev = this.state.deref(); this.history.push(prev); const curr = this.state.reset(this.future.pop()!); this.notify({ id: History.EVENT_REDO, value: { prev, curr } }); return curr; } } /** * `IReset.reset()` implementation. Delegates to wrapped * atom/cursor, but too applies `changed` predicate to determine if * there was a change and if the previous value should be recorded. * * @param val - replacement value */ reset(val: T) { const prev = this.state.deref(); this.state.reset(val); const changed = this.changed(prev, this.state.deref()); if (changed) { this.record(prev); } return val; } resetIn(path: Path0, val: T): T; resetIn<A>(path: Path1<T, A>, val: PathVal<T, [A]>): T; resetIn<A, B>(path: Path2<T, A, B>, val: PathVal<T, [A, B]>): T; resetIn<A, B, C>(path: Path3<T, A, B, C>, val: PathVal<T, [A, B, C]>): T; resetIn<A, B, C, D>( path: Path4<T, A, B, C, D>, val: PathVal<T, [A, B, C, D]> ): T; resetIn<A, B, C, D, E>( path: Path5<T, A, B, C, D, E>, val: PathVal<T, [A, B, C, D, E]> ): T; resetIn<A, B, C, D, E, F>( path: Path6<T, A, B, C, D, E, F>, val: PathVal<T, [A, B, C, D, E, F]> ): T; resetIn<A, B, C, D, E, F, G>( path: Path7<T, A, B, C, D, E, F, G>, val: PathVal<T, [A, B, C, D, E, F, G]> ): T; resetIn<A, B, C, D, E, F, G, H>( path: Path8<T, A, B, C, D, E, F, G, H>, val: PathVal<T, [A, B, C, D, E, F, G, H]> ): T; resetIn<A, B, C, D, E, F, G, H>( path: DeepPath<T, A, B, C, D, E, F, G, H>, val: any ): T; resetIn(path: Path, val: any) { const prev = this.state.deref(); const get = defGetterUnsafe(path); const prevV = get(prev); const curr = setInUnsafe(prev, path, val); this.state.reset(curr); this.changed(prevV, get(curr)) && this.record(prev); return curr; } resetInUnsafe(path: Path, val: any) { return this.resetIn(<any>path, val); } /** * `ISwap.swap()` implementation. Delegates to wrapped atom/cursor, * but too applies `changed` predicate to determine if there was a * change and if the previous value should be recorded. * * @param fn - update function * @param args - additional args passed to `fn` */ swap(fn: SwapFn<T, T>, ...args: any[]): T { return this.reset(fn(this.state.deref(), ...args)); } swapIn<A>(path: Path0, fn: SwapFn<T, T>, ...args: any[]): T; swapIn<A>( path: Path1<T, A>, fn: SwapFn<OptPathVal<T, [A]>, PathVal<T, [A]>>, ...args: any[] ): T; swapIn<A, B>( path: Path2<T, A, B>, fn: SwapFn<OptPathVal<T, [A, B]>, PathVal<T, [A, B]>>, ...args: any[] ): T; swapIn<A, B, C>( path: Path3<T, A, B, C>, fn: SwapFn<OptPathVal<T, [A, B, C]>, PathVal<T, [A, B, C]>>, ...args: any[] ): T; swapIn<A, B, C, D>( path: Path4<T, A, B, C, D>, fn: SwapFn<OptPathVal<T, [A, B, C, D]>, PathVal<T, [A, B, C, D]>>, ...args: any[] ): T; swapIn<A, B, C, D, E>( path: Path5<T, A, B, C, D, E>, fn: SwapFn<OptPathVal<T, [A, B, C, D, E]>, PathVal<T, [A, B, C, D, E]>>, ...args: any[] ): T; swapIn<A, B, C, D, E, F>( path: Path6<T, A, B, C, D, E, F>, fn: SwapFn< OptPathVal<T, [A, B, C, D, E, F]>, PathVal<T, [A, B, C, D, E, F]> >, ...args: any[] ): T; swapIn<A, B, C, D, E, F, G>( path: Path7<T, A, B, C, D, E, F, G>, fn: SwapFn< OptPathVal<T, [A, B, C, D, E, F, G]>, PathVal<T, [A, B, C, D, E, F, G]> >, ...args: any[] ): T; swapIn<A, B, C, D, E, F, G, H>( path: Path8<T, A, B, C, D, E, F, G, H>, fn: SwapFn< OptPathVal<T, [A, B, C, D, E, F, G, H]>, PathVal<T, [A, B, C, D, E, F, G, H]> >, ...args: any[] ): T; swapIn<A, B, C, D, E, F, G, H>( path: DeepPath<T, A, B, C, D, E, F, G, H>, fn: SwapFn<any, any>, ...args: any[] ): T; swapIn(path: Path, fn: SwapFn<any, any>, ...args: any[]) { const prev = this.state.deref(); const get = defGetterUnsafe(path); const prevV = get(prev); const curr = updateInUnsafe(this.state.deref(), path, fn, ...args); this.state.reset(curr); this.changed(prevV, get(curr)) && this.record(prev); return curr; } swapInUnsafe(path: Path, fn: SwapFn<any, any>, ...args: any[]) { return this.swapIn(<any>path, fn, ...args); } /** * Records given state in history. This method is only needed when * manually managing snapshots, i.e. when applying multiple swaps on * the wrapped atom directly, but not wanting to create an history * entry for each change. * * @remarks * **DO NOT call this explicitly if using {@link History.reset} / * {@link History.swap} etc.** * * If no `state` is given, uses the wrapped atom's current state * value (user code SHOULD always call without arg). * * If recording succeeded, the `History.EVENT_RECORD` event is * emitted with the recorded state provided as event value. * * @param state - state to record */ record(state?: T) { const history = this.history; const n = history.length; let ok = true; // check for arg given and not if `state == null` we want to // allow null/undefined as possible values if (!arguments.length) { state = this.state.deref(); ok = !n || this.changed(history[n - 1], state); } if (ok) { if (n >= this.maxLen) { history.shift(); } history.push(state!); this.notify({ id: History.EVENT_RECORD, value: state }); this.future.length = 0; } } /** * Returns wrapped atom's **current** value. */ deref(): T { return this.state.deref(); } /** * `IWatch.addWatch()` implementation. Delegates to wrapped * atom/cursor. * * @param id - watch ID * @param fn - watch function */ addWatch(id: string, fn: Watch<T>) { return this.state.addWatch(id, fn); } /** * `IWatch.removeWatch()` implementation. Delegates to wrapped * atom/cursor. * * @param id - watch iD */ removeWatch(id: string) { return this.state.removeWatch(id); } /** * `IWatch.notifyWatches()` implementation. Delegates to wrapped * atom/cursor. * * @param oldState - * @param newState - */ notifyWatches(oldState: T, newState: T) { return this.state.notifyWatches(oldState, newState); } release() { this.state.release(); delete (<any>this).state; return true; } /** {@inheritDoc @thi.ng/api#INotify.addListener} */ // @ts-ignore: mixin addListener(id: string, fn: Listener, scope?: any): boolean {} /** {@inheritDoc @thi.ng/api#INotify.removeListener} */ // @ts-ignore: mixin removeListener(id: string, fn: Listener, scope?: any): boolean {} /** {@inheritDoc @thi.ng/api#INotify.notify} */ // @ts-ignore: mixin notify(e: Event): void {} }
the_stack
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { BaseDialog, IDialogConfiguration } from '@microsoft/sp-dialog'; import { autobind, PrimaryButton, CommandButton, TextField, Label, DialogFooter, DialogContent, DialogType, Toggle, Spinner, SpinnerSize, Checkbox, Icon } from 'office-ui-fabric-react'; import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker"; import { ListPicker } from "@pnp/spfx-controls-react/lib/ListPicker"; import { LibsOrderBy } from "@pnp/spfx-controls-react/lib/services/ISPService"; import { sp, PermissionKind } from '@pnp/sp'; import { ExtensionContext } from '@microsoft/sp-extension-base'; import { Dialog } from '@microsoft/sp-dialog'; import { MSGraphClient } from '@microsoft/sp-http'; import { IMailMessage } from '../../interfaces/IMailMessage'; import html2canvas from 'html2canvas'; import styles from './MailDetailsDialog.module.scss'; interface IMailDetailsDialogContentProps { context: ExtensionContext; close: () => void; submit: (capturedDetails: IMailDetailsDialogContentState) => void; } interface IMailDetailsDialogContentState { sendTo: string; subject: string; message: string; sendToInternalUser: boolean; saveToSharePoint: boolean; selectedUserHasPermission: boolean; selectedLibrary: string; imageName: string; sendLink: boolean; status: JSX.Element; loading: boolean; } class MailDetailsDialogContent extends React.Component<IMailDetailsDialogContentProps, IMailDetailsDialogContentState> { constructor(props) { super(props); this.state = { sendTo: "", subject: "", message: "", sendToInternalUser: false, saveToSharePoint: false, selectedUserHasPermission: false, selectedLibrary: "", imageName: "", sendLink: false, status: null, loading: false }; } public render(): JSX.Element { return (<div className={styles.mailDetailsDialogRoot}> <DialogContent title="Send view" onDismiss={this.props.close} showCloseButton={true} type={DialogType.largeHeader} > <div className={styles.mailDetailsDialogContent}> <div className="ms-Grid"> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-u-sm12 ms-u-md12 ms-u-lg12"> <div className="ms-borderBase ms-fontColor-themePrimary" /> <Label className="ms-bgColor-themeLight ms-fontWeight-semibold">&nbsp;<Icon iconName="ContactCard" className="ms-IconExample" /> User related</Label> <Toggle defaultChecked={false} label="Send to Internal User" onText="Yes" offText="No" onChanged={this._onChangedInternal} /> <Label><Icon iconName="Contact" className="ms-IconExample" /> {this.state.sendToInternalUser ? " Choose a colleague" : " Type an email address (external user)"}</Label> { this.state.sendToInternalUser ? <PeoplePicker context={this.props.context} //Updated context in IPeoplePicker.d.ts to be of type ExtensionContext - not ideal will be submitting a PR soon titleText=" " personSelectionLimit={1} disabled={false} selectedItems={this._getPeoplePickerItems} showHiddenInUI={false} principleTypes={[PrincipalType.User]} /> : <TextField value={this.state.sendTo} onChanged={this._onChangedSendTo} iconProps={{ iconName: 'World' }} /> } { this.state.sendToInternalUser && this.state.selectedUserHasPermission ? <div> <br /> <Checkbox label="User has view permissions so, send link in mail instead?" onChange={this._onCheckboxChange.bind(this)} /> </div> : null } <br /> <div className="ms-borderBase ms-fontColor-themePrimary" /> <Label className="ms-bgColor-themeLight ms-fontWeight-semibold">&nbsp;<Icon iconName="Mail" className="ms-IconExample" /> Mail related</Label> <Label>The following email will be sent {this.state.sendLink ? " with link in the body." : " with image attached."}</Label> <Label><Icon iconName="Mail" className="ms-IconExample" /> Subject</Label> <TextField value={this.state.subject} onChanged={this._onChangedSubject} /> <Label><Icon iconName="TextField" className="ms-IconExample" /> Message</Label> <TextField multiline rows={4} value={this.state.message} onChanged={this._onChangedMessage} /> {!this.state.sendLink && <div> <Label><Icon iconName="Attach" className="ms-IconExample" /> Attachment name</Label> <TextField suffix=".png" value={this.state.imageName} onChanged={this._onChangedImageName} /> </div> } <br /> <div className="ms-borderBase ms-fontColor-themePrimary" /> <Label className="ms-bgColor-themeLight ms-fontWeight-semibold">&nbsp;<Icon iconName="SharepointLogo" className="ms-IconExample" /> SharePoint related</Label> <Toggle defaultChecked={false} label="Save to library" onText="Yes" offText="No" checked={this.state.saveToSharePoint} onChanged={this._onChangedSave} disabled={this.state.sendLink} /> { this.state.saveToSharePoint && <div> <Label><Icon iconName="FileImage" className="ms-IconExample" /> File name</Label> <TextField suffix=".png" value={this.state.imageName} onChanged={this._onChangedImageName} /> <Label><Icon iconName="DocLibrary" className="ms-IconExample" /> Library</Label> <ListPicker context={this.props.context} //Updated context in IListPicker.d.ts to be of type ExtensionContext - not ideal will be submitting a PR soon placeHolder="Select a library to save in" baseTemplate={101} includeHidden={false} multiSelect={false} orderBy={LibsOrderBy.Title} onSelectionChanged={this._onListPickerChange} /> </div> } <br /> {this.state.status} </div> </div> </div> </div> <DialogFooter> <PrimaryButton text='Submit' title='Submit' iconProps={{ iconName: 'SkypeCircleCheck' }} disabled={this.state.loading} onClick={() => { this.setState({ loading: true, status: <Spinner size={SpinnerSize.large} label='Loading...' /> }); this.props.submit(this.state); }} /> <CommandButton text='Cancel' title='Cancel' iconProps={{ iconName: 'StatusErrorFull' }} disabled={this.state.loading} onClick={this.props.close} /> </DialogFooter> </DialogContent> </div>); } @autobind private async _getPeoplePickerItems(items: any[]) { console.log('Items:', items); this.setState({ sendTo: items.length > 0 ? items[0].secondaryText : "", selectedUserHasPermission: items.length > 0 ? await sp.web.lists.getById(this.props.context.pageContext.list.id.toString()).userHasPermissions("i:0#.f|membership|" + items[0].secondaryText, PermissionKind.ViewListItems) : false, sendLink: false }) } @autobind private _onListPickerChange(list: string) { console.log("List:", list); this.setState({ selectedLibrary: list }) } @autobind private _onChangedSendTo(newValue: string): void { this.setState({ sendTo: newValue, }); } @autobind private _onChangedSubject(newValue: string): void { this.setState({ subject: newValue, }); } @autobind private _onChangedMessage(newValue: string): void { this.setState({ message: newValue, }); } @autobind private _onChangedSave(newValue: boolean): void { this.setState({ saveToSharePoint: newValue, }); } @autobind private _onChangedInternal(newValue: boolean): void { this.setState({ sendToInternalUser: newValue, sendTo: "" }); } @autobind private _onCheckboxChange(ev: React.FormEvent<HTMLElement>, newValue: boolean): void { console.log(newValue); this.setState({ sendLink: newValue, saveToSharePoint: newValue && false }); } @autobind private _onChangedImageName(newValue: string): void { this.setState({ imageName: newValue, }); } private _getErrorMessage(value: string): string { return (value == null || value.length == 0 || value.length >= 10) ? '' : `${value.length}.`; } } export default class MailDetailsDialog extends BaseDialog { public context: ExtensionContext; public render(): void { ReactDOM.render(<MailDetailsDialogContent context={this.context} close={this.close} submit={this._submit} />, this.domElement); } public getConfig(): IDialogConfiguration { return { isBlocking: false }; } @autobind private async _submit(capturedDetails: IMailDetailsDialogContentState): Promise<void> { const mailMessage: IMailMessage = { message: { subject: capturedDetails.subject, body: { contentType: "HTML", content: capturedDetails.message }, toRecipients: [ { emailAddress: { address: capturedDetails.sendTo } } ], attachments: [] }, saveToSentItems: false } if (capturedDetails.sendLink) { mailMessage.message.body.content += `<br/> Here is the <a href="${window.location.href}" target="_blank">Link</a>`; this.sendMail(mailMessage, capturedDetails.saveToSharePoint); } else { html2canvas(document.querySelector('.StandaloneList-innerContent')).then(async (canvas) => { let base64image = canvas.toDataURL('image/png'); let base64String = base64image.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''); !capturedDetails.sendLink && mailMessage.message.attachments.push( { "@odata.type": "#microsoft.graph.fileAttachment", name: `${capturedDetails.imageName}.png`, contentBytes: base64String } ); this.sendMail(mailMessage, capturedDetails.saveToSharePoint); if (capturedDetails.saveToSharePoint) { this.saveImageToSharePoint(base64String, capturedDetails.selectedLibrary, capturedDetails.imageName); } }); } } private async sendMail(mailMessage: IMailMessage, saveToSharePoint: boolean): Promise<void> { const graphClient: MSGraphClient = await this.context.msGraphClientFactory.getClient(); await graphClient .api(`me/sendMail`) .version("v1.0") .post(mailMessage, (err, res) => { if (err) { Dialog.alert(`Failed to send mail.`); } else { if (!saveToSharePoint) { console.log("Done"); Dialog.alert(`Mail sent.`); } } this.close(); }); } private async saveImageToSharePoint(base64String: string, selectedLibrary: string, imageName: string): Promise<void> { var binary_string = window.atob(base64String); var len = binary_string.length; var bytes = new Uint8Array(len); for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); } await sp.web.lists.getById(selectedLibrary).rootFolder .files.add(`${imageName}.png`, bytes.buffer, true) .then(() => { Dialog.alert("Mail sent and saved to SharePoint") this.close(); }); } }
the_stack
import React, { lazy } from 'react' import { ConfigurationReference, getConf, readConfObject, } from '@jbrowse/core/configuration' import { isAbortException, getSession, getContainingView, isSelectionContainer, } from '@jbrowse/core/util' import { getRpcSessionId } from '@jbrowse/core/util/tracks' import { BaseLinearDisplay, LinearGenomeViewModel, } from '@jbrowse/plugin-linear-genome-view' import { autorun, observable, when } from 'mobx' import { addDisposer, isAlive, types, getEnv, Instance } from 'mobx-state-tree' import PluginManager from '@jbrowse/core/PluginManager' import { AnyConfigurationSchemaType } from '@jbrowse/core/configuration/configurationSchema' import { FeatureStats } from '@jbrowse/core/util/stats' import { Feature } from '@jbrowse/core/util/simpleFeature' import { axisPropsFromTickScale } from 'react-d3-axis' import { getNiceDomain, getScale } from '../../util' import Tooltip from '../components/Tooltip' import { YScaleBar } from '../components/WiggleDisplayComponent' const SetMinMaxDlg = lazy(() => import('../components/SetMinMaxDialog')) const SetColorDlg = lazy(() => import('../components/SetColorDialog')) // fudge factor for making all labels on the YScalebar visible export const YSCALEBAR_LABEL_OFFSET = 5 // using a map because it preserves order const rendererTypes = new Map([ ['xyplot', 'XYPlotRenderer'], ['density', 'DensityRenderer'], ['line', 'LinePlotRenderer'], ]) function logb(x: number, y: number) { return Math.log(y) / Math.log(x) } function round(v: number, b = 1.5) { return (v >= 0 ? 1 : -1) * Math.pow(b, 1 + Math.floor(logb(b, Math.abs(v)))) } type LGV = LinearGenomeViewModel const stateModelFactory = ( pluginManager: PluginManager, configSchema: AnyConfigurationSchemaType, ) => types .compose( 'LinearWiggleDisplay', BaseLinearDisplay, types.model({ type: types.literal('LinearWiggleDisplay'), configuration: ConfigurationReference(configSchema), selectedRendering: types.optional(types.string, ''), resolution: types.optional(types.number, 1), fill: types.maybe(types.boolean), color: types.maybe(types.string), summaryScoreMode: types.maybe(types.string), rendererTypeNameState: types.maybe(types.string), scale: types.maybe(types.string), autoscale: types.maybe(types.string), displayCrossHatches: types.maybe(types.boolean), constraints: types.optional( types.model({ max: types.maybe(types.number), min: types.maybe(types.number), }), {}, ), }), ) .volatile(() => ({ ready: false, message: undefined as undefined | string, stats: observable({ scoreMin: 0, scoreMax: 50 }), statsFetchInProgress: undefined as undefined | AbortController, })) .actions(self => ({ updateStats(stats: { scoreMin: number; scoreMax: number }) { self.stats.scoreMin = stats.scoreMin self.stats.scoreMax = stats.scoreMax self.ready = true }, setColor(color: string) { self.color = color }, setLoading(aborter: AbortController) { const { statsFetchInProgress: statsFetch } = self if (statsFetch !== undefined && !statsFetch.signal.aborted) { statsFetch.abort() } self.statsFetchInProgress = aborter }, // this overrides the BaseLinearDisplayModel to avoid popping up a // feature detail display, but still sets the feature selection on the // model so listeners can detect a click selectFeature(feature: Feature) { const session = getSession(self) if (isSelectionContainer(session)) { session.setSelection(feature) } }, setResolution(res: number) { self.resolution = res }, setFill(fill: boolean) { self.fill = fill }, toggleLogScale() { if (self.scale !== 'log') { self.scale = 'log' } else { self.scale = 'linear' } }, setScaleType(scale?: string) { self.scale = scale }, setSummaryScoreMode(val: string) { self.summaryScoreMode = val }, setAutoscale(val: string) { self.autoscale = val }, setMaxScore(val?: number) { self.constraints.max = val }, setRendererType(val: string) { self.rendererTypeNameState = val }, setMinScore(val?: number) { self.constraints.min = val }, toggleCrossHatches() { self.displayCrossHatches = !self.displayCrossHatches }, setCrossHatches(cross: boolean) { self.displayCrossHatches = cross }, })) .views(self => ({ get TooltipComponent(): React.FC { return Tooltip as unknown as React.FC }, get adapterTypeName() { return self.adapterConfig.type }, get rendererTypeName() { const viewName = self.rendererTypeNameState || getConf(self, 'defaultRendering') const rendererType = rendererTypes.get(viewName) if (!rendererType) { throw new Error(`unknown alignments view name ${viewName}`) } return rendererType }, // subclasses can define these, as snpcoverage track does get filters() { return undefined }, get scaleType() { return self.scale || getConf(self, 'scaleType') }, get filled() { return typeof self.fill !== 'undefined' ? self.fill : readConfObject(this.rendererConfig, 'filled') }, get maxScore() { const { max } = self.constraints return max !== undefined ? max : getConf(self, 'maxScore') }, get minScore() { const { min } = self.constraints return min !== undefined ? min : getConf(self, 'minScore') }, get rendererConfig() { const configBlob = getConf(self, ['renderers', this.rendererTypeName]) || {} return self.rendererType.configSchema.create( { ...configBlob, filled: self.fill, scaleType: this.scaleType, displayCrossHatches: self.displayCrossHatches, summaryScoreMode: self.summaryScoreMode, color: self.color, }, getEnv(self), ) }, })) .views(self => { let oldDomain: [number, number] = [0, 0] return { get summaryScoreModeSetting() { return ( self.summaryScoreMode || readConfObject(self.rendererConfig, 'summaryScoreMode') ) }, get domain() { const { stats, scaleType, minScore, maxScore } = self const ret = getNiceDomain({ domain: [stats.scoreMin, stats.scoreMax], bounds: [minScore, maxScore], scaleType, }) const headroom = getConf(self, 'headroom') || 0 // avoid weird scalebar if log value and empty region displayed if (scaleType === 'log' && ret[1] === Number.MIN_VALUE) { return [0, Number.MIN_VALUE] } // heuristic to just give some extra headroom on bigwig scores if no // maxScore/minScore specified (they have MAX_VALUE/MIN_VALUE if so) if (maxScore === Number.MAX_VALUE && ret[1] > 1.0) { ret[1] = round(ret[1] + headroom) } if (minScore === Number.MIN_VALUE && ret[0] < -1.0) { ret[0] = round(ret[0] - headroom) } // avoid returning a new object if it matches the old value if (JSON.stringify(oldDomain) !== JSON.stringify(ret)) { oldDomain = ret } return oldDomain }, get needsScalebar() { return ( self.rendererTypeName === 'XYPlotRenderer' || self.rendererTypeName === 'LinePlotRenderer' ) }, get scaleOpts() { return { domain: this.domain, stats: self.stats, autoscaleType: this.autoscaleType, scaleType: self.scaleType, inverted: getConf(self, 'inverted'), } }, get canHaveFill() { return self.rendererTypeName === 'XYPlotRenderer' }, get autoscaleType() { return self.autoscale || getConf(self, 'autoscale') }, get displayCrossHatchesSetting() { return ( self.displayCrossHatches || readConfObject(self.rendererConfig, 'displayCrossHatches') ) }, } }) .views(self => ({ get ticks() { const { scaleType, domain, height } = self const range = [height - YSCALEBAR_LABEL_OFFSET, YSCALEBAR_LABEL_OFFSET] const scale = getScale({ scaleType, domain, range, inverted: getConf(self, 'inverted'), }) const ticks = height < 50 ? 2 : 4 return axisPropsFromTickScale(scale, ticks) }, })) .views(self => { const { renderProps: superRenderProps } = self return { renderProps() { return { ...superRenderProps(), notReady: !self.ready, rpcDriverName: self.rpcDriverName, displayModel: self, config: self.rendererConfig, scaleOpts: self.scaleOpts, resolution: self.resolution, height: self.height, ticks: self.ticks, displayCrossHatches: self.displayCrossHatches, filters: self.filters, } }, get adapterCapabilities() { return pluginManager.getAdapterType(self.adapterTypeName) .adapterCapabilities }, get hasResolution() { return this.adapterCapabilities.includes('hasResolution') }, get hasGlobalStats() { return this.adapterCapabilities.includes('hasGlobalStats') }, } }) .views(self => { const { trackMenuItems: superTrackMenuItems } = self return { trackMenuItems() { return [ ...superTrackMenuItems(), ...(self.hasResolution ? [ { label: 'Resolution', subMenu: [ { label: 'Finer resolution', onClick: () => { self.setResolution(self.resolution * 5) }, }, { label: 'Coarser resolution', onClick: () => { self.setResolution(self.resolution / 5) }, }, ], }, { label: 'Summary score mode', subMenu: ['min', 'max', 'avg', 'whiskers'].map(elt => { return { label: elt, onClick: () => self.setSummaryScoreMode(elt), } }), }, ] : []), ...(self.canHaveFill ? [ { label: self.filled ? 'Turn off histogram fill' : 'Turn on histogram fill', onClick: () => { self.setFill(!self.filled) }, }, ] : []), { label: self.scaleType === 'log' ? 'Set linear scale' : 'Set log scale', onClick: () => { self.toggleLogScale() }, }, { type: 'checkbox', label: 'Draw cross hatches', checked: self.displayCrossHatchesSetting, onClick: () => { self.toggleCrossHatches() }, }, ...(Object.keys(getConf(self, 'renderers') || {}).length > 1 ? [ { label: 'Renderer type', subMenu: [...rendererTypes.keys()].map(key => ({ label: key, onClick: () => self.setRendererType(key), })), }, ] : []), { label: 'Autoscale type', subMenu: [ ['local', 'Local'], ...(self.hasGlobalStats ? [ ['global', 'Global'], ['globalsd', 'Global ± 3σ'], ] : []), ['localsd', 'Local ± 3σ'], ].map(([val, label]) => { return { label, onClick() { self.setAutoscale(val) }, } }), }, { label: 'Set min/max score', onClick: () => { getSession(self).queueDialog((doneCallback: Function) => [ SetMinMaxDlg, { model: self, handleClose: doneCallback }, ]) }, }, { label: 'Set color', onClick: () => { getSession(self).queueDialog((doneCallback: Function) => [ SetColorDlg, { model: self, handleClose: doneCallback }, ]) }, }, ] }, } }) .actions(self => { const { reload: superReload, renderSvg: superRenderSvg } = self type ExportSvgOpts = Parameters<typeof superRenderSvg>[0] async function getStats(opts: { headers?: Record<string, string> signal?: AbortSignal filters?: string[] }): Promise<FeatureStats> { const { rpcManager } = getSession(self) const nd = getConf(self, 'numStdDev') || 3 const { adapterConfig, autoscaleType } = self const sessionId = getRpcSessionId(self) const params = { sessionId, adapterConfig, statusCallback: (message: string) => { if (isAlive(self)) { self.setMessage(message) } }, ...opts, } if (autoscaleType === 'global' || autoscaleType === 'globalsd') { const results: FeatureStats = (await rpcManager.call( sessionId, 'WiggleGetGlobalStats', params, )) as FeatureStats const { scoreMin, scoreMean, scoreStdDev } = results // globalsd uses heuristic to avoid unnecessary scoreMin<0 // if the scoreMin is never less than 0 // helps with most coverage bigwigs just being >0 return autoscaleType === 'globalsd' ? { ...results, scoreMin: scoreMin >= 0 ? 0 : scoreMean - nd * scoreStdDev, scoreMax: scoreMean + nd * scoreStdDev, } : results } if (autoscaleType === 'local' || autoscaleType === 'localsd') { const { dynamicBlocks, bpPerPx } = getContainingView(self) as LGV const results = (await rpcManager.call( sessionId, 'WiggleGetMultiRegionStats', { ...params, regions: dynamicBlocks.contentBlocks.map(region => { const { start, end } = region return { ...JSON.parse(JSON.stringify(region)), start: Math.floor(start), end: Math.ceil(end), } }), bpPerPx, }, )) as FeatureStats const { scoreMin, scoreMean, scoreStdDev } = results // localsd uses heuristic to avoid unnecessary scoreMin<0 if the // scoreMin is never less than 0 helps with most coverage bigwigs // just being >0 return autoscaleType === 'localsd' ? { ...results, scoreMin: scoreMin >= 0 ? 0 : scoreMean - nd * scoreStdDev, scoreMax: scoreMean + nd * scoreStdDev, } : results } if (autoscaleType === 'zscale') { return rpcManager.call( sessionId, 'WiggleGetGlobalStats', params, ) as Promise<FeatureStats> } throw new Error(`invalid autoscaleType '${autoscaleType}'`) } return { // re-runs stats and refresh whole display on reload async reload() { self.setError() const aborter = new AbortController() let stats try { stats = await getStats({ signal: aborter.signal, filters: self.filters, }) if (isAlive(self)) { self.updateStats(stats) superReload() } } catch (e) { self.setError(e) } }, afterAttach() { addDisposer( self, autorun( async () => { try { const aborter = new AbortController() const view = getContainingView(self) as LGV self.setLoading(aborter) if (!view.initialized) { return } if (view.bpPerPx > self.maxViewBpPerPx) { return } const stats = await getStats({ signal: aborter.signal, filters: self.filters, }) if (isAlive(self)) { self.updateStats(stats) } } catch (e) { if (!isAbortException(e) && isAlive(self)) { console.error(e) self.setError(e) } } }, { delay: 1000 }, ), ) }, async renderSvg(opts: ExportSvgOpts) { await when(() => self.ready && !!self.regionCannotBeRenderedText) const { needsScalebar, stats } = self const { offsetPx } = getContainingView(self) as LGV return ( <> <g id="snpcov">{await superRenderSvg(opts)}</g> {needsScalebar && stats ? ( <g transform={`translate(${Math.max(-offsetPx, 0)})`}> <YScaleBar model={self as WiggleDisplayModel} orientation="left" /> </g> ) : null} </> ) }, } }) export type WiggleDisplayStateModel = ReturnType<typeof stateModelFactory> export type WiggleDisplayModel = Instance<WiggleDisplayStateModel> export default stateModelFactory
the_stack
import * as child_process from "child_process"; import * as stream from "stream"; import * as util from "util"; import EventEmitter = require("eventemitter3"); import * as common from "./common"; import * as log from "./log"; import * as config from "./config"; import * as apid from "../../api"; import status from "./status"; import Event from "./Event"; import ChannelItem from "./ChannelItem"; import TSFilter from "./TSFilter"; import Client, { ProgramsQuery } from "../client"; interface User extends common.User { _stream?: TSFilter; } interface Status { readonly index: number; readonly name: string; readonly types: common.ChannelType[]; readonly command: string; readonly pid: number; readonly users: common.User[]; readonly isAvailable: boolean; readonly isRemote: boolean; readonly isFree: boolean; readonly isUsing: boolean; readonly isFault: boolean; } export default class TunerDevice extends EventEmitter { private _channel: ChannelItem = null; private _command: string = null; private _process: child_process.ChildProcess = null; private _stream: stream.Readable = null; private _users = new Set<User>(); private _isAvailable = true; private _isRemote = false; private _isFault = false; private _fatalCount = 0; private _exited = false; private _closing = false; constructor(private _index: number, private _config: config.Tuner) { super(); this._isRemote = !!this._config.remoteMirakurunHost; Event.emit("tuner", "create", this.toJSON()); log.debug("TunerDevice#%d initialized", this._index); } get index(): number { return this._index; } get config(): config.Tuner { return this._config; } get channel(): ChannelItem { return this._channel; } get command(): string { return this._command; } get pid(): number { return this._process ? this._process.pid : null; } get users(): User[] { return [...this._users].map(user => { return { id: user.id, priority: user.priority, agent: user.agent, url: user.url, disableDecoder: user.disableDecoder, streamSetting: user.streamSetting, streamInfo: user.streamInfo }; }); } get decoder(): string { return this._config.decoder || null; } get isAvailable(): boolean { return this._isAvailable; } get isRemote(): boolean { return this._isRemote; } get isFree(): boolean { return this._isAvailable === true && this._channel === null && this._users.size === 0; } get isUsing(): boolean { return this._isAvailable === true && this._channel !== null && this._users.size !== 0; } get isFault(): boolean { return this._isFault; } getPriority(): number { let priority = -2; for (const user of this._users) { if (user.priority > priority) { priority = user.priority; } } return priority; } toJSON(): Status { return { index: this._index, name: this._config.name, types: this._config.types, command: this._command, pid: this.pid, users: this.users, isAvailable: this.isAvailable, isRemote: this.isRemote, isFree: this.isFree, isUsing: this.isUsing, isFault: this.isFault }; } async kill(): Promise<void> { await this._kill(true); } async startStream(user: User, stream: TSFilter, channel?: ChannelItem): Promise<void> { log.debug("TunerDevice#%d start stream for user `%s` (priority=%d)...", this._index, user.id, user.priority); if (this._isAvailable === false) { throw new Error(util.format("TunerDevice#%d is not available", this._index)); } if (!channel && !this._stream) { throw new Error(util.format("TunerDevice#%d has not stream", this._index)); } if (channel) { if (this._config.types.includes(channel.type) === false) { throw new Error(util.format("TunerDevice#%d is not supported for channel type `%s`", this._index, channel.type)); } if (this._stream) { if (channel.channel !== this._channel.channel) { if (user.priority <= this.getPriority()) { throw new Error(util.format("TunerDevice#%d has higher priority user", this._index)); } await this._kill(true); this._spawn(channel); } } else { this._spawn(channel); } } log.info("TunerDevice#%d streaming to user `%s` (priority=%d)", this._index, user.id, user.priority); user._stream = stream; this._users.add(user); if (stream.closed === true) { this.endStream(user); } else { stream.once("close", () => this.endStream(user)); } this._updated(); } endStream(user: User): void { log.debug("TunerDevice#%d end stream for user `%s` (priority=%d)...", this._index, user.id, user.priority); user._stream.end(); this._users.delete(user); if (this._users.size === 0) { setTimeout(() => { if (this._users.size === 0 && this._process) { this._kill(true).catch(log.error); } }, 3000); } log.info("TunerDevice#%d end streaming to user `%s` (priority=%d)", this._index, user.id, user.priority); this._updated(); } async getRemotePrograms(query?: ProgramsQuery): Promise<apid.Program[]> { if (!this._isRemote) { throw new Error(util.format("TunerDevice#%d is not remote device", this._index)); } const client = new Client(); client.host = this.config.remoteMirakurunHost; client.port = this.config.remoteMirakurunPort || 40772; client.userAgent = "Mirakurun (Remote)"; log.debug("TunerDevice#%d fetching remote programs from %s:%d...", this._index, client.host, client.port); const programs = await client.getPrograms(query); log.info("TunerDevice#%d fetched %d remote programs", this._index, programs.length); return programs; } private _spawn(ch: ChannelItem): void { log.debug("TunerDevice#%d spawn...", this._index); if (this._process) { throw new Error(util.format("TunerDevice#%d has process", this._index)); } let cmd: string; if (this._isRemote === true) { cmd = "node lib/remote"; cmd += " " + this._config.remoteMirakurunHost; cmd += " " + (this._config.remoteMirakurunPort || 40772); cmd += " " + ch.type; cmd += " " + ch.channel; if (this._config.remoteMirakurunDecoder === true) { cmd += " decode"; } } else { cmd = this._config.command; } cmd = cmd.replace("<channel>", ch.channel); if (ch.satellite) { cmd = cmd.replace("<satelite>", ch.satellite); // deprecated cmd = cmd.replace("<satellite>", ch.satellite); } // tslint:disable-next-line:prefer-conditional-expression if (ch.space) { cmd = cmd.replace("<space>", ch.space.toString(10)); } else { cmd = cmd.replace("<space>", "0"); // set default value to '0' } if (ch.freq !== undefined) { cmd = cmd.replace("<freq>", ch.freq.toString(10)); } if (ch.polarity) { cmd = cmd.replace("<polarity>", ch.polarity); } this._process = child_process.spawn(cmd.split(" ")[0], cmd.split(" ").slice(1)); this._command = cmd; this._channel = ch; if (this._config.dvbDevicePath) { const cat = child_process.spawn("cat", [this._config.dvbDevicePath]); cat.once("error", (err) => { log.error("TunerDevice#%d cat process error `%s` (pid=%d)", this._index, err.name, cat.pid); this._kill(false); }); cat.once("close", (code, signal) => { log.debug( "TunerDevice#%d cat process has closed with code=%d by signal `%s` (pid=%d)", this._index, code, signal, cat.pid ); if (this._exited === false) { this._kill(false); } }); this._process.once("exit", () => cat.kill("SIGKILL")); this._stream = cat.stdout; } else { this._stream = this._process.stdout; } this._process.once("exit", () => this._exited = true); this._process.once("error", (err) => { log.fatal("TunerDevice#%d process error `%s` (pid=%d)", this._index, err.name, this._process.pid); ++this._fatalCount; if (this._fatalCount >= 3) { log.fatal("TunerDevice#%d has something fault! **RESTART REQUIRED** after fix it.", this._index); this._isFault = true; this._closing = true; } this._end(); setTimeout(this._release.bind(this), this._config.dvbDevicePath ? 1000 : 100); }); this._process.once("close", (code, signal) => { log.info( "TunerDevice#%d process has closed with exit code=%d by signal `%s` (pid=%d)", this._index, code, signal, this._process.pid ); this._end(); setTimeout(this._release.bind(this), this._config.dvbDevicePath ? 1000 : 100); }); this._process.stderr.on("data", data => { log.debug("TunerDevice#%d > %s", this._index, data.toString().trim()); }); // flowing start this._stream.on("data", this._streamOnData.bind(this)); this._updated(); log.info("TunerDevice#%d process has spawned by command `%s` (pid=%d)", this._index, cmd, this._process.pid); } private _streamOnData(chunk: Buffer): void { for (const user of this._users) { user._stream.write(chunk); } } private _end(): void { this._isAvailable = false; this._stream.removeAllListeners("data"); if (this._closing === true) { for (const user of this._users) { user._stream.end(); } this._users.clear(); } this._updated(); } private async _kill(close: boolean): Promise<void> { log.debug("TunerDevice#%d kill...", this._index); if (!this._process || !this._process.pid) { throw new Error(util.format("TunerDevice#%d has not process", this._index)); } else if (this._closing) { log.debug("TunerDevice#%d return because it is closing", this._index); return; } this._isAvailable = false; this._closing = close; this._updated(); await new Promise<void>(resolve => { this.once("release", resolve); if (process.platform === "win32") { const timer = setTimeout(() => this._process.kill(), 3000); this._process.once("exit", () => clearTimeout(timer)); this._process.stdin.write("\n"); } else if (/^dvbv5-zap /.test(this._command) === true) { this._process.kill("SIGKILL"); } else { const timer = setTimeout(() => { log.warn("TunerDevice#%d will force killed because SIGTERM timed out...", this._index); this._process.kill("SIGKILL"); }, 6000); this._process.once("exit", () => clearTimeout(timer)); // regular way this._process.kill("SIGTERM"); } }); } private _release(): void { if (this._process) { this._process.stderr.removeAllListeners(); this._process.removeAllListeners(); } if (this._stream) { this._stream.removeAllListeners(); } this._command = null; this._process = null; this._stream = null; if (this._closing === false && this._users.size !== 0) { log.warn("TunerDevice#%d respawning because request has not closed", this._index); ++status.errorCount.tunerDeviceRespawn; this._spawn(this._channel); return; } this._fatalCount = 0; this._channel = null; this._users.clear(); if (this._isFault === false) { this._isAvailable = true; } this._closing = false; this._exited = false; this.emit("release"); log.info("TunerDevice#%d released", this._index); this._updated(); } private _updated(): void { Event.emit("tuner", "update", this.toJSON()); } }
the_stack
import { $TSObject, JSONUtilities } from 'amplify-cli-core'; import { addAuthIdentityPoolAndUserPoolWithOAuth, addAuthUserPoolOnlyWithOAuth, amplifyPushAuth, getBackendAmplifyMeta, getProjectMeta, getTeamProviderInfo, } from 'amplify-e2e-core'; import * as aws from 'aws-sdk'; import * as fs from 'fs-extra'; import _ from 'lodash'; import * as path from 'path'; import { v4 as uuid } from 'uuid'; import { AuthProjectDetails, createIDPAndUserPoolWithOAuthSettings, createUserPoolOnlyWithOAuthSettings, StorageProjectDetails } from '.'; import { AppClientSettings, DynamoDBProjectDetails } from './types'; export const getShortId = (): string => { const [shortId] = uuid().split('-'); return shortId; }; export const getAuthProjectDetails = (projectRoot: string): AuthProjectDetails => { const meta = getBackendAmplifyMeta(projectRoot); const team = getTeamProviderInfo(projectRoot); const authMetaKey = Object.keys(meta.auth) .filter(key => meta.auth[key].service === 'Cognito') .map(key => key)[0]; const authMeta = meta.auth[authMetaKey]; const authTeam = _.get(team, ['integtest', 'categories', 'auth', authMetaKey]); const providerTeam = _.get(team, ['integtest', 'awscloudformation']); const parameters = readResourceParametersJson(projectRoot, 'auth', authMetaKey); const result: AuthProjectDetails = { authResourceName: authMetaKey, parameters: { authSelections: parameters.authSelections, resourceName: parameters.userPoolName, }, meta: { UserPoolId: authMeta.output.UserPoolId, UserPoolName: authMeta.output.UserPoolName, AppClientID: authMeta.output.AppClientID, AppClientSecret: authMeta.output.AppClientSecret, AppClientIDWeb: authMeta.output.AppClientIDWeb, HostedUIDomain: authMeta.output.HostedUIDomain, OAuthMetadata: authMeta.output.OAuthMetadata ? JSON.parse(authMeta.output.OAuthMetadata) : undefined, }, team: { userPoolId: authTeam.userPoolId, userPoolName: authTeam.userPoolName, webClientId: authTeam.webClientId, nativeClientId: authTeam.nativeClientId, hostedUIProviderCreds: authTeam.hostedUIProviderCreds ? JSON.parse(authTeam.hostedUIProviderCreds) : undefined, }, }; if (result.parameters.authSelections === 'identityPoolAndUserPool') { result.meta = { ...result.meta, IdentityPoolId: authMeta.output.IdentityPoolId, IdentityPoolName: authMeta.output.IdentityPoolName, AmazonWebClient: authMeta.output.AmazonWebClient, FacebookWebClient: authMeta.output.FacebookWebClient, GoogleWebClient: authMeta.output.GoogleWebClient, }; result.team = { ...result.team, identityPoolId: authMeta.output.IdentityPoolId, identityPoolName: authMeta.output.IdentityPoolName, allowUnauthenticatedIdentities: parameters.allowUnauthenticatedIdentities, authRoleArn: providerTeam.AuthRoleArn, authRoleName: providerTeam.AuthRoleName, unauthRoleArn: providerTeam.UnauthRoleArn, unauthRoleName: providerTeam.UnauthRoleName, amazonAppId: authTeam.amazonAppId, facebookAppId: authTeam.facebookAppId, googleClientId: authTeam.googleClientId, }; } return result; }; export const getOGAuthProjectDetails = (projectRoot: string): AuthProjectDetails => { const meta = getBackendAmplifyMeta(projectRoot); const team = getTeamProviderInfo(projectRoot); const authMetaKey = Object.keys(meta.auth) .filter(key => meta.auth[key].service === 'Cognito') .map(key => key)[0]; const authMeta = meta.auth[authMetaKey]; const authTeam = _.get(team, ['integtest', 'categories', 'auth', authMetaKey]); const parameters = readResourceParametersJson(projectRoot, 'auth', authMetaKey); return { authResourceName: authMetaKey, parameters: { authSelections: parameters.authSelections, resourceName: parameters.userPoolName, }, meta: { UserPoolId: authMeta.output.UserPoolId, UserPoolName: authMeta.output.UserPoolName, AppClientID: authMeta.output.AppClientID, AppClientSecret: authMeta.output.AppClientSecret, AppClientIDWeb: authMeta.output.AppClientIDWeb, HostedUIDomain: authMeta.output.HostedUIDomain, OAuthMetadata: authMeta.output.OAuthMetadata ? JSON.parse(authMeta.output.OAuthMetadata) : undefined, IdentityPoolId: authMeta.output.IdentityPoolId, IdentityPoolName: authMeta.output.IdentityPoolName, }, team: { userPoolId: authMeta.output.UserPoolId, userPoolName: authMeta.output.UserPoolName, webClientId: authMeta.output.AppClientIDWeb, nativeClientId: authMeta.output.AppClientID, hostedUIProviderCreds: authTeam.hostedUIProviderCreds ? JSON.parse(authTeam.hostedUIProviderCreds) : undefined, }, }; }; export const readResourceParametersJson = (projectRoot: string, category: string, resourceName: string): $TSObject => { const parametersFilePath = path.join(projectRoot, 'amplify', 'backend', category, resourceName, 'parameters.json'); const parametersFileBuildPath = path.join(projectRoot, 'amplify', 'backend', category, resourceName, 'build', 'parameters.json'); if (fs.existsSync(parametersFilePath)) { return JSONUtilities.readJson(parametersFilePath); } else if (fs.existsSync(parametersFileBuildPath)) { return JSONUtilities.readJson(parametersFileBuildPath); } else { throw new Error(`parameters.json doesn't exist`); } }; export const readRootStack = (projectRoot: string): $TSObject => { const rootStackFilePath = path.join(projectRoot, 'amplify', 'backend', 'awscloudformation', 'build', 'root-cloudformation-stack.json'); const rootStack = JSONUtilities.readJson(rootStackFilePath); return rootStack; }; export const getOGStorageProjectDetails = (projectRoot: string): StorageProjectDetails => { const meta = getBackendAmplifyMeta(projectRoot); const storageMetaKey = Object.keys(meta.storage) .filter(key => meta.storage[key].service === 'S3') .map(key => key)[0]; const storageMeta = meta.storage[storageMetaKey]; const parameters = readResourceParametersJson(projectRoot, 'storage', storageMetaKey); return { storageResourceName: storageMetaKey, parameters: { resourceName: parameters.resourceName, }, meta: { BucketName: storageMeta.output.BucketName, Region: storageMeta.output.Region, }, }; }; export const getStorageProjectDetails = (projectRoot: string): StorageProjectDetails => { const meta = getBackendAmplifyMeta(projectRoot); const team = getTeamProviderInfo(projectRoot); const storageMetaKey = Object.keys(meta.storage) .filter(key => meta.storage[key].service === 'S3') .map(key => key)[0]; const stoargeMeta = meta.storage[storageMetaKey]; const storageTeam = _.get(team, ['integtest', 'categories', 'storage', storageMetaKey]); const parameters = readResourceParametersJson(projectRoot, 'storage', storageMetaKey); const result: StorageProjectDetails = { storageResourceName: storageMetaKey, parameters: { resourceName: parameters.userPoolName, }, meta: { BucketName: stoargeMeta.output.BucketName, Region: stoargeMeta.output.Region, }, team: { bucketName: storageTeam.bucketName, region: storageTeam.region, }, }; return result; }; export const getS3ResourceName = (projectRoot: string): string => { const amplifyMeta = getBackendAmplifyMeta(projectRoot); const s3ResourceName = Object.keys(amplifyMeta.storage).find((key: any) => { return amplifyMeta.storage[key].service === 'S3'; }) as any; return s3ResourceName; }; export const getOGDynamoDBProjectDetails = (projectRoot: string): DynamoDBProjectDetails => { const meta = getBackendAmplifyMeta(projectRoot); const storageMetaKey = Object.keys(meta.storage) .filter(key => meta.storage[key].service === 'DynamoDB') .map(key => key)[0]; const storageMeta = meta.storage[storageMetaKey]; const parameters = readResourceParametersJson(projectRoot, 'storage', storageMetaKey); return { storageResourceName: storageMetaKey, parameters: { resourceName: parameters.resourceName, }, meta: { Name: storageMeta.output.Name, Region: storageMeta.output.Region, PartitionKeyName: storageMeta.output.PartitionKeyName, PartitionKeyType: storageMeta.output.PartitionKeyType, SortKeyName: storageMeta.output.SortKeyName, SortKeyType: storageMeta.output.SortKeyType, Arn: storageMeta.output.Arn, StreamArn: storageMeta.output.StreamArn, }, }; }; export const getDynamoDBProjectDetails = (projectRoot: string): DynamoDBProjectDetails => { const meta = getBackendAmplifyMeta(projectRoot); const team = getTeamProviderInfo(projectRoot); const storageMetaKey = Object.keys(meta.storage) .filter(key => meta.storage[key].service === 'DynamoDB') .map(key => key)[0]; const dynamodbMeta = meta.storage[storageMetaKey]; const storageTeam = _.get(team, ['integtest', 'categories', 'storage', storageMetaKey]); const parameters = readResourceParametersJson(projectRoot, 'storage', storageMetaKey); return { storageResourceName: storageMetaKey, parameters: { resourceName: parameters.resourceName, }, meta: { Name: dynamodbMeta.output.Name, Region: dynamodbMeta.output.Region, PartitionKeyName: dynamodbMeta.output.PartitionKeyName, PartitionKeyType: dynamodbMeta.output.PartitionKeyType, SortKeyName: dynamodbMeta.output.SortKeyName, SortKeyType: dynamodbMeta.output.SortKeyType, Arn: dynamodbMeta.output.Arn, StreamArn: dynamodbMeta.output.StreamArn, }, team: { tableName: storageTeam.tableName, region: storageTeam.region, partitionKeyName: storageTeam.partitionKeyName, partitionKeyType: storageTeam.partitionKeyType, sortKeyName: storageTeam.sortKeyName, sortKeyType: storageTeam.sortKeyType, arn: storageTeam.arn, streamArn: storageTeam.streamArn, }, }; }; export const getDynamoDBResourceName = (projectRoot: string): string => { const amplifyMeta = getBackendAmplifyMeta(projectRoot); const dynamoDBResourceName = Object.keys(amplifyMeta.storage).find((key: any) => { return amplifyMeta.storage[key].service === 'DynamoDB'; }) as any; return dynamoDBResourceName; }; const addAppClient = async ( profileName: string, projectRoot: string, clientName: string, generateSecret: boolean, settings: AppClientSettings, ) => { const projectDetails = getProjectMeta(projectRoot); const authDetails = getAuthProjectDetails(projectRoot); const creds = new aws.SharedIniFileCredentials({ profile: profileName }); aws.config.credentials = creds; const cognitoClient = new aws.CognitoIdentityServiceProvider({ region: projectDetails.providers.awscloudformation.Region }); const response = await cognitoClient .createUserPoolClient({ ClientName: clientName, UserPoolId: authDetails.meta.UserPoolId, GenerateSecret: generateSecret, AllowedOAuthFlows: settings.allowedOAuthFlows, CallbackURLs: settings.callbackURLs, LogoutURLs: settings.logoutURLs, AllowedOAuthScopes: settings.allowedScopes, SupportedIdentityProviders: settings.supportedIdentityProviders, AllowedOAuthFlowsUserPoolClient: settings.allowedOAuthFlowsUserPoolClient, }) .promise(); return { appClientId: response.UserPoolClient.ClientId, appclientSecret: response.UserPoolClient.ClientSecret }; }; export const addAppClientWithSecret = async (profileName: string, projectRoot: string, clientName: string, settings: AppClientSettings) => { return addAppClient(profileName, projectRoot, clientName, true, settings); }; export const addAppClientWithoutSecret = async ( profileName: string, projectRoot: string, clientName: string, settings: AppClientSettings, ) => { return addAppClient(profileName, projectRoot, clientName, false, settings); }; export const deleteAppClient = async (profileName: string, projectRoot: string, clientId: string) => { const authDetails = getAuthProjectDetails(projectRoot); const projectDetails = getProjectMeta(projectRoot); const creds = new aws.SharedIniFileCredentials({ profile: profileName }); aws.config.credentials = creds; const cognitoClient = new aws.CognitoIdentityServiceProvider({ region: projectDetails.providers.awscloudformation.Region }); await cognitoClient.deleteUserPoolClient({ ClientId: clientId, UserPoolId: authDetails.meta.UserPoolId }).promise(); }; /** * sets up a project with auth (userpool only or userpool & identitypool) * @param ogProjectRoot * @param ogProjectSettings * @param withIdentityPool */ export const setupOgProjectWithAuth = async ( ogProjectRoot: string, ogProjectSettings: { name: string }, withIdentityPool: boolean = false, ) => { const ogShortId = getShortId(); const ogSettings = withIdentityPool ? createIDPAndUserPoolWithOAuthSettings(ogProjectSettings.name, ogShortId) : createUserPoolOnlyWithOAuthSettings(ogProjectSettings.name, ogShortId); if ('identityPoolName' in ogSettings) { await addAuthIdentityPoolAndUserPoolWithOAuth(ogProjectRoot, ogSettings); } else { await addAuthUserPoolOnlyWithOAuth(ogProjectRoot, ogSettings); } await amplifyPushAuth(ogProjectRoot); return getOGAuthProjectDetails(ogProjectRoot); };
the_stack
import { AppRunner } from 'aws-sdk' import * as nls from 'vscode-nls' import { createCommonButtons, createRefreshButton, QuickInputToggleButton } from '../../shared/ui/buttons' import { Remote } from '../../../types/git.d' import { GitExtension } from '../../shared/extensions/git' import * as vscode from 'vscode' import { CachedFunction, CachedPrompter } from '../../shared/ui/prompter' import { WizardForm } from '../../shared/wizards/wizardForm' import { createVariablesPrompter } from '../../shared/ui/common/variablesPrompter' import { AppRunnerClient } from '../../shared/clients/apprunnerClient' import { makeDeploymentButton } from './deploymentButton' import { ConnectionSummary } from 'aws-sdk/clients/apprunner' import { createLabelQuickPick, createQuickPick, DataQuickPickItem, QuickPickPrompter, } from '../../shared/ui/pickerPrompter' import { createInputBox, InputBoxPrompter } from '../../shared/ui/inputPrompter' import { APPRUNNER_CONNECTION_HELP_URL, APPRUNNER_CONFIGURATION_HELP_URL, APPRUNNER_RUNTIME_HELP_URL, } from '../../shared/constants' import { Wizard, WIZARD_BACK } from '../../shared/wizards/wizard' import { getLogger } from '../../shared/logger/logger' const localize = nls.loadMessageBundle() function validateCommand(command: string): string | undefined { if (command == '') { return localize('AWS.apprunner.command.invalid', 'Command cannot be empty') } return undefined } function createRepoPrompter(git: GitExtension): QuickPickPrompter<Remote> { const remotes = git.getRemotes() const userInputString = localize('AWS.apprunner.createService.customRepo', 'Enter GitHub URL') const items = remotes.map(remote => ({ label: remote.name, detail: remote.fetchUrl, data: remote })) return createQuickPick(items, { title: localize('AWS.apprunner.createService.selectRepository.title', 'Select a remote GitHub repository'), placeholder: localize( 'AWS.apprunner.createService.selectRepository.placeholder', 'Select a remote repository or enter a URL' ), filterBoxInputSettings: { label: userInputString, transform: resp => ({ name: 'UserRemote', isReadOnly: true, fetchUrl: resp }), }, buttons: createCommonButtons(), }) } function createBranchPrompter( git: GitExtension, cache: { [key: string]: any }, repo: string = '' ): QuickPickPrompter<string> { const last = cache[repo] const branchItems = last ?? git.getBranchesForRemote({ name: '', fetchUrl: repo } as any).then(branches => { const branchItems = branches .filter(b => b.name !== undefined && b.name !== '') .map(branch => ({ label: branch.name!.split('/').slice(1).join('/'), })) cache[repo] = branchItems return branchItems }) const userInputString = localize('AWS.apprunner.createService.customRepo', 'Enter branch name') return createLabelQuickPick(branchItems, { title: localize('AWS.apprunner.createService.selectBranch.title', 'Select a branch'), filterBoxInputSettings: { label: userInputString, transform: resp => resp, }, buttons: createCommonButtons(), placeholder: localize( 'AWS.apprunner.createService.selectBranch.placeholder', 'Select a branch or enter a branch name' ), }) } function createRuntimePrompter(): QuickPickPrompter<AppRunner.Runtime> { const items = [ { label: 'python3', data: 'PYTHON_3' }, { label: 'nodejs12', data: 'NODEJS_12' }, ] return createQuickPick(items, { title: localize('AWS.apprunner.createService.selectRuntime.title', 'Select a runtime'), buttons: createCommonButtons(APPRUNNER_RUNTIME_HELP_URL), }) } function createBuildCommandPrompter(runtime: AppRunner.Runtime): InputBoxPrompter { const buildCommandMap = { python: 'pip install -r requirements.txt', node: 'npm install', } as { [key: string]: string } return createInputBox({ title: localize('AWS.apprunner.createService.buildCommand.title', 'Enter a build command'), buttons: createCommonButtons(APPRUNNER_RUNTIME_HELP_URL), placeholder: buildCommandMap[Object.keys(buildCommandMap).filter(key => runtime.toLowerCase().includes(key))[0]], validateInput: validateCommand, }) } function createStartCommandPrompter(runtime: AppRunner.Runtime): InputBoxPrompter { const startCommandMap = { python: 'python runapp.py', node: 'node app.js', } as { [key: string]: string } return createInputBox({ title: localize('AWS.apprunner.createService.startCommand.title', 'Enter a start command'), buttons: createCommonButtons(APPRUNNER_RUNTIME_HELP_URL), placeholder: startCommandMap[Object.keys(startCommandMap).filter(key => runtime.toLowerCase().includes(key))[0]], validateInput: validateCommand, }) } function createPortPrompter(): InputBoxPrompter { const validatePort = (port: string) => { if (isNaN(Number(port)) || port === '') { return localize('AWS.apprunner.createService.selectPort.invalidPort', 'Port must be a number') } return undefined } return createInputBox({ validateInput: validatePort, title: localize('AWS.apprunner.createService.selectPort.title', 'Enter a port for the new service'), placeholder: 'Enter a port', buttons: createCommonButtons(), }) } export class ConnectionPrompter extends CachedPrompter<ConnectionSummary> { public constructor(private readonly client: AppRunnerClient) { super() } protected load(): Promise<DataQuickPickItem<ConnectionSummary>[]> { return this.client .listConnections({}) .then(resp => { const connections = resp.ConnectionSummaryList.filter(conn => conn.Status === 'AVAILABLE').map( conn => ({ label: conn.ConnectionName!, data: conn, }) ) if (connections.length === 0) { return [ { label: 'No connections found', detail: 'Click for documentation on creating a new GitHub connection for App Runner', data: {} as any, invalidSelection: true, onClick: vscode.env.openExternal.bind( vscode.env, vscode.Uri.parse(APPRUNNER_CONNECTION_HELP_URL) ), }, ] } else { return connections } }) .catch(err => { getLogger().error(`Failed to list GitHub connections: %O`, err) return [ { label: localize( 'AWS.apprunner.createService.selectConnection.failed', 'Failed to list GitHub connections' ), description: localize('AWS.generic.goBack', 'Click to go back'), data: WIZARD_BACK, }, ] }) } protected createPrompter(loader: CachedFunction<ConnectionPrompter['load']>): QuickPickPrompter<ConnectionSummary> { const connections = loader() const refreshButton = createRefreshButton() const prompter = createQuickPick(connections, { title: localize('AWS.apprunner.createService.selectConnection.title', 'Select a connection'), buttons: [refreshButton, ...createCommonButtons(APPRUNNER_CONNECTION_HELP_URL)], }) const refresh = () => { loader.clearCache() prompter.clearAndLoadItems(loader()) } refreshButton.onClick = refresh return prompter } } function createSourcePrompter(): QuickPickPrompter<AppRunner.ConfigurationSource> { const configDetail = localize( 'AWS.apprunner.createService.configSource.detail', 'App Runner will read "apprunner.yaml" in the root of your repository for configuration details' ) const apiLabel = localize('AWS.apprunner.createService.configSource.apiLabel', 'Configure all settings here') const repoLabel = localize('AWS.apprunner.createService.configSource.repoLabel', 'Use configuration file') return createQuickPick( [ { label: apiLabel, data: 'API' }, { label: repoLabel, data: 'REPOSITORY', detail: configDetail }, ], { title: localize('AWS.apprunner.createService.configSource.title', 'Choose configuration source'), buttons: createCommonButtons(APPRUNNER_CONFIGURATION_HELP_URL), } ) } function createCodeRepositorySubForm(git: GitExtension): WizardForm<AppRunner.CodeRepository> { const subform = new WizardForm<AppRunner.CodeRepository>() const form = subform.body form.RepositoryUrl.bindPrompter(() => createRepoPrompter(git).transform(r => r.fetchUrl!)) form.SourceCodeVersion.Value.bindPrompter(state => createBranchPrompter(git, state.stepCache, state.RepositoryUrl).transform(resp => resp.replace(`${state.RepositoryUrl}/`, '') ) ) form.CodeConfiguration.ConfigurationSource.bindPrompter(createSourcePrompter) form.SourceCodeVersion.Type.setDefault(() => 'BRANCH') const codeConfigForm = new WizardForm<AppRunner.CodeConfigurationValues>() codeConfigForm.body.Runtime.bindPrompter(createRuntimePrompter) codeConfigForm.body.BuildCommand.bindPrompter(state => createBuildCommandPrompter(state.Runtime!)) codeConfigForm.body.StartCommand.bindPrompter(state => createStartCommandPrompter(state.Runtime!)) codeConfigForm.body.Port.bindPrompter(createPortPrompter) codeConfigForm.body.RuntimeEnvironmentVariables.bindPrompter(() => createVariablesPrompter(createCommonButtons())) // TODO: ask user if they would like to save their parameters into an App Runner config file form.CodeConfiguration.CodeConfigurationValues.applyBoundForm(codeConfigForm, { showWhen: state => state.CodeConfiguration?.ConfigurationSource === 'API', }) return subform } export class AppRunnerCodeRepositoryWizard extends Wizard<AppRunner.SourceConfiguration> { constructor( client: AppRunnerClient, git: GitExtension, autoDeployButton: QuickInputToggleButton = makeDeploymentButton() ) { super() const form = this.form const connectionPrompter = new ConnectionPrompter(client) form.AuthenticationConfiguration.ConnectionArn.bindPrompter( connectionPrompter.transform(conn => conn.ConnectionArn!) ) form.CodeRepository.applyBoundForm(createCodeRepositorySubForm(git)) form.AutoDeploymentsEnabled.setDefault(() => autoDeployButton.state === 'on') } }
the_stack
import { BrowserWindow } from 'electron'; import { Account, AccountWithBalance, HexString, Reward, Tx, TxCoinTransfer, TxSendRequest, TxState } from '../shared/types'; import { ipcConsts } from '../app/vars'; import { AccountDataFlag } from '../proto/spacemesh/v1/AccountDataFlag'; import { Transaction__Output } from '../proto/spacemesh/v1/Transaction'; import { TransactionState__Output } from '../proto/spacemesh/v1/TransactionState'; import { AccountData__Output } from '../proto/spacemesh/v1/AccountData'; import { MeshTransaction__Output } from '../proto/spacemesh/v1/MeshTransaction'; import { Reward__Output } from '../proto/spacemesh/v1/Reward'; import { Account__Output } from '../proto/spacemesh/v1/Account'; import { addReceiptToTx, toTx } from '../shared/types/transformers'; import { hasRequiredRewardFields } from '../shared/types/guards'; import { debounce } from '../shared/utils'; import cryptoService from './cryptoService'; import { fromHexString, toHexString } from './utils'; import TransactionService from './TransactionService'; import MeshService from './MeshService'; import GlobalStateService from './GlobalStateService'; import { AccountStateManager } from './AccountState'; import Logger from './logger'; const DATA_BATCH = 50; const IPC_DEBOUNCE = 1000; type TxHandlerArg = MeshTransaction__Output | null | undefined; type TxHandler = (tx: TxHandlerArg) => void; type RewardHandlerArg = Reward__Output | null | undefined; type RewardHandler = (tx: RewardHandlerArg) => void; class TransactionManager { logger = Logger({ className: 'TransactionManager' }); private readonly meshService: MeshService; private readonly glStateService: GlobalStateService; private readonly txService: TransactionService; accounts: AccountWithBalance[] = []; private readonly mainWindow: BrowserWindow; private txStateStream: Record<string, ReturnType<TransactionService['activateTxStream']>> = {}; private accountStates: Record<string, AccountStateManager> = {}; constructor(meshService, glStateService, txService, mainWindow) { this.meshService = meshService; this.glStateService = glStateService; this.txService = txService; this.mainWindow = mainWindow; } // appStateUpdater = (channel: ipcConsts, payload: any) => { this.mainWindow.webContents.send(channel, { ...payload }); }; // Debounce update functions to avoid excessive IPC calls updateAppStateAccount = debounce(IPC_DEBOUNCE, (publicKey: string) => { const account = this.accountStates[publicKey].getAccount(); this.appStateUpdater(ipcConsts.T_M_UPDATE_ACCOUNT, { account, accountId: publicKey }); }); updateAppStateTxs = debounce(IPC_DEBOUNCE, (publicKey: string) => { const txs = this.accountStates[publicKey].getTxs(); this.appStateUpdater(ipcConsts.T_M_UPDATE_TXS, { txs, publicKey }); }); updateAppStateRewards = debounce(IPC_DEBOUNCE, (publicKey: string) => { const rewards = this.accountStates[publicKey].getRewards(); this.appStateUpdater(ipcConsts.T_M_UPDATE_REWARDS, { rewards, publicKey }); }); private storeTx = (publicKey: string, tx: Tx): Promise<void> => this.accountStates[publicKey] .storeTransaction(tx) .then(() => this.updateAppStateTxs(publicKey)) .catch((err) => { console.log('TransactionManager.storeTx', err); // eslint-disable-line no-console this.logger.error('TransactionManager.storeTx', err); }); private storeReward = (publicKey: string, reward: Reward) => this.accountStates[publicKey] .storeReward(reward) .then(() => this.updateAppStateRewards(publicKey)) .catch((err) => { console.log('TransactionManager.storeReward', err); // eslint-disable-line no-console this.logger.error('TransactionManager.storeReward', err); }); private handleNewTx = (publicKey: string) => async (tx: { transaction: Transaction__Output | null; transactionState: TransactionState__Output | null }) => { if (!tx.transaction || !tx.transactionState || !tx.transactionState.state) return; const newTx = toTx(tx.transaction, tx.transactionState); if (!newTx) return; await this.storeTx(publicKey, newTx); }; private subscribeTransactions = debounce(5000, (publicKey: string) => { const txs = this.accountStates[publicKey].getTxs(); const txIds = Object.keys(txs).map(fromHexString); if (this.txStateStream[publicKey]) { this.txStateStream[publicKey](); } this.txStateStream[publicKey] = this.txService.activateTxStream(this.handleNewTx(publicKey), txIds); this.txService .getTxsState(txIds) .then((resp) => // two lists -> list of tuples resp.transactions.map((tx, idx) => ({ transaction: tx, transactionState: resp.transactionsState[idx] })) ) .then((txs) => txs.map(this.handleNewTx(publicKey))) .catch((err) => { console.log('grpc TransactionState', err); // eslint-disable-line no-console this.logger.error('grpc TransactionState', err); }); }); private subscribeAccount = (account: AccountWithBalance): void => { const { publicKey } = account; // Cancel account Txs subscription this.txStateStream[publicKey] && this.txStateStream[publicKey](); const binaryAccountId = fromHexString(publicKey.substring(24)); const addTransaction = this.upsertTransactionFromMesh(publicKey); this.retrieveHistoricTxData({ accountId: binaryAccountId, offset: 0, handler: addTransaction, retries: 0 }); this.meshService.activateAccountMeshDataStream(binaryAccountId, addTransaction); const updateAccountData = this.updateAccountData({ accountId: publicKey }); this.retrieveAccountData({ filter: { accountId: { address: binaryAccountId }, accountDataFlags: AccountDataFlag.ACCOUNT_DATA_FLAG_ACCOUNT }, handler: updateAccountData, retries: 0, }); this.glStateService.activateAccountDataStream(binaryAccountId, AccountDataFlag.ACCOUNT_DATA_FLAG_ACCOUNT, updateAccountData); setInterval(() => { this.retrieveAccountData({ filter: { accountId: { address: binaryAccountId }, accountDataFlags: 4 }, handler: updateAccountData, retries: 0 }); }, 60 * 1000); const txs = Object.keys(this.accountStates[publicKey].getTxs()); if (txs.length > 0) { this.subscribeTransactions(publicKey, txs); } // TODO: https://github.com/spacemeshos/go-spacemesh/issues/2072 // const addReceiptToTx = this.addReceiptToTx({ accountId: publicKey }); // this.retrieveHistoricTxReceipt({ filter: { accountId: { address: binaryAccountId }, accountDataFlags: 1 }, offset: 0, handler: addReceiptToTx, retries: 0 }); // this.glStateService.activateAccountDataStream(binaryAccountId, AccountDataFlag.ACCOUNT_DATA_FLAG_TRANSACTION_RECEIPT, addReceiptToTx); const addReward = this.addReward(publicKey); this.retrieveRewards({ filter: { accountId: { address: binaryAccountId }, accountDataFlags: 2 }, offset: 0, handler: addReward, retries: 0 }); this.glStateService.activateAccountDataStream(binaryAccountId, AccountDataFlag.ACCOUNT_DATA_FLAG_REWARD, addReward); this.updateAppStateTxs(publicKey); this.updateAppStateRewards(publicKey); }; addAccount = (account: Account) => { const idx = this.accounts.findIndex((acc) => acc.publicKey === account.publicKey); const filtered = idx > -1 ? this.accounts.slice(0, Math.max(0, idx - 1)).concat(this.accounts.slice(idx + 1)) : this.accounts; this.accounts = [...filtered, account]; const accManager = new AccountStateManager(account.publicKey); this.accountStates[account.publicKey] = accManager; // Resubscribe this.subscribeAccount(account); }; setAccounts = (accounts: Account[]) => { accounts.forEach(this.addAccount); }; private upsertTransaction = (accountId: HexString) => async (tx: Tx) => { const originalTx = this.accountStates[accountId].getTxById(tx.id); const receipt = tx.receipt ? { ...originalTx?.receipt, ...tx.receipt } : originalTx?.receipt; const updatedTx: Tx = { ...originalTx, ...tx, receipt }; await this.storeTx(accountId, updatedTx); this.subscribeTransactions(accountId); }; private upsertTransactionFromMesh = (accountId: HexString) => async (tx: TxHandlerArg) => { if (!tx || !tx?.transaction?.id?.id || !tx.layerId) return; const newTxData = toTx(tx.transaction, null); if (!newTxData) return; this.upsertTransaction(accountId)({ ...newTxData, ...(tx.layerId?.number ? { layer: tx.layerId.number } : {}), }); }; retrieveHistoricTxData = async ({ accountId, offset, handler, retries }: { accountId: Uint8Array; offset: number; handler: TxHandler; retries: number }) => { const { data, totalResults, error } = await this.meshService.sendAccountMeshDataQuery({ accountId, offset }); // TODO: Get rid of `any` on proto.ts refactoring if (error && retries < 5) { await this.retrieveHistoricTxData({ accountId, offset, handler, retries: retries + 1 }); } else { data && data.length && data.forEach((tx) => handler(tx.meshTransaction)); if (offset + DATA_BATCH < totalResults) { await this.retrieveHistoricTxData({ accountId, offset: offset + DATA_BATCH, handler, retries: 0 }); } } }; updateAccountData = ({ accountId }: { accountId: string }) => (data: Account__Output) => { const currentState = { counter: data.stateCurrent?.counter ? data.stateCurrent.counter.toNumber() : 0, balance: data.stateCurrent?.balance?.value ? data.stateCurrent.balance.value.toNumber() : 0, }; const projectedState = { counter: data.stateProjected?.counter ? data.stateProjected.counter.toNumber() : 0, balance: data.stateProjected?.balance?.value ? data.stateProjected.balance.value.toNumber() : 0, }; this.accountStates[accountId].storeAccountBalance({ currentState, projectedState }); this.updateAppStateAccount(accountId); }; retrieveAccountData = async ({ filter, handler, retries, }: { filter: { accountId: { address: Uint8Array }; accountDataFlags: number }; handler: (data: Account__Output) => void; retries: number; }) => { const { data, error } = await this.glStateService.sendAccountDataQuery({ filter, offset: 0 }); if (error && retries < 5) { await this.retrieveAccountData({ filter, handler, retries: retries + 1 }); } else { data && data.length > 0 && data[0].accountWrapper && handler(data[0].accountWrapper); } }; addReceiptToTx = ({ accountId }: { accountId: string }) => ({ datum }: { datum: AccountData__Output }) => { const { receipt } = datum; if (!receipt || !receipt.id?.id) return; const txId = toHexString(receipt.id.id); const existingTx = this.accountStates[accountId].getTxById(txId) || {}; // TODO: Handle properly case when we got an receipt, but no tx data? const updatedTx = addReceiptToTx(existingTx, receipt); this.storeTx(accountId, updatedTx); }; retrieveHistoricTxReceipt = async ({ filter, offset, handler, retries, }: { filter: { accountId: { address: Uint8Array }; accountDataFlags: number }; offset: number; handler: ({ data }: { data: any }) => void; retries: number; }) => { const { totalResults, data, error } = await this.glStateService.sendAccountDataQuery({ filter, offset }); if (error && retries < 5) { await this.retrieveHistoricTxReceipt({ filter, offset, handler, retries: retries + 1 }); } else { data && data.length && data.length > 0 && data.forEach((item) => handler({ data: item.receipt })); if (offset + DATA_BATCH < totalResults) { await this.retrieveHistoricTxReceipt({ filter, offset: offset + DATA_BATCH, handler, retries: 0 }); } } }; addReward = (accountId: HexString) => (reward: RewardHandlerArg) => { if (!reward || !hasRequiredRewardFields(reward)) return; // const genesisTime = StoreService.get('netSettings.genesisTime'); // const layerDurationSec = StoreService.get('netSettings.layerDurationSec'); const coinbase = toHexString(reward.coinbase.address); const parsedReward: Reward = { layer: reward.layer.number, amount: reward.total.value.toNumber(), layerReward: reward.layerReward.value.toNumber(), // layerComputed: reward.layerComputed.number, // TODO coinbase: `0x${coinbase}`, smesher: toHexString(reward.smesher.id), }; this.storeReward(accountId, parsedReward); }; retrieveRewards = async ({ filter, offset, handler, retries, }: { filter: { accountId: { address: Uint8Array }; accountDataFlags: number }; offset: number; handler: RewardHandler; retries: number; }) => { const { totalResults, data, error } = await this.glStateService.sendAccountDataQuery({ filter, offset }); if (error && retries < 5) { await this.retrieveRewards({ filter, offset, handler, retries: retries + 1 }); } else { data && data.length > 0 && data.forEach((reward) => handler(reward.reward)); if (offset + DATA_BATCH < totalResults) { await this.retrieveRewards({ filter, offset: offset + DATA_BATCH, handler, retries: 0 }); } } }; sendTx = async ({ fullTx, accountIndex }: { fullTx: TxSendRequest; accountIndex: number }) => { const { publicKey } = this.accounts[accountIndex]; const account = this.accountStates[publicKey].getAccount(); const { receiver, amount, fee } = fullTx; const res = await cryptoService.signTransaction({ accountNonce: account.projectedState.counter, receiver, price: fee, amount, secretKey: this.accounts[accountIndex].secretKey, }); const response = await this.txService.submitTransaction({ transaction: res }); const getTxResponseError = () => new Error('Can not retrieve a transaction data'); // TODO: Refactor to avoid mixing data with errors and then get rid of insane ternaries for each data piece const error = response.error || response.txstate === null || !response.txstate.id?.id ? response.error || getTxResponseError() : null; // Compose "initial" transaction record const tx: TxCoinTransfer | null = response.error === null && response.txstate?.id?.id ? { id: toHexString(response.txstate.id.id), sender: fullTx.sender, receiver: fullTx.receiver, amount: fullTx.amount, status: response.txstate.state, receipt: { fee: fullTx.fee, }, } : null; const state = response.error === null && response.txstate?.state ? response.txstate.state : null; if (tx && state && ![TxState.TRANSACTION_STATE_INSUFFICIENT_FUNDS, TxState.TRANSACTION_STATE_REJECTED, TxState.TRANSACTION_STATE_CONFLICTING].includes(state)) { this.upsertTransaction(publicKey)(tx); } return { error, tx, state }; }; updateTxNote = ({ accountIndex, txId, note }: { accountIndex: number; txId: HexString; note: string }) => { const { publicKey } = this.accounts[accountIndex]; const tx = this.accountStates[publicKey].getTxById(txId); this.storeTx(publicKey, { ...tx, note }); }; } export default TransactionManager;
the_stack
import * as angular from "angular"; import {moduleName} from "../module-name"; import * as _ from 'underscore'; import * as moment from "moment"; import {OpsManagerFeedUtil} from "./ops-manager-feed-util"; export default class OpsManagerDashboardService{ static readonly $inject = ['$q', '$http', 'OpsManagerRestUrlService','BroadcastService'] constructor(private $q: any,private $http: any, private OpsManagerRestUrlService: any, private BroadcastService: any){ } DASHBOARD_UPDATED:string = 'DASHBOARD_UPDATED'; FEED_SUMMARY_UPDATED:string ='FEED_SUMMARY_UPDATED'; TAB_SELECTED:string = 'TAB_SELECTED'; feedSummaryData:any = {}; feedsArray:any[]=[]; feedUnhealthyCount:number =0; feedHealthyCount:number = 0; dashboard:any = {}; feedsSearchResult:any = {}; totalFeeds:number = 0; activeFeedRequest:any = null; activeDashboardRequest:any = null; skipDashboardFeedHealth:boolean = false selectFeedHealthTab(tab: any) { this.BroadcastService.notify(this.TAB_SELECTED,tab); } feedHealthQueryParams:any = {fixedFilter:'All',filter:'',start:0,limit:10, sort:''} setupFeedHealth(feedsArray: any){ var processedFeeds: any[] = []; if(feedsArray) { var processed: any[] = []; var arr: any[] = []; _.each(feedsArray, (feedHealth: any) =>{ //pointer to the feed that is used/bound to the ui/service var feedData = null; if (this.feedSummaryData[feedHealth.feed]) { feedData = this.feedSummaryData[feedHealth.feed] angular.extend(feedData, feedHealth); feedHealth = feedData; } else { this.feedSummaryData[feedHealth.feed] = feedHealth; feedData = feedHealth; } arr.push(feedData); processedFeeds.push(feedData); if (feedData.lastUnhealthyTime) { feedData.sinceTimeString = moment(feedData.lastUnhealthyTime).fromNow(); } OpsManagerFeedUtil.decorateFeedSummary(feedData); if(feedData.stream == true && feedData.feedHealth){ feedData.runningCount = feedData.feedHealth.runningCount; if(feedData.runningCount == null){ feedData.runningCount =0; } } if(feedData.running){ feedData.timeSinceEndTime = feedData.runTime; feedData.runTimeString = '--'; } processed.push(feedData.feed); }); var keysToRemove=_.difference(Object.keys(this.feedSummaryData),processed); if(keysToRemove != null && keysToRemove.length >0){ _.each(keysToRemove,(key: any)=>{ delete this.feedSummaryData[key]; }) } this.feedsArray = arr; } return processedFeeds; } isFetchingFeedHealth(){ return this.activeFeedRequest != null && angular.isDefined(this.activeFeedRequest); } isFetchingDashboard() { return this.activeDashboardRequest != null && angular.isDefined(this.activeDashboardRequest); } setSkipDashboardFeedHealth (skip: boolean){ this.skipDashboardFeedHealth = skip; } fetchFeeds(tab: string,filter: string,start: number,limit: number, sort: string){ if(this.activeFeedRequest != null && angular.isDefined(this.activeFeedRequest)){ this.activeFeedRequest.reject(); } //Cancel any active dashboard queries as this will supercede them if(this.activeDashboardRequest != null && angular.isDefined(this.activeDashboardRequest)){ this.skipDashboardFeedHealth = true; } var canceler = this.$q.defer(); this.activeFeedRequest = canceler; var params = {start: start, limit: limit, sort: sort, filter:filter, fixedFilter:tab}; var initDashboard = (responseData:any) => { this.feedsSearchResult = responseData; if(responseData && responseData.data) { this.setupFeedHealth(responseData.data); //reset this.dashboard.feeds.data ? this.totalFeeds = responseData.recordsFiltered; } this.activeFeedRequest = null; this.skipDashboardFeedHealth = false; this.BroadcastService.notify(this.DASHBOARD_UPDATED, this.dashboard); } var successFn = (response: any) =>{ return response.data; } var errorFn = (err: any)=> { canceler.reject(); canceler = null; this.activeFeedRequest = null; this.skipDashboardFeedHealth = false; } var promise = this.$http.get(this.OpsManagerRestUrlService.DASHBOARD_PAGEABLE_FEEDS_URL,{timeout: canceler.promise,params:params}); promise.then(successFn, errorFn).then(this.fetchPageableFeedNames.bind(this)).then(initDashboard); return promise; } fetchPageableFeedNames(resolveObj:any){ var feeds = resolveObj.data; return this.fetchFeedNames(resolveObj, feeds); } fetchFeedNames(resolveObj:any, feeds:any){ var deferred = this.$q.defer(); if (feeds.length > 0) { var feedNames = _.map(feeds, (feed:any) => { return feed.feed; }); var namesPromise = this.$http.post(this.OpsManagerRestUrlService.FEED_SYSTEM_NAMES_TO_DISPLAY_NAMES_URL, feedNames); namesPromise.then((result:any) => { _.each(feeds, (feed:any) => { feed.displayName = _.find(result.data, (systemNameToDisplayName:any) => { return systemNameToDisplayName.key === feed.feed; }) }); deferred.resolve(resolveObj); }, function(err:any) { console.error('Failed to receive feed names', err); deferred.resolve(resolveObj); }); } else { deferred.resolve(resolveObj); } return deferred.promise; } updateFeedHealthQueryParams(tab: string,filter: string,start: number,limit: number, sort: string){ var params = {start: start, limit: limit, sort: sort, filter:filter, fixedFilter:tab}; angular.extend(this.feedHealthQueryParams,params); } fetchDashboard() { if(this.activeDashboardRequest != null && angular.isDefined(this.activeDashboardRequest)){ this.activeDashboardRequest.reject(); } var canceler = this.$q.defer(); this.activeDashboardRequest = canceler; var initDashboard = (dashboard:any) => { this.dashboard = dashboard; //if the pagable feeds query came after this one it will flip the skip flag. // that should supercede this request if(!this.skipDashboardFeedHealth) { this.feedsSearchResult = dashboard.feeds; if (this.dashboard && this.dashboard.feeds && this.dashboard.feeds.data) { var processedFeeds = this.setupFeedHealth(this.dashboard.feeds.data); this.dashboard.feeds.data = processedFeeds; this.totalFeeds = this.dashboard.feeds.recordsFiltered; } } else { // console.log('Skip processing dashboard results for the feed since it was superceded'); } if(angular.isUndefined(this.dashboard.healthCounts['UNHEALTHY'])) { this.dashboard.healthCounts['UNHEALTHY'] = 0; } if(angular.isUndefined(this.dashboard.healthCounts['HEALTHY'])) { this.dashboard.healthCounts['HEALTHY'] = 0; } this.feedUnhealthyCount = this.dashboard.healthCounts['UNHEALTHY'] || 0; this.feedHealthyCount = this.dashboard.healthCounts['HEALTHY'] || 0; this.activeDashboardRequest = null; this.BroadcastService.notify(this.DASHBOARD_UPDATED, dashboard); } var successFn = (response:any) => { initDashboard(response.data) // fetchFeedNames(response.data, response.this.feeds.data).then(initDashboard); } var errorFn = (err: any) =>{ canceler.reject(); canceler = null; this.activeDashboardRequest = null; this.skipDashboardFeedHealth = false; console.error("Dashboard error!!!") } var params = this.feedHealthQueryParams; var promise = this.$http.get(this.OpsManagerRestUrlService.DASHBOARD_URL,{timeout: canceler.promise,params:params}); promise.then(successFn, errorFn); return promise; } } angular.module(moduleName).service('OpsManagerDashboardService',OpsManagerDashboardService);
the_stack
import * as Long from 'long'; import {CPSessionAwareProxy} from './CPSessionAwareProxy'; import {ISemaphore} from '../ISemaphore'; import {CPProxyManager} from './CPProxyManager'; import {CPSessionManager, NO_SESSION_ID} from './CPSessionManager'; import {RaftGroupId} from './RaftGroupId'; import { assertNonNegativeNumber, assertPositiveNumber } from '../../util/Util'; import {UuidUtil} from '../../util/UuidUtil'; import {SemaphoreInitCodec} from '../../codec/SemaphoreInitCodec'; import {SemaphoreAcquireCodec} from '../../codec/SemaphoreAcquireCodec'; import {SemaphoreAvailablePermitsCodec} from '../../codec/SemaphoreAvailablePermitsCodec'; import {SemaphoreDrainCodec} from '../../codec/SemaphoreDrainCodec'; import {SemaphoreChangeCodec} from '../../codec/SemaphoreChangeCodec'; import {SemaphoreReleaseCodec} from '../../codec/SemaphoreReleaseCodec'; import { IllegalStateError, SessionExpiredError, WaitKeyCancelledError, UUID } from '../../core'; import {InvocationService} from '../../invocation/InvocationService'; import {SerializationService} from '../../serialization/SerializationService'; /** * Since a proxy does not know how many permits will be drained on * the Raft group, it uses this constant to increment its local session * acquire count. Then, it adjusts the local session acquire count after * the drain response is returned. */ const DRAIN_SESSION_ACQ_COUNT = 1024; /** @internal */ export class SessionAwareSemaphoreProxy extends CPSessionAwareProxy implements ISemaphore { constructor( groupId: RaftGroupId, proxyName: string, objectName: string, invocationService: InvocationService, serializationService: SerializationService, cpSessionManager: CPSessionManager ) { super( CPProxyManager.SEMAPHORE_SERVICE, groupId, proxyName, objectName, invocationService, serializationService, cpSessionManager ); } init(permits: number): Promise<boolean> { assertNonNegativeNumber(permits); return this.encodeInvokeOnRandomTarget(SemaphoreInitCodec, this.groupId, this.objectName, permits) .then(SemaphoreInitCodec.decodeResponse); } acquire(permits = 1): Promise<void> { assertPositiveNumber(permits); const invocationUid = UuidUtil.generate(); return this.doAcquire(permits, invocationUid); } private doAcquire(permits: number, invocationUid: UUID): Promise<void> { let sessionId: Long; const threadId = Long.fromNumber(this.nextThreadId()); return this.acquireSession(permits) .then((id) => { sessionId = id; return this.requestAcquire(sessionId, threadId, invocationUid, permits, -1); }) .catch((err) => { if (err instanceof SessionExpiredError) { this.invalidateSession(sessionId); return this.doAcquire(permits, invocationUid); } this.releaseSession(sessionId, permits); if (err instanceof WaitKeyCancelledError) { throw new IllegalStateError('Semaphore[' + this.objectName + '] not acquired because the acquire call on the CP group was cancelled.'); } throw err; }) .then(() => {}); } tryAcquire(permits = 1, timeout = 0): Promise<boolean> { assertPositiveNumber(permits); assertNonNegativeNumber(timeout); const invocationUid = UuidUtil.generate(); return this.doTryAcquire(permits, timeout, invocationUid); } private doTryAcquire(permits: number, timeout: number, invocationUid: UUID): Promise<boolean> { const start = Date.now(); let sessionId: Long; const threadId = Long.fromNumber(this.nextThreadId()); return this.acquireSession(permits) .then((id) => { sessionId = id; return this.requestAcquire(sessionId, threadId, invocationUid, permits, timeout); }) .then((acquired) => { if (!acquired) { this.releaseSession(sessionId, permits); } return acquired; }) .catch((err) => { if (err instanceof SessionExpiredError) { this.invalidateSession(sessionId); timeout -= Date.now() - start; if (timeout < 0) { return false; } return this.doTryAcquire(permits, timeout, invocationUid); } this.releaseSession(sessionId, permits); if (err instanceof WaitKeyCancelledError) { return false; } throw err; }); } release(permits = 1): Promise<void> { assertPositiveNumber(permits); const sessionId = this.getSessionId(); if (NO_SESSION_ID.equals(sessionId)) { return Promise.reject(this.newIllegalStateError()); } const threadId = Long.fromNumber(this.nextThreadId()); const invocationUid = UuidUtil.generate(); return this.requestRelease(sessionId, threadId, invocationUid, permits) .then(() => { this.releaseSession(sessionId, permits); }) .catch((err) => { if (err instanceof SessionExpiredError) { this.invalidateSession(sessionId); throw this.newIllegalStateError(err); } this.releaseSession(sessionId, permits); throw err; }); } availablePermits(): Promise<number> { return this.encodeInvokeOnRandomTarget(SemaphoreAvailablePermitsCodec, this.groupId, this.objectName) .then(SemaphoreAvailablePermitsCodec.decodeResponse); } drainPermits(): Promise<number> { const invocationUid = UuidUtil.generate(); return this.doDrainPermits(invocationUid); } private doDrainPermits(invocationUid: UUID): Promise<number> { let sessionId: Long; const threadId = Long.fromNumber(this.nextThreadId()); return this.acquireSession(DRAIN_SESSION_ACQ_COUNT) .then((id) => { sessionId = id; return this.requestDrain(sessionId, threadId, invocationUid); }) .then((count) => { this.releaseSession(sessionId, DRAIN_SESSION_ACQ_COUNT - count); return count; }) .catch((err) => { if (err instanceof SessionExpiredError) { this.invalidateSession(sessionId); return this.doDrainPermits(invocationUid); } this.releaseSession(sessionId, DRAIN_SESSION_ACQ_COUNT); throw err; }); } reducePermits(reduction: number): Promise<void> { assertNonNegativeNumber(reduction); if (reduction === 0) { return Promise.resolve(); } return this.doChangePermits(-reduction); } increasePermits(increase: number): Promise<void> { assertNonNegativeNumber(increase); if (increase === 0) { return Promise.resolve(); } return this.doChangePermits(increase); } private doChangePermits(delta: number): Promise<void> { let sessionId: Long; const threadId = Long.fromNumber(this.nextThreadId()); const invocationUid = UuidUtil.generate(); return this.acquireSession() .then((id) => { sessionId = id; return this.requestChange(sessionId, threadId, invocationUid, delta); }) .then(() => { this.releaseSession(sessionId); }) .catch((err) => { if (err instanceof SessionExpiredError) { this.invalidateSession(sessionId); throw this.newIllegalStateError(err); } this.releaseSession(sessionId); throw err; }); } private requestAcquire(sessionId: Long, threadId: Long, invocationUid: UUID, permits: number, timeout: number): Promise<boolean> { return this.encodeInvokeOnRandomTarget( SemaphoreAcquireCodec, this.groupId, this.objectName, sessionId, threadId, invocationUid, permits, Long.fromNumber(timeout) ).then(SemaphoreAcquireCodec.decodeResponse); } private requestRelease(sessionId: Long, threadId: Long, invocationUid: UUID, permits: number): Promise<void> { return this.encodeInvokeOnRandomTarget( SemaphoreReleaseCodec, this.groupId, this.objectName, sessionId, threadId, invocationUid, permits ).then(() => {}); } private requestDrain(sessionId: Long, threadId: Long, invocationUid: UUID): Promise<number> { return this.encodeInvokeOnRandomTarget( SemaphoreDrainCodec, this.groupId, this.objectName, sessionId, threadId, invocationUid ).then(SemaphoreDrainCodec.decodeResponse); } private requestChange(sessionId: Long, threadId: Long, invocationUid: UUID, delta: number): Promise<void> { return this.encodeInvokeOnRandomTarget( SemaphoreChangeCodec, this.groupId, this.objectName, sessionId, threadId, invocationUid, delta ).then(() => {}); } private newIllegalStateError(cause?: SessionExpiredError) { return new IllegalStateError('Semaphore[' + this.objectName + '] has no valid session!', cause); } }
the_stack
import type {Output} from "../output/Output"; /** * Stylized text output utility functions. * @public */ export const OutputStyle = (function () { const OutputStyle = {} as { /** * Writes the ASCII reset escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ reset<T>(output: Output<T>): Output<T> /** * Writes the ASCII bold (increased intensity) escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ bold<T>(output: Output<T>): Output<T>; /** * Writes the ASCII faint (decreased intensity) escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ faint<T>(output: Output<T>): Output<T>; /** * Writes the ASCII black foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ black<T>(output: Output<T>): Output<T>; /** * Writes the ASCII red foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ red<T>(output: Output<T>): Output<T>; /** * Writes the ASCII green foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ green<T>(output: Output<T>): Output<T>; /** * Writes the ASCII yellow foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ yellow<T>(output: Output<T>): Output<T>; /** * Writes the ASCII blue foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ blue<T>(output: Output<T>): Output<T>; /** * Writes the ASCII magenta foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ magenta<T>(output: Output<T>): Output<T>; /** * Writes the ASCII cyan foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ cyan<T>(output: Output<T>): Output<T>; /** * Writes the ASCII gray foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ gray<T>(output: Output<T>): Output<T>; /** * Writes the ASCII bold black foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ blackBold<T>(output: Output<T>): Output<T>; /** * Writes the ASCII bold red foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ redBold<T>(output: Output<T>): Output<T>; /** * Writes the ASCII bold green foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ greenBold<T>(output: Output<T>): Output<T>; /** * Writes the ASCII bold yellow foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ yellowBold<T>(output: Output<T>): Output<T>; /** * Writes the ASCII bold blue foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ blueBold<T>(output: Output<T>): Output<T>; /** * Writes the ASCII bold magenta foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ magentaBold<T>(output: Output<T>): Output<T>; /** * Writes the ASCII bold cyan foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ cyanBold<T>(output: Output<T>): Output<T>; /** * Writes the ASCII bold gray foreground color escape code to `output`, * if [[OutputSettings.isStyled `output.settings.isStyled()`]] is `true`. * * @returns the continuation of the `output`. */ grayBold<T>(output: Output<T>): Output<T>; }; OutputStyle.reset = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(48/*'0'*/).write(109/*'m'*/); } return output; }; OutputStyle.bold = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(49/*'1'*/).write(109/*'m'*/); } return output; }; OutputStyle.faint = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(50/*'2'*/).write(109/*'m'*/); } return output; }; OutputStyle.black = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(48/*'0'*/).write(59/*';'*/) .write(51/*'3'*/).write(48/*'0'*/).write(109/*'m'*/); } return output; }; OutputStyle.red = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(48/*'0'*/).write(59/*';'*/) .write(51/*'3'*/).write(49/*'1'*/).write(109/*'m'*/); } return output; }; OutputStyle.green = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(48/*'0'*/).write(59/*';'*/) .write(51/*'3'*/).write(50/*'2'*/).write(109/*'m'*/); } return output; }; OutputStyle.yellow = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(48/*'0'*/).write(59/*';'*/) .write(51/*'3'*/).write(51/*'3'*/).write(109/*'m'*/); } return output; }; OutputStyle.blue = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(48/*'0'*/).write(59/*';'*/) .write(51/*'3'*/).write(52/*'4'*/).write(109/*'m'*/); } return output; }; OutputStyle.magenta = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(48/*'0'*/).write(59/*';'*/) .write(51/*'3'*/).write(53/*'5'*/).write(109/*'m'*/); } return output; }; OutputStyle.cyan = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(48/*'0'*/).write(59/*';'*/) .write(51/*'3'*/).write(54/*'6'*/).write(109/*'m'*/); } return output; }; OutputStyle.gray = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(48/*'0'*/).write(59/*';'*/) .write(51/*'3'*/).write(55/*'7'*/).write(109/*'m'*/); } return output; }; OutputStyle.blackBold = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(49/*'1'*/).write(59/*';'*/) .write(51/*'3'*/).write(48/*'0'*/).write(109/*'m'*/); } return output; }; OutputStyle.redBold = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(49/*'1'*/).write(59/*';'*/) .write(51/*'3'*/).write(49/*'1'*/).write(109/*'m'*/); } return output; }; OutputStyle.greenBold = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(49/*'1'*/).write(59/*';'*/) .write(51/*'3'*/).write(50/*'2'*/).write(109/*'m'*/); } return output; }; OutputStyle.yellowBold = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(49/*'1'*/).write(59/*';'*/) .write(51/*'3'*/).write(51/*'3'*/).write(109/*'m'*/); } return output; }; OutputStyle.blueBold = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(49/*'1'*/).write(59/*';'*/) .write(51/*'3'*/).write(52/*'4'*/).write(109/*'m'*/); } return output; }; OutputStyle.magentaBold = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(49/*'1'*/).write(59/*';'*/) .write(51/*'3'*/).write(53/*'5'*/).write(109/*'m'*/); } return output; }; OutputStyle.cyanBold = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(49/*'1'*/).write(59/*';'*/) .write(51/*'3'*/).write(54/*'6'*/).write(109/*'m'*/); } return output; }; OutputStyle.grayBold = function <T>(output: Output<T>): Output<T> { if (output.settings.isStyled()) { output = output.write(27).write(91/*'['*/).write(49/*'1'*/).write(59/*';'*/) .write(51/*'3'*/).write(55/*'7'*/).write(109/*'m'*/); } return output; }; return OutputStyle; })();
the_stack
import Widget from './Widget' import { ListView } from './basicWidget' import Util from '../shared/Util' import { RenderData, ThreshProvider } from '../types/type' import threshApp from './ThreshApp' import appContainer from './AppContainer' import TimerManager from '../manager/TimerManager' import UtilManager from '../manager/UtilManager' export type PropChildrenVNodeType = VNode | VNode[] const ChildrenKey: string = 'children' type W = Widget<any, any> type Key = string | number | void type Ref = ((widget: W) => void) | void export interface PropChildrenVNode { [childrenPropName: string]: PropChildrenVNodeType } interface NodeEvents { [eventName: string]: Function } interface VNodeUpdateInfo { updateNodeId: string, // flutter 端需要被更新的原子组件 node id invokeUpdateNodeId: string // js 端需要出发 update 的自定义组件 node id } export default class VNode { // 节点类型 type: string // 节点属性 props: any // 父节点 parent: VNode | void // 子节点 children: VNode[] = [] // 原子节点属性上的子节点 basicWidgetPropChildren: PropChildrenVNode = {} // 节点的 widget 实例 widget: W // 节点实例构造器 widgetBuilder: any // 是否原子节点 isBasicWidget: boolean // 原子节点 children 属性对应的 name childrenMapedName: string = ChildrenKey // 原子节点 children 属性对应的类型是否为 array childrenIsArray: boolean = true // 节点 id nodeId: string // 节点为 NativeView 时的 viewId nativeViewId?: string // 节点上的事件 events: NodeEvents = {} // 节点所属页面 pageName?: string // 子节点中存在 Page 时保存 Page Node pageNode: VNode | void // 节点是否已挂载 hasMount: boolean = false // context id contextId: string = appContainer.contextId as string isPageNode: boolean = false isNativeViewNode: boolean = false isInputNode: boolean = false key?: Key parentKey?: Key ref?: Ref updateInfo?: VNodeUpdateInfo shouldRender: boolean = true private _refHasMount: boolean = false static nodeIdIndex: number = 0 static getNodeId(type: string): string { return `${type}#${++VNode.nodeIdIndex}` } static asyncEventTypes: string[] = [ 'onRefresh', 'onLoadMore', ] static eventTypes: string[] = [ 'onTap', 'onLongTap', 'onPan', 'onScroll', 'onChange', 'onLoad', 'onLayout', 'onFocus', 'onBlur', 'onActionsOpen', 'onActionsClose', 'willDragStatusChange', 'onDragStatusChange', 'onDragPositionChange', 'onOpen', 'onSubmitted', 'onClicked', ...VNode.asyncEventTypes, ] static throttledEventTypes: string[] = ['onTap'] constructor({ type, props, widgetBuilder, isBasicWidget, childrenMapedName, childrenIsArray, parent, key, ref, }: { type: string, props: any, widgetBuilder: any, isBasicWidget: boolean, childrenMapedName: string childrenIsArray: boolean parent?: VNode | void, key?: Key, ref?: Ref, }) { this.type = type this.props = props this.widgetBuilder = widgetBuilder this.isBasicWidget = isBasicWidget this.childrenMapedName = childrenMapedName this.childrenIsArray = childrenIsArray this.parent = parent this.key = key this.ref = ref this.nodeId = VNode.getNodeId(type) if (isBasicWidget) { this.isPageNode = type === 'Page' this.isNativeViewNode = type === 'NativeView' this.isInputNode = type === 'Input' } if (this.isNativeViewNode) { this.nativeViewId = `${this.nodeId}#${this.props.type}#${Date.now()}` } this.findVNodeInProps() } // 在 props 中查找所有的 vnode findVNodeInProps() { for (let key in this.props) { const item: any = this.props[key] if (item instanceof VNode && this.isBasicWidget) { item.parent = this this.basicWidgetPropChildren[key] = item } if (Array.isArray(item)) { item.forEach((subItem: any) => { if (subItem instanceof VNode) { subItem.parent = this if (key === ChildrenKey) this.appendChild(subItem) else if (this.isBasicWidget) this.appendChildInArrayProps(subItem, key) } }) } } } // 在 props 中查找事件 findEventsInProps() { if (!this.isBasicWidget) return this.events = {} let eventId: number = 0 VNode.eventTypes.forEach(key => { let prop: any = this.props[key] if (prop instanceof Function) { const eventCacheId: string = `event/${++eventId}` if (VNode.throttledEventTypes.includes(key)) prop = Util.throttle(prop) this.events[eventCacheId] = prop this.props[`_${key}Id`] = eventCacheId } }) } // 触发组件实例 render doRender() { if (!this.shouldRender) return this.shouldRender = false if (!this.widget) { this.widget = new this.widgetBuilder(this.props) this.widget.__vNode__ = this } this.widget.props = this.props if (!this.isBasicWidget) { const node: VNode | void = this.widget.render() if (!node) throw new Error(`Widget's render method must return a widget. Error in: <${this.type} />`) node.parent = this this.children = [node] } } // 执行组件更新 doUpdate(): VNode | void { if (!this.widget) { this.widget = new this.widgetBuilder(this.props) this.widget.__vNode__ = this } const newRenderNode: VNode | void = this.widget.render() if (!newRenderNode) throw new Error(`Widget's render method must return a widget. Error in: <${this.type} />`) return newRenderNode } // 新旧节点融合 doMerge(oldNode: VNode) { this.contextId = oldNode.contextId this.hasMount = true this.nodeId = oldNode.nodeId this.nativeViewId = oldNode.nativeViewId this.widget = oldNode.widget this.widget.__vNode__ = this } // 将 vNode 转换为 flutter 可用的 json toRenderData(pageName: string, setStateful: boolean = true): RenderData { this.pageName = pageName if (this.pageNode) this.pageNode = void 0 this.findEventsInProps() this.doRender() if (!this.isBasicWidget) { // 非原子组件,children 只有 1 个元素 // flutter version 1.1.0 及以上,所有自定义组件都是 stateful // flutter version 1.1.0 以下,只有声明了 state 的自定义组件才是 stateful if (this.children.length) { const child: VNode = this.children[0] if (Util.isNil(child.key)) child.parentKey = this.key || this.parentKey return child.toRenderData(pageName, true) } } else { let childrenRenderData: any = {} this.mapChildren((vNode: VNode, key: string, fromArray: boolean) => { if (!fromArray) childrenRenderData[key] = vNode.toRenderData(pageName, false) else { if (!childrenRenderData[key]) childrenRenderData[key] = [] childrenRenderData[key].push(vNode.toRenderData(pageName, false)) } if (key === ChildrenKey && !this.childrenIsArray) { childrenRenderData[this.childrenMapedName] = childrenRenderData[key][0] delete childrenRenderData[key] } }) if (this.isPageNode) { const rootNode: VNode = this.fetchRootNode() rootNode.pageNode = this } if (this.isNativeViewNode) { const params = this.props.params || {} if (!params.__viewId__) { params.__viewId__ = this.nativeViewId this.props.params = params } } return { name: this.type, widgetId: this.nodeId, isStateful: setStateful, pageName, props: this.execPropsProvider(Object.assign({}, this.props, childrenRenderData)), key: this.key || this.parentKey } } } private execPropsProvider(props: Object): Object { const propsProviders: ThreshProvider[] = threshApp.providers.propsProvider || [] let index = propsProviders.length - 1 while (index > -1) { const provider = propsProviders[index--] const tempProps = provider.propsProvider(props) if (tempProps) props = tempProps } return props } // 在当前 vnode 上查找目标节点 fetch(targetNodeId: string): VNode { if (this.nodeId === targetNodeId) return this let targetVNode: VNode this.mapChildren((vNode: VNode) => { if (vNode.nodeId === targetNodeId) { targetVNode = vNode return false } targetVNode = vNode.fetch(targetNodeId) return !targetVNode }) return targetVNode } // 查找距离当前节点向上最近的可更新的原子节点 fetchNearlyCanUpdateBasicNode(): VNode { const node: VNode = this.fetchNearlyCustomNode() let firstChildNode: VNode = node.children[0] while (firstChildNode && !firstChildNode.isBasicWidget) { firstChildNode = firstChildNode.children[0] } return firstChildNode } // 查找距离当前节点向上最近的非原子节点 fetchNearlyCustomNode(): VNode { if (!this.isBasicWidget) return this const parent: VNode | void = this.parent if (parent) return parent.fetchNearlyCustomNode() return this } // 查找距离当前节点向下最近的原子节点 fetchNearlyBasicNode(): VNode { if (this.isBasicWidget) return this return this.children[0].fetchNearlyBasicNode() } // 查找根节点 fetchRootNode(): VNode { if (!this.parent) return this const parent: VNode | void = this.parent if (parent) return parent.fetchRootNode() return this } // 查找页面名 fetchNodePageName(): string { if (this.pageName) return this.pageName if (this.parent) return this.parent.fetchNodePageName() return '' } // 毕竟两个节点的 type & key 是否相等 isSameAs(otherNode: VNode) { return this.type === otherNode.type && this.key === otherNode.key } // 触发组件上的事件 async invokeEvent(targetNodeId: string, eventId: string, eventType: string, params: any) { const targetNode: VNode = this.fetch(targetNodeId) if (!targetNode) return const eventFn: Function = targetNode.events[eventId] if (!eventFn) return if (!eventType || !VNode.asyncEventTypes.includes(eventType)) eventFn(params) else { try { await eventFn(params) } finally { // Hack fix // 异步操作完成后的32毫秒再发送停止异步操作的通知 // 异步操作中可能含有setState,从而保证停止通知在setState后再发送 TimerManager.setTimeout(() => { this.stopAsyncEvent(targetNode, eventType) }, 32) } } } // 停止异步事件 stopAsyncEvent(node: VNode, eventType: string) { if (!node || !eventType || !VNode.asyncEventTypes.includes(eventType)) return if (node.type === 'ListView') { (node.widget as unknown as ListView).stopAsyncOperate(eventType === 'onRefresh' ? 'refresh' : 'loadMore') } } // 触发组件生命周期方法 invokeLifeCycle(lifeStep: string) { if (!this.widget || !LifeCycle.isExist(lifeStep)) return const lifeStepIsDidUnmount = lifeStep === LifeCycle.widgetDidUnmount // 当生命周期不是卸载时,从子组件向父组件依次触发 if (!lifeStepIsDidUnmount) { this._invokeChildrenLifeCycle(lifeStep) } if (!this.hasMount && lifeStep === LifeCycle.widgetDidUpdate) { this.hasMount = true this._invokeMountRef() this.widget.widgetDidMount() } else { this.hasMount = !lifeStepIsDidUnmount this._invokeMountRef() this.widget[lifeStep]() } // 当组件卸载时,didUnmount从父组件向子组件触发 if (lifeStepIsDidUnmount) { this._invokeChildrenLifeCycle(lifeStep) } } private _invokeChildrenLifeCycle(lifeStep: string) { this.mapChildren((vNode: VNode) => { vNode.invokeLifeCycle(lifeStep) }) } private _invokeMountRef() { if (!this.ref) return if (this.hasMount && !this._refHasMount) { this.ref(this.widget) this._refHasMount = true } else if (!this.hasMount && this._refHasMount) { this.ref(undefined) this._refHasMount = false } } // 向数组尾部添加子节点 appendChild(child: VNode, target: VNode[] = this.children) { if (target.includes(child)) this.removeChild(child) target.push(child) } // 移除数组中的某个节点 removeChild(child: VNode, target: VNode[] = this.children) { const removeIndex: number = target.indexOf(child) if (removeIndex > -1) target.splice(removeIndex, 1) } // 向 basicWidgetPropChildren 中的某个数组属性添加子节点 appendChildInArrayProps(child: VNode, propName: string) { this.appendChild(child, this.getTargetChildrenArrayInPropChildren(propName)) } // 遍历当前节点或目标中的所有子节点 private mapChildren( cb: (vNode: VNode, key: string, fromArray: boolean) => boolean | void, mapTarget?: PropChildrenVNode | VNode[] ) { if (!mapTarget) { for (let i = 0; i < this.children.length; i++) { const item: VNode = this.children[i] if (item instanceof VNode && cb(item, ChildrenKey, true) === false) return } for (let key in this.basicWidgetPropChildren) { const item: PropChildrenVNodeType = this.basicWidgetPropChildren[key] if (!Array.isArray(item)) { if (item instanceof VNode && cb(item, key, false) === false) return } else { for (let i = 0; i < item.length; i++) { if (item[i] instanceof VNode && cb(item[i], key, true) === false) return } } } } else { if (Util.isArray(mapTarget)) { for (let i = 0; i < mapTarget.length; i++) { const item: VNode = mapTarget[i] if (item instanceof VNode && cb(item, '', true) === false) return } } else { for (let key in mapTarget) { const item: PropChildrenVNodeType = mapTarget[key] if (!Array.isArray(item)) { if (item instanceof VNode && cb(item, key, false) === false) return } else { for (let i = 0; i < item.length; i++) { if (item[i] instanceof VNode && cb(item[i], key, true) === false) return } } } } } } // 获取 basicWidgetPropChildren 中的某个数组属性 private getTargetChildrenArrayInPropChildren(propName: string): VNode[] { if (!this.basicWidgetPropChildren[propName]) this.basicWidgetPropChildren[propName] = [] return this.basicWidgetPropChildren[propName] as VNode[] } } /** * 生命周期类 */ export class LifeCycle { private static lifes: string[] = [ 'widgetDidMount', 'widgetDidUpdate', 'widgetDidUnmount', ] static widgetDidMount: string = LifeCycle.lifes[0] static widgetDidUpdate: string = LifeCycle.lifes[1] static widgetDidUnmount: string = LifeCycle.lifes[2] static isExist(lifeStep: string): boolean { return LifeCycle.lifes.indexOf(lifeStep) > -1 } }
the_stack
import ReactDOMServer from "react-dom/server" import { JSONOutput } from "typedoc" import * as React from "react" import { ReactNode, ReactElement } from "react" import * as fs from "fs" import { tmpNameSync, file } from "tmp" import { execSync } from "child_process" // import filesize from "filesize" import { gzip, gzipSync } from "zlib" // @ts-ignore import unescape from "unescape" import ReactMarkdown from "react-markdown" // @ts-ignore import unescape from "unescape" // import docjson from "./doc.json" // const tmpName = tmpNameSync({ postfix: ".json" }) const tmpName = "./out/doc.json" if (!process.argv.includes("--reusejson")) { // console.log("Writing typedoc --json to " + tmpName) execSync( "node node_modules/typedoc/bin/typedoc src/serializr.ts --mode library --json " + tmpName, { cwd: __dirname, stdio: "inherit" } ) } const docjson: JSONOutput.Reflection = require(tmpName) // @ts-ignore import { gfm } from "turndown-plugin-gfm" // @ts-ignore import TurndownService from "turndown" import { SourceReference } from "typedoc/dist/lib/models/sources/file" import { TypeAliasDeclaration } from "typescript" let scaleCounter = 0 const turndownService = new TurndownService({ codeBlockStyle: "fenced" }) turndownService.use(gfm) turndownService.keep(["sub"]) const sorter = (a: any, b: any) => a.sources[0].line - b.sources[0].line const gzippedBundleSize = 0 // const gzippedBundleSize = filesize( // gzipSync(fs.readFileSync("./dist/index.umd.min.js", "utf8")).byteLength // ) console.log("gzippedBundleSize:", gzippedBundleSize) function DocPage({ docJson }: { docJson: typeof docjson }) { // docJson.children[0].children.sort(sorter) return ( <> <h2>API</h2> {docJson.children.map(x => render(x, ""))} </> ) } function Typealias({ of: { type, sources, typeParameter, comment, name, id } }: { of: JSONOutput.TypeParameterReflection }) { return ( <> <h3 id={"typedoc-id-" + id}> <em>type</em> <code>{name}</code> <TypeParameters of={typeParameter} /> = <Type {...type} /> <Src {...sources[0]} /> </h3> <Comment of={comment} /> </> ) } function Comment(props: { of: any }) { const { shortText, text, tags } = props.of || {} return ( <> <ReactMarkdown source={shortText} /> <ReactMarkdown source={text} /> {(tags || []).map(({ tag, text }: { tag: string; text: string }, tagIndex) => { const out = (text: string, result?: React.ReactNode) => ( <React.Fragment key={tagIndex}> <em>example</em>{" "} <code> {text /* remove existing result in comment */ .replace(/\/\/\s*=.*?((?=\/\/)|$)/m, "") .trim()} </code>{" "} {result} <br /> </React.Fragment> ) if ("example" === tag) { return ( <pre> <code className="language-ts">{text.trim().replace(/\\@/g, "@")}</code> </pre> ) } return ( <p> @{tag} {text} </p> ) })} </> ) } function Class({ of: { name, kindString, comment, children, signatures, sources, typeParameter, flags, id } }: { of: JSONOutput.DeclarationReflection }) { if (kindString == "Variable" && flags.isConst) { kindString = "const" } return ( <> <h3 id={"typedoc-id-" + id}> <em>{kindString.toLowerCase()}</em> <code>{name}</code> <TypeParameters of={typeParameter} /> <Src {...sources[0]} /> </h3> <Comment of={comment} /> {signatures && signatures.map((sig, i) => ( <Signature of={{ ...sig, name: "__call" }} prefix={name} src={sources[i]} /> ))} {children && children.sort(sorter) && children.map(c => render(c, name))} </> ) } function Objectliteral({ name, kindString, comment, children, id }: JSONOutput.Reflection) { return ( <> <h3 id={"typedoc-id-" + id}> <em>{kindString}</em> <code>{name}</code> </h3> <Comment of={comment} /> </> ) } function Method({ of: { signatures, name, kindString, comment, children, sources }, prefix }: { of: JSONOutput.DeclarationReflection prefix: string }) { return ( <> {signatures.map((sig, i) => ( <Signature key={i} of={sig} prefix={prefix} src={sources[i]} kindString={kindString} /> ))} <Comment of={comment} /> {children && children.sort(sorter) && children.map(c => render(c, name))} </> ) } function Parameters({ of }: { of: JSONOutput.ParameterReflection[] }) { return of ? reactJoin( of.map(param => { const defaultMatch = param.comment && param.comment.text && param.comment.text.match(/default=(.*)$/m) const defaultValue = param.defaultValue || (defaultMatch && defaultMatch[1]) return ( <> {param.flags.isRest && "..."} <em>{param.name}</em> {param.flags.isOptional && !defaultMatch && "?"}:{" "} <Type {...param.type} noUndefinedInUnion={defaultValue} /> {defaultValue && " = " + defaultValue.trim()} </> ) }) ) : null } function TypeParameters({ of: typeParameters }: { of: JSONOutput.TypeParameterReflection[] }) { // tslint:disable-next-line:no-null-keyword react requires null return value if (!typeParameters) return null const uniqueTPs: JSONOutput.TypeParameterReflection[] = [] for (const tp of typeParameters) { if (!uniqueTPs.some(utp => utp.name == tp.name)) { uniqueTPs.push(tp) } } return ( <> {"&lt;"} {reactJoin( uniqueTPs.map(tp => tp.name), ", " )} {"&gt;"} </> ) } function TypeArguments({ of: typeParameters }: { of: JSONOutput.TypeParameterReflection[] }) { // tslint:disable-next-line:no-null-keyword react requires null return value if (!typeParameters) return null return ( <> {"&lt;"} {reactJoin( typeParameters.map(t => <Type {...t} />), ", " )} {"&gt;"} </> ) } function Signature({ of, prefix, src, kindString }: { of: JSONOutput.SignatureReflection prefix: string src: SourceReference kindString?: string }) { return ( <> <h3> <em>{(kindString || of.kindString).toLowerCase()}</em> <a id={of.name} /> <code> {prefix.toLowerCase()} {of.name} </code> <TypeParameters of={of.typeParameter} />(<Parameters of={of.parameters} /> ): <Type {...of.type} /> <Src {...src} /> </h3> <Comment of={of.comment} /> </> ) } function Type(type: any) { switch (type.type) { case "reference": return ( <> <a href={"typedoc-id-" + type.id}>{type.name}</a> <TypeArguments of={type.typeArguments} /> </> ) case "intrinsic": case "typeParameter": case "unknown": return type.name case "query": return ( <> typeof <Type {...type.queryType} /> </> ) case "union": return reactJoin( type.types .filter( t => !( type.noUndefinedInUnion && t.type == "intrinsic" && t.name == "undefined" ) ) .map(t => ( <Type {...t} inUnion={true} noUndefinedInUnion={type.noUndefinedInUnion} /> )), " | " ) case "tuple": return <>[{reactJoin(type.elements.map((type, i) => <Type {...type} />))}]</> case "reflection": try { if (type.declaration.signatures?.length == 1) { const sig = type.declaration.signatures[0] return ( <> {type.inUnion && "("}(<Parameters of={sig.parameters} />) =&gt;{" "} <Type {...sig.type} /> {type.inUnion && ")"} </> ) } else if (type.declaration.kindString === "Type literal") { return ( <> {"{ "} {type.declaration.children?.map(c => { if ("Variable" === c.kindString) { return ( <> {c.name}: <Type {...c.type} /> </> ) } })} {" }"} </> ) } else { return <Json of={type} /> } } catch (e) { console.log(e) return JSON.stringify(type) } case "array": return ( <> <Type {...type.elementType} /> [] </> ) case "stringLiteral": return <code>{JSON.stringify(type.value)}</code> case "typeOperator": return "typeof " + type } console.error(type) return JSON.stringify(type) // throw new Error(type) } function Json({ of }: { of: any }) { return ( <pre className="language-js"> <code>{JSON.stringify(of, undefined, " ")}</code> </pre> ) } function Src(x: SourceReference) { return ( <sub> <a href={"src/" + x.fileName + "#L" + x.line}>src</a> </sub> ) } 1 function Property({ of }: { of: JSONOutput.DeclarationReflection }) { return ( <> <h4> {of.kindString.toLowerCase()} <code>{of.name}</code> {of.flags.isOptional && "?"}: <Type {...of.type} /> </h4> <Comment of={of.comment} /> {/* <Json of={of} /> */} </> ) } const X: { [what: string]: React.ComponentType<any> } = { Comment, Typealias, Class, Method, Function: Method, Objectliteral, Property } function render(child: JSONOutput.Reflection, prefix: string): React.ReactNode { const n = child.kindString.replace(/\s+/g, "") const What = X[n] || Class if (child.flags && child.flags.isPrivate) { return undefined } if (child.comment?.tags?.some(tag => tag.tag === "internal")) { return undefined } if (!child.flags.isExported && !["Interface", "Class"].includes(child.kindString)) { return undefined } if (!What) throw new Error(child.kindString) return What && <What key={child.name} of={child} prefix={prefix} /> } function reactJoin(x: React.ReactNode[], joiner: React.ReactNode = ", ") { const result: React.ReactNode[] = [] x.forEach((x, i) => result.push(...(0 == i ? [x] : [joiner, x]))) return <>{result}</> } // render twice to resolve references const html1 = ReactDOMServer.renderToStaticMarkup(<DocPage docJson={docjson} />) const idToHrefMap: Map<number, string> = new Map() let match const regex = /<h\d id="typedoc-id-(\d+)">(.*?)<\/h\d>/g while ((match = regex.exec(html1))) { console.log("match", match[1]) // see https://github.com/jch/html-pipeline/blob/master/lib/html/pipeline/toc_filter.rb const PUNCTUATION_REGEXP = /[^\w\- ]/g const [, id, h] = match const href = "#" + unescape( unescape( h .toLowerCase() .replace(/<.*?>/g, "") // remove tags .replace(/\s+/g, " ") ) ) .trim() .replace(PUNCTUATION_REGEXP, "") .replace(/ /g, "-") !idToHrefMap.has(+id) && idToHrefMap.set(+id, href) } const htmlWithGfmLinks = html1.replace(/href="typedoc-id-(\d+)"/g, (m, id) => { const href = idToHrefMap.get(+id) if (!href) { console.warn("did not find href for typedoc-id-" + id) return m } return 'href="' + href + '"' }) const md = turndownService.turndown(htmlWithGfmLinks) const mdFileName = "README.md" const prevReadme = fs.readFileSync(mdFileName, "utf8") const findRegex = /<!-- START API AUTOGEN -->[\s\S]*?<!-- END API AUTOGEN -->/m if (!findRegex.test(prevReadme)) { throw new Error("DID NOT FIND THINGS IN README") } const newReadme = prevReadme.replace( findRegex, "<!-- START API AUTOGEN -->\n" + "<!-- THIS SECTION WAS AUTOGENERATED BY gendoc.tsx! DO NOT EDIT! -->\n" + md + "<!-- END API AUTOGEN -->" ) fs.writeFileSync(mdFileName, newReadme, "utf8") fs.writeFileSync("out/README.html", htmlWithGfmLinks, "utf8")
the_stack
import * as assert from "power-assert"; import { kubernetesSpecFileBasename, kubernetesSpecStringify, parseKubernetesSpecs, specSlug, specSnippet, specStringSnippet, } from "../../../../lib/pack/k8s/kubernetes/spec"; /* tslint:disable:max-file-line-count */ describe("pack/k8s/kubernetes/spec", () => { describe("kubernetesSpecFileBasename", () => { it("should create a namespace file name", () => { const o = { apiVersion: "v1", kind: "Namespace", metadata: { name: "lyle", }, }; const s = kubernetesSpecFileBasename(o); assert(s === "10_lyle_namespace"); }); it("should create a simple namespaced file name", () => { [ { a: "apps/v1", k: "Deployment", p: "70" }, { a: "networking.k8s.io/v1beta1", k: "Ingress", p: "80" }, { a: "rbac.authorization.k8s.io/v1", k: "Role", p: "25" }, { a: "v1", k: "Secret", p: "60" }, { a: "v1", k: "Service", p: "50" }, ].forEach(r => { const o = { apiVersion: r.a, kind: r.k, metadata: { name: "lyle", namespace: "lovett", }, }; const s = kubernetesSpecFileBasename(o); const e = r.p + "_lovett_lyle_" + r.k.toLowerCase(); assert(s === e); }); }); it("should create a kebab-case namespaced file name", () => { [ { a: "v1", k: "ServiceAccount", l: "service-account", p: "20" }, { a: "rbac.authorization.k8s.io/v1", k: "RoleBinding", l: "role-binding", p: "30" }, { a: "apps/v1", k: "DaemonSet", l: "daemon-set", p: "70" }, { a: "networking.k8s.io/v1", k: "NetworkPolicy", l: "network-policy", p: "40" }, { a: "v1", k: "PersistentVolumeClaim", l: "persistent-volume-claim", p: "40" }, { a: "extensions/v1beta1", k: "PodSecurityPolicy", l: "pod-security-policy", p: "40" }, { a: "policy/v1beta1", k: "HorizontalPodAutoscaler", l: "horizontal-pod-autoscaler", p: "80" }, { a: "policy/v1beta1", k: "PodDisruptionBudget", l: "pod-disruption-budget", p: "80" }, ].forEach(r => { const o = { apiVersion: r.a, kind: r.k, metadata: { name: "lyle", namespace: "lovett", }, }; const s = kubernetesSpecFileBasename(o); const e = r.p + "_lovett_lyle_" + r.l; assert(s === e); }); }); it("should create a kebab-case cluster file name", () => { [ { a: "v1", k: "PersistentVolume", l: "persistent-volume", p: "15" }, { a: "storage.k8s.io/v1", k: "StorageClass", l: "storage-class", p: "15" }, { a: "rbac.authorization.k8s.io/v1", k: "ClusterRole", l: "cluster-role", p: "25" }, { a: "rbac.authorization.k8s.io/v1", k: "ClusterRoleBinding", l: "cluster-role-binding", p: "30" }, ].forEach(r => { const o = { apiVersion: r.a, kind: r.k, metadata: { name: "lyle", }, }; const s = kubernetesSpecFileBasename(o); const e = r.p + "_lyle_" + r.l; assert(s === e); }); }); }); describe("kubernetesSpecStringify", () => { it("should stringify a spec", async () => { const r = { apiVersion: "v1", kind: "Service", metadata: { name: "kubernetes", namespace: "default", labels: { component: "apiserver", provider: "kubernetes", }, }, spec: { type: "ClusterIP", ports: [ { name: "https", protocol: "TCP", port: 443, targetPort: 8443, }, ], sessionAffinity: "None", clusterIP: "10.96.0.1", }, }; const s = await kubernetesSpecStringify(r); const e = `{ "apiVersion": "v1", "kind": "Service", "metadata": { "labels": { "component": "apiserver", "provider": "kubernetes" }, "name": "kubernetes", "namespace": "default" }, "spec": { "clusterIP": "10.96.0.1", "ports": [ { "name": "https", "port": 443, "protocol": "TCP", "targetPort": 8443 } ], "sessionAffinity": "None", "type": "ClusterIP" } } `; assert(s === e); }); it("should stringify a spec to yaml", async () => { const r = { apiVersion: "v1", kind: "Service", metadata: { name: "kubernetes", namespace: "default", labels: { component: "apiserver", provider: "kubernetes", }, }, spec: { type: "ClusterIP", ports: [ { name: "https", protocol: "TCP", port: 443, targetPort: 8443, }, ], sessionAffinity: "None", clusterIP: "10.96.0.1", }, }; const s = await kubernetesSpecStringify(r, { format: "yaml" }); const e = `apiVersion: v1 kind: Service metadata: labels: component: apiserver provider: kubernetes name: kubernetes namespace: default spec: clusterIP: 10.96.0.1 ports: - name: https port: 443 protocol: TCP targetPort: 8443 sessionAffinity: None type: ClusterIP `; assert(s === e); }); it("should encrypt secret values", async () => { const r = { apiVersion: "v1", kind: "Secret", type: "Opaque", metadata: { name: "butterfly", namespace: "the-hollies", }, data: { year: "MTk2Nw==", studio: "QWJiZXkgUm9hZCBTdHVkaW9z", producer: "Um9uIFJpY2hhcmRz", }, }; const k = "Dear Eloise / King Midas in Reverse"; const s = await kubernetesSpecStringify(r, { secretKey: k }); const e = `{ "apiVersion": "v1", "data": { "producer": "fIXYFs7jyC5iLxbeC3iGuYdgMhA/hxHaX80SocbXKX4=", "studio": "CC4ZtaHs9d3f5uZ9FoTAuLGel2mTG+Wmj6iOdssUoi4=", "year": "gqOPJs0mmn7vj7PMjQl7Hg==" }, "kind": "Secret", "metadata": { "name": "butterfly", "namespace": "the-hollies" }, "type": "Opaque" } `; assert(s === e); }); }); describe("parseKubernetesSpecs", () => { it("should parse JSON", async () => { const c = `{ "apiVersion": "v1", "kind": "Service", "metadata": { "name": "satisfied-mind", "namespace": "the-byrds" }, "spec": { "ports": [ { "port": 80 } ], "selector": { "app.kubernetes.io/name": "satisfied-mind" } } } `; const s = parseKubernetesSpecs(c); const e = [ { apiVersion: "v1", kind: "Service", metadata: { name: "satisfied-mind", namespace: "the-byrds", }, spec: { ports: [ { port: 80, }, ], selector: { "app.kubernetes.io/name": "satisfied-mind", }, }, }, ]; assert.deepStrictEqual(s, e); }); it("should parse YAML", async () => { const c = `apiVersion: apps/v1 kind: Deployment metadata: name: turn-turn-turn namespace: the-byrds spec: template: spec: serviceAccountName: sdm-serviceaccount terminationGracePeriodSeconds: 180 `; const s = parseKubernetesSpecs(c); const e = [ { apiVersion: "apps/v1", kind: "Deployment", metadata: { name: "turn-turn-turn", namespace: "the-byrds", }, spec: { template: { spec: { serviceAccountName: "sdm-serviceaccount", terminationGracePeriodSeconds: 180, }, }, }, }, ]; assert.deepStrictEqual(s, e); }); it("should parse empty YAML and return nothing", async () => { [undefined, "", " ", "\n"].forEach(c => { const s = parseKubernetesSpecs(c); assert.deepStrictEqual(s, []); }); }); it("should filter out non-specs", async () => { [ "", "{}", `{"apiVersion":"v1"}`, `{"kind":"Secret"}`, `{"metadata":{"name":"niteclub"}}`, `{"apiVersion":"v1","kind":"Secret"}`, `{"kind":"Secret","metadata":{"name":"niteclub"}}`, `{"apiVersion":"v1","kind":"Secret","metadata":{"namespace":"old97s"}}`, ].forEach(c => { const s = parseKubernetesSpecs(c); assert.deepStrictEqual(s, []); }); }); it("should parse multiple YAML documents", async () => { const c = `apiVersion: v1 kind: Namespace metadata: name: cert-manager labels: certmanager.k8s.io/disable-validation: "true" --- --- # Source: cert-manager/charts/cainjector/templates/serviceaccount.yaml apiVersion: v1 kind: ServiceAccount metadata: name: cert-manager-cainjector namespace: "cert-manager" labels: app: cainjector app.kubernetes.io/name: cainjector app.kubernetes.io/instance: cert-manager app.kubernetes.io/managed-by: Tiller helm.sh/chart: cainjector-v0.9.1 --- # Source: cert-manager/charts/webhook/templates/serviceaccount.yaml apiVersion: v1 kind: ServiceAccount metadata: name: cert-manager-webhook namespace: "cert-manager" labels: app: webhook app.kubernetes.io/name: webhook app.kubernetes.io/instance: cert-manager app.kubernetes.io/managed-by: Tiller helm.sh/chart: webhook-v0.9.1 --- # Source: cert-manager/templates/serviceaccount.yaml apiVersion: v1 kind: ServiceAccount metadata: name: cert-manager namespace: "cert-manager" labels: app: cert-manager app.kubernetes.io/name: cert-manager app.kubernetes.io/instance: cert-manager app.kubernetes.io/managed-by: Tiller helm.sh/chart: cert-manager-v0.9.1 --- `; const s = parseKubernetesSpecs(c); const e = [ { apiVersion: "v1", kind: "Namespace", metadata: { name: "cert-manager", labels: { "certmanager.k8s.io/disable-validation": "true", }, }, }, { apiVersion: "v1", kind: "ServiceAccount", metadata: { name: "cert-manager-cainjector", namespace: "cert-manager", labels: { "app": "cainjector", "app.kubernetes.io/name": "cainjector", "app.kubernetes.io/instance": "cert-manager", "app.kubernetes.io/managed-by": "Tiller", "helm.sh/chart": "cainjector-v0.9.1", }, }, }, { apiVersion: "v1", kind: "ServiceAccount", metadata: { name: "cert-manager-webhook", namespace: "cert-manager", labels: { "app": "webhook", "app.kubernetes.io/name": "webhook", "app.kubernetes.io/instance": "cert-manager", "app.kubernetes.io/managed-by": "Tiller", "helm.sh/chart": "webhook-v0.9.1", }, }, }, { apiVersion: "v1", kind: "ServiceAccount", metadata: { name: "cert-manager", namespace: "cert-manager", labels: { "app": "cert-manager", "app.kubernetes.io/name": "cert-manager", "app.kubernetes.io/instance": "cert-manager", "app.kubernetes.io/managed-by": "Tiller", "helm.sh/chart": "cert-manager-v0.9.1", }, }, }, ]; assert.deepStrictEqual(s, e); }); }); describe("specSlug", () => { it("should return a namespaced slug", () => { const s = { apiVersion: "v1", kind: "Service", metadata: { name: "mermaid", namespace: "avenue", }, }; const l = specSlug(s); const e = "v1/avenue/services/mermaid"; assert(l === e); }); it("should return pluralize properly", () => { const s = { apiVersion: "networking.k8s.io/v1beta1", kind: "Ingress", metadata: { name: "mermaid", namespace: "avenue", }, }; const l = specSlug(s); const e = "networking.k8s.io/v1beta1/avenue/ingresses/mermaid"; assert(l === e); }); it("should return a cluster slug", () => { const s = { apiVersion: "policy/v1beta1", kind: "PodSecurityPolicy", metadata: { name: "mermaid", }, }; const l = specSlug(s); const e = "policy/v1beta1/podsecuritypolicies/mermaid"; assert(l === e); }); }); describe("specSnippet", () => { it("should return the full string", () => { const s = { apiVersion: "v1", kind: "Service", metadata: { name: "mermaid", namespace: "avenue", }, }; const l = specSnippet(s); const e = `{"apiVersion":"v1","kind":"Service","metadata":{"name":"mermaid","namespace":"avenue"}}`; assert(l === e); }); it("should truncate the spec string", () => { const s = { apiVersion: "v1", kind: "Service", metadata: { labels: { component: "apiserver", provider: "kubernetes", }, name: "kubernetes", namespace: "default", resourceVersion: "37", selfLink: "/api/v1/namespaces/default/services/kubernetes", uid: "e68c82ed-111d-11ea-980a-080027477353", }, spec: { clusterIP: "10.96.0.1", ports: [ { name: "https", port: 443, protocol: "TCP", targetPort: 8443, }, ], sessionAffinity: "None", type: "ClusterIP", }, status: { loadBalancer: {}, }, }; const l = specSnippet(s); // tslint:disable-next-line:max-line-length const e = `{"apiVersion":"v1","kind":"Service","metadata":{"labels":{"component":"apiserver","provider":"kubernetes"},"name":"kubernetes","namespace":"default","resourceVersion":"37","selfLink":"/api/v1/name...}`; assert(l === e); }); }); describe("specSnippet", () => { it("should return the full string", () => { const s = `{"apiVersion":"v1","kind":"Service","metadata":{"name":"mermaid","namespace":"avenue"}}`; const l = specStringSnippet(s); assert(l === s); }); it("should truncate the string", () => { /* tslint:disable:max-line-length */ const s = `{"apiVersion":"v1","kind":"Service","metadata":{"labels":{"component":"apiserver","provider":"kubernetes"},"name":"kubernetes","namespace":"default","resourceVersion":"37","selfLink":"/api/v1/nameces/default/services/kubernetes","uid":"e68c82ed-111d-11ea-980a-080027477353"},"spec":{"clusterIP":"10.96.0.1","ports":[{"name":"https","port":443,"protocol":"TCP","targetPort":8443}],"sessionAffinity":"None","type":"ClusterIP"},"status":{"loadBalancer":{}}}`; const l = specStringSnippet(s); const e = `{"apiVersion":"v1","kind":"Service","metadata":{"labels":{"component":"apiserver","provider":"kubernetes"},"name":"kubernetes","namespace":"default","resourceVersion":"37","selfLink":"/api/v1/name...}`; /* tslint:enable:max-line-length */ assert(l === e); }); }); });
the_stack
import firebase from "firebase/app"; import { Alert, AsyncStorage, Dimensions } from "react-native"; import Settings from "../constants/Settings"; import Fire from "../ExpoParty/Fire"; import GameStates from "../Game/GameStates"; import Constants from "expo-constants"; import * as Facebook from "expo-facebook"; import { takeSnapshotAsync } from "expo"; import getDeviceInfo from "../utils/getUserInfo"; import * as Analytics from "expo-firebase-analytics"; import Challenges from "../constants/Achievements"; import * as StoreReview from "expo-store-review"; export const skins = { state: {}, reducers: { setBest: (state, best) => ({ ...state, best }), increment: ({ current, best, isBest, ...props }) => {}, }, effects: { sync: () => {}, unlock: ({ key }, { skins }) => { if (skins) { } }, }, }; export type PresentAchievementShape = null | { id: string; name: string; }; export const presentAchievement = { state: null, reducers: { set: ( state: PresentAchievementShape, val: PresentAchievementShape ): PresentAchievementShape => val, }, effects: {}, }; export type AchievementsShape = Record<string, true>; export const achievements = { state: {}, reducers: { _reset: () => ({}), set: ( state: AchievementsShape, val: AchievementsShape ): AchievementsShape => ({ ...state, ...val }), }, effects: { sync: () => {}, unlock: ( key: string, { achievements }: { achievements: AchievementsShape } ) => { if (!achievements[key] && Challenges[key]) { Analytics.logEvent("achievement_unlocked", { id: [key], ...Challenges[key], }); dispatch.achievements.set({ [key]: true }); dispatch.presentAchievement.set({ id: key, ...Challenges[key] }); } }, }, }; import { promptToReviewAsync } from "../utils/promptStoreReview"; // A cached value that represents the amount of times a user has beaten their best score. // Logic for store review: // Since you can only prompt to review roughly once, we want to ensure that only users who like the game are prompted to rate it. // We can determine if they like the game based on if they keep playing it. export const bestRounds = { state: 0, reducers: { _reset: () => 0, set: (state: number, rounds: number): number => rounds, }, effects: { increment: ( input: unknown, { score, bestRounds }: { score: ScoreShape; bestRounds: number } ) => { const next = bestRounds + 1; Analytics.logEvent("had_best_round", { count: bestRounds, score: score.total, }); // if the user ever beats their highscore twice after the first day of using the app, prompt them to rate the app. if (bestRounds > 1) { dispatch.storeReview.promptAsync(); } dispatch.bestRounds.set(next); }, }, }; function hasBeenAtLeastOneDaySinceTime(time: number): boolean { // 1 Day after the last prompt time (or since the app was first opened). const appropriateTimeToAskAgain = new Date(time); // DEBUG: Wait 20 seconds // appropriateTimeToAskAgain.setSeconds( // appropriateTimeToAskAgain.getSeconds() + 20 // ); // Wait 1 day appropriateTimeToAskAgain.setDate(appropriateTimeToAskAgain.getDate() + 1); const hasBeenAtLeastOneDay = new Date() > appropriateTimeToAskAgain; return hasBeenAtLeastOneDay; } export type StoreReviewShape = { promptTime: number; }; export const storeReview = { state: { promptTime: Date.now() }, reducers: { _reset: () => ({ promptTime: Date.now() }), set: ( state: StoreReviewShape, value: Partial<StoreReviewShape> ): StoreReviewShape => ({ ...state, ...value }), }, effects: { promptAsync: async ( input: unknown, { storeReview }: { storeReview: StoreReviewShape } ) => { const isAvailable = await StoreReview.isAvailableAsync(); if (!isAvailable) return; const isReady = hasBeenAtLeastOneDaySinceTime(storeReview.promptTime); console.log("prompt async: ", storeReview.promptTime); if (!isReady) return; dispatch.storeReview.set({ promptTime: Date.now() }); await promptToReviewAsync(); }, }, }; export const rounds = { state: 0, reducers: { _reset: () => 0, set: (state: number, rounds: number): number => rounds, }, effects: { increment: (input: unknown, { rounds }: { rounds: number }) => { const next = rounds + 1; if (next === 10) { dispatch.achievements.unlock("rounds-10"); } else if (next === 50) { dispatch.achievements.unlock("rounds-50"); } else if (next === 100) { dispatch.achievements.unlock("rounds-100"); } else if (next === 500) { dispatch.achievements.unlock("rounds-500"); } else if (next === 1000) { dispatch.achievements.unlock("rounds-1000"); } dispatch.rounds.set(next); }, }, }; export type ScoreShape = { current: number; best: number; total: number; last: number | null; isBest: boolean; }; const initialScoreState: ScoreShape = { current: 0, best: 0, total: 0, last: null, isBest: false, }; export const score = { state: { ...initialScoreState }, reducers: { _hardReset: () => ({ ...initialScoreState }), setBest: (state: ScoreShape, best: number): ScoreShape => ({ ...state, best, }), setTotal: (state: ScoreShape, total: number): ScoreShape => ({ ...state, total, }), increment: ({ current, best, isBest, ...props }: ScoreShape): ScoreShape => { const nextScore = current + 1; return { current: nextScore, best: Math.max(nextScore, best), isBest: nextScore > best, ...props, }; }, _reset: (state: ScoreShape): ScoreShape => ({ ...state, current: 0, last: state.current, isBest: false, }), }, effects: { updateTotal(current: number, { score }: { score: ScoreShape }) { const total = score.total + current; if (current > 100) { dispatch.achievements.unlock("score-100"); } else if (current > 50) { dispatch.achievements.unlock("score-50"); } else if (current > 20) { dispatch.achievements.unlock("score-20"); } if (total > 10000) { dispatch.achievements.unlock("total-score-10000"); } else if (total > 5000) { dispatch.achievements.unlock("total-score-5000"); } else if (total > 1000) { dispatch.achievements.unlock("total-score-1000"); } else if (total > 500) { dispatch.achievements.unlock("total-score-500"); } dispatch.score.setTotal(total); }, reset: (props: unknown, { score }: { score: ScoreShape }) => { if (Settings.isEveryScoreBest) { dispatch.score.setHighScore(score.current); } else if (score.isBest) { dispatch.score.setHighScore(score.best); } dispatch.score.updateTotal(score.current); dispatch.score._reset(); dispatch.rounds.increment(); }, setHighScore: async (highScore: number, { user }) => { dispatch.bestRounds.increment(); if (!Settings.isFirebaseEnabled) { return; } const { displayName, photoURL } = user; console.log("set High score", highScore); const _displayName = parseName(displayName); const docRef = Fire.doc; try { await Fire.db.runTransaction((transaction) => transaction.get(docRef).then((doc) => { if (!doc.exists) { throw new Error("Document does not exist!"); } const data = doc.data(); const cloudHighScore = data.score || 0; console.log("cloud score", cloudHighScore); if (Settings.isEveryScoreBest || highScore > cloudHighScore) { transaction.update(docRef, { score: highScore, timestamp: Date.now(), displayName: _displayName, photoURL: photoURL || "", }); } else { transaction.update(docRef, { ...data, displayName: _displayName, photoURL: photoURL || "", }); dispatch.score.setBest(cloudHighScore); } }) ); console.log("Successfully wrote score"); } catch ({ message }) { console.log("Failed to write score", message); Alert.alert(message); } }, }, }; export const currency = { state: { current: 0, }, reducers: { change: ({ current, ...props }, value) => { return { current: current + value, ...props, }; }, _reset: (state) => ({ ...state, current: 0, }), }, effects: {}, }; export const game = { state: GameStates.Menu, reducers: { play: () => GameStates.Playing, menu: () => GameStates.Menu, }, effects: {}, }; export const muted = { state: false, reducers: { toggle: (state: boolean): boolean => { Analytics.logEvent("toggle_music", { on: !state }); return !state; }, }, effects: {}, }; export const screenshot = { state: null, reducers: { update: (state, uri) => uri, }, effects: { updateAsync: async ({ ref }) => { const { width, height } = Dimensions.get("window"); const options = { format: "jpg", quality: 0.3, result: "file", height, width, }; const uri = await takeSnapshotAsync(ref, options); dispatch.screenshot.update(uri); }, }, }; async function incrementDailyReward() { const timestamp = Date.now(); return new Promise((res, rej) => { Fire.db .runTransaction((transaction) => transaction.get(Fire.doc).then((userDoc) => { console.log("Fire.doc", Fire.doc); if (!userDoc.exists) { throw new Error("Document does not exist!"); } const data = userDoc.data(); const { lastRewardTimestamp } = data; const hours = Math.abs(lastRewardTimestamp - timestamp) / 36e5; // 60000; if (hours >= 24) { if (hours >= 48) { // console.log('More than a day'); // It has been more than 1 day since the last visit - break the streak const newDailyVisits = 0; transaction.update(Fire.doc, { dailyVisits: newDailyVisits, lastRewardTimestamp: timestamp, }); // / TODO:EVAN: save timestamp // this.userData.lastRewardTimestamp = timestamp; return newDailyVisits; } // console.log('You were here yesterday'); // Perfect! It has been 1 day since the last visit - increment streak and save current time const dailyVisits = data.dailyVisits || 0; const newDailyVisits = dailyVisits + 1; transaction.update(Fire.doc, { dailyVisits: newDailyVisits, lastRewardTimestamp: timestamp, }); // / TODO:EVAN: save timestamp // this.userData.lastRewardTimestamp = timestamp; return newDailyVisits; } // console.log('Within day'); transaction.update(Fire.doc, { dailyVisits: data.dailyVisits || 0, lastRewardTimestamp: data.lastRewardTimestamp || Date.now(), }); // It hasn't been a day yet - do nothing return data.dailyVisits || 0; }) ) .then(res) .catch(rej); }); } export const dailyStreak = { state: 0, reducers: { increment: (s) => s + 1, set: (s, props) => props, reset: () => 0, }, effects: { rewardUser: async (streak) => { console.log("award", streak); }, compareDaily: async (props, { user }) => { const dailyVisits = await incrementDailyReward(); if (dailyVisits !== user.dailyVisits) { // console.log('Yay! You came back, your streak is now at: ' + dailyVisits); dispatch.dailyStreak.set(dailyVisits); if (dailyVisits > user.dailyVisits) { dispatch.dailyStreak.rewardUser(dailyVisits); } dispatch.user.update({ dailyVisits }); // / Give reward! } else { // console.log('ummmm', dailyVisits); } }, }, }; function mergeInternal(state, { uid, user }) { const { [uid]: currentUser, ...otherUsers } = state; return { ...otherUsers, [uid]: { ...(currentUser || {}), ...user }, }; } function parseName(inputName, backupName) { let name = inputName || backupName || "Markipillar"; if (typeof name === "string") { name = name.trim(); } return name; } export const leaders = { state: {}, reducers: { batchUpdate: (state, users) => { let nextData = state; for (const user of users) { nextData = mergeInternal(nextData, user); } return nextData; }, update: (state, { uid, user }) => mergeInternal(state, { uid, user }), set: (state, { uid, user }) => { const { [uid]: currentUser, ...otherUsers } = state; return { ...otherUsers, [uid]: user, }; }, clear: () => ({}), }, effects: { getPagedAsync: async ({ start, size, callback }) => { // This is just a place holder to prevent constant updates in development if (__DEV__) { dispatch.leaders.batchUpdate([ { uid: "0oK50HoGt6PqXG1ApBTroS3IxR23", user: { key: "0oK50HoGt6PqXG1ApBTroS3IxR23", uid: "0oK50HoGt6PqXG1ApBTroS3IxR23", displayName: "Evan Bacon", dailyVisits: 1, lastRewardTimestamp: 1531172844644, photoURL: "https://graph.facebook.com/10209775308018161/picture", rank: 999999, score: 33, timestamp: 1531019432478, }, }, { uid: "R2XBuw9im3QBtpU6YYck2tdhpEI3", user: { key: "R2XBuw9im3QBtpU6YYck2tdhpEI3", uid: "R2XBuw9im3QBtpU6YYck2tdhpEI3", displayName: "Expo iPhone X", appOwnership: "expo", dailyVisits: 0, deviceId: "9E917464-CF47-417B-AA41-07E52190F26A", deviceName: "Expo iPhone X", deviceYearClass: 2017, expoVersion: "2.4.7.1013849", isDevice: true, lastRewardTimestamp: 1524197897114, platform: { ios: { buildNumber: "2.4.7.1013849", model: "iPhone X", platform: "iPhone10,6", systemVersion: "11.0.1", userInterfaceIdiom: "handset", }, }, score: 1, slug: "crossy-road", }, }, ]); return; } const collection = firebase .firestore() .collection(Settings.slug) .where("score", ">", 0); let ref = collection.orderBy("score", "desc").limit(size); try { if (start) { ref = ref.startAfter(start); } const querySnapshot = await ref.get(); const data = []; querySnapshot.forEach((doc) => { if (!doc.exists) { console.log("leaders.getPagedAsync(): Error: data doesn't exist", { size, start, }); } else { const _data = doc.data(); const uid = doc.id; data.push({ uid, user: { key: uid, uid, displayName: parseName(_data.displayName, _data.deviceName), ..._data, }, }); } }); console.log("Batch update", data.length, JSON.stringify(data)); // console.log("Batch update", data.length, { data }); dispatch.leaders.batchUpdate(data); const cursor = querySnapshot.docs[querySnapshot.docs.length - 1]; if (callback) callback({ data, cursor, noMore: data.length < size }); return; } catch (error) { console.error("Error getting documents: ", error); } if (callback) callback({}); }, getAsync: async ({ uid, callback }) => { try { const ref = firebase.firestore().collection(Settings.slug).doc(uid); const doc = await ref.get(); if (!doc.exists) { if (uid === Fire.uid) { const currentUser = firebase.auth().currentUser || {}; const _displayName = parseName( currentUser.displayName, Constants.deviceName ); const nUser = { rank: 999999, displayName: _displayName, photoURL: currentUser.photoURL || "", score: 0, timestamp: Date.now(), }; ref.set(nUser); if (callback) callback(nUser); return; } console.log(`No document: leaders/${uid}`); } else { const user = doc.data(); console.log("got leader", user); dispatch.leaders.update({ uid, user }); if (callback) callback(user); return; } } catch ({ message }) { console.log("Error: leaders.get", message); alert(message); } if (callback) callback(null); }, }, }; export const players = { state: {}, reducers: { update: (state, { uid, user }) => { const { [uid]: currentUser, ...otherUsers } = state; return { ...otherUsers, [uid]: { ...(currentUser || {}), ...user }, }; }, set: (state, { uid, user }) => { const { [uid]: currentUser, ...otherUsers } = state; return { ...otherUsers, [uid]: user, }; }, clear: () => ({}), }, effects: { getAsync: async ({ uid, callback }) => { // DO NOTHING IN DEV return; try { const ref = firebase.firestore().collection("players").doc(uid); const doc = await ref.get(); if (!doc.exists) { console.log(`No document: players/${uid}`); if (uid === Fire.uid) { const currentUser = firebase.auth().currentUser || {}; const _displayName = parseName( currentUser.displayName, Constants.deviceName ); const user = { rank: 999999, displayName: _displayName, score: 0, timestamp: Date.now(), }; if (currentUser.photoURL) { user.photoURL = currentUser.photoURL; } ref.add(user); dispatch.players.update({ uid, user }); if (callback) callback(user); } else { dispatch.leaders.getAsync({ uid, callback: (user) => { if (user) { dispatch.players.update({ uid, user }); } if (callback) callback(user); }, }); } } else { const user = doc.data(); console.log("got player", user); dispatch.players.update({ uid, user }); if (callback) callback(user); } } catch ({ message }) { console.log("Error: players.get", message); Alert.alert(message); } }, }, }; function reduceFirebaseUser(user) { const nextUser = user; const possibleUpdates = {}; if (user.providerData && user.providerData.length > 0) { const facebookData = user.providerData[0]; nextUser.fbuid = facebookData.uid; const keysToCheck = ["displayName", "photoURL"]; for (const key of keysToCheck) { if (!nextUser[key] && facebookData[key]) { possibleUpdates[key] = facebookData[key]; } } if (Object.keys(possibleUpdates).length > 0) { const user = firebase.auth().currentUser; console.log({ possibleUpdates }); firebase.auth().currentUser.updateProfile(possibleUpdates); } // //DEBUG Clear // firebase // .auth() // .currentUser.updateProfile({ displayName: null, photoURL: null }); } const { uid, photoURL, phoneNumber, lastLoginAt, isAnonymous, fbuid, displayName, emailVerified, email, createdAt, } = nextUser; return { uid, photoURL: photoURL || "", phoneNumber, lastLoginAt, isAnonymous, fbuid, displayName: displayName || Constants.deviceName, emailVerified, email, createdAt, ...possibleUpdates, // stsTokenManager, // redirectEventId, // authDomain, // appName, // apiKey }; } export const user = { state: null, reducers: { update: (state, props) => ({ ...state, ...props }), set: (state, props) => props, clear: () => null, }, effects: { logoutAsync: async (props, { players }) => { try { const uid = firebase.auth().currentUser.uid; await firebase.auth().signOut(); // dispatch.leaders.set({ uid, user: null }); } catch ({ message }) { console.log("ERROR: user.logoutAsync: ", message); Alert.alert(message); } }, signInAnonymously: () => { try { firebase.auth().signInAnonymously(); } catch ({ message }) { console.log("Error: signInAnonymously", message); Alert.alert(message); } }, observeAuth: (props) => { firebase.auth().onAuthStateChanged((user) => { if (!user) { // TODO: Evan: Y tho... dispatch.user.clear(); dispatch.user.signInAnonymously(); } else { dispatch.user.getAsync(); // DISABLED IN DEV // dispatch.leaders.getAsync({ uid: user.uid }); } }); }, getAsync: async (props, { user: localUserData }) => { const nextLocalUserData = localUserData || {}; let combinedUserData = {}; const firebaseAuthData = firebase.auth().currentUser.toJSON(); if (firebaseAuthData == null) { console.warn( "models: Shouldn't call user.getAsync until the user is authed" ); return; } const nextFirebaseAuthData = reduceFirebaseUser(firebaseAuthData); const deviceInfo = getDeviceInfo(); combinedUserData = { ...deviceInfo, ...nextFirebaseAuthData, }; const updates = {}; for (const key of Object.keys(combinedUserData)) { if ( combinedUserData[key] != undefined && combinedUserData[key] !== nextLocalUserData[key] ) { updates[key] = combinedUserData[key]; } } if (Object.keys(updates).length > 0) { dispatch.user.update(updates); } // dispatch.dailyStreak.compareDaily(); dispatch.players.update({ uid: combinedUserData.uid, user: combinedUserData, }); // THIS IS DEV ONLY return; if (Settings.isCacheProfileUpdateActive) { const shouldUpdateKey = "@PillarValley/shouldUpdateProfile"; const something = await getItemWithExpiration(shouldUpdateKey); if (!something) { const some = await setItemWithExpiration( shouldUpdateKey, { update: true }, Settings.shouldDelayFirebaseProfileSyncInMinutes ); dispatch.user.syncLocalToFirebase(); } else { console.log("Prevent: syncLocalToFirebase"); } } else { dispatch.user.syncLocalToFirebase(); } }, mergeDataWithFirebase: async (props) => { const doc = await firebase .firestore() .collection("players") .doc(Fire.uid); const setWithMerge = doc.set(props, { merge: true }); }, syncLocalToFirebase: async ( props, { user: { additionalUserInfo, credential, user, ...otherUserProps } } ) => { console.log("syncLocalToFirebase", otherUserProps); const doc = await firebase .firestore() .collection("players") .doc(Fire.uid); const setWithMerge = doc.set(otherUserProps, { merge: true }); }, setGameData: (props) => { const { uid, doc } = Fire; if (!uid) { // todo: add error return; } const setWithMerge = doc.set(props, { merge: true }); }, }, }; const FacebookLoginTypes = { Success: "success", Cancel: "cancel", }; function deleteUserAsync(uid) { const db = firebase.firestore(); return Promise.all([ db.collection(Settings.slug).doc(uid).delete(), db.collection("players").doc(uid).delete(), ]); } export const facebook = { state: null, reducers: { set: (state, props) => props, setAuth: (state, props) => ({ ...(state || {}), auth: props }), setGraphResults: (state = {}, props) => { const { graph = {}, ...otherState } = state; return { ...otherState, graph: { ...graph, ...props, }, }; }, }, effects: { upgradeAccount: () => { dispatch.facebook.getToken(dispatch.facebook.upgradeAccountWithToken); }, login: () => { dispatch.facebook.getToken(dispatch.facebook.loginToFirebaseWithToken); }, getToken: async (callback) => { let auth; try { auth = await Facebook.logInWithReadPermissionsAsync( Constants.manifest.facebookAppId, Settings.facebookLoginProps ); } catch ({ message }) { alert("Facebook Login Error:", message); } if (auth) { const { type, expires, token } = auth; if (type === FacebookLoginTypes.Success) { dispatch.facebook.set({ expires, token }); } else if (type === FacebookLoginTypes.Cancel) { // do nothing, user cancelled } else { // unknown type, this should never happen alert("Failed to authenticate", type); } if (callback) callback(token); } }, upgradeAccountWithToken: async (token, { facebook }) => { if (!token && (!facebook || !facebook.token)) { console.warn( "upgradeAccountWithToken: Can't upgrade account without a token" ); return; } const _token = token || facebook.token; try { const user = await linkAndRetrieveDataWithToken(_token); console.log("upgradeAccountWithToken: Upgraded Successful"); dispatch.facebook.authorized(user); } catch ({ message, code, ...error }) { if (code === "auth/credential-already-in-use") { // Delete current account while signed in // TODO: This wont work const uid = Fire.uid; if (uid) { console.log("Should delete:", uid); await deleteUserAsync(uid); console.log("All deleted"); } else { console.log("??? do something:", uid); } await dispatch.facebook.loginToFirebaseWithToken(_token); } else { // If the account is already linked this error will be thrown console.log("Error: upgradeAccountWithToken", message); console.log("error", code, error); Alert.alert(message); } } }, loginToFirebaseWithToken: async (token, { facebook }) => { if (!token && (!facebook || !facebook.token)) { console.warn( "loginToFirebaseWithToken: Can't login to firebase without a token" ); return; } const _token = token || facebook.token; try { const user = await signInWithToken(_token); dispatch.facebook.authorized(user); } catch ({ message }) { console.log("Error: loginToFirebase"); Alert.alert(message); } }, callGraphWithToken: async ({ token, params, callback }, { facebook }) => { if (!token && (!facebook || !facebook.token)) { console.warn( "callGraphWithToken: Can't call the Facebook graph API without a Facebook Auth token" ); return; } const _token = token || facebook.token; const paramString = (params || ["id", "name", "email", "picture"]).join( "," ); let results; try { const response = await fetch( `https://graph.facebook.com/me?access_token=${_token}&fields=${params.join( "," )}` ); results = await response.json(); dispatch.facebook.setGraphResults(results); } catch ({ message }) { console.log("Error: callGraphWithToken", message); alert(message); } if (callback) callback(results); }, authorized: (user, {}) => { console.log("Authorized Facebook", user); // dispatch.facebook.setAuth(user); let _user = user; if (_user.toJSON) { _user = user.toJSON(); } dispatch.user.update(_user); }, }, }; function linkAndRetrieveDataWithToken(token) { const credential = firebase.auth.FacebookAuthProvider.credential(token); return firebase .auth() .currentUser.linkAndRetrieveDataWithCredential(credential); } function signInWithToken(token) { const credential = firebase.auth.FacebookAuthProvider.credential(token); return firebase.auth().signInAndRetrieveDataWithCredential(credential); } /** * * @param urlAsKey * @param expireInMinutes * @returns {Promise.<*>} */ async function setItemWithExpiration(key, value, minutes) { // set expire at value = { value, expireAt: getExpireDate(minutes) }; // stringify object const objectToStore = JSON.stringify(value); // store object return AsyncStorage.setItem(key, objectToStore); } async function getItemWithExpiration(urlAsKey) { let data; await AsyncStorage.getItem(urlAsKey, async (err, value) => { data = JSON.parse(value); // there is data in cache && cache is expired if ( data !== null && data.expireAt && new Date(data.expireAt) < new Date() ) { // clear cache AsyncStorage.removeItem(urlAsKey); // update res to be null data = null; } else { console.log("read data from cache "); } }); if (data) { return data.value; } } function getExpireDate(expireInMinutes) { const now = new Date(); const expireTime = new Date(now); expireTime.setMinutes(now.getMinutes() + expireInMinutes); return expireTime; }
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as readline from 'readline'; import * as yargs from 'yargs'; import * as uuid from 'uuid'; import { URI } from 'vscode-uri'; import * as paths from './paths'; import PackageJson from './package'; import { Edge, Vertex, Id, Moniker, PackageInformation, packageInformation, EdgeLabels, ElementTypes, VertexLabels, MonikerKind, attach, UniquenessLevel, MonikerAttachEvent, EventScope, EventKind, Event, Source } from 'lsif-protocol'; import { TscMoniker, NpmMoniker } from './common/moniker'; import { StdoutWriter, FileWriter, Writer } from './common/writer'; import { Options, builder } from './args'; class AttachQueue { private _idGenerator: (() => Id) | undefined; private _idMode: 'uuid' | 'number' | undefined; private attachedId: Id | undefined; private store: (Event | PackageInformation | Moniker | attach | packageInformation)[]; public constructor(private emit: (value: string | Edge | Vertex) => void) { this.store = []; } public initialize(id: Id): void { if (typeof id === 'number') { let counter = -1; this._idGenerator = () => { return counter--; }; this._idMode = 'number'; } else { this._idGenerator = () => { return uuid.v4(); }; this._idMode = 'uuid'; } this.attachedId = this.idGenerator(); const startEvent: MonikerAttachEvent = { id: this.attachedId, type: ElementTypes.vertex, label: VertexLabels.event, scope: EventScope.monikerAttach, kind: EventKind.begin, data: this.attachedId }; this.store.push(startEvent); } private get idGenerator(): () => Id { if (this._idGenerator === undefined) { throw new Error(`ID Generator not initialized.`); } return this._idGenerator; } public createPackageInformation(packageJson: PackageJson): PackageInformation { const result: PackageInformation = { id: this.idGenerator(), type: ElementTypes.vertex, label: VertexLabels.packageInformation, name: packageJson.name, manager: 'npm', version: packageJson.version }; if (packageJson.hasRepository()) { result.repository = packageJson.repository; } this.store.push(result); return result; } public createMoniker(scheme: string, identifier: string, unique: UniquenessLevel, kind: MonikerKind): Moniker { const result: Moniker = { id: this.idGenerator(), type: ElementTypes.vertex, label: VertexLabels.moniker, scheme: scheme, identifier: identifier, unique, kind: kind }; this.store.push(result); return result; } public createAttachEdge(outV: Id, inV: Id): attach { const result: attach = { id: this.idGenerator(), type: ElementTypes.edge, label: EdgeLabels.attach, outV: outV, inV: inV }; this.store.push(result); return result; } public createPackageInformationEdge(outV: Id, inV: Id): packageInformation { const result: packageInformation = { id: this.idGenerator(), type: ElementTypes.edge, label: EdgeLabels.packageInformation, outV: outV, inV: inV }; this.store.push(result); return result; } public flush(lastId: Id): void { if (this.store.length === 0) { return; } if (this.attachedId === undefined || typeof lastId === 'number' && this._idMode !== 'number') { throw new Error(`Id mismatch.`); } const startEvent: MonikerAttachEvent = { id: this.idGenerator(), type: ElementTypes.vertex, label: VertexLabels.event, scope: EventScope.monikerAttach, kind: EventKind.begin, data: this.attachedId }; this.store.push(startEvent); if (this._idMode === 'uuid') { this.store.forEach(element => this.emit(element)); } else { const start: number = lastId as number; for (const element of this.store) { element.id = start + Math.abs(element.id as number); switch(element.label) { case VertexLabels.event: if (element.scope === EventScope.monikerAttach) { element.data = start + Math.abs(element.data as number); } break; case EdgeLabels.attach: element.outV = start + Math.abs(element.outV as number); break; case EdgeLabels.packageInformation: element.inV = start + Math.abs(element.inV as number); element.outV = start + Math.abs(element.outV as number); break; } this.emit(element); } } } } class SourceInfo { private _workspaceRoot: string | undefined; public handleSource(source: Source): void { this._workspaceRoot = URI.parse(source.workspaceRoot).fsPath; } public get workspaceRoot(): string | undefined { return this._workspaceRoot; } } class ExportLinker { private packageInformation: PackageInformation | undefined; private pathPrefix: string; constructor(private source: SourceInfo, private packageJson: PackageJson, private queue: AttachQueue) { this.pathPrefix = packageJson.$location; if (this.pathPrefix[this.pathPrefix.length - 1] !== '/') { this.pathPrefix = `${this.pathPrefix}/`; } } public handleMoniker(moniker: Moniker): void { if (moniker.kind !== MonikerKind.export || moniker.scheme !== TscMoniker.scheme) { return; } const workspaceRoot: string | undefined = this.source.workspaceRoot; if (workspaceRoot === undefined) { return; } const tscMoniker: TscMoniker = TscMoniker.parse(moniker.identifier); if (TscMoniker.hasPath(tscMoniker) && this.isPackaged(path.join(workspaceRoot, tscMoniker.path))) { this.ensurePackageInformation(); const monikerPath = this.getMonikerPath(workspaceRoot, tscMoniker); let npmIdentifier: string; if (this.packageJson.main === monikerPath || this.packageJson.typings === monikerPath) { npmIdentifier = NpmMoniker.create(this.packageJson.name, undefined, tscMoniker.name); } else { npmIdentifier = NpmMoniker.create(this.packageJson.name, monikerPath, tscMoniker.name); } let npmMoniker = this.queue.createMoniker(NpmMoniker.scheme, npmIdentifier, UniquenessLevel.scheme, moniker.kind); this.queue.createPackageInformationEdge(npmMoniker.id, this.packageInformation!.id); this.queue.createAttachEdge(npmMoniker.id, moniker.id); } } private isPackaged(_uri: string): boolean { // This needs to consult the .npmignore file and checks if the // document is actually published via npm. For now we return // true for all documents. return true; } private ensurePackageInformation(): void { if (this.packageInformation === undefined) { this.packageInformation = this.queue.createPackageInformation(this.packageJson); } } private getMonikerPath(projectRoot: string, tscMoniker: TscMoniker & { path: string; }): string { const fullPath = path.posix.join(projectRoot, tscMoniker.path); if (paths.isParent(this.pathPrefix, fullPath)) { return path.posix.relative(this.pathPrefix, fullPath); } return tscMoniker.path; } } class ImportLinker { private packageData: Map<string, { packageInfo: PackageInformation, packageJson: PackageJson } | null>; constructor(private source: SourceInfo, private queue: AttachQueue) { this.packageData = new Map(); } public handleMoniker(moniker: Moniker): void { if (moniker.kind !== MonikerKind.import || moniker.scheme !== TscMoniker.scheme) { return; } const tscMoniker = TscMoniker.parse(moniker.identifier); if (!TscMoniker.hasPath(tscMoniker)) { return; } const workspaceRoot = this.source.workspaceRoot; if (workspaceRoot === undefined) { return; } const parts = tscMoniker.path.split('/'); let packagePath: string | undefined; let monikerPath: string | undefined; for (let i = parts.length - 1; i >= 0; i--) { const part = parts[i]; if (part === 'node_modules') { // End is exclusive and one for the name const packageIndex = i + (parts[i + 1].startsWith('@') ? 3 : 2); packagePath = path.join(workspaceRoot, ...parts.slice(0, packageIndex), `package.json`); monikerPath = parts.slice(packageIndex).join('/'); break; } } if (packagePath === undefined || (monikerPath !== undefined && monikerPath.length === 0)) { return; } let packageData = this.packageData.get(packagePath); if (packageData === undefined) { const packageJson = PackageJson.read(packagePath); if (packageJson === undefined) { this.packageData.set(packagePath, null); } else { packageData = { packageInfo: this.queue.createPackageInformation(packageJson), packageJson: packageJson }; this.packageData.set(packagePath, packageData); } } if (packageData !== null && packageData !== undefined) { let npmIdentifier: string; if (packageData.packageJson.typings === monikerPath || packageData.packageJson.main === monikerPath) { npmIdentifier = NpmMoniker.create(packageData.packageJson.name, undefined, tscMoniker.name); } else { npmIdentifier = NpmMoniker.create(packageData.packageJson.name, monikerPath, tscMoniker.name); } const npmMoniker = this.queue.createMoniker(NpmMoniker.scheme, npmIdentifier, UniquenessLevel.scheme, moniker.kind); this.queue.createPackageInformationEdge(npmMoniker.id, packageData.packageInfo.id); this.queue.createAttachEdge(npmMoniker.id, moniker.id); } } } export async function run(options: Options): Promise<void> { if (options.help) { return; } if (options.version) { console.log(require('../package.json').version); return; } let packageFile: string | undefined = options.package; if (packageFile === undefined) { packageFile = 'package.json'; } packageFile = paths.makeAbsolute(packageFile); const packageJson: PackageJson | undefined = PackageJson.read(packageFile); let projectRoot = options.projectRoot; if (projectRoot === undefined && packageFile !== undefined) { projectRoot = path.posix.dirname(packageFile); if (!path.isAbsolute(projectRoot)) { projectRoot = paths.makeAbsolute(projectRoot); } } if (projectRoot === undefined) { console.error(`No project root specified.`); process.exitCode = -1; return; } if (!options.stdin && options.in === undefined) { console.error(`Either a input file using --in or --stdin must be specified`); process.exitCode = -1; return; } if (!options.stdout && options.out === undefined) { console.error(`Either a output file using --out or --stdout must be specified.`); process.exitCode = -1; return; } if (options.in !== undefined && options.out !== undefined && paths.makeAbsolute(options.in) === paths.makeAbsolute(options.out)) { console.error(`Input and output file can't be the same.`); process.exitCode = -1; return; } let writer: Writer = new StdoutWriter(); function emit(value: string | Edge | Vertex): void { if (typeof value === 'string') { writer.writeln(value); } else { writer.writeln(JSON.stringify(value, undefined, 0)); } } const queue: AttachQueue = new AttachQueue(emit); const sourceInfo: SourceInfo = new SourceInfo(); let exportLinker: ExportLinker | undefined; if (packageJson !== undefined) { exportLinker = new ExportLinker(sourceInfo, packageJson, queue); } const importLinker: ImportLinker = new ImportLinker(sourceInfo, queue); let input: NodeJS.ReadStream | fs.ReadStream = process.stdin; if (options.in !== undefined && fs.existsSync(options.in)) { input = fs.createReadStream(options.in, { encoding: 'utf8'}); } if (options.out !== undefined) { writer = new FileWriter(fs.openSync(options.out, 'w')); } let needsInitialization: boolean = true; let lastId: Id | undefined; const rd = readline.createInterface(input); rd.on('line', (line) => { emit(line); let element: Edge | Vertex = JSON.parse(line); lastId = element.id; if (needsInitialization) { queue.initialize(element.id); needsInitialization = false; } if (element.type === ElementTypes.vertex) { switch (element.label) { case VertexLabels.moniker: if (exportLinker !== undefined) { exportLinker.handleMoniker(element); } importLinker.handleMoniker(element); break; case VertexLabels.source: sourceInfo.handleSource(element); break; } } }); rd.on('close', () => { if (lastId !== undefined) { queue.flush(lastId); } }); } export function main(): Promise<void> { yargs. parserConfiguration({ 'camel-case-expansion': false }). exitProcess(false). usage(`Language Server Index Format tool for NPM monikers\nVersion: ${require('../package.json').version}\nUsage: lsif-npm [options][tsc options]`). example(`lsif-npm --package package.json --stdin --stdout`, `Reads an LSIF dump from stdin and transforms tsc monikers into npm monikers and prints the result to stdout.`). version(false). wrap(Math.min(100, yargs.terminalWidth())); const options: Options = Object.assign({}, Options.defaults, builder(yargs).argv); return run(options); } if (require.main === module) { main(); }
the_stack
import Conditions from '../../../../../resources/conditions'; import NetRegexes from '../../../../../resources/netregexes'; import { Responses } from '../../../../../resources/responses'; import ZoneId from '../../../../../resources/zone_id'; import { RaidbossData } from '../../../../../types/data'; import { NetMatches } from '../../../../../types/net_matches'; import { TriggerSet } from '../../../../../types/trigger'; // export type Data = RaidbossData; export interface Data extends RaidbossData { bombCount: number; boostCount: number; boostBombs?: { x: number; y: number }[]; } // TODO: do the gobcut and gobstraight really alternate? // if so, then maybe we could call out which was coming. // I thought some of them were fixed and don't have enough data. // TODO: is it worth calling out where to hide for Bomb's Away? // There's a callout for where to hit the bombs to that everybody // will see, and it's natural to go away from that. An extra // callout seems noisy. // TODO: is it worth calling out a safe spot for the second boost? // There's some notes below, but good words for directions are hard. const bombLocation = (matches: NetMatches['AddedCombatant']) => { // x = -15, -5, +5, +15 (east to west) // y = -205, -195, -185, -175 (north to south) return { x: Math.round((parseFloat(matches.x) + 15) / 10), y: Math.round((parseFloat(matches.y) + 205) / 10), }; }; const triggerSet: TriggerSet<Data> = { zoneId: ZoneId.AlexanderTheFistOfTheSonSavage, timelineFile: 'a5s.txt', initData: () => { return { bombCount: 0, boostCount: 0, }; }, timelineTriggers: [ { id: 'A5S Kaltstrahl', regex: /Kaltstrahl/, // Hopefully you'll figure it out the first time. suppressSeconds: 9999, response: Responses.tankCleave(), }, { id: 'A5S Panzerschreck', regex: /Panzerschreck/, beforeSeconds: 10, suppressSeconds: 10, response: Responses.aoe(), }, { id: 'A5S Gobhook', regex: /Gobhook/, // Needs more warning than the cast. beforeSeconds: 7, suppressSeconds: 1, response: Responses.getBehind(), }, { id: 'A5S Boost', regex: /Boost/, beforeSeconds: 10, suppressSeconds: 1, alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Bird Soon (Purple)', de: 'Vogel bald (Lila)', fr: 'Oiseau bientôt (Violet)', ja: 'まもなく鳥に変化 (紫の薬)', cn: '准备变鸟(紫药)', ko: '새 변신 준비 (보라)', }, }, }, { id: 'A5S Bomb\'s Away Soon', regex: /Bomb's Away/, beforeSeconds: 10, suppressSeconds: 1, alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Gorilla Soon (Red)', de: 'Gorilla bald (Rot)', fr: 'Gorille bientôt (Rouge)', ja: 'まもなくゴリラに変化 (赤の薬)', cn: '准备变猩猩(红药)', ko: '고릴라 변신 준비 (빨강)', }, }, }, { id: 'A5S Debuff Refresh', regex: /Disorienting Groan/, beforeSeconds: 1, suppressSeconds: 1, infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'refresh debuff in puddle soon', de: 'Debuff in der Fläche bald erneuern', fr: 'Rafraîchissez le debuff dans la zone au sol bientôt', ja: 'デバフを癒す', cn: '踩圈刷新debuff', ko: '디버프 해제하기', }, }, }, ], triggers: [ { id: 'A5S Gobcut Stack', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '003E' }), response: Responses.stackMarkerOn(), }, { id: 'A5S Concussion', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: '3E4' }), condition: (data, matches) => { if (data.me !== matches.target) return false; return data.role === 'tank'; }, response: Responses.tankBusterSwap(), }, { id: 'A5S Concussion BLU', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: '3E4' }), condition: (data, matches) => { if (data.me !== matches.target) return false; return data.role !== 'tank' && data.job === 'BLU'; }, response: Responses.tankBusterSwap('info'), }, { id: 'A5S Bomb Direction', type: 'Ability', netRegex: NetRegexes.ability({ source: 'Ratfinx Twinkledinks', id: '1590', capture: false }), netRegexDe: NetRegexes.ability({ source: 'Ratfix Blinkdings', id: '1590', capture: false }), netRegexFr: NetRegexes.ability({ source: 'Ratfinx Le Génie', id: '1590', capture: false }), netRegexJa: NetRegexes.ability({ source: '奇才のラットフィンクス', id: '1590', capture: false }), netRegexCn: NetRegexes.ability({ source: '奇才 拉特芬克斯', id: '1590', capture: false }), netRegexKo: NetRegexes.ability({ source: '재주꾼 랫핑크스', id: '1590', capture: false }), preRun: (data) => data.bombCount++, // We could give directions here, but "into / opposite spikey" is pretty succinct. infoText: (data, _matches, output) => { if (data.bombCount === 1) return output.knockBombsIntoSpikey!(); return output.knockBombsOppositeSpikey!(); }, outputStrings: { knockBombsIntoSpikey: { en: 'Knock Bombs Into Spikey', de: 'Bombe in die Spike-Bombe stoßen', fr: 'Poussez les bombes dans la bombe à pointe', ja: 'トゲ爆弾を飛ばす', cn: '把炸弹拍到地雷处', ko: '지뢰쪽으로 폭탄 밀기', }, knockBombsOppositeSpikey: { en: 'Knock Bombs Opposite Spikey', de: 'Bombe gegnüber der Spike-Bombe stoßen', fr: 'Poussez les bombes à l\'opposé de la bombe à pointe', ja: 'トゲ爆弾を対角に飛ばす', cn: '把炸弹拍到地雷处', ko: '지뢰 반대쪽으로 폭탄 밀기', }, }, }, { id: 'A5S Boost Count', type: 'Ability', netRegex: NetRegexes.ability({ source: 'Ratfinx Twinkledinks', id: '16A6', capture: false }), netRegexDe: NetRegexes.ability({ source: 'Ratfix Blinkdings', id: '16A6', capture: false }), netRegexFr: NetRegexes.ability({ source: 'Ratfinx Le Génie', id: '16A6', capture: false }), netRegexJa: NetRegexes.ability({ source: '奇才のラットフィンクス', id: '16A6', capture: false }), netRegexCn: NetRegexes.ability({ source: '奇才 拉特芬克斯', id: '16A6', capture: false }), netRegexKo: NetRegexes.ability({ source: '재주꾼 랫핑크스', id: '16A6', capture: false }), run: (data) => { data.boostCount++; data.boostBombs = []; }, }, { id: 'A5S Bomb', type: 'AddedCombatant', netRegex: NetRegexes.addedCombatantFull({ name: 'Bomb' }), netRegexDe: NetRegexes.addedCombatantFull({ name: 'Bombe' }), netRegexFr: NetRegexes.addedCombatantFull({ name: 'Bombe' }), netRegexJa: NetRegexes.addedCombatantFull({ name: '爆弾' }), netRegexCn: NetRegexes.addedCombatantFull({ name: '炸弹' }), netRegexKo: NetRegexes.addedCombatantFull({ name: '폭탄' }), preRun: (data, matches) => { data.boostBombs ??= []; data.boostBombs.push(bombLocation(matches)); }, alertText: (data, _matches, output) => { if (data.boostBombs && data.boostCount === 1) { const firstBomb = data.boostBombs[0]; if (!firstBomb) return; // index 0 = NW, 3 = NE, 12 = SW, 15 = SE const index = firstBomb.x + firstBomb.y * 4; const outputs: { [index: number]: string } = { 0: output.northwestFirst!(), 3: output.northeastFirst!(), 12: output.southwestFirst!(), 15: output.southeastFirst!(), }; return outputs[index]; } // Otherwise, we're on the second and final set of boost bombs. // TODO: This would be trivial to find the safe spot, // buuuuut this is hard to find good words for 16 spots. // Do you call it "NNW" or "East of NW But Also Outside" @_@ }, outputStrings: { northwestFirst: { en: 'NW first', de: 'NW zuerst', fr: 'NO en premier', ja: 'まずは北西', cn: '先左上', ko: '북서쪽 먼저', }, northeastFirst: { en: 'NE first', de: 'NO zuerst', fr: 'NE en premier', ja: 'まずは北東', cn: '先右上', ko: '북동쪽 먼저', }, southwestFirst: { en: 'SW first', de: 'SW zuerst', fr: 'SO en premier', ja: 'まずは南西', cn: '先左下', ko: '남서쪽 먼저', }, southeastFirst: { en: 'SE first', de: 'SO zuerst', fr: 'SE en premier', ja: 'まずは南東', cn: '先右下', ko: '남동쪽 먼저', }, }, }, { id: 'A5S Prey', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '001E' }), condition: Conditions.targetIsYou(), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Get Away', de: 'Weg gehen', fr: 'Éloignez-vous', ja: '外へ', cn: '快出去', ko: '멀리 떨어지기', }, }, }, { id: 'A5S Prey Healer', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '001E' }), condition: (data) => data.role === 'healer', infoText: (data, matches, output) => output.text!({ player: data.ShortName(matches.target) }), outputStrings: { text: { en: 'Shield ${player}', de: 'Schild ${player}', fr: 'Bouclier sur ${player}', ja: '${player}にバリア', cn: '给${player}单盾', ko: '"${player}" 에게 보호막', }, }, }, { id: 'A5S Glupgloop', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '0017' }), condition: Conditions.targetIsYou(), alarmText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'GLOOPYGLOOP~', de: 'GLOOPYGLOOP~', fr: 'Gobacide gluant', ja: '強酸性劇物薬', cn: '强酸剧毒药', ko: '강산성 극약', }, }, }, { id: 'A5S Snake Adds', type: 'AddedCombatant', netRegex: NetRegexes.addedCombatant({ name: 'Glassy-Eyed Cobra', capture: false }), netRegexDe: NetRegexes.addedCombatant({ name: 'Aufgerüstet(?:e|er|es|en) Kobra', capture: false }), netRegexFr: NetRegexes.addedCombatant({ name: 'Cobra Au Regard Vide', capture: false }), netRegexJa: NetRegexes.addedCombatant({ name: 'ドーピング・コブラ', capture: false }), netRegexCn: NetRegexes.addedCombatant({ name: '兴奋眼镜蛇', capture: false }), netRegexKo: NetRegexes.addedCombatant({ name: '약에 찌든 코브라', capture: false }), suppressSeconds: 5, response: Responses.killAdds(), }, { id: 'A5S Steel Scales', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Glassy-Eyed Cobra', id: '16A2' }), netRegexDe: NetRegexes.startsUsing({ source: 'Aufgerüstet(?:e|er|es|en) Kobra', id: '16A2' }), netRegexFr: NetRegexes.startsUsing({ source: 'Cobra Au Regard Vide', id: '16A2' }), netRegexJa: NetRegexes.startsUsing({ source: 'ドーピング・コブラ', id: '16A2' }), netRegexCn: NetRegexes.startsUsing({ source: '兴奋眼镜蛇', id: '16A2' }), netRegexKo: NetRegexes.startsUsing({ source: '약에 찌든 코브라', id: '16A2' }), condition: (data) => data.CanStun(), suppressSeconds: 60, response: Responses.stun(), }, { id: 'A5S Anti-Coagulant Cleanse', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: '3EC' }), condition: Conditions.targetIsYou(), durationSeconds: 8, suppressSeconds: 30, alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Cleanse (Green)', de: 'Reinigen (Grün)', fr: 'Purifiez-vous (Vert)', ja: 'エスナ (緑の薬)', cn: '解毒(绿药)', ko: '디버프 해제 (초록)', }, }, }, { id: 'A5S Gobbledygroper', type: 'Ability', // FIXME: this is a case where the tether is part of the added combatant network data, // but isn't exposed as a separate tether line. Instead, just assume the first auto // is going to hit the tethered person, and suppress everything else. netRegex: NetRegexes.ability({ source: 'Gobbledygroper', id: '366' }), netRegexDe: NetRegexes.ability({ source: 'Gobgreifer', id: '366' }), netRegexFr: NetRegexes.ability({ source: 'Gobchimère', id: '366' }), netRegexJa: NetRegexes.ability({ source: 'ゴブリキマイラ', id: '366' }), netRegexCn: NetRegexes.ability({ source: '哥布林奇美拉', id: '366' }), netRegexKo: NetRegexes.ability({ source: '고블키마이라', id: '366' }), condition: Conditions.targetIsYou(), suppressSeconds: 100, alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Break Tether (Blue)', de: 'Verbindungen brechen (Blau)', fr: 'Cassez le lien (Bleu)', ja: '線を断つ (青の薬)', cn: '消除连线(蓝药)', ko: '선 끊기 (파랑)', }, }, }, { id: 'A5S Oogle', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Gobbledygawker', id: '169C', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Gobglotzer', id: '169C', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Gobœil', id: '169C', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ゴブリアイ', id: '169C', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '哥布之眼', id: '169C', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '고블주시자', id: '169C', capture: false }), // These seem to come within ~2s of each other, so just have one trigger. suppressSeconds: 5, response: Responses.lookAway('alert'), }, ], timelineReplace: [ { 'locale': 'de', 'replaceSync': { '(?<!Hummel)Faust': 'Faust', '(?<!Smart)Bomb': 'Bombe', 'Hummelfaust': 'Hummelfaust', 'Glassy-Eyed Cobra': 'aufgerüstet(?:e|er|es|en) Kobra', 'Gobbledygawker': 'Gobglotzer', 'Gobbledygroper': 'Gobgreifer', 'Ratfinx Twinkledinks': 'Ratfix Blinkdings', 'Smartbomb': 'Best(?:e|er|es|en) Sprengenkörper', 'The Clevering': 'Forschenraum', }, 'replaceText': { '--big--': '--Groß--', '--small--': '--Klein--', '10-Tonze Slash': '11-Tonzen-Schlag', 'Big Burst': 'Detonation', 'Bomb\'s Away': 'Plumpsbombe', 'Boost': 'Starksammeln', 'Cobra': 'Kobra', 'Disorienting Groan': 'Kampfgebrüll', 'Feast': 'Festmahl', 'Glupgloop': 'Sauresaft', 'Gobbledygawker': 'Gobglotzer', 'Gobbledygroper Add': 'Gobgreifer Add', 'Gobcut/Straight': 'Gobhaken/gerade', 'Gobdash': 'Große Karacho', 'Gobhook': 'Bogene Haken', 'Gobjab': 'Hüpfzzu mal', 'Gobstraight/Cut': 'Gobgerade/haken', 'Gobswing': 'Schwirrenschwung', 'Guzzle': 'Gluckgluck', 'Kaltstrahl': 'Kaltstrahl', 'Minotaur': 'Minotaurus', 'Oogle': 'Steinstarren', 'Panzer Vor': 'Panzer vor', 'Panzerschreck': 'Panzerschreck', 'Regorge': 'Auswürgen', 'Relaxant': 'Ausnüchterung', 'Shabti': 'Shabti', 'Shock Therapy': 'Kleine Knisterklaps', 'Steel Scales': 'Stahlschuppen', 'Tetra Burst': 'Tetra-Detonation', 'The Lion\'s Breath': 'Atem des Löwen', 'Yorn Pig': 'Mankei', }, }, { 'locale': 'fr', 'replaceSync': { '(?<!Smart)Bomb(?!e)': 'Bombe', '(?<!Hummel)Faust': 'Faust', 'Glassy-Eyed Minotaur': 'Minotaure au regard vide', 'Glassy-Eyed Cobra': 'cobra au regard vide', 'Gobbledygawker': 'Gobœil', 'Gobbledygroper': 'Gobchimère', 'Hummelfaust': 'Hummelfaust', 'Ratfinx Twinkledinks': 'Ratfinx le Génie', 'Smartbomb': 'mégagobbombe', 'The Clevering': 'la gobexpérimentation super-avancée', }, 'replaceText': { '\\(NW\\)': '(NO)', '\\(SE/SW\\)': '(SE/SO)', '--big--': '--grand--', '--small--': '--petit--', '10-Tonze Slash': 'Taillade de 10 tonz', 'Big Burst': 'Grande explosion', 'Bomb\'s Away': 'Lâcher de bombe', 'Boost': 'Contraction musculaire', 'Cobra': 'Cobra', 'Disorienting Groan': 'Cri désorientant', 'Feast': 'Festin', 'Glupgloop': 'Gobacide gluant', 'Gobbledygawker': 'Gobœil', 'Gobbledygroper Add': 'Add Gobchimère', 'Gobcut/Straight': 'Uppercut/Direct du droit', 'Gobdash': 'Gobcharge', 'Gobhook': 'Gobcrochet', 'Gobjab': 'Gobcoup du gauche', 'Gobstraight/Cut': 'Direct du droit/Uppercut', 'Gobswing': 'Gobcrochet plongeant', 'Guzzle': 'Glouglou', 'Kaltstrahl': 'Kaltstrahl', 'Minotaur': 'Minotaure', 'Oogle': 'Vue pétrifiante', 'Panzer Vor': 'Panzer Vor', 'Panzerschreck': 'Panzerschreck', 'Regorge': 'Vomissure', 'Relaxant': 'Décontracturant', 'Shabti': 'Chaouabti', 'Shock Therapy': 'Thérapie de choc', 'Steel Scales': 'Écailles d\'acier', 'Tetra Burst': 'Explosion en croix', 'The Lion\'s Breath': 'Souffle du lion', 'Yorn Pig': 'Cochon de Yorn', }, }, { 'locale': 'ja', 'replaceSync': { '(?<!Hummel)Faust': 'ファウスト', '(?<!Smart)Bomb': '爆弾', 'Hummelfaust': 'ネオ・ファウスト', 'Gobbledygroper': 'ゴブリキマイラ', 'Ratfinx Twinkledinks': '奇才のラットフィンクス', 'Smartbomb': '超高性能爆弾', 'The Clevering': 'ゴブリサイエンス研究室', 'Glassy-Eyed Cobra': 'ドーピング・コブラ', 'Gobbledygawker': 'ゴブリアイ', }, 'replaceText': { '--big--': '--巨大化--', '--small--': '--小さくなる--', '10-Tonze Slash': '10トンズ・スラッシュ', 'Big Burst': '大爆発', 'Bomb\'s Away': '爆弾投下', 'Boost': '力溜め', 'Cobra': 'コブラ', 'Disorienting Groan': '雄叫び', 'Feast': 'フィースト', 'Glupgloop': '強酸性劇物薬', 'Gobbledygawker': 'ゴブリアイ', 'Gobbledygroper Add': '雑魚: ゴブリキマイラ', 'Gobcut/Straight': '衝撃のアッパー/渾身のストレート', 'Gobdash': '怒濤のダッシュブロー', 'Gobhook': '剛力のフック', 'Gobjab': '牽制のジャブ', 'Gobstraight/Cut': '渾身のストレート/衝撃のアッパー', 'Gobswing': '激震のオーバーハンド', 'Guzzle': 'ガブ飲み', 'Kaltstrahl': 'カルトシュトラール', 'Minotaur': 'ミノタウロス', 'Oogle': '石化の視線', 'Panzer Vor': 'パンツァーフォー', 'Panzerschreck': 'パンツァーシュレッケ', 'Regorge': 'リゴージ', 'Relaxant': '薬効切れ', 'Shabti': 'シュワブチ', 'Shock Therapy': '雷気ショック', 'Steel Scales': 'スチールスケール', 'Tetra Burst': '四方爆発', 'The Lion\'s Breath': 'フレイムブレス', 'Yorn Pig': 'モルモット', }, }, { 'locale': 'cn', 'replaceSync': { '(?<!Smart)Bomb(?!e)': '炸弹', '(?<!Hummel)Faust': '浮士德', 'Glassy-Eyed Minotaur': '兴奋弥诺陶洛斯', 'Gobbledygawker': '哥布之眼', 'Gobbledygroper': '哥布林奇美拉', 'Hummelfaust': '新型浮士德', 'Ratfinx Twinkledinks': '奇才 拉特芬克斯', 'Smartbomb': '超高性能炸弹', 'The Clevering': '哥布林科学研究室', 'Glassy-Eyed Cobra': '兴奋眼镜蛇', }, 'replaceText': { '--big--': '--大--', '--small--': '--小--', '10-Tonze Slash': '十吨挥打', 'Big Burst': '大爆炸', 'Bomb\'s Away': '投放炸弹', 'Boost': '蓄力', 'Cobra': 'Cobra', 'Disorienting Groan': '吼叫', 'Feast': '飨宴', 'Glupgloop': '强酸剧毒药', 'Gobbledygawker': '哥布之眼', 'Gobbledygroper Add': '哥布林奇美拉出现', 'Gobcut/Straight': '猛击上勾拳/全力重拳', 'Gobdash': '怒涛冲拳', 'Gobhook': '刚猛勾拳', 'Gobjab': '牵制刺拳', 'Gobstraight/Cut': '全力重拳/猛击上勾拳', 'Gobswing': '激震抛拳', 'Guzzle': '一饮而尽', 'Kaltstrahl': '寒光', 'Minotaur': '弥诺陶洛斯', 'Oogle': '石化视线', 'Panzer Vor': '战车前进', 'Panzerschreck': '反坦克火箭筒', 'Regorge': '喷毒', 'Relaxant': '药物失效', 'Shabti': '沙布提', 'Shock Therapy': '电气冲击', 'Steel Scales': '钢鳞', 'Tetra Burst': '四方爆炸', 'The Lion\'s Breath': '火焰吐息', 'Yorn Pig': '豚鼠', }, }, { 'locale': 'ko', 'replaceSync': { '(?<!Hummel)Faust': '파우스트', '(?<!Smart)Bomb': '폭탄', 'Hummelfaust': '네오 파우스트', 'Gobbledygroper': '고블키마이라', 'Ratfinx Twinkledinks': '재주꾼 랫핑크스', 'Smartbomb': '초고성능 폭탄', 'The Clevering': '고블린 과학 연구실', 'Gobbledygawker': '고블주시자', 'Glassy-Eyed Cobra': '약에 찌든 코브라', 'Glassy-Eyed Minotaur': '약에 찌든 미노타우로스', }, 'replaceText': { '--big--': '--커짐--', '--small--': '--작아짐--', '10-Tonze Slash': '10톤즈 베기', 'Big Burst': '대폭발', 'Bomb\'s Away': '폭탄 투하', 'Boost': '힘 모으기', 'Cobra': '코브라', 'Disorienting Groan': '우렁찬 외침', 'Feast': '사육제', 'Glupgloop': '강산성 극약', 'Gobbledygawker': '고블주시자', 'Gobbledygroper Add': '고블주시자 등장', 'Gobcut/Straight': '올려치기/직격타', 'Gobdash': '노도의 접근 강타', 'Gobhook': '저력의 옆치기', 'Gobjab': '견제타', 'Gobswing': '격진의 주먹 휘두르기', 'Guzzle': '들이켜기', 'Gobstraight/Cut': '직격타/올려치기', 'Kaltstrahl': '냉병기 공격', 'Minotaur': '미노타우로스', 'Oogle': '석화 시선', 'Panzer Vor': '기갑 전진', 'Panzerschreck': '대전차포', 'Regorge': '게워내기', 'Relaxant': '약효 소진', 'Shabti': '샤브티', 'Shock Therapy': '감전 충격', 'Steel Scales': '강철 비늘', 'Tetra Burst': '사방 폭발', 'The Lion\'s Breath': '화염 숨결', 'Yorn Pig': '모르모트', }, }, ], }; export default triggerSet;
the_stack
import { css } from "styled-components"; import { theme, colorScheme, getConcreteBreakpointSize } from "@typestrap/config"; interface Props { hidden: boolean; theme: typeof theme; } /* Constants and helpers */ const capitalizeFirstLetter = (string: string) => string.charAt(0).toUpperCase() + string.slice(1); const colors = [ "primary", "secondary", "success", "danger", "warning", "info", "light", "dark", "darker", "white", "transparent" ]; /* Vertical align --------------------------------------------------------- */ const verticalAlign = (size: string) => css` vertical-align: ${(props: Props) => { if (props[`text${size}Baseline`]) { return "baseline"; } if (props[`text${size}Top`]) { return "top"; } if (props[`text${size}Bottom`]) { return "bottom"; } if (props[`text${size}TextTop`]) { return "text-top"; } if (props[`text${size}TextBottom`]) { return "text-bottom"; } return null; }}; `; /* Text ------------------------------------------------------------------- */ const textAlign = (size: string) => css` text-align: ${(props: Props) => { if (props[`text${size}Justify`]) { return "justify"; } if (props[`text${size}Left`]) { return "left"; } if (props[`text${size}Right`]) { return "right"; } if (props[`text${size}Center`]) { return "center"; } return null; }}; `; const textWrap = (size: string) => css` white-space: ${(props: Props) => { if (props[`text${size}Wrap`]) { return "normal"; } if (props[`text${size}NoWrap`]) { return "nowrap"; } return null; }}; `; const textTransform = (size: string) => css` text-transform: ${(props: Props) => { if (props[`text${size}Lowercase`]) { return "lowercase"; } if (props[`text${size}Uppercase`]) { return "uppercase"; } if (props[`text${size}Capitalize`]) { return "capitalize"; } return null; }}; `; const textWeight = (size: string) => css` font-weight: ${(props: Props) => { if (props[`text${size}WeightBold`]) { return "bold"; } if (props[`text${size}WeightBolder`]) { return "bolder"; } if (props[`text${size}WeightNormal`]) { return "normal"; } if (props[`text${size}WeightLight`]) { return "light"; } if (props[`text${size}WeightLighter`]) { return "lighter"; } return null; }}; `; const textStyle = (size: string) => css` font-style: ${(props: Props) => { if (props[`text${size}Italic`]) { return "italic"; } return null; }}; `; const textMonospace = (size: string) => css` font-family: ${(props: Props) => { if (props[`text${size}Monospace`]) { return 'SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace'; } return null; }}; `; const textReset = (size: string) => css` color: ${(props: Props) => { if (props[`text${size}Reset`]) { return "inherit"; } return null; }}; `; const textDecoration = (size: string) => css` text-decoration: ${(props: Props) => { if (props[`textDecoration${size}None`]) { return "none!important"; } return null; }}; `; const textWordBreak = (size: string) => css` ${(props: Props) => { if (props[`text${size}WordBreak`]) { return css` word-break: break-word; overflow-wrap: break-word; `; } return null; }}; `; const textTruncate = (size: string) => css` ${(props: Props) => { if (props[`text${size}Truncate`]) { return css` overflow: hidden; text-overflow: ellipsis; white-space: nowrap; `; } return null; }}; `; /* Sizing ----------------------------------------------------------------- */ const sizing = (size: string) => ["max-", ""].map(m => ["width", "height"].map(a => ["25", "50", "75", "100", "Auto"].map( p => css` ${(props: Props) => props[`${m.slice(0, 1)}${a[0]}${size}${p}`] && css` ${m}${a}: ${p === "Auto" ? "auto" : `${p}%`}; `} ` ) ) ); /* Shadows ---------------------------------------------------------------- */ const shadow = (size: string) => css` box-shadow: ${(props: Props) => { if (props[`shadow${size}None`]) { return "none"; } if (props[`shadow${size}Small`]) { return "0 .25rem .5rem rgba(0,0,0,.1)"; } if (props[`shadow${size}`]) { return "0 .75rem 1.5rem rgba(0,0,0,.2)"; } if (props[`shadow${size}Large`]) { return "0 1.25rem 3.5rem rgba(0,0,0,.25)"; } return null; }}; `; /* Position --------------------------------------------------------------- */ const position = (size: string) => css` position: ${(props: Props) => { if (props[`position${size}Static`]) { return "static"; } if (props[`position${size}Relative`]) { return "relative"; } if (props[`position${size}Absolute`]) { return "absolute"; } if (props[`position${size}Fixed`]) { return "fixed"; } if (props[`position${size}Sticky`]) { return "sticky"; } return null; }}; `; /* Overflow --------------------------------------------------------------- */ const overflow = (size: string) => css` overflow: ${(props: Props) => { if (props[`overflow${size}Auto`]) { return "auto"; } if (props[`overflow${size}Hidden`]) { return "hidden"; } return null; }}; `; /* Hidden ----------------------------------------------------------------- */ const hidden = () => css` ${(props: Props) => { if (props.hidden) { return css` display: none; `; } return null; }}; `; /* Text hide ------------------------------------------------------------- */ const textHide = (size: string) => css` ${(props: Props) => { if (props[`text${size}Hide`]) { return css` font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; `; } return null; }} `; /* Float ----------------------------------------------------------------- */ const float = (size: string) => css` float: ${(props: Props) => { if (props[`float${size}Right`]) { return "right"; } if (props[`float${size}Left`]) { return "left"; } if (props[`float${size}None`]) { return "none"; } return null; }}; `; /* Colors ---------------------------------------------------------------- */ const textColors = (size: string) => css` ${(props: Props) => colors.map( color => props[`text${size}${capitalizeFirstLetter(color)}`] && css` color: ${colorScheme[color]}; ` )}; `; const backgroundColors = (size: string) => css` ${(props: Props) => colors.map( color => props[`bg${size}${capitalizeFirstLetter(color)}`] && css` background-color: ${colorScheme[color]}; ` )}; `; /* Borders ---------------------------------------------------------------- */ const normalizeBorderValue = (value: string) => { if (value === "0") { return "0"; } return "1px solid"; }; const border = (size: string, value: string) => { const suffix = `${size}${value}`; return css` border-left: ${(props: Props) => (props[`borderLeft${suffix}`] || props[`border${suffix}`]) && normalizeBorderValue(value)}; border-right: ${props => (props[`borderRight${suffix}`] || props[`border${suffix}`]) && normalizeBorderValue(value)}; border-top: ${props => (props[`borderTop${suffix}`] || props[`border${suffix}`]) && normalizeBorderValue(value)}; border-bottom: ${props => (props[`borderBottom${suffix}`] || props[`border${suffix}`]) && normalizeBorderValue(value)}; ${(props: Props) => colors.map( color => props[`border${size}${capitalizeFirstLetter(color)}`] && css` border-color: ${colorScheme[color]}; ` )}; `; }; const borderColor = (size: string) => css` ${(props: Props) => colors.map( color => props[`border${size}${capitalizeFirstLetter(color)}`] && css` border-color: ${colorScheme[color]}; ` )}; `; const rounded = (size: string) => css` border-top-left-radius: ${(props: Props) => props[`roundedTop${size}`] || props[`roundedLeft${size}`] || props[`rounded${size}`] ? ".25rem" : null}; border-top-right-radius: ${(props: Props) => props[`roundedTop${size}`] || props[`roundedRight${size}`] || props[`rounded${size}`] ? ".25rem" : null}; border-bottom-left-radius: ${(props: Props) => props[`roundedBottom${size}`] || props[`roundedLeft${size}`] || props[`rounded${size}`] ? ".25rem" : null}; border-bottom-right-radius: ${(props: Props) => props[`roundedBottom${size}`] || props[`roundedRight${size}`] || props[`rounded${size}`] ? ".25rem" : null}; `; const roundedCircle = (size: string) => css` border-radius: ${(props: Props) => props[`rounded${size}Circle`] ? "50%" : null}; `; const roundedPill = (size: string) => css` border-radius: ${(props: Props) => props[`rounded${size}Pill`] ? "50rem" : null}; `; /* Spacing ---------------------------------------------------------------- */ const normalizeSpacingValue = (value, allowAuto = false) => { // allowed value if (allowAuto && value === "Auto") { return "auto"; } // rem value return `${value * 0.25}rem`; }; // Margin const spacingMargin = (size, value, negative = false) => { const suffix = `${size}${negative ? "n" : ""}${value}`; const val = negative ? -value : value; return css` margin-left: ${(props: Props) => (props[`ml${suffix}`] || props[`mx${suffix}`] || props[`m${suffix}`]) && normalizeSpacingValue(val, true)}; margin-right: ${props => (props[`mr${suffix}`] || props[`mx${suffix}`] || props[`m${suffix}`]) && normalizeSpacingValue(val, true)}; margin-top: ${props => (props[`mt${suffix}`] || props[`my${suffix}`] || props[`m${suffix}`]) && normalizeSpacingValue(val, true)}; margin-bottom: ${props => (props[`mb${suffix}`] || props[`my${suffix}`] || props[`m${suffix}`]) && normalizeSpacingValue(val, true)}; `; }; // Padding const spacingPadding = (size: string, value: number) => { const suffix = `${size}${value}`; return css` padding-left: ${(props: Props) => (props[`pl${suffix}`] || props[`px${suffix}`] || props[`p${suffix}`]) && normalizeSpacingValue(value)}; padding-right: ${props => (props[`pr${suffix}`] || props[`px${suffix}`] || props[`p${suffix}`]) && normalizeSpacingValue(value)}; padding-top: ${props => (props[`pt${suffix}`] || props[`py${suffix}`] || props[`p${suffix}`]) && normalizeSpacingValue(value)}; padding-bottom: ${props => (props[`pb${suffix}`] || props[`py${suffix}`] || props[`p${suffix}`]) && normalizeSpacingValue(value)}; `; }; /* Flex ------------------------------------------------------------------- */ const flexDirection = (size: string) => css` flex-direction: ${(props: Props) => (props[`flex${size}Row`] ? "row" : "") || (props[`flex${size}RowReverse`] ? "row-reverse" : "") || (props[`flex${size}Column`] ? "column" : "") || (props[`flex${size}ColumnReverse`] ? "column-reverse" : "") || null}; `; const justifyContent = (size: string) => css` justify-content: ${(props: Props) => (props[`justifyContent${size}Start`] ? "start" : "") || (props[`justifyContent${size}End`] ? "end" : "") || (props[`justifyContent${size}Center`] ? "center" : "") || (props[`justifyContent${size}SpaceBetween`] ? "space-between" : "") || (props[`justifyContent${size}SpaceAround`] ? "space-around" : "") || (props[`justifyContent${size}SpaceEvenly`] ? "space-evenly" : "") || null}; `; const alignItems = (size: string) => css` align-items: ${(props: Props) => (props[`alignItems${size}Start`] ? "start" : "") || (props[`alignItems${size}End`] ? "end" : "") || (props[`alignItems${size}Center`] ? "center" : "") || (props[`alignItems${size}Baseline`] ? "baseline" : "") || (props[`alignItems${size}Stretch`] ? "stretch" : "") || null}; `; const alignSelf = (size: string) => css` align-self: ${(props: Props) => (props[`alignSelf${size}Start`] ? "start" : "") || (props[`alignSelf${size}End`] ? "end" : "") || (props[`alignSelf${size}Center`] ? "center" : "") || (props[`alignSelf${size}Baseline`] ? "baseline" : "") || (props[`alignSelf${size}Stretch`] ? "stretch" : "") || null}; `; const alignContent = (size: string) => css` align-content: ${(props: Props) => (props[`alignContent${size}Start`] ? "start" : "") || (props[`alignContent${size}End`] ? "end" : "") || (props[`alignContent${size}Center`] ? "center" : "") || (props[`alignContent${size}Baseline`] ? "baseline" : "") || (props[`alignContent${size}Stretch`] ? "stretch" : "") || null}; `; const flexOrder = (size: string) => css` ${(props: Props) => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map( order => props[`order${size}${order}`] && css` order: ${order}; ` )}; `; const flexGrow = (size: string) => css` flex-grow: ${(props: Props) => { if (props[`flexGrow${size}`] !== undefined) { return "1"; } if (props[`flexGrow${size}0`] !== undefined) { return "0"; } return null; }}; `; const flexShrink = (size: string) => css` flex-shrink: ${(props: Props) => { if (props[`flexShrink${size}`] !== undefined) { return "1"; } if (props[`flexShrink${size}0`] !== undefined) { return "0"; } return null; }}; `; const flexWrap = (size: string) => css` flex-wrap: ${(props: Props) => { if (props[`flexWrap${size}`] !== undefined) { return "wrap"; } if (props[`flexWrap${size}Reverse`] !== undefined) { return "wrap-reverse"; } if (props[`flexNoWrap${size}`] !== undefined) { return "nowrap"; } return null; }}; `; /* Visibility ------------------------------------------------------------- */ const visibility = (size: string) => css` visibility: ${(props: Props) => { if (props[`visible${size}`] !== undefined) { return "visible"; } if (props[`invisible${size}`] !== undefined) { return "hidden"; } return null; }}; `; /* Resize ----------------------------------------------------------------- */ const resize = (size: string) => css` resize: ${(props: Props) => { if (props[`resize${size}None`] !== undefined) { return "none"; } if (props[`resize${size}Both`] !== undefined) { return "both"; } if (props[`resize${size}Vertical`] !== undefined) { return "vertical"; } if (props[`resize${size}Horizontal`] !== undefined) { return "horizontal"; } return null; }}; `; /* Display ---------------------------------------------------------------- */ const display = (size: string) => css` display: ${(props: Props) => (props[`d${size}None`] ? "none" : "") || (props[`d${size}Inline`] ? "inline" : "") || (props[`d${size}InlineBlock`] ? "inline-block" : "") || (props[`d${size}Block`] ? "block" : "") || (props[`d${size}Table`] ? "table" : "") || (props[`d${size}TableCell`] ? "table-cell" : "") || (props[`d${size}TableRow`] ? "table-row" : "") || (props[`d${size}Flex`] ? "flex" : "") || (props[`d${size}InlineFlex`] ? "inline-flex" : "") || null}; `; /* Clearfix --------------------------------------------------------------- */ const clearfix = (size: string) => css` ${(props: Props) => props[`clearfix${size}`] && css` display: block; content: ""; clear: both; `} `; /* Aggregation ------------------------------------------------------------ */ const makeUtilitiesForScreenSize = (size: string) => css<Props>` ${display(size)}; ${sizing(size)}; ${float(size)}; ${spacingMargin(size, "Auto")}; ${() => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map( s => css` ${spacingMargin(size, s)}; ${spacingMargin(size, s, true)}; ${spacingPadding(size, s)}; ` )} ${textTransform(size)}; ${textAlign(size)}; ${textWrap(size)}; ${textWeight(size)}; ${textStyle(size)}; ${textMonospace(size)}; ${textReset(size)}; ${textDecoration(size)}; ${textWordBreak(size)}; ${textTruncate(size)}; ${verticalAlign(size)}; ${flexDirection(size)}; ${justifyContent(size)}; ${alignContent(size)}; ${alignItems(size)}; ${alignSelf(size)}; ${flexGrow(size)}; ${flexShrink(size)}; ${flexWrap(size)}; ${flexOrder(size)}; ${visibility(size)}; ${border(size, "")}; ${border(size, "0")}; ${borderColor(size)}; ${rounded(size)}; ${roundedCircle(size)}; ${roundedPill(size)}; ${textColors(size)}; ${backgroundColors(size)}; ${resize(size)}; ${clearfix(size)}; ${textHide(size)}; ${overflow(size)}; ${position(size)}; ${shadow(size)}; `; export const Utilities = css<Props>` ${makeUtilitiesForScreenSize("")}; ${["Sm", "Md", "Lg", "Xl"].map( size => css` @media (min-width: ${(props: Props) => getConcreteBreakpointSize(props, size.toLowerCase())}) { ${makeUtilitiesForScreenSize(size)}; } ` )}; ${hidden()}; `;
the_stack
//declare var self:any; module TDev.Plugins { var pluginsBySlot:StringMap<Plugin> = {} var pluginWorker:Worker = null; export interface PluginOperation extends RT.AstAnnotationOp { icon?: string; buttonScope?: string; } class Plugin { public slotId = Random.uniqueId(8); public name:string; public operations:PluginOperation[] = []; public intelliProfile : AST.IntelliProfile = undefined; public scriptInfo:Browser.ScriptInfo; public everRegistered = false; public buttonGuid = ""; public uninstall() { delete pluginsBySlot[this.slotId] if (this.buttonGuid) return pluginWorker.postMessage({ tdOperation: "uninstall", slotId: this.slotId, }) } public runOperationAsync(op:PluginOperation) : Promise { if (this.buttonGuid) { return executeButtonPluginAsync(this.scriptInfo, op.opid); } else { pluginWorker.postMessage({ tdSlotId: this.slotId, op: "run_operation", opid: op.opid }) return Promise.as(); } } } class PluginRequest { constructor(public data:any, public plugin:Plugin) { } public respond(resp:any) { if (!resp.status) resp.status = "ok" resp.id = this.data.id; resp.tdSlotId = this.plugin.slotId; pluginWorker.postMessage(resp) } public error(msg:string) { Util.log("plugin error (" + this.plugin.name + "): " + msg) this.respond({ status: "error", message: msg }) } op_current_script_ast() { this.respond({ id: Script.localGuid, ast: AST.Json.dump(Script) }) } op_current_script_id() { this.respond({ script_id: Script.localGuid }) } op_annotate_ast() { TheEditor.clearAnnotations(this.plugin.slotId) TheEditor.injectAnnotations(this.data.annotations.map(a => { return <RT.AstAnnotation>{ id: a.id + "", category: a.category + "", message: a.message + "", ops: (a.ops || []).map(op => { return <RT.AstAnnotationOp>{ opid: op.opid + "", header: op.header + "", description: op.description + "", } }), pluginRef: this.plugin.slotId }})) TheEditor.refreshDecl() if (this.data.annotations.length > 0) TheEditor.searchFor(":plugin") this.respond({ }) } op_progress() { HTML.showProgressNotification(this.plugin.name + ": " + this.data.message) this.respond({ }) } op_info() { HTML.showPluginNotification(this.plugin.name + ": " + this.data.message) this.respond({ }) } op_plugin_crashed() { HTML.showErrorNotification(lf("plugin crashed: ") + this.data.message) this.plugin.uninstall() } op_register_operations() { this.plugin.operations = this.data.operations.map(op => { return <PluginOperation>{ header: op.header + "", description: op.description + "", opid: op.opid + "", icon: /^[a-z0-9A-Z]+$/.test(op.icon) ? op.icon : "plug", buttonScope: op.buttonScope ? op.buttonScope + "" : "", } }) if (!this.plugin.everRegistered) { showPluginUI() this.plugin.everRegistered = true } this.respond({ }) } op_goto() { AST.Json.setStableId(Script) var id = this.data.astid var loc = CodeLocation.fromNodeId(id) if (loc) { TheEditor.goToLocation(loc); this.respond({ status: "found" }) } else { this.respond({ status: "not-found" }) } } // TODO // callback on every top-level change // query if script has errors // modal dialog with markdown // replace a list of stmts in a block with a differnet list (fix it) } export function stopAllPlugins() { Util.values(pluginsBySlot).forEach(p => p.uninstall()) pluginsBySlot = {} } function handlePluginMessage(e:MessageEvent) { var d = e.data if (typeof d != "object") { Util.log("wrong plugin message: " + d) return } if (!Script) return; // TODO make sure we kill the plugins for unloaded scripts if (!e.data.tdSlotId) { Util.log("no slot id in plugin message") return } var p = pluginsBySlot[e.data.tdSlotId] if (!p) { Util.log("no plugin with slot id " + e.data.tdSlotId) return } var r = new PluginRequest(d, p) try { if (r["op_" + d.op]) r["op_" + d.op]() else r.error("no such command: " + d.op) } catch (e) { r.error("exception: " + e) } } function runBackgroundPluginAsync(si:Browser.ScriptInfo) { if (!pluginWorker) { var r = new PromiseInv() var base = /http:\/\/localhost[:\/]/.test(baseUrl) ? "./" : baseUrl pluginWorker = new Worker(base == "./" ? "worker.js" : "https://www.touchdevelop.com/app/?releaseid=2519967637668242448-920d9e58.a88e.4fa8.bcd1.9be5ba29da9f-workerjs" ); pluginWorker.onmessage = (e) => { if (e.data.tdStatus == "ready") { pluginWorker.onmessage = Util.catchErrors("handlePluginMsg", handlePluginMessage) r.success(runBackgroundPluginAsync(si)) } } pluginWorker.postMessage({ op: "load", url: base + "browser.js" }) pluginWorker.postMessage({ op: "load", url: base + "main.js" }) return r } var guid = si.getCloudHeader() ? Promise.as(si.getGuid()) : Browser.TheApiCacheMgr.getAsync(si.publicId, true) .then((info: JsonScript) => World.installPublishedAsync(si.publicId, info.userid)) .then((hd:Cloud.Header) => hd.guid) return guid.then((g:string) => AST.loadScriptAsync(World.getAnyScriptAsync, g)) .then((resp:AST.LoadScriptResult) => { Script.setStableNames(); var cs = AST.Compiler.getCompiledScript(Script, { }) Script = resp.prevScript var p = new Plugin() p.scriptInfo = si p.name = si.getTitle() pluginsBySlot[p.slotId] = p pluginWorker.postMessage({ tdOperation: "install", slotId: p.slotId, entropy: Random.uniqueId(128), precompiled: cs.getCompiledCode() }) }) } function showPluginUI() { var plugins = Util.values(pluginsBySlot) plugins.stableSortObjs((a, b) => Util.stringCompare(a.name, b.name)) var boxes = [] var m = new ModalDialog() var addNew = () => { var e = new DeclEntry("start more plugins") e.makeIntoAddButton(); e.description = "install plugins in this script" var ee = e.mkBox(); HTML.setTickCallback(ee, Ticks.pluginAddMore, () => { m.dismiss() choosePlugin() }); boxes.push(ee) } addNew() TheEditor.queueNavRefresh() plugins.forEach(p => { var box = p.scriptInfo.mkSmallBoxNoClick() box.className += " pluginHeader"; var stopbtn = HTML.mkRoundButton("svg:cancel,currentColor", lf("stop"), Ticks.pluginStop, () => { var ids = Script.editorState.buttonPlugins if (p.buttonGuid && ids) delete ids[p.buttonGuid] p.uninstall() TheEditor.refreshIntelliProfile(); TheEditor.queueNavRefresh() m.dismiss() }); box = ScriptNav.addSideButton(box, stopbtn); boxes.push(box) p.operations.forEach(op => { var e = new DeclEntry(op.header) e.classAdd += " pluginOp"; e.icon = "svg:" + op.icon + ",white" e.color = "#0af" e.description = op.description var ee = e.mkBox(); HTML.setTickCallback(ee, Ticks.pluginRunOperation, () => { p.runOperationAsync(op).done(); m.dismiss() }); boxes.push(ee) }) }) m.choose(boxes) } export function getPluginButtons(scope:string) : HTMLElement[] { var btns:HTMLElement[] = [] Util.values(pluginsBySlot).forEach(p => { p.operations.forEach(op => { if (op.buttonScope == scope) { var pluginid = Util.htmlEscape(op.header.replace(/\s/, '').toLowerCase()); var b = HTML.mkRoundButton("svg:" + op.icon + ",currentColor", op.header, Ticks.sideButtonPlugin, () => { TheEditor.notifyTutorial("plugin:" + pluginid); p.runOperationAsync(op).done(); }) b.id += pluginid // syntax expected by tutorial {stcmd:plugin:<pluginid>} b.className += " navItem-button" btns.push(b) } }) }) return btns } export function getPluginIntelliProfile() : AST.IntelliProfile { // undefined if no profile is defined. var profile : AST.IntelliProfile = null; Util.values(pluginsBySlot) .filter(p => !!p.intelliProfile) .forEach(p => { if (!profile) profile = new AST.IntelliProfile(); profile.merge(p.intelliProfile); }); return profile; } export function installButtonPluginAsync(id:string) { var getHeader:Promise if (Util.values(pluginsBySlot).some(p => p.buttonGuid == id)) return Promise.as() if (/-/.test(id)) getHeader = World.getInstalledHeaderAsync(id) else getHeader = Browser.TheApiCacheMgr.getAsync(id, true) .then((json:JsonScript) => World.installPublishedAsync(json.updateid, json.userid)) var si:Browser.ScriptInfo; return getHeader .then(hd => { if (!hd || hd.status == "deleted") return null if (Util.values(pluginsBySlot).some(p => p.buttonGuid == hd.guid)) return null si = Browser.TheHost.createInstalled(hd) return si.getScriptTextAsync() }) .then(text => { if (!text) return var app = AST.Parser.parseScript(text) // extract buttons var btns = app.actions().filter(a => a.isButtonPlugin()) var p = new Plugin() p.scriptInfo = si p.name = si.getName() p.buttonGuid = si.getGuid() pluginsBySlot[p.slotId] = p if (!Script.editorState.buttonPlugins) Script.editorState.buttonPlugins = {} Script.editorState.buttonPlugins[si.getGuid()] = 1 btns.forEach(btn => { var ico = /{icon:([a-zA-Z0-9]+)}/.exec(btn.getDescription()); p.operations.push(<PluginOperation> { opid: btn.getName(), header: btn.getName(), description: btn.getInlineHelp(), buttonScope: "script", icon: ico ? ico[1] : app.iconName(), }) }) // extract profile var profileAction = app.actions().filter((a : AST.Action) => a.isPrivate && a.getName() == "supported apis")[0]; if (profileAction) { Util.log('loading intelliprofile for plugin {0}', p.name); AST.TypeChecker.tcApp(app); p.intelliProfile = new AST.IntelliProfile(); p.intelliProfile.allowAllLibraries = true; p.intelliProfile.loadFrom(profileAction, false); } }) } function choosePlugin() { Meta.chooseScriptAsync({ searchPath: "scripts?count=60&q=" + encodeURIComponent("#scriptPlugin "), filter: (si:Browser.ScriptInfo) => { return /#scriptPlugin/i.test(si.getDescription()) }, header: lf("choose a plugin"), initialEmptyQuery: true, }).then(si => { if (!Script || !si) return; if (/#backgroundPlugin/i.test(si.getDescription())) { runBackgroundPluginAsync(si).done() return } if (/#buttonPlugin/i.test(si.getDescription())) { installButtonPluginAsync(si.getAnyId()) .then(() => TheEditor.refreshIntelliProfile()) .done(() => showPluginUI()) return } return executeButtonPluginAsync(si, "plugin") }).done(); } function executeButtonPluginAsync(si:Browser.ScriptInfo, actionName:string) { var guid = Script.localGuid; return TheEditor.saveStateAsync() .then(() => { setGlobalScript(null); }) .then(() => ProgressOverlay.lockAndShowAsync(lf("loading plugin"))) .then(() => { if (si.getCloudHeader()) return TheEditor.loadScriptAsync(si.getCloudHeader(), true); else return Browser.TheApiCacheMgr.getAsync(si.publicId, true) .then((info: JsonScript) => TheEditor.loadPublicScriptAsync(si.publicId, info.userid, true)); }) .then(() => { var f = Script.actions().filter(a => !a.isPrivate && a.getName() == actionName)[0] if (!f) { ModalDialog.info(lf("errors in plugin"), lf("no public '{0}' function", actionName)) TheEditor.reload(); } else if (!f.isButtonPlugin() && !f.isPlugin()) { ModalDialog.info(lf("errors in plugin"), lf("'{0}' has unsupported signature", actionName)) TheEditor.reload(); } else { var k = f.getInParameters()[0].getKind() TheEditor.forceReload = true; if (k == api.core.Editor) { setupEditorObject(guid) TheEditor.host.canEdit = false TheEditor.runAction(f, [TheEditor.rtEditor]) } else { TheEditor.runAction(f, [guid]); } } }) } export function setupEditorObject(guid:string, headless = true) { TheEditor.rtEditor = new RT.Editor(TheEditor.currentRt, headless) TheEditor.currentRt.runningPluginOn = guid; } export function runAnnotationOp(ann:RT.AstAnnotation, op:RT.AstAnnotationOp) { var plugin = pluginsBySlot[ann.pluginRef] if (!plugin) return pluginWorker.postMessage({ tdSlotId: plugin.slotId, op: "run_operation", opid: op.opid }) } export function runPlugin() { if (Object.keys(pluginsBySlot).length > 0) showPluginUI() else choosePlugin() } }
the_stack
export class Huffman { static IndexTable = [ 0x0247, 0x0236, 0x0225, 0x0214, 0x0203, 0x01f2, 0x01e1, 0x01d0, 0x01bf, 0x01ae, 0x019d, 0x018c, 0x017b, 0x016a, 0x0161, 0x0158, 0x014f, 0x0146, 0x013d, 0x0134, 0x012b, 0x0122, 0x0119, 0x0110, 0x0107, 0x00fe, 0x00f5, 0x00ec, 0x00e3, 0x00da, 0x00d1, 0x00c8, 0x00bf, 0x00b6, 0x00ad, 0x00a8, 0x00a3, 0x009e, 0x0099, 0x0094, 0x008f, 0x008a, 0x0085, 0x0080, 0x007b, 0x0076, 0x0071, 0x006c, 0x0069, 0x0066, 0x0063, 0x0060, 0x005d, 0x005a, 0x0057, 0x0054, 0x0051, 0x004e, 0x004b, 0x0048, 0x0045, 0x0042, 0x003f, 0x003f, 0x003c, 0x003c, 0x0039, 0x0039, 0x0036, 0x0036, 0x0033, 0x0033, 0x0030, 0x0030, 0x002d, 0x002d, 0x002a, 0x002a, 0x0027, 0x0027, 0x0024, 0x0024, 0x0021, 0x0021, 0x001e, 0x001e, 0x001b, 0x001b, 0x0018, 0x0018, 0x0015, 0x0015, 0x0012, 0x0012, 0x0012, 0x0012, 0x000f, 0x000f, 0x000f, 0x000f, 0x000c, 0x000c, 0x000c, 0x000c, 0x0009, 0x0009, 0x0009, 0x0009, 0x0006, 0x0006, 0x0006, 0x0006, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, ]; static CharacterTable = [ 0x00, 0x00, 0x01, 0x00, 0x01, 0x04, 0x00, 0xff, 0x06, 0x00, 0x14, 0x06, 0x00, 0x13, 0x06, 0x00, 0x05, 0x06, 0x00, 0x02, 0x06, 0x00, 0x80, 0x07, 0x00, 0x6d, 0x07, 0x00, 0x69, 0x07, 0x00, 0x68, 0x07, 0x00, 0x67, 0x07, 0x00, 0x1e, 0x07, 0x00, 0x15, 0x07, 0x00, 0x12, 0x07, 0x00, 0x0d, 0x07, 0x00, 0x0a, 0x07, 0x00, 0x08, 0x07, 0x00, 0x07, 0x07, 0x00, 0x06, 0x07, 0x00, 0x04, 0x07, 0x00, 0x03, 0x07, 0x00, 0x6c, 0x08, 0x00, 0x51, 0x08, 0x00, 0x20, 0x08, 0x00, 0x1f, 0x08, 0x00, 0x1d, 0x08, 0x00, 0x18, 0x08, 0x00, 0x17, 0x08, 0x00, 0x16, 0x08, 0x00, 0x11, 0x08, 0x00, 0x10, 0x08, 0x00, 0x0f, 0x08, 0x00, 0x0c, 0x08, 0x00, 0x0b, 0x08, 0x00, 0x09, 0x08, 0x01, 0x96, 0x09, 0x97, 0x09, 0x01, 0x90, 0x09, 0x95, 0x09, 0x01, 0x64, 0x09, 0x6b, 0x09, 0x01, 0x62, 0x09, 0x63, 0x09, 0x01, 0x56, 0x09, 0x58, 0x09, 0x01, 0x52, 0x09, 0x55, 0x09, 0x01, 0x4d, 0x09, 0x50, 0x09, 0x01, 0x45, 0x09, 0x4c, 0x09, 0x01, 0x40, 0x09, 0x43, 0x09, 0x01, 0x31, 0x09, 0x3b, 0x09, 0x01, 0x28, 0x09, 0x30, 0x09, 0x01, 0x1a, 0x09, 0x25, 0x09, 0x01, 0x0e, 0x09, 0x19, 0x09, 0x02, 0xe2, 0x0a, 0xe8, 0x0a, 0xf0, 0x0a, 0xf8, 0x0a, 0x02, 0xc0, 0x0a, 0xc2, 0x0a, 0xce, 0x0a, 0xe0, 0x0a, 0x02, 0xa0, 0x0a, 0xa2, 0x0a, 0xb0, 0x0a, 0xb8, 0x0a, 0x02, 0x8a, 0x0a, 0x8f, 0x0a, 0x93, 0x0a, 0x98, 0x0a, 0x02, 0x81, 0x0a, 0x82, 0x0a, 0x83, 0x0a, 0x89, 0x0a, 0x02, 0x7c, 0x0a, 0x7d, 0x0a, 0x7e, 0x0a, 0x7f, 0x0a, 0x02, 0x77, 0x0a, 0x78, 0x0a, 0x79, 0x0a, 0x7a, 0x0a, 0x02, 0x73, 0x0a, 0x74, 0x0a, 0x75, 0x0a, 0x76, 0x0a, 0x02, 0x6e, 0x0a, 0x6f, 0x0a, 0x70, 0x0a, 0x72, 0x0a, 0x02, 0x61, 0x0a, 0x65, 0x0a, 0x66, 0x0a, 0x6a, 0x0a, 0x02, 0x5d, 0x0a, 0x5e, 0x0a, 0x5f, 0x0a, 0x60, 0x0a, 0x02, 0x57, 0x0a, 0x59, 0x0a, 0x5a, 0x0a, 0x5b, 0x0a, 0x02, 0x4a, 0x0a, 0x4b, 0x0a, 0x4e, 0x0a, 0x53, 0x0a, 0x02, 0x46, 0x0a, 0x47, 0x0a, 0x48, 0x0a, 0x49, 0x0a, 0x02, 0x3f, 0x0a, 0x41, 0x0a, 0x42, 0x0a, 0x44, 0x0a, 0x02, 0x3a, 0x0a, 0x3c, 0x0a, 0x3d, 0x0a, 0x3e, 0x0a, 0x02, 0x36, 0x0a, 0x37, 0x0a, 0x38, 0x0a, 0x39, 0x0a, 0x02, 0x32, 0x0a, 0x33, 0x0a, 0x34, 0x0a, 0x35, 0x0a, 0x02, 0x2b, 0x0a, 0x2c, 0x0a, 0x2d, 0x0a, 0x2e, 0x0a, 0x02, 0x26, 0x0a, 0x27, 0x0a, 0x29, 0x0a, 0x2a, 0x0a, 0x02, 0x21, 0x0a, 0x22, 0x0a, 0x23, 0x0a, 0x24, 0x0a, 0x03, 0xfb, 0x0b, 0xfc, 0x0b, 0xfd, 0x0b, 0xfe, 0x0b, 0x1b, 0x0a, 0x1b, 0x0a, 0x1c, 0x0a, 0x1c, 0x0a, 0x03, 0xf2, 0x0b, 0xf3, 0x0b, 0xf4, 0x0b, 0xf5, 0x0b, 0xf6, 0x0b, 0xf7, 0x0b, 0xf9, 0x0b, 0xfa, 0x0b, 0x03, 0xe9, 0x0b, 0xea, 0x0b, 0xeb, 0x0b, 0xec, 0x0b, 0xed, 0x0b, 0xee, 0x0b, 0xef, 0x0b, 0xf1, 0x0b, 0x03, 0xde, 0x0b, 0xdf, 0x0b, 0xe1, 0x0b, 0xe3, 0x0b, 0xe4, 0x0b, 0xe5, 0x0b, 0xe6, 0x0b, 0xe7, 0x0b, 0x03, 0xd6, 0x0b, 0xd7, 0x0b, 0xd8, 0x0b, 0xd9, 0x0b, 0xda, 0x0b, 0xdb, 0x0b, 0xdc, 0x0b, 0xdd, 0x0b, 0x03, 0xcd, 0x0b, 0xcf, 0x0b, 0xd0, 0x0b, 0xd1, 0x0b, 0xd2, 0x0b, 0xd3, 0x0b, 0xd4, 0x0b, 0xd5, 0x0b, 0x03, 0xc5, 0x0b, 0xc6, 0x0b, 0xc7, 0x0b, 0xc8, 0x0b, 0xc9, 0x0b, 0xca, 0x0b, 0xcb, 0x0b, 0xcc, 0x0b, 0x03, 0xbb, 0x0b, 0xbc, 0x0b, 0xbd, 0x0b, 0xbe, 0x0b, 0xbf, 0x0b, 0xc1, 0x0b, 0xc3, 0x0b, 0xc4, 0x0b, 0x03, 0xb2, 0x0b, 0xb3, 0x0b, 0xb4, 0x0b, 0xb5, 0x0b, 0xb6, 0x0b, 0xb7, 0x0b, 0xb9, 0x0b, 0xba, 0x0b, 0x03, 0xa9, 0x0b, 0xaa, 0x0b, 0xab, 0x0b, 0xac, 0x0b, 0xad, 0x0b, 0xae, 0x0b, 0xaf, 0x0b, 0xb1, 0x0b, 0x03, 0x9f, 0x0b, 0xa1, 0x0b, 0xa3, 0x0b, 0xa4, 0x0b, 0xa5, 0x0b, 0xa6, 0x0b, 0xa7, 0x0b, 0xa8, 0x0b, 0x03, 0x92, 0x0b, 0x94, 0x0b, 0x99, 0x0b, 0x9a, 0x0b, 0x9b, 0x0b, 0x9c, 0x0b, 0x9d, 0x0b, 0x9e, 0x0b, 0x03, 0x86, 0x0b, 0x87, 0x0b, 0x88, 0x0b, 0x8b, 0x0b, 0x8c, 0x0b, 0x8d, 0x0b, 0x8e, 0x0b, 0x91, 0x0b, 0x03, 0x2f, 0x0b, 0x4f, 0x0b, 0x54, 0x0b, 0x5c, 0x0b, 0x71, 0x0b, 0x7b, 0x0b, 0x84, 0x0b, 0x85, 0x0b, ]; static BitMasks = [ 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, ]; static CompressionTable = [ 0x80010000, 0x70040000, 0x5c060000, 0x3e070000, 0x40070000, 0x60060000, 0x42070000, 0x44070000, 0x46070000, 0x30080000, 0x48070000, 0x31080000, 0x32080000, 0x4a070000, 0x23080100, 0x33080000, 0x34080000, 0x35080000, 0x4c070000, 0x64060000, 0x68060000, 0x4e070000, 0x36080000, 0x37080000, 0x38080000, 0x23080101, 0x24080100, 0x0d070306, 0x0d070307, 0x39080000, 0x50070000, 0x3a080000, 0x3b080000, 0x0e080200, 0x0e080201, 0x0e080202, 0x0e080203, 0x24080101, 0x0f080200, 0x0f080201, 0x25080100, 0x0f080202, 0x0f080203, 0x10080200, 0x10080201, 0x10080202, 0x10080203, 0x00080300, 0x25080101, 0x26080100, 0x11080200, 0x11080201, 0x11080202, 0x11080203, 0x12080200, 0x12080201, 0x12080202, 0x12080203, 0x13080200, 0x26080101, 0x13080201, 0x13080202, 0x13080203, 0x14080200, 0x27080100, 0x14080201, 0x14080202, 0x27080101, 0x14080203, 0x28080100, 0x15080200, 0x15080201, 0x15080202, 0x15080203, 0x16080200, 0x16080201, 0x28080101, 0x29080100, 0x16080202, 0x00080301, 0x29080101, 0x3c080000, 0x2a080100, 0x16080203, 0x00080302, 0x2a080101, 0x2b080100, 0x17080200, 0x2b080101, 0x17080201, 0x17080202, 0x17080203, 0x00080303, 0x18080200, 0x18080201, 0x18080202, 0x18080203, 0x19080200, 0x2c080100, 0x2c080101, 0x2d080100, 0x19080201, 0x19080202, 0x52070000, 0x54070000, 0x56070000, 0x19080203, 0x2d080101, 0x3d080000, 0x58070000, 0x1a080200, 0x1a080201, 0x1a080202, 0x00080304, 0x1a080203, 0x1b080200, 0x1b080201, 0x1b080202, 0x1b080203, 0x1c080200, 0x1c080201, 0x1c080202, 0x1c080203, 0x00080305, 0x1d080200, 0x1d080201, 0x1d080202, 0x1d080203, 0x5a070000, 0x1e080200, 0x1e080201, 0x1e080202, 0x00080306, 0x00080307, 0x01080300, 0x01080301, 0x01080302, 0x1e080203, 0x1f080200, 0x01080303, 0x01080304, 0x01080305, 0x01080306, 0x1f080201, 0x2e080100, 0x01080307, 0x02080300, 0x1f080202, 0x02080301, 0x2e080101, 0x2f080100, 0x2f080101, 0x1f080203, 0x02080302, 0x02080303, 0x02080304, 0x02080305, 0x02080306, 0x02080307, 0x03080300, 0x20080200, 0x03080301, 0x20080201, 0x03080302, 0x03080303, 0x03080304, 0x03080305, 0x03080306, 0x03080307, 0x04080300, 0x04080301, 0x04080302, 0x04080303, 0x04080304, 0x04080305, 0x04080306, 0x20080202, 0x04080307, 0x05080300, 0x05080301, 0x05080302, 0x05080303, 0x05080304, 0x05080305, 0x20080203, 0x05080306, 0x05080307, 0x06080300, 0x06080301, 0x06080302, 0x06080303, 0x06080304, 0x21080200, 0x06080305, 0x21080201, 0x06080306, 0x06080307, 0x07080300, 0x07080301, 0x07080302, 0x07080303, 0x07080304, 0x07080305, 0x07080306, 0x07080307, 0x08080300, 0x21080202, 0x08080301, 0x08080302, 0x08080303, 0x08080304, 0x08080305, 0x08080306, 0x08080307, 0x09080300, 0x09080301, 0x09080302, 0x09080303, 0x09080304, 0x09080305, 0x09080306, 0x09080307, 0x0a080300, 0x0a080301, 0x21080203, 0x0a080302, 0x22080200, 0x0a080303, 0x0a080304, 0x0a080305, 0x0a080306, 0x0a080307, 0x22080201, 0x0b080300, 0x0b080301, 0x0b080302, 0x0b080303, 0x0b080304, 0x0b080305, 0x0b080306, 0x22080202, 0x0b080307, 0x0c080300, 0x0c080301, 0x0c080302, 0x0c080303, 0x0c080304, 0x0c080305, 0x22080203, 0x0c080306, 0x0c080307, 0x0d080300, 0x0d080301, 0x0d080302, 0x0d080303, 0x6c060000, ]; static decompress(input: number[] | Buffer | Uint8Array): number[] { // Offset to first data byte let i = Huffman.getHeaderSize(input); // Total number of bytes to parse let size = Huffman.getPacketSize(input) - i; const output: number[] = []; let a: number; let b = 0; let c: number; let d: number; let count = 0x20; while (true) { if (count >= 8) { while (size > 0 && count >= 8) { count -= 8; size--; a = input[i++] << count; b |= a; } } const index = Huffman.IndexTable[b >> 0x18] || 0; a = Huffman.CharacterTable[index]; d = (b >> (0x18 - a)) & Huffman.BitMasks[a]; c = Huffman.CharacterTable[index + 2 * d + 2]; count += c; if (count > 0x20) return output; a = Huffman.CharacterTable[index + 2 * d + 1]; output.push(a); b <<= c & 0xff; } } /** * Get the number of bytes used for the packet header * @param buffer buffer to parse */ static getHeaderSize(buffer: number[] | Buffer | Uint8Array): number { if (buffer[0] < 0xf0) return 1; return 2; } /** * Get the size of the huffman encoded data * This includes the size of the header * @param buffer buffer to parse */ static getPacketSize(buffer: number[] | Buffer | Uint8Array): number { if (buffer[0] < 0xf0) return buffer[0]; return 0 + ((buffer[0] & 0x0f) << 8) + buffer[0 + 1]; } }
the_stack
import chai from "chai"; import "@openzeppelin/test-helpers"; import { solidity } from "ethereum-waffle"; import { BigNumber, Signer } from "ethers"; import { ethers, upgrades, waffle } from "hardhat"; import { ChainLinkPriceOracle, ChainLinkPriceOracle__factory, MockAggregatorV3, MockAggregatorV3__factory, MockERC20, MockERC20__factory, OracleMedianizer, OracleMedianizer__factory, SimplePriceOracle, SimplePriceOracle__factory, } from "../../../typechain"; import * as TimeHelpers from "../../helpers/time"; chai.use(solidity); const { expect } = chai; // Accounts let deployer: Signer; let feeder: Signer; let alice: Signer; let token0: MockERC20; let token1: MockERC20; let token2: MockERC20; let token3: MockERC20; let simplePriceOracle: SimplePriceOracle; let simplePriceOracleAsFeeder: SimplePriceOracle; let mockAggregatorV3T0T1: MockAggregatorV3; let mockAggregatorV3T0T1AsDeployer: MockAggregatorV3; let chainLinkPriceOracle: ChainLinkPriceOracle; let bobPriceOracle: SimplePriceOracle; let bobPriceOracleAsFeeder: SimplePriceOracle; let evePriceOracle: SimplePriceOracle; let evePriceOracleAsFeeder: SimplePriceOracle; let oracleMedianizer: OracleMedianizer; let oracleMedianizerAsDeployer: OracleMedianizer; let oracleMedianizerAsAlice: OracleMedianizer; describe("OracleMedianizer", () => { async function fixture() { [deployer, feeder, alice] = await ethers.getSigners(); const ERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory; token0 = (await upgrades.deployProxy(ERC20, ["token0", "token0", "18"])) as MockERC20; await token0.deployed(); token1 = (await upgrades.deployProxy(ERC20, ["token1", "token1", "18"])) as MockERC20; await token1.deployed(); token2 = (await upgrades.deployProxy(ERC20, ["token2", "token2", "18"])) as MockERC20; await token0.deployed(); token3 = (await upgrades.deployProxy(ERC20, ["token3", "token3", "18"])) as MockERC20; await token1.deployed(); const SimplePriceOracle = (await ethers.getContractFactory( "SimplePriceOracle", deployer )) as SimplePriceOracle__factory; simplePriceOracle = (await upgrades.deployProxy(SimplePriceOracle, [ await feeder.getAddress(), ])) as SimplePriceOracle; await simplePriceOracle.deployed(); simplePriceOracleAsFeeder = SimplePriceOracle__factory.connect(simplePriceOracle.address, feeder); const MockAggregatorV3 = (await ethers.getContractFactory( "MockAggregatorV3", deployer )) as MockAggregatorV3__factory; mockAggregatorV3T0T1 = await MockAggregatorV3.deploy(BigNumber.from("900000000000000000"), 18); await mockAggregatorV3T0T1.deployed(); mockAggregatorV3T0T1AsDeployer = MockAggregatorV3__factory.connect(mockAggregatorV3T0T1.address, deployer); const ChainLinkPriceOracle = (await ethers.getContractFactory( "ChainLinkPriceOracle", deployer )) as ChainLinkPriceOracle__factory; chainLinkPriceOracle = (await upgrades.deployProxy(ChainLinkPriceOracle)) as ChainLinkPriceOracle; chainLinkPriceOracle.deployed(); const BobPriceOracle = (await ethers.getContractFactory( "SimplePriceOracle", deployer )) as SimplePriceOracle__factory; bobPriceOracle = (await upgrades.deployProxy(BobPriceOracle, [await feeder.getAddress()])) as SimplePriceOracle; await bobPriceOracle.deployed(); bobPriceOracleAsFeeder = SimplePriceOracle__factory.connect(bobPriceOracle.address, feeder); const EvePriceOracle = (await ethers.getContractFactory( "SimplePriceOracle", deployer )) as SimplePriceOracle__factory; evePriceOracle = (await upgrades.deployProxy(EvePriceOracle, [await feeder.getAddress()])) as SimplePriceOracle; await evePriceOracle.deployed(); evePriceOracleAsFeeder = SimplePriceOracle__factory.connect(evePriceOracle.address, feeder); const OracleMedianizer = (await ethers.getContractFactory( "OracleMedianizer", deployer )) as OracleMedianizer__factory; oracleMedianizer = (await upgrades.deployProxy(OracleMedianizer)) as OracleMedianizer; await oracleMedianizer.deployed(); oracleMedianizerAsDeployer = OracleMedianizer__factory.connect(oracleMedianizer.address, deployer); oracleMedianizerAsAlice = OracleMedianizer__factory.connect(oracleMedianizer.address, alice); } beforeEach(async () => { await waffle.loadFixture(fixture); }); describe("#setPrimarySources", async () => { context("when the caller is not the owner", async () => { it("should be reverted", async () => { await expect( oracleMedianizerAsAlice.setPrimarySources( token0.address, token1.address, BigNumber.from("1000000000000000000"), 60, [simplePriceOracle.address] ) ).to.revertedWith("Ownable: caller is not the owner"); }); }); context("when the caller is the owner", async () => { context("when bad max deviation value", async () => { it("should be reverted", async () => { await expect( oracleMedianizerAsDeployer.setPrimarySources(token0.address, token1.address, BigNumber.from("0"), 60, [ simplePriceOracle.address, ]) ).to.revertedWith("OracleMedianizer::setPrimarySources:: bad max deviation value"); }); it("should be reverted", async () => { await expect( oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("2000000000000000000"), 60, [simplePriceOracle.address] ) ).to.revertedWith("OracleMedianizer::setPrimarySources:: bad max deviation value"); }); }); context("when sources length exceed 3", async () => { it("should be reverted", async () => { await expect( oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1000000000000000000"), 60, [ simplePriceOracle.address, simplePriceOracle.address, simplePriceOracle.address, simplePriceOracle.address, ] ) ).to.revertedWith("OracleMedianizer::setPrimarySources:: sources length exceed 3"); }); }); context("when set SimplePriceOracle source", async () => { it("should successfully", async () => { await expect( oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1000000000000000000"), 60, [simplePriceOracle.address] ) ).to.emit(oracleMedianizerAsDeployer, "SetPrimarySources"); // T0T1 pair const sourceT0T1 = await oracleMedianizerAsDeployer.primarySources(token0.address, token1.address, 0); const sourceCountT0T1 = await oracleMedianizerAsDeployer.primarySourceCount(token0.address, token1.address); const maxPriceDeviationT0T1 = await oracleMedianizerAsDeployer.maxPriceDeviations( token0.address, token1.address ); const maxPriceStaleT0T1 = await oracleMedianizerAsDeployer.maxPriceStales(token0.address, token1.address); expect(sourceT0T1).to.eq(simplePriceOracle.address); expect(sourceCountT0T1).to.eq(BigNumber.from(1)); expect(maxPriceDeviationT0T1).to.eq(BigNumber.from("1000000000000000000")); expect(maxPriceStaleT0T1).to.eq(60); // T1T0 pair const sourceT1T0 = await oracleMedianizerAsDeployer.primarySources(token1.address, token0.address, 0); const sourceCountT1T0 = await oracleMedianizerAsDeployer.primarySourceCount(token1.address, token0.address); const maxPriceDeviationT1T0 = await oracleMedianizerAsDeployer.maxPriceDeviations( token1.address, token0.address ); const maxPriceStaleT1T0 = await oracleMedianizerAsDeployer.maxPriceStales(token1.address, token0.address); expect(sourceT1T0).to.eq(simplePriceOracle.address); expect(sourceCountT1T0).to.eq(BigNumber.from(1)); expect(maxPriceDeviationT1T0).to.eq(BigNumber.from("1000000000000000000")); expect(maxPriceStaleT1T0).to.eq(60); }); }); context("when set ChainLinkPriceOracle source", async () => { it("should successfully", async () => { await expect( oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1000000000000000000"), 60, [chainLinkPriceOracle.address] ) ).to.emit(oracleMedianizerAsDeployer, "SetPrimarySources"); // T0T1 pair const sourceT0T1 = await oracleMedianizerAsDeployer.primarySources(token0.address, token1.address, 0); const sourceCountT0T1 = await oracleMedianizerAsDeployer.primarySourceCount(token0.address, token1.address); const maxPriceDeviationT0T1 = await oracleMedianizerAsDeployer.maxPriceDeviations( token0.address, token1.address ); const maxPriceStaleT0T1 = await oracleMedianizerAsDeployer.maxPriceStales(token0.address, token1.address); expect(sourceT0T1).to.eq(chainLinkPriceOracle.address); expect(sourceCountT0T1).to.eq(BigNumber.from(1)); expect(maxPriceDeviationT0T1).to.eq(BigNumber.from("1000000000000000000")); expect(maxPriceStaleT0T1).to.eq(60); // T1T0 pair const sourceT1T0 = await oracleMedianizerAsDeployer.primarySources(token1.address, token0.address, 0); const sourceCountT1T0 = await oracleMedianizerAsDeployer.primarySourceCount(token1.address, token0.address); const maxPriceDeviationT1T0 = await oracleMedianizerAsDeployer.maxPriceDeviations( token1.address, token0.address ); const maxPriceStaleT1T0 = await oracleMedianizerAsDeployer.maxPriceStales(token1.address, token0.address); expect(sourceT1T0).to.eq(chainLinkPriceOracle.address); expect(sourceCountT1T0).to.eq(BigNumber.from(1)); expect(maxPriceDeviationT1T0).to.eq(BigNumber.from("1000000000000000000")); expect(maxPriceStaleT1T0).to.eq(60); }); }); }); }); describe("#setMultiPrimarySources", async () => { context("when inconsistent length", async () => { it("should be reverted", async () => { await expect( oracleMedianizerAsDeployer.setMultiPrimarySources( [token0.address, token2.address], [token1.address], [BigNumber.from("1000000000000000000")], [60], [[simplePriceOracle.address]] ) ).to.revertedWith("OracleMedianizer::setMultiPrimarySources:: inconsistent length"); }); it("should be reverted", async () => { await expect( oracleMedianizerAsDeployer.setMultiPrimarySources( [token0.address, token2.address], [token1.address, token3.address], [BigNumber.from("1000000000000000000")], [60], [[simplePriceOracle.address]] ) ).to.revertedWith("OracleMedianizer::setMultiPrimarySources:: inconsistent length"); }); it("should be reverted", async () => { await expect( oracleMedianizerAsDeployer.setMultiPrimarySources( [token0.address, token2.address], [token1.address, token3.address], [BigNumber.from("1000000000000000000"), BigNumber.from("900000000000000000")], [60], [[simplePriceOracle.address]] ) ).to.revertedWith("OracleMedianizer::setMultiPrimarySources:: inconsistent length"); }); it("should be reverted", async () => { await expect( oracleMedianizerAsDeployer.setMultiPrimarySources( [token0.address, token2.address], [token1.address, token3.address], [BigNumber.from("1000000000000000000"), BigNumber.from("900000000000000000")], [60, 60], [[simplePriceOracle.address]] ) ).to.revertedWith("OracleMedianizer::setMultiPrimarySources:: inconsistent length"); }); }); context("when successfully", async () => { it("should successfully", async () => { await expect( oracleMedianizerAsDeployer.setMultiPrimarySources( [token0.address, token2.address], [token1.address, token3.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1100000000000000000")], [60, 900], [ [simplePriceOracle.address], [simplePriceOracle.address, bobPriceOracle.address, chainLinkPriceOracle.address], ] ) ).to.emit(oracleMedianizerAsDeployer, "SetPrimarySources"); // T0T1 pair const sourceT0T1 = await oracleMedianizerAsDeployer.primarySources(token0.address, token1.address, 0); const sourceCountT0T1 = await oracleMedianizerAsDeployer.primarySourceCount(token0.address, token1.address); const maxPriceDeviationT0T1 = await oracleMedianizerAsDeployer.maxPriceDeviations( token0.address, token1.address ); const maxPriceStaleT0T1 = await oracleMedianizerAsDeployer.maxPriceStales(token0.address, token1.address); expect(sourceT0T1).to.eq(simplePriceOracle.address); expect(sourceCountT0T1).to.eq(BigNumber.from(1)); expect(maxPriceDeviationT0T1).to.eq(BigNumber.from("1000000000000000000")); expect(maxPriceStaleT0T1).to.eq(60); // T1T0 pair const sourceT1T0 = await oracleMedianizerAsDeployer.primarySources(token1.address, token0.address, 0); const sourceCountT1T0 = await oracleMedianizerAsDeployer.primarySourceCount(token1.address, token0.address); const maxPriceDeviationT1T0 = await oracleMedianizerAsDeployer.maxPriceDeviations( token1.address, token0.address ); const maxPriceStaleT1T0 = await oracleMedianizerAsDeployer.maxPriceStales(token1.address, token0.address); expect(sourceT1T0).to.eq(simplePriceOracle.address); expect(sourceCountT1T0).to.eq(BigNumber.from(1)); expect(maxPriceDeviationT1T0).to.eq(BigNumber.from("1000000000000000000")); expect(maxPriceStaleT1T0).to.eq(60); // T2T3 pair // source 0 const sourceT2T3 = await oracleMedianizerAsDeployer.primarySources(token2.address, token3.address, 0); // source 1 const source1T2T3 = await oracleMedianizerAsDeployer.primarySources(token2.address, token3.address, 1); // source 2 const source2T2T3 = await oracleMedianizerAsDeployer.primarySources(token2.address, token3.address, 2); const sourceCountT2T3 = await oracleMedianizerAsDeployer.primarySourceCount(token2.address, token3.address); const maxPriceDeviationT2T3 = await oracleMedianizerAsDeployer.maxPriceDeviations( token2.address, token3.address ); const maxPriceStaleT2T3 = await oracleMedianizerAsDeployer.maxPriceStales(token2.address, token3.address); expect(sourceT2T3).to.eq(simplePriceOracle.address); expect(source1T2T3).to.eq(bobPriceOracle.address); expect(source2T2T3).to.eq(chainLinkPriceOracle.address); expect(sourceCountT2T3).to.eq(BigNumber.from(3)); expect(maxPriceDeviationT2T3).to.eq(BigNumber.from("1100000000000000000")); expect(maxPriceStaleT2T3).to.eq(900); // T3T2 pair // source 0 const sourceT3T2 = await oracleMedianizerAsDeployer.primarySources(token3.address, token2.address, 0); // source 1 const source1T3T2 = await oracleMedianizerAsDeployer.primarySources(token3.address, token2.address, 1); // source 2 const source2T3T2 = await oracleMedianizerAsDeployer.primarySources(token3.address, token2.address, 2); const sourceCountT3T2 = await oracleMedianizerAsDeployer.primarySourceCount(token3.address, token2.address); const maxPriceDeviationT3T2 = await oracleMedianizerAsDeployer.maxPriceDeviations( token3.address, token2.address ); const maxPriceStaleT3T2 = await oracleMedianizerAsDeployer.maxPriceStales(token3.address, token2.address); expect(sourceT3T2).to.eq(simplePriceOracle.address); expect(source1T3T2).to.eq(bobPriceOracle.address); expect(source2T3T2).to.eq(chainLinkPriceOracle.address); expect(sourceCountT3T2).to.eq(BigNumber.from(3)); expect(maxPriceDeviationT3T2).to.eq(BigNumber.from("1100000000000000000")); expect(maxPriceStaleT3T2).to.eq(900); }); }); }); describe("#getPrice", async () => { context("when no primary source", async () => { it("should be reverted", async () => { await expect(oracleMedianizerAsAlice.getPrice(token0.address, token1.address)).to.revertedWith( "OracleMedianizer::getPrice:: no primary source" ); }); }); context("when no valid source", async () => { context("when has SimplePriceOracle source", async () => { it("should be reverted", async () => { await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1000000000000000000"), 60, [simplePriceOracle.address] ); await expect(oracleMedianizerAsAlice.getPrice(token0.address, token1.address)).to.revertedWith( "OracleMedianizer::getPrice:: no valid source" ); }); }); context("when has ChainLinkOracle source", async () => { it("should be reverted", async () => { await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1000000000000000000"), 60, [chainLinkPriceOracle.address] ); await expect(oracleMedianizerAsAlice.getPrice(token0.address, token1.address)).to.revertedWith( "OracleMedianizer::getPrice:: no valid source" ); }); }); }); context("when has 1 sources", async () => { context("when has 1 source price too stale", async () => { it("should be reverted", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1000000000000000000"), 900, [simplePriceOracle.address] ); await TimeHelpers.increase(BigNumber.from("3600")); // 1 hour have passed await expect(oracleMedianizerAsAlice.getPrice(token0.address, token1.address)).to.revertedWith( "OracleMedianizer::getPrice:: no valid source" ); }); }); }); context("when has 1 valid sources", async () => { context("when has SimplePriceOracle source", async () => { context("when successfully", async () => { it("should successfully", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1000000000000000000"), 900, [simplePriceOracle.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed const [price, lastTime] = await oracleMedianizerAsAlice.getPrice(token0.address, token1.address); // result should be Med(price0) => price0 = 1000000000000000000 expect(price).to.eq(BigNumber.from("1000000000000000000")); }); }); }); context("when has ChainLinkPriceOracle source", async () => { context("when successfully", async () => { it("should successfully", async () => { await chainLinkPriceOracle.setPriceFeeds( [token0.address], [token1.address], [mockAggregatorV3T0T1.address] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1000000000000000000"), 900, [chainLinkPriceOracle.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed const [price, lastTime] = await oracleMedianizerAsAlice.getPrice(token0.address, token1.address); // result should be Med(price0) => price0 = 900000000000000000 expect(price).to.eq(BigNumber.from("900000000000000000")); }); }); }); }); context("when has 2 valid sources", async () => { context("when too much deviation (2 valid sources)", async () => { context("when has only SimplePriceOracle source", async () => { it("should be reverted", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await bobPriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("900000000000000000"), BigNumber.from("1000000000000000000").div(9)] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1100000000000000000"), 900, [simplePriceOracle.address, bobPriceOracle.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed await expect(oracleMedianizerAsAlice.getPrice(token0.address, token1.address)).to.revertedWith( "OracleMedianizer::getPrice:: too much deviation 2 valid sources" ); }); }); context("when has SimplePriceOracle and ChainLinkPriceOracle source", async () => { it("should be reverted", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await chainLinkPriceOracle.setPriceFeeds( [token0.address], [token1.address], [mockAggregatorV3T0T1.address] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1100000000000000000"), 900, [simplePriceOracle.address, chainLinkPriceOracle.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed await expect(oracleMedianizerAsAlice.getPrice(token0.address, token1.address)).to.revertedWith( "OracleMedianizer::getPrice:: too much deviation 2 valid sources" ); }); }); }); context("when successfully", async () => { context("when has only SimplePriceOracle source", async () => { it("should successfully", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await bobPriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("900000000000000000"), BigNumber.from("1000000000000000000").div(9)] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1200000000000000000"), 900, [simplePriceOracle.address, bobPriceOracle.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed const [price, lastTime] = await oracleMedianizerAsAlice.getPrice(token0.address, token1.address); // result should be Med(price0, price1) => (price0 + price1) / 2 = (1000000000000000000 + 900000000000000000) / 2 = 950000000000000000 expect(price).to.eq(BigNumber.from("950000000000000000")); }); }); context("when has SimplePriceOracle and ChainLinkPriceOracle source", async () => { it("should successfully", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await chainLinkPriceOracle.setPriceFeeds( [token0.address], [token1.address], [mockAggregatorV3T0T1.address] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1200000000000000000"), 900, [simplePriceOracle.address, chainLinkPriceOracle.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed const [price, lastTime] = await oracleMedianizerAsAlice.getPrice(token0.address, token1.address); // result should be Med(price0, price1) => (price0 + price1) / 2 = (1000000000000000000 + 900000000000000000) / 2 = 950000000000000000 expect(price).to.eq(BigNumber.from("950000000000000000")); }); }); }); }); context("when has 3 valid sources", async () => { context("when too much deviation", async () => { context("when has only SimplePriceOracle source", async () => { it("should be reverted", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await bobPriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("900000000000000000"), BigNumber.from("1000000000000000000").div(9)] ); await evePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("800000000000000000"), BigNumber.from("1000000000000000000").div(8)] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1100000000000000000"), 900, [simplePriceOracle.address, bobPriceOracle.address, evePriceOracleAsFeeder.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed await expect(oracleMedianizerAsAlice.getPrice(token0.address, token1.address)).to.revertedWith( "OracleMedianizer::getPrice:: too much deviation 3 valid sources" ); }); }); context("when has SimplePriceOracle and ChainLinkPriceOracle source", async () => { it("should be reverted", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await chainLinkPriceOracle.setPriceFeeds( [token0.address], [token1.address], [mockAggregatorV3T0T1.address] ); await evePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("800000000000000000"), BigNumber.from("1000000000000000000").div(8)] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1100000000000000000"), 900, [simplePriceOracle.address, chainLinkPriceOracle.address, evePriceOracleAsFeeder.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed await expect(oracleMedianizerAsAlice.getPrice(token0.address, token1.address)).to.revertedWith( "OracleMedianizer::getPrice:: too much deviation 3 valid sources" ); }); }); }); context(`when price0 and price1 are within max deviation, but price2 doesn't`, async () => { it("should be successfully", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1100000000000000000"), BigNumber.from("1000000000000000000").div(11)] ); await chainLinkPriceOracle.setPriceFeeds([token0.address], [token1.address], [mockAggregatorV3T0T1.address]); await evePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("800000000000000000"), BigNumber.from("1000000000000000000").div(8)] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1200000000000000000"), 900, [simplePriceOracle.address, chainLinkPriceOracle.address, evePriceOracleAsFeeder.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed const [price, lastTime] = await oracleMedianizerAsAlice.getPrice(token0.address, token1.address); // result should be Med(price1, price2) => (price1 + price2) / 2 = (900000000000000000 + 800000000000000000) / 2 = 850000000000000000 expect(price).to.eq(BigNumber.from("850000000000000000")); }); }); context(`when price1 and price2 are within max deviation, but price0 doesn't`, async () => { it("should be successfully", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await chainLinkPriceOracle.setPriceFeeds([token0.address], [token1.address], [mockAggregatorV3T0T1.address]); await evePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("700000000000000000"), BigNumber.from("1000000000000000000").div(7)] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1200000000000000000"), 900, [simplePriceOracle.address, chainLinkPriceOracle.address, evePriceOracleAsFeeder.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed const [price, lastTime] = await oracleMedianizerAsAlice.getPrice(token0.address, token1.address); // result should be Med(price0, price1) => (price0 + price1) / 2 = (1000000000000000000 + 900000000000000000) / 2 = 950000000000000000 expect(price).to.eq(BigNumber.from("950000000000000000")); }); }); context("when price0, price1 and price2 are ok", async () => { it("should be successfully", async () => { await simplePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("1000000000000000000"), BigNumber.from("1000000000000000000").div(10)] ); await chainLinkPriceOracle.setPriceFeeds([token0.address], [token1.address], [mockAggregatorV3T0T1.address]); await evePriceOracleAsFeeder.setPrices( [token0.address, token1.address], [token1.address, token0.address], [BigNumber.from("800000000000000000"), BigNumber.from("1000000000000000000").div(8)] ); await oracleMedianizerAsDeployer.setPrimarySources( token0.address, token1.address, BigNumber.from("1200000000000000000"), 900, [simplePriceOracle.address, chainLinkPriceOracle.address, evePriceOracleAsFeeder.address] ); await TimeHelpers.increase(BigNumber.from("60")); // 1 minutes have passed const [price, lastTime] = await oracleMedianizerAsAlice.getPrice(token0.address, token1.address); // result should be Med(price0, price1, price2) => price1 = 900000000000000000 expect(price).to.eq(BigNumber.from("900000000000000000")); }); }); }); }); });
the_stack
"use strict"; /* * Generated by PEG.js 0.10.0. * * http://pegjs.org/ */ function buildMessage(expected, found): any { var DESCRIBE_EXPECTATION_FNS = { literal: function (expectation) { return "\"" + literalEscape(expectation.text) + "\""; }, "class": function (expectation) { var escapedParts = "", i; for (i = 0; i < expectation.parts.length; i++) { escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); } return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; }, any: function (expectation) { return "any character"; }, end: function (expectation) { return "end of input"; }, other: function (expectation) { return expectation.description; } }; function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } function literalEscape(s) { return s .replace(/\\/g, "\\\\") .replace(/"/g, "\\\"") .replace(/\0/g, "\\0") .replace(/\t/g, "\\t") .replace(/\n/g, "\\n") .replace(/\r/g, "\\r") .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); } function classEscape(s) { return s .replace(/\\/g, "\\\\") .replace(/\]/g, "\\]") .replace(/\^/g, "\\^") .replace(/-/g, "\\-") .replace(/\0/g, "\\0") .replace(/\t/g, "\\t") .replace(/\n/g, "\\n") .replace(/\r/g, "\\r") .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); } function describeExpectation(expectation) { return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); } function describeExpected(expected) { var descriptions = new Array(expected.length), i, j; for (i = 0; i < expected.length; i++) { descriptions[i] = describeExpectation(expected[i]); } descriptions.sort(); if (descriptions.length > 0) { for (i = 1, j = 1; i < descriptions.length; i++) { if (descriptions[i - 1] !== descriptions[i]) { descriptions[j] = descriptions[i]; j++; } } descriptions.length = j; } switch (descriptions.length) { case 1: return descriptions[0]; case 2: return descriptions[0] + " or " + descriptions[1]; default: return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; } } function describeFound(found) { return found ? "\"" + literalEscape(found) + "\"" : "end of input"; } return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; class pegSyntaxError extends Error { public expected: any; public found: any; public location: any; public name: string; constructor(message, expected, found?, location?) { super(message); this.message = message; this.expected = expected; this.found = found; this.location = location; this.name = "SyntaxError"; if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, pegSyntaxError); } } } function peg$parse(input, options) { options = options !== void 0 ? options : {}; // KEEP THIS WHEN REGENERATING THE PARSER !! var nOpenParentheses = input.split("(").length - 1; var nCloseParentheses = input.split(")").length - 1; if (nOpenParentheses !== nCloseParentheses) { throw peg$buildSimpleError("The number of opening parentheses does not match the number of closing parentheses.", 0); } // KEEP THIS WHEN REGENERATING THE PARSER !! var peg$FAILED = {}, peg$startRuleFunctions = { chain: peg$parsechain }, peg$startRuleFunction = peg$parsechain, peg$c0 = function (s) { var branches = []; var rings = []; for (var i = 0; i < s[1].length; i++) { branches.push(s[1][i]); } for (var i = 0; i < s[2].length; i++) { var bond = (s[2][i][0]) ? s[2][i][0] : "-"; rings.push({ "bond": bond, "id": s[2][i][1] }); } for (var i = 0; i < s[3].length; i++) { branches.push(s[3][i]); } for (var i = 0; i < s[6].length; i++) { branches.push(s[6][i]); } return { "atom": s[0], "isBracket": s[0].element ? true : false, "branches": branches, "branchCount": branches.length, "ringbonds": rings, "ringbondCount": rings.length, "bond": s[4] ? s[4] : "-", "next": s[5], "hasNext": s[5] ? true : false }; return s; }, peg$c1 = "(", peg$c2 = peg$literalExpectation("(", false), peg$c3 = ")", peg$c4 = peg$literalExpectation(")", false), peg$c5 = function (b) { var bond = (b[1]) ? b[1] : "-"; b[2].branchBond = bond; return b[2]; }, peg$c6 = function (a) { return a; }, peg$c7 = /^[\-=#$:\/\\.]/, peg$c8 = peg$classExpectation(["-", "=", "#", "$", ":", "/", "\\", "."], false, false), peg$c9 = function (b) { return b; }, peg$c10 = "[", peg$c11 = peg$literalExpectation("[", false), peg$c12 = "se", peg$c13 = peg$literalExpectation("se", false), peg$c14 = "as", peg$c15 = peg$literalExpectation("as", false), peg$c16 = "]", peg$c17 = peg$literalExpectation("]", false), peg$c18 = function (b) { return { "isotope": b[1], "element": b[2], "chirality": b[3], "hcount": b[4], "charge": b[5], "class": b[6] }; }, peg$c19 = "B", peg$c20 = peg$literalExpectation("B", false), peg$c21 = "r", peg$c22 = peg$literalExpectation("r", false), peg$c23 = "C", peg$c24 = peg$literalExpectation("C", false), peg$c25 = "l", peg$c26 = peg$literalExpectation("l", false), peg$c27 = /^[NOPSFI]/, peg$c28 = peg$classExpectation(["N", "O", "P", "S", "F", "I"], false, false), peg$c29 = function (o) { if (o.length > 1) return o.join(""); return o; }, peg$c30 = /^[bcnops]/, peg$c31 = peg$classExpectation(["b", "c", "n", "o", "p", "s"], false, false), peg$c32 = "*", peg$c33 = peg$literalExpectation("*", false), peg$c34 = function (w) { return w; }, peg$c35 = /^[A-Z]/, peg$c36 = peg$classExpectation([ ["A", "Z"] ], false, false), peg$c37 = /^[a-z]/, peg$c38 = peg$classExpectation([ ["a", "z"] ], false, false), peg$c39 = function (e) { return e.join(""); }, peg$c40 = "%", peg$c41 = peg$literalExpectation("%", false), peg$c42 = /^[1-9]/, peg$c43 = peg$classExpectation([ ["1", "9"] ], false, false), peg$c44 = /^[0-9]/, peg$c45 = peg$classExpectation([ ["0", "9"] ], false, false), peg$c46 = function (r) { if (r.length == 1) return Number(r); return Number(r.join("").replace("%", "")); }, peg$c47 = "@", peg$c48 = peg$literalExpectation("@", false), peg$c49 = "TH", peg$c50 = peg$literalExpectation("TH", false), peg$c51 = /^[12]/, peg$c52 = peg$classExpectation(["1", "2"], false, false), peg$c53 = "AL", peg$c54 = peg$literalExpectation("AL", false), peg$c55 = "SP", peg$c56 = peg$literalExpectation("SP", false), peg$c57 = /^[1-3]/, peg$c58 = peg$classExpectation([ ["1", "3"] ], false, false), peg$c59 = "TB", peg$c60 = peg$literalExpectation("TB", false), peg$c61 = "OH", peg$c62 = peg$literalExpectation("OH", false), peg$c63 = function (c) { if (!c[1]) return "@"; if (c[1] == "@") return "@@"; return c[1].join("").replace(",", ""); }, peg$c64 = function (c) { return c; }, peg$c65 = "+", peg$c66 = peg$literalExpectation("+", false), peg$c67 = function (c) { if (!c[1]) return 1; if (c[1] != "+") return Number(c[1].join("")); return 2; }, peg$c68 = "-", peg$c69 = peg$literalExpectation("-", false), peg$c70 = function (c) { if (!c[1]) return -1; if (c[1] != "-") return -Number(c[1].join("")); return -2; }, peg$c71 = "H", peg$c72 = peg$literalExpectation("H", false), peg$c73 = function (h) { if (h[1]) return Number(h[1]); return 1; }, peg$c74 = ":", peg$c75 = peg$literalExpectation(":", false), peg$c76 = /^[0]/, peg$c77 = peg$classExpectation(["0"], false, false), peg$c78 = function (c) { return Number(c[1][0] + c[1][1].join("")); }, peg$c79 = function (i) { return Number(i.join("")); }, peg$currPos = 0, // peg$savedPos = 0, peg$posDetailsCache = [{ line: 1, column: 1 }], peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } // function text() { // return input.substring(peg$savedPos, peg$currPos); // } // // function location() { // return peg$computeLocation(peg$savedPos, peg$currPos); // } // // function expected(description, location) { // location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos); // // throw peg$buildStructuredError( // [peg$otherExpectation(description)], // input.substring(peg$savedPos, peg$currPos), // location // ); // } // function error(message, location) { // location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos); // // throw peg$buildSimpleError(message, location); // } function peg$literalExpectation(text, ignoreCase) { return { type: "literal", text: text, ignoreCase: ignoreCase }; } function peg$classExpectation(parts, inverted, ignoreCase) { return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; } // function peg$anyExpectation() { // return { // type: "any" // }; // } function peg$endExpectation() { return { type: "end" }; } // function peg$otherExpectation(description) { // return { // type: "other", // description: description // }; // } function peg$computePosDetails(pos) { var details = peg$posDetailsCache[pos], p; if (details) { return details; } else { p = pos - 1; while (!peg$posDetailsCache[p]) { p--; } details = peg$posDetailsCache[p]; details = { line: details.line, column: details.column }; while (p < pos) { if (input.charCodeAt(p) === 10) { details.line++; details.column = 1; } else { details.column++; } p++; } peg$posDetailsCache[pos] = details; return details; } } function peg$computeLocation(startPos, endPos) { var startPosDetails = peg$computePosDetails(startPos), endPosDetails = peg$computePosDetails(endPos); return { start: { offset: startPos, line: startPosDetails.line, column: startPosDetails.column }, end: { offset: endPos, line: endPosDetails.line, column: endPosDetails.column } }; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildSimpleError(message, location) { return new pegSyntaxError(message, null, null, location); } function peg$buildStructuredError(expected, found, location) { return new pegSyntaxError( buildMessage(expected, found), expected, found, location ); } function peg$parsechain() { var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; s0 = peg$currPos; s1 = peg$currPos; s2 = peg$parseatom(); if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parsebranch(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parsebranch(); } if (s3 !== peg$FAILED) { s4 = []; s5 = peg$currPos; s6 = peg$parsebond(); if (s6 === peg$FAILED) { s6 = null; } if (s6 !== peg$FAILED) { s7 = peg$parsering(); if (s7 !== peg$FAILED) { s6 = [s6, s7]; s5 = s6; } else { peg$currPos = s5; s5 = peg$FAILED; } } else { peg$currPos = s5; s5 = peg$FAILED; } while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$currPos; s6 = peg$parsebond(); if (s6 === peg$FAILED) { s6 = null; } if (s6 !== peg$FAILED) { s7 = peg$parsering(); if (s7 !== peg$FAILED) { s6 = [s6, s7]; s5 = s6; } else { peg$currPos = s5; s5 = peg$FAILED; } } else { peg$currPos = s5; s5 = peg$FAILED; } } if (s4 !== peg$FAILED) { s5 = []; s6 = peg$parsebranch(); while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$parsebranch(); } if (s5 !== peg$FAILED) { s6 = peg$parsebond(); if (s6 === peg$FAILED) { s6 = null; } if (s6 !== peg$FAILED) { s7 = peg$parsechain(); if (s7 === peg$FAILED) { s7 = null; } if (s7 !== peg$FAILED) { s8 = []; s9 = peg$parsebranch(); while (s9 !== peg$FAILED) { s8.push(s9); s9 = peg$parsebranch(); } if (s8 !== peg$FAILED) { s2 = [s2, s3, s4, s5, s6, s7, s8]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c0(s1); } s0 = s1; return s0; } function peg$parsebranch() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 40) { s2 = peg$c1; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c2); } } if (s2 !== peg$FAILED) { s3 = peg$parsebond(); if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { s4 = peg$parsechain(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s5 = peg$c3; peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c4); } } if (s5 !== peg$FAILED) { s2 = [s2, s3, s4, s5]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c5(s1); } s0 = s1; return s0; } function peg$parseatom() { var s0, s1; s0 = peg$currPos; s1 = peg$parseorganicsymbol(); if (s1 === peg$FAILED) { s1 = peg$parsearomaticsymbol(); if (s1 === peg$FAILED) { s1 = peg$parsebracketatom(); if (s1 === peg$FAILED) { s1 = peg$parsewildcard(); } } } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c6(s1); } s0 = s1; return s0; } function peg$parsebond() { var s0, s1; s0 = peg$currPos; if (peg$c7.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); // Hack to resolve problem caused by: // O=C(N[C@@H](CC(O)=O)C(N[C@H](C1=CC=C(O)C=C1)C(N[C@@H](CC(O)=O)C(NCC(N[C@@H](C(N[C@@H]([C@H](C)CC(O)=O)C(N/C(C(O[C@H](C)[C@@H]2NC([C@H](CO)NC(C(O3)C3CCC)=O)=O)=O)=C\\\\C4=CNC5=C4C=CC=C5)=O)=O)[C@H](O)C(N)=O)=O)=O)=O)=O)[C@H](CC(O)=O)NC([C@@H](CC6=CNC7=C6C=CC=C7)NC2=O)=O // KEEP THIS WHEN REGENERATING THE PARSER !! if (s1 === input.charAt(peg$currPos + 1)) { s1 = peg$FAILED; if (peg$silentFails === 0) { throw peg$buildSimpleError("The parser encountered a bond repetition.", peg$currPos + 1); } } // KEEP THIS WHEN REGENERATING THE PARSER !! peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c9(s1); } s0 = s1; return s0; } function peg$parsebracketatom() { var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 91) { s2 = peg$c10; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c11); } } if (s2 !== peg$FAILED) { s3 = peg$parseisotope(); if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c12) { s4 = peg$c12; peg$currPos += 2; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c13); } } if (s4 === peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c14) { s4 = peg$c14; peg$currPos += 2; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c15); } } if (s4 === peg$FAILED) { s4 = peg$parsearomaticsymbol(); if (s4 === peg$FAILED) { s4 = peg$parseelementsymbol(); if (s4 === peg$FAILED) { s4 = peg$parsewildcard(); } } } } if (s4 !== peg$FAILED) { s5 = peg$parsechiral(); if (s5 === peg$FAILED) { s5 = null; } if (s5 !== peg$FAILED) { s6 = peg$parsehcount(); if (s6 === peg$FAILED) { s6 = null; } if (s6 !== peg$FAILED) { s7 = peg$parsecharge(); if (s7 === peg$FAILED) { s7 = null; } if (s7 !== peg$FAILED) { s8 = peg$parseclass(); if (s8 === peg$FAILED) { s8 = null; } if (s8 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 93) { s9 = peg$c16; peg$currPos++; } else { s9 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c17); } } if (s9 !== peg$FAILED) { s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c18(s1); } s0 = s1; return s0; } function peg$parseorganicsymbol() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 66) { s2 = peg$c19; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 114) { s3 = peg$c21; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c22); } } if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 === peg$FAILED) { s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 67) { s2 = peg$c23; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c24); } } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 108) { s3 = peg$c25; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 === peg$FAILED) { if (peg$c27.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c28); } } } } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c29(s1); } s0 = s1; return s0; } function peg$parsearomaticsymbol() { var s0, s1; s0 = peg$currPos; if (peg$c30.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c31); } } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c6(s1); } s0 = s1; return s0; } function peg$parsewildcard() { var s0, s1; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 42) { s1 = peg$c32; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c33); } } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c34(s1); } s0 = s1; return s0; } function peg$parseelementsymbol() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; if (peg$c35.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c36); } } if (s2 !== peg$FAILED) { if (peg$c37.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c38); } } if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c39(s1); } s0 = s1; return s0; } function peg$parsering() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 37) { s2 = peg$c40; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c41); } } if (s2 !== peg$FAILED) { if (peg$c42.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c43); } } if (s3 !== peg$FAILED) { if (peg$c44.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s4 !== peg$FAILED) { s2 = [s2, s3, s4]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 === peg$FAILED) { if (peg$c44.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c46(s1); } s0 = s1; return s0; } function peg$parsechiral() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 64) { s2 = peg$c47; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c48); } } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 64) { s3 = peg$c47; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c48); } } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c49) { s4 = peg$c49; peg$currPos += 2; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c50); } } if (s4 !== peg$FAILED) { if (peg$c51.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c52); } } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c53) { s4 = peg$c53; peg$currPos += 2; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c54); } } if (s4 !== peg$FAILED) { if (peg$c51.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c52); } } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c55) { s4 = peg$c55; peg$currPos += 2; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c56); } } if (s4 !== peg$FAILED) { if (peg$c57.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c58); } } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c59) { s4 = peg$c59; peg$currPos += 2; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c60); } } if (s4 !== peg$FAILED) { if (peg$c42.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c43); } } if (s5 !== peg$FAILED) { if (peg$c44.test(input.charAt(peg$currPos))) { s6 = input.charAt(peg$currPos); peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s6 === peg$FAILED) { s6 = null; } if (s6 !== peg$FAILED) { s4 = [s4, s5, s6]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c61) { s4 = peg$c61; peg$currPos += 2; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c62); } } if (s4 !== peg$FAILED) { if (peg$c42.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c43); } } if (s5 !== peg$FAILED) { if (peg$c44.test(input.charAt(peg$currPos))) { s6 = input.charAt(peg$currPos); peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s6 === peg$FAILED) { s6 = null; } if (s6 !== peg$FAILED) { s4 = [s4, s5, s6]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } } } } } if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c63(s1); } s0 = s1; return s0; } function peg$parsecharge() { var s0, s1; s0 = peg$currPos; s1 = peg$parseposcharge(); if (s1 === peg$FAILED) { s1 = peg$parsenegcharge(); } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c64(s1); } s0 = s1; return s0; } function peg$parseposcharge() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 43) { s2 = peg$c65; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c66); } } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 43) { s3 = peg$c65; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c66); } } if (s3 === peg$FAILED) { s3 = peg$currPos; if (peg$c42.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c43); } } if (s4 !== peg$FAILED) { if (peg$c44.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s5 === peg$FAILED) { s5 = null; } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c67(s1); } s0 = s1; return s0; } function peg$parsenegcharge() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 45) { s2 = peg$c68; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c69); } } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 45) { s3 = peg$c68; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c69); } } if (s3 === peg$FAILED) { s3 = peg$currPos; if (peg$c42.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c43); } } if (s4 !== peg$FAILED) { if (peg$c44.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s5 === peg$FAILED) { s5 = null; } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c70(s1); } s0 = s1; return s0; } function peg$parsehcount() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 72) { s2 = peg$c71; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c72); } } if (s2 !== peg$FAILED) { if (peg$c44.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c73(s1); } s0 = s1; return s0; } function peg$parseclass() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 58) { s2 = peg$c74; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c75); } } if (s2 !== peg$FAILED) { s3 = peg$currPos; if (peg$c42.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c43); } } if (s4 !== peg$FAILED) { s5 = []; if (peg$c44.test(input.charAt(peg$currPos))) { s6 = input.charAt(peg$currPos); peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } while (s6 !== peg$FAILED) { s5.push(s6); if (peg$c44.test(input.charAt(peg$currPos))) { s6 = input.charAt(peg$currPos); peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 === peg$FAILED) { if (peg$c76.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c77); } } } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c78(s1); } s0 = s1; return s0; } function peg$parseisotope() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$currPos; if (peg$c42.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c43); } } if (s2 !== peg$FAILED) { if (peg$c44.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { if (peg$c44.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s4 === peg$FAILED) { s4 = null; } if (s4 !== peg$FAILED) { s2 = [s2, s3, s4]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { // peg$savedPos = s0; s1 = peg$c79(s1); } s0 = s1; return s0; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail(peg$endExpectation()); } throw peg$buildStructuredError( peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) ); } } const Parser = { SyntaxError: pegSyntaxError, parse: peg$parse }; export default Parser
the_stack
import { Convert } from '../..'; import { UnresolvedMapping } from '../../core/utils'; import { MessageFactory, MosaicSupplyRevocationTransaction, UInt64 } from '../../model'; import { Address, PublicAccount } from '../../model/account'; import { Mosaic, MosaicFlags, MosaicId, MosaicNonce } from '../../model/mosaic'; import { NamespaceId } from '../../model/namespace'; import { AccountAddressRestrictionTransaction, AccountKeyLinkTransaction, AccountMetadataTransaction, AccountMosaicRestrictionTransaction, AccountOperationRestrictionTransaction, AddressAliasTransaction, AggregateTransaction, AggregateTransactionCosignature, AggregateTransactionInfo, Deadline, LockFundsTransaction, MosaicAddressRestrictionTransaction, MosaicAliasTransaction, MosaicDefinitionTransaction, MosaicGlobalRestrictionTransaction, MosaicMetadataTransaction, MosaicSupplyChangeTransaction, MultisigAccountModificationTransaction, NamespaceMetadataTransaction, NamespaceRegistrationTransaction, NodeKeyLinkTransaction, SecretLockTransaction, SecretProofTransaction, SignedTransaction, Transaction, TransactionInfo, TransactionType, TransferTransaction, VotingKeyLinkTransaction, VrfKeyLinkTransaction, } from '../../model/transaction'; /** * Extract recipientAddress value from encoded hexadecimal notation. * * If bit 0 of byte 0 is not set (e.g. 0x90), then it is a regular address. * Else (e.g. 0x91) it represents a namespace id which starts at byte 1. * * @param recipientAddress {string} Encoded hexadecimal recipientAddress notation * @return {Address | NamespaceId} */ export const extractRecipient = (recipientAddress: any): Address | NamespaceId => { if (typeof recipientAddress === 'string') { return UnresolvedMapping.toUnresolvedAddress(recipientAddress); } else if (typeof recipientAddress === 'object') { // Is JSON object if (recipientAddress.hasOwnProperty('address')) { return Address.createFromRawAddress(recipientAddress.address); } else if (recipientAddress.hasOwnProperty('id')) { return NamespaceId.createFromEncoded(recipientAddress.id); } } throw new Error(`Recipient: ${recipientAddress} type is not recognised`); }; /** * Extract mosaics from encoded UInt64 notation. * * If most significant bit of byte 0 is set, then it is a namespaceId. * If most significant bit of byte 0 is not set, then it is a mosaicId. * * @param mosaics {Array | undefined} The DTO array of mosaics (with UInt64 Id notation) * @return {Mosaic[]} */ export const extractMosaics = (mosaics: any): Mosaic[] => { if (mosaics === undefined) { return []; } return mosaics.map((mosaicDTO) => { const id = UnresolvedMapping.toUnresolvedMosaic(mosaicDTO.id); return new Mosaic(id, UInt64.fromNumericString(mosaicDTO.amount)); }); }; /** * Extract deadline from json payload. * @param deadline - deadline dto */ const extractDeadline = (deadline?: string): Deadline => { if (!deadline) { return Deadline.createEmtpy(); } return Deadline.createFromDTO(deadline); }; /** * @internal * Extract transaction meta data * * @param meta - Transaction meta data * @param id - TransactionId * @return {TransactionInfo | AggregateTransactionInfo | undefined} */ const extractTransactionMeta = (meta: any, id: string): TransactionInfo | AggregateTransactionInfo | undefined => { if (!meta) { return undefined; } if (meta.aggregateHash || meta.aggregateId) { return new AggregateTransactionInfo(UInt64.fromNumericString(meta.height), meta.index, id, meta.aggregateHash, meta.aggregateId); } return new TransactionInfo(UInt64.fromNumericString(meta.height), meta.index, id, meta.hash, meta.merkleComponentHash); }; /** * @internal * @param transactionDTO * @param isEmbedded * @returns {any} * @constructor */ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Transaction => { const type: TransactionType = transactionDTO.type; const version: number = transactionDTO.version; const signature = Transaction.resolveSignature(transactionDTO.signature, false); const maxFee = UInt64.fromNumericString(transactionDTO.maxFee || '0'); const deadline = extractDeadline(transactionDTO.deadline); const networkType = transactionDTO.network; const signer = transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, networkType) : undefined; switch (type) { case TransactionType.TRANSFER: return new TransferTransaction( networkType, version, deadline, maxFee, extractRecipient(transactionDTO.recipientAddress), extractMosaics(transactionDTO.mosaics), MessageFactory.createMessageFromHex(transactionDTO.message), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.NAMESPACE_REGISTRATION: return new NamespaceRegistrationTransaction( networkType, version, deadline, maxFee, transactionDTO.registrationType, transactionDTO.name, NamespaceId.createFromEncoded(transactionDTO.id), transactionDTO.registrationType === 0 ? UInt64.fromNumericString(transactionDTO.duration) : undefined, transactionDTO.registrationType === 1 ? NamespaceId.createFromEncoded(transactionDTO.parentId) : undefined, signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.MOSAIC_DEFINITION: return new MosaicDefinitionTransaction( networkType, version, deadline, maxFee, MosaicNonce.createFromNumber(transactionDTO.nonce), new MosaicId(transactionDTO.id), new MosaicFlags(transactionDTO.flags), transactionDTO.divisibility, UInt64.fromNumericString(transactionDTO.duration), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.MOSAIC_SUPPLY_CHANGE: return new MosaicSupplyChangeTransaction( networkType, version, deadline, maxFee, UnresolvedMapping.toUnresolvedMosaic(transactionDTO.mosaicId), transactionDTO.action, UInt64.fromNumericString(transactionDTO.delta), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.MOSAIC_SUPPLY_REVOCATION: return new MosaicSupplyRevocationTransaction( networkType, version, deadline, maxFee, extractRecipient(transactionDTO.sourceAddress), new Mosaic(new MosaicId(transactionDTO.mosaicId), UInt64.fromNumericString(transactionDTO.amount)), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.MULTISIG_ACCOUNT_MODIFICATION: return new MultisigAccountModificationTransaction( networkType, version, deadline, maxFee, transactionDTO.minApprovalDelta, transactionDTO.minRemovalDelta, transactionDTO.addressAdditions ? transactionDTO.addressAdditions.map((addition) => extractRecipient(addition)) : [], transactionDTO.addressDeletions ? transactionDTO.addressDeletions.map((deletion) => extractRecipient(deletion)) : [], signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.HASH_LOCK: return new LockFundsTransaction( networkType, version, deadline, maxFee, new Mosaic(new MosaicId(transactionDTO.mosaicId), UInt64.fromNumericString(transactionDTO.amount)), UInt64.fromNumericString(transactionDTO.duration), new SignedTransaction('', transactionDTO.hash, '', TransactionType.AGGREGATE_BONDED, networkType), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.SECRET_LOCK: const recipientAddress = transactionDTO.recipientAddress; const mosaicId = UnresolvedMapping.toUnresolvedMosaic(transactionDTO.mosaicId); return new SecretLockTransaction( networkType, version, deadline, maxFee, new Mosaic(mosaicId, UInt64.fromNumericString(transactionDTO.amount)), UInt64.fromNumericString(transactionDTO.duration), transactionDTO.hashAlgorithm, transactionDTO.secret, extractRecipient(recipientAddress), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.SECRET_PROOF: return new SecretProofTransaction( networkType, version, deadline, maxFee, transactionDTO.hashAlgorithm, transactionDTO.secret, extractRecipient(transactionDTO.recipientAddress), transactionDTO.proof, signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.MOSAIC_ALIAS: return new MosaicAliasTransaction( networkType, version, deadline, maxFee, transactionDTO.aliasAction, NamespaceId.createFromEncoded(transactionDTO.namespaceId), new MosaicId(transactionDTO.mosaicId), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.ADDRESS_ALIAS: return new AddressAliasTransaction( networkType, version, deadline, maxFee, transactionDTO.aliasAction, NamespaceId.createFromEncoded(transactionDTO.namespaceId), extractRecipient(transactionDTO.address) as Address, signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.ACCOUNT_ADDRESS_RESTRICTION: return new AccountAddressRestrictionTransaction( networkType, version, deadline, maxFee, transactionDTO.restrictionFlags, transactionDTO.restrictionAdditions ? transactionDTO.restrictionAdditions.map((addition) => extractRecipient(addition)) : [], transactionDTO.restrictionDeletions ? transactionDTO.restrictionDeletions.map((deletion) => extractRecipient(deletion)) : [], signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.ACCOUNT_OPERATION_RESTRICTION: return new AccountOperationRestrictionTransaction( networkType, version, deadline, maxFee, transactionDTO.restrictionFlags, transactionDTO.restrictionAdditions ? transactionDTO.restrictionAdditions : [], transactionDTO.restrictionDeletions ? transactionDTO.restrictionDeletions : [], signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.ACCOUNT_MOSAIC_RESTRICTION: return new AccountMosaicRestrictionTransaction( networkType, version, deadline, maxFee, transactionDTO.restrictionFlags, transactionDTO.restrictionAdditions ? transactionDTO.restrictionAdditions.map((addition) => UnresolvedMapping.toUnresolvedMosaic(addition)) : [], transactionDTO.restrictionDeletions ? transactionDTO.restrictionDeletions.map((deletion) => UnresolvedMapping.toUnresolvedMosaic(deletion)) : [], signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.ACCOUNT_KEY_LINK: return new AccountKeyLinkTransaction( networkType, version, deadline, maxFee, transactionDTO.linkedPublicKey, transactionDTO.linkAction, signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.MOSAIC_GLOBAL_RESTRICTION: return new MosaicGlobalRestrictionTransaction( networkType, version, deadline, maxFee, UnresolvedMapping.toUnresolvedMosaic(transactionDTO.mosaicId), UnresolvedMapping.toUnresolvedMosaic(transactionDTO.referenceMosaicId), UInt64.fromHex(transactionDTO.restrictionKey), UInt64.fromNumericString(transactionDTO.previousRestrictionValue), transactionDTO.previousRestrictionType, UInt64.fromNumericString(transactionDTO.newRestrictionValue), transactionDTO.newRestrictionType, signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.MOSAIC_ADDRESS_RESTRICTION: return new MosaicAddressRestrictionTransaction( networkType, version, deadline, maxFee, UnresolvedMapping.toUnresolvedMosaic(transactionDTO.mosaicId), UInt64.fromHex(transactionDTO.restrictionKey), extractRecipient(transactionDTO.targetAddress), UInt64.fromNumericString(transactionDTO.previousRestrictionValue), UInt64.fromNumericString(transactionDTO.newRestrictionValue), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.ACCOUNT_METADATA: return new AccountMetadataTransaction( networkType, version, deadline, maxFee, extractRecipient(transactionDTO.targetAddress), UInt64.fromHex(transactionDTO.scopedMetadataKey), transactionDTO.valueSizeDelta, Convert.hexToUint8(transactionDTO.value), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.MOSAIC_METADATA: return new MosaicMetadataTransaction( networkType, version, deadline, maxFee, extractRecipient(transactionDTO.targetAddress), UInt64.fromHex(transactionDTO.scopedMetadataKey), UnresolvedMapping.toUnresolvedMosaic(transactionDTO.targetMosaicId), transactionDTO.valueSizeDelta, Convert.hexToUint8(transactionDTO.value), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.NAMESPACE_METADATA: return new NamespaceMetadataTransaction( networkType, version, deadline, maxFee, extractRecipient(transactionDTO.targetAddress), UInt64.fromHex(transactionDTO.scopedMetadataKey), NamespaceId.createFromEncoded(transactionDTO.targetNamespaceId), transactionDTO.valueSizeDelta, Convert.hexToUint8(transactionDTO.value), signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.VRF_KEY_LINK: return new VrfKeyLinkTransaction( networkType, version, deadline, maxFee, transactionDTO.linkedPublicKey, transactionDTO.linkAction, signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.NODE_KEY_LINK: return new NodeKeyLinkTransaction( networkType, version, deadline, maxFee, transactionDTO.linkedPublicKey, transactionDTO.linkAction, signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); case TransactionType.VOTING_KEY_LINK: return new VotingKeyLinkTransaction( networkType, version, deadline, maxFee, transactionDTO.linkedPublicKey, transactionDTO.startEpoch, transactionDTO.endEpoch, transactionDTO.linkAction, signature, signer, transactionInfo, ).setPayloadSize(transactionDTO.size); default: throw new Error(`Unimplemented transaction with type ${type} for version ${version}`); } }; /** * @internal * @param transactionDTO * @returns {Transaction} * @constructor */ export const CreateTransactionFromDTO = (transactionDTO): Transaction => { if ( transactionDTO.transaction.type === TransactionType.AGGREGATE_COMPLETE || transactionDTO.transaction.type === TransactionType.AGGREGATE_BONDED ) { const innerTransactions = transactionDTO.transaction.transactions ? transactionDTO.transaction.transactions.map((innerTransactionDTO) => { const aggregateTransactionInfo = extractTransactionMeta(innerTransactionDTO.meta, innerTransactionDTO.id); innerTransactionDTO.transaction.maxFee = transactionDTO.transaction.maxFee; innerTransactionDTO.transaction.deadline = transactionDTO.transaction.deadline; innerTransactionDTO.transaction.signature = transactionDTO.transaction.signature; return CreateStandaloneTransactionFromDTO(innerTransactionDTO.transaction, aggregateTransactionInfo); }) : []; return new AggregateTransaction( transactionDTO.transaction.network, transactionDTO.transaction.type, transactionDTO.transaction.version, extractDeadline(transactionDTO.transaction.deadline), UInt64.fromNumericString(transactionDTO.transaction.maxFee || '0'), innerTransactions, transactionDTO.transaction.cosignatures ? transactionDTO.transaction.cosignatures.map((aggregateCosignatureDTO) => { return new AggregateTransactionCosignature( aggregateCosignatureDTO.signature, PublicAccount.createFromPublicKey(aggregateCosignatureDTO.signerPublicKey, transactionDTO.transaction.network), UInt64.fromNumericString(aggregateCosignatureDTO.version), ); }) : [], Transaction.resolveSignature(transactionDTO.transaction.signature, false), transactionDTO.transaction.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.transaction.signerPublicKey, transactionDTO.transaction.network) : undefined, extractTransactionMeta(transactionDTO.meta, transactionDTO.id), ).setPayloadSize(transactionDTO.transaction.size); } else { return CreateStandaloneTransactionFromDTO( transactionDTO.transaction, extractTransactionMeta(transactionDTO.meta, transactionDTO.id), ); } };
the_stack
import { TfCommand, CoreArguments } from "../../lib/tfcommand"; import { MergeSettings, PackageSettings, PublishSettings } from "./_lib/interfaces"; import { WebApi, getBasicHandler } from "azure-devops-node-api/WebApi"; import { BasicCredentialHandler } from "azure-devops-node-api/handlers/basiccreds"; import { GalleryBase, CoreExtInfo, PublisherManager, PackagePublisher } from "./_lib/publish"; import * as path from "path"; import _ = require("lodash"); import jju = require("jju"); import args = require("../../lib/arguments"); import https = require("https"); import trace = require("../../lib/trace"); import { readFile } from "fs"; import { promisify } from "util"; import { GalleryApi } from "azure-devops-node-api/GalleryApi"; export function getCommand(args: string[]): TfCommand<ExtensionArguments, void> { return new ExtensionBase<void>(args); } export class ManifestJsonArgument extends args.JsonArgument<any> {} export interface ExtensionArguments extends CoreArguments { accounts: args.ArrayArgument; branch: args.StringArgument; bypassValidation: args.BooleanArgument; description: args.StringArgument; displayName: args.StringArgument; extensionId: args.StringArgument; extensionName: args.StringArgument; json5: args.BooleanArgument; locRoot: args.ExistingDirectoriesArgument; manifestJs: args.ReadableFilePathsArgument; env: args.ArrayArgument; manifestGlobs: args.ArrayArgument; manifests: args.ArrayArgument; metadataOnly: args.BooleanArgument; noDownload: args.BooleanArgument; noWaitValidation: args.BooleanArgument; npmPath: args.StringArgument; outputPath: args.StringArgument; override: ManifestJsonArgument; overridesFile: args.ReadableFilePathsArgument; path: args.FilePathsArgument; publisher: args.StringArgument; revVersion: args.BooleanArgument; samples: args.StringArgument; shareWith: args.ArrayArgument; unshareWith: args.ArrayArgument; version: args.StringArgument; vsix: args.ReadableFilePathsArgument; zipUri: args.StringArgument; } export class ExtensionBase<T> extends TfCommand<ExtensionArguments, T> { protected description = "Commands to package, publish, and manage Extensions for Azure DevOps Services."; protected serverCommand = false; constructor(passedArgs: string[]) { super(passedArgs); } protected getHelpArgs(): string[] { return []; } protected setCommandArgs(): void { super.setCommandArgs(); this.registerCommandArgument( "extensionId", "Extension ID", "Use this as the extension ID instead of what is specified in the manifest.", args.StringArgument, ); this.registerCommandArgument( "publisher", "Publisher name", "Use this as the publisher ID instead of what is specified in the manifest.", args.StringArgument, ); this.registerCommandArgument( "manifestJs", "Manifest JS file", "A manifest in the form of a JS file with an exported function that can be called by node and will return the manifest JSON object.", args.ReadableFilePathsArgument, null, ); this.registerCommandArgument( "env", "Manifest JS environment", "Environment variables passed to the Manifest JS function.", args.ArrayArgument, null, ); this.registerCommandArgument( "manifests", "Manifests", "List of individual manifest files (space separated).", args.ArrayArgument, "vss-extension.json", ); this.registerCommandArgument( "manifestGlobs", "Manifest globs", "List of globs to find manifests (space separated).", args.ArrayArgument, null, ); this.registerCommandArgument( "json5", "Extended JSON", "Support extended JSON (aka JSON 5) for comments, unquoted strings, dangling commas, etc.", args.BooleanArgument, "false" ); this.registerCommandArgument("outputPath", "Output path", "Path to write the VSIX.", args.StringArgument, "{auto}"); this.registerCommandArgument( "override", "Overrides JSON", "JSON string which is merged into the manifests, overriding any values.", ManifestJsonArgument, "{}", ); this.registerCommandArgument( "overridesFile", "Overrides JSON file", "Path to a JSON file with overrides. This partial manifest will always take precedence over any values in the manifests.", args.ReadableFilePathsArgument, null, ); this.registerCommandArgument( "shareWith", "Share with", "List of Azure DevOps organization(s) with which to share the extension (space separated).", args.ArrayArgument, null, ); this.registerCommandArgument( "unshareWith", "Un-share with", "List of Azure DevOps organization(s) with which to un-share the extension (space separated).", args.ArrayArgument, null, ); this.registerCommandArgument( "vsix", "VSIX path", "Path to an existing VSIX (to publish or query for).", args.ReadableFilePathsArgument, ); this.registerCommandArgument("bypassValidation", "Bypass local validation", null, args.BooleanArgument, "false"); this.registerCommandArgument( "locRoot", "Localization root", "Root of localization hierarchy (see README for more info).", args.ExistingDirectoriesArgument, null, ); this.registerCommandArgument("displayName", "Display name", null, args.StringArgument); this.registerCommandArgument("description", "Description", "Description of the Publisher.", args.StringArgument); this.registerCommandArgument( "revVersion", "Rev version", "Rev the patch-version of the extension and save the result.", args.BooleanArgument, "false", ); this.registerCommandArgument( "noWaitValidation", "Wait for validation?", "Don't block command for extension validation.", args.BooleanArgument, "false", ); this.registerCommandArgument( "metadataOnly", "Metadata only", "Only copy metadata to the path specified and do not package the extension", args.BooleanArgument, "false", true, // undocumented ); } protected getMergeSettings(): Promise<MergeSettings> { return Promise.all([ this.commandArgs.root.val(), this.commandArgs.locRoot.val(), this.commandArgs.manifestJs.val().then(files => files && files.length ? files[0] : null), this.commandArgs.env.val(), this.commandArgs.manifests.val(), this.commandArgs.manifestGlobs.val(), this.commandArgs.override.val(), this.commandArgs.overridesFile.val(), this.commandArgs.revVersion.val(), this.commandArgs.bypassValidation.val(), this.commandArgs.publisher.val(true), this.commandArgs.extensionId.val(true), this.commandArgs.json5.val(true), ]).then<MergeSettings>(values => { const [ root, locRoot, manifestJs, env, manifests, manifestGlob, override, overridesFile, revVersion, bypassValidation, publisher, extensionId, json5, ] = values; if (publisher) { _.set(override, "publisher", publisher); } if (extensionId) { _.set(override, "extensionid", extensionId); } let overrideFileContent = Promise.resolve(""); if (overridesFile && overridesFile.length > 0) { overrideFileContent = promisify(readFile)(overridesFile[0], "utf8"); } return overrideFileContent.then(contentStr => { let content = contentStr; if (content === "") { content = "{}"; if (overridesFile && overridesFile.length > 0) { trace.warn("Overrides file was empty. No overrides will be imported from " + overridesFile[0]); } } let mergedOverrides = {}; let contentJSON = {}; try { contentJSON = json5 ? jju.parse(content) : JSON.parse(content); } catch (e) { throw new Error("Could not parse contents of " + overridesFile[0] + " as JSON. \n"); } contentJSON["__origin"] = overridesFile ? overridesFile[0] : path.join(root[0], "_override.json"); _.merge(mergedOverrides, contentJSON, override); return { root: root[0], locRoot: locRoot && locRoot[0], manifestJs: manifestJs, env: env, manifests: manifests, manifestGlobs: manifestGlob, overrides: mergedOverrides, bypassValidation: bypassValidation, revVersion: revVersion, json5: json5, }; }); }); } protected getPackageSettings(): Promise<PackageSettings> { return Promise.all([ this.commandArgs.outputPath.val(), this.commandArgs.locRoot.val(), this.commandArgs.metadataOnly.val(), ]).then(values => { const [outputPath, locRoot, metadataOnly] = values; return { outputPath: outputPath as string, locRoot: locRoot && locRoot[0], metadataOnly: metadataOnly, }; }); } protected identifyExtension(): Promise<CoreExtInfo> { return this.commandArgs.vsix.val(true).then(result => { let vsixPath = _.isArray(result) ? result[0] : null; let infoPromise: Promise<CoreExtInfo>; if (!vsixPath) { infoPromise = Promise.all([this.commandArgs.publisher.val(), this.commandArgs.extensionId.val()]).then(values => { const [publisher, extensionId] = values; return GalleryBase.getExtInfo({ extensionId: extensionId, publisher: publisher }); }); } else { infoPromise = Promise.all([this.commandArgs.publisher.val(true), this.commandArgs.extensionId.val(true)]).then( values => { const [publisher, extensionId] = values; return GalleryBase.getExtInfo({ vsixPath: vsixPath, publisher: publisher, extensionId: extensionId }); }, ); } return infoPromise; }); } protected getPublishSettings(): Promise<PublishSettings> { return Promise.all<any>([ this.commandArgs.serviceUrl.val(), this.commandArgs.vsix.val(true), this.commandArgs.publisher.val(true), this.commandArgs.extensionId.val(true), this.commandArgs.shareWith.val(), this.commandArgs.noWaitValidation.val(), ]).then<PublishSettings>(values => { const [marketUrl, vsix, publisher, extensionId, shareWith, noWaitValidation] = values; let vsixPath: string = _.isArray<string>(vsix) ? vsix[0] : null; return { galleryUrl: marketUrl, vsixPath: vsixPath, publisher: publisher, extensionId: extensionId, shareWith: shareWith, noWaitValidation: noWaitValidation, }; }); } public exec(cmd?: any): Promise<any> { return this.getHelp(cmd); } /**** TEMPORARY until Marketplace fixes getResourceArea ****/ protected async getGalleryApi() { const handler = await this.getCredentials(this.webApi.serverUrl, false); return new GalleryApi(this.webApi.serverUrl, [handler]); // await this.webApi.getGalleryApi(this.webApi.serverUrl); } /**** TEMPORARY until Marketplace fixes getResourceArea ****/ public static async getMarketplaceUrl(): Promise<string[]> { trace.debug("getMarketplaceUrl"); const url = "https://app.vssps.visualstudio.com/_apis/resourceareas/69D21C00-F135-441B-B5CE-3626378E0819"; const response = await new Promise<string>((resolve, reject) => { https .get(url, resp => { let data = ""; resp.on("data", chunk => { data += chunk; }); resp.on("end", () => { resolve(data); }); }) .on("error", err => { reject(err); }); }); const resourceArea = JSON.parse(response); return [resourceArea["locationUrl"]]; } }
the_stack
import React from 'react'; import * as pc from 'playcanvas/build/playcanvas.js'; import Example from '../../app/example'; import { AssetLoader } from '../../app/helpers/loader'; // @ts-ignore: library file import import Panel from '@playcanvas/pcui/Panel/component'; // @ts-ignore: library file import import SliderInput from '@playcanvas/pcui/SliderInput/component'; // @ts-ignore: library file import import LabelGroup from '@playcanvas/pcui/LabelGroup/component'; // @ts-ignore: library file import import Label from '@playcanvas/pcui/Label/component'; // @ts-ignore: library file import import BooleanInput from '@playcanvas/pcui/BooleanInput/component'; // @ts-ignore: library file import import BindingTwoWay from '@playcanvas/pcui/BindingTwoWay'; // @ts-ignore: library file import import { Observer } from '@playcanvas/observer'; class LightsBakedAOExample extends Example { static CATEGORY = 'Graphics'; static NAME = 'Lights Baked AO'; load() { return <> <AssetLoader name='cubemap' type='cubemap' url='static/assets/cubemaps/helipad.dds' data={{ type: pc.TEXTURETYPE_RGBM }}/> <AssetLoader name='house' type='container' url='static/assets/models/house.glb' /> <AssetLoader name='script' type='script' url='static/scripts/camera/orbit-camera.js' /> </>; } // @ts-ignore: override class function controls(data: Observer) { return <> <Panel headerText='Lightmap Filter Settings'> <LabelGroup text='enable'> <BooleanInput type='toggle' binding={new BindingTwoWay()} link={{ observer: data, path: 'data.settings.lightmapFilterEnabled' }} value={data.get('data.settings.lightmapFilterEnabled')}/> </LabelGroup> <LabelGroup text='range'> <SliderInput binding={new BindingTwoWay()} link={{ observer: data, path: 'data.settings.lightmapFilterRange' }} value={data.get('data.settings.lightmapFilterRange')} min = {1} max = {20} precision = {0}/> </LabelGroup> <LabelGroup text='smoothness'> <SliderInput binding={new BindingTwoWay()} link={{ observer: data, path: 'data.settings.lightmapFilterSmoothness' }} value={data.get('data.settings.lightmapFilterSmoothness')} min = {0.1} max = {2} precision = {1}/> </LabelGroup> </Panel> <Panel headerText='Ambient light'> <LabelGroup text='bake'> <BooleanInput type='toggle' binding={new BindingTwoWay()} link={{ observer: data, path: 'data.ambient.ambientBake' }} value={data.get('data.ambient.ambientBake')}/> </LabelGroup> <LabelGroup text='cubemap'> <BooleanInput type='toggle' binding={new BindingTwoWay()} link={{ observer: data, path: 'data.ambient.cubemap' }} value={data.get('data.ambient.cubemap')}/> </LabelGroup> <LabelGroup text='hemisphere'> <BooleanInput type='toggle' binding={new BindingTwoWay()} link={{ observer: data, path: 'data.ambient.hemisphere' }} value={data.get('data.ambient.hemisphere')}/> </LabelGroup> <LabelGroup text='samples'> <SliderInput binding={new BindingTwoWay()} link={{ observer: data, path: 'data.ambient.ambientBakeNumSamples' }} value={data.get('data.ambient.ambientBakeNumSamples')} max={64} precision={0}/> </LabelGroup> <LabelGroup text='contrast'> <SliderInput binding={new BindingTwoWay()} link={{ observer: data, path: 'data.ambient.ambientBakeOcclusionContrast' }} value={data.get('data.ambient.ambientBakeOcclusionContrast')} min = {-1} max={1} precision={1}/> </LabelGroup> <LabelGroup text='brightness'> <SliderInput binding={new BindingTwoWay()} link={{ observer: data, path: 'data.ambient.ambientBakeOcclusionBrightness' }} value={data.get('data.ambient.ambientBakeOcclusionBrightness')} min = {-1} max={1} precision={1}/> </LabelGroup> </Panel> <Panel headerText='Directional light'> <LabelGroup text='enable'> <BooleanInput type='toggle' binding={new BindingTwoWay()} link={{ observer: data, path: 'data.directional.enabled' }} value={data.get('data.directional.enabled')}/> </LabelGroup> <LabelGroup text='bake'> <BooleanInput type='toggle' binding={new BindingTwoWay()} link={{ observer: data, path: 'data.directional.bake' }} value={data.get('data.directional.bake')}/> </LabelGroup> <LabelGroup text='samples'> <SliderInput binding={new BindingTwoWay()} link={{ observer: data, path: 'data.directional.bakeNumSamples' }} value={data.get('data.directional.bakeNumSamples')} max={64} precision={0}/> </LabelGroup> <LabelGroup text='area'> <SliderInput binding={new BindingTwoWay()} link={{ observer: data, path: 'data.directional.bakeArea' }} value={data.get('data.directional.bakeArea')} max={40} precision={0}/> </LabelGroup> </Panel> <Panel headerText='Other lights'> <LabelGroup text='enable'> <BooleanInput type='toggle' binding={new BindingTwoWay()} link={{ observer: data, path: 'data.other.enabled' }} value={data.get('data.other.enabled')}/> </LabelGroup> </Panel> <Panel headerText='Bake stats'> <LabelGroup text='duration'> <Label binding={new BindingTwoWay()} link={{ observer: data, path: 'data.stats.duration' }} value={data.get('data.stats.duration')}/> </LabelGroup> </Panel> </>; } // @ts-ignore: override class function example(canvas: HTMLCanvasElement, assets: any, data: any): void { // Create the app and start the update loop const app = new pc.Application(canvas, { mouse: new pc.Mouse(document.body), touch: new pc.TouchDevice(document.body) }); app.start(); // Set the canvas to fill the window and automatically change resolution to be the same as the canvas size app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW); app.setCanvasResolution(pc.RESOLUTION_AUTO); // setup skydome - this is the main source of ambient light app.scene.skyboxMip = 3; app.scene.skyboxIntensity = 1.5; app.scene.setSkybox(assets.cubemap.resources); // if skydome cubemap is disabled using HUD, a constant ambient color is used instead app.scene.ambientLight = new pc.Color(0.1, 0.3, 0.4); // instantiate the house model, which has unwrapped texture coordinates for lightmap in UV1 const house = assets.house.resource.instantiateRenderEntity(); house.setLocalScale(100, 100, 100); app.root.addChild(house); // change its materials to lightmapping const renders: Array<pc.RenderComponent> = house.findComponents("render"); renders.forEach((render) => { render.castShadows = true; render.castShadowsLightmap = true; render.lightmapped = true; }); // directional light const lightDirectional = new pc.Entity("Directional"); lightDirectional.addComponent("light", { type: "directional", affectDynamic: true, affectLightmapped: true, castShadows: true, normalOffsetBias: 0.05, shadowBias: 0.2, shadowDistance: 100, shadowResolution: 2048, shadowType: pc.SHADOW_PCF3, color: new pc.Color(0.7, 0.7, 0.5), intensity: 1.2 }); app.root.addChild(lightDirectional); lightDirectional.setLocalEulerAngles(-55, 0, -30); // Create an entity with a omni light component that is configured as a baked light const lightOmni = new pc.Entity("Omni"); lightOmni.addComponent("light", { type: "omni", affectDynamic: false, affectLightmapped: true, bake: true, castShadows: true, normalOffsetBias: 0.05, shadowBias: 0.2, shadowDistance: 50, shadowResolution: 512, shadowType: pc.SHADOW_PCF3, color: pc.Color.YELLOW, range: 10, intensity: 0.7 }); lightOmni.setLocalPosition(-4, 10, 5); app.root.addChild(lightOmni); // Create an entity with a spot light component that is configured as a baked light const lightSpot = new pc.Entity("Spot"); lightSpot.addComponent("light", { type: "spot", affectDynamic: false, affectLightmapped: true, bake: true, castShadows: true, normalOffsetBias: 0.05, shadowBias: 0.2, shadowDistance: 50, shadowResolution: 512, shadowType: pc.SHADOW_PCF3, color: pc.Color.RED, range: 10, intensity: 2 }); lightSpot.setLocalPosition(-5, 10, -7.5); app.root.addChild(lightSpot); // Create an entity with a camera component const camera = new pc.Entity(); camera.addComponent("camera", { clearColor: new pc.Color(0.4, 0.45, 0.5), farClip: 100, nearClip: 1 }); camera.setLocalPosition(40, 20, 40); // add orbit camera script with a mouse and a touch support camera.addComponent("script"); camera.script.create("orbitCamera", { attributes: { inertiaFactor: 0.2, focusEntity: house, distanceMax: 60 } }); camera.script.create("orbitCameraInputMouse"); camera.script.create("orbitCameraInputTouch"); app.root.addChild(camera); // lightmap baking properties const bakeType = pc.BAKE_COLOR; app.scene.lightmapMode = bakeType; app.scene.lightmapMaxResolution = 1024; // multiplier for lightmap resolution app.scene.lightmapSizeMultiplier = 512; // bake when settings are changed only let needBake = false; // handle data changes from HUD to modify baking properties data.on('*:set', (path: string, value: any) => { let bakeSettingChanged = true; const pathArray = path.split('.'); // ambient light if (pathArray[1] === 'ambient') { if (pathArray[2] === 'cubemap') { // enable / disable cubemap app.scene.setSkybox(value ? assets.cubemap.resources : null); } else if (pathArray[2] === 'hemisphere') { // switch between smaller upper hemosphere and full sphere app.scene.ambientBakeSpherePart = value ? 0.4 : 1; } else { // all other values are set directly on the scene // @ts-ignore engine-tsd app.scene[pathArray[2]] = value; } } else if (pathArray[1] === 'directional') { // @ts-ignore engine-tsd lightDirectional.light[pathArray[2]] = value; } else if (pathArray[1] === 'settings') { // @ts-ignore engine-tsd app.scene[pathArray[2]] = value; } else if (pathArray[1] === 'other') { // @ts-ignore engine-tsd lightOmni.light[pathArray[2]] = value; // @ts-ignore engine-tsd lightSpot.light[pathArray[2]] = value; } else { // don't rebake if stats change bakeSettingChanged = false; } // trigger bake on the next frame if relevant settings were changes needBake ||= bakeSettingChanged; }); // bake properties connected to the HUD data.set('data', { settings: { lightmapFilterEnabled: true, lightmapFilterRange: 10, lightmapFilterSmoothness: 0.2 }, ambient: { ambientBake: true, cubemap: true, hemisphere: true, ambientBakeNumSamples: 20, ambientBakeOcclusionContrast: 0, ambientBakeOcclusionBrightness: 0.4 }, directional: { enabled: true, bake: true, bakeNumSamples: 15, bakeArea: 10 }, other: { enabled: true }, stats: { duration: '' } }); // Set an update function on the app's update event app.on("update", function (dt) { // bake lightmaps when HUD properties change if (needBake) { needBake = false; app.lightmapper.bake(null, bakeType); // update stats with the bake duration // @ts-ignore engine-tsd data.set('data.stats.duration', app.lightmapper.stats.totalRenderTime.toFixed(1) + 'ms'); } }); } } export default LightsBakedAOExample;
the_stack
import { applyPatches } from 'immer'; import { Middleware } from 'redux'; import { injectable, createContainer, state, createStore, action, getStagedState, enablePatchesKey, applyMiddleware, } from '../..'; describe('@action', () => { test('base', () => { @injectable() class Counter { @state count = 0; @action increase() { this.count += 1; } } const ServiceIdentifiers = new Map(); const modules = [Counter]; const container = createContainer({ ServiceIdentifiers, modules, options: { defaultScope: 'Singleton', }, }); const counter = container.get(Counter); const store = createStore( modules, container, ServiceIdentifiers, new Set(), (...args: any[]) => {}, { middleware: [], beforeCombineRootReducers: [], afterCombineRootReducers: [], enhancer: [], preloadedStateHandler: [], afterCreateStore: [], provider: [], } ); counter.increase(); expect(counter.count).toBe(1); expect((counter as any)[enablePatchesKey]).toBe(false); expect(Object.values(store.getState())).toEqual([{ count: 1 }]); }); test('enable `autoFreeze` in devOptions', () => { @injectable({ name: 'counter', }) class Counter { @state count = 0; @state sum = { count: 0 }; @action increase() { this.sum.count += 1; } increase1() { this.sum.count += 1; } increase2() { this.count += 1; } } const ServiceIdentifiers = new Map(); const modules = [Counter]; const container = createContainer({ ServiceIdentifiers, modules, options: { defaultScope: 'Singleton', }, }); const counter = container.get(Counter); const store = createStore( modules, container, ServiceIdentifiers, new Set(), (...args: any[]) => { // }, { middleware: [], beforeCombineRootReducers: [], afterCombineRootReducers: [], enhancer: [], preloadedStateHandler: [], afterCreateStore: [], provider: [], }, undefined, { autoFreeze: true } ); expect(() => { store.getState().counter.sum.count = 1; }).toThrowError(/Cannot assign to read only property/); counter.increase(); for (const fn of [ () => { store.getState().counter.sum.count = 1; }, () => counter.increase1(), () => counter.increase2(), ]) { expect(fn).toThrowError(/Cannot assign to read only property/); } }); test('inherited module with stagedState about more effects', () => { @injectable({ name: 'foo0', }) class Foo0 { @state count0 = 1; @state count1 = 1; @action increase() { this.count0 += 1; } @action decrease() { this.count0 -= 1; } @action decrease1() { this.count0 -= 1; } } @injectable({ name: 'foo', }) class Foo extends Foo0 { count = 1; add(count: number) { this.count += count; } @action increase() { // inheritance super.increase(); // change state this.count0 += 1; // call other action function this.increase1(); // call unwrapped `@action` function this.add(this.count); } @action increase1() { this.count1 += 1; } @action decrease() { super.decrease(); this.count0 -= 1; } decrease1() { super.decrease1(); } } @injectable() class FooBar { constructor(public foo: Foo, public foo0: Foo0) {} } const ServiceIdentifiers = new Map(); const modules = [FooBar]; const container = createContainer({ ServiceIdentifiers, modules, options: { defaultScope: 'Singleton', }, }); const fooBar = container.get(FooBar); const store = createStore( modules, container, ServiceIdentifiers, new Set(), (...args: any[]) => { // }, { middleware: [], beforeCombineRootReducers: [], afterCombineRootReducers: [], enhancer: [], preloadedStateHandler: [], afterCreateStore: [], provider: [], } ); const subscribe = jest.fn(); store.subscribe(subscribe); fooBar.foo.increase(); expect(fooBar.foo.count0).toBe(3); expect(fooBar.foo.count1).toBe(2); expect(fooBar.foo.count).toBe(2); fooBar.foo0.increase(); expect(fooBar.foo.count0).toBe(3); expect(fooBar.foo.count1).toBe(2); expect(fooBar.foo.count).toBe(2); // merge the multi-actions changed states as one redux dispatch. expect(subscribe.mock.calls.length).toBe(2); // inheritance fooBar.foo.decrease(); expect(fooBar.foo.count0).toBe(1); fooBar.foo.decrease1(); expect(fooBar.foo.count0).toBe(0); }); test('across module changing state', () => { @injectable() class Foo { @state textList: string[] = []; @action addText(text: string) { this.textList.push(text); } } @injectable() class Counter { constructor(public foo: Foo) {} @state count = 0; @action increase() { this.foo.addText(`test${this.count}`); this.count += 1; this.foo.addText(`test${this.count}`); this.count += 1; this.foo.addText(`test${this.count}`); } } const ServiceIdentifiers = new Map(); const modules = [Counter]; const container = createContainer({ ServiceIdentifiers, modules, options: { defaultScope: 'Singleton', }, }); const counter = container.get(Counter); const store = createStore( modules, container, ServiceIdentifiers, new Set(), (...args: any[]) => { // }, { middleware: [], beforeCombineRootReducers: [], afterCombineRootReducers: [], enhancer: [], preloadedStateHandler: [], afterCreateStore: [], provider: [], } ); const subscribeFn = jest.fn(); store.subscribe(subscribeFn); counter.increase(); expect(subscribeFn.mock.calls.length).toBe(1); expect(counter.count).toEqual(2); expect(counter.foo.textList).toEqual(['test0', 'test1', 'test2']); }); test('across module changing state with error', () => { @injectable({ name: 'foo', }) class Foo { @state list: number[] = []; @action addItem(num: number) { if (num === 1) { // eslint-disable-next-line no-throw-literal throw 'something error'; } else { this.list.push(num); } } } @injectable({ name: 'counter', }) class Counter { constructor(public foo: Foo) {} @state count = 0; @action increase() { this.foo.addItem(this.count); this.count += 1; } @action increase1() { this.foo.addItem(this.count + 1); this.count += 1; } } const ServiceIdentifiers = new Map(); const modules = [Counter]; const container = createContainer({ ServiceIdentifiers, modules, options: { defaultScope: 'Singleton', }, }); const counter = container.get(Counter); const store = createStore( modules, container, ServiceIdentifiers, new Set(), (...args: any[]) => { // }, { middleware: [], beforeCombineRootReducers: [], afterCombineRootReducers: [], enhancer: [], preloadedStateHandler: [], afterCreateStore: [], provider: [], } ); const subscribeFn = jest.fn(); store.subscribe(subscribeFn); counter.increase(); expect(subscribeFn.mock.calls.length).toBe(1); expect(() => { counter.increase(); }).toThrowError('something error'); expect(getStagedState()).toBeUndefined(); expect(subscribeFn.mock.calls.length).toBe(1); counter.increase1(); expect(subscribeFn.mock.calls.length).toBe(2); expect(counter.count).toBe(2); expect(counter.foo.list).toEqual([0, 2]); expect(store.getState()).toEqual({ counter: { count: 2 }, foo: { list: [0, 2] }, }); }); test('base with `enablePatches`', () => { interface Todo { text: string; } @injectable({ name: 'todo', }) class TodoList { @state list: Todo[] = [ { text: 'foo', }, ]; @action add(text: string) { this.list.slice(-1)[0].text = text; this.list.push({ text }); } } const actionFn = jest.fn(); const middleware: Middleware = (store) => (next) => (_action) => { actionFn(_action); return next(_action); }; const ServiceIdentifiers = new Map(); const modules = [TodoList, applyMiddleware(middleware)]; const container = createContainer({ ServiceIdentifiers, modules, options: { defaultScope: 'Singleton', }, }); const todoList = container.get(TodoList); const store = createStore( modules, container, ServiceIdentifiers, new Set(), (...args: any[]) => { // }, { middleware: [], beforeCombineRootReducers: [], afterCombineRootReducers: [], enhancer: [], preloadedStateHandler: [], afterCreateStore: [], provider: [], }, undefined, { enablePatches: true, } ); const originalTodoState = store.getState(); expect(Object.values(store.getState())).toEqual([ { list: [{ text: 'foo' }] }, ]); expect(actionFn.mock.calls.length).toBe(0); todoList.add('test'); expect(Object.values(store.getState())).toEqual([ { list: [{ text: 'test' }, { text: 'test' }] }, ]); expect(actionFn.mock.calls.length).toBe(1); expect(actionFn.mock.calls[0][0]._patches).toEqual([ { op: 'replace', path: ['todo', 'list', 0, 'text'], value: 'test', }, { op: 'add', path: ['todo', 'list', 1], value: { text: 'test', }, }, ]); expect(actionFn.mock.calls[0][0]._inversePatches).toEqual([ { op: 'replace', path: ['todo', 'list', 0, 'text'], value: 'foo', }, { op: 'replace', path: ['todo', 'list', 'length'], value: 1, }, ]); expect( applyPatches(originalTodoState, actionFn.mock.calls[0][0]._patches) ).toEqual(store.getState()); expect( applyPatches(originalTodoState, actionFn.mock.calls[0][0]._patches) === store.getState() ).toBe(false); expect( applyPatches(store.getState(), actionFn.mock.calls[0][0]._inversePatches) ).toEqual(originalTodoState); }); });
the_stack
import path from "path"; const binary = require("@mapbox/node-pre-gyp"); const binding_path = binary.find(path.resolve(path.join(__dirname,"../package.json"))); const maluuba: Maluuba = require(binding_path); /** * The exported classes for phonetic matching. * * @export * @interface Maluuba */ export interface Maluuba { EnPronunciation: EnPronunciationStatic; EnPronouncer: EnPronouncerConstructor; AcceleratedFuzzyMatcher : FuzzyMatcherConstructor; FuzzyMatcher : FuzzyMatcherConstructor; StringDistance : StringDistanceConstructor; EnPhoneticDistance: EnPhoneticDistanceConstructor; EnHybridDistance: EnHybridDistanceConstructor; }; /** * Factory methods to create {@link Speech.EnPronunciation} from other sources. * * @export * @interface EnPronunciationStatic */ export interface EnPronunciationStatic { /** * Constructs a {@link Speech.EnPronunciation} from an IPA string. E.g. (phonetic) "fənɛtɪk". * * @param {string} ipa The IPA string. * @returns {Speech.EnPronunciation} The English pronunciation. * @memberof EnPronunciationStatic */ fromIpa(ipa: string): Speech.EnPronunciation; /** * Constructs a {@link Speech.EnPronunciation} from an ARPABET string array. E.g. (phonetic) ["F","AH","N","EH","T","IH","K"]. * * @param {Array<string>} arpabet The ARPABET array. * @returns {Speech.EnPronunciation} The English pronunciation. * @memberof EnPronunciationStatic */ fromArpabet(arpabet: Array<string>): Speech.EnPronunciation; }; /** * Constructs an English pronouncer. * * @export * @class * @interface EnPronouncerConstructor */ export interface EnPronouncerConstructor { new(): Speech.EnPronouncer; }; /** * Constructs an English phonetic distance metric. * * @export * @class * @interface EnPhoneticDistanceConstructor */ export interface EnPhoneticDistanceConstructor { new(): Speech.Distance<Speech.EnPronunciation>; }; /** * Input object for __EnHybridDistance__. Hold the text and the pronunciation of that text. * * @export * @interface DistanceInput */ export interface DistanceInput { phrase: string; pronunciation: Speech.EnPronunciation; }; /** * Constructs a distance metric that weighs between an English phonetic distance and string distance. * * @export * @class * @interface EnHybridDistanceConstructor */ export interface EnHybridDistanceConstructor { /** * Create an English hybrid distance. * * @param {number} phoneticWeightPercentage Between 0 and 1. Weighting trade-off between the phonetic * distance and the lexical distance scores. 1 meaning 100% phonetic score and 0% lexical score. * @returns {(Speech.Distance<DistanceInput> & {readonly phoneticWeightPercentage: number})} * @memberof EnHybridDistanceConstructor */ new(phoneticWeightPercentage: number): Speech.Distance<DistanceInput> & {readonly phoneticWeightPercentage: number}; }; /** * Constructs a fuzzy matcher. * * @export * @class * @interface FuzzyMatcherConstructor */ export interface FuzzyMatcherConstructor { /** * * * @template Target The type of the object to match against. * @template Pronounceable The type of input for the distance function. * @template Extraction The type of query object. * @param {Array<Target>} targets The set of objects that will be matched against. The order of equal targets is not guaranteed to be preserved. * @param {(((a: Pronounceable, b: Pronounceable) => number) | Speech.Distance<Pronounceable>)} distance The distance function. * @param {(target: Target) => Extraction} [extract] A mapping of the input types to a type understood by the distance function. Note that Extraction == Pronounceable for the usual case. * @returns {Speech.FuzzyMatcher<Target, Extraction>} The fuzzy matcher instance. * @memberof FuzzyMatcherConstructor */ new<Target, Pronounceable, Extraction>( targets: Array<Target>, distance: ((a: Pronounceable, b: Pronounceable) => number) | Speech.Distance<Pronounceable>, extract?: (target: Target) => Extraction ): Speech.FuzzyMatcher<Target, Extraction>; }; /** * Constructs a string edit distance metric. * * @export * @class * @interface StringDistanceConstructor */ export interface StringDistanceConstructor { new(): Speech.Distance<string>; }; export namespace Speech { /** * Phone type (consonant or vowel). * * @export * @enum {number} */ export const enum PhoneType { CONSONANT, VOWEL, }; /** * Phonation (voice intensity). * * @export * @enum {number} */ export const enum Phonation { VOICELESS, BREATHY, SLACK, MODAL, STIFF, CREAKY, GLOTTAL_CLOSURE, }; /** * Place of articulation for consonants. * * @export * @enum {number} */ export const enum PlaceOfArticulation { BILABIAL, LABIODENTAL, DENTAL, ALVEOLAR, PALATO_ALVEOLAR, RETROFLEX, ALVEOLO_PALATAL, LABIAL_PALATAL, PALATAL, PALATAL_VELAR, LABIAL_VELAR, VELAR, UVULAR, PHARYNGEAL, EPIGLOTTAL, GLOTTAL, }; /** * Manner of articulation for consonants. * * @export * @enum {number} */ export const enum MannerOfArticulation { NASAL, PLOSIVE, SIBILANT_FRICATIVE, NON_SIBILANT_FRICATIVE, APPROXIMANT, FLAP, TRILL, LATERAL_FRICATIVE, LATERAL_APPROXIMANT, LATERAL_FLAP, CLICK, IMPLOSIVE, EJECTIVE, }; /** * Vowel height. * * @export * @enum {number} */ export const enum VowelHeight { CLOSE, NEAR_CLOSE, CLOSE_MID, MID, OPEN_MID, NEAR_OPEN, OPEN, }; /** * Horizontal vowel position. * * @export * @enum {number} */ export const enum VowelBackness { FRONT, NEAR_FRONT, CENTRAL, NEAR_BACK, BACK, }; /** * Vowel roundedness. * * @export * @enum {number} */ export const enum VowelRoundedness { UNROUNDED, LESS_ROUNDED, ROUNDED, MORE_ROUNDED, }; /** * A __phone__ is a unit of speech sound. * * @export * @interface Phone */ export interface Phone { readonly type: PhoneType; readonly phonation: Phonation; readonly place: PlaceOfArticulation; readonly manner: MannerOfArticulation; readonly height: VowelHeight; readonly backness: VowelBackness; readonly roundedness: VowelRoundedness; readonly isRhotic: boolean; readonly isSyllabic: boolean; }; /** * A matched element with its distance score. * * @export * @interface Match * @template T The element type. */ export interface Match<T> { readonly element: T; readonly distance: number; }; /** * A phonetic pronunciation by a general english speaker. * * @export * @interface EnPronunciation */ export interface EnPronunciation { readonly ipa: string; readonly phones: Array<Phone>; }; /** * Pronounces English texts. * * @export * @interface EnPronouncer */ export interface EnPronouncer { /** * Pronounce text. * * @param {string} phrase The text to pronounce. * @returns {EnPronunciation} The English Pronunciation. * @memberof EnPronouncer */ pronounce(phrase: string): EnPronunciation; }; export interface Distance<T> { distance(a: T, b: T): number; }; /** * A fuzzy matcher. The fuzziness it determined by the provided distance function. * * @export * @interface FuzzyMatcher * @template Target The type of the returned matched object. * @template Extraction The type of the query object. */ export interface FuzzyMatcher<Target, Extraction> { /** * @returns {boolean} true iff size === 0 * @memberof FuzzyMatcher */ empty(): boolean; /** * @returns {number} The number of targets constructed with. * @memberof FuzzyMatcher */ size(): number; /** * Find the nearest element. * * @param {Extraction} target The search target. * @returns {(Match<Target> | undefined)} The closest match to __target__, or __undefined__ if the initial __targets__ list was empty. * @memberof FuzzyMatcher */ nearest(target: Extraction): Match<Target> | undefined; /** * Find the nearest element. * * @param {Extraction} target The search target. * @param {number} threshold The maximum distance to a match. * @returns {(Match<Target> | undefined)} The closest match to __target__ within __threshold__, or __undefined__ if no match is found. * @memberof FuzzyMatcher */ nearestWithin(target: Extraction, threshold: number): Match<Target> | undefined; /** * Find the __k__ nearest elements. * * @param {Extraction} target The search target. * @param {number} k The maximum number of result to return. * @returns {Array<Match<Target>>} The __k__ nearest matches to __target__. * @memberof FuzzyMatcher */ kNearest(target: Extraction, k: number): Array<Match<Target>>; /** * Find the __k__ nearest elements. * * @param {Extraction} target The search target. * @param {number} k The maximum number of result to return. * @param {number} threshold The maximum distance to a match. * @returns {Array<Match<Target>>} The __k__ nearest matches to __target__ within __threshold__. * @memberof FuzzyMatcher */ kNearestWithin(target: Extraction, k: number, threshold: number): Array<Match<Target>>; }; } export const { EnPronouncer, EnPronunciation, EnPhoneticDistance, FuzzyMatcher, AcceleratedFuzzyMatcher, EnHybridDistance, StringDistance } = maluuba;
the_stack
import * as React from 'react' import { Button, Table, Row, Col, Icon, Dropdown, Card, Checkbox, Menu, Affix } from 'antd' import update from 'immutability-helper' import { PaginationProps } from 'antd/lib/pagination/Pagination' import { ValidationRule } from 'antd/lib/form/Form' import SearchField from './SearchField' import { TableRowSelection, ColumnProps } from 'antd/lib/table' export type ValidateError = { [fieldName: string]: { errors: { message: string, field: string }[] } } export type SearchInfo = { values: any, page: number, pageSize: number } export type SearchFunc<T = void> = (page: number, values?: object, clearPagination?: boolean) => Promise<T> export type SearchResponse<T> = { dataSource: T[], total: number } export type FieldRenderer = (payload?: object) => React.ReactNode export type RendererType = 'input' | 'select' | 'datePicker' | 'treeSelect' export type SearchField = { /** 条件名称 */ label: string, /** 条件别名,会作为 onSearch 时 values 的 key 名 */ name: string, /** 渲染的组件类型 */ type?: RendererType, /** 当不使用自带的组件类型时,可以自己写 renderer */ renderer?: FieldRenderer, /** antd 的表单验证规则 */ validationRule?: ValidationRule[], /** 初始值 */ initialValue?: any, /** 表单项的 span 值, 默认 6 */ span?: number, /** 传给渲染的组件的参数 */ payload?: SearchFieldPayload } export type SearchFieldPayload = { /** props that pass to the main component */ props?: object, [key: string]: any } export type RowAction = { label: string, children?: RowAction[], action?: (record) => void } export type Plugin = { colSpan?: number, renderer: (selectedRowKeys: string[], selectedRows: any[], clearSelectionCallback: () => void) => React.ReactNode } export type Expand = { title: string, dataIndex: string, render?: (text: any, record?: {}) => React.ReactNode } /** Your component's props */ export interface IDataTableProps { name?: string, initialColumns: ColumnProps<any>[], searchFields: SearchField[], rowActions?: RowAction[], enableListSelection?: boolean, plugins?: Plugin[], /** 表格行 key 的取值 */ rowKey: (record: any) => string, title?: React.ReactNode, searchBtnText?: string, clearBtnText?: string, listSelectionBtnText?: string, /** 最大的表单项显示数,当表单项超过此数值时,会自动出现 collapse 按钮 */ maxVisibleFieldCount?: number, pageSize?: number, /** handle form validate error */ onValidateFailed?: (err: ValidateError) => void, /** 页面加载完成后是否立即加载数据 */ loadDataImmediately?: boolean, /** 执行 search 动作,返回一个 AxiosPromis */ onSearch<T> (info: SearchInfo): Promise<SearchResponse<T>>, /** reject handler */ onError? (err): void, rowSelection?: TableRowSelection<any>, affixTarget?: () => HTMLElement, affixOffsetTop?: number, affixOffsetBottom?: number, initialExpands?: Expand[] } /** Your component's state */ export interface IDataTableState { columns: ColumnProps<any>[], data: any[], page: number, currentValues: object, pagination: PaginationProps, tableLoading: boolean, searchButtonLoading: boolean, selectedRowKeys: string[], selectedRows: any[] } const renderActions = (actions: RowAction[], record) => { return ( <span> {actions.map((action, i) => { if (action.children) { const menu = ( <Menu> {action.children.map(child => { const onClick = () => { child.action && child.action(record) } return ( <Menu.Item> <a onClick={onClick}>{child.label}</a> </Menu.Item> ) })} </Menu> ) return ( <Dropdown overlay={menu}> <a className='ant-dropdown-link'> {action.label} <Icon type='down' /> </a> </Dropdown> ) } else { const onClick = () => { action.action && action.action(record) } return [ <a onClick={onClick}>{action.label}</a>, i === 0 && <span className='ant-divider' /> ] } })} </span> ) } /** Your component */ export class DataTable extends React.Component<IDataTableProps, IDataTableState> { static storageKey = 'antd-data-table' static defaultProps = { pageSize: 10, searchBtnText: 'Search', clearBtnText: 'Clear', listSelectionBtnText: 'List selection' } readonly actionsColumn = this.props.rowActions && { key: 'actions', title: 'Actions', render: (record) => { return renderActions(this.props.rowActions as RowAction[], record) } } as ColumnProps<any> readonly shouldShowTableTitle = this.props.title || this.props.enableListSelection readonly initialColumns = this.actionsColumn ? [...this.props.initialColumns, this.actionsColumn] : this.props.initialColumns readonly visibleColumnKeys = localStorage.getItem(`${DataTable.storageKey}-${this.props.name}-columnIds`) readonly visibleColumns = (this.props.enableListSelection === true) && this.visibleColumnKeys ? this.initialColumns.filter(column => (this.visibleColumnKeys as string).indexOf(column.key as string) !== -1) : this.initialColumns state = { columns: [] = this.visibleColumns, data: [], page: 1, pagination: { pageSize: this.props.pageSize } as PaginationProps, currentValues: {}, tableLoading: false, searchButtonLoading: false, selectedRows: [], selectedRowKeys: [] } private filterPannel = (<Card bodyStyle={{ padding: '1em', width: '12em' }}> {this.initialColumns.map(column => { const isSelected = this.state.columns.find(c => c.key === column.key) !== undefined const onChange = (e) => { if (e.target.checked) { this.showColumn(column.key) } else { this.hideColumn(column.key) } } return ( <p key={column.key} style={{ marginTop: '.5em', marginBottom: '.5em' }}> <Checkbox defaultChecked={isSelected} onChange={onChange}>{column.title as any}</Checkbox> </p> ) })} </Card>) constructor (props) { super(props) if (this.props.enableListSelection && !this.props.name) { console.warn('`name` is required while `enableListSelection` is true!') } } fetch: SearchFunc = async (page: number, values: object = this.state.currentValues, clearPagination: boolean = false) => { const { onError } = this.props this.applyValues(values, async () => { try { // 这里先简单认为 clearPagination 为 true 就是从 Search button 触发的 fetch clearPagination && this.startSearchButtonLoading() this.startTableLoading() const pager = { ...this.state.pagination } const response = await this.props.onSearch({ page: page, // pageSize 有 default pageSize: this.props.pageSize as number, values: this.state.currentValues }) pager.total = response.total this.setState({ pagination: pager }) this.applyData(response.dataSource) clearPagination && this.clearPagination() } catch (e) { onError && onError(e) } finally { clearPagination && this.stopSearchButtonLoading() this.stopTableLoading() } }) } private saveVisibleColumnKeysToStorage = (columns: ColumnProps<any>[]) => { localStorage.setItem(`${DataTable.storageKey}-${this.props.name}-columnIds`, columns.map(column => column.key).join(',')) } private applyData = (data: any[]) => { this.setState({ data }) } private applyValues = (values, cb) => { this.setState({ currentValues: values }, cb) } private clearPagination = () => { const pager = { ...this.state.pagination } pager.current = 1 this.setState({ pagination: pager }) } private handleChange = (pagination: PaginationProps) => { const pager = { ...this.state.pagination } pager.current = pagination.current this.setState({ pagination: pager }) this.fetch(pager.current || 1) // tslint:disable-line } private hideColumn = (key?: string | number) => { this.state.columns.forEach((column, i) => { if (column.key === key) { const columns = update(this.state.columns, { $splice: [[i, 1]] }) as any this.setState({ columns }, () => this.saveVisibleColumnKeysToStorage(columns)) } }) } private clearSelection = () => { this.setState({ selectedRows: [], selectedRowKeys: [] }) } private showColumn = (key?: string | number) => { this.initialColumns.forEach((column, i) => { if (column.key === key) { const columns = update(this.state.columns, { $splice: [[i, 0, column]] }) as any this.setState({ columns }, () => this.saveVisibleColumnKeysToStorage(columns)) } }) } private startTableLoading = () => { this.setState({ tableLoading: true }) } private stopTableLoading = () => { this.setState({ tableLoading: false }) } private startSearchButtonLoading = () => { this.setState({ searchButtonLoading: true }) } private stopSearchButtonLoading = () => { this.setState({ searchButtonLoading: false }) } private tableTitle = (currentPageData) => { if (this.shouldShowTableTitle) { return ( <Row type='flex'> <Col span={12}> {this.props.title} </Col> <Col span={12}> <Row type='flex' justify='end'> <Col> {this.props.enableListSelection && ( <Dropdown overlay={this.filterPannel} trigger={['click']}> <Button size='small'>{this.props.listSelectionBtnText}</Button> </Dropdown> )} </Col> </Row> </Col> </Row> ) } } private accordingly = (dataIndex: string, record: Object) => { const indexArr = dataIndex.split('.') const key = indexArr.shift() || '' const index = indexArr.join('.') const subData = record[key] || {} const value = record[key] || '' return indexArr.length ? this.accordingly(index, subData) : value } private renderExpandedRow = (record) => { const { initialExpands } = this.props const expandTitleStyle: Object = { textAlign: 'right', color: 'rgba(0, 0, 0, 0.85)', fontWeight: 500 } if (initialExpands) { return ( <Row gutter={16}> {initialExpands.map(col => { const value = this.accordingly(col.dataIndex, record) return ( <Col sm={12} md={8} xl={6}> <Row gutter={8}> <Col span={8} style={expandTitleStyle}>{col.title}</Col> <Col span={16}>{col.render ? col.render(value, record) : value}</Col> </Row> </Col> ) })} </Row> ) } } render () { const rowSelection = Object.assign({}, { selectedRowKeys: this.state.selectedRowKeys, onChange: (selectedRowKeys, selectedRows) => { this.setState({ selectedRowKeys, selectedRows }) } }, this.props.rowSelection) const ActionPanel = this.props.plugins && ( <Row className='operationpannel' gutter={16} type='flex' style={{ paddingBottom: '1em' }}> {(this.props.plugins).map(plugin => { return ( <Col span={plugin.colSpan}> {plugin.renderer(this.state.selectedRowKeys, this.state.selectedRows, this.clearSelection)} </Col> ) })} </Row> ) return ( <div> <div> <SearchField {...this.props} fetch={this.fetch} btnLoading={this.state.searchButtonLoading} /> </div> <div> {this.props.affixTarget ? ( <Affix target={this.props.affixTarget} offsetBottom={this.props.affixOffsetBottom} offsetTop={this.props.affixOffsetTop} > {ActionPanel} </Affix> ) : ActionPanel} <Row> <Table bordered size='middle' {...this.shouldShowTableTitle && { title: this.tableTitle }} rowSelection={rowSelection} rowKey={this.props.rowKey} loading={this.state.tableLoading} columns={this.state.columns} dataSource={this.state.data} onChange={this.handleChange} pagination={this.state.pagination} expandedRowRender={this.props.initialExpands ? this.renderExpandedRow : undefined} /> </Row> </div> </div> ) } } /** Export as default */ export default DataTable
the_stack
const models = require('../../../../../db/mysqldb/index') import moment from 'moment' const { resClientJson } = require('../../../utils/resData') const Op = require('sequelize').Op const cheerio = require('cheerio') const clientWhere = require('../../../utils/clientWhere') const xss = require('xss') const config = require('../../../../../config') const lowdb = require('../../../../../db/lowdb/index') import { statusList, modelName, userMessageAction, modelAction, isFree, isOpen, isOpenInfo } from '../../../utils/constant' const { TimeNow, TimeDistance } = require('../../../utils/time') import userVirtual from '../../../common/userVirtual' import attention from '../../../common/attention' import useExperience from '../../../common/useExperience' import e from 'express' function getNoMarkupStr(markupStr: string) { /* markupStr 源码</> */ // console.log(markupStr); let noMarkupStr = markupStr /* 得到可视文本(不含图片),将&nbsp;&lt;&gt;转为空字符串和<和>显示,同时去掉了换行,文本单行显示 */ // console.log("1--S" + noMarkupStr + "E--"); noMarkupStr = noMarkupStr.replace(/(\r\n|\n|\r)/gm, '') /* 去掉可视文本中的换行,(没有用,上一步已经自动处理) */ // console.log("2--S" + noMarkupStr + "E--"); noMarkupStr = noMarkupStr.replace(/^\s+/g, '') /* 替换开始位置一个或多个空格为一个空字符串 */ // console.log("3--S" + noMarkupStr + "E--"); noMarkupStr = noMarkupStr.replace(/\s+$/g, '') /* 替换结束位置一个或多个空格为一个空字符串 */ // console.log("4--S" + noMarkupStr + "E--"); noMarkupStr = noMarkupStr.replace(/\s+/g, ' ') /* 替换中间位置一个或多个空格为一个空格 */ // console.log("5--S" + noMarkupStr + "E--"); return noMarkupStr } function isDigit(value: any) { var patrn = /^[0-9]*$/ if (patrn.exec(value) == null || value == '') { return false } else { return true } } function getSubStr(string: string) { let str = '' let len = 0 for (var i = 0; i < string.length; i++) { if (string[i].match(/[^\x00-\xff]/gi) != null) { len += 2 } else { len += 1 } if (len > 240) { /* 240为要截取的长度 */ str += '...' break } str += string[i] } return str } class Article { /** * 新建文章post提交 * @param {object} ctx 上下文对象 */ static async createArticle(req: any, res: any, next: any) { let reqData = req.body let { user = '' } = req let resultArticle: any = {} // 新建成功后的文章 try { if (!reqData.title) { throw new Error('请输入文章标题') } if (reqData.title.length > 150) { throw new Error('文章标题过长,请小于150个字符') } if (!reqData.content) { throw new Error('请输入文章内容') } if (reqData.source.length === 0 || reqData.source === null) { throw new Error('请选择文章来源类型') } if (!reqData.tag_ids) { throw new Error('请选择文章标签') } let date = new Date() let currDate = moment(date.setHours(date.getHours())).format( 'YYYY-MM-DD HH:mm:ss' ) if (Number(reqData.is_attachment) === isOpen.yes) { if (Number(reqData.is_free) !== isFree.free) { if (!reqData.pay_type) { throw new Error('请选择支付类型') } if (reqData.price < 0) { throw new Error('请请输入大于等于0的定价!') } if (reqData.price > 100) { throw new Error('当前定价不能超过100,后续等待管理员开放!') } if (!isDigit(reqData.price)) { throw new Error('请输入整数数字类型!') } } if (!reqData.attachment || reqData.attachment.length <= 0) { throw new Error('附件内容不能为空') } } if (new Date(currDate).getTime() < new Date(user.ban_dt).getTime()) { throw new Error( `当前用户因违规已被管理员禁用发布文章,时间到:${moment( user.ban_dt ).format('YYYY年MM月DD日 HH时mm分ss秒')},如有疑问请联系网站管理员` ) } // 虚拟币判断是否可以进行继续的操作 const isVirtual = await userVirtual.isVirtual({ uid: user.uid, type: modelName.article, action: modelAction.create }) if (!isVirtual) { throw new Error('贝壳余额不足!') } let oneArticleTag = await models.article_tag.findOne({ where: { tag_id: config.ARTICLE_TAG.dfOfficialExclusive } }) const website = lowdb .read() .get('website') .value() if (~reqData.tag_ids.indexOf(config.ARTICLE_TAG.dfOfficialExclusive)) { if (!~user.user_role_ids.indexOf(config.USER_ROLE.dfManagementTeam)) { throw new Error( `${oneArticleTag.name}只有${website.website_name}管理团队才能发布文章` ) } } const coverImg = reqData.origin_content.match(/!\[(.*?)\]\((.*?)\)/) let $ = cheerio.load(reqData.content) let userRoleALL = await models.user_role.findAll({ where: { user_role_id: { [Op.or]: user.user_role_ids.split(',') }, user_role_type: 1 // 用户角色类型1是默认角色 } }) let userAuthorityIds = '' userRoleALL.map((roleItem: { user_authority_ids: string }) => { userAuthorityIds += roleItem.user_authority_ids + ',' }) let status = ~userAuthorityIds.indexOf( config.USER_AUTHORITY.dfNoReviewArticleId ) ? statusList.freeReview // 免审核 : statusList.pendingReview // 待审核 let createArticle = await models.article .create({ uid: user.uid, title: xss(reqData.title), excerpt: getSubStr(getNoMarkupStr($.text())) /* 摘记 */, content: xss(reqData.content) /* 主内容 */, origin_content: reqData.origin_content /* 源内容 */, source: reqData.source, // 来源 (1原创 2转载) cover_img: coverImg ? coverImg[2] : '', status, // '状态(0:草稿;1:审核中;2:审核通过;3:审核失败;4:回收站;5:已删除;6:无需审核)' is_public: Number(reqData.is_public), // 是否公开 type: reqData.type, // 类型 (1文章 2日记 3草稿 ) blog_ids: reqData.blog_ids, tag_ids: reqData.tag_ids, is_attachment: Number(reqData.is_attachment) /* 是否开启附件 */ }) .then((result: any) => { resultArticle = result.get({ plain: true }) return result }) if (Number(reqData.is_attachment) === isOpen.yes) { // 附件功能 await models.article_annex.create({ uid: user.uid, aid: createArticle.aid, is_free: Number(reqData.is_free) /* 源内容 */, pay_type: reqData.pay_type /* 源内容 */, price: Number(reqData.is_free) === isFree.pay ? parseInt(reqData.price) : 0 /* 源内容 */, title: xss(reqData.title), attachment: xss(reqData.attachment) /*主内容*/, origin_attachment: reqData.origin_attachment }) } await userVirtual.setVirtual({ uid: user.uid, associate: createArticle.aid, type: modelName.article, action: modelAction.create }) await attention.attentionMessage({ uid: user.uid, type: modelName.article, action: modelAction.create, associate_id: resultArticle.aid }) resClientJson(res, { state: 'success', message: '文章创建成功,最晚会在4小时内由人工审核通过后发布,超过24点文章,将在次日8.30审核后发布' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 更新文章 * @param {object} ctx 上下文对象 */ static async updateArticle(req: any, res: any, next: any) { let reqData = req.body let { user = '' } = req try { let oneArticle = await models.article.findOne({ where: { aid: reqData.aid, uid: user.uid // 查询条件 } }) if (!oneArticle) { throw new Error('非法操作') } if (!reqData.title) { throw new Error('请输入文章标题') } if (reqData.title.length > 150) { throw new Error('文章标题过长,请小于150个字符') } if (!reqData.content) { throw new Error('请输入文章内容') } if (reqData.source.length === 0 || reqData.source === null) { throw new Error('请选择文章来源类型') } if (!reqData.tag_ids) { throw new Error('请选择文章标签') } if (Number(reqData.is_attachment) === isOpen.yes) { if (Number(reqData.is_free) !== isFree.free) { if (!reqData.pay_type) { throw new Error('请选择支付类型') } if (reqData.price < 0) { throw new Error('请请输入大于等于0的定价!') } if (reqData.price > 100) { throw new Error('当前定价不能超过100,后续等待管理员开放!') } if (!isDigit(reqData.price)) { throw new Error('请输入整数数字类型!') } } if (!reqData.attachment || reqData.attachment.length <= 0) { throw new Error('附件内容不能为空') } } let date = new Date() let currDate = moment(date.setHours(date.getHours())).format( 'YYYY-MM-DD HH:mm:ss' ) if (new Date(currDate).getTime() < new Date(user.ban_dt).getTime()) { throw new Error( `当前用户因违规已被管理员禁用修改文章,时间到:${moment( user.ban_dt ).format('YYYY年MM月DD日 HH时mm分ss秒')},如有疑问请联系网站管理员` ) } let oneArticleTag = await models.article_tag.findOne({ where: { tag_id: config.ARTICLE_TAG.dfOfficialExclusive } }) const website = lowdb .read() .get('website') .value() if (~reqData.tag_ids.indexOf(config.ARTICLE_TAG.dfOfficialExclusive)) { if (!~user.user_role_ids.indexOf(config.USER_ROLE.dfManagementTeam)) { throw new Error( `${oneArticleTag.name}只有${website.website_name}管理团队才能更新文章` ) } } const coverImg = reqData.origin_content.match(/!\[(.*?)\]\((.*?)\)/) let $ = cheerio.load(reqData.content) let userRoleAll = await models.user_role.findAll({ where: { user_role_id: { [Op.or]: user.user_role_ids.split(',') }, user_role_type: 1 // 用户角色类型1是默认角色 } }) let userAuthorityIds = '' userRoleAll.map((roleItem: any) => { userAuthorityIds += roleItem.user_authority_ids + ',' }) let status = ~userAuthorityIds.indexOf( config.USER_AUTHORITY.dfNoReviewArticleId ) ? statusList.freeReview : statusList.pendingReview await models.article.update( { title: reqData.title, excerpt: getSubStr(getNoMarkupStr($.text())) /* 摘记 */, content: xss(reqData.content) /* 主内容 */, origin_content: reqData.origin_content /* 源内容 */, source: reqData.source, // 来源 (1原创 2转载) cover_img: coverImg ? coverImg[2] : '', status, // '状态(0:草稿;1:审核中;2:审核通过;3:审核失败;4:回收站;5:已删除;6:无需审核)' is_public: Number(reqData.is_public), // 是否公开 type: reqData.type, // 类型 (1文章 2日记 3草稿 ) blog_ids: reqData.blog_ids, tag_ids: reqData.tag_ids, is_attachment: Number(reqData.is_attachment) /* 是否开启附件 */, update_date: moment(date.setHours(date.getHours())).format( 'YYYY-MM-DD HH:mm:ss' ) /* 时间 */, update_date_timestamp: moment(date.setHours(date.getHours())).format( 'X' ) /* 时间戳 */ }, { where: { aid: reqData.aid, uid: user.uid // 查询条件 } } ) let articleAnnex = await models.article_annex.findOne({ where: { aid: reqData.aid, uid: user.uid } }) if (Number(reqData.is_attachment) === isOpen.yes) { // 附件功能 if (articleAnnex) { await models.article_annex.update( { is_free: Number(reqData.is_free) /* 源内容 */, pay_type: reqData.pay_type /* 源内容 */, price: Number(reqData.is_free) === isFree.pay ? parseInt(reqData.price) : 0 /* 源内容 */, title: xss(reqData.title), attachment: xss(reqData.attachment) /*主内容*/, origin_attachment: reqData.origin_attachment, update_date: moment(date.setHours(date.getHours())).format( 'YYYY-MM-DD HH:mm:ss' ) /* 时间 */, update_date_timestamp: moment( date.setHours(date.getHours()) ).format('X') /* 时间戳 */ }, { where: { aid: reqData.aid, uid: user.uid // 查询条件 } } ) } else { // 附件功能 await models.article_annex.create({ uid: user.uid, aid: reqData.aid, is_free: Number(reqData.is_free) /* 源内容 */, pay_type: reqData.pay_type /* 源内容 */, price: Number(reqData.is_free) === isFree.pay ? parseInt(reqData.price) : 0 /* 源内容 */, title: xss(reqData.title), attachment: xss(reqData.attachment) /*主内容*/, origin_attachment: reqData.origin_attachment }) } } resClientJson(res, { state: 'success', message: '文章更新后需要重新审核,最晚会在4小时内由人工审核通过后发布,超过24点文章,将在次日8.30审核后发布' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 文章的标签页面 * @param {object} ctx 上下文对象 */ static async getArticleTag(req: any, res: any, next: any) { let qyData = req.query let page = req.query.page || 1 let pageSize = req.query.pageSize || 25 try { let oneArticleTag = await models.article_tag.findOne({ where: { en_name: qyData.en_name } }) if (oneArticleTag) { let { count, rows } = await models.article.findAndCountAll({ where: { tag_ids: { [Op.like]: `%${oneArticleTag.tag_id}%` }, is_public: true, // 公开的文章 status: { [Op.or]: [statusList.reviewSuccess, statusList.freeReview] // 审核成功、免审核 } // web 表示前台 公共文章限制文件 }, // 为空,获取全部,也可以自己添加条件 offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目 limit: pageSize, // 每页限制返回的数据条数 order: [['create_timestamp', 'desc']] }) for (let i in rows) { rows[i].setDataValue( 'create_dt', await TimeDistance(rows[i].create_date) ) let oneArticleBlog = await models.article_blog.findOne({ where: { blog_id: rows[i].blog_ids } }) if ( oneArticleBlog && ~[statusList.reviewSuccess, statusList.freeReview].indexOf( oneArticleBlog.status ) ) { rows[i].setDataValue('article_blog', oneArticleBlog) } if (rows[i].tag_ids) { rows[i].setDataValue( 'tag', await models.article_tag.findAll({ where: { tag_id: { [Op.or]: rows[i].tag_ids.split(',') } } }) ) } rows[i].setDataValue( 'user', await models.user.findOne({ where: { uid: rows[i].uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) } let subscribeArticleTagCount = await models.attention.count({ where: { associate_id: oneArticleTag.tag_id, is_associate: true, type: modelName.article_tag } }) /* 所有文章专题 */ let articleTagAll = await models.article_tag.findAll({ attributes: ['tag_id', 'name', 'en_name'] }) await resClientJson(res, { state: 'success', message: 'user', data: { page, count, pageSize, en_name: qyData.en_name, subscribe_count: subscribeArticleTagCount, article_tag: oneArticleTag, tag_all: articleTagAll, article_list: rows } }) } else { throw new Error('当前文章标签不存在') } } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 获取热门文章标签 * @param {object} ctx 上下文对象 */ static async getPopularArticleTag(req: any, res: any, next: any) { try { let articleTagAll = await models.article_tag.findAll({ attributes: ['tag_id', 'name', 'en_name', 'icon', 'description'], where: { enable: true }, limit: 12, // 为空,获取全部,也可以自己添加条件 order: [ ['attention_count', 'DESC'] // ASC ] }) for (let i in articleTagAll) { articleTagAll[i].setDataValue( 'subscribe_count', await models.attention.count({ where: { associate_id: articleTagAll[i].id || '', is_associate: true, type: modelName.article_tag } }) ) articleTagAll[i].setDataValue( 'article_count', await models.article.count({ where: { tag_ids: { [Op.like]: `%${articleTagAll[i].tag_id}%` } } }) ) } resClientJson(res, { state: 'success', message: '获取所有文章标签成功', data: { list: articleTagAll } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 获取所有文章标签get * @param {object} ctx 上下文对象 */ static async getArticleTagAll(req: any, res: any, next: any) { try { let articleTagAll = await models.article_tag.findAll({ attributes: ['tag_id', 'name', 'en_name', 'icon', 'description'], where: { enable: true } // 为空,获取全部,也可以自己添加条件 }) for (let i in articleTagAll) { articleTagAll[i].setDataValue( 'subscribe_count', await models.attention.count({ where: { associate_id: articleTagAll[i].id || '', is_associate: true, type: modelName.article_tag } }) ) articleTagAll[i].setDataValue( 'article_count', await models.article.count({ where: { tag_ids: { [Op.like]: `%${articleTagAll[i].tag_id}%` } } }) ) } resClientJson(res, { state: 'success', message: '获取所有文章标签成功', data: { list: articleTagAll } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * ajax 查询一篇文章 * @param {object} ctx 上下文对象 */ static async getArticle(req: any, res: any, next: any) { const { aid } = req.query const { user, islogin } = req try { let oneArticle = await models.article.findOne({ where: { aid, status: { [Op.or]: [statusList.reviewSuccess, statusList.freeReview] // 审核成功、免审核 } } }) if (oneArticle) { await models.article.update( { read_count: Number(oneArticle.read_count) + 1 }, { where: { aid } } // 为空,获取全部,也可以自己添加条件 ) oneArticle.setDataValue( 'create_dt', await TimeDistance(oneArticle.create_date) ) let oneArticleBlog = await models.article_blog.findOne({ where: { blog_id: oneArticle.blog_ids } }) if ( oneArticleBlog && ~[statusList.reviewSuccess, statusList.freeReview].indexOf( oneArticleBlog.status ) ) { oneArticle.setDataValue('article_blog', oneArticleBlog) } if (oneArticle.tag_ids) { oneArticle.setDataValue( 'tag', await models.article_tag.findAll({ where: { tag_id: { [Op.or]: oneArticle.tag_ids.split(',') } } }) ) } oneArticle.setDataValue( 'user', await models.user.findOne({ where: { uid: oneArticle.uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) if (islogin && user.uid !== oneArticle.uid) { // 阅读他人的文章 await useExperience.setExperience({ uid: user.uid, ass_uid: oneArticle.uid, associate: aid, type: modelName.article, action: modelAction.readOther }) } if (oneArticle) { resClientJson(res, { state: 'success', message: '获取文章成功', data: { article: oneArticle } }) } else { resClientJson(res, { state: 'error', message: '获取文章失败' }) } } else { throw new Error('获取文章失败') } } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * ajax 获取用户自己的一篇文章 * @param {object} ctx 上下文对象 */ static async getUserArticle(req: any, res: any, next: any) { let { aid } = req.query let { user = '' } = req try { let article = await models.article.findOne({ where: { aid, uid: user.uid } }) if (article) { let articleAnnex = await models.article_annex.findOne({ where: { aid: article.aid, uid: user.uid } }) article.setDataValue( 'user', await models.user.findOne({ where: { uid: article.uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) article.setDataValue( 'create_dt', await TimeDistance(article.create_date) ) if (article) { resClientJson(res, { state: 'success', message: '获取当前用户文章成功', data: { article, articleAnnex } }) } else { resClientJson(res, { state: 'error', message: '获取当前用户文章失败' }) } } else { throw new Error('获取当前用户文章失败') } } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 删除文章 * @param {object} ctx 上下文对象 * 删除文章判断是否有文章 * 无关联则直接删除文章,有关联则开启事务同时删除与文章的关联 * 前台用户删除文章并不是真的删除,只是置为了删除态 */ static async deleteArticle(req: any, res: any, next: any) { const { aid } = req.query let { islogin = '', user = '' } = req try { let oneArticle = await models.article.findOne({ where: { aid, uid: user.uid // 查询条件 } }) if (!oneArticle) { throw new Error('文章不存在') } if (!islogin) { throw new Error('请登录后尝试') } if (user.uid !== oneArticle.uid) { throw new Error('非法操作已禁止') } await models.article.update( { status: statusList.deleted }, // '状态(0:草稿;1:审核中;2:审核通过;3:审核失败,4回收站,5已删除)'}, { { where: { aid, uid: user.uid // 查询条件 } } ) resClientJson(res, { state: 'success', message: '删除文章成功' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 搜索 * @param {object} ctx 上下文对象 */ static async searchArticle(req: any, res: any, next: any) { let page = req.query.page || 1 let pageSize = req.query.pageSize || 25 let search = req.query.search try { let { count, rows } = await models.article.findAndCountAll({ where: { title: { [Op.like]: `%${search}%` }, is_public: true, // 公开的文章 status: { [Op.or]: [statusList.reviewSuccess, statusList.freeReview] // 审核成功、免审核 } // web 表示前台 公共文章限制文件 }, // 为空,获取全部,也可以自己添加条件 // status: 2 限制只有 审核通过的显示 offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目 limit: pageSize, // 每页限制返回的数据条数 order: [['create_timestamp', 'desc']] }) for (let i in rows) { rows[i].setDataValue( 'create_dt', await TimeDistance(rows[i].create_date) ) let oneArticleBlog = await models.article_blog.findOne({ where: { blog_id: rows[i].blog_ids } }) if ( oneArticleBlog && ~[statusList.reviewSuccess, statusList.freeReview].indexOf( oneArticleBlog.status ) ) { rows[i].setDataValue('article_blog', oneArticleBlog) } if (rows[i].tag_ids) { rows[i].setDataValue( 'tag', await models.article_tag.findAll({ where: { tag_id: { [Op.or]: rows[i].tag_ids.split(',') } } }) ) } rows[i].setDataValue( 'user', await models.user.findOne({ where: { uid: rows[i].uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) } /* 所有文章专题 */ let allArticleTag = await models.article_tag.findAll({ attributes: ['tag_id', 'name'] }) await resClientJson(res, { state: 'success', message: 'search', data: { page, count, pageSize, search, tag_all: allArticleTag, article_list: rows } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 获取文章专栏 * @param {object} ctx 上下文对象 */ static async getArticleColumn(req: any, res: any, next: any) { try { const en_name = req.query.en_name let oneArticleColumn = await models.article_column.findOne({ attributes: [ 'column_id', 'name', 'en_name', 'icon', 'tag_ids', 'description' ], where: { enable: true, is_home: true, en_name: en_name } }) if (oneArticleColumn && oneArticleColumn.tag_ids) { oneArticleColumn.setDataValue( 'tag', await models.article_tag.findAll({ where: { tag_id: { [Op.or]: oneArticleColumn.tag_ids.split(',') } } }) ) } resClientJson(res, { state: 'success', message: '获取所有文章专栏成功', data: { view: oneArticleColumn } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 获取文章专栏全部列表 * @param {object} ctx 上下文对象 */ static async getArticleColumnAll(req: any, res: any, next: any) { try { let allArticleColumn = await models.article_column.findAll({ attributes: [ 'column_id', 'name', 'en_name', 'icon', 'tag_ids', 'description' ], where: { enable: true, is_home: true }, // 为空,获取全部,也可以自己添加条件 order: [ ['sort', 'ASC'] // asc ] }) for (let i in allArticleColumn) { if (allArticleColumn[i].tag_ids) { allArticleColumn[i].setDataValue( 'tag', await models.article_tag.findAll({ where: { tag_id: { [Op.or]: allArticleColumn[i].tag_ids.split(',') } } }) ) } } resClientJson(res, { state: 'success', message: '获取所有文章专栏成功', data: { list: allArticleColumn } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 获取文章专栏分页列表 * @param {object} ctx 上下文对象 */ static async getArticleColumnList(req: any, res: any, next: any) { let page = req.query.page || 1 let pageSize = req.query.pageSize || 25 let whereParams = { enable: 1 } try { let { count, rows } = await models.article_column.findAndCountAll({ attributes: [ 'column_id', 'name', 'en_name', 'icon', 'tag_ids', 'description' ], where: whereParams, // 为空,获取全部,也可以自己添加条件 offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目 limit: pageSize // 每页限制返回的数据条数 }) for (let i in rows) { let tag_id: any = {} if (rows[i].tag_ids && rows[i].tag_ids.length > 0) { tag_id = { [Op.in]: rows[i].tag_ids.split(',') } } else { tag_id = rows[i].tag_ids } rows[i].setDataValue( 'tag', await models.article_tag.findAll({ where: { tag_id } }) ) } await resClientJson(res, { state: 'success', message: 'column', data: { page, count, pageSize, list: rows } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * ajax 获取文章附件 * @param {object} ctx 上下文对象 */ static async getArticleAnnex(req: any, res: any, next: any) { let { aid } = req.query let { user = '', islogin } = req try { let articleAnnex = await models.article_annex.findOne({ where: { aid } }) if (islogin && articleAnnex) { let productInfo = await models.order.findOne({ where: { product_id: articleAnnex.id, product_type: modelName.article_annex, uid: user.uid } }) if (articleAnnex.uid === user.uid) { articleAnnex.setDataValue('isBuy', true) } else { if (articleAnnex.is_free === isFree.free) { articleAnnex.setDataValue('isBuy', true) } else { if (productInfo) { articleAnnex.setDataValue('isBuy', true) } else { articleAnnex.setDataValue('attachment', '') articleAnnex.setDataValue('isBuy', false) } } } } else if (articleAnnex) { articleAnnex.setDataValue('attachment', '') articleAnnex.setDataValue('isBuy', false) } resClientJson(res, { state: 'success', message: '获取当前用户文章附件信息成功', data: { articleAnnex } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } } export default Article
the_stack
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { map, switchMap, mergeMap } from 'rxjs/operators'; import { FollowLinkConfig, followLink } from '../../../shared/utils/follow-link-config.model'; import { dataService } from '../../cache/builders/build-decorators'; import { DataService } from '../../data/data.service'; import { RequestService } from '../../data/request.service'; import { FindListOptions } from '../../data/request.models'; import { HALEndpointService } from '../../shared/hal-endpoint.service'; import { RemoteData } from '../../data/remote-data'; import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; import { CoreState } from '../../core.reducers'; import { ObjectCacheService } from '../../cache/object-cache.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { ChangeAnalyzer } from '../../data/change-analyzer'; import { DefaultChangeAnalyzer } from '../../data/default-change-analyzer.service'; import { PaginatedList } from '../../data/paginated-list.model'; import { Vocabulary } from './models/vocabulary.model'; import { VOCABULARY } from './models/vocabularies.resource-type'; import { VocabularyEntry } from './models/vocabulary-entry.model'; import { isNotEmpty } from '../../../shared/empty.util'; import { getFirstSucceededRemoteDataPayload, getFirstSucceededRemoteListPayload } from '../../shared/operators'; import { VocabularyFindOptions } from './models/vocabulary-find-options.model'; import { VocabularyEntryDetail } from './models/vocabulary-entry-detail.model'; import { RequestParam } from '../../cache/models/request-param.model'; import { VocabularyOptions } from './models/vocabulary-options.model'; import { PageInfo } from '../../shared/page-info.model'; import { HrefOnlyDataService } from '../../data/href-only-data.service'; /* tslint:disable:max-classes-per-file */ /** * A private DataService implementation to delegate specific methods to. */ class VocabularyDataServiceImpl extends DataService<Vocabulary> { protected linkPath = 'vocabularies'; constructor( protected requestService: RequestService, protected rdbService: RemoteDataBuildService, protected store: Store<CoreState>, protected objectCache: ObjectCacheService, protected halService: HALEndpointService, protected notificationsService: NotificationsService, protected http: HttpClient, protected comparator: ChangeAnalyzer<Vocabulary>) { super(); } } /** * A private DataService implementation to delegate specific methods to. */ class VocabularyEntryDetailDataServiceImpl extends DataService<VocabularyEntryDetail> { protected linkPath = 'vocabularyEntryDetails'; constructor( protected requestService: RequestService, protected rdbService: RemoteDataBuildService, protected store: Store<CoreState>, protected objectCache: ObjectCacheService, protected halService: HALEndpointService, protected notificationsService: NotificationsService, protected hrefOnlyDataService: HrefOnlyDataService, protected http: HttpClient, protected comparator: ChangeAnalyzer<VocabularyEntryDetail>) { super(); } } /** * A service responsible for fetching/sending data from/to the REST API on the vocabularies endpoint */ @Injectable() @dataService(VOCABULARY) export class VocabularyService { protected searchTopMethod = 'top'; private vocabularyDataService: VocabularyDataServiceImpl; private vocabularyEntryDetailDataService: VocabularyEntryDetailDataServiceImpl; constructor( protected requestService: RequestService, protected rdbService: RemoteDataBuildService, protected objectCache: ObjectCacheService, protected halService: HALEndpointService, protected notificationsService: NotificationsService, protected hrefOnlyDataService: HrefOnlyDataService, protected http: HttpClient, protected comparatorVocabulary: DefaultChangeAnalyzer<Vocabulary>, protected comparatorEntry: DefaultChangeAnalyzer<VocabularyEntryDetail>) { this.vocabularyDataService = new VocabularyDataServiceImpl(requestService, rdbService, null, objectCache, halService, notificationsService, http, comparatorVocabulary); this.vocabularyEntryDetailDataService = new VocabularyEntryDetailDataServiceImpl(requestService, rdbService, null, objectCache, halService, notificationsService, hrefOnlyDataService, http, comparatorEntry); } /** * Returns an observable of {@link RemoteData} of a {@link Vocabulary}, based on an href, with a list of {@link FollowLinkConfig}, * to automatically resolve {@link HALLink}s of the {@link Vocabulary} * @param href The url of object we want to retrieve * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved * @return {Observable<RemoteData<Vocabulary>>} * Return an observable that emits vocabulary object */ findVocabularyByHref(href: string, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Vocabulary>[]): Observable<RemoteData<any>> { return this.vocabularyDataService.findByHref(href, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Returns an observable of {@link RemoteData} of a {@link Vocabulary}, based on its ID, with a list of {@link FollowLinkConfig}, * to automatically resolve {@link HALLink}s of the object * @param name The name of {@link Vocabulary} we want to retrieve * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved * @return {Observable<RemoteData<Vocabulary>>} * Return an observable that emits vocabulary object */ findVocabularyById(name: string, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Vocabulary>[]): Observable<RemoteData<Vocabulary>> { return this.vocabularyDataService.findById(name, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Returns {@link RemoteData} of all object with a list of {@link FollowLinkConfig}, to indicate which embedded * info should be added to the objects * * @param options Find list options object * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved * @return {Observable<RemoteData<PaginatedList<Vocabulary>>>} * Return an observable that emits object list */ findAllVocabularies(options: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Vocabulary>[]): Observable<RemoteData<PaginatedList<Vocabulary>>> { return this.vocabularyDataService.findAll(options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Return the {@link VocabularyEntry} list for a given {@link Vocabulary} * * @param vocabularyOptions The {@link VocabularyOptions} for the request to which the entries belong * @param pageInfo The {@link PageInfo} for the request * @return {Observable<RemoteData<PaginatedList<VocabularyEntry>>>} * Return an observable that emits object list */ getVocabularyEntries(vocabularyOptions: VocabularyOptions, pageInfo: PageInfo): Observable<RemoteData<PaginatedList<VocabularyEntry>>> { const options: VocabularyFindOptions = new VocabularyFindOptions( null, null, null, null, pageInfo.elementsPerPage, pageInfo.currentPage ); // TODO remove false for the entries embed when https://github.com/DSpace/DSpace/issues/3096 is solved return this.findVocabularyById(vocabularyOptions.name, true, true, followLink('entries', { findListOptions: options, shouldEmbed: false })).pipe( getFirstSucceededRemoteDataPayload(), switchMap((vocabulary: Vocabulary) => vocabulary.entries), ); } /** * Return the {@link VocabularyEntry} list for a given value * * @param value The entry value to retrieve * @param exact If true force the vocabulary to provide only entries that match exactly with the value * @param vocabularyOptions The {@link VocabularyOptions} for the request to which the entries belong * @param pageInfo The {@link PageInfo} for the request * @return {Observable<RemoteData<PaginatedList<VocabularyEntry>>>} * Return an observable that emits object list */ getVocabularyEntriesByValue(value: string, exact: boolean, vocabularyOptions: VocabularyOptions, pageInfo: PageInfo): Observable<RemoteData<PaginatedList<VocabularyEntry>>> { const options: VocabularyFindOptions = new VocabularyFindOptions( null, value, exact, null, pageInfo.elementsPerPage, pageInfo.currentPage ); // TODO remove false for the entries embed when https://github.com/DSpace/DSpace/issues/3096 is solved return this.findVocabularyById(vocabularyOptions.name, true, true, followLink('entries', { findListOptions: options, shouldEmbed: false })).pipe( getFirstSucceededRemoteDataPayload(), switchMap((vocabulary: Vocabulary) => vocabulary.entries), ); } /** * Return the {@link VocabularyEntry} list for a given value * * @param value The entry value to retrieve * @param vocabularyOptions The {@link VocabularyOptions} for the request to which the entry belongs * @return {Observable<RemoteData<PaginatedList<VocabularyEntry>>>} * Return an observable that emits {@link VocabularyEntry} object */ getVocabularyEntryByValue(value: string, vocabularyOptions: VocabularyOptions): Observable<VocabularyEntry> { return this.getVocabularyEntriesByValue(value, true, vocabularyOptions, new PageInfo()).pipe( getFirstSucceededRemoteListPayload(), map((list: VocabularyEntry[]) => { if (isNotEmpty(list)) { return list[0]; } else { return null; } }) ); } /** * Return the {@link VocabularyEntry} list for a given ID * * @param ID The entry ID to retrieve * @param vocabularyOptions The {@link VocabularyOptions} for the request to which the entry belongs * @return {Observable<RemoteData<PaginatedList<VocabularyEntry>>>} * Return an observable that emits {@link VocabularyEntry} object */ getVocabularyEntryByID(ID: string, vocabularyOptions: VocabularyOptions): Observable<VocabularyEntry> { const pageInfo = new PageInfo(); const options: VocabularyFindOptions = new VocabularyFindOptions( null, null, null, ID, pageInfo.elementsPerPage, pageInfo.currentPage ); // TODO remove false for the entries embed when https://github.com/DSpace/DSpace/issues/3096 is solved return this.findVocabularyById(vocabularyOptions.name, true, true, followLink('entries', { findListOptions: options, shouldEmbed: false })).pipe( getFirstSucceededRemoteDataPayload(), switchMap((vocabulary: Vocabulary) => vocabulary.entries), getFirstSucceededRemoteListPayload(), map((list: VocabularyEntry[]) => { if (isNotEmpty(list)) { return list[0]; } else { return null; } }) ); } /** * Returns an observable of {@link RemoteData} of a {@link VocabularyEntryDetail}, based on an href, with a list of {@link FollowLinkConfig}, * to automatically resolve {@link HALLink}s of the {@link VocabularyEntryDetail} * @param href The url of object we want to retrieve * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved * @return {Observable<RemoteData<VocabularyEntryDetail>>} * Return an observable that emits vocabulary object */ findEntryDetailByHref(href: string, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<VocabularyEntryDetail>[]): Observable<RemoteData<VocabularyEntryDetail>> { return this.vocabularyEntryDetailDataService.findByHref(href, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Returns an observable of {@link RemoteData} of a {@link VocabularyEntryDetail}, based on its ID, with a list of {@link FollowLinkConfig}, * to automatically resolve {@link HALLink}s of the object * @param id The entry id for which to provide detailed information. * @param name The name of {@link Vocabulary} to which the entry belongs * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved * @return {Observable<RemoteData<VocabularyEntryDetail>>} * Return an observable that emits VocabularyEntryDetail object */ findEntryDetailById(id: string, name: string, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<VocabularyEntryDetail>[]): Observable<RemoteData<VocabularyEntryDetail>> { const findId = `${name}:${id}`; return this.vocabularyEntryDetailDataService.findById(findId, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Returns the parent detail entry for a given detail entry, with a list of {@link FollowLinkConfig}, * to automatically resolve {@link HALLink}s of the object * @param value The entry value for which to provide parent. * @param name The name of {@link Vocabulary} to which the entry belongs * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved * @return {Observable<RemoteData<PaginatedList<VocabularyEntryDetail>>>} * Return an observable that emits a PaginatedList of VocabularyEntryDetail */ getEntryDetailParent(value: string, name: string, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<VocabularyEntryDetail>[]): Observable<RemoteData<VocabularyEntryDetail>> { const linkPath = `${name}:${value}/parent`; return this.vocabularyEntryDetailDataService.getBrowseEndpoint().pipe( map((href: string) => `${href}/${linkPath}`), mergeMap((href) => this.vocabularyEntryDetailDataService.findByHref(href, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)) ); } /** * Returns the list of children detail entries for a given detail entry, with a list of {@link FollowLinkConfig}, * to automatically resolve {@link HALLink}s of the object * @param value The entry value for which to provide children list. * @param name The name of {@link Vocabulary} to which the entry belongs * @param pageInfo The {@link PageInfo} for the request * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved * @return {Observable<RemoteData<PaginatedList<VocabularyEntryDetail>>>} * Return an observable that emits a PaginatedList of VocabularyEntryDetail */ getEntryDetailChildren(value: string, name: string, pageInfo: PageInfo, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<VocabularyEntryDetail>[]): Observable<RemoteData<PaginatedList<VocabularyEntryDetail>>> { const linkPath = `${name}:${value}/children`; const options: VocabularyFindOptions = new VocabularyFindOptions( null, null, null, null, pageInfo.elementsPerPage, pageInfo.currentPage ); return this.vocabularyEntryDetailDataService.getFindAllHref(options, linkPath).pipe( mergeMap((href) => this.vocabularyEntryDetailDataService.findAllByHref(href, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)) ); } /** * Return the top level {@link VocabularyEntryDetail} list for a given hierarchical vocabulary * * @param name The name of hierarchical {@link Vocabulary} to which the * entries belongs * @param pageInfo The {@link PageInfo} for the request * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved */ searchTopEntries(name: string, pageInfo: PageInfo, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<VocabularyEntryDetail>[]): Observable<RemoteData<PaginatedList<VocabularyEntryDetail>>> { const options: VocabularyFindOptions = new VocabularyFindOptions( null, null, null, null, pageInfo.elementsPerPage, pageInfo.currentPage ); options.searchParams = [new RequestParam('vocabulary', name)]; return this.vocabularyEntryDetailDataService.searchBy(this.searchTopMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Clear all search Top Requests */ clearSearchTopRequests(): void { this.requestService.removeByHrefSubstring(`search/${this.searchTopMethod}`); } } /* tslint:enable:max-classes-per-file */
the_stack
import {ethers} from 'hardhat'; import {setupTestGiveaway} from './fixtures'; import {constants, BigNumber} from 'ethers'; import { waitFor, expectReceiptEventWithArgs, expectEventWithArgs, } from '../utils'; import {expect} from '../chai-setup'; import helpers from '../../lib/merkleTreeHelper'; const {calculateMultiClaimHash} = helpers; const zeroAddress = constants.AddressZero; const emptyBytes32 = '0x0000000000000000000000000000000000000000000000000000000000000000'; describe('Multi_Giveaway', function () { describe('Multi_Giveaway_common_functionality', function () { it('Admin can add a new giveaway', async function () { const options = {}; const setUp = await setupTestGiveaway(options); const {giveawayContract, nftGiveawayAdmin} = setUp; const giveawayContractAsAdmin = await giveawayContract.connect( ethers.provider.getSigner(nftGiveawayAdmin) ); const receipt = await waitFor( giveawayContractAsAdmin.addNewGiveaway( emptyBytes32, '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' // does not expire ) ); const event = await expectReceiptEventWithArgs(receipt, 'NewGiveaway'); expect(event.args[0]).to.equal(emptyBytes32); expect(event.args[1]).to.equal( '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' ); }); it('Cannot add a new giveaway if not admin', async function () { const options = {}; const setUp = await setupTestGiveaway(options); const {giveawayContract, others} = setUp; const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.addNewGiveaway( emptyBytes32, '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' ) ).to.be.revertedWith('ADMIN_ONLY'); }); it('User can get their claimed status', async function () { const options = {multi: true}; const setUp = await setupTestGiveaway(options); const {giveawayContract, others, allMerkleRoots} = setUp; const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const statuses = await giveawayContractAsUser.getClaimedStatus( others[0], allMerkleRoots ); expect(statuses[0]).to.equal(false); expect(statuses[1]).to.equal(false); }); it('Claimed status is correctly updated after allocated tokens are claimed - 2 claims of 2 claimed', async function () { const options = { mint: true, sand: true, multi: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userClaims = []; const claim = allClaims[0][0]; const secondClaim = allClaims[1][0]; userClaims.push(claim); userClaims.push(secondClaim); for (let i = 0; i < userClaims.length; i++) { userProofs.push( allTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); userMerkleRoots.push(allMerkleRoots[1]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const statuses = await giveawayContractAsUser.getClaimedStatus( others[0], allMerkleRoots ); expect(statuses[0]).to.equal(false); expect(statuses[1]).to.equal(false); await giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ); const statusesAfterClaim = await giveawayContractAsUser.getClaimedStatus( others[0], allMerkleRoots ); expect(statusesAfterClaim[0]).to.equal(true); expect(statusesAfterClaim[1]).to.equal(true); }); it('Claimed status is correctly updated after allocated tokens are claimed - 1 claim of 2 claimed', async function () { const options = { mint: true, sand: true, multi: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userClaims = []; const secondClaim = allClaims[1][0]; userClaims.push(secondClaim); userProofs.push( allTrees[1].getProof(calculateMultiClaimHash(userClaims[0])) ); const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[1]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const statuses = await giveawayContractAsUser.getClaimedStatus( others[0], allMerkleRoots ); expect(statuses[0]).to.equal(false); expect(statuses[1]).to.equal(false); await giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ); const statusesAfterClaim = await giveawayContractAsUser.getClaimedStatus( others[0], allMerkleRoots ); expect(statusesAfterClaim[0]).to.equal(false); expect(statusesAfterClaim[1]).to.equal(true); }); }); describe('Multi_Giveaway_single_giveaway', function () { it('User cannot claim when test contract holds no tokens', async function () { const options = {}; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, // all claims from all giveaways allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; userClaims.push(allClaims[0][0]); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ).to.be.revertedWith(`can't substract more than there is`); }); it('User cannot claim sand when contract does not hold any', async function () { const options = { mint: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; userClaims.push(allClaims[0][0]); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ).to.be.revertedWith(`not enough fund`); }); it('User can claim allocated multiple tokens from Giveaway contract', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, assetContract, landContract, sandContract, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; const claim = allClaims[0][0]; userClaims.push(claim); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const initBalanceAssetId1 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[0]); expect(initBalanceAssetId1).to.equal(claim.erc1155[0].values[0]); const initBalanceAssetId2 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[1]); expect(initBalanceAssetId2).to.equal(claim.erc1155[0].values[1]); const initBalanceAssetId3 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[2]); expect(initBalanceAssetId3).to.equal(claim.erc1155[0].values[2]); const originalOwnerLandId1 = await landContract.ownerOf(0); expect(originalOwnerLandId1).to.equal(giveawayContract.address); const originalOwnerLandId2 = await landContract.ownerOf(1); expect(originalOwnerLandId2).to.equal(giveawayContract.address); const originalOwnerLandId3 = await landContract.ownerOf(2); expect(originalOwnerLandId3).to.equal(giveawayContract.address); const originalOwnerLandId4 = await landContract.ownerOf(3); expect(originalOwnerLandId4).to.equal(giveawayContract.address); const originalOwnerLandId5 = await landContract.ownerOf(4); expect(originalOwnerLandId5).to.equal(giveawayContract.address); const originalOwnerLandId6 = await landContract.ownerOf(5); expect(originalOwnerLandId6).to.equal(giveawayContract.address); const initialSandBalance = await sandContract.balanceOf(others[0]); expect(initialSandBalance).to.equal(0); await waitFor( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ); const updatedSandBalance = await sandContract.balanceOf(others[0]); expect(updatedSandBalance).to.equal(claim.erc20.amounts[0]); const balanceAssetId1 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[0] ); expect(balanceAssetId1).to.equal(claim.erc1155[0].values[0]); const balanceAssetId2 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[1] ); expect(balanceAssetId2).to.equal(claim.erc1155[0].values[1]); const balanceAssetId3 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[2] ); expect(balanceAssetId3).to.equal(claim.erc1155[0].values[2]); const ownerLandId1 = await landContract.ownerOf(0); expect(ownerLandId1).to.equal(claim.to); const ownerLandId2 = await landContract.ownerOf(1); expect(ownerLandId2).to.equal(claim.to); const ownerLandId3 = await landContract.ownerOf(2); expect(ownerLandId3).to.equal(claim.to); const ownerLandId4 = await landContract.ownerOf(3); expect(ownerLandId4).to.equal(claim.to); const ownerLandId5 = await landContract.ownerOf(4); expect(ownerLandId5).to.equal(claim.to); const ownerLandId6 = await landContract.ownerOf(5); expect(ownerLandId6).to.equal(claim.to); }); it('User can claim allocated 64 tokens from Giveaway contract', async function () { const numberOfAssets = 64; const options = { mint: true, sand: true, numberOfAssets, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, assetContract, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; const claim = allClaims[0][0]; userClaims.push(claim); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const receipt = await waitFor( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ); console.log( 'Number of assets:', numberOfAssets, '; Gas used:', receipt.gasUsed.toString() ); const event = await expectEventWithArgs( assetContract, receipt, 'TransferBatch' ); expect(event.args.ids.length).to.eq(numberOfAssets); }); it('Claimed Event is emitted for successful claim', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allClaims, allTrees, allMerkleRoots, } = setUp; const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; const claim = allClaims[0][0]; userClaims.push(claim); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const receipt = await waitFor( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ); const claimedEvent = await expectReceiptEventWithArgs( receipt, 'ClaimedMultipleTokens' ); expect(claimedEvent.args[0]).to.equal(others[0]); // to expect(claimedEvent.args[1][0][0][0]).to.equal(claim.erc1155[0].ids[0]); expect(claimedEvent.args[1][0][0][1]).to.equal(claim.erc1155[0].ids[1]); expect(claimedEvent.args[1][0][0][2]).to.equal(claim.erc1155[0].ids[2]); expect(claimedEvent.args[1][0][1][0]).to.equal( claim.erc1155[0].values[0] ); expect(claimedEvent.args[1][0][1][1]).to.equal( claim.erc1155[0].values[1] ); expect(claimedEvent.args[1][0][1][2]).to.equal( claim.erc1155[0].values[2] ); expect(claimedEvent.args[1][0][2]).to.equal( claim.erc1155[0].contractAddress ); expect(claimedEvent.args[2][0][0][0]).to.equal(claim.erc721[0].ids[0]); expect(claimedEvent.args[2][0][0][1]).to.equal(claim.erc721[0].ids[1]); expect(claimedEvent.args[2][0][0][2]).to.equal(claim.erc721[0].ids[2]); expect(claimedEvent.args[2][0][0][3]).to.equal(claim.erc721[0].ids[3]); expect(claimedEvent.args[2][0][0][4]).to.equal(claim.erc721[0].ids[4]); expect(claimedEvent.args[2][0][0][5]).to.equal(claim.erc721[0].ids[5]); expect(claimedEvent.args[2][0][1]).to.equal( claim.erc721[0].contractAddress ); expect(claimedEvent.args[3][0][0]).to.equal(claim.erc20.amounts[0]); expect(claimedEvent.args[3][1][0]).to.equal( claim.erc20.contractAddresses[0] ); }); it('User can claim allocated ERC20 from Giveaway contract when there are no assets or lands allocated', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, sandContract, } = setUp; const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; const claim = allClaims[0][4]; userClaims.push(claim); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const initialSandBalance = await sandContract.balanceOf(others[0]); expect(initialSandBalance).to.equal(0); await waitFor( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ); const updatedSandBalance = await sandContract.balanceOf(others[0]); expect(updatedSandBalance).to.equal(claim.erc20.amounts[0]); }); it('User cannot claim if they claim the wrong amount of ERC20', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; const badClaim = JSON.parse(JSON.stringify(allClaims[0][0])); // deep clone badClaim.erc20.amounts[0] = 250; // bad param const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; userClaims.push(badClaim); userProofs.push( userTrees[0].getProof(calculateMultiClaimHash(allClaims[0][0])) ); const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ).to.be.revertedWith('INVALID_CLAIM'); }); it('User cannot claim more than once', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; const claim = allClaims[0][0]; userClaims.push(claim); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await waitFor( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ); await expect( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ).to.be.revertedWith('DESTINATION_ALREADY_CLAIMED'); }); it('User cannot claim from Giveaway contract if destination is not the reserved address', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allClaims, allTrees, allMerkleRoots, } = setUp; const badClaim = JSON.parse(JSON.stringify(allClaims[0][0])); // deep clone badClaim.to = others[2]; // bad param const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; userClaims.push(badClaim); userProofs.push( userTrees[0].getProof(calculateMultiClaimHash(allClaims[0][0])) ); const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ).to.be.revertedWith('INVALID_CLAIM'); }); it('User cannot claim from Giveaway contract to destination zeroAddress', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allClaims, allTrees, allMerkleRoots, } = setUp; const badClaim = JSON.parse(JSON.stringify(allClaims[0][0])); // deep clone badClaim.to = zeroAddress; // bad param const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; userClaims.push(badClaim); userProofs.push( userTrees[0].getProof(calculateMultiClaimHash(allClaims[0][0])) ); const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ).to.be.revertedWith('INVALID_TO_ZERO_ADDRESS'); }); // NOT USED BECAUSE NO EXPIRY // it('User cannot claim after the expiryTime', async function () { // const options = {}; // const setUp = await setupTestGiveaway(options); // const { // giveawayContract, // others, // allTrees, // allClaims, // allMerkleRoots, // } = setUp; // const userProofs = []; // const userTrees = []; // userTrees.push(allTrees[0]); // const userClaims = []; // const claim = allClaims[0][0]; // userClaims.push(claim); // for (let i = 0; i < userClaims.length; i++) { // userProofs.push( // userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) // ); // } // const userMerkleRoots = []; // userMerkleRoots.push(allMerkleRoots[0]); // const giveawayContractAsUser = await giveawayContract.connect( // ethers.provider.getSigner(others[0]) // ); // await increaseTime(60 * 60 * 24 * 30 * 4); // await expect( // giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( // userMerkleRoots, // userClaims, // userProofs // ) // ).to.be.revertedWith('CLAIM_PERIOD_IS_OVER'); // }); }); describe('Multi_Giveaway_two_giveaways', function () { it('User cannot claim when test contract holds no tokens - multiple giveaways, 1 claim', async function () { const options = {multi: true}; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; userClaims.push(allClaims[0][0]); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ).to.be.revertedWith(`can't substract more than there is`); }); it('User cannot claim sand when contract does not hold any - multiple giveaways, 1 claim', async function () { const options = { mint: true, multi: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; userClaims.push(allClaims[0][0]); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ).to.be.revertedWith(`not enough fund`); }); it('User can claim allocated multiple tokens from Giveaway contract - multiple giveaways, 1 claim', async function () { const options = { mint: true, sand: true, multi: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, assetContract, landContract, sandContract, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userTrees = []; userTrees.push(allTrees[0]); const userClaims = []; const claim = allClaims[0][0]; userClaims.push(claim); for (let i = 0; i < userClaims.length; i++) { userProofs.push( userTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const initBalanceAssetId1 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[0]); expect(initBalanceAssetId1).to.equal(claim.erc1155[0].values[0]); const initBalanceAssetId2 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[1]); expect(initBalanceAssetId2).to.equal(claim.erc1155[0].values[1]); const initBalanceAssetId3 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[2]); expect(initBalanceAssetId3).to.equal(claim.erc1155[0].values[2]); const originalOwnerLandId1 = await landContract.ownerOf(0); expect(originalOwnerLandId1).to.equal(giveawayContract.address); const originalOwnerLandId2 = await landContract.ownerOf(1); expect(originalOwnerLandId2).to.equal(giveawayContract.address); const originalOwnerLandId3 = await landContract.ownerOf(2); expect(originalOwnerLandId3).to.equal(giveawayContract.address); const originalOwnerLandId4 = await landContract.ownerOf(3); expect(originalOwnerLandId4).to.equal(giveawayContract.address); const originalOwnerLandId5 = await landContract.ownerOf(4); expect(originalOwnerLandId5).to.equal(giveawayContract.address); const originalOwnerLandId6 = await landContract.ownerOf(5); expect(originalOwnerLandId6).to.equal(giveawayContract.address); const initialSandBalance = await sandContract.balanceOf(others[0]); expect(initialSandBalance).to.equal(0); await waitFor( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ); const updatedSandBalance = await sandContract.balanceOf(others[0]); expect(updatedSandBalance).to.equal(claim.erc20.amounts[0]); const balanceAssetId1 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[0] ); expect(balanceAssetId1).to.equal(claim.erc1155[0].values[0]); const balanceAssetId2 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[1] ); expect(balanceAssetId2).to.equal(claim.erc1155[0].values[1]); const balanceAssetId3 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[2] ); expect(balanceAssetId3).to.equal(claim.erc1155[0].values[2]); const ownerLandId1 = await landContract.ownerOf(0); expect(ownerLandId1).to.equal(claim.to); const ownerLandId2 = await landContract.ownerOf(1); expect(ownerLandId2).to.equal(claim.to); const ownerLandId3 = await landContract.ownerOf(2); expect(ownerLandId3).to.equal(claim.to); const ownerLandId4 = await landContract.ownerOf(3); expect(ownerLandId4).to.equal(claim.to); const ownerLandId5 = await landContract.ownerOf(4); expect(ownerLandId5).to.equal(claim.to); const ownerLandId6 = await landContract.ownerOf(5); expect(ownerLandId6).to.equal(claim.to); }); it('User can claim allocated multiple tokens from Giveaway contract - multiple giveaways, 2 claims', async function () { const options = { mint: true, sand: true, multi: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, speedGemContract, rareCatalystContract, others, allTrees, allClaims, assetContract, landContract, sandContract, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userClaims = []; const claim = allClaims[0][0]; const secondClaim = allClaims[1][0]; userClaims.push(claim); userClaims.push(secondClaim); for (let i = 0; i < userClaims.length; i++) { userProofs.push( allTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); userMerkleRoots.push(allMerkleRoots[1]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); // ERC20 const initialSandBalance = await sandContract.balanceOf(others[0]); expect(initialSandBalance).to.equal(0); const initialGemBalance = await speedGemContract.balanceOf(others[0]); expect(initialGemBalance).to.equal(0); const initialCatBalance = await rareCatalystContract.balanceOf(others[0]); expect(initialCatBalance).to.equal(0); // Claim 1 const initBalanceAssetId1 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[0]); expect(initBalanceAssetId1).to.equal(claim.erc1155[0].values[0]); const initBalanceAssetId2 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[1]); expect(initBalanceAssetId2).to.equal(claim.erc1155[0].values[1]); const initBalanceAssetId3 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[2]); expect(initBalanceAssetId3).to.equal(claim.erc1155[0].values[2]); const originalOwnerLandId1 = await landContract.ownerOf(0); expect(originalOwnerLandId1).to.equal(giveawayContract.address); const originalOwnerLandId2 = await landContract.ownerOf(1); expect(originalOwnerLandId2).to.equal(giveawayContract.address); const originalOwnerLandId3 = await landContract.ownerOf(2); expect(originalOwnerLandId3).to.equal(giveawayContract.address); const originalOwnerLandId4 = await landContract.ownerOf(3); expect(originalOwnerLandId4).to.equal(giveawayContract.address); const originalOwnerLandId5 = await landContract.ownerOf(4); expect(originalOwnerLandId5).to.equal(giveawayContract.address); const originalOwnerLandId6 = await landContract.ownerOf(5); expect(originalOwnerLandId6).to.equal(giveawayContract.address); // Claim 2 const initBalanceAssetId7 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[0]); expect(initBalanceAssetId7).to.equal(secondClaim.erc1155[0].values[0]); const initBalanceAssetId8 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[1]); expect(initBalanceAssetId8).to.equal(secondClaim.erc1155[0].values[1]); const initBalanceAssetId9 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[2]); expect(initBalanceAssetId9).to.equal(secondClaim.erc1155[0].values[2]); const originalOwnerLandId8 = await landContract.ownerOf(0); expect(originalOwnerLandId8).to.equal(giveawayContract.address); const originalOwnerLandId9 = await landContract.ownerOf(1); expect(originalOwnerLandId9).to.equal(giveawayContract.address); const originalOwnerLandId10 = await landContract.ownerOf(2); expect(originalOwnerLandId10).to.equal(giveawayContract.address); const originalOwnerLandId11 = await landContract.ownerOf(3); expect(originalOwnerLandId11).to.equal(giveawayContract.address); const originalOwnerLandId12 = await landContract.ownerOf(4); expect(originalOwnerLandId12).to.equal(giveawayContract.address); const originalOwnerLandId13 = await landContract.ownerOf(5); expect(originalOwnerLandId13).to.equal(giveawayContract.address); await waitFor( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ); // ERC20 const updatedSandBalance = await sandContract.balanceOf(others[0]); expect(updatedSandBalance).to.equal( BigNumber.from(claim.erc20.amounts[0]).add( BigNumber.from(secondClaim.erc20.amounts[0]) ) ); const updatedGemBalance = await speedGemContract.balanceOf(others[0]); expect(updatedGemBalance).to.equal(secondClaim.erc20.amounts[1]); const updatedCatBalance = await rareCatalystContract.balanceOf(others[0]); expect(updatedCatBalance).to.equal(secondClaim.erc20.amounts[2]); // Claim 1 const balanceAssetId1 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[0] ); expect(balanceAssetId1).to.equal(claim.erc1155[0].values[0]); const balanceAssetId2 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[1] ); expect(balanceAssetId2).to.equal(claim.erc1155[0].values[1]); const balanceAssetId3 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[2] ); expect(balanceAssetId3).to.equal(claim.erc1155[0].values[2]); const ownerLandId1 = await landContract.ownerOf(0); expect(ownerLandId1).to.equal(claim.to); const ownerLandId2 = await landContract.ownerOf(1); expect(ownerLandId2).to.equal(claim.to); const ownerLandId3 = await landContract.ownerOf(2); expect(ownerLandId3).to.equal(claim.to); const ownerLandId4 = await landContract.ownerOf(3); expect(ownerLandId4).to.equal(claim.to); const ownerLandId5 = await landContract.ownerOf(4); expect(ownerLandId5).to.equal(claim.to); const ownerLandId6 = await landContract.ownerOf(5); expect(ownerLandId6).to.equal(claim.to); // Claim 2 const balanceAssetId7 = await assetContract['balanceOf(address,uint256)']( others[0], secondClaim.erc1155[0].ids[0] ); expect(balanceAssetId7).to.equal(secondClaim.erc1155[0].values[0]); const balanceAssetId8 = await assetContract['balanceOf(address,uint256)']( others[0], secondClaim.erc1155[0].ids[1] ); expect(balanceAssetId8).to.equal(secondClaim.erc1155[0].values[1]); const balanceAssetId9 = await assetContract['balanceOf(address,uint256)']( others[0], secondClaim.erc1155[0].ids[2] ); expect(balanceAssetId9).to.equal(secondClaim.erc1155[0].values[2]); const ownerLandId8 = await landContract.ownerOf(0); expect(ownerLandId8).to.equal(secondClaim.to); const ownerLandId9 = await landContract.ownerOf(1); expect(ownerLandId9).to.equal(secondClaim.to); const ownerLandId10 = await landContract.ownerOf(2); expect(ownerLandId10).to.equal(secondClaim.to); const ownerLandId11 = await landContract.ownerOf(3); expect(ownerLandId11).to.equal(secondClaim.to); const ownerLandId12 = await landContract.ownerOf(4); expect(ownerLandId12).to.equal(secondClaim.to); const ownerLandId13 = await landContract.ownerOf(5); expect(ownerLandId13).to.equal(secondClaim.to); }); it('User cannot claim allocated tokens from Giveaway contract more than once - multiple giveaways, 2 claims', async function () { const options = { mint: true, sand: true, multi: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; // make arrays of claims and proofs relevant to specific user const userProofs = []; const userClaims = []; const claim = allClaims[0][0]; const secondClaim = allClaims[1][0]; userClaims.push(claim); userClaims.push(secondClaim); for (let i = 0; i < userClaims.length; i++) { userProofs.push( allTrees[i].getProof(calculateMultiClaimHash(userClaims[i])) ); } const userMerkleRoots = []; userMerkleRoots.push(allMerkleRoots[0]); userMerkleRoots.push(allMerkleRoots[1]); const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await waitFor( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ); await expect( giveawayContractAsUser.claimMultipleTokensFromMultipleMerkleTree( userMerkleRoots, userClaims, userProofs ) ).to.be.revertedWith(`DESTINATION_ALREADY_CLAIMED`); }); }); describe('Multi_Giveaway_single_claim', function () { it('User cannot claim when test contract holds no tokens', async function () { const options = {}; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, // all claims from all giveaways allMerkleRoots, } = setUp; const tree = allTrees[0]; const claim = allClaims[0][0]; const proof = tree.getProof(calculateMultiClaimHash(claim)); const merkleRoot = allMerkleRoots[0]; const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.claimMultipleTokens(merkleRoot, claim, proof) ).to.be.revertedWith(`can't substract more than there is`); }); it('User cannot claim sand when contract does not hold any', async function () { const options = { mint: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; const tree = allTrees[0]; const claim = allClaims[0][0]; const proof = tree.getProof(calculateMultiClaimHash(claim)); const merkleRoot = allMerkleRoots[0]; const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await expect( giveawayContractAsUser.claimMultipleTokens(merkleRoot, claim, proof) ).to.be.revertedWith(`not enough fund`); }); it('User can claim allocated multiple tokens from Giveaway contract', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, assetContract, landContract, sandContract, allMerkleRoots, } = setUp; const tree = allTrees[0]; const claim = allClaims[0][0]; const proof = tree.getProof(calculateMultiClaimHash(claim)); const merkleRoot = allMerkleRoots[0]; const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const initBalanceAssetId1 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[0]); expect(initBalanceAssetId1).to.equal(claim.erc1155[0].values[0]); const initBalanceAssetId2 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[1]); expect(initBalanceAssetId2).to.equal(claim.erc1155[0].values[1]); const initBalanceAssetId3 = await assetContract[ 'balanceOf(address,uint256)' ](giveawayContract.address, claim.erc1155[0].ids[2]); expect(initBalanceAssetId3).to.equal(claim.erc1155[0].values[2]); const originalOwnerLandId1 = await landContract.ownerOf(0); expect(originalOwnerLandId1).to.equal(giveawayContract.address); const originalOwnerLandId2 = await landContract.ownerOf(1); expect(originalOwnerLandId2).to.equal(giveawayContract.address); const originalOwnerLandId3 = await landContract.ownerOf(2); expect(originalOwnerLandId3).to.equal(giveawayContract.address); const originalOwnerLandId4 = await landContract.ownerOf(3); expect(originalOwnerLandId4).to.equal(giveawayContract.address); const originalOwnerLandId5 = await landContract.ownerOf(4); expect(originalOwnerLandId5).to.equal(giveawayContract.address); const originalOwnerLandId6 = await landContract.ownerOf(5); expect(originalOwnerLandId6).to.equal(giveawayContract.address); const initialSandBalance = await sandContract.balanceOf(others[0]); expect(initialSandBalance).to.equal(0); await waitFor( giveawayContractAsUser.claimMultipleTokens(merkleRoot, claim, proof) ); const updatedSandBalance = await sandContract.balanceOf(others[0]); expect(updatedSandBalance).to.equal(claim.erc20.amounts[0]); const balanceAssetId1 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[0] ); expect(balanceAssetId1).to.equal(claim.erc1155[0].values[0]); const balanceAssetId2 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[1] ); expect(balanceAssetId2).to.equal(claim.erc1155[0].values[1]); const balanceAssetId3 = await assetContract['balanceOf(address,uint256)']( others[0], claim.erc1155[0].ids[2] ); expect(balanceAssetId3).to.equal(claim.erc1155[0].values[2]); const ownerLandId1 = await landContract.ownerOf(0); expect(ownerLandId1).to.equal(claim.to); const ownerLandId2 = await landContract.ownerOf(1); expect(ownerLandId2).to.equal(claim.to); const ownerLandId3 = await landContract.ownerOf(2); expect(ownerLandId3).to.equal(claim.to); const ownerLandId4 = await landContract.ownerOf(3); expect(ownerLandId4).to.equal(claim.to); const ownerLandId5 = await landContract.ownerOf(4); expect(ownerLandId5).to.equal(claim.to); const ownerLandId6 = await landContract.ownerOf(5); expect(ownerLandId6).to.equal(claim.to); }); it('Claimed Event is emitted for successful claim', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allClaims, allTrees, allMerkleRoots, } = setUp; const tree = allTrees[0]; const claim = allClaims[0][0]; const proof = tree.getProof(calculateMultiClaimHash(claim)); const merkleRoot = allMerkleRoots[0]; const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); const receipt = await waitFor( giveawayContractAsUser.claimMultipleTokens(merkleRoot, claim, proof) ); const claimedEvent = await expectReceiptEventWithArgs( receipt, 'ClaimedMultipleTokens' ); expect(claimedEvent.args[0]).to.equal(others[0]); // to expect(claimedEvent.args[1][0][0][0]).to.equal(claim.erc1155[0].ids[0]); expect(claimedEvent.args[1][0][0][1]).to.equal(claim.erc1155[0].ids[1]); expect(claimedEvent.args[1][0][0][2]).to.equal(claim.erc1155[0].ids[2]); expect(claimedEvent.args[1][0][1][0]).to.equal( claim.erc1155[0].values[0] ); expect(claimedEvent.args[1][0][1][1]).to.equal( claim.erc1155[0].values[1] ); expect(claimedEvent.args[1][0][1][2]).to.equal( claim.erc1155[0].values[2] ); expect(claimedEvent.args[1][0][2]).to.equal( claim.erc1155[0].contractAddress ); expect(claimedEvent.args[2][0][0][0]).to.equal(claim.erc721[0].ids[0]); expect(claimedEvent.args[2][0][0][1]).to.equal(claim.erc721[0].ids[1]); expect(claimedEvent.args[2][0][0][2]).to.equal(claim.erc721[0].ids[2]); expect(claimedEvent.args[2][0][0][3]).to.equal(claim.erc721[0].ids[3]); expect(claimedEvent.args[2][0][0][4]).to.equal(claim.erc721[0].ids[4]); expect(claimedEvent.args[2][0][0][5]).to.equal(claim.erc721[0].ids[5]); expect(claimedEvent.args[2][0][1]).to.equal( claim.erc721[0].contractAddress ); expect(claimedEvent.args[3][0][0]).to.equal(claim.erc20.amounts[0]); expect(claimedEvent.args[3][1][0]).to.equal( claim.erc20.contractAddresses[0] ); }); it('User cannot claim more than once', async function () { const options = { mint: true, sand: true, }; const setUp = await setupTestGiveaway(options); const { giveawayContract, others, allTrees, allClaims, allMerkleRoots, } = setUp; const tree = allTrees[0]; const claim = allClaims[0][0]; const proof = tree.getProof(calculateMultiClaimHash(claim)); const merkleRoot = allMerkleRoots[0]; const giveawayContractAsUser = await giveawayContract.connect( ethers.provider.getSigner(others[0]) ); await waitFor( giveawayContractAsUser.claimMultipleTokens(merkleRoot, claim, proof) ); await expect( giveawayContractAsUser.claimMultipleTokens(merkleRoot, claim, proof) ).to.be.revertedWith('DESTINATION_ALREADY_CLAIMED'); }); }); });
the_stack
* @module Polyface */ // import { Point2d } from "./Geometry2d"; /* eslint-disable @typescript-eslint/naming-convention, no-empty */ import { Transform } from "../geometry3d/Transform"; import { Matrix3d } from "../geometry3d/Matrix3d"; import { Point3d } from "../geometry3d/Point3dVector3d"; import { NumberArray } from "../geometry3d/PointHelpers"; // import { Geometry } from "./Geometry"; import { Range1d, Range3d } from "../geometry3d/Range"; /** The types of data that can be represented by an [[AuxChannelData]]. Each type of data contributes differently to the * animation applied by an [AnalysisStyle]($common) and responds differently when the host [[PolyfaceAuxData]] is transformed. * @public */ export enum AuxChannelDataType { /** General-purpose scalar values like stress, temperature, etc., used to recolor the [[Polyface]]'s vertices. * When the host Polyface is transformed, scalar values remain unmodified. */ Scalar = 0, /** Distances in meters used to recolor the [[Polyface]]'s vertices. * When the host [[Polyface]] is transformed the [[Transform]]'s scale is applied to the distances. */ Distance = 1, /** (X, Y, Z) displacement vectors added to the [[Polyface]]'s vertex positions resulting in deformation of the mesh. * When the host Polyface is transformed the displacements are rotated and scaled accordingly. */ Vector = 2, /** (X, Y, Z) normal vectors that replace the host [[Polyface]]'s own normals. * When the Polyface is transformed the normals are rotated accordingly. */ Normal = 3, } /** Represents the [[AuxChannel]] data at a single input value. * @public */ export class AuxChannelData { /** The input value for this data. */ public input: number; /** The vertex values for this data. A single value per vertex for scalar and distance types and 3 values (x,y,z) for normal or vector channels. */ public values: number[]; /** Construct a new [[AuxChannelData]] from input value and vertex values. */ constructor(input: number, values: number[] | Float64Array) { this.input = input; if (values instanceof Float64Array) { this.values = []; for (const v of values) this.values.push(v); } else this.values = values; } /** Copy blocks of size `blockSize` from (blocked index) `thisIndex` in this AuxChannelData to (blockIndex) `otherIndex` of `other` */ public copyValues(other: AuxChannelData, thisIndex: number, otherIndex: number, blockSize: number): void { for (let i = 0; i < blockSize; i++) this.values[thisIndex * blockSize + i] = other.values[otherIndex * blockSize + i]; } /** return a deep copy */ public clone(): AuxChannelData { return new AuxChannelData(this.input, this.values.slice()); } /** toleranced comparison of the `input` and `value` fields. * * Default tolerance is 1.0e-8 */ public isAlmostEqual(other: AuxChannelData, tol?: number): boolean { const tolerance = tol ? tol : 1.0E-8; return Math.abs(this.input - other.input) < tolerance && NumberArray.isAlmostEqual(this.values, other.values, tolerance); } } /** Represents a single [[PolyfaceAuxData]] channel. * @public */ export class AuxChannel { /** An array of [[AuxChannelData]] that represents the vertex data at one or more input values. */ public data: AuxChannelData[]; /** The type of data stored in this channel. */ public dataType: AuxChannelDataType; /** The channel name. This is used to present the [[AuxChannel]] to the user and also to select the [[AuxChannel]] for display from AnalysisStyle */ public name?: string; /** The input name. */ public inputName?: string; /** Create a [[AuxChannel]] */ public constructor(data: AuxChannelData[], dataType: AuxChannelDataType, name?: string, inputName?: string) { this.data = data; this.dataType = dataType; this.name = name; this.inputName = inputName; } /** Return a deep copy. */ public clone(): AuxChannel { const clonedData = []; for (const data of this.data) clonedData.push(data.clone()); return new AuxChannel(clonedData, this.dataType, this.name, this.inputName); } /** Toleranced comparison of contents. */ public isAlmostEqual(other: AuxChannel, tol?: number): boolean { if (this.dataType !== other.dataType || this.name !== other.name || this.inputName !== other.inputName || this.data.length !== other.data.length) return false; for (let i = 0; i < this.data.length; i++) if (!this.data[i].isAlmostEqual(other.data[i], tol)) return false; return true; } /** True if [[entriesPerValue]] is `1`. */ public get isScalar(): boolean { return this.dataType === AuxChannelDataType.Distance || this.dataType === AuxChannelDataType.Scalar; } /** The number of values in `data.values` per entry - 1 for scalar and distance types, 3 for normal and vector types. */ public get entriesPerValue(): number { return this.isScalar ? 1 : 3; } /** The number of entries in `data.values`. */ public get valueCount(): number { return 0 === this.data.length ? 0 : this.data[0].values.length / this.entriesPerValue; } /** The minimum and maximum values in `data.values`, or `undefined` if [[isScalar]] is false. */ public get scalarRange(): Range1d | undefined { if (!this.isScalar) return undefined; const range = Range1d.createNull(); for (const data of this.data) range.extendArray(data.values); return range; } /** Compute the range of this channel's displacement values, if [[dataType]] is [[AuxChannelDataType.Vector]]. * @param scale Scale by which to multiply each displacement. * @param result Preallocated object in which to store result. * @returns The range encompassing all this channel's displacements scaled by `scale`; or a null range if this channel does not contain displacements. */ public computeDisplacementRange(scale = 1, result?: Range3d): Range3d { result = Range3d.createNull(result); if (AuxChannelDataType.Vector === this.dataType) { for (const data of this.data) { const v = data.values; for (let i = 0; i < v.length; i += 3) result.extendXYZ(v[i] * scale, v[i + 1] * scale, v[i + 2] * scale); } } return result; } } /** The `PolyfaceAuxData` structure contains one or more analytical data channels for each vertex of a [[Polyface]], allowing the polyface to be styled * using an [AnalysisStyle]($common). * Typically a polyface will contain only vertex data required for its basic display: the vertex position, normal * and possibly texture parameter. `PolyfaceAuxData` provides supplemental data that is generally computed * in an analysis program or other external data source. This can be scalar data used to either override the vertex colors through, or * XYZ data used to deform the mesh by adjusting the vertex positions and/or normals. * @see [[PolyfaceData.auxData]] to associate auxiliary data with a polyface. * @public */ export class PolyfaceAuxData { /** Array with one or more channels of auxiliary data for the associated polyface. */ public channels: AuxChannel[]; /** The indices (shared by all data in all channels) mapping the data to the mesh facets. */ public indices: number[]; public constructor(channels: AuxChannel[], indices: number[]) { this.channels = channels; this.indices = indices; } /** Return a deep copy. */ public clone(): PolyfaceAuxData { const clonedChannels = this.channels.map((x) => x.clone()); return new PolyfaceAuxData(clonedChannels, this.indices.slice()); } /** Returns true if `this` is equivalent to `other` within `tolerance`. * The indices are compared for exact equality. The data in the channels are compared using `tolerance`, which defaults to 1.0e-8. */ public isAlmostEqual(other: PolyfaceAuxData, tolerance?: number): boolean { if (!NumberArray.isExactEqual(this.indices, other.indices) || this.channels.length !== other.channels.length) return false; for (let i = 0; i < this.channels.length; i++) if (!this.channels[i].isAlmostEqual(other.channels[i], tolerance)) return false; return true; } /** Returns true if both `left` and `right` are undefined, or both are defined and equivalent within `tolerance` (default: 1.0e-8). */ public static isAlmostEqual(left: PolyfaceAuxData | undefined, right: PolyfaceAuxData | undefined, tol?: number): boolean { if (left === right) // This catches double undefined !!! return true; if (left && right) return left.isAlmostEqual(right, tol); return false; } /** Create a PolyfaceAuxData for use by a [[PolyfaceVisitor]]. */ public createForVisitor(): PolyfaceAuxData { const visitorChannels: AuxChannel[] = []; for (const parentChannel of this.channels) { const visitorChannelData: AuxChannelData[] = []; for (const parentChannelData of parentChannel.data) visitorChannelData.push(new AuxChannelData(parentChannelData.input, [])); visitorChannels.push(new AuxChannel(visitorChannelData, parentChannel.dataType, parentChannel.name, parentChannel.inputName)); } return new PolyfaceAuxData(visitorChannels, []); } /** Apply `transform` to the data in each channel. * @see [[AuxChannelDataType]] for details regarding how each data type is affected by the transform. * @note This method may fail if a channel of [[AuxChannelDataType.Normal]] exists and `transform.matrix` is non-invertible. * @returns true if the channels were all successfully transformed. */ public tryTransformInPlace(transform: Transform): boolean { let inverseRot: Matrix3d | undefined; const rot = transform.matrix; const det = rot.determinant(); const scale = Math.pow(Math.abs(det), 1 / 3) * (det >= 0 ? 1 : -1); for (const channel of this.channels) { for (const data of channel.data) { switch (channel.dataType) { case AuxChannelDataType.Scalar: continue; case AuxChannelDataType.Distance: { for (let i = 0; i < data.values.length; i++) data.values[i] *= scale; break; } case AuxChannelDataType.Normal: { inverseRot = inverseRot ?? rot.inverse(); if (!inverseRot) return false; transformPoints(data.values, (point) => inverseRot!.multiplyTransposeVectorInPlace(point)); break; } case AuxChannelDataType.Vector: { transformPoints(data.values, (point) => rot.multiplyVectorInPlace(point)); break; } } } } return true; } } function transformPoints(coords: number[], transform: (point: Point3d) => void): void { const point = new Point3d(); for (let i = 0; i < coords.length; i += 3) { point.set(coords[i], coords[i + 1], coords[i + 2]); transform(point); coords[i] = point.x; coords[i + 1] = point.y; coords[i + 2] = point.z; } }
the_stack
namespace gdjs { export namespace evtTools { export namespace firebaseTools { /** * Firebase Authentication Event Tools. * @namespace */ export namespace auth { type ProviderClass = | typeof firebase.auth.GoogleAuthProvider | typeof firebase.auth.FacebookAuthProvider | typeof firebase.auth.GithubAuthProvider | typeof firebase.auth.TwitterAuthProvider; type ProviderInstance = | firebase.auth.GoogleAuthProvider_Instance | firebase.auth.FacebookAuthProvider_Instance | firebase.auth.GithubAuthProvider_Instance | firebase.auth.TwitterAuthProvider_Instance; type ProviderName = 'google' | 'facebook' | 'github' | 'twitter'; /** * Table of available external providers. */ const providersList: Record<ProviderName, ProviderClass> = { google: firebase.auth.GoogleAuthProvider, facebook: firebase.auth.FacebookAuthProvider, github: firebase.auth.GithubAuthProvider, twitter: firebase.auth.TwitterAuthProvider, }; /** * The actual current token. */ let _token = ''; /** * The current auth provider for reauthenticating. */ let _currentProvider: ProviderInstance | null = null; /** * The current authentication status. */ export let authentified = false; /** * The logged-in users data. */ export let currentUser: firebase.User | null = null; /** * A namespace containing tools for managing the current user. * @namespace */ export namespace userManagement { /** * Contains dangerous management functions. Requires reauthentication before usage. * @namespace */ export namespace dangerous { /** * Changes the users email. * Use this when using basic auth. * @param oldEmail - Old email for reauthentication. * @param password - Old password for reauthentication. * @param newEmail - New email for the user. * @param [sendVerificationEmail] - Send a verification email to the old address before changing the email? * @param [callbackStateVariable] - The variable where to store the result. */ export const changeEmail = ( oldEmail: string, password: string, newEmail: string, sendVerificationEmail: boolean = true, callbackStateVariable?: gdjs.Variable ) => { if (!currentUser) return; const credential = firebase.auth.EmailAuthProvider.credential( oldEmail, password ); const updater = sendVerificationEmail ? currentUser.updateEmail : currentUser.verifyBeforeUpdateEmail; currentUser .reauthenticateWithCredential(credential) .then(() => updater(newEmail)) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Changes the users password. * Use this when using basic auth. * @param email - Old email for reauthentication. * @param oldPassword - Old password for reauthentication. * @param newPassword - New password for the user. * @param [callbackStateVariable] - The variable where to store the result. */ export const changePassword = ( email: string, oldPassword: string, newPassword: string, callbackStateVariable?: gdjs.Variable ) => { if (!currentUser) return; const credential = firebase.auth.EmailAuthProvider.credential( email, oldPassword ); currentUser .reauthenticateWithCredential(credential) .then(() => (currentUser as firebase.User).updatePassword(newPassword) ) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Deletes the current user. * Use this when using basic auth. * @param email - Old email for reauthentication. * @param password - Old password for reauthentication. * @param [callbackStateVariable] - The variable where to store the result. */ export const deleteUser = ( email: string, password: string, callbackStateVariable?: gdjs.Variable ) => { if (!currentUser) return; const credential = firebase.auth.EmailAuthProvider.credential( email, password ); currentUser .reauthenticateWithCredential(credential) .then(() => (currentUser as firebase.User).delete()) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Changes the users email. * Use this when using an external provider. * @param newEmail - New email for the user. * @param sendVerificationEmail - Send a verification email to the old address before changing the email? * @param [callbackStateVariable] - The variable where to store the result. */ export const changeEmailProvider = ( newEmail: string, sendVerificationEmail: boolean, callbackStateVariable?: gdjs.Variable ) => { if (!currentUser || !_currentProvider) return; const updater = sendVerificationEmail ? currentUser.updateEmail : currentUser.verifyBeforeUpdateEmail; currentUser .reauthenticateWithPopup(_currentProvider) .then(() => updater(newEmail)) .then(() => { if (typeof callbackStateVariable !== 'undefined') { callbackStateVariable.setString('ok'); } }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') { callbackStateVariable.setString(error.message); } }); }; /** * Changes the users password. * Use this when using an external provider. * @param newPassword - New password for the user. * @param [callbackStateVariable] - The variable where to store the result. */ export const changePasswordProvider = ( newPassword: string, callbackStateVariable?: gdjs.Variable ) => { if (currentUser && _currentProvider) currentUser .reauthenticateWithPopup(_currentProvider) .then(() => (currentUser as firebase.User).updatePassword(newPassword) ) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Deletes the current user. * Use this when using an external provider. * @param [callbackStateVariable] - The variable where to store the result. */ export const deleteUserProvider = ( callbackStateVariable?: gdjs.Variable ) => { if (currentUser && _currentProvider) currentUser .reauthenticateWithPopup(_currentProvider) .then(() => (currentUser as firebase.User).delete()) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; } /** * Verifies if the current users email is verified. */ export const isEmailVerified = (): boolean => currentUser ? currentUser.emailVerified : false; /** * Gets the users email address. */ export const getEmail = (): string => currentUser ? currentUser.email || '' : ''; /** * Gets the creation date of the logged in users account. */ export const getCreationTime = (): string => currentUser ? currentUser.metadata.creationTime || '' : ''; /** * Gets the last login date of the logged in users account. */ export const getLastLoginTime = (): string => currentUser ? currentUser.metadata.lastSignInTime || '' : ''; /** * Gets the display name of the current user. */ export const getDisplayName = (): string => currentUser ? currentUser.displayName || '' : ''; /** * Gets the current users phone number. */ export const getPhoneNumber = (): string => currentUser ? currentUser.phoneNumber || '' : ''; /** * Gets the current users Unique IDentifier. */ export const getUID = (): string => currentUser ? currentUser.uid || '' : ''; /** * Gets the tenant ID. * For advanced usage only. */ export const getTenantID = (): string => currentUser ? currentUser.tenantId || '' : ''; /** * Gets the refresh token. * For advanced usage only. */ export const getRefreshToken = (): string => currentUser ? currentUser.refreshToken || '' : ''; /** * Gets the users profile picture URL. */ export const getPhotoURL = (): string => currentUser ? currentUser.photoURL || '' : ''; /** * Changes the display name of an user. */ export const setDisplayName = (newDisplayName: string) => { if (currentUser) return currentUser.updateProfile({ displayName: newDisplayName, }); return Promise.reject('Sign in before setting displayName'); }; /** * Changes the URL to the profile picture of the user. */ export const setPhotoURL = (newPhotoURL: string) => { if (currentUser) return currentUser.updateProfile({ photoURL: newPhotoURL, }); return Promise.reject('Sign in before setting photoURL'); }; /** * Send an email to the users email adress to verify it. * @note Even though this function is redundant, we keep it for consistency. * @see currentUser.sendEmailVerification */ export const sendVerificationEmail = () => currentUser ? currentUser.sendEmailVerification() : ''; } /** * Get the logged-in users authentication token. * Tries to refresh it everytime the function is called. */ export const token = (): string => { if (currentUser) currentUser.getIdToken().then((token) => (_token = token)); return _token; }; /** * Returns true if the user is currently authentified. * @see authentified */ export const isAuthentified = (): boolean => authentified; /** * Signs the user in with basic email-password authentication. * @param email - The users email. * @param password - The users password. * @param [callbackStateVariable] - The variable where to store the result. */ export const signInWithEmail = ( email: string, password: string, callbackStateVariable?: gdjs.Variable ) => firebase .auth() .signInWithEmailAndPassword(email, password) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); /** * Creates an account with basic email-password authentication. * @param email - The users email. * @param password - The users password. * @param [callbackStateVariable] - The variable where to store the result. */ export const createAccountWithEmail = ( email: string, password: string, callbackStateVariable?: gdjs.Variable ) => firebase .auth() .createUserWithEmailAndPassword(email, password) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); /** * Login with a temporary account. * @param [callbackStateVariable] - The variable where to store the result. */ export const anonymSignIn = (callbackStateVariable?: gdjs.Variable) => firebase .auth() .signInAnonymously() .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); /** * Signs the user in with an external provider. * Only works on the web, NOT on Electron/Cordova. * @param providerName - The external provider to use. * @param [callbackStateVariable] - The variable where to store the result. */ export const signInWithProvider = function ( providerName: ProviderName, callbackStateVariable?: gdjs.Variable ) { _currentProvider = new providersList[providerName](); firebase .auth() .signInWithPopup(_currentProvider) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; // Listen to authentication state changes to regenerate tokens and keep the user and the authenticated state up to date firebaseTools.onAppCreated.push(() => { firebase.auth().onAuthStateChanged((user) => { if (user) { authentified = true; currentUser = user; user.getIdToken().then( // Prefetch the token (token) => (_token = token) ); } else { authentified = false; currentUser = null; } }); }); } } } }
the_stack
import React from 'react'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import noop from 'lodash/noop'; import * as tokens from '@thumbtack/thumbprint-tokens'; import { TextButton } from '../Button/index'; import StickyFooter from './components/sticky-footer'; import Transition from './components/transition'; import ModalCurtain from '../ModalCurtain/index'; import styles from './index.module.scss'; type StickyContext = { stickyFooterContainerRef: React.RefObject<HTMLDivElement> | null; setSticky: (isSticky: boolean) => void; }; const { Provider, Consumer } = React.createContext<StickyContext>({ stickyFooterContainerRef: null, setSticky: noop, }); // These values are duplicated in the Sass. const TRANSITION_OPEN_SPEED = tokens.tpDuration5; const TRANSITION_CLOSE_SPEED = tokens.tpDuration4; /** * `ModalAnimatedWrapper` is an exported component that we export for developers that want access to * `Modal` without padding and a close button. We export it as a named export instead of * creating a `hasNoPadding` prop partly to discourage the use of `Modal` without padding. * * This component uses `ModalCurtain` and includes the backdrop, transition, and white modal * wrapper that is available at a few widths. */ const ModalAnimatedWrapper = ({ children, isOpen = false, onCloseClick, onCloseFinish, onOpenFinish, shouldCloseOnCurtainClick = true, width = 'medium', heightAboveSmall = 'auto', shouldPageScrollAboveSmall = true, }: ModalAnimatedWrapperPropTypes): JSX.Element => ( <Transition in={isOpen} timeout={{ enter: TRANSITION_OPEN_SPEED, exit: TRANSITION_CLOSE_SPEED, }} onEntered={onOpenFinish} onExited={onCloseFinish} > {(transitionStage): JSX.Element => ( <ModalCurtain stage={transitionStage} onCloseClick={onCloseClick}> {({ curtainClassName, curtainOnClick }): JSX.Element => ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions <div className={classNames({ [curtainClassName]: true, [styles.curtain]: true, [styles.curtainOpen]: isOpen, })} > {/* Extra nested <div> to prevent curtain's bottom padding from being ignored in Firefox and Edge (See #376 and https://github.com/w3c/csswg-drafts/issues/129) onClick listener is attached to this innermost node that constitutes curtain */} {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */} <div className={classNames({ [styles.curtainInner]: true, [styles.curtainInnerShouldPageScrollAboveSmall]: shouldPageScrollAboveSmall, })} onClick={shouldCloseOnCurtainClick ? curtainOnClick : undefined} data-test="thumbprint-modal-curtain" > <div className={classNames({ [styles.wrapper]: true, [styles.wrapperOpen]: isOpen, [styles.wrapperWide]: width === 'wide', [styles.wrapperNarrow]: width === 'narrow', [styles.wrapperMedium]: width === 'medium', [styles.wrapperHeightMedium]: heightAboveSmall === 'medium', [styles.wrapperHeightTall]: heightAboveSmall === 'tall', [styles.wrapperShouldPageScrollAboveSmall]: shouldPageScrollAboveSmall, })} data-test="thumbprint-modal-wrapper" > <div className={classNames({ [styles.container]: true, })} data-test="thumbprint-modal-container" > {children} </div> </div> </div> </div> )} </ModalCurtain> )} </Transition> ); interface ModalAnimatedWrapperPropTypes { /** * Content that appears within the modal. */ children?: React.ReactNode; /** * Function that fires to close the modal. */ onCloseClick: () => void; /** * Function that fires once the modal has opened and transitions have ended. */ onOpenFinish?: () => void; /** * Function that fires once the modal has closed and transitions have ended. */ onCloseFinish?: () => void; /** * Determines if the modal should close when clicking on the curtain, outside of the `children`. */ shouldCloseOnCurtainClick?: boolean; /** * Allows the page to scroll vertically at viewports larger than the small breakpoint. If * `false`, the modal will always be equal to or smaller than the viewport and the contents * of the modal will scroll, not the page itself. */ shouldPageScrollAboveSmall?: boolean; /** * Should the modal appear open. */ isOpen?: boolean; /** * Sets the max-width of the modal container. */ width?: 'narrow' | 'medium' | 'wide'; /** * Sets height of the modal container above small viewport. * If `auto` (default), the modal height will be determined by its content. * Otherwise, the modal height will be fixed at some constant px. */ heightAboveSmall?: 'auto' | 'medium' | 'tall'; } interface ModalHeaderPropTypes { /** * Content (usually a `ModalTitle` and `ModalDescription`) that appears at the top of the * modal. */ children: React.ReactNode; } interface ModalTitlePropTypes { /** * Text that describes the modal contents. It is intended for use within the `ModalHeader`. */ children: string; } interface ModalDescriptionPropTypes { /** * Text intended for use below a `ModalTitle` and within a `ModalHeader`. */ children: React.ReactNode; } interface ModalContentPropTypes { /** * Content (usually a form) that makes up the main part of the modal. */ children: React.ReactNode; } interface ModalContentFullBleedPropTypes { /** * Content (usually a form) that makes up the main part of the modal. */ children: React.ReactNode; /** * Allows the React `className` prop to be passed through to the rendered element. */ className?: string; /** * Allows the React `style` prop to be passed through to the rendered element. */ style?: React.CSSProperties; } interface ModalFooterPropTypes { /** * Content (ususally buttons) to render within the footer. */ children: React.ReactNode; /** * Attaches the footer to the bottom of the modal below the small breakpoint. */ isSticky?: boolean; } interface ModalPropTypes { /** * Content that appears within the modal. */ children?: React.ReactNode; /** * Function that fires to close the modal. */ onCloseClick: () => void; /** * Function that fires once the modal has opened and transitions have ended. */ onOpenFinish?: () => void; /** * Function that fires once the modal has closed and transitions have ended. */ onCloseFinish?: () => void; /** * Determines if the close button should be rendered. This is generally discouraged and should * be used carefully. If used, the contents passed into the modal must contain a focusable * element such as a link or button. */ shouldHideCloseButton?: boolean; /** * Determines if the modal should close when clicking on the curtain, outside of the `children`. */ shouldCloseOnCurtainClick?: boolean; /** * Should the modal appear open. */ isOpen?: boolean; /** * Sets the max-width of the modal container. */ width?: 'narrow' | 'medium' | 'wide'; /** * Sets height of the modal container above small viewport. * If `auto` (default), the modal height will be determined by its content. * Otherwise, the modal height will be fixed at some constant px. */ heightAboveSmall?: 'auto' | 'medium' | 'tall'; } const ModalHeader = ({ children }: ModalHeaderPropTypes): JSX.Element => ( <div className={styles.modalHeader}>{children}</div> ); const ModalTitle = ({ children }: ModalTitlePropTypes): JSX.Element => ( <div className={styles.modalTitle}>{children}</div> ); const ModalDescription = ({ children }: ModalDescriptionPropTypes): JSX.Element => ( <div className={styles.modalDescription}>{children}</div> ); const ModalContent = ({ children }: ModalContentPropTypes): JSX.Element => ( <div className={styles.modalContent}>{children}</div> ); const ModalContentFullBleed = ({ children, className = '', style = {}, }: ModalContentFullBleedPropTypes): JSX.Element => ( <div className={classNames(className, styles.modalContentFullBleed)} style={style}> {children} </div> ); class ModalFooter extends React.Component<ModalFooterPropTypes, { isClient: boolean }> { constructor(props: ModalFooterPropTypes) { super(props); this.state = { isClient: false, }; } componentDidMount(): void { this.setState({ isClient: true, }); } render(): JSX.Element | null { const { isClient } = this.state; const { isSticky, children } = this.props; if (!isClient) { return null; } return ( <Consumer> {({ stickyFooterContainerRef, setSticky }): JSX.Element => { // When `isSticky` is true, the `ModalFooter` must change its position in the // DOM so that it is fixed at the bottom of the modal on small viewports. We // use React's Context API so that it is a property of the `ModalFooter` // component and not the `Modal` API. // // `stickyFooterContainerRef` is the DOM element where the sticky footer will // render. `setSticky` is a function that updates the state in `Modal`, // changing the CSS to make the contents scroll and the footer fixed at the // bottom. if ( !isSticky || stickyFooterContainerRef === null || stickyFooterContainerRef.current === null ) { return <div className={styles.modalFooterFluid}>{children}</div>; } // We have to create a separate component here because `setSticky` updates // state in `Modal` and state updates are not allowed within `render`. // Moving it to a separate component allows us to call it within // `componentDidMount`. // https://blog.kentcdodds.com/answers-to-common-questions-about-render-props-a9f84bb12d5d#6a05 return ReactDOM.createPortal( <StickyFooter setSticky={setSticky}>{children}</StickyFooter>, stickyFooterContainerRef.current, ); }} </Consumer> ); } } interface ModalStateTypes { hasStickyFooter: boolean; stickyFooterContainerRef: React.RefObject<HTMLDivElement> | null; } class Modal extends React.Component<ModalPropTypes, ModalStateTypes> { constructor(props: ModalPropTypes) { super(props); this.state = { hasStickyFooter: false, stickyFooterContainerRef: React.createRef<HTMLDivElement>(), }; this.setSticky = this.setSticky.bind(this); } setSticky(newVal: boolean): void { const { hasStickyFooter } = this.state; if (newVal !== hasStickyFooter) { this.setState({ hasStickyFooter: newVal, }); } } render(): JSX.Element { const { children, isOpen = false, onCloseClick, onCloseFinish, onOpenFinish, shouldCloseOnCurtainClick = true, shouldHideCloseButton = false, width = 'medium', heightAboveSmall = 'auto', } = this.props; const { hasStickyFooter, stickyFooterContainerRef } = this.state; return ( <ModalAnimatedWrapper onCloseClick={onCloseClick} onOpenFinish={onOpenFinish} onCloseFinish={onCloseFinish} shouldCloseOnCurtainClick={shouldCloseOnCurtainClick} isOpen={isOpen} width={width} heightAboveSmall={heightAboveSmall} // We allow the modal to grow taller than the page only if there is no sticky // footer. This means that the page can scroll vertically when the modal contents // are tall enough. If we have a sticky footer, we prevent the modal from getting // taller than the viewport so that the footer can always appear at the bottom. // In this case, the inside of the modal itself will scroll vertically as needed. shouldPageScrollAboveSmall={!hasStickyFooter} > <Provider value={{ stickyFooterContainerRef, setSticky: this.setSticky, }} > <div className={styles.contents}> {/* Extra nested <div> to prevent bottom padding from being ignored in Firefox and Edge (See #376 and https://github.com/w3c/csswg-drafts/issues/129) */} <div className={classNames(styles.contentsPadding, { [styles.contentsPaddingNotSticky]: !hasStickyFooter, })} > {children} </div> </div> {/* If a user uses `<ModalFooter isSticky />`, it gets moved here with React portals. */} <div ref={stickyFooterContainerRef} /> {/* The close button is last in the DOM so that it is not focused first by the focus trap. We visually position it at the top with flexbox. */} <div className={classNames({ [styles.closeButton]: true, [styles.closeButtonNotSticky]: !hasStickyFooter, })} > {shouldHideCloseButton === false && ( <TextButton accessibilityLabel="Close modal" dataTest="close-modal" iconLeft={ <svg viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round" className={styles.closeButtonIcon} > <line x1="18" y1="6" x2="6" y2="18" /> <line x1="6" y1="6" x2="18" y2="18" /> </svg> } onClick={onCloseClick} theme="inherit" /> )} </div> </Provider> </ModalAnimatedWrapper> ); } } export default Modal; export { ModalHeader, ModalTitle, ModalDescription, ModalContent, ModalContentFullBleed, ModalFooter, ModalAnimatedWrapper, };
the_stack
import {Routes} from '@angular/router'; import {DevApp404} from './dev-app/dev-app-404'; import {DevAppHome} from './dev-app/dev-app-home'; export const DEV_APP_ROUTES: Routes = [ {path: '', component: DevAppHome}, { path: 'autocomplete', loadComponent: () => import('./autocomplete/autocomplete-demo').then(m => m.AutocompleteDemo), }, { path: 'badge', loadComponent: () => import('./badge/badge-demo').then(m => m.BadgeDemo), }, { path: 'bottom-sheet', loadComponent: () => import('./bottom-sheet/bottom-sheet-demo').then(m => m.BottomSheetDemo), }, { path: 'baseline', loadComponent: () => import('./baseline/baseline-demo').then(m => m.BaselineDemo), }, { path: 'button', loadComponent: () => import('./button/button-demo').then(m => m.ButtonDemo), }, { path: 'button-toggle', loadComponent: () => import('./button-toggle/button-toggle-demo').then(m => m.ButtonToggleDemo), }, { path: 'card', loadComponent: () => import('./card/card-demo').then(m => m.CardDemo), }, { path: 'cdk-experimental-combobox', loadComponent: () => import('./cdk-experimental-combobox/cdk-combobox-demo').then(m => m.CdkComboboxDemo), }, { path: 'cdk-dialog', loadComponent: () => import('./cdk-dialog/dialog-demo').then(m => m.DialogDemo), }, { path: 'cdk-experimental-listbox', loadComponent: () => import('./cdk-experimental-listbox/cdk-listbox-demo').then(m => m.CdkListboxDemo), }, { path: 'cdk-menu', loadComponent: () => import('./cdk-menu/cdk-menu-demo').then(m => m.CdkMenuDemo), }, { path: 'checkbox', loadComponent: () => import('./checkbox/checkbox-demo').then(m => m.CheckboxDemo), }, { path: 'chips', loadComponent: () => import('./chips/chips-demo').then(m => m.ChipsDemo), }, { path: 'clipboard', loadComponent: () => import('./clipboard/clipboard-demo').then(m => m.ClipboardDemo), }, { path: 'column-resize', loadComponent: () => import('./column-resize/column-resize-home').then(m => m.ColumnResizeHome), }, { path: 'datepicker', loadComponent: () => import('./datepicker/datepicker-demo').then(m => m.DatepickerDemo), }, { path: 'dialog', loadComponent: () => import('./dialog/dialog-demo').then(m => m.DialogDemo), }, { path: 'drawer', loadComponent: () => import('./drawer/drawer-demo').then(m => m.DrawerDemo), }, { path: 'drag-drop', loadComponent: () => import('./drag-drop/drag-drop-demo').then(m => m.DragAndDropDemo), }, { path: 'expansion', loadComponent: () => import('./expansion/expansion-demo').then(m => m.ExpansionDemo), }, { path: 'focus-origin', loadComponent: () => import('./focus-origin/focus-origin-demo').then(m => m.FocusOriginDemo), }, { path: 'focus-trap', loadComponent: () => import('./focus-trap/focus-trap-demo').then(m => m.FocusTrapDemo), }, { path: 'google-map', loadComponent: () => import('./google-map/google-map-demo').then(m => m.GoogleMapDemo), }, { path: 'grid-list', loadComponent: () => import('./grid-list/grid-list-demo').then(m => m.GridListDemo), }, { path: 'icon', loadComponent: () => import('./icon/icon-demo').then(m => m.IconDemo), }, { path: 'input', loadComponent: () => import('./input/input-demo').then(m => m.InputDemo), }, { path: 'layout', loadComponent: () => import('./layout/layout-demo').then(m => m.LayoutDemo), }, { path: 'input-modality', loadComponent: () => import('./input-modality/input-modality-detector-demo').then( m => m.InputModalityDetectorDemo, ), }, { path: 'list', loadComponent: () => import('./list/list-demo').then(m => m.ListDemo), }, { path: 'live-announcer', loadComponent: () => import('./live-announcer/live-announcer-demo').then(m => m.LiveAnnouncerDemo), }, { path: 'menubar', loadComponent: () => import('./menubar/mat-menubar-demo').then(m => m.MatMenuBarDemo), }, { path: 'mdc-autocomplete', loadComponent: () => import('./mdc-autocomplete/mdc-autocomplete-demo').then(m => m.MdcAutocompleteDemo), }, { path: 'mdc-button', loadComponent: () => import('./mdc-button/mdc-button-demo').then(m => m.MdcButtonDemo), }, { path: 'mdc-card', loadComponent: () => import('./mdc-card/mdc-card-demo').then(m => m.MdcCardDemo), }, { path: 'mdc-checkbox', loadComponent: () => import('./mdc-checkbox/mdc-checkbox-demo').then(m => m.MdcCheckboxDemo), }, { path: 'mdc-progress-bar', loadComponent: () => import('./mdc-progress-bar/mdc-progress-bar-demo').then(m => m.MdcProgressBarDemo), }, { path: 'mdc-chips', loadComponent: () => import('./mdc-chips/mdc-chips-demo').then(m => m.MdcChipsDemo), }, { path: 'mdc-dialog', loadComponent: () => import('./mdc-dialog/mdc-dialog-demo').then(m => m.DialogDemo), }, { path: 'mdc-input', loadComponent: () => import('./mdc-input/mdc-input-demo').then(m => m.MdcInputDemo), }, { path: 'mdc-list', loadComponent: () => import('./mdc-list/mdc-list-demo').then(m => m.MdcListDemo), }, { path: 'mdc-menu', loadComponent: () => import('./mdc-menu/mdc-menu-demo').then(m => m.MdcMenuDemo), }, { path: 'mdc-paginator', loadComponent: () => import('./mdc-paginator/mdc-paginator-demo').then(m => m.MdcPaginatorDemo), }, { path: 'mdc-progress-spinner', loadComponent: () => import('./mdc-progress-spinner/mdc-progress-spinner-demo').then( m => m.MdcProgressSpinnerDemo, ), }, { path: 'mdc-radio', loadComponent: () => import('./mdc-radio/mdc-radio-demo').then(m => m.MdcRadioDemo), }, { path: 'mdc-select', loadComponent: () => import('./mdc-select/mdc-select-demo').then(m => m.MdcSelectDemo), }, { path: 'mdc-snack-bar', loadComponent: () => import('./mdc-snack-bar/mdc-snack-bar-demo').then(m => m.MdcSnackBarDemo), }, { path: 'mdc-slide-toggle', loadComponent: () => import('./mdc-slide-toggle/mdc-slide-toggle-demo').then(m => m.MdcSlideToggleDemo), }, { path: 'mdc-slider', loadComponent: () => import('./mdc-slider/mdc-slider-demo').then(m => m.MdcSliderDemo), }, { path: 'mdc-table', loadComponent: () => import('./mdc-table/mdc-table-demo').then(m => m.MdcTableDemo), }, { path: 'mdc-tabs', loadComponent: () => import('./mdc-tabs/mdc-tabs-demo').then(m => m.MdcTabsDemo), }, { path: 'mdc-tooltip', loadComponent: () => import('./mdc-tooltip/mdc-tooltip-demo').then(m => m.MdcTooltipDemo), }, { path: 'menu', loadComponent: () => import('./menu/menu-demo').then(m => m.MenuDemo), }, { path: 'paginator', loadComponent: () => import('./paginator/paginator-demo').then(m => m.PaginatorDemo), }, { path: 'platform', loadComponent: () => import('./platform/platform-demo').then(m => m.PlatformDemo), }, { path: 'popover-edit', loadComponent: () => import('./popover-edit/popover-edit-demo').then(m => m.PopoverEditDemo), }, { path: 'portal', loadComponent: () => import('./portal/portal-demo').then(m => m.PortalDemo), }, { path: 'progress-bar', loadComponent: () => import('./progress-bar/progress-bar-demo').then(m => m.ProgressBarDemo), }, { path: 'progress-spinner', loadComponent: () => import('./progress-spinner/progress-spinner-demo').then(m => m.ProgressSpinnerDemo), }, { path: 'radio', loadComponent: () => import('./radio/radio-demo').then(m => m.RadioDemo), }, { path: 'ripple', loadComponent: () => import('./ripple/ripple-demo').then(m => m.RippleDemo), }, { path: 'select', loadComponent: () => import('./select/select-demo').then(m => m.SelectDemo), }, { path: 'sidenav', loadComponent: () => import('./sidenav/sidenav-demo').then(m => m.SidenavDemo), }, { path: 'slide-toggle', loadComponent: () => import('./slide-toggle/slide-toggle-demo').then(m => m.SlideToggleDemo), }, { path: 'slider', loadComponent: () => import('./slider/slider-demo').then(m => m.SliderDemo), }, { path: 'snack-bar', loadComponent: () => import('./snack-bar/snack-bar-demo').then(m => m.SnackBarDemo), }, { path: 'stepper', loadComponent: () => import('./stepper/stepper-demo').then(m => m.StepperDemo), }, { path: 'table', loadComponent: () => import('./table/table-demo').then(m => m.TableDemo), }, { path: 'table-scroll-container', loadComponent: () => import('./table-scroll-container/table-scroll-container-demo').then( m => m.TableScrollContainerDemo, ), }, { path: 'tabs', loadComponent: () => import('./tabs/tabs-demo').then(m => m.TabsDemo), }, { path: 'toolbar', loadComponent: () => import('./toolbar/toolbar-demo').then(m => m.ToolbarDemo), }, { path: 'tooltip', loadComponent: () => import('./tooltip/tooltip-demo').then(m => m.TooltipDemo), }, { path: 'tree', loadComponent: () => import('./tree/tree-demo').then(m => m.TreeDemo), }, { path: 'typography', loadComponent: () => import('./typography/typography-demo').then(m => m.TypographyDemo), }, { path: 'screen-type', loadComponent: () => import('./screen-type/screen-type-demo').then(m => m.ScreenTypeDemo), }, { path: 'connected-overlay', loadComponent: () => import('./connected-overlay/connected-overlay-demo').then(m => m.ConnectedOverlayDemo), }, { path: 'virtual-scroll', loadComponent: () => import('./virtual-scroll/virtual-scroll-demo').then(m => m.VirtualScrollDemo), }, { path: 'youtube-player', loadComponent: () => import('./youtube-player/youtube-player-demo').then(m => m.YouTubePlayerDemo), }, { path: 'selection', loadComponent: () => import('./selection/selection-demo').then(m => m.SelectionDemo), }, { path: 'examples', loadComponent: () => import('./examples-page/examples-page').then(m => m.ExamplesPage), }, {path: '**', component: DevApp404}, ];
the_stack
import * as angular from 'angular'; describe('navbar: <uif-nav-bar />', () => { beforeEach(() => { angular.mock.module('officeuifabric.core'); angular.mock.module('officeuifabric.components.navbar'); }); describe('regular navbar tests', () => { let $element: JQuery; let $scope: any; beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => { $element = angular.element(` <uif-nav-bar> <uif-nav-bar-search placeholder="search for smth" uif-on-search="onSearchCallback(search)"> </uif-nav-bar-search> <uif-nav-bar-item uif-text="'Home'" ng-click="logClick('Home item clicked')"></uif-nav-bar-item> <uif-nav-bar-item uif-type="menu"> <uif-content><uif-icon uif-type="arrowRight"></uif-icon>Sub Menu</uif-content> <uif-contextual-menu> <uif-contextual-menu-item uif-text="'Delete'"></uif-contextual-menu-item> <uif-contextual-menu-item uif-text="'Flag'"></uif-contextual-menu-item> </uif-contextual-menu-item> </uif-nav-bar-item> <uif-nav-bar-item uif-text="'Root'" disabled="disabled"></uif-nav-bar-item> </uif-nav-bar>`); $scope = $rootScope; $scope.sub = {}; $compile($element)($scope); $element = jQuery($element[0]); $scope.$apply(); })); it('should not to have \'href\' attribute', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').last(); let navBarLink: JQuery = link.find('.ms-NavBar-link'); expect(navBarLink).not.toHaveAttr('href'); })); it('should select menu which is clicked', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').first(); link.click(); $scope.$apply(); expect(link).toHaveClass('is-selected'); })); it('should render enhanced menu item', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').eq(1); let content: JQuery = link.find('span.uif-content'); expect(content.length).toEqual(1); })); it('should render enhanced menu item with icon', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').eq(1); let icon: JQuery = link.find('span.uif-content .ms-Icon'); expect(icon.length).toEqual(1); })); it('should execute click handler', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { $scope.logClick = () => { // }; spyOn($scope, 'logClick'); let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').first(); link.click(); $scope.$apply(); expect($scope.logClick).toHaveBeenCalled(); })); it('should open search by clicking on icon', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-item--search').first(); link.click(); $scope.$apply(); expect(link).toHaveClass('is-selected'); expect(link).toHaveClass('is-open'); })); it('should trigger on search event with correct text by click', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { $scope.onSearchCallback = (search: string) => { console.log(search); }; spyOn($scope, 'onSearchCallback'); let link: JQuery = $element.find('.ms-NavBar-item--search').first(); link.click(); $scope.$apply(); let textbox: JQuery = link.find('.ms-TextField-field').first(); let searchText: string = 'search data'; textbox.val(searchText); angular.element(textbox[0]).triggerHandler('input'); $scope.$apply(); link.click(); $scope.$apply(); expect($scope.onSearchCallback).toHaveBeenCalledWith(searchText); })); it('should not trigger on search event when clicking on div', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { $scope.onSearchCallback = (search: string) => { console.log(search); }; spyOn($scope, 'onSearchCallback'); let link: JQuery = $element.find('.ms-NavBar-item--search').first(); link.click(); $scope.$apply(); let textbox: JQuery = link.find('.ms-TextField-field').first(); let searchText: string = 'search data'; textbox.val(searchText); angular.element(textbox[0]).triggerHandler('input'); $scope.$apply(); link.find('div.ms-TextField').click(); $scope.$apply(); expect($scope.onSearchCallback).not.toHaveBeenCalled(); })); it( 'should close search control', inject(($compile: Function, $rootScope: angular.IRootScopeService, $timeout: angular.ITimeoutService) => { let search: JQuery = $element.find('.ms-NavBar-item--search').first(); search.click(); $scope.$apply(); let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').first(); link.click(); $scope.$apply(); $timeout.flush(); expect(search).not.toHaveClass('is-selected'); expect(search).not.toHaveClass('is-open'); })); it('should open submenu', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').eq(1); link.click(); $scope.$apply(); expect(link.find('.ms-ContextualMenu').first()).toHaveClass('is-open'); })); it('should close submenu by clicking on sub menu item', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').eq(1); link.click(); $scope.$apply(); link.find('.ms-ContextualMenu-link').first().click(); $scope.$apply(); expect(link.find('.ms-ContextualMenu').first()).not.toHaveClass('is-open'); })); it('should close submenu by clicking on other menu', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').eq(1); link.click(); $scope.$apply(); link.click(); $scope.$apply(); expect(link.find('.ms-ContextualMenu').first()).not.toHaveClass('is-open'); })); it('should close submenu by click on document', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').eq(1); link.click(); $scope.$apply(); jQuery(document.body).click(); $scope.$apply(); expect(link.find('.ms-ContextualMenu').first()).not.toHaveClass('is-open'); })); it('should write an error - invalid overlay type', inject(( $compile: Function, $rootScope: angular.IRootScopeService, /* tslint:disable:variable-name */ _$log_: any) => { /* tslint:enable:variable-name */ $scope = $rootScope.$new(); spyOn(_$log_, 'error'); $compile(angular.element(` <uif-nav-bar uif-overlay="hidden"> <uif-nav-bar-item uif-text="'Home'"></uif-nav-bar-item> </uif-nav-bar>`))($scope); $scope.$apply(); expect(_$log_.error).toHaveBeenCalled(); })); it('should write an error - invalid item type', inject(( $compile: Function, $rootScope: angular.IRootScopeService, /* tslint:disable:variable-name */ _$log_: any) => { /* tslint:enable:variable-name */ $scope = $rootScope.$new(); spyOn(_$log_, 'error'); $compile(angular.element(` <uif-nav-bar uif-overlay="hidden"> <uif-nav-bar-item uif-text="'Home'" uif-type="mytype"></uif-nav-bar-item> </uif-nav-bar>`))($scope); $scope.$apply(); expect(_$log_.error).toHaveBeenCalled(); })); it('should write an error - no text for menu item provided', inject(( $compile: Function, $rootScope: angular.IRootScopeService, /* tslint:disable:variable-name */ _$log_: any) => { /* tslint:enable:variable-name */ $scope = $rootScope.$new(); spyOn(_$log_, 'error'); $compile(angular.element(` <uif-nav-bar uif-overlay="hidden"> <uif-nav-bar-item></uif-nav-bar-item> </uif-nav-bar>`))($scope); $scope.$apply(); expect(_$log_.error).toHaveBeenCalled(); })); it('should create disabled menu', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let link: JQuery = $element.find('.ms-NavBar-items .ms-NavBar-item:not(.ms-NavBar-item--search)').eq(2); link.click(); $scope.$apply(); expect(link).toHaveClass('is-disabled'); expect(link).not.toHaveClass('is-selected'); })); }); describe('mobile navbar tests', () => { let $element: JQuery; let $scope: any; let originalWidth: string; beforeAll(() => { originalWidth = jQuery(document.body).css('width'); jQuery(document.body).css('width', '470px'); jQuery(window).trigger('resize'); }); afterAll(() => { jQuery(document.body).css('width', originalWidth); jQuery(window).trigger('resize'); }); beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => { $element = angular.element(` <uif-nav-bar> <uif-nav-bar-search placeholder="search for smth" uif-on-search="onSearchCallback(search)"> </uif-nav-bar-search> <uif-nav-bar-item uif-text="'Home'" ng-click="logClick('Home item clicked')"></uif-nav-bar-item> <uif-nav-bar-item uif-text="'Contacts'" uif-type="menu"> <uif-contextual-menu> <uif-contextual-menu-item uif-text="'Delete'"></uif-contextual-menu-item> <uif-contextual-menu-item uif-text="'Flag'"></uif-contextual-menu-item> </uif-contextual-menu-item> </uif-nav-bar-item> </uif-nav-bar>`); $scope = $rootScope; $scope.sub = {}; $compile($element)($scope); $element = jQuery($element[0]); $scope.$apply(); })); it('should open mobile menu when clicked', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let menu: JQuery = $element.find('.js-openMenu').first(); menu.click(); $scope.$apply(); expect($element).toHaveClass('is-open'); })); it('should close mobile menu by clicking on menu', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let menu: JQuery = $element.find('.js-openMenu').first(); menu.click(); $scope.$apply(); let link: JQuery = $element.find('.ms-NavBar-items li:not(.ms-NavBar-item--search)').first(); link.click(); $scope.$apply(); expect($element).not.toHaveClass('is-open'); })); it('should close mobile menu by clicking on overlay', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let menu: JQuery = $element.find('.js-openMenu').first(); menu.click(); $scope.$apply(); let link: JQuery = $element.find('uif-overlay').first(); link.click(); $scope.$apply(); expect($element).not.toHaveClass('is-open'); })); }); });
the_stack
import { strict as assert } from "assert"; import got from "got"; import { KubeConfig } from "@kubernetes/client-node"; import { Deployment, K8sResource, Service, V1ServicemonitorResource } from "@opstrace/kubernetes"; import { enrichHeadersWithAuthTokenFile, globalTestSuiteSetupOnce, httpTimeoutSettings, log, logHTTPResponse, mtime, mtimeDeadlineInSeconds, rndstring, sleep, CLUSTER_BASE_URL, CORTEX_API_TLS_VERIFY, TENANT_DEFAULT_API_TOKEN_FILEPATH, TENANT_DEFAULT_CORTEX_API_BASE_URL, TENANT_SYSTEM_API_TOKEN_FILEPATH, TENANT_SYSTEM_CORTEX_API_BASE_URL } from "./testutils"; import { deleteAll, deployAll, waitForAllReady } from "./testutils/deployment"; import { waitForCortexMetricResult, waitForPrometheusTarget } from "./testutils/metrics"; function getE2EAlertingResources( kubeConfig: KubeConfig, tenant: string, job: string ): Array<K8sResource> { const name = "e2ealerting"; const namespace = `${tenant}-tenant`; const matchLabels = { app: name, tenant }; // With a randomized 'job' label that will appear in metrics const labels = { app: name, tenant, job }; const resources: Array<K8sResource> = []; resources.push( new Deployment( { apiVersion: "apps/v1", kind: "Deployment", metadata: { name, namespace, labels }, spec: { replicas: 1, selector: { matchLabels }, template: { metadata: { labels }, spec: { containers: [ { name: "e2ealerting", image: "grafana/e2ealerting:master-db38b142", args: ["-server.http-listen-port=8080", "-log.level=debug"], ports: [{ name: "http", containerPort: 8080 }], livenessProbe: { httpGet: { path: "/metrics", // eslint-disable-next-line @typescript-eslint/no-explicit-any port: "http" as any, scheme: "HTTP" }, periodSeconds: 10, successThreshold: 1, failureThreshold: 3, timeoutSeconds: 1 } } ] } } } }, kubeConfig ) ); resources.push( new Service( { apiVersion: "v1", kind: "Service", metadata: { name, namespace, labels }, spec: { ports: [ { name: "http", port: 80, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: "http" as any } ], selector: labels } }, kubeConfig ) ); resources.push( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { name, namespace, labels }, spec: { jobLabel: "job", // point to 'job' label in the pod endpoints: [ { // Spam it at 5s to get faster responses in tests interval: "5s", port: "http", path: "/metrics" } ], selector: { matchLabels } } }, kubeConfig ) ); return resources; } async function storeE2EAlertsConfig( authTokenFilepath: string | undefined, tenant: string ) { // Configure tenant alertmanager to send alerts to e2ealerting service // Using cortex API proxied via config-api: https://cortexmetrics.io/docs/api/#set-alertmanager-configuration const alertmanagerConfigUrl = `${CLUSTER_BASE_URL}/api/v1/alerts`; const alertmanagerPostResponse = await got.post(alertmanagerConfigUrl, { body: `alertmanager_config: | receivers: - name: e2e-alerting webhook_configs: - url: http://e2ealerting.${tenant}-tenant.svc.cluster.local/api/v1/receiver route: group_interval: 1s group_wait: 1s receiver: e2e-alerting repeat_interval: 1s `, throwHttpErrors: false, timeout: httpTimeoutSettings, headers: enrichHeadersWithAuthTokenFile(authTokenFilepath, {}), https: { rejectUnauthorized: CORTEX_API_TLS_VERIFY } }); logHTTPResponse(alertmanagerPostResponse); assert( alertmanagerPostResponse.statusCode == 201 || alertmanagerPostResponse.statusCode == 202 ); // Configure tenant ruler to fire alert against metric scraped from e2ealerting pod // Using cortex API proxied via config-api: https://cortexmetrics.io/docs/api/#set-rule-group const ruleGroupConfigUrl = `${CLUSTER_BASE_URL}/api/v1/rules/testremote`; const ruleGroupPostResponse = await got.post(ruleGroupConfigUrl, { body: `name: e2ealerting rules: - alert: E2EAlertingAlwaysFiring annotations: time: '{{ $value }}' expr: e2ealerting_now_in_seconds > 0 for: 5s `, throwHttpErrors: false, timeout: httpTimeoutSettings, headers: enrichHeadersWithAuthTokenFile(authTokenFilepath, {}), https: { rejectUnauthorized: CORTEX_API_TLS_VERIFY } }); logHTTPResponse(ruleGroupPostResponse); assert( ruleGroupPostResponse.statusCode == 201 || ruleGroupPostResponse.statusCode == 202 ); } // Returns true if any deletes were performed. async function deleteE2EAlertsConfig( authTokenFilepath: string | undefined, tenant: string ): Promise<boolean> { log.info(`Deleting any alerts configs that exist for tenant=${tenant}`); let deletesOccurred = false; // Delete any alertmanager config created for tenant earlier // Using cortex API proxied via config-api: https://cortexmetrics.io/docs/api/#delete-alertmanager-configuration const alertmanagerConfigUrl = `${CLUSTER_BASE_URL}/api/v1/alerts`; const alertmanagerGetResponse = await got.get(alertmanagerConfigUrl, { throwHttpErrors: false, timeout: httpTimeoutSettings, headers: enrichHeadersWithAuthTokenFile(authTokenFilepath, {}), https: { rejectUnauthorized: CORTEX_API_TLS_VERIFY } }); logHTTPResponse(alertmanagerGetResponse); // Only delete if the config currently exists (non-404). // This reduces the possibility of a rapid delete+set causing a race condition if (alertmanagerGetResponse.statusCode !== 404) { const alertmanagerDeleteResponse = await got.delete(alertmanagerConfigUrl, { throwHttpErrors: false, timeout: httpTimeoutSettings, headers: enrichHeadersWithAuthTokenFile(authTokenFilepath, {}), https: { rejectUnauthorized: CORTEX_API_TLS_VERIFY } }); logHTTPResponse(alertmanagerDeleteResponse); assert( alertmanagerDeleteResponse.statusCode == 202 || alertmanagerDeleteResponse.statusCode == 200 ); deletesOccurred = true; } // Delete any 'testremote' rule namespace created for tenant earlier // Using cortex API proxied via config-api: https://cortexmetrics.io/docs/api/#delete-namespace const ruleGroupConfigUrl = `${CLUSTER_BASE_URL}/api/v1/rules/testremote`; const ruleGroupGetResponse = await got.get(ruleGroupConfigUrl, { throwHttpErrors: false, timeout: httpTimeoutSettings, headers: enrichHeadersWithAuthTokenFile(authTokenFilepath, {}), https: { rejectUnauthorized: CORTEX_API_TLS_VERIFY } }); logHTTPResponse(ruleGroupGetResponse); // Only delete if the config currently exists (non-404). // This reduces the possibility of a rapid delete+set causing a race condition if (ruleGroupGetResponse.statusCode !== 404) { const ruleGroupDeleteResponse = await got.delete(ruleGroupConfigUrl, { throwHttpErrors: false, timeout: httpTimeoutSettings, headers: enrichHeadersWithAuthTokenFile(authTokenFilepath, {}), https: { rejectUnauthorized: CORTEX_API_TLS_VERIFY } }); logHTTPResponse(ruleGroupDeleteResponse); assert( ruleGroupDeleteResponse.statusCode == 202 || ruleGroupDeleteResponse.statusCode == 404 ); deletesOccurred = true; } return deletesOccurred; } async function getE2EAlertCountMetric( cortexBaseUrl: string, uniqueScrapeJobName: string ): Promise<string> { // Instant query - get current value // https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries const queryParams = { query: `e2ealerting_webhook_receiver_evaluations_total{job="${uniqueScrapeJobName}"}` }; const resultArray = await waitForCortexMetricResult( cortexBaseUrl, queryParams, "query" ); // Sanity check: label should match assert.strictEqual( resultArray[0]["metric"]["job"], uniqueScrapeJobName, "Expected to get matching job label for e2ealerting webhook metric: ${resultArray}" ); const value = resultArray[0]["value"][1]; // debug-log for 0 to reduce verbosity if (value == 0) { log.debug(`Got alert count value: ${value}`); } else { log.info(`Got alert count value: ${value}`); } return value; } async function setupE2EAlertsForTenant( kubeConfig: KubeConfig, authTokenFilepath: string | undefined, tenant: string, uniqueScrapeJobName: string ): Promise<Array<K8sResource>> { log.info(`Setting up E2E alerts webhook for tenant=${tenant}`); await storeE2EAlertsConfig(authTokenFilepath, tenant); log.info(`Deploying E2E alerting resources into ${tenant}-tenant namespace`); const resources = getE2EAlertingResources( kubeConfig, tenant, uniqueScrapeJobName ); await deployAll(resources); return resources; } async function waitForE2EAlertFiring( cortexBaseUrl: string, tenant: string, uniqueScrapeJobName: string ) { // Wait for the E2E pod to appear in prometheus scrape targets // This separate check shouldn't contribute to the time spent on the test, and can help with tracing a test failure. log.info( `Waiting for E2E scrape target to appear in tenant prometheus for tenant=${tenant} job=${uniqueScrapeJobName}` ); await waitForPrometheusTarget(tenant, uniqueScrapeJobName); // With the alert outputs configured earlier, wait for the e2ealerting webhook to be queried // and the count of evaluations to be incremented at least once. log.info( `Waiting for cortex E2E alerting metric for tenant=${tenant} job=${uniqueScrapeJobName} with nonzero value` ); const deadline = mtimeDeadlineInSeconds(300); while (true) { if (mtime() > deadline) { throw new Error( "Failed to get non-zero alerts metric value after 300s. Are alerts successfully reaching the e2ealerting pod?" ); } const value = await getE2EAlertCountMetric( cortexBaseUrl, uniqueScrapeJobName ); if (value !== "0") { log.info(`Got alerts metric value for tenant ${tenant}: ${value}`); break; } await sleep(15.0); } } suite("End-to-end alert tests", function () { suiteSetup(async function () { log.info("suite setup"); globalTestSuiteSetupOnce(); }); suiteTeardown(async function () { log.info("suite teardown"); }); test("End-to-end alerts for default and system tenants", async function () { // Give a random token to include for the 'job' label in metrics. // This is just in case e.g. tests are re-run against the same cluster. // Include '-job' at the end just to avoid punctuation at the end of the label which K8s disallows const defaultUniqueScrapeJobName = `testalerts-default-${rndstring().slice( 0, 5 )}-job`; const systemUniqueScrapeJobName = `testalerts-system-${rndstring().slice( 0, 5 )}-job`; // The test environment should already have kubectl working, so we can use that. const kubeConfig = new KubeConfig(); kubeConfig.loadFromDefault(); // loadFromDefault will fall back to e.g. localhost if it cant find something. // So let's explicitly try to communicate with the cluster. const kubeContext = kubeConfig.getCurrentContext(); if (kubeContext === null) { throw new Error( "Unable to communicate with kubernetes cluster. Is kubectl set up?" ); } // Before deploying anything, delete any existing alertmanager/rulegroup configuration. // This avoids an old alert config writing to the newly deployed webhook, making its hit count 1 when we expect 0 // This should only be a problem when running the same test repeatedly against a cluster. log.info("Deleting any preexisting E2E alerts webhooks"); const deletedDefault = await deleteE2EAlertsConfig( TENANT_DEFAULT_API_TOKEN_FILEPATH, "default" ); const deletedSystem = await deleteE2EAlertsConfig( TENANT_SYSTEM_API_TOKEN_FILEPATH, "system" ); // If any deletes were requested, do a quick sleep() to reduce the likelihood of a // race condition between configs being deleted and then assigned. // See also: https://github.com/opstrace/opstrace/issues/1130 if (deletedDefault || deletedSystem) { log.info("Waiting 15s after configs were deleted"); await sleep(15.0); } else { log.info("Continuing immediately after no configs needed to be deleted"); } // To save time, we set up the default and system tenant E2E environments in parallel const defaultTestResources = await setupE2EAlertsForTenant( kubeConfig, TENANT_DEFAULT_API_TOKEN_FILEPATH, "default", defaultUniqueScrapeJobName ); const systemTestResources = await setupE2EAlertsForTenant( kubeConfig, TENANT_SYSTEM_API_TOKEN_FILEPATH, "system", systemUniqueScrapeJobName ); const testResources = defaultTestResources.concat(systemTestResources); // Wait for deployments to be Running/Ready. // This may take around 5 minutes if an image pull is flaking/timing out. await waitForAllReady(kubeConfig, testResources); // With everything deployed, wait for each of the tenants' alerts to start firing await waitForE2EAlertFiring( TENANT_DEFAULT_CORTEX_API_BASE_URL, "default", defaultUniqueScrapeJobName ); await waitForE2EAlertFiring( TENANT_SYSTEM_CORTEX_API_BASE_URL, "system", systemUniqueScrapeJobName ); // Clean up both tenants log.info("Deleting E2E alerts webhooks"); await deleteE2EAlertsConfig(TENANT_DEFAULT_API_TOKEN_FILEPATH, "default"); await deleteE2EAlertsConfig(TENANT_SYSTEM_API_TOKEN_FILEPATH, "system"); // Don't worry about sleep()ing here since we aren't going to set a new config right away. log.info("Deleting E2E alerting resources"); await deleteAll(testResources); }); });
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [medialive](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awselementalmedialive.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Medialive extends PolicyStatement { public servicePrefix = 'medialive'; /** * Statement provider for service [medialive](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awselementalmedialive.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to accept an input device transfer * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/eml-devices.html */ public toAcceptInputDeviceTransfer() { return this.to('AcceptInputDeviceTransfer'); } /** * Grants permission to delete channels, inputs, input security groups, and multiplexes * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/editing-deleting-channel.html */ public toBatchDelete() { return this.to('BatchDelete'); } /** * Grants permission to start channels and multiplexes * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/starting-stopping-deleting-a-channel.html */ public toBatchStart() { return this.to('BatchStart'); } /** * Grants permission to stop channels and multiplexes * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/starting-stopping-deleting-a-channel.html */ public toBatchStop() { return this.to('BatchStop'); } /** * Grants permission to add and remove actions from a channel's schedule * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/batching-actions.html */ public toBatchUpdateSchedule() { return this.to('BatchUpdateSchedule'); } /** * Grants permission to cancel an input device transfer * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/eml-devices.html */ public toCancelInputDeviceTransfer() { return this.to('CancelInputDeviceTransfer'); } /** * Grants permission to create a channel * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/medialive/latest/ug/creating-channel-scratch.html */ public toCreateChannel() { return this.to('CreateChannel'); } /** * Grants permission to create an input * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/medialive/latest/ug/creating-input.html */ public toCreateInput() { return this.to('CreateInput'); } /** * Grants permission to create an input security group * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/medialive/latest/ug/working-with-input-security-groups.html */ public toCreateInputSecurityGroup() { return this.to('CreateInputSecurityGroup'); } /** * Grants permission to create a multiplex * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/medialive/latest/ug/creating-multiplex.html */ public toCreateMultiplex() { return this.to('CreateMultiplex'); } /** * Grants permission to create a multiplex program * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/multiplex-create.html */ public toCreateMultiplexProgram() { return this.to('CreateMultiplexProgram'); } /** * Grants permission to create a partner input * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/medialive/latest/ug/create-partner-input.html */ public toCreatePartnerInput() { return this.to('CreatePartnerInput'); } /** * Grants permission to create tags for channels, inputs, input security groups, multiplexes, and reservations * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/medialive/latest/ug/tagging.html */ public toCreateTags() { return this.to('CreateTags'); } /** * Grants permission to delete a channel * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/editing-deleting-channel.html */ public toDeleteChannel() { return this.to('DeleteChannel'); } /** * Grants permission to delete an input * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/delete-input.html */ public toDeleteInput() { return this.to('DeleteInput'); } /** * Grants permission to delete an input security group * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/delete-input-security-group.html */ public toDeleteInputSecurityGroup() { return this.to('DeleteInputSecurityGroup'); } /** * Grants permission to delete a multiplex * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/delete-multiplex.html */ public toDeleteMultiplex() { return this.to('DeleteMultiplex'); } /** * Grants permission to delete a multiplex program * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/delete-multiplex-program.html */ public toDeleteMultiplexProgram() { return this.to('DeleteMultiplexProgram'); } /** * Grants permission to delete an expired reservation * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/deleting-reservations.html */ public toDeleteReservation() { return this.to('DeleteReservation'); } /** * Grants permission to delete all schedule actions for a channel * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/schedule-using-console-delete.html */ public toDeleteSchedule() { return this.to('DeleteSchedule'); } /** * Grants permission to delete tags from channels, inputs, input security groups, multiplexes, and reservations * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/medialive/latest/ug/tagging.html */ public toDeleteTags() { return this.to('DeleteTags'); } /** * Grants permission to get details about a channel * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/viewing-channel-configuration.html */ public toDescribeChannel() { return this.to('DescribeChannel'); } /** * Grants permission to describe an input * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input.html */ public toDescribeInput() { return this.to('DescribeInput'); } /** * Grants permission to describe an input device * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input-device.html */ public toDescribeInputDevice() { return this.to('DescribeInputDevice'); } /** * Grants permission to describe an input device thumbnail * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input-device.html */ public toDescribeInputDeviceThumbnail() { return this.to('DescribeInputDeviceThumbnail'); } /** * Grants permission to describe an input security group * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input-security-group.html */ public toDescribeInputSecurityGroup() { return this.to('DescribeInputSecurityGroup'); } /** * Grants permission to describe a multiplex * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/viewing-multiplex-configuration.html */ public toDescribeMultiplex() { return this.to('DescribeMultiplex'); } /** * Grants permission to describe a multiplex program * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/monitoring-multiplex-console.html */ public toDescribeMultiplexProgram() { return this.to('DescribeMultiplexProgram'); } /** * Grants permission to get details about a reservation offering * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/purchasing-reservations.html */ public toDescribeOffering() { return this.to('DescribeOffering'); } /** * Grants permission to get details about a reservation * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/view-reservations.html */ public toDescribeReservation() { return this.to('DescribeReservation'); } /** * Grants permission to view a list of actions scheduled on a channel * * Access Level: Read * * https://docs.aws.amazon.com/medialive/latest/ug/viewing-actions-schedule.html */ public toDescribeSchedule() { return this.to('DescribeSchedule'); } /** * Grants permission to list channels * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/viewing-channel-configuration.html */ public toListChannels() { return this.to('ListChannels'); } /** * Grants permission to list input device transfers * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/eml-devices.html */ public toListInputDeviceTransfers() { return this.to('ListInputDeviceTransfers'); } /** * Grants permission to list input devices * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input-device.html */ public toListInputDevices() { return this.to('ListInputDevices'); } /** * Grants permission to list input security groups * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input-security-group.html */ public toListInputSecurityGroups() { return this.to('ListInputSecurityGroups'); } /** * Grants permission to list inputs * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input.html */ public toListInputs() { return this.to('ListInputs'); } /** * Grants permission to list multiplex programs * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/monitoring-multiplex-console.html */ public toListMultiplexPrograms() { return this.to('ListMultiplexPrograms'); } /** * Grants permission to list multiplexes * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/viewing-multiplex-configuration.html */ public toListMultiplexes() { return this.to('ListMultiplexes'); } /** * Grants permission to list reservation offerings * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/purchasing-reservations.html */ public toListOfferings() { return this.to('ListOfferings'); } /** * Grants permission to list reservations * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/view-reservations.html */ public toListReservations() { return this.to('ListReservations'); } /** * Grants permission to list tags for channels, inputs, input security groups, multiplexes, and reservations * * Access Level: List * * https://docs.aws.amazon.com/medialive/latest/ug/tagging.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to purchase a reservation offering * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/medialive/latest/ug/purchasing-reservations.html */ public toPurchaseOffering() { return this.to('PurchaseOffering'); } /** * Grants permission to reject an input device transfer * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/eml-devices.html */ public toRejectInputDeviceTransfer() { return this.to('RejectInputDeviceTransfer'); } /** * Grants permission to start a channel * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/starting-stopping-deleting-a-channel.html */ public toStartChannel() { return this.to('StartChannel'); } /** * Grants permission to start a multiplex * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/starting-stopping-a-multiplex.html */ public toStartMultiplex() { return this.to('StartMultiplex'); } /** * Grants permission to stop a channel * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/starting-stopping-deleting-a-channel.html */ public toStopChannel() { return this.to('StopChannel'); } /** * Grants permission to stop a multiplex * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/starting-stopping-a-multiplex.html */ public toStopMultiplex() { return this.to('StopMultiplex'); } /** * Grants permission to transfer an input device * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/eml-devices.html */ public toTransferInputDevice() { return this.to('TransferInputDevice'); } /** * Grants permission to update a channel * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/editing-deleting-channel.html */ public toUpdateChannel() { return this.to('UpdateChannel'); } /** * Grants permission to update the class of a channel * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/editing-deleting-channel.html */ public toUpdateChannelClass() { return this.to('UpdateChannelClass'); } /** * Grants permission to update an input * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input.html */ public toUpdateInput() { return this.to('UpdateInput'); } /** * Grants permission to update an input device * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input-device.html */ public toUpdateInputDevice() { return this.to('UpdateInputDevice'); } /** * Grants permission to update an input security group * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/edit-input-security-group.html */ public toUpdateInputSecurityGroup() { return this.to('UpdateInputSecurityGroup'); } /** * Grants permission to update a multiplex * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/edit-multiplex.html */ public toUpdateMultiplex() { return this.to('UpdateMultiplex'); } /** * Grants permission to update a multiplex program * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/edit-multiplex-program-channel.html */ public toUpdateMultiplexProgram() { return this.to('UpdateMultiplexProgram'); } /** * Grants permission to update a reservation * * Access Level: Write * * https://docs.aws.amazon.com/medialive/latest/ug/reservations.html */ public toUpdateReservation() { return this.to('UpdateReservation'); } protected accessLevelList: AccessLevelList = { "Write": [ "AcceptInputDeviceTransfer", "BatchDelete", "BatchStart", "BatchStop", "BatchUpdateSchedule", "CancelInputDeviceTransfer", "CreateChannel", "CreateInput", "CreateInputSecurityGroup", "CreateMultiplex", "CreateMultiplexProgram", "CreatePartnerInput", "DeleteChannel", "DeleteInput", "DeleteInputSecurityGroup", "DeleteMultiplex", "DeleteMultiplexProgram", "DeleteReservation", "DeleteSchedule", "PurchaseOffering", "RejectInputDeviceTransfer", "StartChannel", "StartMultiplex", "StopChannel", "StopMultiplex", "TransferInputDevice", "UpdateChannel", "UpdateChannelClass", "UpdateInput", "UpdateInputDevice", "UpdateInputSecurityGroup", "UpdateMultiplex", "UpdateMultiplexProgram", "UpdateReservation" ], "Tagging": [ "CreateTags", "DeleteTags" ], "Read": [ "DescribeChannel", "DescribeInput", "DescribeInputDevice", "DescribeInputDeviceThumbnail", "DescribeInputSecurityGroup", "DescribeMultiplex", "DescribeMultiplexProgram", "DescribeOffering", "DescribeReservation", "DescribeSchedule" ], "List": [ "ListChannels", "ListInputDeviceTransfers", "ListInputDevices", "ListInputSecurityGroups", "ListInputs", "ListMultiplexPrograms", "ListMultiplexes", "ListOfferings", "ListReservations", "ListTagsForResource" ] }; /** * Adds a resource of type channel to the statement * * https://docs.aws.amazon.com/medialive/latest/ug/channels.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onChannel(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:medialive:${Region}:${Account}:channel:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type input to the statement * * https://docs.aws.amazon.com/medialive/latest/ug/inputs.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onInput(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:medialive:${Region}:${Account}:input:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type input-device to the statement * * https://docs.aws.amazon.com/medialive/latest/ug/inputdevices.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onInputDevice(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:medialive:${Region}:${Account}:inputDevice:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type input-security-group to the statement * * https://docs.aws.amazon.com/medialive/latest/ug/inputsecuritygroups.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onInputSecurityGroup(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:medialive:${Region}:${Account}:inputSecurityGroup:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type multiplex to the statement * * https://docs.aws.amazon.com/medialive/latest/ug/multiplexes.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onMultiplex(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:medialive:${Region}:${Account}:multiplex:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type reservation to the statement * * https://docs.aws.amazon.com/medialive/latest/ug/reservations.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onReservation(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:medialive:${Region}:${Account}:reservation:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type offering to the statement * * https://docs.aws.amazon.com/medialive/latest/ug/input-output-reservations.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onOffering(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:medialive:${Region}:${Account}:offering:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import * as angular from 'angular'; /** * @ngdoc class * @name DatepickerController * @module officeuifabric.components.datepicker * * @restrict E * * @description * DatepickerController is the controller for the <uif-datepicker> directive * */ export class DatepickerController { public static $inject: string[] = ['$element', '$scope']; public isPickingYears: boolean = false; public isPickingMonths: boolean = false; public displayDateFormat: string = 'd mmmm, yyyy'; private jElement: JQuery; constructor($element: JQuery, public $scope: IDatepickerDirectiveScope) { this.jElement = $($element[0]); this.displayDateFormat = $scope.uifDateFormat; $scope.ctrl = this; } public range(min: number, max: number, step: number): number[] { step = step || 1; let input: number[] = []; for (let i: number = min; i <= max; i += step) { input.push(i); } return input; } public getPicker(): Pickadate.DatePicker { return this.jElement.find('.ms-TextField-field').pickadate('picker'); } public setValue(value: Date): void { this.getPicker().set('select', value); this.changeHighlightedDate(value.getFullYear(), value.getMonth(), value.getDate()); } public initDatepicker(ngModel: angular.INgModelController): void { let self: DatepickerController = this; this.jElement.find('.ms-TextField-field').pickadate({ // don't render the buttons clear: '', close: '', // formats format: self.displayDateFormat, // classes klass: { active: 'ms-DatePicker-input--active', box: 'ms-DatePicker-dayPicker', day: 'ms-DatePicker-day', disabled: 'ms-DatePicker-day--disabled', focused: 'ms-DatePicker-picker--focused', frame: 'ms-DatePicker-frame', header: 'ms-DatePicker-header', holder: 'ms-DatePicker-holder', infocus: 'ms-DatePicker-day--infocus', input: 'ms-DatePicker-input', month: 'ms-DatePicker-month', now: 'ms-DatePicker-day--today', opened: 'ms-DatePicker-picker--opened', outfocus: 'ms-DatePicker-day--outfocus', picker: 'ms-DatePicker-picker', selected: 'ms-DatePicker-day--selected', table: 'ms-DatePicker-table', weekdays: 'ms-DatePicker-weekday', wrap: 'ms-DatePicker-wrap', year: 'ms-DatePicker-year' }, // events onStart: function (): void { self.initCustomView(); }, today: '', // strings and translations weekdaysShort: ['S', 'M', 'T', 'W', 'T', 'F', 'S'] }); let picker: Pickadate.DatePicker = this.getPicker(); /** Respond to built-in picker events. */ picker.on({ open: function (): void { self.scrollUp(); if (angular.isDefined(ngModel) && ngModel !== null) { ngModel.$setTouched(); } self.$scope.$apply(); }, set: function (value: string): void { let formattedValue: string = picker.get('select', 'yyyy-mm-dd'); if (angular.isDefined(ngModel) && ngModel !== null) { ngModel.$setViewValue(formattedValue); } } }); } private initCustomView(): void { /** Get some variables ready. */ let $monthControls: JQuery = this.jElement.find('.ms-DatePicker-monthComponents'); let $goToday: JQuery = this.jElement.find('.ms-DatePicker-goToday'); // let $dayPicker: JQuery = jElement.find('.ms-DatePicker-dayPicker'); let $monthPicker: JQuery = this.jElement.find('.ms-DatePicker-monthPicker'); let $yearPicker: JQuery = this.jElement.find('.ms-DatePicker-yearPicker'); let $pickerWrapper: JQuery = this.jElement.find('.ms-DatePicker-wrap'); let $picker: Pickadate.DatePicker = this.getPicker(); let self: DatepickerController = this; /** Move the month picker into position. */ $monthControls.appendTo($pickerWrapper); $goToday.appendTo($pickerWrapper); $monthPicker.appendTo($pickerWrapper); $yearPicker.appendTo($pickerWrapper); /** Move back one month. */ $monthControls.on('click', '.js-prevMonth', function (event: JQueryEventObject): void { event.preventDefault(); let newMonth: number = $picker.get('highlight').month - 1; self.changeHighlightedDate(null, newMonth, null); self.$scope.$apply(); }); /** Move ahead one month. */ $monthControls.on('click', '.js-nextMonth', function (event: JQueryEventObject): void { event.preventDefault(); let newMonth: number = $picker.get('highlight').month + 1; self.changeHighlightedDate(null, newMonth, null); self.$scope.$apply(); }); /** Move back one year. */ $monthPicker.on('click', '.js-prevYear', function (event: JQueryEventObject): void { event.preventDefault(); let newYear: number = $picker.get('highlight').year - 1; self.changeHighlightedDate(newYear, null, null); self.$scope.$apply(); }); /** Move ahead one year. */ $monthPicker.on('click', '.js-nextYear', function (event: JQueryEventObject): void { event.preventDefault(); let newYear: number = $picker.get('highlight').year + 1; self.changeHighlightedDate(newYear, null, null); self.$scope.$apply(); }); /** Move back one decade. */ $yearPicker.on('click', '.js-prevDecade', function (event: JQueryEventObject): void { event.preventDefault(); let newYear: number = $picker.get('highlight').year - 10; self.changeHighlightedDate(newYear, null, null); self.$scope.$apply(); }); /** Move ahead one decade. */ $yearPicker.on('click', '.js-nextDecade', function (event: JQueryEventObject): void { event.preventDefault(); let newYear: number = $picker.get('highlight').year + 10; self.changeHighlightedDate(newYear, null, null); self.$scope.$apply(); }); /** Go to the current date, shown in the day picking view. */ $goToday.on('click', function (event: JQueryEventObject): void { event.preventDefault(); /** Select the current date, while keeping the picker open. */ let now: Date = new Date(); $picker.set('select', now); /** Switch to the default (calendar) view. */ self.jElement.removeClass('is-pickingMonths').removeClass('is-pickingYears'); self.$scope.$apply(); }); /** Change the highlighted month. */ $monthPicker.on('click', '.js-changeDate', function (event: JQueryEventObject): void { event.preventDefault(); /** Get the requested date from the data attributes. */ let currentDate: Pickadate.DateItem = $picker.get('highlight'); let newYear: number = currentDate.year; let newMonth: number = +$(this).attr('data-month'); let newDay: number = currentDate.date; /** Update the date. */ self.changeHighlightedDate(newYear, newMonth, newDay); /** If we've been in the "picking months" state on mobile, remove that state so we show the calendar again. */ if (self.jElement.hasClass('is-pickingMonths')) { self.jElement.removeClass('is-pickingMonths'); } self.$scope.$apply(); }); /** Change the highlighted year. */ $yearPicker.on('click', '.js-changeDate', function (event: JQueryEventObject): void { event.preventDefault(); /** Get the requested date from the data attributes. */ let currentDate: Pickadate.DateItem = $picker.get('highlight'); let newYear: number = +$(this).attr('data-year'); let newMonth: number = currentDate.month; let newDay: number = currentDate.date; /** Update the date. */ self.changeHighlightedDate(newYear, newMonth, newDay); /** If we've been in the "picking years" state on mobile, remove that state so we show the calendar again. */ if (self.jElement.hasClass('is-pickingYears')) { self.jElement.removeClass('is-pickingYears'); } self.$scope.$apply(); }); /** Switch to the is-pickingMonths state. */ $monthControls.on('click', '.js-showMonthPicker', function (event: JQueryEventObject): void { self.isPickingMonths = !self.isPickingMonths; self.$scope.$apply(); }); /** Switch to the is-pickingYears state. */ $monthPicker.on('click', '.js-showYearPicker', function (event: JQueryEventObject): void { self.isPickingYears = !self.isPickingYears; self.$scope.$apply(); }); // set the highlighted value self.$scope.highlightedValue = $picker.get('highlight'); } private scrollUp(): void { $('html, body').animate({ scrollTop: this.jElement.offset().top }, 367); } private changeHighlightedDate(newYear: number, newMonth: number, newDay: number): void { let picker: Pickadate.DatePicker = this.getPicker(); /** All variables are optional. If not provided, default to the current value. */ if (newYear == null) { newYear = picker.get('highlight').year; } if (newMonth == null) { newMonth = picker.get('highlight').month; } if (newDay == null) { newDay = picker.get('highlight').date; } /** Update it. */ picker.set('highlight', [newYear, newMonth, newDay]); this.$scope.highlightedValue = picker.get('highlight'); } } /** * @ngdoc interface * @name IDatepickerDirectiveScope * @module officeuifabric.components.datepicker * * @description * This is the scope used by the directive. * * * @property {string} uifMonths - Comma separated list of all months * @property {string} placeholder - The placeholder to display in the text box */ export interface IDatepickerDirectiveScope extends angular.IScope { uifMonths: string; uifDateFormat: string; placeholder: string; monthsArray: string[]; highlightedValue: Pickadate.DateItem; ctrl: DatepickerController; isDisabled: boolean; } /** * @ngdoc directive * @name uifDatepicker * @module officeuifabric.components.datepicker * * @restrict E * * @description * `<uif-datepicker>` is an directive for rendering a datepicker * * @usage * <uif-datepicker * ng-model="value" * placeholder="Please, find a date" * uif-months="Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec" /> */ export class DatepickerDirective implements angular.IDirective { public template: string = '<div ng-class="{\'ms-DatePicker\': true, \'is-pickingYears\': ctrl.isPickingYears, \'is-pickingMonths\': ctrl.isPickingMonths}">' + '<div class="ms-TextField">' + '<i class="ms-DatePicker-event ms-Icon ms-Icon--event"></i>' + '<input class="ms-TextField-field" type="text" placeholder="{{placeholder}}" ng-disabled="isDisabled">' + '</div>' + '<div class="ms-DatePicker-monthComponents">' + '<span class="ms-DatePicker-nextMonth js-nextMonth"><i class="ms-Icon ms-Icon--chevronRight"></i></span>' + '<span class="ms-DatePicker-prevMonth js-prevMonth"><i class="ms-Icon ms-Icon--chevronLeft"></i></span>' + '<div class="ms-DatePicker-headerToggleView js-showMonthPicker"></div>' + '</div>' + '<span class="ms-DatePicker-goToday js-goToday">Go to today</span>' + '<div class="ms-DatePicker-monthPicker">' + '<div class="ms-DatePicker-header">' + '<div class="ms-DatePicker-yearComponents">' + '<span class="ms-DatePicker-nextYear js-nextYear"><i class="ms-Icon ms-Icon--chevronRight"></i></span>' + '<span class="ms-DatePicker-prevYear js-prevYear"><i class="ms-Icon ms-Icon--chevronLeft"></i></span>' + '</div>' + '<div class="ms-DatePicker-currentYear js-showYearPicker">{{highlightedValue.year}}</div>' + '</div>' + '<div class="ms-DatePicker-optionGrid" >' + '<span ng-repeat="month in monthsArray"' + 'ng-class="{\'ms-DatePicker-monthOption js-changeDate\': true, ' + '\'is-highlighted\': highlightedValue.month == $index}"' + 'data-month="{{$index}}">' + '{{month}}</span>' + '</div>' + '</div>' + '<div class="ms-DatePicker-yearPicker">' + '<div class="ms-DatePicker-decadeComponents">' + '<span class="ms-DatePicker-nextDecade js-nextDecade"><i class="ms-Icon ms-Icon--chevronRight"></i></span>' + '<span class="ms-DatePicker-prevDecade js-prevDecade"><i class="ms-Icon ms-Icon--chevronLeft"></i></span>' + '</div>' + '<div class="ms-DatePicker-currentDecade">{{highlightedValue.year - 10}} - {{highlightedValue.year}}</div>' + '<div class="ms-DatePicker-optionGrid">' + '<span ng-class="{\'ms-DatePicker-yearOption js-changeDate\': true,' + '\'is-highlighted\': highlightedValue.year == year}" ' + 'ng-repeat="year in ctrl.range(highlightedValue.year - 10, highlightedValue.year)"' + 'data-year="{{year}}">{{year}}</span>' + '</div>' + '</div>' + '</div>'; public controller: typeof DatepickerController = DatepickerController; public restrict: string = 'E'; public replace: boolean = true; public scope: any = { placeholder: '@', uifDateFormat: '@', uifMonths: '@' }; public require: string[] = ['uifDatepicker', '?ngModel']; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new DatepickerDirective(); return directive; } public compile( templateElement: angular.IAugmentedJQuery, templateAttributes: angular.IAttributes, transclude: angular.ITranscludeFunction ): angular.IDirectivePrePost { return { post: this.postLink, pre: this.preLink }; } private preLink( $scope: IDatepickerDirectiveScope, instanceElement: angular.IAugmentedJQuery, instanceAttributes: angular.IAttributes, ctrls: {}): void { if (!$scope.uifMonths) { $scope.uifMonths = 'Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec'; } if (!$scope.placeholder) { $scope.placeholder = 'Select a date'; } if (!$scope.uifDateFormat) { $scope.uifDateFormat = 'd mmmm, yyyy'; } $scope.monthsArray = $scope.uifMonths.split(','); if ($scope.monthsArray.length !== 12) { throw 'Months setting should have 12 months, separated by a comma'; } instanceAttributes.$observe('disabled', (disabled) => { $scope.isDisabled = !!disabled; }); } private postLink($scope: IDatepickerDirectiveScope, $element: JQuery, attrs: any, ctrls: any[]): void { let datepickerController: DatepickerController = ctrls[0]; let ngModel: angular.INgModelController = ctrls[1]; datepickerController.initDatepicker(ngModel); if (angular.isDefined(ngModel) && ngModel !== null) { ngModel.$render = function (): void { if ( ngModel.$modelValue !== null && ngModel.$modelValue !== '' && typeof ngModel.$modelValue !== 'undefined' ) { if (typeof ngModel.$modelValue === 'string') { let date: Date = new Date(ngModel.$modelValue); datepickerController.setValue(date); } else { datepickerController.setValue(ngModel.$modelValue); } ngModel.$setPristine(); } }; } } } /** * @ngdoc module * @name officeuifabric.components.datepicker * * @description * datepicker. Depends on angular-pickadate https://github.com/restorando/angular-pickadate * */ export let module: angular.IModule = angular.module('officeuifabric.components.datepicker', [ 'officeuifabric.components' ]) .directive('uifDatepicker', DatepickerDirective.factory());
the_stack
"use strict"; module AlienTube { /** * The extension ptions page for all browsers. * @class Options */ export class Options { private static preferenceKeyList = [ "hiddenPostScoreThreshold", "hiddenCommentScoreThreshold", "showGooglePlusWhenNoPosts", "showGooglePlusButton", "defaultDisplayAction" ]; /* Declare the page HTML elements. */ private defaultDisplayActionElement; private resetButtonElement; private excludeSubredditsField; private addToExcludeButton; private excludeListContainer; /* Declare the preferences object and the localisation object. */ private localisationManager; private excludedSubreddits; constructor() { this.localisationManager = new LocalisationManager(function () { /* Get the element for inputs we need to specifically modify. */ this.defaultDisplayActionElement = document.getElementById("defaultDisplayAction"); /* Get the various buttons for the page. */ this.resetButtonElement = document.getElementById("reset"); this.addToExcludeButton = document.getElementById("addSubredditToList"); /* Set the localised text of the reset button. */ this.resetButtonElement.textContent = this.localisationManager.get("options_label_reset"); this.addToExcludeButton.textContent = this.localisationManager.get("options_button_add"); /* Get the element for the exclude subreddits input field and the list container. */ this.excludeSubredditsField = document.getElementById("addSubredditsForExclusion"); this.excludeListContainer = document.getElementById("excludedSubreddits"); /* Set the page title */ window.document.title = this.localisationManager.get("options_label_title"); Preferences.initialise(function (preferences) { // Check if a version migration is necessary. if (Preferences.getString("lastRunVersion") !== Options.getExtensionVersionNumber()) { new Migration(Preferences.getString("lastRunVersion")); /* Update the last run version paramater with the current version so we'll know not to run this migration again. */ Preferences.set("lastRunVersion", Options.getExtensionVersionNumber()); } /* Go over every setting in the options panel. */ for (let i = 0, len = Options.preferenceKeyList.length; i < len; i += 1) { /* Set the localised text for every setting. */ let label = <HTMLLabelElement> document.querySelector("label[for='" + Options.preferenceKeyList[i] + "']"); label.textContent = this.localisationManager.get("options_label_" + Options.preferenceKeyList[i]); /* Get the control for the setting. */ let inputElement = document.getElementById(Options.preferenceKeyList[i]); if (inputElement.tagName === "SELECT") { /* This control is a select/dropdown element. Retreive the existing setting for this. */ var selectInputElement = <HTMLSelectElement> inputElement; var selectValue = Preferences.getString(Options.preferenceKeyList[i]); /* Go over every dropdown item to find the one we need to set as selected. Unfortunately NodeList does not inherit from Array and does not have forEach. Therefor we will force an iteration over it by calling Array.prototype.forEach.call */ var optionElementIndex = 0; Array.prototype.forEach.call(selectInputElement.options, function (optionElement) { if (optionElement.value === selectValue) { selectInputElement.selectedIndex = optionElementIndex; } optionElementIndex += 1; }); /* Call the settings changed event when the user has selected a different dropdown item.*/ inputElement.addEventListener("change", this.saveUpdatedSettings, false); } else if (inputElement.getAttribute("type") === "number") { let numberInputElement = <HTMLInputElement>inputElement; /* This control is a number input element. Retreive the existing setting for this. */ numberInputElement.value = Preferences.getNumber(Options.preferenceKeyList[i]).toString(); /* Call the settings changed event when the user has pushed a key, cut to clipboard, or pasted, from clipboard */ inputElement.addEventListener("keyup", this.saveUpdatedSettings, false); inputElement.addEventListener("cut", this.saveUpdatedSettings, false); inputElement.addEventListener("paste", this.saveUpdatedSettings, false); } else if (inputElement.getAttribute("type") === "checkbox") { let checkboxInputElement = <HTMLInputElement> inputElement; /* This control is a checkbox. Retreive the existing setting for this. */ checkboxInputElement.checked = Preferences.getBoolean(Options.preferenceKeyList[i]); /* Call the settings changed event when the user has changed the state of the checkbox. */ checkboxInputElement.addEventListener("change", this.saveUpdatedSettings, false); } } document.querySelector("label[for='addSubredditForExclusion']").textContent = this.localisationManager.get("options_label_hide_following"); /* Set event handler for the reset button. */ this.resetButtonElement.addEventListener("click", this.resetSettings, false); /* Set the localised text for the "default display action" dropdown options. */ this.defaultDisplayActionElement.options[0].textContent = this.localisationManager.get("options_label_alientube"); this.defaultDisplayActionElement.options[1].textContent = this.localisationManager.get("options_label_gplus"); this.excludedSubreddits = Preferences.getArray("excludedSubredditsSelectedByUser"); /* Erase the current contents of the subreddit list, in case this is an update call on an existing page. */ while (this.excludeListContainer.firstChild !== null) { this.excludeListContainer.removeChild(this.excludeListContainer.firstChild); } /* Populate the excluded subreddit list. */ this.excludedSubreddits.forEach(function (subreddit) { this.addSubredditExclusionItem(subreddit); }); /* Validate the input to see if it is a valid subreddit on key press, cut, or paste, and aditionally check for an 'Enter' key press and process it as a submission. */ this.excludeSubredditsField.addEventListener("keyup", this.onExcludeFieldKeyUp.bind(this), false); this.addToExcludeButton.addEventListener("click", this.addItemToExcludeList.bind(this), false); this.excludeSubredditsField.addEventListener("cut", this.validateExcludeField.bind(this), false); this.excludeSubredditsField.addEventListener("paste", this.validateExcludeField.bind(this), false); /* Set the extension version label. */ document.getElementById("versiontext").textContent = this.localisationManager.get("options_label_version"); document.getElementById('version').textContent = Options.getExtensionVersionNumber(); }.bind(this)); }.bind(this)); } /** * Trigger when a setting has been changed by the user, update the control, and save the setting. * @param event The event object. * @private */ private saveUpdatedSettings(event: Event) { let inputElement = <HTMLInputElement> event.target; if (inputElement.getAttribute("type") === "number") { if (inputElement.value.match(/[0-9]+/)) { inputElement.removeAttribute("invalidInput"); } else { inputElement.setAttribute("invalidInput", "true"); return; } } if (inputElement.getAttribute("type") === "checkbox") { Preferences.set(inputElement.id, inputElement.checked); } else { Preferences.set(inputElement.id, inputElement.value); } } /** * Reset all the settings to factory defaults. * @private */ private resetSettings() { Preferences.reset(); new AlienTube.Options(); Preferences.set("lastRunVersion", Options.getExtensionVersionNumber()); } /** * Add a subreddit item to the excluded subreddits list on the options page. This does not automatically add it to preferences. * @param subreddit The name of the subreddit to block, case insensitive. * @param [animate] Whether to visualise the submission as text animating from the input field into the list. * @private */ private addSubredditExclusionItem(subreddit: string, animate?: boolean) { /* Create the list item and set the name of the subreddit. */ let subredditElement = document.createElement("div"); subredditElement.setAttribute("subreddit", subreddit); /* Create and populate the label that contains the name of the subreddit. */ let subredditLabel = document.createElement("span"); subredditLabel.textContent = subreddit; subredditElement.appendChild(subredditLabel); /* Create the remove item button and set the event handler. */ let removeButton = document.createElement("button"); removeButton.textContent = '╳'; subredditElement.appendChild(removeButton); removeButton.addEventListener("click", this.removeSubredditFromExcludeList.bind(this), false); /* If requested, place the list item on top of the input field and css transition it to the top of the list. */ if (animate) { subredditElement.classList.add("new"); setTimeout(function () { subredditElement.classList.remove("new"); }, 100); } /* Add the item to the top of the list view. */ this.excludeListContainer.insertBefore(subredditElement, this.excludeListContainer.firstChild); } /** * Validate keyboard input in the exclude subreddits text field, and if an enter press is detected, process it as a submission. * @param event A keyboard event object * @private */ private onExcludeFieldKeyUp(event : KeyboardEvent) { if (!this.validateExcludeField(event)) return; if (event.keyCode === 13) { this.addItemToExcludeList(event); } } /** * Validate the exclude subreddits text field after any input change event. * @param event Any input event with the exclude subreddits text field as a target. * @private */ private validateExcludeField(event: Event): boolean { let textfield = <HTMLInputElement>event.target; /* Check that the text field contents is a valid subreddit name. */ if (textfield.value.match(/([A-Za-z0-9_]+|[reddit.com]){3}/) !== null) { this.addToExcludeButton.disabled = false; return true; } this.addToExcludeButton.disabled = true; return false; } /** * Add the contents of the exclude subreddits field to the exclude subreddits list in the options page and in the preferences. * @param event A button press or enter event. * @private */ private addItemToExcludeList(event: Event) { /* Retrieve the subreddit name from the text field, and add it to the list. */ let subredditName = this.excludeSubredditsField.value; this.addSubredditExclusionItem(subredditName, true); /* Add the subreddit name to the list in preferences. */ this.excludedSubreddits.push(subredditName); Preferences.set("excludedSubredditsSelectedByUser", this.excludedSubreddits); /* Remove the contents of the text field and reset the submit button state. */ setTimeout(function () { this.addToExcludeButton.disabled = true; this.excludeSubredditsField.value = ""; }, 150); } /** * Remove a subreddit from the exclude list on the options page and in the preferences. * @param event An event from the click of a remove button on a subreddit list item. * @private */ private removeSubredditFromExcludeList(event: Event) { /* Retrieve the subreddit item that will be removed. */ let subredditElement = <HTMLDivElement>(<HTMLButtonElement> event.target).parentNode; /* Remove the item from the preferences file. */ this.excludedSubreddits.splice(this.excludedSubreddits.indexOf(subredditElement.getAttribute("subreddit")), 1); Preferences.set("excludedSubredditsSelectedByUser", this.excludedSubreddits); /* Remove the item from the list on the options page and animate its removal. */ subredditElement.classList.add("removed"); setTimeout(function () { this.excludeListContainer.removeChild(subredditElement); }, 500); } /** * Get the current version of the extension running on this machine. * @private */ private static getExtensionVersionNumber(): string { let version = ""; switch (Utilities.getCurrentBrowser()) { case Browser.CHROME: version = chrome.app.getDetails().version; break; case Browser.FIREFOX: version = self.options.version; break; case Browser.SAFARI: version = safari.extension.displayVersion; break; } return version || ""; } } interface AlienTubePreferenceKeys { hiddenPostScoreThreshold: number; hiddenCommentScoreThreshold: number; showGooglePlusWhenNoPosts: boolean; showGooglePlusButton: boolean; defaultDisplayAction: string; } } new AlienTube.Options();
the_stack
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SprkIconComponent } from '../sprk-icon/sprk-icon.component'; import { SprkLinkDirective } from '../../directives/sprk-link/sprk-link.directive'; import { SprkUnorderedListComponent } from '../sprk-unordered-list/sprk-unordered-list.component'; import { SprkListItemComponent } from '../sprk-list-item/sprk-list-item.component'; import { SprkPaginationComponent } from './sprk-pagination.component'; describe('SprkPaginationComponent', () => { let component: SprkPaginationComponent; let fixture: ComponentFixture<SprkPaginationComponent>; let element; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ SprkPaginationComponent, SprkUnorderedListComponent, SprkIconComponent, SprkLinkDirective, SprkListItemComponent ] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SprkPaginationComponent); component = fixture.componentInstance; element = fixture.nativeElement; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('getClasses should match what gets set on the element', () => { fixture.detectChanges(); expect(element.classList.toString()).toEqual(component.getClasses()); }); it('should add the correct aria-label to links based on page number', () => { // < 1 ... 4 > component.currentPage = 1; component.totalItems = 100; component.itemsPerPage = 25; fixture.detectChanges(); const pageItem = element.querySelectorAll('.sprk-b-Link'); expect(pageItem[1].hasAttribute('aria-label')).toEqual(true); expect(pageItem[1].getAttribute('aria-label')).toEqual('Page 1'); expect(pageItem[2].hasAttribute('aria-label')).toEqual(true); expect(pageItem[2].getAttribute('aria-label')).toEqual('Page 4'); }); it('should add the correct classes if additionalClasses has a value', () => { component.currentPage = 7; component.totalItems = 7; component.itemsPerPage = 1; component.additionalClasses = 'sprk-u-pam sprk-u-man'; fixture.detectChanges(); expect(component.getClasses()).toEqual(' sprk-u-pam sprk-u-man'); }); it('should set the data-analytics attribute given a value in the analyticsStringLinkPrev Input', () => { component.analyticsStringLinkPrev = 'previous'; fixture.detectChanges(); expect( element.querySelector('.sprk-b-Link').hasAttribute('data-analytics') ).toEqual(true); expect( element.querySelector('.sprk-b-Link').getAttribute('data-analytics') ).toEqual('previous'); }); it('should set the data-analytics attribute given a value in the analyticsStringLinkNext Input', () => { component.analyticsStringLinkNext = 'foo'; fixture.detectChanges(); const item = element.querySelectorAll('.sprk-c-Pagination__icon')[1]; expect(item.hasAttribute('data-analytics')).toEqual(true); expect(item.getAttribute('data-analytics')).toEqual('foo'); }); it('should emit pageClick when an individual page is clicked', done => { let called = false; component.currentPage = 2; component.totalItems = 3; component.itemsPerPage = 1; fixture.detectChanges(); component.pageClick.subscribe(g => { called = true; done(); }); let pageItem = element.querySelectorAll('.sprk-b-Link'); pageItem = pageItem[1]; pageItem.click(); expect(called).toEqual(true); }); it('should emit previousClick when prev link is clicked', done => { let called = false; const expectedPage = 2; const expectedNewPage = 1; let actualPage = -1; let actualNewPage = -1; component.currentPage = 2; component.totalItems = 3; component.itemsPerPage = 1; component.previousClick.subscribe(g => { called = true; actualPage = g.page; actualNewPage = g.newPage; done(); }); const item = element.querySelectorAll('a.sprk-c-Pagination__icon')[0]; item.click(); expect(called).toEqual(true); // Page is still returning the old page. This allows us to // close Issue 1401 without introducing a breaking change. expect(actualPage).toEqual(expectedPage); expect(actualNewPage).toEqual(expectedNewPage); }); it('should emit nextClick when next link is clicked', done => { let called = false; const expectedPage = 2; const expectedNewPage = 3; let actualPage = -1; let actualNewPage = -1; component.currentPage = 2; component.totalItems = 3; component.itemsPerPage = 1; component.nextClick.subscribe(g => { called = true; actualPage = g.page; actualNewPage = g.newPage; done(); }); const item = element.querySelectorAll('a.sprk-c-Pagination__icon')[1]; item.click(); expect(called).toEqual(true); // Page is still returning the old page. This allows us to // close Issue 1401 without introducing a breaking change. expect(actualPage).toEqual(expectedPage); expect(actualNewPage).toEqual(expectedNewPage); }); it('should add data-id when idString has a value', () => { const testString = 'element-id'; component.idString = testString; fixture.detectChanges(); expect(element.querySelector('nav').getAttribute('data-id')).toEqual( testString ); }); it('should not add data-id when idString has no value', () => { component.idString = null; fixture.detectChanges(); expect(element.querySelector('nav').getAttribute('data-id')).toBeNull(); }); it('should allow for single-page configurations', () => { component.totalItems = 1; component.itemsPerPage = 1; component.currentPage = 1; fixture.detectChanges(); // expect 1 page expect(element.querySelectorAll('.sprk-c-Pagination__link').length).toEqual( 1 ); // expect 1 selected page with text 1 expect( element.querySelector('.sprk-c-Pagination__link--current').textContent.trim() ).toEqual('1'); }); it('should calculate total pages correctly', () => { component.totalItems = 1; component.itemsPerPage = 1; component.currentPage = 1; fixture.detectChanges(); let expectedPages = 1; expect(component.totalPages()).toEqual(expectedPages); component.totalItems = 2; fixture.detectChanges(); expectedPages = 2; expect(component.totalPages()).toEqual(expectedPages); component.totalItems = 5; component.itemsPerPage = 2; fixture.detectChanges(); expectedPages = 3; expect(component.totalPages()).toEqual(expectedPages); }); it('renders three numbered pages and no ellipses with 3 or fewer pages', () => { // < 1 2 3 > component.totalItems = 30; component.itemsPerPage = 10; fixture.detectChanges(); expect( element.querySelectorAll('a.sprk-c-Pagination__icon').length ).toEqual(2); // 2 chevrons expect( element.querySelectorAll('a.sprk-c-Pagination__link').length ).toEqual(3); // 3 pages expect( Array.from(element.querySelectorAll('a')).filter( (x: HTMLLIElement) => x.textContent === '...' ).length ).toEqual(0); // 0 chevrons }); it('renders ellipses with more than 3 pages', () => { const str = '...'; // < 1 ... 3 ... 5 > component.totalItems = 50; component.itemsPerPage = 10; component.currentPage = 3; fixture.detectChanges(); expect( element.querySelectorAll('a.sprk-c-Pagination__icon').length ).toEqual(2); // 2 chevrons expect( element.querySelectorAll('a.sprk-c-Pagination__link').length ).toEqual(3); // 3 pages expect( Array.from(element.querySelectorAll('li')).filter( (x: HTMLLIElement) => x.textContent.trim() === str ).length ).toEqual(2); // 2 ellipses // < 1 ... 4 5 > component.currentPage = 4; fixture.detectChanges(); expect( Array.from(element.querySelectorAll('li')).filter( (x: HTMLLIElement) => x.textContent.trim() === str ).length ).toEqual(1); // 1 ellipsis }); it('handles currentPage outside bounds', () => { // should render 5 pages component.totalItems = 5; component.itemsPerPage = 1; component.currentPage = 99; fixture.detectChanges(); expect(component.currentPage).toEqual(5); component.currentPage = -99; fixture.detectChanges(); expect(component.currentPage).toEqual(1); }); it('defaults currentPage to 1', () => { expect(component.currentPage).toEqual(1); }); it('renders ellipses with more than 3 pages in long variant', () => { // < 1 ... 3 ... 5 > component.paginationType = 'long'; component.totalItems = 50; component.itemsPerPage = 10; component.currentPage = 3; fixture.detectChanges(); const str = '...'; expect( element.querySelectorAll('a.sprk-c-Pagination__icon').length ).toEqual(2); // 2 chevrons expect( element.querySelectorAll('a.sprk-c-Pagination__link').length ).toEqual(3); // 3 pages expect( Array.from(element.querySelectorAll('li')).filter( (x: HTMLLIElement) => x.textContent.trim() === str ).length ).toEqual(2); // 2 ellipses // < 1 ... 4 5 > component.currentPage = 4; fixture.detectChanges(); expect( Array.from(element.querySelectorAll('li')).filter( (x: HTMLLIElement) => x.textContent.trim() === str ).length ).toEqual(1); // 1 ellipsis }); it('renders three numbered pages and no ellipses with 3 or fewer pages in long variant', () => { const str = '...'; // < 1 2 3 > component.paginationType = 'long'; component.totalItems = 30; component.itemsPerPage = 10; fixture.detectChanges(); expect( element.querySelectorAll('a.sprk-c-Pagination__icon').length ).toEqual(2); // 2 chevrons expect( element.querySelectorAll('a.sprk-c-Pagination__link').length ).toEqual(3); // 3 pages expect( Array.from(element.querySelectorAll('a')).filter( (x: HTMLLIElement) => x.textContent.trim() === str ).length ).toEqual(0); // 0 chevrons }); it('should not change page when going back from page 1', () => { // < 1 2 3 > component.totalItems = 3; component.itemsPerPage = 1; component.currentPage = 1; fixture.detectChanges(); const goBackArrow = element.querySelectorAll('.sprk-b-Link')[0]; goBackArrow.click(); expect(component.currentPage).toEqual(1); }); it('should not change page when going forward from last page', () => { // < 1 2 3 > component.totalItems = 3; component.itemsPerPage = 1; component.currentPage = 3; fixture.detectChanges(); const goForwardArrow = element.querySelectorAll('.sprk-b-Link')[4]; goForwardArrow.click(); expect(component.currentPage).toEqual(3); }); });
the_stack
import { BigNumber, BigNumberish, constants, ContractTransaction, providers, Signer } from 'ethers'; import { erc20EscrowToPayArtifact } from '@requestnetwork/smart-contracts'; import { ERC20EscrowToPay__factory } from '@requestnetwork/smart-contracts/types/'; import { ClientTypes, PaymentTypes } from '@requestnetwork/types'; import { getAmountToPay, getProvider, getRequestPaymentValues, getSigner, validateRequest, } from './utils'; import { ITransactionOverrides } from './transaction-overrides'; import { encodeApproveAnyErc20 } from './erc20'; /** * Processes the approval transaction of the payment ERC20 to be spent by the erc20EscrowToPay * contract during the fee proxy delegate call. * @param request request to pay, used to know the network * @param paymentTokenAddress picked currency to pay * @param signerOrProvider the web3 provider. Defaults to Etherscan. * @param overrides optionally, override default transaction values, like gas. */ export async function approveErc20ForEscrow( request: ClientTypes.IRequestData, paymentTokenAddress: string, signerOrProvider: providers.Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const contractAddress = erc20EscrowToPayArtifact.getAddress(request.currencyInfo.network!); const encodedTx = encodeApproveAnyErc20(paymentTokenAddress, contractAddress, signerOrProvider); const signer = getSigner(signerOrProvider); const tx = await signer.sendTransaction({ data: encodedTx, to: paymentTokenAddress, value: 0, ...overrides, }); return tx; } /** * Processes a transaction to payEscrow(). * @param request request to pay. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param amount optional, if you want to override the amount in the request. * @param feeAmount optional, if you want to override the feeAmount in the request. * @param overrides optionally, override default transaction values, like gas. */ export async function payEscrow( request: ClientTypes.IRequestData, signerOrProvider: providers.Web3Provider | Signer = getProvider(), amount?: BigNumberish, feeAmount?: BigNumberish, overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const encodedTx = encodePayEscrow(request, amount, feeAmount); const contractAddress = erc20EscrowToPayArtifact.getAddress(request.currencyInfo.network!); const signer = getSigner(signerOrProvider); const tx = await signer.sendTransaction({ data: encodedTx, to: contractAddress, value: 0, ...overrides, }); return tx; } /** * Processes a transaction to freeze request. * @param request request to pay. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param overrides optionally, override default transaction values, like gas. */ export async function freezeRequest( request: ClientTypes.IRequestData, signerOrProvider: providers.Web3Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const encodedTx = encodeFreezeRequest(request); const contractAddress = erc20EscrowToPayArtifact.getAddress(request.currencyInfo.network!); const signer = getSigner(signerOrProvider); const tx = await signer.sendTransaction({ data: encodedTx, to: contractAddress, value: 0, ...overrides, }); return tx; } /** * Processes a transaction to payRequestFromEscrow(). * @param request request to pay. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param overrides optionally, override default transaction values, like gas. */ export async function payRequestFromEscrow( request: ClientTypes.IRequestData, signerOrProvider: providers.Web3Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const encodedTx = encodePayRequestFromEscrow(request); const contractAddress = erc20EscrowToPayArtifact.getAddress(request.currencyInfo.network!); const signer = getSigner(signerOrProvider); const tx = await signer.sendTransaction({ data: encodedTx, to: contractAddress, value: 0, ...overrides, }); return tx; } /** * Processes a transaction to initiateEmergencyClaim(). * @param request request to pay. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param overrides optionally, override default transaction values, like gas. */ export async function initiateEmergencyClaim( request: ClientTypes.IRequestData, signerOrProvider: providers.Web3Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const encodedTx = encodeInitiateEmergencyClaim(request); const contractAddress = erc20EscrowToPayArtifact.getAddress(request.currencyInfo.network!); const signer = getSigner(signerOrProvider); const tx = await signer.sendTransaction({ data: encodedTx, to: contractAddress, value: 0, ...overrides, }); return tx; } /** * Processes a transaction to completeEmergencyClaim(). * @param request request to pay. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param overrides optionally, override default transaction values, like gas. */ export async function completeEmergencyClaim( request: ClientTypes.IRequestData, signerOrProvider: providers.Web3Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const encodedTx = encodeCompleteEmergencyClaim(request); const contractAddress = erc20EscrowToPayArtifact.getAddress(request.currencyInfo.network!); const signer = getSigner(signerOrProvider); const tx = await signer.sendTransaction({ data: encodedTx, to: contractAddress, value: 0, ...overrides, }); return tx; } /** * Processes a transaction to revertEmergencyClaim(). * @param request request to pay. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param overrides optionally, override default transaction values, like gas. */ export async function revertEmergencyClaim( request: ClientTypes.IRequestData, signerOrProvider: providers.Web3Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const encodedTx = encodeRevertEmergencyClaim(request); const contractAddress = erc20EscrowToPayArtifact.getAddress(request.currencyInfo.network!); const signer = getSigner(signerOrProvider); const tx = await signer.sendTransaction({ data: encodedTx, to: contractAddress, value: 0, ...overrides, }); return tx; } /** * Processes a transaction to refundFrozenFunds(). * @param request request to pay. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param overrides optionally, override default transaction values, like gas. */ export async function refundFrozenFunds( request: ClientTypes.IRequestData, signerOrProvider: providers.Web3Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const encodedTx = encodeRefundFrozenFunds(request); const contractAddress = erc20EscrowToPayArtifact.getAddress(request.currencyInfo.network!); const signer = getSigner(signerOrProvider); const tx = await signer.sendTransaction({ data: encodedTx, to: contractAddress, value: 0, ...overrides, }); return tx; } /** * Encodes the call to payEscrow(). * @param request request to pay. * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param amount optionally, the amount to pay. Defaults to remaining amount of the request. */ export function encodePayEscrow( request: ClientTypes.IRequestData, amount?: BigNumberish, feeAmountOverride?: BigNumberish, ): string { validateRequest(request, PaymentTypes.PAYMENT_NETWORK_ID.ERC20_FEE_PROXY_CONTRACT); const tokenAddress = request.currencyInfo.value; // collects the parameters to be used, from the request const { paymentReference, paymentAddress, feeAmount, feeAddress } = getRequestPaymentValues(request); const amountToPay = getAmountToPay(request, amount); const feeToPay = BigNumber.from(feeAmountOverride || feeAmount || 0); const erc20EscrowContract = ERC20EscrowToPay__factory.createInterface(); return erc20EscrowContract.encodeFunctionData('payEscrow', [ tokenAddress, paymentAddress, amountToPay, `0x${paymentReference}`, feeToPay, feeAddress || constants.AddressZero, ]); } /** * Encapsulates the validation, paymentReference calculation and escrow contract interface creation. * These steps are used in all subsequent functions encoding escrow interaction transactions * @param request Request data * @returns {erc20EscrowToPayContract, paymentReference} */ function prepareForEncoding(request: ClientTypes.IRequestData) { validateRequest(request, PaymentTypes.PAYMENT_NETWORK_ID.ERC20_FEE_PROXY_CONTRACT); // collects the parameters to be used from the request const { paymentReference } = getRequestPaymentValues(request); // connections to the escrow contract const erc20EscrowToPayContract = ERC20EscrowToPay__factory.createInterface(); return { erc20EscrowToPayContract, paymentReference, }; } /** * Returns the encoded data to freezeRequest(). * @param request request to pay. */ export function encodeFreezeRequest(request: ClientTypes.IRequestData): string { const { erc20EscrowToPayContract, paymentReference } = prepareForEncoding(request); return erc20EscrowToPayContract.encodeFunctionData('freezeRequest', [`0x${paymentReference}`]); } /** * Returns the encoded data to payRequestFromEscrow(). * @param request request for pay */ export function encodePayRequestFromEscrow(request: ClientTypes.IRequestData): string { const { erc20EscrowToPayContract, paymentReference } = prepareForEncoding(request); return erc20EscrowToPayContract.encodeFunctionData('payRequestFromEscrow', [ `0x${paymentReference}`, ]); } /** * Returns the encoded data to initiateEmergencyClaim(). * @param request request to pay. */ export function encodeInitiateEmergencyClaim(request: ClientTypes.IRequestData): string { const { erc20EscrowToPayContract, paymentReference } = prepareForEncoding(request); return erc20EscrowToPayContract.encodeFunctionData('initiateEmergencyClaim', [ `0x${paymentReference}`, ]); } /** * Returns the encoded data to completeEmergencyClaim(). * @param request request to pay. */ export function encodeCompleteEmergencyClaim(request: ClientTypes.IRequestData): string { const { erc20EscrowToPayContract, paymentReference } = prepareForEncoding(request); return erc20EscrowToPayContract.encodeFunctionData('completeEmergencyClaim', [ `0x${paymentReference}`, ]); } /** * Returns the encoded data to revertEmergencyClaim(). * @param request request to pay. */ export function encodeRevertEmergencyClaim(request: ClientTypes.IRequestData): string { const { erc20EscrowToPayContract, paymentReference } = prepareForEncoding(request); return erc20EscrowToPayContract.encodeFunctionData('revertEmergencyClaim', [ `0x${paymentReference}`, ]); } /** * Returns the encoded data to refundFrozenFunds(). * @param request request to pay. */ export function encodeRefundFrozenFunds(request: ClientTypes.IRequestData): string { const { erc20EscrowToPayContract, paymentReference } = prepareForEncoding(request); return erc20EscrowToPayContract.encodeFunctionData('refundFrozenFunds', [ `0x${paymentReference}`, ]); }
the_stack
import {Oas20ParameterDefinition} from "../../models/2.0/parameter.model"; import {Oas20Response, Oas20ResponseDefinition} from "../../models/2.0/response.model"; import {Oas20SecurityScheme} from "../../models/2.0/security-scheme.model"; import {Oas20SchemaDefinition} from "../../models/2.0/schema.model"; import {Oas20Example} from "../../models/2.0/example.model"; import {Oas20Scopes} from "../../models/2.0/scopes.model"; import {Oas20Document} from "../../models/2.0/document.model"; import {Oas20Operation} from "../../models/2.0/operation.model"; import {OasValidationRuleUtil, PathSegment} from "../validation" import {OasPathItem} from "../../models/common/path-item.model"; import {Oas30Response, Oas30ResponseDefinition} from "../../models/3.0/response.model"; import {OasValidationRule} from "./common.rule"; import {Oas30Schema, Oas30SchemaDefinition} from "../../models/3.0/schema.model"; import {Oas30ParameterDefinition} from "../../models/3.0/parameter.model"; import {Oas30PathItem} from "../../models/3.0/path-item.model"; import {Oas30ExampleDefinition} from "../../models/3.0/example.model"; import {Oas30RequestBodyDefinition} from "../../models/3.0/request-body.model"; import {Oas30HeaderDefinition} from "../../models/3.0/header.model"; import {Oas30LinkDefinition} from "../../models/3.0/link.model"; import {Oas30CallbackDefinition} from "../../models/3.0/callback.model"; import {Oas30Encoding} from "../../models/3.0/encoding.model"; import {Oas30MediaType} from "../../models/3.0/media-type.model"; /** * Base class for all Invalid Property Name rules. */ export abstract class OasInvalidPropertyNameRule extends OasValidationRule { /** * Returns true if the definition name is valid. * @param name * @return {boolean} */ protected isValidDefinitionName(name: string): boolean { // TODO should this be different for OAS 2.0 vs. 3.x?? Only 3.x dictates the format to some extent (I think). let definitionNamePattern: RegExp = /^[a-zA-Z0-9\.\-_]+$/; return definitionNamePattern.test(name); } /** * Returns true if the scope name is valid. * @param scope */ protected isValidScopeName(scope: string): boolean { // TODO implement some reasonable rules for this return true; } /** * Finds all occurences of path segments that are empty. * i.e. they neither have a prefix nor a path variable within curly braces. * * @param pathSegments * @return {PathSegment[]} */ protected findEmptySegmentsInPath(pathSegments: PathSegment[]): PathSegment[] { return pathSegments.filter(pathSegment => { return pathSegment.prefix === "" && pathSegment.formalName === undefined; }); } /** * Finds path segments that are duplicates i.e. they have the same formal name used across multiple segments. * For example, in a path like /prefix/{var1}/{var1}, var1 is used in multiple segments. * * @param pathSegments * @return {PathSegment[]} */ protected findDuplicateParametersInPath(pathSegments: PathSegment[]): string[] { const uniq: any = pathSegments .filter(pathSegment => { return pathSegment.formalName !== undefined; }) .map(pathSegment => { return { parameter: pathSegment.formalName, count: 1 }; }) .reduce((parameterCounts, segmentEntry) => { parameterCounts[segmentEntry.parameter] = (parameterCounts[segmentEntry.parameter] || 0) + segmentEntry.count; return parameterCounts; }, {}); return Object.keys(uniq).filter(a => uniq[a] > 1); } } /** * Implements the Empty Path Segment Rule. */ export class OasEmptyPathSegmentRule extends OasInvalidPropertyNameRule { public visitPathItem(node: OasPathItem): void { const pathTemplate: string = node.path(); let pathSegments: PathSegment[]; if (this.isPathWellFormed(pathTemplate) === true) { pathSegments = this.getPathSegments(pathTemplate); const emptySegments = this.findEmptySegmentsInPath(pathSegments); if (emptySegments.length > 0) { this.reportPathError(node, { path: node.path() }); } } } } /** * Implements the Duplicate Path Segment Rule. */ export class OasDuplicatePathSegmentRule extends OasInvalidPropertyNameRule { public visitPathItem(node: OasPathItem): void { const pathTemplate: string = node.path(); let pathSegments: PathSegment[]; if (this.isPathWellFormed(pathTemplate) === true) { pathSegments = this.getPathSegments(pathTemplate); const duplicateParameters: string[] = this.findDuplicateParametersInPath(pathSegments); if (duplicateParameters.length > 0) { this.reportPathError(node, { path: node.path(), duplicates: duplicateParameters.join(", ") }); } } } } /** * Implements the Invalid Path Segment Rule. */ export class OasInvalidPathSegmentRule extends OasInvalidPropertyNameRule { public visitPathItem(node: OasPathItem): void { const pathTemplate: string = node.path(); if (!this.isPathWellFormed(pathTemplate) === true) { this.reportPathError(node, { path: node.path() }); } } } /** * Implements the Identical Path Template Rule. */ type IdenticalPathRecord = { identicalReported: boolean, pathSegments: PathSegment[], node: Oas30PathItem, }; export class OasIdenticalPathTemplateRule extends OasInvalidPropertyNameRule { private indexedPathTemplates: any = {}; /** * Utility function to find other paths that are semantically similar to the path that is being checked against. * Two paths that differ only in formal parameter name are considered identical. * For example, paths /test/{var1} and /test/{var2} are identical. * See OAS 3 Specification's Path Templates section for more details. * * https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#path-templating-matching * * @param pathToCheck * @param pathIndex */ private findIdenticalPaths(pathToCheck: string, pathIndex: any): string[] { const identicalPaths: string[] = []; const pathSegments: PathSegment[] = pathIndex[pathToCheck].pathSegments; Object.keys(pathIndex) .filter(checkAgainst => checkAgainst !== pathToCheck) .forEach(checkAgainst => { let segmentsIdential: boolean = true; const pathSegmentsToCheckAgainst: PathSegment[] = pathIndex[checkAgainst].pathSegments; if (pathSegments.length !== pathSegmentsToCheckAgainst.length) { segmentsIdential = false; } else { pathSegments.forEach((pathSegment, index) => { segmentsIdential = segmentsIdential && this.isSegmentIdentical(pathSegment, pathSegmentsToCheckAgainst[index]); }); } if (segmentsIdential === true) { identicalPaths.push(checkAgainst); } }); return identicalPaths; } /** * Utility function to test the equality of two path segments. * Segments are considered equal if they have same prefixes (if any) and same "normalized name". * * @param segment1 * @param segment2 * @return {boolean} */ private isSegmentIdentical(segment1: PathSegment, segment2: PathSegment): boolean { if (segment1.prefix === segment2.prefix) { if (segment1.normalizedName === undefined && segment2.normalizedName === undefined) { return true; } if ( (segment1.normalizedName === undefined && segment2.normalizedName !== undefined) || (segment1.normalizedName !== undefined && segment2.normalizedName === undefined) ) { return false; } return segment1.normalizedName === segment2.normalizedName; } return false; } public visitPathItem(node: Oas30PathItem): void { const pathTemplate: string = node.path(); if (this.isPathWellFormed(pathTemplate)) { let pathSegments: PathSegment[] = this.getPathSegments(pathTemplate); const currentPathRecord: IdenticalPathRecord = { identicalReported: false, pathSegments, node, }; this.indexedPathTemplates[pathTemplate] = currentPathRecord; const identicalPaths: string[] = this.findIdenticalPaths(pathTemplate, this.indexedPathTemplates); if (identicalPaths.length > 0) { this.reportPathError(node, {path: node.path()}); currentPathRecord.identicalReported = true; identicalPaths.forEach(path => { const identicalPathRecord: IdenticalPathRecord = this.indexedPathTemplates[path]; if (identicalPathRecord.identicalReported === false) { this.reportPathError(identicalPathRecord.node, {path: node.path()}); identicalPathRecord.identicalReported = true; } }); } } } } /** * Implements the Invalid Http Response Code Rule. */ export class OasInvalidHttpResponseCodeRule extends OasInvalidPropertyNameRule { public visitResponse(node: Oas20Response | Oas30Response): void { // The "default" response will have a statusCode of "null" if (this.hasValue(node.statusCode())) { this.reportIfInvalid(OasValidationRuleUtil.isValidHttpCode(node.statusCode()), node, "statusCode", { statusCode: node.statusCode() }); } } } /** * Implements the Unmatched Example Type Rule. */ export class OasUnmatchedExampleTypeRule extends OasInvalidPropertyNameRule { public visitExample(node: Oas20Example): void { let produces: string[] = (node.ownerDocument() as Oas20Document).produces; let operation: Oas20Operation = node.parent().parent().parent() as Oas20Operation; if (this.hasValue(operation.produces)) { produces = operation.produces; } if (!this.hasValue(produces)) { produces = []; } let ctypes: string[] = node.exampleContentTypes(); ctypes.forEach( ct => { this.reportIfInvalid(produces.indexOf(ct) !== -1, node, "produces", { contentType: ct }); }); } } /** * Implements the Invalid Schema Definition Name Rule. */ export class OasInvalidSchemaDefNameRule extends OasInvalidPropertyNameRule { public visitSchemaDefinition(node: Oas20SchemaDefinition | Oas30SchemaDefinition): void { if (node.ownerDocument().is2xDocument()) { this.reportIfInvalid(this.isValidDefinitionName((<Oas20SchemaDefinition>node).definitionName()), node, "definitionName"); } else { this.reportIfInvalid(this.isValidDefinitionName((<Oas30SchemaDefinition>node).name()), node, "name"); } } } /** * Implements the Invalid Parameter Definition Name Rule. */ export class OasInvalidParameterDefNameRule extends OasInvalidPropertyNameRule { public visitParameterDefinition(node: Oas20ParameterDefinition | Oas30ParameterDefinition): void { this.reportIfInvalid(this.isValidDefinitionName(node.parameterName()), node, "parameterName"); } } /** * Implements the Invalid Response Definition Name Rule. */ export class OasInvalidResponseDefNameRule extends OasInvalidPropertyNameRule { public visitResponseDefinition(node: Oas20ResponseDefinition | Oas30ResponseDefinition): void { this.reportIfInvalid(this.isValidDefinitionName(node.name()), node, "name"); } } /** * Implements the Invalid Scope Name Rule. */ export class OasInvalidScopeNameRule extends OasInvalidPropertyNameRule { public visitScopes(node: Oas20Scopes): void { node.scopes().forEach( scope => { this.reportIfInvalid(this.isValidScopeName(scope), node, "scopes", { scope: scope }); }) } } /** * Implements the Invalid Security Scheme Name Rule. */ export class OasInvalidSecuritySchemeNameRule extends OasInvalidPropertyNameRule { public visitSecurityScheme(node: Oas20SecurityScheme): void { this.reportIfInvalid(this.isValidDefinitionName(node.schemeName()), node, "schemeName"); } } /** * Implements the Invalid Example Definition Name Rule. */ export class OasInvalidExampleDefinitionNameRule extends OasInvalidPropertyNameRule { public visitExampleDefinition(node: Oas30ExampleDefinition): void { this.reportIfInvalid(this.isValidDefinitionName(node.name()), node, "name"); } } /** * Implements the Invalid Request Body Definition Name Rule. */ export class OasInvalidRequestBodyDefinitionNameRule extends OasInvalidPropertyNameRule { public visitRequestBodyDefinition(node: Oas30RequestBodyDefinition): void { this.reportIfInvalid(this.isValidDefinitionName(node.name()), node, "name"); } } /** * Implements the Invalid Header Definition Name Rule. */ export class OasInvalidHeaderDefinitionNameRule extends OasInvalidPropertyNameRule { public visitHeaderDefinition(node: Oas30HeaderDefinition): void { this.reportIfInvalid(this.isValidDefinitionName(node.name()), node, "name"); } } /** * Implements the Invalid Link Definition Name Rule. */ export class OasInvalidLinkDefinitionNameRule extends OasInvalidPropertyNameRule { public visitLinkDefinition(node: Oas30LinkDefinition): void { this.reportIfInvalid(this.isValidDefinitionName(node.name()), node, "name"); } } /** * Implements the Invalid Callback Definition Name Rule. */ export class OasInvalidCallbackDefinitionNameRule extends OasInvalidPropertyNameRule { public visitCallbackDefinition(node: Oas30CallbackDefinition): void { this.reportIfInvalid(this.isValidDefinitionName(node.name()), node, "name"); } } /** * Implements the Unmatched Encoding Property Rule. */ export class OasUnmatchedEncodingPropertyRule extends OasInvalidPropertyNameRule { /** * Returns true if the given schema has a property defined with the given name. * @param {Oas30Schema} schema * @param {string} propertyName * @return {boolean} */ private isValidSchemaProperty(schema: Oas30Schema, propertyName: string): boolean { if (this.isNullOrUndefined(schema)) { return false; } return !this.isNullOrUndefined(schema.property(propertyName)); } public visitEncoding(node: Oas30Encoding): void { let name: string = node.name(); let schema: Oas30Schema = (node.parent() as Oas30MediaType).schema; this.reportIfInvalid(this.isValidSchemaProperty(schema, name), node, name, { name: name }); } }
the_stack
import {getPluralCase} from '../../i18n/localization'; import {assertDefined, assertDomNode, assertEqual, assertGreaterThan, assertIndexInRange, throwError} from '../../util/assert'; import {assertIndexInExpandoRange, assertTIcu} from '../assert'; import {attachPatchData} from '../context_discovery'; import {elementPropertyInternal, setElementAttribute} from '../instructions/shared'; import {ELEMENT_MARKER, I18nCreateOpCode, I18nCreateOpCodes, I18nUpdateOpCode, I18nUpdateOpCodes, ICU_MARKER, IcuCreateOpCode, IcuCreateOpCodes, IcuType, TI18n, TIcu} from '../interfaces/i18n'; import {TNode} from '../interfaces/node'; import {RElement, RNode, RText} from '../interfaces/renderer_dom'; import {SanitizerFn} from '../interfaces/sanitization'; import {HEADER_OFFSET, LView, RENDERER, TView} from '../interfaces/view'; import {createCommentNode, createElementNode, createTextNode, nativeInsertBefore, nativeParentNode, nativeRemoveNode, updateTextNode} from '../node_manipulation'; import {getBindingIndex} from '../state'; import {renderStringify} from '../util/stringify_utils'; import {getNativeByIndex, unwrapRNode} from '../util/view_utils'; import {getLocaleId} from './i18n_locale_id'; import {getCurrentICUCaseIndex, getParentFromIcuCreateOpCode, getRefFromIcuCreateOpCode, getTIcu} from './i18n_util'; /** * Keep track of which input bindings in `ɵɵi18nExp` have changed. * * This is used to efficiently update expressions in i18n only when the corresponding input has * changed. * * 1) Each bit represents which of the `ɵɵi18nExp` has changed. * 2) There are 32 bits allowed in JS. * 3) Bit 32 is special as it is shared for all changes past 32. (In other words if you have more * than 32 `ɵɵi18nExp` then all changes past 32nd `ɵɵi18nExp` will be mapped to same bit. This means * that we may end up changing more than we need to. But i18n expressions with 32 bindings is rare * so in practice it should not be an issue.) */ let changeMask = 0b0; /** * Keeps track of which bit needs to be updated in `changeMask` * * This value gets incremented on every call to `ɵɵi18nExp` */ let changeMaskCounter = 0; /** * Keep track of which input bindings in `ɵɵi18nExp` have changed. * * `setMaskBit` gets invoked by each call to `ɵɵi18nExp`. * * @param hasChange did `ɵɵi18nExp` detect a change. */ export function setMaskBit(hasChange: boolean) { if (hasChange) { changeMask = changeMask | (1 << Math.min(changeMaskCounter, 31)); } changeMaskCounter++; } export function applyI18n(tView: TView, lView: LView, index: number) { if (changeMaskCounter > 0) { ngDevMode && assertDefined(tView, `tView should be defined`); const tI18n = tView.data[index] as TI18n | I18nUpdateOpCodes; // When `index` points to an `ɵɵi18nAttributes` then we have an array otherwise `TI18n` const updateOpCodes: I18nUpdateOpCodes = Array.isArray(tI18n) ? tI18n as I18nUpdateOpCodes : (tI18n as TI18n).update; const bindingsStartIndex = getBindingIndex() - changeMaskCounter - 1; applyUpdateOpCodes(tView, lView, updateOpCodes, bindingsStartIndex, changeMask); } // Reset changeMask & maskBit to default for the next update cycle changeMask = 0b0; changeMaskCounter = 0; } /** * Apply `I18nCreateOpCodes` op-codes as stored in `TI18n.create`. * * Creates text (and comment) nodes which are internationalized. * * @param lView Current lView * @param createOpCodes Set of op-codes to apply * @param parentRNode Parent node (so that direct children can be added eagerly) or `null` if it is * a root node. * @param insertInFrontOf DOM node that should be used as an anchor. */ export function applyCreateOpCodes( lView: LView, createOpCodes: I18nCreateOpCodes, parentRNode: RElement|null, insertInFrontOf: RElement|null): void { const renderer = lView[RENDERER]; for (let i = 0; i < createOpCodes.length; i++) { const opCode = createOpCodes[i++] as any; const text = createOpCodes[i] as string; const isComment = (opCode & I18nCreateOpCode.COMMENT) === I18nCreateOpCode.COMMENT; const appendNow = (opCode & I18nCreateOpCode.APPEND_EAGERLY) === I18nCreateOpCode.APPEND_EAGERLY; const index = opCode >>> I18nCreateOpCode.SHIFT; let rNode = lView[index]; if (rNode === null) { // We only create new DOM nodes if they don't already exist: If ICU switches case back to a // case which was already instantiated, no need to create new DOM nodes. rNode = lView[index] = isComment ? renderer.createComment(text) : createTextNode(renderer, text); } if (appendNow && parentRNode !== null) { nativeInsertBefore(renderer, parentRNode, rNode, insertInFrontOf, false); } } } /** * Apply `I18nMutateOpCodes` OpCodes. * * @param tView Current `TView` * @param mutableOpCodes Mutable OpCodes to process * @param lView Current `LView` * @param anchorRNode place where the i18n node should be inserted. */ export function applyMutableOpCodes( tView: TView, mutableOpCodes: IcuCreateOpCodes, lView: LView, anchorRNode: RNode): void { ngDevMode && assertDomNode(anchorRNode); const renderer = lView[RENDERER]; // `rootIdx` represents the node into which all inserts happen. let rootIdx: number|null = null; // `rootRNode` represents the real node into which we insert. This can be different from // `lView[rootIdx]` if we have projection. // - null we don't have a parent (as can be the case in when we are inserting into a root of // LView which has no parent.) // - `RElement` The element representing the root after taking projection into account. let rootRNode!: RElement|null; for (let i = 0; i < mutableOpCodes.length; i++) { const opCode = mutableOpCodes[i]; if (typeof opCode == 'string') { const textNodeIndex = mutableOpCodes[++i] as number; if (lView[textNodeIndex] === null) { ngDevMode && ngDevMode.rendererCreateTextNode++; ngDevMode && assertIndexInRange(lView, textNodeIndex); lView[textNodeIndex] = createTextNode(renderer, opCode); } } else if (typeof opCode == 'number') { switch (opCode & IcuCreateOpCode.MASK_INSTRUCTION) { case IcuCreateOpCode.AppendChild: const parentIdx = getParentFromIcuCreateOpCode(opCode); if (rootIdx === null) { // The first operation should save the `rootIdx` because the first operation // must insert into the root. (Only subsequent operations can insert into a dynamic // parent) rootIdx = parentIdx; rootRNode = nativeParentNode(renderer, anchorRNode); } let insertInFrontOf: RNode|null; let parentRNode: RElement|null; if (parentIdx === rootIdx) { insertInFrontOf = anchorRNode; parentRNode = rootRNode; } else { insertInFrontOf = null; parentRNode = unwrapRNode(lView[parentIdx]) as RElement; } // FIXME(misko): Refactor with `processI18nText` if (parentRNode !== null) { // This can happen if the `LView` we are adding to is not attached to a parent `LView`. // In such a case there is no "root" we can attach to. This is fine, as we still need to // create the elements. When the `LView` gets later added to a parent these "root" nodes // get picked up and added. ngDevMode && assertDomNode(parentRNode); const refIdx = getRefFromIcuCreateOpCode(opCode); ngDevMode && assertGreaterThan(refIdx, HEADER_OFFSET, 'Missing ref'); // `unwrapRNode` is not needed here as all of these point to RNodes as part of the i18n // which can't have components. const child = lView[refIdx] as RElement; ngDevMode && assertDomNode(child); nativeInsertBefore(renderer, parentRNode, child, insertInFrontOf, false); const tIcu = getTIcu(tView, refIdx); if (tIcu !== null && typeof tIcu === 'object') { // If we just added a comment node which has ICU then that ICU may have already been // rendered and therefore we need to re-add it here. ngDevMode && assertTIcu(tIcu); const caseIndex = getCurrentICUCaseIndex(tIcu, lView); if (caseIndex !== null) { applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, lView[tIcu.anchorIdx]); } } } break; case IcuCreateOpCode.Attr: const elementNodeIndex = opCode >>> IcuCreateOpCode.SHIFT_REF; const attrName = mutableOpCodes[++i] as string; const attrValue = mutableOpCodes[++i] as string; // This code is used for ICU expressions only, since we don't support // directives/components in ICUs, we don't need to worry about inputs here setElementAttribute( renderer, getNativeByIndex(elementNodeIndex, lView) as RElement, null, null, attrName, attrValue, null); break; default: throw new Error(`Unable to determine the type of mutate operation for "${opCode}"`); } } else { switch (opCode) { case ICU_MARKER: const commentValue = mutableOpCodes[++i] as string; const commentNodeIndex = mutableOpCodes[++i] as number; if (lView[commentNodeIndex] === null) { ngDevMode && assertEqual( typeof commentValue, 'string', `Expected "${commentValue}" to be a comment node value`); ngDevMode && ngDevMode.rendererCreateComment++; ngDevMode && assertIndexInExpandoRange(lView, commentNodeIndex); const commentRNode = lView[commentNodeIndex] = createCommentNode(renderer, commentValue); // FIXME(misko): Attaching patch data is only needed for the root (Also add tests) attachPatchData(commentRNode, lView); } break; case ELEMENT_MARKER: const tagName = mutableOpCodes[++i] as string; const elementNodeIndex = mutableOpCodes[++i] as number; if (lView[elementNodeIndex] === null) { ngDevMode && assertEqual( typeof tagName, 'string', `Expected "${tagName}" to be an element node tag name`); ngDevMode && ngDevMode.rendererCreateElement++; ngDevMode && assertIndexInExpandoRange(lView, elementNodeIndex); const elementRNode = lView[elementNodeIndex] = createElementNode(renderer, tagName, null); // FIXME(misko): Attaching patch data is only needed for the root (Also add tests) attachPatchData(elementRNode, lView); } break; default: ngDevMode && throwError(`Unable to determine the type of mutate operation for "${opCode}"`); } } } } /** * Apply `I18nUpdateOpCodes` OpCodes * * @param tView Current `TView` * @param lView Current `LView` * @param updateOpCodes OpCodes to process * @param bindingsStartIndex Location of the first `ɵɵi18nApply` * @param changeMask Each bit corresponds to a `ɵɵi18nExp` (Counting backwards from * `bindingsStartIndex`) */ export function applyUpdateOpCodes( tView: TView, lView: LView, updateOpCodes: I18nUpdateOpCodes, bindingsStartIndex: number, changeMask: number) { for (let i = 0; i < updateOpCodes.length; i++) { // bit code to check if we should apply the next update const checkBit = updateOpCodes[i] as number; // Number of opCodes to skip until next set of update codes const skipCodes = updateOpCodes[++i] as number; if (checkBit & changeMask) { // The value has been updated since last checked let value = ''; for (let j = i + 1; j <= (i + skipCodes); j++) { const opCode = updateOpCodes[j]; if (typeof opCode == 'string') { value += opCode; } else if (typeof opCode == 'number') { if (opCode < 0) { // Negative opCode represent `i18nExp` values offset. value += renderStringify(lView[bindingsStartIndex - opCode]); } else { const nodeIndex = (opCode >>> I18nUpdateOpCode.SHIFT_REF); switch (opCode & I18nUpdateOpCode.MASK_OPCODE) { case I18nUpdateOpCode.Attr: const propName = updateOpCodes[++j] as string; const sanitizeFn = updateOpCodes[++j] as SanitizerFn | null; const tNodeOrTagName = tView.data[nodeIndex] as TNode | string; ngDevMode && assertDefined(tNodeOrTagName, 'Experting TNode or string'); if (typeof tNodeOrTagName === 'string') { // IF we don't have a `TNode`, then we are an element in ICU (as ICU content does // not have TNode), in which case we know that there are no directives, and hence // we use attribute setting. setElementAttribute( lView[RENDERER], lView[nodeIndex], null, tNodeOrTagName, propName, value, sanitizeFn); } else { elementPropertyInternal( tView, tNodeOrTagName, lView, propName, value, lView[RENDERER], sanitizeFn, false); } break; case I18nUpdateOpCode.Text: const rText = lView[nodeIndex] as RText | null; rText !== null && updateTextNode(lView[RENDERER], rText, value); break; case I18nUpdateOpCode.IcuSwitch: applyIcuSwitchCase(tView, getTIcu(tView, nodeIndex)!, lView, value); break; case I18nUpdateOpCode.IcuUpdate: applyIcuUpdateCase(tView, getTIcu(tView, nodeIndex)!, bindingsStartIndex, lView); break; } } } } } else { const opCode = updateOpCodes[i + 1] as number; if (opCode > 0 && (opCode & I18nUpdateOpCode.MASK_OPCODE) === I18nUpdateOpCode.IcuUpdate) { // Special case for the `icuUpdateCase`. It could be that the mask did not match, but // we still need to execute `icuUpdateCase` because the case has changed recently due to // previous `icuSwitchCase` instruction. (`icuSwitchCase` and `icuUpdateCase` always come in // pairs.) const nodeIndex = (opCode >>> I18nUpdateOpCode.SHIFT_REF); const tIcu = getTIcu(tView, nodeIndex)!; const currentIndex = lView[tIcu.currentCaseLViewIndex]; if (currentIndex < 0) { applyIcuUpdateCase(tView, tIcu, bindingsStartIndex, lView); } } } i += skipCodes; } } /** * Apply OpCodes associated with updating an existing ICU. * * @param tView Current `TView` * @param tIcu Current `TIcu` * @param bindingsStartIndex Location of the first `ɵɵi18nApply` * @param lView Current `LView` */ function applyIcuUpdateCase(tView: TView, tIcu: TIcu, bindingsStartIndex: number, lView: LView) { ngDevMode && assertIndexInRange(lView, tIcu.currentCaseLViewIndex); let activeCaseIndex = lView[tIcu.currentCaseLViewIndex]; if (activeCaseIndex !== null) { let mask = changeMask; if (activeCaseIndex < 0) { // Clear the flag. // Negative number means that the ICU was freshly created and we need to force the update. activeCaseIndex = lView[tIcu.currentCaseLViewIndex] = ~activeCaseIndex; // -1 is same as all bits on, which simulates creation since it marks all bits dirty mask = -1; } applyUpdateOpCodes(tView, lView, tIcu.update[activeCaseIndex], bindingsStartIndex, mask); } } /** * Apply OpCodes associated with switching a case on ICU. * * This involves tearing down existing case and than building up a new case. * * @param tView Current `TView` * @param tIcu Current `TIcu` * @param lView Current `LView` * @param value Value of the case to update to. */ function applyIcuSwitchCase(tView: TView, tIcu: TIcu, lView: LView, value: string) { // Rebuild a new case for this ICU const caseIndex = getCaseIndex(tIcu, value); let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView); if (activeCaseIndex !== caseIndex) { applyIcuSwitchCaseRemove(tView, tIcu, lView); lView[tIcu.currentCaseLViewIndex] = caseIndex === null ? null : ~caseIndex; if (caseIndex !== null) { // Add the nodes for the new case const anchorRNode = lView[tIcu.anchorIdx]; if (anchorRNode) { ngDevMode && assertDomNode(anchorRNode); applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, anchorRNode); } } } } /** * Apply OpCodes associated with tearing ICU case. * * This involves tearing down existing case and than building up a new case. * * @param tView Current `TView` * @param tIcu Current `TIcu` * @param lView Current `LView` */ function applyIcuSwitchCaseRemove(tView: TView, tIcu: TIcu, lView: LView) { let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView); if (activeCaseIndex !== null) { const removeCodes = tIcu.remove[activeCaseIndex]; for (let i = 0; i < removeCodes.length; i++) { const nodeOrIcuIndex = removeCodes[i] as number; if (nodeOrIcuIndex > 0) { // Positive numbers are `RNode`s. const rNode = getNativeByIndex(nodeOrIcuIndex, lView); rNode !== null && nativeRemoveNode(lView[RENDERER], rNode); } else { // Negative numbers are ICUs applyIcuSwitchCaseRemove(tView, getTIcu(tView, ~nodeOrIcuIndex)!, lView); } } } } /** * Returns the index of the current case of an ICU expression depending on the main binding value * * @param icuExpression * @param bindingValue The value of the main binding used by this ICU expression */ function getCaseIndex(icuExpression: TIcu, bindingValue: string): number|null { let index = icuExpression.cases.indexOf(bindingValue); if (index === -1) { switch (icuExpression.type) { case IcuType.plural: { const resolvedCase = getPluralCase(bindingValue, getLocaleId()); index = icuExpression.cases.indexOf(resolvedCase); if (index === -1 && resolvedCase !== 'other') { index = icuExpression.cases.indexOf('other'); } break; } case IcuType.select: { index = icuExpression.cases.indexOf('other'); break; } } } return index === -1 ? null : index; }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type AuctionResultQueryVariables = { auctionResultInternalID: string; artistID: string; }; export type AuctionResultQueryResponse = { readonly auctionResult: { readonly " $fragmentRefs": FragmentRefs<"AuctionResult_auctionResult">; } | null; readonly artist: { readonly " $fragmentRefs": FragmentRefs<"AuctionResult_artist">; } | null; }; export type AuctionResultQuery = { readonly response: AuctionResultQueryResponse; readonly variables: AuctionResultQueryVariables; }; /* query AuctionResultQuery( $auctionResultInternalID: String! $artistID: String! ) { auctionResult(id: $auctionResultInternalID) { ...AuctionResult_auctionResult id } artist(id: $artistID) { ...AuctionResult_artist id } } fragment AuctionResultListItem_auctionResult on AuctionResult { currency dateText id internalID artist { name id } images { thumbnail { url(version: "square140") height width aspectRatio } } estimate { low } mediumText organization boughtIn performance { mid } priceRealized { cents display displayUSD } saleDate title } fragment AuctionResult_artist on Artist { name href } fragment AuctionResult_auctionResult on AuctionResult { id internalID artistID boughtIn currency categoryText dateText dimensions { height width } dimensionText estimate { display high low } images { thumbnail { url(version: "square140") height width aspectRatio } } location mediumText organization performance { mid } priceRealized { cents centsUSD display displayUSD } saleDate saleTitle title ...ComparableWorks_auctionResult } fragment ComparableWorks_auctionResult on AuctionResult { comparableAuctionResults(first: 3) @optionalField { edges { cursor node { ...AuctionResultListItem_auctionResult artistID internalID id } } } } */ const node: ConcreteRequest = (function(){ var v0 = { "defaultValue": null, "kind": "LocalArgument", "name": "artistID" }, v1 = { "defaultValue": null, "kind": "LocalArgument", "name": "auctionResultInternalID" }, v2 = [ { "kind": "Variable", "name": "id", "variableName": "auctionResultInternalID" } ], v3 = [ { "kind": "Variable", "name": "id", "variableName": "artistID" } ], v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "artistID", "storageKey": null }, v7 = { "alias": null, "args": null, "kind": "ScalarField", "name": "boughtIn", "storageKey": null }, v8 = { "alias": null, "args": null, "kind": "ScalarField", "name": "currency", "storageKey": null }, v9 = { "alias": null, "args": null, "kind": "ScalarField", "name": "dateText", "storageKey": null }, v10 = { "alias": null, "args": null, "kind": "ScalarField", "name": "height", "storageKey": null }, v11 = { "alias": null, "args": null, "kind": "ScalarField", "name": "width", "storageKey": null }, v12 = { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null }, v13 = { "alias": null, "args": null, "kind": "ScalarField", "name": "low", "storageKey": null }, v14 = { "alias": null, "args": null, "concreteType": "AuctionLotImages", "kind": "LinkedField", "name": "images", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "thumbnail", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "square140" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"square140\")" }, (v10/*: any*/), (v11/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "aspectRatio", "storageKey": null } ], "storageKey": null } ], "storageKey": null }, v15 = { "alias": null, "args": null, "kind": "ScalarField", "name": "mediumText", "storageKey": null }, v16 = { "alias": null, "args": null, "kind": "ScalarField", "name": "organization", "storageKey": null }, v17 = { "alias": null, "args": null, "concreteType": "AuctionLotPerformance", "kind": "LinkedField", "name": "performance", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "mid", "storageKey": null } ], "storageKey": null }, v18 = { "alias": null, "args": null, "kind": "ScalarField", "name": "cents", "storageKey": null }, v19 = { "alias": null, "args": null, "kind": "ScalarField", "name": "displayUSD", "storageKey": null }, v20 = { "alias": null, "args": null, "kind": "ScalarField", "name": "saleDate", "storageKey": null }, v21 = { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, v22 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }; return { "fragment": { "argumentDefinitions": [ (v0/*: any*/), (v1/*: any*/) ], "kind": "Fragment", "metadata": null, "name": "AuctionResultQuery", "selections": [ { "alias": null, "args": (v2/*: any*/), "concreteType": "AuctionResult", "kind": "LinkedField", "name": "auctionResult", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "AuctionResult_auctionResult" } ], "storageKey": null }, { "alias": null, "args": (v3/*: any*/), "concreteType": "Artist", "kind": "LinkedField", "name": "artist", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "AuctionResult_artist" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [ (v1/*: any*/), (v0/*: any*/) ], "kind": "Operation", "name": "AuctionResultQuery", "selections": [ { "alias": null, "args": (v2/*: any*/), "concreteType": "AuctionResult", "kind": "LinkedField", "name": "auctionResult", "plural": false, "selections": [ (v4/*: any*/), (v5/*: any*/), (v6/*: any*/), (v7/*: any*/), (v8/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "categoryText", "storageKey": null }, (v9/*: any*/), { "alias": null, "args": null, "concreteType": "AuctionLotDimensions", "kind": "LinkedField", "name": "dimensions", "plural": false, "selections": [ (v10/*: any*/), (v11/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "dimensionText", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionLotEstimate", "kind": "LinkedField", "name": "estimate", "plural": false, "selections": [ (v12/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "high", "storageKey": null }, (v13/*: any*/) ], "storageKey": null }, (v14/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "location", "storageKey": null }, (v15/*: any*/), (v16/*: any*/), (v17/*: any*/), { "alias": null, "args": null, "concreteType": "AuctionResultPriceRealized", "kind": "LinkedField", "name": "priceRealized", "plural": false, "selections": [ (v18/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "centsUSD", "storageKey": null }, (v12/*: any*/), (v19/*: any*/) ], "storageKey": null }, (v20/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "saleTitle", "storageKey": null }, (v21/*: any*/), { "alias": null, "args": [ { "kind": "Literal", "name": "first", "value": 3 } ], "concreteType": "AuctionResultConnection", "kind": "LinkedField", "name": "comparableAuctionResults", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "AuctionResultEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "cursor", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionResult", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v8/*: any*/), (v9/*: any*/), (v4/*: any*/), (v5/*: any*/), { "alias": null, "args": null, "concreteType": "Artist", "kind": "LinkedField", "name": "artist", "plural": false, "selections": [ (v22/*: any*/), (v4/*: any*/) ], "storageKey": null }, (v14/*: any*/), { "alias": null, "args": null, "concreteType": "AuctionLotEstimate", "kind": "LinkedField", "name": "estimate", "plural": false, "selections": [ (v13/*: any*/) ], "storageKey": null }, (v15/*: any*/), (v16/*: any*/), (v7/*: any*/), (v17/*: any*/), { "alias": null, "args": null, "concreteType": "AuctionResultPriceRealized", "kind": "LinkedField", "name": "priceRealized", "plural": false, "selections": [ (v18/*: any*/), (v12/*: any*/), (v19/*: any*/) ], "storageKey": null }, (v20/*: any*/), (v21/*: any*/), (v6/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": "comparableAuctionResults(first:3)" } ], "storageKey": null }, { "alias": null, "args": (v3/*: any*/), "concreteType": "Artist", "kind": "LinkedField", "name": "artist", "plural": false, "selections": [ (v22/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, (v4/*: any*/) ], "storageKey": null } ] }, "params": { "id": "6081b6aed78fe56e5cf0a7dbedd02a21", "metadata": {}, "name": "AuctionResultQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = 'bc5ee899b66c353cefd0c2034c7fa600'; export default node;
the_stack
import { defineConfig, equal, flatMerge, generateId, isFunction, isValidObject, notEqual, } from '@agile-ts/utils'; import { logCodeManager } from '../logCodeManager'; import { State, StateConfigInterface, StateKey } from './state'; import { Agile } from '../agile'; import { StateIngestConfigInterface } from './state.observer'; import { CreateStatePersistentConfigInterface, StatePersistent, } from './state.persistent'; import { PersistentKey, StorageKey } from '../storages'; export class EnhancedState<ValueType = any> extends State<ValueType> { // Whether the State is persisted in an external Storage public isPersisted = false; // Manages the permanent persistent in external Storages public persistent: StatePersistent | undefined; // Method for dynamically computing the State value public computeValueMethod?: ComputeValueMethod<ValueType>; // Method for dynamically computing the existence of the State public computeExistsMethod: ComputeExistsMethod<ValueType>; // When an interval is active, the 'intervalId' to clear the interval is temporary stored here public currentInterval?: NodeJS.Timer | number; /** * An enhanced State manages, like a normal State, a piece of Information * that we need to remember globally at a later point in time. * While providing a toolkit to use and mutate this piece of Information. * * The main difference to a normal State is however * that an enhanced State provides a wider variety of inbuilt utilities (like a persist, undo, watch functionality) * but requires a larger bundle size in return. * * You can create as many global enhanced States as you need. * * [Learn more..](https://agile-ts.org/docs/core/agile-instance/methods#createstate) * * @public * @param agileInstance - Instance of Agile the State belongs to. * @param initialValue - Initial value of the State. * @param config - Configuration object */ constructor( agileInstance: Agile, initialValue: ValueType, config: StateConfigInterface = {} ) { super(agileInstance, initialValue, config); this.computeExistsMethod = (v) => { return v != null; }; } public setKey(value: StateKey | undefined): this { const oldKey = this._key; // Update State key super.setKey(value); // Update key in Persistent (only if oldKey is equal to persistentKey // because otherwise the persistentKey is detached from the State key // -> not managed by State anymore) if (value != null && this.persistent?._key === oldKey) this.persistent?.setKey(value); return this; } /** * Undoes the latest State value change. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#undo) * * @public * @param config - Configuration object */ public undo(config: StateIngestConfigInterface = {}): this { this.set(this.previousStateValue, config); return this; } /** * Resets the State value to its initial value. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#reset) * * @public * @param config - Configuration object */ public reset(config: StateIngestConfigInterface = {}): this { this.set(this.initialStateValue, config); return this; } /** * Merges the specified `targetWithChanges` object into the current State value. * This merge can differ for different value combinations: * - If the current State value is an `object`, it does a partial update for the object. * - If the current State value is an `array` and the specified argument is an array too, * it concatenates the current State value with the value of the argument. * - If the current State value is neither an `object` nor an `array`, the patch can't be performed. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#patch) * * @public * @param targetWithChanges - Object to be merged into the current State value. * @param config - Configuration object */ public patch( targetWithChanges: Object, config: PatchConfigInterface = {} ): this { config = defineConfig(config, { addNewProperties: true, }); // Check if the given conditions are suitable for a patch action if (!isValidObject(this.nextStateValue, true)) { logCodeManager.log('14:03:02'); return this; } if (!isValidObject(targetWithChanges, true)) { logCodeManager.log('00:03:01', { replacers: ['TargetWithChanges', 'object'], }); return this; } // Merge targetWithChanges object into the nextStateValue if ( Array.isArray(targetWithChanges) && Array.isArray(this.nextStateValue) ) { this.nextStateValue = [ ...this.nextStateValue, ...targetWithChanges, ] as any; } else { this.nextStateValue = flatMerge<ValueType>( this.nextStateValue, targetWithChanges, { addNewProperties: config.addNewProperties } ); } // Ingest updated 'nextStateValue' into runtime this.ingest(config); return this; } /** * Fires on each State value change. * * Returns the key/name identifier of the created watcher callback. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#watch) * * @public * @param callback - A function to be executed on each State value change. */ public watch(callback: StateWatcherCallback<ValueType>): string; /** * Fires on each State value change. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#watch) * * @public * @param key - Key/Name identifier of the watcher callback. * @param callback - A function to be executed on each State value change. */ public watch(key: string, callback: StateWatcherCallback<ValueType>): this; public watch( keyOrCallback: string | StateWatcherCallback<ValueType>, callback?: StateWatcherCallback<ValueType> ): this | string { const generateKey = isFunction(keyOrCallback); let _callback: StateWatcherCallback<ValueType>; let key: string; if (generateKey) { key = generateId(); _callback = keyOrCallback as StateWatcherCallback<ValueType>; } else { key = keyOrCallback as string; _callback = callback as StateWatcherCallback<ValueType>; } if (!isFunction(_callback)) { logCodeManager.log('00:03:01', { replacers: ['Watcher Callback', 'function'], }); return this; } this.addSideEffect( key, (instance) => { _callback(instance.value, key); }, { weight: 0 } ); return generateKey ? key : this; } /** * Removes a watcher callback with the specified key/name identifier from the State. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#removewatcher) * * @public * @param key - Key/Name identifier of the watcher callback to be removed. */ public removeWatcher(key: string): this { this.removeSideEffect(key); return this; } /** * Fires on the initial State value assignment and then destroys itself. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#oninaugurated) * * @public * @param callback - A function to be executed after the first State value assignment. */ public onInaugurated(callback: StateWatcherCallback<ValueType>): this { const watcherKey = 'InauguratedWatcherKey'; this.watch(watcherKey, (value, key) => { callback(value, key); this.removeSideEffect(watcherKey); }); return this; } /** * Repeatedly calls the specified callback function, * with a fixed time delay between each call. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#interval) * * @public * @param handler - A function to be executed every delay milliseconds. * @param delay - The time, in milliseconds (thousandths of a second), * the timer should delay in between executions of the specified function. */ public interval( handler: (value: ValueType) => ValueType, delay?: number ): this { if (!isFunction(handler)) { logCodeManager.log('00:03:01', { replacers: ['Interval Callback', 'function'], }); return this; } if (this.currentInterval) { logCodeManager.log('14:03:03', { replacers: [] }, this.currentInterval); return this; } this.currentInterval = setInterval(() => { this.set(handler(this._value)); }, delay ?? 1000); return this; } /** * Cancels a active timed, repeating action * which was previously established by a call to `interval()`. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#clearinterval) * * @public */ public clearInterval(): void { if (this.currentInterval) { clearInterval(this.currentInterval as number); delete this.currentInterval; } } /** * Returns a boolean indicating whether the State exists. * * It calculates the value based on the `computeExistsMethod()` * and whether the State is a placeholder. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#exists) * * @public */ public get exists(): boolean { return !this.isPlaceholder && this.computeExistsMethod(this.value); } /** * Defines the method used to compute the existence of the State. * * It is retrieved on each `exists()` method call * to determine whether the State exists or not. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#computeexists) * * @public * @param method - Method to compute the existence of the State. */ public computeExists(method: ComputeExistsMethod<ValueType>): this { if (!isFunction(method)) { logCodeManager.log('00:03:01', { replacers: ['Compute Exists Method', 'function'], }); return this; } this.computeExistsMethod = method; return this; } /** * Defines the method used to compute the value of the State. * * It is retrieved on each State value change, * in order to compute the new State value * based on the specified compute method. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#computevalue) * * @public * @param method - Method to compute the value of the State. */ public computeValue(method: ComputeValueMethod<ValueType>): this { if (!isFunction(method)) { logCodeManager.log('00:03:01', { replacers: ['Compute Value Method', 'function'], }); return this; } this.computeValueMethod = method; // Initial compute // (not directly computing it here since it is computed once in the runtime!) this.set(this.nextStateValue); return this; } /** * Returns a boolean indicating whether the specified value is equal to the current State value. * * Equivalent to `===` with the difference that it looks at the value * and not on the reference in the case of objects. * * @public * @param value - Value to be compared with the current State value. */ public is(value: ValueType): boolean { return equal(value, this.value); } /** * Returns a boolean indicating whether the specified value is not equal to the current State value. * * Equivalent to `!==` with the difference that it looks at the value * and not on the reference in the case of objects. * * @public * @param value - Value to be compared with the current State value. */ public isNot(value: ValueType): boolean { return notEqual(value, this.value); } /** * Inverts the current State value. * * Some examples are: * - `'jeff'` -> `'ffej'` * - `true` -> `false` * - `[1, 2, 3]` -> `[3, 2, 1]` * - `10` -> `-10` * * @public */ public invert(): this { switch (typeof this.nextStateValue) { case 'boolean': this.set(!this.nextStateValue as any); break; case 'object': if (Array.isArray(this.nextStateValue)) this.set(this.nextStateValue.reverse() as any); break; case 'string': this.set(this.nextStateValue.split('').reverse().join('') as any); break; case 'number': this.set((this.nextStateValue * -1) as any); break; default: logCodeManager.log('14:03:04', { replacers: [typeof this.nextStateValue], }); } return this; } /** * Preserves the State `value` in the corresponding external Storage. * * The State key/name is used as the unique identifier for the Persistent. * If that is not desired or the State has no unique identifier, * please specify a separate unique identifier for the Persistent. * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#persist) * * @public * @param config - Configuration object */ public persist(config: CreateStatePersistentConfigInterface = {}): this { config = defineConfig(config, { key: this._key, }); // Check if State is already persisted if (this.persistent != null && this.isPersisted) return this; // Create Persistent (-> persist value) this.persistent = new StatePersistent<ValueType>(this, config); return this; } /** * Fires immediately after the persisted `value` * is loaded into the State from a corresponding external Storage. * * Registering such callback function makes only sense * when the State is [persisted](https://agile-ts.org/docs/core/state/methods/#persist). * * [Learn more..](https://agile-ts.org/docs/core/state/methods/#onload) * * @public * @param callback - A function to be executed after the externally persisted `value` was loaded into the State. */ public onLoad(callback: (success: boolean) => void): this { if (!this.persistent) return this; if (!isFunction(callback)) { logCodeManager.log('00:03:01', { replacers: ['OnLoad Callback', 'function'], }); return this; } // Register specified callback this.persistent.onLoad = callback; // If State is already persisted ('isPersisted') fire specified callback immediately if (this.isPersisted) callback(true); return this; } /** * Returns the persistable value of the State. * * @internal */ public getPersistableValue(): any { return this._value; } } export interface PatchConfigInterface extends StateIngestConfigInterface, PatchOptionConfigInterface {} export interface PatchOptionConfigInterface { /** * Whether to add new properties to the object during the merge. * @default true */ addNewProperties?: boolean; } export type StateWatcherCallback<T = any> = (value: T, key: string) => void; export type ComputeValueMethod<T = any> = (value: T) => T; export type ComputeExistsMethod<T = any> = (value: T) => boolean;
the_stack
import * as child_process from 'child_process' import { commands, ExtensionContext, LanguageClient, LanguageClientOptions, languages, OutputChannel, ServerOptions, services, Terminal, Uri, window, workspace } from 'coc.nvim' import * as fs from 'fs' import os from 'os' import path from 'path' import { NotificationType, WorkspaceFolder } from 'vscode-languageserver-protocol' import { RLSConfiguration } from './configuration' import SignatureHelpProvider from './providers/signatureHelpProvider' import { ensureComponents, ensureToolchain, rustupUpdate } from './rustup' import { startSpinner, stopSpinner } from './spinner' import { ExecChildProcessResult, execFile } from './utils/child_process' let client: ClientWorkspace export async function activate(context: ExtensionContext): Promise<void> { let { subscriptions } = context let workspaceFolder = workspace.workspaceFolders.find(workspaceFolder => { let folder = Uri.parse(workspaceFolder.uri).fsPath return fs.existsSync(path.join(folder, 'Cargo.toml')) }) let folder = workspaceFolder ? Uri.parse(workspaceFolder.uri).fsPath : workspace.rootPath const config = RLSConfiguration.loadFromWorkspace(Uri.parse(Uri.file(folder).toString()).fsPath) if (!config.enable) return; let channel = window.createOutputChannel('rls') if (!workspaceFolder) { channel.appendLine(`[Warning]: A Cargo.toml file must be at the root of the workspace in order to support all features`) } client = new ClientWorkspace({ uri: Uri.file(folder).toString(), name: path.basename(folder), }, config, channel) client.start(context).catch(_e => { // noop }) subscriptions.push(workspace.onDidChangeWorkspaceFolders(e => { if (e.added) { let folder = e.added.find(workspaceFolder => { let folder = Uri.parse(workspaceFolder.uri).fsPath return fs.existsSync(path.join(folder, 'Cargo.toml')) }) if (folder) channel.appendLine(`[Warning]: Multiple rust workspace folder not supported!`) } })) } export async function deactivate(): Promise<void> { await client.stop() } // We run one RLS and one corresponding language client per workspace folder // (VSCode workspace, not Cargo workspace). This class contains all the per-client // and per-workspace stuff. class ClientWorkspace { // FIXME(#233): Don't only rely on lazily initializing it once on startup, // handle possible `rust-client.*` value changes while extension is running public readonly config: RLSConfiguration public lc: LanguageClient | null = null public readonly folder: WorkspaceFolder constructor(folder: WorkspaceFolder, config: RLSConfiguration, private channel: OutputChannel) { this.config = config this.folder = folder } public async start(context: ExtensionContext) { // These methods cannot throw an error, so we can drop it. startSpinner('RLS', 'Starting') const serverOptions: ServerOptions = async () => { await this.autoUpdate() return this.makeRlsProcess() } const clientOptions: LanguageClientOptions = { // Register the server for Rust files documentSelector: [ { language: 'rust', scheme: 'file' }, { language: 'rust', scheme: 'untitled' }, { pattern: 'Cargo.toml' } ], diagnosticCollectionName: 'rust', synchronize: { configurationSection: 'rust' }, outputChannel: this.channel, // Controls when to focus the channel rather than when to reveal it in the drop-down list revealOutputChannelOn: this.config.revealOutputChannelOn, initializationOptions: { omitInitBuild: true, cmdRun: true, }, workspaceFolder: this.folder, } // Create the language client and start the client. this.lc = new LanguageClient('rust-client', 'Rust Language Server', serverOptions, clientOptions) context.subscriptions.push( languages.registerSignatureHelpProvider(['rust'], new SignatureHelpProvider(this.lc), ['(', ',',] ) ) const promise = this.progressCounter() const disposable = this.lc.start() context.subscriptions.push(disposable) context.subscriptions.push(services.registLanguageClient(this.lc)) this.registerCommands(context) return promise } public registerCommands(context: ExtensionContext) { if (!this.lc) { return } const rustupUpdateDisposable = commands.registerCommand('rls.update', () => { return rustupUpdate(this.config.rustupConfig()) }) context.subscriptions.push(rustupUpdateDisposable) const restartServer = commands.registerCommand('rls.restart', async () => { if (this.lc) { this.lc.stop() } return this.start(context) }) context.subscriptions.push(restartServer) let terminal: Terminal context.subscriptions.push( commands.registerCommand('rls.run', async () => { if (terminal) terminal.dispose() terminal = await workspace.createTerminal({ name: 'cargo run', cwd: workspace.rootPath, env: process.env }) terminal.show(true) terminal.sendText('cargo run') }) ) } public async progressCounter() { if (!this.lc) { return } const runningProgress: Set<string> = new Set() const asPercent = (fraction: number): string => `${Math.round(fraction * 100)}%` await this.lc.onReady() stopSpinner('RLS') this.lc.onNotification(new NotificationType('window/progress'), (progress: any) => { if (progress.done) { runningProgress.delete(progress.id) } else { runningProgress.add(progress.id) } if (runningProgress.size) { let status = '' if (typeof progress.percentage === 'number') { status = asPercent(progress.percentage) } else if (progress.message) { status = progress.message } else if (progress.title) { status = `[${progress.title.toLowerCase()}]` } startSpinner('RLS', status) } else { stopSpinner('RLS') } }) } public async stop() { let promise: Thenable<void> = Promise.resolve(void 0) if (this.lc) { promise = this.lc.stop() } return promise.then(() => { }) } public async getSysroot(env: Object): Promise<string> { let output: ExecChildProcessResult try { if (this.config.rustupDisabled) { output = await execFile( 'rustc', ['--print', 'sysroot'], { env } as any ) } else { output = await execFile( this.config.rustupPath, ['run', this.config.channel, 'rustc', '--print', 'sysroot'], { env } as any ) } } catch (e) { throw new Error(`Error getting sysroot from \`rustc\`: ${e}`) } if (!output.stdout) { throw new Error(`Couldn't get sysroot from \`rustc\`: Got no ouput`) } return output.stdout.replace('\n', '').replace('\r', '') } // Make an evironment to run the RLS. public async makeRlsEnv(setLibPath = false): Promise<any> { const env = process.env let sysroot: string | undefined try { sysroot = await this.getSysroot(env) } catch (err) { this.channel.appendLine('[Error] ' + err.message) this.channel.appendLine(`Let's retry with extended $PATH`) env.PATH = `${os.homedir()}/.cargo/bin:${env.PATH || ''}` try { sysroot = await this.getSysroot(env) } catch (e) { // tslint:disable-next-line: no-console console.error('Error reading sysroot (second try)', e) window.showMessage(`Error reading sysroot: ${e.message}`, 'error') return env } } this.channel.appendLine(`Setting sysroot to` + sysroot) if (setLibPath) { function appendEnv(envVar: string, newComponent: string) { const old = process.env[envVar] return old ? `${newComponent}:${old}` : newComponent } env.DYLD_LIBRARY_PATH = appendEnv('DYLD_LIBRARY_PATH', path.join(sysroot, 'lib')) env.LD_LIBRARY_PATH = appendEnv('LD_LIBRARY_PATH', path.join(sysroot, 'lib')) } return env } public async makeRlsProcess(): Promise<child_process.ChildProcess> { // Allow to override how RLS is started up. const rls_path = this.config.rlsPath let childProcess: child_process.ChildProcess if (rls_path) { const env = await this.makeRlsEnv(this.config.setLibPath) this.channel.appendLine(`running: ${rls_path} at ${workspace.rootPath}`) childProcess = child_process.spawn(rls_path, [], { env, cwd: workspace.rootPath }) } else if (this.config.rustupDisabled) { const env = await this.makeRlsEnv(this.config.setLibPath) this.channel.appendLine(`running: rls at ${workspace.rootPath}`) childProcess = child_process.spawn('rls', [], { env, cwd: workspace.rootPath }) } else { let config = this.config.rustupConfig() await ensureToolchain(config) // We only need a rustup-installed RLS if we weren't given a // custom RLS path. await ensureComponents(config) // return child_process.spawn(config.path, ['run', config.channel, 'rls'], { env, cwd: workspace.rootPath }) const env = await this.makeRlsEnv() this.channel.appendLine(`running: ${config.path} run ${config.channel} rls, at ${workspace.rootPath}`) childProcess = child_process.spawn(config.path, ['run', config.channel, 'rls'], { env, cwd: workspace.rootPath }) } childProcess.on('error', (err: { code?: string; message: string }) => { if (err.code === 'ENOENT') { stopSpinner('RLS could not be started') window.showMessage(`Could not spawn RLS: ${err.message}`, 'error') this.channel.appendLine(`Could not spawn RLS: ${err.message}`) } }) if (this.config.logToFile) { const logPath = path.join(workspace.rootPath, 'rls' + Date.now() + '.log') const logStream = fs.createWriteStream(logPath, { flags: 'w+' }) childProcess.stderr.pipe(logStream) } return childProcess } public async autoUpdate() { if (this.config.updateOnStartup && !this.config.rustupDisabled) { await rustupUpdate(this.config.rustupConfig()) } } }
the_stack
import * as assert from 'assert'; import { Hanging } from 'python-indent-parser'; // You can import and use all API from the 'vscode' module // as well as import your extension to test it // import * as vscode from 'vscode'; import * as indent from '../../indent'; suite("dedent current line", function () { test("normal else", function () { assert.equal(4, indent.currentLineDedentation( [ "if True:", " pass", " else:" ], 4)); }); test("else with small tabsize", function () { assert.equal(2, indent.currentLineDedentation( [ " if True:", " pass", " else:" ], 2)); }); test("else resulting in over dedentation", function () { assert.equal(0, indent.currentLineDedentation( [ "if True:", " pass", "else:" ], 4)); }); test("else resulting in over dedentation, 2", function () { assert.equal(2, indent.currentLineDedentation( [ "if True:", " pass", " else:" ], 4)); }); test("elif", function () { assert.equal(2, indent.currentLineDedentation( [ " if True:", " pass", " elif False:" ], 2)); }); test("except", function () { assert.equal(2, indent.currentLineDedentation( [ " try:", " pass", " except ValueError:" ], 2)); }); test("finally", function () { assert.equal(2, indent.currentLineDedentation( [ " try:", " pass", " except ValueError:", " pass", " finally:" ], 2)); }); test("try...else", function () { assert.equal(2, indent.currentLineDedentation( [ " try:", " pass", " except ValueError:", " pass", " else:" ], 2)); }); test("if...try...else do not go past try", function () { assert.equal(0, indent.currentLineDedentation( [ "if True:", " try:", " pass", " except ValueError:", " pass", " else:" ], 2)); }); test("for...else", function () { assert.equal(2, indent.currentLineDedentation( [ " for i in range(5):", " pass", " else:" ], 2)); }); test("if...for...else", function () { assert.equal(2, indent.currentLineDedentation( [ "if True:", " for i in range(5):", " pass", " else:" ], 2)); }); test("if...for...else do not go past for", function () { assert.equal(0, indent.currentLineDedentation( [ "if True:", " for i in range(5):", " pass", " else:" ], 2)); }); test("while...else", function () { assert.equal(2, indent.currentLineDedentation( [ " while True:", " pass", " else:" ], 2)); }); test("if...while...else", function () { assert.equal(2, indent.currentLineDedentation( [ "if True:", " while True:", " pass", " else:" ], 2)); }); test("if...while...else do not go past while", function () { assert.equal(0, indent.currentLineDedentation( [ "if True:", " while True:", " pass", " else:" ], 2)); }); test("do not dedent past matching if", function () { assert.equal(0, indent.currentLineDedentation( [ " if True:", " pass", " else:" ], 2)); }); test("do not dedent past FIRST matching if", function () { assert.equal(2, indent.currentLineDedentation( [ " if True:", " if False:", " pass", " else:", ], 2)); }); test("do not dedent past FIRST matching if, already dedented", function () { assert.equal(0, indent.currentLineDedentation( [ " if True:", " if False:", " pass", " else:", ], 2)); }); test("do not re-indent with nested if", function () { assert.equal(0, indent.currentLineDedentation( [ " if True:", " if False:", " pass", " else:", ], 2)); }); }); suite("extend comment line", function () { test("should extend", function () { assert.equal(true, indent.extendCommentToNextLine( " # this is a comment", 8)); }); test("no extend if cursor at end of line", function () { assert.equal(false, indent.extendCommentToNextLine( " # this is a comment", " # this is a comment".length)); }); test("no extend if cursor left of comment", function () { assert.equal(false, indent.extendCommentToNextLine( " # this is a comment", 0)); assert.equal(false, indent.extendCommentToNextLine( " # this is a comment", 1)); assert.equal(false, indent.extendCommentToNextLine( " # this is a comment", 2)); }); test("no extend if only whitespace to right of cursor", function () { assert.equal(false, indent.extendCommentToNextLine( " # x ", 5)); assert.equal(false, indent.extendCommentToNextLine( " # x ", 6)); assert.equal(false, indent.extendCommentToNextLine( " # x ", 7)); }); }); suite("trim whitespace-only lines", function () { test("do not trim whitespace from empty line without setting", async () => { assert.equal(false, indent.trimCurrentLine(" ", false)); }); test("do not trim whitespace from non-empty line without setting", function () { assert.equal(false, indent.trimCurrentLine(" a", false)); }); test("do not trim whitespace from non-empty line with setting", async () => { assert.equal(false, indent.trimCurrentLine(" a", true)); }); test("trim whitespace on empty line with setting", function () { assert.equal(true, indent.trimCurrentLine(" ", true)); }); test("trim whitespace on empty line with tabs with setting", function () { assert.equal(true, indent.trimCurrentLine(" \t", true)); }); }); suite("detect whitespace length", function () { test("empty string", function () { assert.equal(0, indent.startingWhitespaceLength("")); }); test("space-only string", function () { assert.equal(0, indent.startingWhitespaceLength(" ")); }); test("tab-only-2 string", function () { assert.equal(0, indent.startingWhitespaceLength("\t\t")); }); test("arbitrary whitespace-only string", function () { assert.equal(0, indent.startingWhitespaceLength(" \t\t ")); }); test("real example 1", function () { assert.equal(4, indent.startingWhitespaceLength(" 4")); }); test("real example 2", function () { assert.equal(4, indent.startingWhitespaceLength(" 456")); }); test("real example 3", function () { assert.equal(5, indent.startingWhitespaceLength(" \t56")); }); test("real example 4", function () { assert.equal(1, indent.startingWhitespaceLength(" Quota Era Demonstratum")); }); }); suite("integration tests", function () { const simpleCases: [string, string][] = [ [ "data = {'a': 0,|}", "data = {'a': 0,\n }" ], [ "def f():|", "def f():\n " ], [ ` data = {'a': 0, 'b': [[1, 2,],|]}`, ` data = {'a': 0, 'b': [[1, 2,], ]}` ], [ ` data = {'a': 0, 'b': [[1, 2,], [3, 4]], 'c': 5}|`, ` data = {'a': 0, 'b': [[1, 2,], [3, 4]], 'c': 5} `, ], [ ` def f(): if first and second:|`, ` def f(): if first and second: `, ], [ ` def f(): if first and second: raise ValueError('no')|`, ` def f(): if first and second: raise ValueError('no') `, ], [ ` def f(): if first and second: raise ValueError('no') else:|`, ` def f(): if first and second: raise ValueError('no') else: `, ], [ ` def f(): if first and second: raise ValueError('no') else: print('hello')|`, ` def f(): if first and second: raise ValueError('no') else: print('hello') `, ], [ ` def f(): if first and second: raise ValueError('no') else: print('hello') return 'done'|`, ` def f(): if first and second: raise ValueError('no') else: print('hello') return 'done' `, ] ]; simpleCases.forEach((input_output, index) => { let paramGrid: [boolean, boolean][] = [ [false, false], [false, true], [true, false], [true, true]]; test("simple case # " + (index + 1).toString(), async () => { let lastLine = input_output[0].split('\n').pop()!; let lines = input_output[0].replace(/\|.*/, '').split('\n'); paramGrid.forEach((params) => { let edits = indent.editsToMake( lines, lastLine.replace('|', ''), 4, lines.length - 1, lastLine.indexOf('|'), params[0], params[1], ); let result = input_output[0].replace('|', edits.insert); assert.equal(input_output[1], result); assert.equal(Hanging.None, edits.hanging); assert.equal(0, edits.deletes.length); }); }); }); test("requires delete # 1", async () => { let edits = indent.editsToMake( [ "if True:", " print('hi')", " else:" ], " else:", 2, 2, " else:".length, false, false, ); assert.equal("\n ", edits.insert); assert.equal(1, edits.deletes.length); assert.equal(2, edits.deletes[0].start.line); assert.equal(0, edits.deletes[0].start.character); assert.equal(2, edits.deletes[0].end.line); assert.equal(2, edits.deletes[0].end.character); assert.equal(Hanging.None, edits.hanging); }); test("requires delete # 2", async () => { let edits = indent.editsToMake( [ "if True:", " print('hi')", " " ], " ", 2, 2, " ".length, true, false, ); assert.equal("\n ", edits.insert); assert.equal(1, edits.deletes.length); assert.equal(2, edits.deletes[0].start.line); assert.equal(0, edits.deletes[0].start.character); assert.equal(2, edits.deletes[0].end.line); assert.equal(2, edits.deletes[0].end.character); assert.equal(Hanging.None, edits.hanging); }); test("requires delete # 3", async () => { let edits = indent.editsToMake( [ "if True:", " print('hi')", " # this is a" ], " # this is a long comment", 2, 2, " # this is a".length, true, false, ); assert.equal("\n # ", edits.insert); assert.equal(1, edits.deletes.length); assert.equal(2, edits.deletes[0].start.line); assert.equal(13, edits.deletes[0].start.character); assert.equal(2, edits.deletes[0].end.line); assert.equal(14, edits.deletes[0].end.character); assert.equal(Hanging.None, edits.hanging); }); test("hanging indent # 1", async () => { let edits = indent.editsToMake( [ "", "def f(", ], "def f():", 2, 1, "def f(".length, false, false, ); assert.equal(0, edits.deletes.length); assert.equal(Hanging.Full, edits.hanging); }); test("hanging indent # 2", async () => { let edits = indent.editsToMake( [ "", "def f(", ], "def f():", 2, 1, "def f(".length, false, true, ); assert.equal("\n ", edits.insert); assert.equal(0, edits.deletes.length); assert.equal(Hanging.Partial, edits.hanging); }); test("respects trimLinesWithOnlyWhitespace parameter", async () => { let edits = indent.editsToMake( [ "def f():", " # this is a ", ], " # this is a long comment", 2, 3, " # this is a ".length, false, false, ); assert.equal("\n # ", edits.insert); assert.equal(0, edits.deletes.length); assert.equal(Hanging.None, edits.hanging); }); });
the_stack
import * as chai from "chai"; import * as chaiAsPromised from "chai-as-promised"; import { ECClass, ECClassModifier, ECVersion, EntityClass, PrimitiveProperty, PrimitiveType, Schema, SchemaContext, SchemaItemKey, SchemaKey, SchemaMatchType, } from "@itwin/ecschema-metadata"; import { SchemaContextEditor } from "../../Editing/Editor"; import { BisTestHelper } from "../TestUtils/BisTestHelper"; const expect = chai.expect; chai.use(chaiAsPromised); describe("SchemaEditor tests", () => { let testEditor: SchemaContextEditor; let testSchema: Schema; let testSchemaKey: SchemaKey; let bisSchema: Schema; let bisSchemaKey: SchemaKey; let context: SchemaContext; beforeEach(async () => { context = await BisTestHelper.getNewContext(); testEditor = new SchemaContextEditor(context); const result = await context.getSchema(new SchemaKey("BisCore", 1, 0, 1), SchemaMatchType.Latest); if (!result) throw new Error("Could not retrieve BisCore schema."); bisSchema = result; bisSchemaKey = bisSchema!.schemaKey; }); describe("Schema tests", () => { it("should create a new schema and return a SchemaEditResults", async () => { const result = await testEditor.createSchema("testSchema", "test", 1, 0, 0); expect(result).to.not.be.undefined; expect(result.schemaKey).to.not.be.undefined; expect(result.schemaKey).to.deep.equal(new SchemaKey("testSchema", new ECVersion(1,0,0))); }); }); describe("Class tests", () => { beforeEach(async () => { const result = await testEditor.createSchema("testSchema", "test", 1, 0, 0); expect(result).to.not.be.undefined; testSchemaKey = result.schemaKey as SchemaKey; const result2 = await testEditor.schemaContext.getCachedSchema(testSchemaKey); if (!result2) throw new Error("Could not retrieve cached schema!"); testSchema = result2; }); it("should create BisCore.Element subclass successfully", async () => { const elementKey = new SchemaItemKey("Element", bisSchemaKey); const result = await testEditor.entities.createElement(testSchemaKey, "testElement", ECClassModifier.None, elementKey, "test element"); expect(result).to.not.be.undefined; expect(result.itemKey).to.not.be.undefined; expect(result.itemKey).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); const element = await testSchema!.getItem("testElement") as EntityClass; expect(element).to.not.be.undefined; const baseClass = await element.baseClass; expect(baseClass).to.not.be.undefined; expect(baseClass?.key).to.deep.equal(new SchemaItemKey("Element", bisSchemaKey)); }); it("should create BisCore.Element grandchild successfully", async () => { const elementKey = new SchemaItemKey("Element", bisSchemaKey); const result = await testEditor.entities.createElement(testSchemaKey, "testElement", ECClassModifier.None, elementKey, "test element"); expect(result).to.not.be.undefined; expect(result.itemKey).to.not.be.undefined; expect(result.itemKey).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); const element = await testSchema!.getItem("testElement") as EntityClass; expect(element).to.not.be.undefined; const baseClass = await element.baseClass; expect(baseClass).to.not.be.undefined; expect(baseClass?.key).to.deep.equal(new SchemaItemKey("Element", bisSchemaKey)); const result2 = await testEditor.entities.createElement(testSchemaKey, "testElement2", ECClassModifier.None, result.itemKey!, "test element2"); expect(result2).to.not.be.undefined; expect(result2.itemKey).to.not.be.undefined; expect(result2.itemKey).to.deep.equal(new SchemaItemKey("testElement2", testSchemaKey)); const element2 = await testSchema!.getItem("testElement2") as EntityClass; expect(element2).to.not.be.undefined; const baseClass2 = await element2.baseClass; expect(baseClass2).to.not.be.undefined; expect(baseClass2?.key).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); }); it("should create BisCore.ElementUniqueAspect subclass successfully", async () => { const uniqueAspectKey = new SchemaItemKey("ElementUniqueAspect", bisSchemaKey); const result = await testEditor.entities.createElementUniqueAspect(testSchemaKey, "testElement", ECClassModifier.None, uniqueAspectKey, "test element"); expect(result).to.not.be.undefined; expect(result.itemKey).to.not.be.undefined; expect(result.itemKey).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); const element = await testSchema!.getItem("testElement") as ECClass; expect(element).to.not.be.undefined; const baseClass = await element?.baseClass; expect(baseClass).to.not.be.undefined; expect(baseClass).to.eql(await testEditor.schemaContext.getSchemaItem(uniqueAspectKey)); }); it("should create BisCore.ElementUniqueAspect grandchild successfully", async () => { const elementKey = new SchemaItemKey("ElementUniqueAspect", bisSchemaKey); const result = await testEditor.entities.createElementUniqueAspect(testSchemaKey, "testElement", ECClassModifier.None, elementKey, "test element"); expect(result).to.not.be.undefined; expect(result.itemKey).to.not.be.undefined; expect(result.itemKey).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); const element = await testSchema!.getItem("testElement") as EntityClass; expect(element).to.not.be.undefined; const baseClass = await element.baseClass; expect(baseClass).to.not.be.undefined; expect(baseClass?.key).to.deep.equal(new SchemaItemKey("ElementUniqueAspect", bisSchemaKey)); const result2 = await testEditor.entities.createElementUniqueAspect(testSchemaKey, "testElement2", ECClassModifier.None, result.itemKey!, "test element2"); expect(result2).to.not.be.undefined; expect(result2.itemKey).to.not.be.undefined; expect(result2.itemKey).to.deep.equal(new SchemaItemKey("testElement2", testSchemaKey)); const element2 = await testSchema!.getItem("testElement2") as EntityClass; expect(element2).to.not.be.undefined; const baseClass2 = await element2.baseClass; expect(baseClass2).to.not.be.undefined; expect(baseClass2?.key).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); }); it("should create BisCore.ElementMultiAspect subclass successfully", async () => { const multiAspectKey = new SchemaItemKey("ElementMultiAspect", bisSchemaKey); const result = await testEditor.entities.createElementMultiAspect(testSchemaKey, "testElement", ECClassModifier.None, multiAspectKey, "test element"); expect(result).to.not.be.undefined; expect(result.itemKey).to.not.be.undefined; expect(result.itemKey).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); const element = await testSchema!.getItem("testElement") as ECClass; expect(element).to.not.be.undefined; const baseClass = await element?.baseClass; expect(baseClass).to.not.be.undefined; expect(baseClass).to.eql(await testEditor.schemaContext.getSchemaItem(multiAspectKey)); }); it("should create BisCore.ElementMultiAspect grandchild successfully", async () => { const elementKey = new SchemaItemKey("ElementMultiAspect", bisSchemaKey); const result = await testEditor.entities.createElementMultiAspect(testSchemaKey, "testElement", ECClassModifier.None, elementKey, "test element"); expect(result).to.not.be.undefined; expect(result.itemKey).to.not.be.undefined; expect(result.itemKey).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); const element = await testSchema!.getItem("testElement") as EntityClass; expect(element).to.not.be.undefined; const baseClass = await element.baseClass; expect(baseClass).to.not.be.undefined; expect(baseClass?.key).to.deep.equal(new SchemaItemKey("ElementMultiAspect", bisSchemaKey)); const result2 = await testEditor.entities.createElementMultiAspect(testSchemaKey, "testElement2", ECClassModifier.None, result.itemKey!, "test element2"); expect(result2).to.not.be.undefined; expect(result2.itemKey).to.not.be.undefined; expect(result2.itemKey).to.deep.equal(new SchemaItemKey("testElement2", testSchemaKey)); const element2 = await testSchema!.getItem("testElement2") as EntityClass; expect(element2).to.not.be.undefined; const baseClass2 = await element2.baseClass; expect(baseClass2).to.not.be.undefined; expect(baseClass2?.key).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); }); it("Creating Element, try subclassing unsupported base class, throws", async () => { const elementKey = new SchemaItemKey("PhysicalModel", bisSchemaKey); await expect(testEditor.entities.createElement(testSchemaKey, "testElement", ECClassModifier.None, elementKey, "test element")).to.be.rejectedWith(Error, "The class testElement could not be created because the specified base class BisCore.PhysicalModel is not an Element."); }); it("Creating ElementMultiAspect, try subclassing unsupported base class, throws", async () => { const uniqueAspectKey = new SchemaItemKey("PhysicalModel", bisSchemaKey); await expect(testEditor.entities.createElementUniqueAspect(testSchemaKey, "testElement", ECClassModifier.None, uniqueAspectKey, "test element")).to.be.rejectedWith(Error, "The class testElement could not be created because the specified base class BisCore.PhysicalModel is not an ElementUniqueAspect."); }); it("Creating ElementMultiAspect, try subclassing unsupported base class, throws", async () => { const multiAspectKey = new SchemaItemKey("PhysicalModel", bisSchemaKey); await expect(testEditor.entities.createElementMultiAspect(testSchemaKey, "testElement", ECClassModifier.None, multiAspectKey, "test element")).to.be.rejectedWith(Error, "The class testElement could not be created because the specified base class BisCore.PhysicalModel is not an ElementMultiAspect."); }); it("should delete class successfully", async () => { const multiAspectKey = new SchemaItemKey("ElementMultiAspect", bisSchemaKey); const result = await testEditor.entities.createElementMultiAspect(testSchemaKey, "testElement", ECClassModifier.None, multiAspectKey, "test element"); expect(result).to.not.be.undefined; expect(result.itemKey).to.not.be.undefined; expect(result.itemKey).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); let element = await testSchema!.getItem("testElement"); expect(element).to.not.be.undefined; await testEditor.entities.delete(result.itemKey!); expect(result.itemKey).to.not.be.undefined; expect(result.itemKey).to.deep.equal(new SchemaItemKey("testElement", testSchemaKey)); element = await testSchema!.getItem("testElements"); expect(element).to.be.undefined; const classes = testSchema!.getClasses(); for (const _class of classes) { expect(false, "Expected no classes in the schema.").to.be.true; } }); describe("Property tests", () => { let testEntity: EntityClass | undefined; let entityKey: SchemaItemKey | undefined; beforeEach(async () => { const elementKey = new SchemaItemKey("Element", bisSchemaKey); const result = await testEditor.entities.create(testSchemaKey, "testElement", ECClassModifier.None, "test element", elementKey); entityKey = result.itemKey; testEntity = await testSchema!.getItem("testElement"); }); it("should successfully create a PrimitiveProperty of type double", async () => { const createResult = await testEditor.entities.createProperty(entityKey as SchemaItemKey, "TestProperty", PrimitiveType.Double, "p"); const property = await testEntity?.getProperty(createResult.propertyName!) as PrimitiveProperty; expect(property.class.key).to.eql(createResult.itemKey); expect(property.name).to.eql(createResult.propertyName); expect(property.name).to.equal("p_TestProperty"); }); it("should successfully create a PrimitiveProperty of type String", async () => { const createResult = await testEditor.entities.createProperty(entityKey as SchemaItemKey, "TestProperty", PrimitiveType.String, "p"); const property = await testEntity?.getProperty(createResult.propertyName!) as PrimitiveProperty; expect(property.class.key).to.eql(createResult.itemKey); expect(property.name).to.eql(createResult.propertyName); expect(property.name).to.equal("p_TestProperty"); }); it("should successfully create a PrimitiveProperty of type DateTime", async () => { const createResult = await testEditor.entities.createProperty(entityKey as SchemaItemKey, "TestProperty", PrimitiveType.DateTime, "p"); const property = await testEntity?.getProperty(createResult.propertyName!) as PrimitiveProperty; expect(property.class.key).to.eql(createResult.itemKey); expect(property.name).to.eql(createResult.propertyName); expect(property.name).to.equal("p_TestProperty"); }); it("should successfully create a PrimitiveProperty of type Integer", async () => { const createResult = await testEditor.entities.createProperty(entityKey as SchemaItemKey, "TestProperty", PrimitiveType.Integer, "p"); const property = await testEntity?.getProperty(createResult.propertyName!) as PrimitiveProperty; expect(property.class.key).to.eql(createResult.itemKey); expect(property.name).to.eql(createResult.propertyName); expect(property.name).to.equal("p_TestProperty"); }); it("try to create a property of unsupported type, throws", async () => { await expect(testEditor.entities.createProperty(entityKey as SchemaItemKey, "TestProperty", PrimitiveType.Boolean, "p")).to.be.rejectedWith(Error, "Property creation is restricted to type Double, String, DateTime, and Integer."); }); it("should successfully delete PrimitiveProperty.", async () => { const createResult = await testEditor.entities.createProperty(entityKey as SchemaItemKey, "TestProperty", PrimitiveType.Double, "p"); let property = await testEntity?.getProperty(createResult.propertyName!) as PrimitiveProperty; expect(property.class.key).to.eql(createResult.itemKey); expect(property.name).to.eql(createResult.propertyName); const delResult = await testEditor.entities.deleteProperty(entityKey as SchemaItemKey, "p_TestProperty"); expect(delResult.itemKey).to.eql(entityKey); expect(delResult.propertyName).to.eql("p_TestProperty"); // Should get undefined since property has been deleted property = await testEntity?.getProperty(createResult.propertyName!) as PrimitiveProperty; expect(property).to.be.undefined; }); }); }); });
the_stack
import 'chrome://resources/polymer/v3_0/iron-media-query/iron-media-query.js'; import './styles.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {afterNextRender, html} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {ImageTile} from '../../common/constants.js'; import {isNonEmptyArray, promisifyOnload} from '../../common/utils.js'; import {sendCurrentWallpaperAssetId, sendImageTiles, sendPendingWallpaperAssetId, sendVisible} from '../iframe_api.js'; import {CurrentWallpaper, OnlineImageType, WallpaperCollection, WallpaperImage, WallpaperType} from '../personalization_app.mojom-webui.js'; import {DisplayableImage} from '../personalization_reducers.js'; import {PersonalizationRouter} from '../personalization_router_element.js'; import {WithPersonalizationStore} from '../personalization_store.js'; import {isWallpaperImage} from '../utils.js'; let sendCurrentWallpaperAssetIdFunction = sendCurrentWallpaperAssetId; let sendImageTilesFunction = sendImageTiles; /** * Mock out the images iframe api functions for testing. Return promises that * are resolved when the function is called by |WallpaperImagesElement|. */ interface PromisifyResult { sendCurrentWallpaperAssetId: Promise<unknown>; sendImageTiles: Promise<unknown>; } export function promisifyImagesIframeFunctionsForTesting(): PromisifyResult { const resolvers = {} as {[key in keyof PromisifyResult]: (_: unknown) => void}; const promises = (['sendCurrentWallpaperAssetId', 'sendImageTiles'] as (keyof PromisifyResult)[]) .reduce((result, next) => { result[next] = new Promise(resolve => resolvers[next] = resolve); return result; }, {} as PromisifyResult); sendCurrentWallpaperAssetIdFunction = (...args) => resolvers['sendCurrentWallpaperAssetId'](args); sendImageTilesFunction = (...args) => resolvers['sendImageTiles'](args); return promises; } /** * If |current| is set and is an online wallpaper (include daily refresh * wallpaper), return the assetId of that image. Otherwise returns null. */ function getAssetId(current: CurrentWallpaper|null): bigint|undefined { if (current == null) { return undefined; } if (current.type !== WallpaperType.kOnline && current.type !== WallpaperType.kDaily) { return undefined; } try { return BigInt(current.key); } catch (e) { console.warn('Required a BigInt value here', e); return undefined; } } /** * Return a list of tile where each tile contains a single image. */ export function getRegularImageTiles(images: WallpaperImage[]): ImageTile[] { return images.reduce((result, next) => { result.push({ assetId: next.assetId, attribution: next.attribution, preview: [next.url], }); return result; }, [] as ImageTile[]); } /** * Return a list of tiles capturing units of Dark/Light images. */ export function getDarkLightImageTiles( isDarkModeActive: boolean, images: WallpaperImage[]): ImageTile[] { const tileMap = images.reduce((result, next) => { if (result.has(next.unitId)) { // Add light url to the front and dark url to the back of the preview. if (next.type === OnlineImageType.kLight) { result.get(next.unitId)!['preview'].unshift(next.url); } else { result.get(next.unitId)!['preview'].push(next.url); } } else { result.set(next.unitId, { preview: [next.url], unitId: next.unitId, }); } // Populate the assetId and attribution based on image type and system's // color mode. if ((isDarkModeActive && next.type !== OnlineImageType.kLight) || (!isDarkModeActive && next.type !== OnlineImageType.kDark)) { result.get(next.unitId)!['assetId'] = next.assetId; result.get(next.unitId)!['attribution'] = next.attribution; } return result; }, new Map() as Map<bigint, ImageTile>); return [...tileMap.values()]; } export class WallpaperImages extends WithPersonalizationStore { static get is() { return 'wallpaper-images'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * Hidden state of this element. Used to notify iframe of visibility * changes. */ hidden: { type: Boolean, reflectToAttribute: true, observer: 'onHiddenChanged_', }, /** * The current collection id to display. */ collectionId: String, collections_: Array, collectionsLoading_: Boolean, images_: Object, /** * Mapping of collection_id to boolean. */ imagesLoading_: Object, currentSelected_: { type: Object, observer: 'onCurrentSelectedChanged_', }, /** * The pending selected image. */ pendingSelected_: { type: Object, observer: 'onPendingSelectedChanged_', }, hasError_: { type: Boolean, // Call computed functions with their dependencies as arguments so that // polymer knows when to re-run the computation. computed: 'computeHasError_(images_, imagesLoading_, collections_, collectionsLoading_, collectionId)', }, /** * In order to prevent re-sending images every time a collection loads in * the background, calculate this intermediate boolean. That way * |onImagesUpdated_| will re-run whenever this value flips from false to * true, rather than each time a new collection is changed in the * background. */ hasImages_: { type: Boolean, computed: 'computeHasImages_(images_, imagesLoading_, collectionId)', }, /** * Whether dark mode is the active preferred color scheme. */ isDarkModeActive_: { type: Boolean, value: false, }, }; } hidden: boolean; collectionId: string; private collections_: WallpaperCollection[]|null; private collectionsLoading_: boolean; private images_: Record<string, WallpaperImage[]|null>; private imagesLoading_: Record<string, boolean>; private currentSelected_: CurrentWallpaper|null; private pendingSelected_: DisplayableImage|null; private hasError_: boolean; private hasImages_: boolean; private isDarkModeActive_: boolean; private iframePromise_: Promise<HTMLIFrameElement>; static get observers() { return [ 'onImagesUpdated_(hasImages_, hasError_, collectionId, isDarkModeActive_)', ]; } constructor() { super(); this.iframePromise_ = promisifyOnload(this, 'images-iframe', afterNextRender) as Promise<HTMLIFrameElement>; } connectedCallback() { super.connectedCallback(); this.watch<WallpaperImages['images_']>( 'images_', state => state.wallpaper.backdrop.images); this.watch<WallpaperImages['imagesLoading_']>( 'imagesLoading_', state => state.wallpaper.loading.images); this.watch<WallpaperImages['collections_']>( 'collections_', state => state.wallpaper.backdrop.collections); this.watch<WallpaperImages['collectionsLoading_']>( 'collectionsLoading_', state => state.wallpaper.loading.collections); this.watch<WallpaperImages['currentSelected_']>( 'currentSelected_', state => state.wallpaper.currentSelected); this.watch<WallpaperImages['pendingSelected_']>( 'pendingSelected_', state => state.wallpaper.pendingSelected); this.updateFromStore(); } /** * Notify iframe that this element visibility has changed. */ private async onHiddenChanged_(hidden: boolean) { if (!hidden) { this.shadowRoot!.getElementById('main')!.focus(); } const iframe = await this.iframePromise_; sendVisible(iframe.contentWindow!, !hidden); } private async onCurrentSelectedChanged_(selected: CurrentWallpaper|null) { const assetId = getAssetId(selected); const iframe = await this.iframePromise_; sendCurrentWallpaperAssetIdFunction(iframe.contentWindow!, assetId); } private async onPendingSelectedChanged_(pendingSelected: DisplayableImage| null) { const iframe = await this.iframePromise_; sendPendingWallpaperAssetId( iframe.contentWindow!, isWallpaperImage(pendingSelected) ? pendingSelected.assetId : undefined); } /** * Determine whether the current collection failed to load or is not a valid * |collectionId|. Check that collections list loaded successfully, and that * the collection with id |collectionId| also loaded successfully. */ private computeHasError_( images: Record<string, WallpaperImage>, imagesLoading: Record<string, boolean>, collections: WallpaperCollection[], collectionsLoading: boolean, collectionId: string): boolean { // Not yet initialized or still loading. if (!imagesLoading || !collectionId || collectionsLoading) { return false; } // Failed to load collections or unknown collectionId. if (!isNonEmptyArray(collections) || !collections.some(collection => collection.id === collectionId)) { return true; } // Specifically check === false to guarantee that key is in the object and // set as false. return imagesLoading[collectionId] === false && !isNonEmptyArray(images[collectionId]); } private computeHasImages_( images: Record<string, WallpaperImage>, imagesLoading: Record<string, boolean>, collectionId: string): boolean { return !!images && !!imagesLoading && // Specifically check === false again here. imagesLoading[collectionId] === false && isNonEmptyArray(images[collectionId]); } /** * Send images if loading is ready and we have some images. Punt back to * main page if there is an error viewing this collection. */ private async onImagesUpdated_( hasImages: boolean, hasError: boolean, collectionId: string, isDarkModeActive: boolean) { if (hasError) { console.warn('An error occurred while loading collections or images'); // Navigate back to main page and refresh. PersonalizationRouter.reloadAtWallpaper(); return; } if (hasImages && collectionId) { const iframe = await this.iframePromise_; const imageArr = this.images_[collectionId]; const isDarkLightModeEnabled = loadTimeData.getBoolean('isDarkLightModeEnabled'); if (isDarkLightModeEnabled) { sendImageTilesFunction( iframe.contentWindow!, getDarkLightImageTiles(isDarkModeActive, imageArr!)); } else { sendImageTilesFunction( iframe.contentWindow!, getRegularImageTiles(imageArr!)); } } } private getMainAriaLabel_( collectionId: string, collections: WallpaperCollection[]) { if (!collectionId || !Array.isArray(collections)) { return ''; } const collection = collections.find(collection => collection.id === collectionId); if (!collection) { console.warn('Did not find collection matching collectionId'); return ''; } return collection.name; } } customElements.define(WallpaperImages.is, WallpaperImages);
the_stack
'use strict'; import 'chord/css!../../media/artist'; import * as React from 'react'; import { connect } from 'react-redux'; import { getLikeAndPlayCount } from 'chord/workbench/api/utils/statistic'; import { ESize } from 'chord/music/common/size'; import { IArtistViewProps } from 'chord/workbench/parts/mainView/browser/component/artist/props/artist'; import { IStateGlobal } from 'chord/workbench/api/common/state/stateGlobal'; import SongItemView from 'chord/workbench/parts/common/component/songItem'; import AlbumItemView from 'chord/workbench/parts/common/component/albumItem'; import { ViewMorePlusItem } from 'chord/workbench/parts/common/component/viewMoreItem'; import { getMoreSongs, getMoreAlbums } from 'chord/workbench/parts/mainView/browser/action/artist'; import { handlePlayArtist } from 'chord/workbench/parts/player/browser/action/playArtist'; import { MenuButton } from 'chord/workbench/parts/common/component/buttons'; import { showArtistMenu } from 'chord/workbench/parts/menu/browser/action/menu'; import { musicApi } from 'chord/music/core/api'; function ArtistNavMenu({ view, changeArtistNavMenuView }) { return ( <nav className='search-nav-container'> <ul className='search-nav-ul'> <li className='search-nav-li'> <div className={`search-nav-item link-subtle cursor-pointer ${view == 'overview' ? 'search-nav-item__active' : ''}`} onClick={() => changeArtistNavMenuView('overview')}> OVERVIEW</div> </li> <li className='search-nav-li'> <div className={`search-nav-item link-subtle cursor-pointer ${view == 'songs' ? 'search-nav-item__active' : ''}`} onClick={() => changeArtistNavMenuView('songs')}> SONGS</div> </li> <li className='search-nav-li'> <div className={`search-nav-item link-subtle cursor-pointer ${view == 'albums' ? 'search-nav-item__active' : ''}`} onClick={() => changeArtistNavMenuView('albums')}> ALBUMS</div> </li> </ul> </nav> ); } class ArtistView extends React.Component<IArtistViewProps, any> { static view: string constructor(props: IArtistViewProps) { super(props); if (!ArtistView.view) { ArtistView.view = this.props.view; } this.state = { view: ArtistView.view }; this.changeArtistNavMenuView = this.changeArtistNavMenuView.bind(this); this._getSongsView = this._getSongsView.bind(this); this._getAlbumsView = this._getAlbumsView.bind(this); this._getArtistHeader = this._getArtistHeader.bind(this); this.overviewView = this.overviewView.bind(this); this.songsView = this.songsView.bind(this); this.albumsView = this.albumsView.bind(this); } componentDidMount() { // Scroll to document top window.scroll(0, 0); } changeArtistNavMenuView(view: string) { ArtistView.view = view; this.setState({ view }); } _getSongsView(size?: number) { let artist = this.props.artist; let songsView = artist.songs.slice(0, size ? size : Infinity).map( (song, index) => ( <SongItemView key={'artist_song_' + index.toString().padStart(3, '0')} song={song} active={false} short={false} thumb={true} handlePlay={null} /> ) ); return songsView; } _getAlbumsView(size?: number) { let artist = this.props.artist; let albumsView = artist.albums.slice(0, size ? size : Infinity).map( (album, index) => ( <div className='col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2' key={'artist_album_' + index.toString().padStart(3, '0')}> <AlbumItemView album={album} /> </div> ) ); return albumsView; } _getArtistHeader() { // Maybe need to set background image let artist = this.props.artist; let cover = artist.artistAvatarPath || musicApi.resizeImageUrl(artist.origin, artist.artistAvatarUrl, ESize.Large); let likeAndPlayCount = getLikeAndPlayCount(artist); return ( <header className='artist-header' style={{ backgroundImage: `url("${cover}")`, backgroundPosition: '100% 12%', height: '500px', }}> <span className='monthly-listeners'>{'\u00A0'}</span> <h1 className='large'>{artist.artistName}</h1> {/* like count and play count */} <h1 className='small' style={{ opacity: 0.4 }}>{likeAndPlayCount}</h1> <div className='header-buttons'> <button className='btn btn-green cursor-pointer' onClick={() => this.props.handlePlayArtist(artist)}> PLAY</button> <MenuButton click={(e) => this.props.showArtistMenu(e, artist)} /> </div> <ArtistNavMenu view={ArtistView.view} changeArtistNavMenuView={this.changeArtistNavMenuView} /> </header> ); } overviewView() { let defaultSize = 10; let songsView = this._getSongsView(defaultSize); let albumsView = this._getAlbumsView(defaultSize); let artist = this.props.artist; return ( <div> <div className='artist-description' dangerouslySetInnerHTML={{ __html: artist.description }}> </div> {/* Top Songs */} <section className='artist-music container-fluid'> <div className='row'> <div className='contentSpacing'> <section className='col-sm-12 col-md-10 col-md-push-1 artist-toptracks'> <h1 className='search-result-title' style={{ textAlign: 'center' }}>Popular</h1> <section className='tracklist-container full-width'> <ol> {songsView} </ol> </section> </section> </div> </div> </section> {/* Albums */} <section className='artist-albums'> <div className='contentSpacing'> <h1 className='search-result-title' style={{ textAlign: 'center' }}>Albums</h1> <div className='container-fluid container-fluid--noSpaceAround'> <div className='align-row-wrap grid--limit row'> {albumsView} </div> </div> </div> </section> </div> ); } songsView() { let artist = this.props.artist; let songsView = this._getSongsView(); let offset = this.props.songsOffset; let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMoreSongs(artist, offset, size)} />) : null; return ( <section className='artist-music container-fluid'> <div className='row'> <div className='contentSpacing'> <section className='col-sm-12 col-md-10 col-md-push-1 artist-toptracks'> { /* No Show */} <h1 className='search-result-title' style={{ textAlign: 'center', display: 'none' }}>Popular</h1> <section className='tracklist-container full-width'> <ol> {songsView} </ol> </section> </section> </div> </div> {viewMore} </section> ); } albumsView() { let artist = this.props.artist; let albumsView = this._getAlbumsView(); let offset = this.props.albumsOffset; let viewMore = offset.more ? (<ViewMorePlusItem handler={(size) => this.props.getMoreAlbums(artist, offset, size)} />) : null; return ( <section className='artist-albums'> <div className='contentSpacing'> { /* No Show */} <h1 className='search-result-title' style={{ textAlign: 'center', display: 'none' }}>Albums</h1> <div className='container-fluid container-fluid--noSpaceAround'> <div className='align-row-wrap grid--limit row'> {albumsView} </div> </div> {viewMore} </div> </section> ); } render() { let artistHeaderView = this._getArtistHeader(); let view = ArtistView.view; let contentView = null; if (view == 'overview') { contentView = this.overviewView(); } else if (view == 'songs') { contentView = this.songsView(); } else if (view == 'albums') { contentView = this.albumsView(); } else { return null; } return ( <div className='hw-accelerate'> <section className='content artist'> {artistHeaderView} {contentView} </section> </div> ); } } function mapStateToProps(state: IStateGlobal) { return state.mainView.artistView; } function mapDispatchToProps(dispatch) { return { getMoreSongs: (artist, offset, size) => getMoreSongs(artist, offset, size).then(act => dispatch(act)), getMoreAlbums: (artist, offset, size) => getMoreAlbums(artist, offset, size).then(act => dispatch(act)), handlePlayArtist: artist => handlePlayArtist(artist).then(act => dispatch(act)), showArtistMenu: (e, artist) => dispatch(showArtistMenu(e, artist)), }; } export default connect(mapStateToProps, mapDispatchToProps)(ArtistView);
the_stack
import { WindowPostMessageProxy } from 'window-post-message-proxy'; import { HttpPostMessage } from 'http-post-message'; import { Router } from 'powerbi-router'; import { mockAppSpyObj, mockApp } from './mockApp'; import * as models from 'powerbi-models'; export const spyApp = mockAppSpyObj; export function setupEmbedMockApp(iframeContentWindow: Window, parentWindow: Window, logMessages: boolean, name: string = 'MockAppWindowPostMessageProxy'): HttpPostMessage { const parent = parentWindow || iframeContentWindow.parent; const wpmp = new WindowPostMessageProxy({ processTrackingProperties: { addTrackingProperties: HttpPostMessage.addTrackingProperties, getTrackingProperties: HttpPostMessage.getTrackingProperties, }, isErrorMessage: HttpPostMessage.isErrorMessage, receiveWindow: iframeContentWindow, name, logMessages }); const hpm = new HttpPostMessage(wpmp, { 'origin': 'reportEmbedMock', 'x-version': '1.0.0' }, parent); const router = new Router(wpmp); const app = mockApp; /** * Setup not found handlers. */ function notFoundHandler(req, res): void { res.send(404, `Not Found. Url: ${req.params.notfound} was not found.`); } router.get('*notfound', notFoundHandler); router.post('*notfound', notFoundHandler); router.patch('*notfound', notFoundHandler); router.put('*notfound', notFoundHandler); router.delete('*notfound', notFoundHandler); /** * Dashboard Embed */ router.post('/dashboard/load', async (req, res) => { const uniqueId = req.headers['uid']; const loadConfig = req.body; try { await app.validateDashboardLoad(loadConfig); try { await app.dashboardLoad(loadConfig); hpm.post(`/dashboards/${uniqueId}/events/loaded`, { initiator: "sdk" }); } catch (error) { hpm.post(`/dashboards/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); /** * Create Report */ router.post('/report/create', async (req, res) => { const uniqueId = req.headers['uid']; const createConfig = req.body; try { await app.validateCreateReport(createConfig); try { await app.reportLoad(createConfig); hpm.post(`/reports/${uniqueId}/events/loaded`, { initiator: "sdk" }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); /** * Report Embed */ router.post('/report/load', async (req, res) => { const uniqueId = req.headers['uid']; const loadConfig = req.body; try { await app.validateReportLoad(loadConfig); try { await app.reportLoad(loadConfig); hpm.post(`/reports/${uniqueId}/events/loaded`, { initiator: "sdk" }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); /** * Report Embed */ router.post('/report/prepare', async (req, res) => { const uniqueId = req.headers['uid']; const loadConfig = req.body; try { await app.validateReportLoad(loadConfig); try { await app.reportLoad(loadConfig); hpm.post(`/reports/${uniqueId}/events/loaded`, { initiator: "sdk" }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); router.post('/report/render', (req, res) => { app.render(); res.send(202, {}); }); router.get('/report/pages', async (req, res) => { try { const pages = await app.getPages(); res.send(200, pages); } catch (error) { res.send(500, error); } }); router.put('/report/pages/active', async (req, res) => { const uniqueId = req.headers['uid']; const page = req.body; try { await app.validatePage(page); try { await app.setPage(page); hpm.post(`/reports/${uniqueId}/events/pageChanged`, { initiator: "sdk", newPage: page }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202); } catch (error) { res.send(400, error); } }); router.get('/report/filters', async (req, res) => { try { const filters = await app.getFilters(); res.send(200, filters); } catch (error) { res.send(500, error); } }); router.put('/report/filters', async (req, res) => { const uniqueId = req.headers['uid']; const filters = req.body; try { await Promise.all(filters.map(filter => app.validateFilter(filter))); try { const filter = await app.setFilters(filters); hpm.post(`/reports/${uniqueId}/events/filtersApplied`, { initiator: "sdk", filter }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); router.post('/report/filters', async (req, res) => { const uniqueId = req.headers['uid']; const operation = req.body.filtersOperation; const filters = req.body.filters; try { Promise.all(filters ? filters.map(filter => app.validateFilter(filter)) : [Promise.resolve(null)]); try { const filter = await app.updateFilters(operation, filters); hpm.post(`/reports/${uniqueId}/events/filtersApplied`, { initiator: "sdk", filter }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); router.get('/report/pages/:pageName/filters', async (req, res) => { const page = { name: req.params.pageName, displayName: null }; try { await app.validatePage(page); try { const filters = await app.getFilters(); res.send(200, filters); } catch (error) { res.send(500, error); } } catch (error) { res.send(400, error); } }); router.post('/report/pages/:pageName/filters', async (req, res) => { const pageName = req.params.pageName; const uniqueId = req.headers['uid']; const operation = req.body.filtersOperation; const filters = req.body.filters; const page: models.IPage = { name: pageName, displayName: null }; try { await app.validatePage(page); await Promise.all(filters ? filters.map(filter => app.validateFilter(filter)) : [Promise.resolve(null)]); try { const filter = await app.updateFilters(operation, filters); hpm.post(`/reports/${uniqueId}/pages/${pageName}/events/filtersApplied`, { initiator: "sdk", filter }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); router.put('/report/pages/:pageName/filters', async (req, res) => { const pageName = req.params.pageName; const uniqueId = req.headers['uid']; const filters = req.body; const page: models.IPage = { name: pageName, displayName: null }; try { await app.validatePage(page); await Promise.all(filters.map(filter => app.validateFilter(filter))); try { const filter = await app.setFilters(filters); hpm.post(`/reports/${uniqueId}/pages/${pageName}/events/filtersApplied`, { initiator: "sdk", filter }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); router.get('/report/pages/:pageName/visuals/:visualName/filters', async (req, res) => { const page = { name: req.params.pageName, displayName: null }; const visual: models.IVisual = { name: req.params.visualName, title: 'title', type: 'type', layout: {}, }; try { await app.validateVisual(page, visual); try { const filters = await app.getFilters(); res.send(200, filters); } catch (error) { res.send(500, error); } } catch (error) { res.send(400, error); } }); router.post('/report/pages/:pageName/visuals/:visualName/filters', async (req, res) => { const pageName = req.params.pageName; const visualName = req.params.visualName; const uniqueId = req.headers['uid']; const operation = req.body.filtersOperation; const filters = req.body.filters; const page: models.IPage = { name: pageName, displayName: null }; const visual: models.IVisual = { name: visualName, title: 'title', type: 'type', layout: {}, }; try { await app.validateVisual(page, visual); await Promise.all(filters ? filters.map(filter => app.validateFilter(filter)) : [Promise.resolve(null)]); try { const filter = await app.updateFilters(operation, filters); hpm.post(`/reports/${uniqueId}/pages/${pageName}/visuals/${visualName}/events/filtersApplied`, { initiator: "sdk", filter }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); router.put('/report/pages/:pageName/visuals/:visualName/filters', async (req, res) => { const pageName = req.params.pageName; const visualName = req.params.visualName; const uniqueId = req.headers['uid']; const filters = req.body; const page: models.IPage = { name: pageName, displayName: null }; const visual: models.IVisual = { name: visualName, title: 'title', type: 'type', layout: {}, }; try { await app.validateVisual(page, visual); await Promise.all(filters.map(filter => app.validateFilter(filter))); try { const filter = await app.setFilters(filters); hpm.post(`/reports/${uniqueId}/pages/${pageName}/visuals/${visualName}/events/filtersApplied`, { initiator: "sdk", filter }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); router.patch('/report/settings', async (req, res) => { const uniqueId = req.headers['uid']; const settings = req.body; try { await app.validateSettings(settings); try { const updatedSettings = await app.updateSettings(settings); hpm.post(`/reports/${uniqueId}/events/settingsUpdated`, { initiator: "sdk", settings: updatedSettings }); } catch (error) { hpm.post(`/reports/${uniqueId}/events/error`, error); } res.send(202, {}); } catch (error) { res.send(400, error); } }); router.get('/report/data', async (req, res) => { const data = await app.exportData(); res.send(200, data); }); router.post('/report/refresh', (req, res) => { app.refreshData(); res.send(202); }); router.post('/report/print', (req, res) => { app.print(); res.send(202); }); router.post('report/switchMode/Edit', (req, res) => { app.switchMode(); res.send(202); }); router.post('report/save', (req, res) => { app.save(); res.send(202); }); router.post('report/saveAs', (req, res) => { const settings = req.body; app.saveAs(settings); res.send(202); }); router.post('report/token', (req, res) => { const settings = req.body; app.setAccessToken(settings); res.send(202); }); return hpm; }
the_stack
import * as React from "react"; import { Trans } from "@lingui/macro"; import { Tooltip } from "reactjs-components"; import { routerShape } from "react-router"; import PropTypes from "prop-types"; import sort from "array-sort"; import { componentFromStream } from "@dcos/data-service"; import { combineLatest, pipe } from "rxjs"; import { map } from "rxjs/operators"; import { Icon, Table_Deprecated, Column, SortableHeaderCell, } from "@dcos/ui-kit"; import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum"; import { greyDark, iconSizeXs, } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens"; import CompositeState from "#SRC/js/structs/CompositeState"; import Loader from "#SRC/js/components/Loader"; import MetadataStore from "#SRC/js/stores/MetadataStore"; import TableColumnResizeStore from "#SRC/js/stores/TableColumnResizeStore"; import { MesosMasterRequestType, getMasterRegionName, } from "#SRC/js/core/MesosMasterRequest"; import container from "#SRC/js/container"; import { ServiceActionItem } from "../../constants/ServiceActionItem"; import ServiceTree from "../../structs/ServiceTree"; import ServiceActionDisabledModal from "../../components/modals/ServiceActionDisabledModal"; import * as Version from "#SRC/js/utils/Version"; import { nameRenderer } from "../../columns/ServicesTableNameColumn"; import { statusRenderer } from "../../columns/ServicesTableStatusColumn"; import { versionRenderer } from "../../columns/ServicesTableVersionColumn"; import { regionRendererFactory } from "../../columns/ServicesTableRegionColumn"; import { instancesRenderer } from "../../columns/ServicesTableInstancesColumn"; import { memRenderer } from "../../columns/ServicesTableMemColumn"; import { diskRenderer } from "../../columns/ServicesTableDiskColumn"; import { gpuRenderer } from "../../columns/ServicesTableGPUColumn"; import { cpuRenderer } from "../../columns/ServicesTableCPUColumn"; import { actionsRendererFactory } from "../../columns/ServicesTableActionsColumn"; const DELETE = ServiceActionItem.DELETE; const EDIT = ServiceActionItem.EDIT; const OPEN = ServiceActionItem.OPEN; const RESTART = ServiceActionItem.RESTART; const RESUME = ServiceActionItem.RESUME; const SCALE = ServiceActionItem.SCALE; const STOP = ServiceActionItem.STOP; const RESET_DELAYED = ServiceActionItem.RESET_DELAYED; const VIEW_PLANS = ServiceActionItem.VIEW_PLANS; const VIEW_ENDPOINTS = ServiceActionItem.VIEW_ENDPOINTS; const serviceToVersion = (serviceTreeNode) => { if (serviceTreeNode instanceof ServiceTree) { return ""; } return pipe(Version.fromService)(serviceTreeNode); }; function sortForColumn(name) { switch (name) { case "name": return (a, b) => a.getName().localeCompare(b.getName()); case "status": return (a, b) => b.getServiceStatus().priority - a.getServiceStatus().priority; case "version": return (a, b) => Version.compare(serviceToVersion(a), serviceToVersion(b)); case "region": return (a, b) => (a.getRegions()[0] || "") < (b.getRegions()[0] || "") ? 1 : -1; case "instances": return (a, b) => a.getInstancesCount() - b.getInstancesCount(); case "cpus": return (a, b) => a.getResources().cpus - b.getResources().cpus; case "mem": return (a, b) => a.getResources().mem - b.getResources().mem; case "disk": return (a, b) => a.getResources().disk - b.getResources().disk; case "gpus": return (a, b) => a.getResources().gpus - b.getResources().gpus; default: return () => 0; } } function sortData( data, sortColumn, sortDirection, currentSortDirection, currentSortColumn ) { const copiedData = data.slice(); if (sortColumn === currentSortColumn) { return { data: sortDirection === currentSortDirection ? copiedData : copiedData.reverse(), sortColumn, sortDirection, }; } return { data: sort(copiedData, sortForColumn(sortColumn), { reverse: sortDirection !== "ASC", }), sortColumn, sortDirection, }; } const widthFor = (col: string) => TableColumnResizeStore.get(columnWidthsStorageKey)?.[col]; export const columnWidthsStorageKey = "servicesTableColWidths"; class ServicesTable extends React.Component { static defaultProps = { isFiltered: false, services: [], }; static propTypes = { isFiltered: PropTypes.bool, services: PropTypes.array, }; state = { actionDisabledService: null, data: [], sortColumn: "name", sortDirection: "ASC", }; regionRenderer = regionRendererFactory(this.props.masterRegionName); constructor(props) { super(props); this.actionsRenderer = actionsRendererFactory( this.handleActionDisabledModalOpen.bind(this), this.handleServiceAction.bind(this) ); } // this page does not use the composite state anymore, so let's not calculate it componentDidMount() { CompositeState.disable(); } componentWillUnmount() { CompositeState.enable(); } UNSAFE_componentWillReceiveProps(nextProps) { this.regionRenderer = regionRendererFactory(nextProps.masterRegionName); this.setState( sortData( nextProps.services, this.state.sortColumn, this.state.sortDirection ) ); } handleServiceAction = (service, actionID) => { const { modalHandlers, router } = this.context; switch (actionID) { case EDIT: router.push( `/services/detail/${encodeURIComponent(service.getId())}/edit/` ); break; case VIEW_PLANS: router.push( `/services/detail/${encodeURIComponent(service.getId())}/plans/` ); break; case VIEW_ENDPOINTS: router.push( `/services/detail/${encodeURIComponent(service.getId())}/endpoints/` ); break; case SCALE: modalHandlers.scaleService({ service }); break; case RESET_DELAYED: modalHandlers.resetDelayedService({ service }); break; case OPEN: modalHandlers.openServiceUI({ service }); break; case RESTART: modalHandlers.restartService({ service }); break; case RESUME: modalHandlers.resumeService({ service }); break; case STOP: modalHandlers.stopService({ service }); break; case DELETE: modalHandlers.deleteService({ service }); break; } }; handleActionDisabledModalOpen = (actionDisabledService, actionDisabledID) => { this.setState({ actionDisabledService, actionDisabledID }); }; handleActionDisabledModalClose = () => { this.setState({ actionDisabledService: null, actionDisabledID: null }); }; handleSortClick = (columnName) => { const toggledDirection = this.state.sortDirection === "ASC" || this.state.sortColumn !== columnName ? "DESC" : "ASC"; this.setState( sortData( this.state.data, columnName, toggledDirection, this.state.sortDirection, this.state.sortColumn ) ); }; sortGroupsOnTop(data) { const groups = data.filter((service) => service instanceof ServiceTree); const services = data.filter( (service) => !(service instanceof ServiceTree) ); return [...groups, ...services]; } handleResize(columnName, resizedColWidth) { const savedColWidths = TableColumnResizeStore.get(columnWidthsStorageKey); TableColumnResizeStore.set(columnWidthsStorageKey, { ...savedColWidths, [columnName]: resizedColWidth, }); } render(...args) { const { actionDisabledService, actionDisabledID, data, sortColumn, sortDirection, } = this.state; if (data.length === 0) { if (this.props.isFiltered === false) { return <Loader />; } return <div>No data.</div>; } const sortedGroups = this.sortGroupsOnTop(data); // Hiding the table when the create service modal is open. // // This is a workaround for an issue where Cypress' `type` // command would not work as expected when there is a table // with many resizable columns in the DOM return this.props.hideTable ? null : ( <div className="table-wrapper service-table"> <Table_Deprecated data={sortedGroups.slice()} rowHeight={this.props.isFiltered ? 45 : 35} > <Column header={ <SortableHeaderCell columnContent={<Trans render="span">Name</Trans>} sortHandler={this.handleSortClick.bind(null, "name")} sortDirection={sortColumn === "name" ? sortDirection : null} /> } cellRenderer={nameRenderer.bind( null, this.props.isFiltered, false, ...args )} growToFill={!widthFor("name")} minWidth={widthFor("name") ? undefined : 200} resizable={true} onResize={this.handleResize.bind(null, "name")} width={() => widthFor("name")} /> <Column header={ <SortableHeaderCell columnContent={ <span> <Trans render="span">Status</Trans>{" "} <Tooltip interactive={true} wrapperClassName="tooltip-wrapper" wrapText={true} content={ <Trans render="span"> At-a-glance overview of the global application or group state.{" "} <a href={MetadataStore.buildDocsURI( "/deploying-services/task-handling" )} target="_blank" > Read more </a> . </Trans> } > <span className="icon-margin-right"> <Icon color={greyDark} shape={SystemIcons.CircleQuestion} size={iconSizeXs} /> </span> </Tooltip> </span> } sortHandler={this.handleSortClick.bind(null, "status")} sortDirection={sortColumn === "status" ? sortDirection : null} /> } cellRenderer={statusRenderer} growToFill={!widthFor("status")} minWidth={widthFor("status") ? undefined : 210} resizable={true} onResize={this.handleResize.bind(null, "status")} width={() => widthFor("status")} /> <Column header={ <SortableHeaderCell columnContent={<Trans render="span">Version</Trans>} sortHandler={this.handleSortClick.bind(null, "version")} sortDirection={sortColumn === "version" ? sortDirection : null} /> } cellRenderer={versionRenderer} growToFill={!widthFor("version")} maxWidth={widthFor("version") ? undefined : 120} resizable={true} onResize={this.handleResize.bind(null, "version")} width={() => widthFor("version")} /> <Column header={ <SortableHeaderCell columnContent={<Trans render="span">Region</Trans>} sortHandler={this.handleSortClick.bind(null, "region")} sortDirection={sortColumn === "region" ? sortDirection : null} /> } cellRenderer={this.regionRenderer} growToFill={!widthFor("region")} minWidth={widthFor("region") ? undefined : 60} maxWidth={widthFor("region") ? undefined : 150} resizable={true} onResize={this.handleResize.bind(null, "region")} width={() => widthFor("region")} /> <Column header={ <SortableHeaderCell columnContent={<Trans render="span">Instances</Trans>} sortHandler={this.handleSortClick.bind(null, "instances")} sortDirection={ sortColumn === "instances" ? sortDirection : null } textAlign="right" /> } cellRenderer={instancesRenderer} growToFill={!widthFor("instances")} minWidth={widthFor("instances") ? undefined : 100} maxWidth={!widthFor("instances") ? undefined : 120} resizable={true} onResize={this.handleResize.bind(null, "instances")} width={() => widthFor("instances")} /> <Column header={ <SortableHeaderCell columnContent={<Trans render="span">CPU Allocated</Trans>} sortHandler={this.handleSortClick.bind(null, "cpus")} sortDirection={sortColumn === "cpus" ? sortDirection : null} textAlign="right" /> } cellRenderer={cpuRenderer} minWidth={widthFor("cpu") ? undefined : 135} maxWidth={widthFor("cpu") ? undefined : 150} growToFill={!widthFor("cpu")} resizable={true} onResize={this.handleResize.bind(null, "cpu")} width={() => widthFor("cpu")} /> <Column header={ <SortableHeaderCell columnContent={<Trans render="span">Mem Allocated</Trans>} sortHandler={this.handleSortClick.bind(null, "mem")} sortDirection={sortColumn === "mem" ? sortDirection : null} textAlign="right" /> } cellRenderer={memRenderer} growToFill={!widthFor("mem")} minWidth={widthFor("mem") ? undefined : 140} maxWidth={widthFor("mem") ? undefined : 155} resizable={true} onResize={this.handleResize.bind(null, "mem")} width={() => widthFor("mem")} /> <Column header={ <SortableHeaderCell columnContent={<Trans render="span">Disk Allocated</Trans>} sortHandler={this.handleSortClick.bind(null, "disk")} sortDirection={sortColumn === "disk" ? sortDirection : null} textAlign="right" /> } cellRenderer={diskRenderer} growToFill={!widthFor("disk")} minWidth={widthFor("disk") ? undefined : 140} maxWidth={widthFor("disk") ? undefined : 150} resizable={true} onResize={this.handleResize.bind(null, "disk")} width={() => widthFor("disk")} /> <Column header={ <SortableHeaderCell columnContent={<Trans render="span">GPU Allocated</Trans>} sortHandler={this.handleSortClick.bind(null, "gpu")} sortDirection={sortColumn === "gpus" ? sortDirection : null} textAlign="right" /> } cellRenderer={gpuRenderer} growToFill={!widthFor("gpu")} minWidth={widthFor("gpu") ? undefined : 135} maxWidth={widthFor("gpu") ? undefined : 135} resizable={true} onResize={this.handleResize.bind(null, "gpu")} width={() => widthFor("gpu")} /> <Column cellRenderer={this.actionsRenderer} handleActionDisabledModalOpen={this.handleActionDisabledModalOpen} handleServiceAction={this.handleServiceAction} growToFill={true} minWidth={24} maxWidth={36} /> </Table_Deprecated> <ServiceActionDisabledModal actionID={actionDisabledID} open={actionDisabledService != null} onClose={this.handleActionDisabledModalClose} service={actionDisabledService} /> </div> ); } } ServicesTable.contextTypes = { modalHandlers: PropTypes.shape({ scaleService: PropTypes.func, restartService: PropTypes.func, resumeService: PropTypes.func, stopService: PropTypes.func, deleteService: PropTypes.func, resetDelayedService: PropTypes.func, }).isRequired, router: routerShape, }; function withMasterRegionName(Component) { const master$ = container .get(MesosMasterRequestType) .pipe(map((data) => JSON.parse(data))); const masterRegionName$ = getMasterRegionName(master$); return componentFromStream((prop$) => combineLatest([prop$, masterRegionName$]).pipe( map(([props, masterRegionName]) => ( <Component {...props} masterRegionName={masterRegionName} /> )) ) ); } const Component = withMasterRegionName(ServicesTable); export { Component as default, sortData };
the_stack
import * as ts from 'typescript'; export class IdentifierResolver { public constructor(private typeChecker: ts.TypeChecker) { } public getFirstDeclaration(typeInfo: ts.Type): ts.Declaration { return typeInfo && typeInfo.symbol && typeInfo.symbol.declarations[0]; } public getValueDeclaration(typeInfo: ts.Type): ts.Declaration { return typeInfo.symbol && typeInfo.symbol.valueDeclaration; } public getValueDeclarationType(typeInfo: ts.Type) { return (<any>this.getValueDeclaration(typeInfo))?.type; } public typesAreTheSame(typeReturnIn: ts.TypeNode, functionReturnIn: ts.TypeNode): boolean { let typeReturn = typeReturnIn; let functionReturn = functionReturnIn; if (!typeReturn || !functionReturn) { return false; } if (typeReturn.kind === ts.SyntaxKind.LiteralType) { typeReturn = (<any>typeReturn).literal; } if (functionReturn.kind === ts.SyntaxKind.LiteralType) { functionReturn = (<any>functionReturn).literal; } if ((typeReturn.kind === ts.SyntaxKind.BooleanKeyword && (functionReturn.kind === ts.SyntaxKind.TrueKeyword || functionReturn.kind === ts.SyntaxKind.FalseKeyword)) || (functionReturn.kind === ts.SyntaxKind.BooleanKeyword && (typeReturn.kind === ts.SyntaxKind.TrueKeyword || typeReturn.kind === ts.SyntaxKind.FalseKeyword))) { return true; } if ((typeReturn.kind === ts.SyntaxKind.StringKeyword && functionReturn.kind === ts.SyntaxKind.StringLiteral) || (functionReturn.kind === ts.SyntaxKind.StringKeyword && typeReturn.kind === ts.SyntaxKind.StringLiteral)) { return true; } if ((typeReturn.kind === ts.SyntaxKind.NumberKeyword && functionReturn.kind === ts.SyntaxKind.NumericLiteral) || (functionReturn.kind === ts.SyntaxKind.NumberKeyword && typeReturn.kind === ts.SyntaxKind.NumericLiteral)) { return true; } if (typeReturn.kind !== functionReturn.kind) { return false; } if (typeReturn.kind === ts.SyntaxKind.ArrayType) { return this.typesAreTheSame((<any>typeReturn).elementType, (<any>functionReturn).elementType); } if ((<any>typeReturn).typeName === (<any>functionReturn).typeName) { return true; } return (<any>typeReturn).typeName.text === (<any>functionReturn).typeName.text; } public isAnyLikeType(typeInfo: ts.Type): boolean { if (!typeInfo) { return false; } const isAnonymousObject = ((<ts.ObjectType>typeInfo).objectFlags & ts.ObjectFlags.Anonymous) === ts.ObjectFlags.Anonymous; return (isAnonymousObject && (!typeInfo.symbol.name || typeInfo.symbol.name === '__type' || typeInfo.symbol.name === '__object')) || (<any>typeInfo).intrinsicName === 'any'; } public isTypeFromSymbol(node: ts.Node | ts.Type, kind: ts.SyntaxKind) { return node && (<any>node).symbol && (<any>node).symbol.declarations[0].kind === kind; } public isThisType(typeInfo: ts.Type): boolean { if (!typeInfo) { return false; } if ((<ts.InterfaceType>typeInfo).thisType || (<any>typeInfo).isThisType || this.isThisType((<any>typeInfo).target)) { return true; } const type = this.getValueDeclarationType(typeInfo); if (type && type.kind === ts.SyntaxKind.TypeReference) { return typeInfo.symbol.name === 'Date' || typeInfo.symbol.name === 'RegExp'; } return false; } public isArrayType(typeInfo: ts.Type) { if (!typeInfo) { return false; } if (typeInfo.symbol && typeInfo.symbol.valueDeclaration) { const type = (<any>typeInfo.symbol.valueDeclaration).type; if (type && type.kind === ts.SyntaxKind.TypeReference) { return typeInfo.symbol.name === 'Array'; } } return false; } public isObjectType(typeInfo: ts.Type) { if (!typeInfo) { return false; } if (typeInfo.symbol && typeInfo.symbol.valueDeclaration) { const type = (<any>typeInfo.symbol.valueDeclaration).type; if (type && type.kind === ts.SyntaxKind.TypeReference) { return typeInfo.symbol.name === 'Object'; } } return false; } public isNumberType(typeInfo: ts.Type) { if (!typeInfo) { return false; } if ((<any>typeInfo).intrinsicName === 'number') { return true; } if (!typeInfo.symbol && (<any>typeInfo).value !== undefined && typeof((<any>typeInfo).value) === 'number') { return true; } return this.isNumberTypeFromSymbol(typeInfo.symbol); } public isNumberTypeFromSymbol(symbol: ts.Symbol) { if (symbol && symbol.valueDeclaration) { const type = (<any>symbol.valueDeclaration).type; if (type && type.kind === ts.SyntaxKind.TypeReference) { return symbol.name === 'Number'; } } return false; } public isStringType(typeInfo: ts.Type) { if (!typeInfo) { return false; } if ((<any>typeInfo).intrinsicName === 'string') { return true; } if (!typeInfo.symbol && (<any>typeInfo).value && typeof((<any>typeInfo).value) === 'string') { return true; } return this.isStringTypeFromSymbol(typeInfo.symbol); } public isStringTypeFromSymbol(symbol: ts.Symbol) { if (symbol && symbol.valueDeclaration) { const type = (<any>symbol.valueDeclaration).type; if (type && type.kind === ts.SyntaxKind.TypeReference) { return symbol.name === 'String'; } } return false; } public isArrayOrStringType(typeInfo: ts.Type) { if (!typeInfo) { return false; } if ((<any>typeInfo).intrinsicName === 'string') { return true; } if (!typeInfo.symbol && (<any>typeInfo).value && typeof((<any>typeInfo).value) === 'string') { return true; } return this.isArrayOrStringTypeFromSymbol(typeInfo.symbol); } public isArrayOrStringTypeFromSymbol(symbol: ts.Symbol) { if (symbol && symbol.valueDeclaration) { const type = (<any>symbol.valueDeclaration).type; if (type && type.kind === ts.SyntaxKind.TypeReference) { return symbol.name === 'Array' || symbol.name === 'String'; } } return false; } public isStaticAccess(typeInfo: ts.Type): boolean { if (this.isThisType(typeInfo)) { return false; } if (!typeInfo || !typeInfo.symbol || !typeInfo.symbol.valueDeclaration) { return false; } return typeInfo.symbol.valueDeclaration.kind === ts.SyntaxKind.EnumDeclaration || typeInfo.symbol.valueDeclaration.kind === ts.SyntaxKind.ClassDeclaration; } public isNotDetected(typeInfo: ts.Type): boolean { return !typeInfo || (<any>typeInfo).intrinsicName === 'error'; } public getOrResolveTypeOfAsTypeNode(location: ts.Node): ts.TypeNode { return this.typeToTypeNode(this.getOrResolveTypeOf(location)); } public getOrResolveTypeOf(location: ts.Node): ts.Type { const type = this.getTypeAtLocation(location); if (!type || this.isNotDetected(type)) { return this.resolveTypeOf(location); } return type; } public getTypeOf(location: ts.Node): ts.Type { const type = this.getTypeAtLocation(location); return type; } public getSymbolAtLocation(location: ts.Node): ts.Symbol { return this.typeChecker.getSymbolAtLocation(location); } public getTypeAtLocation(location: ts.Node): ts.Type { return this.typeChecker.getTypeAtLocation(location); } public getTypeOfSymbolAtLocation(symbol: ts.Symbol, location: ts.Node): ts.Type { return this.typeChecker.getTypeOfSymbolAtLocation(symbol, location); } public typeToTypeNode(type: ts.Type): ts.TypeNode { return this.typeChecker.typeToTypeNode(type); } public checkTypeAlias(symbol: ts.Symbol): boolean { if (symbol && symbol.declarations[0].kind === ts.SyntaxKind.TypeAliasDeclaration) { return true; } return false; } public checkImportSpecifier(symbol: ts.Symbol): boolean { if (symbol && symbol.declarations[0].kind === ts.SyntaxKind.ImportSpecifier) { return true; } return false; } public checkUnionSymbol(symbol: ts.Symbol): boolean { if (symbol && (<any>symbol.declarations[0]).type) { return this.checkUnionType((<any>symbol.declarations[0]).type); } return false; } public checkUnionType(type: ts.TypeNode): boolean { if (type && type.kind === ts.SyntaxKind.UnionType) { const unionType = <ts.UnionTypeNode>(type); return unionType.types.filter(f => f.kind !== ts.SyntaxKind.NullKeyword && f.kind !== ts.SyntaxKind.UndefinedKeyword).length > 1; } return false; } public isTypeAlias(location: ts.Node): boolean { if (!location) { return undefined; } if (location.kind !== ts.SyntaxKind.Identifier) { // only identifier is accepted return undefined; } const name = (<ts.Identifier>location).text; let resolvedSymbol = this.resolveNameFromLocals(location); if (this.checkTypeAlias(resolvedSymbol)) { return true; } const typeInfo = this.getTypeAtLocation(location); if (typeInfo) { return this.checkTypeAlias(typeInfo.aliasSymbol); } return false; } public isTypeAliasUnionType(location: ts.Node): boolean { if (!location) { return undefined; } if (location.kind !== ts.SyntaxKind.Identifier) { // only identifier is accepted return undefined; } let resolvedSymbol = this.resolveNameFromLocals(location); if (!this.checkTypeAlias(resolvedSymbol) && !this.checkImportSpecifier(resolvedSymbol)) { return false; } const typeInfo = this.getTypeAtLocation(location); if (this.checkUnionSymbol(typeInfo.aliasSymbol)) { return true; } return false; } public isTypeParameter(location: ts.Node): boolean { const typeInfo = this.getTypeAtLocation(location); if (this.isTypeFromSymbol(typeInfo, ts.SyntaxKind.TypeParameter)) { return true; } return false; } public resolveTypeOf(location: ts.Node): ts.Type { if (!location) { return undefined; } if (location.kind !== ts.SyntaxKind.Identifier) { // only identifier is accepted return undefined; } let resolvedSymbol = this.resolveNameFromLocals(location); if (this.checkImportSpecifier(resolvedSymbol)) { /* todo: finish it */ return undefined; } try { return this.typeChecker.getTypeOfSymbolAtLocation(resolvedSymbol, location); } catch (e) { } return undefined; } public resolveNameFromLocals(location: ts.Node): ts.Symbol { let resolvedSymbol: ts.Symbol; const name = (<ts.Identifier>location).text; // find first node with 'locals' let locationWithLocals = location; while (true) { while (locationWithLocals) { if ((<any>locationWithLocals).locals) { break; } locationWithLocals = locationWithLocals.parent; } if (!locationWithLocals) { // todo function, method etc can't be found return null; } resolvedSymbol = (<any>this.typeChecker).resolveName( name, locationWithLocals, ((1 << 27) - 1)); if (!resolvedSymbol) { locationWithLocals = locationWithLocals.parent; continue; } break; } return resolvedSymbol; } public isLocal(location: ts.Node): [boolean, any] { if (location.kind !== ts.SyntaxKind.Identifier && location.parent.kind === ts.SyntaxKind.PropertyAccessExpression) { // only identifier is accepted return undefined; } const name = (<ts.Identifier>location).text; let resolvedSymbol; // find first node with 'locals' let locationWithLocals = location; let level = 0; while (true) { while (locationWithLocals) { if ((<any>locationWithLocals).locals) { resolvedSymbol = (<any>locationWithLocals).locals.get(name); if (resolvedSymbol) { break; } if (locationWithLocals.kind === ts.SyntaxKind.FunctionDeclaration || locationWithLocals.kind === ts.SyntaxKind.FunctionExpression || locationWithLocals.kind === ts.SyntaxKind.ArrowFunction || locationWithLocals.kind === ts.SyntaxKind.MethodDeclaration || locationWithLocals.kind === ts.SyntaxKind.ClassDeclaration) { level++; } } locationWithLocals = locationWithLocals.parent; } if (resolvedSymbol) { return [resolvedSymbol.valueDeclaration ? level === 0 : undefined, resolvedSymbol]; } if (!locationWithLocals) { // todo function, method etc can't be found return undefined; } locationWithLocals = locationWithLocals.parent; } } }
the_stack
import {Oas20Document} from "../../models/2.0/document.model"; import {OasValidationRule} from "./common.rule"; import {Oas20Operation} from "../../models/2.0/operation.model"; import {Oas20Parameter, Oas20ParameterBase, Oas20ParameterDefinition} from "../../models/2.0/parameter.model"; import {Oas20Items} from "../../models/2.0/items.model"; import {Oas20Header} from "../../models/2.0/header.model"; import {Oas20SecurityScheme} from "../../models/2.0/security-scheme.model"; import {OasValidationRuleUtil} from "../validation"; import {OasInfo} from "../../models/common/info.model"; import {OasContact} from "../../models/common/contact.model"; import {OasLicense} from "../../models/common/license.model"; import {OasOperation} from "../../models/common/operation.model"; import {OasExternalDocumentation} from "../../models/common/external-documentation.model"; import {Oas30Parameter, Oas30ParameterBase, Oas30ParameterDefinition} from "../../models/3.0/parameter.model"; import {OasTag} from "../../models/common/tag.model"; import {OasXML} from "../../models/common/xml.model"; import {Oas30Info} from "../../models/3.0/info.model"; import {Oas30Response, Oas30ResponseBase, Oas30ResponseDefinition} from "../../models/3.0/response.model"; import {Oas30Example, Oas30ExampleDefinition} from "../../models/3.0/example.model"; import {Oas30Link, Oas30LinkDefinition} from "../../models/3.0/link.model"; import { Oas30AuthorizationCodeOAuthFlow, Oas30ClientCredentialsOAuthFlow, Oas30ImplicitOAuthFlow, Oas30OAuthFlow, Oas30PasswordOAuthFlow } from "../../models/3.0/oauth-flow.model"; import {Oas30PathItem} from "../../models/3.0/path-item.model"; import {Oas30RequestBody, Oas30RequestBodyDefinition} from "../../models/3.0/request-body.model"; import {Oas30Header, Oas30HeaderDefinition} from "../../models/3.0/header.model"; import {Oas30SecurityScheme} from "../../models/3.0/security-scheme.model"; import {Oas30Server} from "../../models/3.0/server.model"; import {Oas30ServerVariable} from "../../models/3.0/server-variable.model"; /** * Implements the Invalid API Host Rule. */ export class OasInvalidApiHostRule extends OasValidationRule { public visitDocument(node: Oas20Document): void { if (this.hasValue(node.host)) { this.reportIfInvalid(OasValidationRuleUtil.isValidHost(node.host), node, "host"); } } } /** * Implements the Invalid API Base Path Rule */ export class OasInvalidApiBasePathRule extends OasValidationRule { public visitDocument(node: Oas20Document): void { if (this.hasValue(node.basePath)) { this.reportIfInvalid(node.basePath.indexOf("/") === 0, node, "basePath"); } } } /** * Implements the Invalid API Description Rule */ export class OasInvalidApiDescriptionRule extends OasValidationRule { public visitInfo(node: OasInfo): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidGFM(node.description), node, "description"); } } } /** * Implements the Invalid Contact URL Rule */ export class OasInvalidContactUrlRule extends OasValidationRule { public visitContact(node: OasContact): void { if (this.hasValue(node.url)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.url), node, "url"); } } } /** * Implements the Invalid Contact Email Rule */ export class OasInvalidContactEmailRule extends OasValidationRule { public visitContact(node: OasContact): void { if (this.hasValue(node.email)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEmailAddress(node.email), node, "email"); } } } /** * Implements the Invalid License URL Rule */ export class OasInvalidLicenseUrlRule extends OasValidationRule { public visitLicense(node: OasLicense): void { if (this.hasValue(node.url)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.url), node, "url"); } } } /** * Implements the Invalid Operation Description Rule */ export class OasInvalidOperationDescriptionRule extends OasValidationRule { public visitOperation(node: OasOperation): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidGFM(node.description), node, "description"); } } } /** * Implements the Invalid Operation Consumes Rule */ export class OasInvalidOperationConsumesRule extends OasValidationRule { public visitOperation(node: Oas20Operation): void { if (this.hasValue(node.consumes)) { this.reportIfInvalid(OasValidationRuleUtil.isValidMimeType(node.consumes), node, "consumes"); } } } /** * Implements the Invalid Operation Produces Rule */ export class OasInvalidOperationProducesRule extends OasValidationRule { public visitOperation(node: Oas20Operation): void { if (this.hasValue(node.produces)) { this.reportIfInvalid(OasValidationRuleUtil.isValidMimeType(node.produces), node, "produces"); } } } /** * Implements the Invalid External Documentation Description Rule */ export class OasInvalidExternalDocsDescriptionRule extends OasValidationRule { public visitExternalDocumentation(node: OasExternalDocumentation): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidGFM(node.description), node, "description"); } } } /** * Implements the Invalid External Documentation URL Rule */ export class OasInvalidExternalDocsUrlRule extends OasValidationRule { public visitExternalDocumentation(node: OasExternalDocumentation): void { if (this.hasValue(node.url)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.url), node, "url"); } } } /** * Implements the Invalid Parameter Description Rule */ export class OasInvalidParameterDescriptionRule extends OasValidationRule { protected validateParameter(node: Oas20ParameterBase | Oas30ParameterBase): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidGFM(node.description), node, "description"); } } public visitParameter(node: Oas20Parameter | Oas30Parameter): void { this.validateParameter(node); } public visitParameterDefinition(node: Oas20ParameterDefinition | Oas30ParameterDefinition): void { this.validateParameter(node); } } /** * Implements the Invalid Schema Items Default Value Rule */ export class OasInvalidSchemaItemsDefaultValueRule extends OasValidationRule { public visitItems(node: Oas20Items): void { if (this.hasValue(node.default)) { this.reportIfInvalid(OasValidationRuleUtil.isValidForType(node.default, node), node, "default"); } } } /** * Implements the Invalid Header Default Value Rule */ export class OasInvalidHeaderDefaultValueRule extends OasValidationRule { public visitHeader(node: Oas20Header): void { if (this.hasValue(node.default)) { this.reportIfInvalid(OasValidationRuleUtil.isValidForType(node.default, node), node, "default"); } } } /** * Implements the Invalid Tag Description Rule */ export class OasInvalidTagDescriptionRule extends OasValidationRule { public visitTag(node: OasTag): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidGFM(node.description), node, "description"); } } } /** * Implements the Invalid Security Scheme Auth URL Rule */ export class OasInvalidSecuritySchemeAuthUrlRule extends OasValidationRule { public visitSecurityScheme(node: Oas20SecurityScheme): void { if (this.hasValue(node.authorizationUrl)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.authorizationUrl), node, "authorizationUrl"); } } } /** * Implements the Invalid Security Scheme Token URL Rule */ export class OasInvalidSecuritySchemeTokenUrlRule extends OasValidationRule { public visitSecurityScheme(node: Oas20SecurityScheme): void { if (this.hasValue(node.tokenUrl)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.tokenUrl), node, "tokenUrl"); } } } /** * Implements the Invalid XML Namespace URL Rule */ export class OasInvalidXmlNamespaceUrlRule extends OasValidationRule { public visitXML(node: OasXML): void { if (this.hasValue(node.namespace)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.namespace), node, "namespace"); } } } /** * Implements the Invalid Terms of Service URL Rule */ export class OasInvalidTermsOfServiceUrlRule extends OasValidationRule { public visitInfo(node: Oas30Info): void { if (this.hasValue(node.termsOfService)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.termsOfService), node, "termsOfService"); } } } /** * Implements the Invalid Response Description Rule */ export class OasInvalidResponseDescriptionRule extends OasValidationRule { protected visitResponseBase(node: Oas30ResponseBase): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidCommonMark(node.description), node, "description"); } } public visitResponse(node: Oas30Response): void { this.visitResponseBase(node); } public visitResponseDefinition(node: Oas30ResponseDefinition): void { this.visitResponseBase(node); } } /** * Implements the Invalid Example Description Rule */ export class OasInvalidExampleDescriptionRule extends OasValidationRule { public visitExample(node: Oas30Example): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidCommonMark(node.description), node, "description"); } } public visitExampleDefinition(node: Oas30ExampleDefinition): void { this.visitExample(node); } } /** * Implements the Invalid Link Description Rule */ export class OasInvalidLinkDescriptionRule extends OasValidationRule { public visitLink(node: Oas30Link): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidCommonMark(node.description), node, "description"); } } public visitLinkDefinition(node: Oas30LinkDefinition): void { this.visitLink(node); } } /** * Implements the Invalid OAuth Authorization URL Rule */ export class OasInvalidOAuthAuthorizationUrlRule extends OasValidationRule { protected visitFlow(node: Oas30OAuthFlow): void { if (this.hasValue(node.authorizationUrl)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.authorizationUrl), node, "authorizationUrl"); } } public visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void { this.visitFlow(node); } public visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void { this.visitFlow(node); } public visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void { this.visitFlow(node); } public visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void { this.visitFlow(node); } } /** * Implements the Invalid OAuth Token URL Rule */ export class OasInvalidOAuthTokenUrlRule extends OasValidationRule { protected visitFlow(node: Oas30OAuthFlow): void { if (this.hasValue(node.tokenUrl)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.tokenUrl), node, "tokenUrl"); } } public visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void { this.visitFlow(node); } public visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void { this.visitFlow(node); } public visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void { this.visitFlow(node); } public visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void { this.visitFlow(node); } } /** * Implements the Invalid OAuth Refresh URL Rule */ export class OasInvalidOAuthRefreshUrlRule extends OasValidationRule { protected visitFlow(node: Oas30OAuthFlow): void { if (this.hasValue(node.refreshUrl)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.refreshUrl), node, "refreshUrl"); } } public visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void { this.visitFlow(node); } public visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void { this.visitFlow(node); } public visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void { this.visitFlow(node); } public visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void { this.visitFlow(node); } } /** * Implements the Invalid Path Item Description Rule */ export class OasInvalidPathItemDescriptionRule extends OasValidationRule { public visitPathItem(node: Oas30PathItem): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidCommonMark(node.description), node, "description"); } } } /** * Implements the Invalid Request Body Description Rule */ export class OasInvalidRequestBodyDescriptionRule extends OasValidationRule { public visitRequestBody(node: Oas30RequestBody): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidCommonMark(node.description), node, "description"); } } public visitRequestBodyDefinition(node: Oas30RequestBodyDefinition): void { this.visitRequestBody(node); } } /** * Implements the Invalid Header Description Rule */ export class OasInvalidHeaderDescriptionRule extends OasValidationRule { public visitHeader(node: Oas30Header): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidCommonMark(node.description), node, "description"); } } public visitHeaderDefinition(node: Oas30HeaderDefinition): void { this.visitHeader(node); } } /** * Implements the Invalid OpenId Connect URL Rule */ export class OasInvalidOpenIDConnectUrlRule extends OasValidationRule { public visitSecurityScheme(node: Oas30SecurityScheme): void { if (this.hasValue(node.openIdConnectUrl)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrl(node.openIdConnectUrl), node, "openIdConnectUrl"); } } } /** * Implements the Invalid Security Scheme Description Rule */ export class OasInvalidSecuritySchemeDescriptionRule extends OasValidationRule { public visitSecurityScheme(node: Oas30SecurityScheme): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidCommonMark(node.description), node, "description"); } } } /** * Implements the Invalid Server Description Rule */ export class OasInvalidServerDescriptionRule extends OasValidationRule { public visitServer(node: Oas30Server): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidCommonMark(node.description), node, "description"); } } } /** * Implements the Invalid Server URL Rule */ export class OasInvalidServerUrlRule extends OasValidationRule { public visitServer(node: Oas30Server): void { if (this.hasValue(node.url)) { this.reportIfInvalid(OasValidationRuleUtil.isValidUrlTemplate(node.url), node, "url"); } } } /** * Implements the Invalid Server Variable Description Rule */ export class OasInvalidServerVariableDescriptionRule extends OasValidationRule { public visitServerVariable(node: Oas30ServerVariable): void { if (this.hasValue(node.description)) { this.reportIfInvalid(OasValidationRuleUtil.isValidCommonMark(node.description), node, "description"); } } }
the_stack
import {Proposal, Change, ResolvedValue, createArray, createHash, IGNORE_REG, ID, EAVN, EAVNField, Iterator, Register, Constraint, ALLOCATION_COUNT, RoundArray} from "./runtime"; //------------------------------------------------------------------------ // Utils //------------------------------------------------------------------------ function isResolved(field:ResolvedValue): field is ID { return !!field || field === 0; } function sumTimes(roundArray:RoundArray, transaction:number, round:number) { if(!roundArray) return 0; let total = 0; for(let cur of roundArray) { if(Math.abs(cur) - 1 <= round) { total += cur > 0 ? 1 : -1; } } return total; } //------------------------------------------------------------------------ // Indexes //------------------------------------------------------------------------ export interface Index { insert(change:Change):void; propose(proposal:Proposal, e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue, transaction:number, round:number):Proposal; resolveProposal(proposal:Proposal):any[][]; check(e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue, transaction:number, round:number):boolean; getDiffs(e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue):RoundArray; get(e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue, transaction:number, round:number):EAVN[]; } export class HashIndex implements Index { eavIndex = createHash(); aveIndex = createHash(); cardinality = 0; getOrCreateHash(parent:any, key:any) { let found = parent[key]; if(!found) { found = parent[key] = createHash("hashLevel"); } return found; } getOrCreateArray(parent:any, key:any) { let found = parent[key]; if(!found) { found = parent[key] = createArray("hashVix"); } return found; } roundArrayInsert(arr:RoundArray, change:Change) { let round = change.round + 1; let neue = round * change.count; let ix = 0; let handled = false; for(let cur of arr) { let curRound = Math.abs(cur); if(curRound === round) { let updated = cur + neue; if(updated === 0) { arr.splice(ix,1); } else { arr[ix] = updated; } handled = true; break; } else if(curRound > round) { arr.splice(ix, 0, neue); handled = true; break; } ix++; } if(!handled) arr.push(neue) } insert(change:Change) { let {getOrCreateHash, getOrCreateArray} = this; let eIx = getOrCreateHash(this.eavIndex, change.e); let aIx = getOrCreateHash(eIx, change.a); let vIx = getOrCreateArray(aIx, change.v); this.roundArrayInsert(vIx, change); let shouldRemove = false; if(!vIx.length) { this.cardinality--; delete aIx[change.v]; if(!Object.keys(aIx).length) { delete eIx[change.a]; if(!Object.keys(eIx).length) { delete this.eavIndex[change.e]; } } shouldRemove = true; } aIx = getOrCreateHash(this.aveIndex, change.a); vIx = getOrCreateHash(aIx, change.v); eIx = getOrCreateArray(vIx, change.e); if(shouldRemove) { delete vIx[change.e]; if(!Object.keys(vIx).length) { delete aIx[change.v]; if(!Object.keys(aIx).length) { delete this.aveIndex[change.a]; } } } else { this.roundArrayInsert(eIx, change) this.cardinality++; } } resolveProposal(proposal:Proposal) { return proposal.info; } propose(proposal:Proposal, e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue, transaction:number, round:number) { let forFields = proposal.forFields; forFields.clear(); if(isResolved(e)) { return this.walkPropose(proposal, this.eavIndex, e, a, v, n, "a", "v", transaction, round); } else if(isResolved(a)) { return this.walkPropose(proposal, this.aveIndex, a, v, e, n, "v", "e", transaction, round); } else { // propose for attribute since that's likely to be the smallest forFields.push("a"); proposal.info = Object.keys(this.aveIndex); proposal.cardinality = proposal.info.length; } return proposal; } walkPropose(proposal:Proposal, index:any, a:ResolvedValue, b:ResolvedValue, c:ResolvedValue, n:ResolvedValue, fieldB:EAVNField, fieldC:EAVNField, transaction:number, round:number):Proposal { let {forFields} = proposal; forFields.clear(); let bIx = index[a as ID]; if(!bIx) { proposal.cardinality = 0; return proposal; } if(isResolved(b)) { let cIx = bIx[b]; if(!cIx) { proposal.cardinality = 0; return proposal; } if(isResolved(c)) { let roundArray = cIx[c]; if(roundArray) { proposal.skip = true; return proposal; } proposal.cardinality = 0; return proposal; } else { forFields.push(fieldC); proposal.info = Object.keys(cIx); proposal.cardinality = proposal.info.length; return proposal; } } else { forFields.push(fieldB); proposal.info = Object.keys(bIx); proposal.cardinality = proposal.info.length; return proposal; } } // This function checks that there is at least one value in the index that matches the // given pattern. If a level is free, we have to run through the potential values // until we come across one that could match or we run out of values to check. walkCheck(index:any, a:ResolvedValue, b:ResolvedValue, c:ResolvedValue, n:ResolvedValue, transaction:number, round:number):boolean { let bIx = index[a as ID]; if(!bIx) return false; if(isResolved(b)) { let cIx = bIx[b]; if(!cIx) return false; if(isResolved(c)) { let roundArray = cIx[c]; if(roundArray) { return true; } return false; } else { return Object.keys(cIx).length !== 0; } } else { for(let key of Object.keys(bIx)) { let cIx = bIx[key]; if(!cIx) continue; if(isResolved(c)) { let roundArray = cIx[c]; if(roundArray) { return true; } return false; } else if(Object.keys(cIx).length !== 0) { return true; } } } return false; } check(e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue, transaction:number, round:number):boolean { if(isResolved(e)) { return this.walkCheck(this.eavIndex, e, a, v, n, transaction, round); } else if(isResolved(a)) { return this.walkCheck(this.aveIndex, a, v, e, n, transaction, round); } return true; } // This function finds all EAVs in the index that match the given // pattern at the stated time. If a level is free, we have to run // through the potential values until we come across one that could // match or we run out of values to check. walkGet(index:any, a:ResolvedValue, b:ResolvedValue, c:ResolvedValue, n:ResolvedValue, fieldB:EAVNField, fieldC:EAVNField, transaction:number, round:number):EAVN[] { let fieldA:EAVNField = "e"; if(fieldB === "e") fieldA = "a"; let results:EAVN[] = createArray("IndexWalkGet"); let bIx = index[a as ID]; if(!bIx) return results; if(isResolved(b)) { let cIx = bIx[b]; if(!cIx) return results; if(isResolved(c)) { // ABC if(sumTimes(cIx[c], transaction, round) > 0) { results.push({[fieldA]: +a!, [fieldB]: +b, [fieldC]: +c, n} as any); } return results; } else { // ABc for(let c of Object.keys(cIx)) { if(sumTimes(cIx[c], transaction, round) > 0) { results.push({[fieldA]: +a!, [fieldB]: +b, [fieldC]: +c, n} as any); } } return results; } } else { for(let b of Object.keys(bIx)) { let cIx = bIx[b]; if(!cIx) continue; if(isResolved(c)) { // AbC if(sumTimes(cIx[c], transaction, round) > 0) { results.push({[fieldA]: +a!, [fieldB]: +b, [fieldC]: +c, n} as any); } } else { // Abc for(let c of Object.keys(cIx)) { if(sumTimes(cIx[c], transaction, round) > 0) { results.push({[fieldA]: +a!, [fieldB]: +b, [fieldC]: +c, n} as any); } } } } return results; } // throw new Error("HashIndex.walkGet eav not implemented."); } get(e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue, transaction:number, round:number):EAVN[] { if(isResolved(e)) { return this.walkGet(this.eavIndex, e, a, v, n, "a", "v", transaction, round); } else if(isResolved(a)) { return this.walkGet(this.aveIndex, a, v, e, n, "v", "e", transaction, round); } else throw new Error("HashIndex.get eaV not implemented."); } getDiffs(e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue):RoundArray { let aIx = this.eavIndex[e!]; if(aIx) { let vIx = aIx[a!]; if(vIx && vIx[v!]) { return vIx[v!]; } } return createArray(); } } //------------------------------------------------------------------------ // Bit Matrix index //------------------------------------------------------------------------ export class BitMatrixIndex { insert(change:Change):void { throw new Error("not implemented") } propose(proposal:Proposal, e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue, transaction:number, round:number):Proposal { throw new Error("not implemented") } resolveProposal(proposal:Proposal):any[][] { throw new Error("not implemented") } check(e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue, transaction:number, round:number):boolean { throw new Error("not implemented") } getDiffs(e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue):RoundArray { throw new Error("not implemented") } get(e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue, transaction:number, round:number):EAVN[] { throw new Error("not implemented") } } //------------------------------------------------------------------------ // DistinctIndex //------------------------------------------------------------------------ export class DistinctIndex { index:{[key:string]: (number|undefined)[]|undefined} = {}; getDelta(last:number, next:number) { let delta = 0; if(last == 0 && next > 0) delta = 1; if(last > 0 && next == 0) delta = -1; if(last > 0 && next < 0) delta = -1; if(last < 0 && next > 0) delta = 1; return delta; } shouldOutput(key:string, prefixRound:number, prefixCount:number):number[] { let {index} = this; let roundCounts = index[key] || createArray("Insert intermediate counts"); index[key] = roundCounts; let curCount = 0; let startingCount = roundCounts[prefixRound] = roundCounts[prefixRound] || 0; let minRound = Math.min(roundCounts.length, prefixRound + 1); for(let roundIx = 0; roundIx < minRound; roundIx++) { let prevCount = roundCounts[roundIx]; if(!prevCount) continue; curCount += prevCount; } let deltas = []; // We only need delta changed here because if there's a round delta, it // would have been applied already. if(prefixCount === -Infinity) { if(curCount === Infinity) { curCount = 1; startingCount = 1; } prefixCount = -curCount; } let nextCount = curCount + prefixCount; let delta = this.getDelta(curCount, nextCount); if(delta) { deltas.push(prefixRound, delta); } curCount = nextCount; roundCounts[prefixRound] = startingCount + prefixCount; for(let roundIx = prefixRound + 1; roundIx < roundCounts.length; roundIx++) { let roundCount = roundCounts[roundIx]; if(roundCount === undefined || roundCount === 0) continue; let lastCount = curCount - prefixCount; let nextCount = lastCount + roundCount; let delta = this.getDelta(lastCount, nextCount); let lastCountChanged = curCount; let nextCountChanged = curCount + roundCount; let deltaChanged = this.getDelta(lastCountChanged, nextCountChanged); // let finalDelta = deltaChanged - delta; let finalDelta = 0; if(delta && delta !== deltaChanged) { // undo delta finalDelta = -delta; } else if(delta !== deltaChanged) { finalDelta = deltaChanged; } if(finalDelta) { deltas.push(roundIx, finalDelta); } curCount = nextCountChanged; } return deltas; } distinct(input:Change, results:Iterator<Change>):boolean { let {e, a, v, n, round, count} = input; // @FIXME: When we start to unintern, we'll have invalid keys left in this index, // so we'll need to delete the keys themselves from the index let key = `${e}|${a}|${v}`; let deltas = this.shouldOutput(key, round, count); for(let deltaIx = 0; deltaIx < deltas.length; deltaIx += 2) { let deltaRound = deltas[deltaIx]; let delta = deltas[deltaIx + 1]; let change = new Change(e!, a!, v!, n!, input.transaction, deltaRound, delta); results.push(change) } return deltas.length > 0; } distinctKey(key:string, round:number, count:number, results:Iterator<[number, number]>):boolean { let deltas = this.shouldOutput(key, round, count); for(let deltaIx = 0; deltaIx < deltas.length; deltaIx += 2) { let deltaRound = deltas[deltaIx]; let delta = deltas[deltaIx + 1]; results.push([deltaRound, delta]); } return deltas.length > 0; } getCounts(change:Change) { let {e, a, v} = change; let key = `${e}|${a}|${v}`; return this.index[key]; } sanityCheck() { let failed = false; let {index} = this; for(let key in index) { let counts = index[key]!; let sum = 0; for(let c of counts) { if(!c) continue; sum += c; if(sum < 0) { failed = true; console.error("# Negative postDistinct: ", key, counts.slice()) } } } if(failed) throw new Error("Distinct sanity check failed."); } }
the_stack
import { anyObject } from "jest-mock-extended"; import mockFs from "mock-fs"; import type { CatalogEntity, CatalogEntityData, CatalogEntityKindData } from "../catalog"; import { getDiForUnitTesting } from "../../main/getDiForUnitTesting"; import getConfigurationFileModelInjectable from "../get-configuration-file-model/get-configuration-file-model.injectable"; import appVersionInjectable from "../get-configuration-file-model/app-version/app-version.injectable"; import type { DiContainer } from "@ogre-tools/injectable"; import hotbarStoreInjectable from "../hotbars/store.injectable"; import type { HotbarStore } from "../hotbars/store"; import catalogEntityRegistryInjectable from "../../main/catalog/entity-registry.injectable"; import { computed } from "mobx"; import hasCategoryForEntityInjectable from "../catalog/has-category-for-entity.injectable"; import catalogCatalogEntityInjectable from "../catalog-entities/general-catalog-entities/implementations/catalog-catalog-entity.injectable"; import loggerInjectable from "../logger.injectable"; import type { Logger } from "../logger"; import directoryForUserDataInjectable from "../app-paths/directory-for-user-data/directory-for-user-data.injectable"; function getMockCatalogEntity(data: Partial<CatalogEntityData> & CatalogEntityKindData): CatalogEntity { return { getName: jest.fn(() => data.metadata?.name), getId: jest.fn(() => data.metadata?.uid), getSource: jest.fn(() => data.metadata?.source ?? "unknown"), isEnabled: jest.fn(() => data.status?.enabled ?? true), onContextMenuOpen: jest.fn(), onSettingsOpen: jest.fn(), metadata: {}, spec: {}, status: {}, ...data, } as CatalogEntity; } describe("HotbarStore", () => { let di: DiContainer; let hotbarStore: HotbarStore; let testCluster: CatalogEntity; let minikubeCluster: CatalogEntity; let awsCluster: CatalogEntity; let loggerMock: jest.Mocked<Logger>; beforeEach(async () => { di = getDiForUnitTesting({ doGeneralOverrides: true }); (di as any).unoverride(hotbarStoreInjectable); testCluster = getMockCatalogEntity({ apiVersion: "v1", kind: "Cluster", status: { phase: "Running", }, metadata: { uid: "some-test-id", name: "my-test-cluster", source: "local", labels: {}, }, }); minikubeCluster = getMockCatalogEntity({ apiVersion: "v1", kind: "Cluster", status: { phase: "Running", }, metadata: { uid: "some-minikube-id", name: "my-minikube-cluster", source: "local", labels: {}, }, }); awsCluster = getMockCatalogEntity({ apiVersion: "v1", kind: "Cluster", status: { phase: "Running", }, metadata: { uid: "some-aws-id", name: "my-aws-cluster", source: "local", labels: {}, }, }); di.override(hasCategoryForEntityInjectable, () => () => true); loggerMock = { warn: jest.fn(), debug: jest.fn(), error: jest.fn(), info: jest.fn(), silly: jest.fn(), }; di.override(loggerInjectable, () => loggerMock); di.override(directoryForUserDataInjectable, () => "some-directory-for-user-data"); const catalogEntityRegistry = di.inject(catalogEntityRegistryInjectable); const catalogCatalogEntity = di.inject(catalogCatalogEntityInjectable); catalogEntityRegistry.addComputedSource("some-id", computed(() => [ testCluster, minikubeCluster, awsCluster, catalogCatalogEntity, ])); di.permitSideEffects(getConfigurationFileModelInjectable); di.permitSideEffects(appVersionInjectable); di.permitSideEffects(hotbarStoreInjectable); }); afterEach(() => { mockFs.restore(); }); describe("given no previous data in store, running all migrations", () => { beforeEach(() => { mockFs(); hotbarStore = di.inject(hotbarStoreInjectable); hotbarStore.load(); }); describe("load", () => { it("loads one hotbar by default", () => { expect(hotbarStore.hotbars.length).toEqual(1); }); }); describe("add", () => { it("adds a hotbar", () => { hotbarStore.add({ name: "hottest" }); expect(hotbarStore.hotbars.length).toEqual(2); }); }); describe("hotbar items", () => { it("initially creates 12 empty cells", () => { expect(hotbarStore.getActive().items.length).toEqual(12); }); it("initially adds catalog entity as first item", () => { expect(hotbarStore.getActive().items[0]?.entity.name).toEqual("Catalog"); }); it("adds items", () => { hotbarStore.addToHotbar(testCluster); const items = hotbarStore.getActive().items.filter(Boolean); expect(items.length).toEqual(2); }); it("removes items", () => { hotbarStore.addToHotbar(testCluster); hotbarStore.removeFromHotbar("some-test-id"); hotbarStore.removeFromHotbar("catalog-entity"); const items = hotbarStore.getActive().items.filter(Boolean); expect(items).toStrictEqual([]); }); it("does nothing if removing with invalid uid", () => { hotbarStore.addToHotbar(testCluster); hotbarStore.removeFromHotbar("invalid uid"); const items = hotbarStore.getActive().items.filter(Boolean); expect(items.length).toEqual(2); }); it("moves item to empty cell", () => { hotbarStore.addToHotbar(testCluster); hotbarStore.addToHotbar(minikubeCluster); hotbarStore.addToHotbar(awsCluster); expect(hotbarStore.getActive().items[6]).toBeNull(); hotbarStore.restackItems(1, 5); expect(hotbarStore.getActive().items[5]).toBeTruthy(); expect(hotbarStore.getActive().items[5]?.entity.uid).toEqual("some-test-id"); }); it("moves items down", () => { hotbarStore.addToHotbar(testCluster); hotbarStore.addToHotbar(minikubeCluster); hotbarStore.addToHotbar(awsCluster); // aws -> catalog hotbarStore.restackItems(3, 0); const items = hotbarStore.getActive().items.map(item => item?.entity.uid || null); expect(items.slice(0, 4)).toEqual(["some-aws-id", "catalog-entity", "some-test-id", "some-minikube-id"]); }); it("moves items up", () => { hotbarStore.addToHotbar(testCluster); hotbarStore.addToHotbar(minikubeCluster); hotbarStore.addToHotbar(awsCluster); // test -> aws hotbarStore.restackItems(1, 3); const items = hotbarStore.getActive().items.map(item => item?.entity.uid || null); expect(items.slice(0, 4)).toEqual(["catalog-entity", "some-minikube-id", "some-aws-id", "some-test-id"]); }); it("logs an error if cellIndex is out of bounds", () => { hotbarStore.add({ name: "hottest", id: "hottest" }); hotbarStore.setActiveHotbar("hottest"); hotbarStore.addToHotbar(testCluster, -1); expect(loggerMock.error).toBeCalledWith("[HOTBAR-STORE]: cannot pin entity to hotbar outside of index range", anyObject()); hotbarStore.addToHotbar(testCluster, 12); expect(loggerMock.error).toBeCalledWith("[HOTBAR-STORE]: cannot pin entity to hotbar outside of index range", anyObject()); hotbarStore.addToHotbar(testCluster, 13); expect(loggerMock.error).toBeCalledWith("[HOTBAR-STORE]: cannot pin entity to hotbar outside of index range", anyObject()); }); it("throws an error if getId is invalid or returns not a string", () => { expect(() => hotbarStore.addToHotbar({} as any)).toThrowError(TypeError); expect(() => hotbarStore.addToHotbar({ getId: () => true } as any)).toThrowError(TypeError); }); it("throws an error if getName is invalid or returns not a string", () => { expect(() => hotbarStore.addToHotbar({ getId: () => "" } as any)).toThrowError(TypeError); expect(() => hotbarStore.addToHotbar({ getId: () => "", getName: () => 4 } as any)).toThrowError(TypeError); }); it("does nothing when item moved to same cell", () => { hotbarStore.addToHotbar(testCluster); hotbarStore.restackItems(1, 1); expect(hotbarStore.getActive().items[1]?.entity.uid).toEqual("some-test-id"); }); it("new items takes first empty cell", () => { hotbarStore.addToHotbar(testCluster); hotbarStore.addToHotbar(awsCluster); hotbarStore.restackItems(0, 3); hotbarStore.addToHotbar(minikubeCluster); expect(hotbarStore.getActive().items[0]?.entity.uid).toEqual("some-minikube-id"); }); it("throws if invalid arguments provided", () => { // Prevent writing to stderr during this render. const { error, warn } = console; console.error = jest.fn(); console.warn = jest.fn(); hotbarStore.addToHotbar(testCluster); expect(() => hotbarStore.restackItems(-5, 0)).toThrow(); expect(() => hotbarStore.restackItems(2, -1)).toThrow(); expect(() => hotbarStore.restackItems(14, 1)).toThrow(); expect(() => hotbarStore.restackItems(11, 112)).toThrow(); // Restore writing to stderr. console.error = error; console.warn = warn; }); it("checks if entity already pinned to hotbar", () => { hotbarStore.addToHotbar(testCluster); expect(hotbarStore.isAddedToActive(testCluster)).toBeTruthy(); expect(hotbarStore.isAddedToActive(awsCluster)).toBeFalsy(); }); }); }); describe("given data from 5.0.0-beta.3 and version being 5.0.0-beta.10", () => { beforeEach(() => { const configurationToBeMigrated = { "some-directory-for-user-data": { "lens-hotbar-store.json": JSON.stringify({ __internal__: { migrations: { version: "5.0.0-beta.3", }, }, hotbars: [ { id: "3caac17f-aec2-4723-9694-ad204465d935", name: "myhotbar", items: [ { entity: { uid: "some-aws-id", }, }, { entity: { uid: "55b42c3c7ba3b04193416cda405269a5", }, }, { entity: { uid: "176fd331968660832f62283219d7eb6e", }, }, { entity: { uid: "61c4fb45528840ebad1badc25da41d14", name: "user1-context", source: "local", }, }, { entity: { uid: "27d6f99fe9e7548a6e306760bfe19969", name: "foo2", source: "local", }, }, null, { entity: { uid: "c0b20040646849bb4dcf773e43a0bf27", name: "multinode-demo", source: "local", }, }, null, null, null, null, null, ], }, ], }), }, }; mockFs(configurationToBeMigrated); di.override(appVersionInjectable, () => "5.0.0-beta.10"); hotbarStore = di.inject(hotbarStoreInjectable); hotbarStore.load(); }); it("allows to retrieve a hotbar", () => { const hotbar = hotbarStore.findById("3caac17f-aec2-4723-9694-ad204465d935"); expect(hotbar?.id).toBe("3caac17f-aec2-4723-9694-ad204465d935"); }); it("clears cells without entity", () => { const items = hotbarStore.hotbars[0].items; expect(items[2]).toBeNull(); }); it("adds extra data to cells with according entity", () => { const items = hotbarStore.hotbars[0].items; expect(items[0]).toEqual({ entity: { name: "my-aws-cluster", source: "local", uid: "some-aws-id", }, }); }); }); });
the_stack
import { HttpClient } from '@angular/common/http'; import { Observable, from, forkJoin } from 'rxjs'; import { map} from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { ConfigService } from './config.service'; import { PresetOption, PrimaryTag, TagConfig } from "../../type"; @Injectable({ providedIn: 'root' }) export class TagsService { lastTagsUsedIds: string[]; bookmarksIds: string[] = []; savedFields = {}; tags:TagConfig[]; userTags:TagConfig[]; primaryKeys = []; presets = {}; hiddenTagsIds: string[]; basemaps; jsonSprites defaultHiddenTagsIds :string[] = [ 'highway/pedestrian_area', 'highway/footway', 'highway/motorway', 'highway/trunk', 'highway/trunk_link', 'highway/primary', 'highway/primary_link', 'highway/secondary', 'highway/secondary_link', 'highway/tertiary', 'highway/tertiary_link', 'highway/unclassified', 'highway/residential', 'highway/service', 'highway/motorway_link', 'highway/living_street', 'highway/track', 'highway/bus_guideway', 'highway/road', 'highway/bridleway', 'highway/path', 'highway/cycleway', 'highway/construction', 'highway/steps', 'highway/motorway_junction', 'highway/corridor', 'highway/pedestrian_line', 'highway/cycleway/bicycle_foot', 'highway/footway/crossing', 'highway/service/parking_aisle', 'highway/service/driveway', 'highway/path/informal', 'highway/stop', 'highway/turning_circle', 'railway/platform', 'railway/abandoned', 'railway/construction', 'railway/disused', 'railway/funicular', 'railway/light_rail', 'railway/miniature', 'railway/monorail', 'railway/narrow_gauge', 'railway/rail', 'railway/rail/highspeed', 'railway/subway', 'railway/tram', 'railway/tram_level_crossing', 'railway/tram_crossing', 'railway/railway_crossing', 'barrier/kerb', 'barrier/kerb/flush', 'barrier/kerb/lowered', 'barrier/kerb/raised', 'barrier/kerb/rolled', 'natural/grassland', 'natural/wood', 'natural/bare_rock', 'natural/cliff', 'natural/shingle', 'natural/coastline', 'waterway/riverbank', 'waterway/canal', 'waterway/canal/lock', 'waterway/ditch', 'waterway/drain', 'waterway/fish_pass', 'waterway/river', 'waterway/stream_intermittent', 'waterway/stream', 'waterway/tidal_channel', 'man_made/bridge', 'building/yes', 'building/train_station', 'building/apartments', 'building/barn', 'building/boathouse', 'building/bungalow', 'building/cabin', 'building/carport', 'building/cathedral', 'building/chapel', 'building/church', 'building/civic', 'building/college', 'building/commercial', 'building/construction', 'building/detached', 'building/dormitory', 'building/farm_auxiliary', 'building/farm', 'building/garage', 'building/garages', 'building/grandstand', 'building/greenhouse', 'building/hangar', 'building/hospital', 'building/hotel', 'building/house', 'building/houseboat', 'building/hut', 'building/industrial', 'building/kindergarten', 'building/mosque', 'building/pavilion', 'building/public', 'building/residential', 'building/retail', 'building/roof', 'building/ruins', 'building/school', 'building/semidetached_house', 'building/service', 'building/shed', 'building/stable', 'building/stadium', 'building/static_caravan', 'building/temple', 'building/terrace', 'building/transportation', 'building/university', 'building/warehouse', 'building/office' ] constructor(private http: HttpClient, public localStorage: Storage, public configService: ConfigService) { } getTagConfigFromTagsID( tagIds:string[]){ return this.tags.filter( tag => tagIds.includes(tag.id)) } setBookMarksIds(bookmarksIds: string[]) { this.localStorage.set('bookmarksIds', bookmarksIds); this.bookmarksIds = bookmarksIds; } setLastTagsUsedIds(lastTagsUsedIds: string[]){ this.localStorage.set('lastTagsUsedIds', lastTagsUsedIds); this.lastTagsUsedIds = lastTagsUsedIds; } removeBookMark( tag: TagConfig ){ this.bookmarksIds = this.bookmarksIds.filter( b => b !== tag.id); this.setBookMarksIds(this.bookmarksIds) } addBookMark(tag: TagConfig){ if (this.bookmarksIds.includes(tag.id)){ return; } let currentTag = this.tags.find( t => t.id === tag.id); if (!currentTag){ this.addUserTags(tag) } this.bookmarksIds = [tag.id, ...this.bookmarksIds ]; this.setBookMarksIds(this.bookmarksIds) // TODO : si tag inconnu => ajouter à userTag return currentTag; } loadBookMarksIds$() { return from(this.localStorage.get('bookmarksIds')) .pipe( map( bookmarksIds => { bookmarksIds = bookmarksIds ? bookmarksIds : [] this.bookmarksIds = bookmarksIds return bookmarksIds }) ) } // hidden tags loadHiddenTagsIds$() { return from(this.localStorage.get('hiddenTagsIds')) .pipe( map( hiddenTagsIds => { hiddenTagsIds = hiddenTagsIds ? hiddenTagsIds : [...this.defaultHiddenTagsIds]; this.hiddenTagsIds = hiddenTagsIds; return hiddenTagsIds; }) ) } setHiddenTagsIds(hiddenTagsIds: string[]) { this.localStorage.set('hiddenTagsIds', hiddenTagsIds); this.hiddenTagsIds = hiddenTagsIds; } removeHiddenTag(tag:TagConfig){ if(!tag.id){ return; } const newHiddenTags = this.hiddenTagsIds.filter(t => t !== tag.id) this.setHiddenTagsIds(newHiddenTags) } addHiddenTag(tag:TagConfig){ // => hide a tag if(!tag.id){ return; } if (!this.hiddenTagsIds.includes(tag.id)){ const newHiddenTags = [tag.id, ...this.hiddenTagsIds] this.setHiddenTagsIds(newHiddenTags) // delete bookmark... this.removeBookMark(tag) } } resetHiddenTags(){ const defaultHiddenTagsIds = [...this.defaultHiddenTagsIds]; this.setHiddenTagsIds(defaultHiddenTagsIds) } loadLastTagsUsedIds$(){ return from(this.localStorage.get('lastTagsUsedIds')) .pipe( map( lastTagsUsedIds => { lastTagsUsedIds = lastTagsUsedIds ? lastTagsUsedIds : []; this.lastTagsUsedIds = lastTagsUsedIds; return lastTagsUsedIds; }) ) } addTagTolastTagsUsed(tagId: string) { if (!tagId){ return; } if (this.lastTagsUsedIds.includes(tagId)){ this.lastTagsUsedIds = this.lastTagsUsedIds.filter( tu => tu !== tagId); } let currentTag = this.tags.find( t => t.id === tagId); if (!currentTag){ return; } this.lastTagsUsedIds = [tagId, ...this.lastTagsUsedIds].slice(0,20); this.setLastTagsUsedIds(this.lastTagsUsedIds) return currentTag; } loadUserTags$(){ return from( this.localStorage.get('userTags')) .pipe( map( userTags => { userTags = userTags ? userTags : []; this.userTags = userTags; return userTags; }) ) } setUserTags(userTags: TagConfig[]) { this.localStorage.set('userTags', userTags); this.userTags = userTags; } addUserTags(newTag: TagConfig){ const newTagId = newTag.id; if (this.userTags.find( t => t.id === newTagId)){ return; } newTag['geometry'] = ['point', 'vertex', 'line', 'area'] newTag['icon'] = "maki-circle-custom", newTag['markerColor'] = "#000000"; this.userTags = [...this.userTags, newTag] this.tags = [...this.tags, newTag ] this.setUserTags(this.userTags) } loadSavedFields$() { return from(this.localStorage.get('savedFields')) .pipe( map(d => { const res = d ? d : {} this.savedFields = res return res; }) ) } addSavedField(tagId, tags){ if (!this.savedFields[tagId]){ this.savedFields[tagId] = {}; } this.savedFields[tagId]['tags'] = tags // .tags = tags; this.localStorage.set('savedFields', this.savedFields); } findPkey( featureOrTags): PrimaryTag{ const pkeys = this.primaryKeys; if (featureOrTags.properties && featureOrTags.properties.tags){ for (let k in featureOrTags.properties.tags){ if (pkeys.includes(k)){ return {key: k, value:featureOrTags.properties.tags[k] } } return undefined } } else { for (let t of featureOrTags){ if (pkeys.includes(t.key)){ return {key: t.key, value:t.value } } } return undefined } } getTagsConfig$(): Observable<any> { return this.http.get(`assets/tagsAndPresets/tags.json`) .pipe( map( tagsConfig => { this.primaryKeys = tagsConfig['primaryKeys']; return tagsConfig }) ) } loadBaseMaps$() { return this.http.get(`assets/tagsAndPresets/basemap.json`) .pipe( map(baseMaps => { this.configService.baseMapSources = baseMaps; return baseMaps }) ) } loadPresets$() { return this.http.get(`assets/tagsAndPresets/presets.json`) .pipe( map((p) => { const json = p; for (const k in json) { json[k]['_id'] = k; } this.presets = json; return json; }) ); } loadJsonSprites$() { const devicePixelRatio = window.devicePixelRatio > 1 ? 2 : 1; return this.http.get('assets/iconsSprites@x'+devicePixelRatio+'.json') .pipe( map( jsonSprites => { this.jsonSprites = jsonSprites; return jsonSprites; } ) ) } loadTags$(){ return forkJoin( this.getTagsConfig$(), this.loadUserTags$(), ).pipe( map( ([tagsConfig, userTags]) => { let tags = [...tagsConfig['tags'], ...userTags]; this.tags = tags; return tags; }) ) } // loadtagsAndPresets$() { // return forkJoin( // this.loadJsonSprites$(), // this.loadPresets$(), // this.loadTags$(), // this.loadBaseMaps$(), // this.loadBookMarksIds$(), // this.loadLastTagsUsedIds$(), // this.loadHiddenTagsIds$() // ) // .pipe( // map( ([jsonSprites, presets, tagsConfig, baseMaps, bookmarksIds, lastTagsUsedIds, userTags, hiddenTagsIds]) => { // return [jsonSprites, presets, tagsConfig, baseMaps, bookmarksIds, lastTagsUsedIds, userTags, hiddenTagsIds] // } ) // ) // } }
the_stack
import * as $protobuf from "protobufjs"; /** Namespace google. */ export namespace google { /** Namespace cloud. */ namespace cloud { /** Namespace compute. */ namespace compute { /** Namespace v1. */ namespace v1 { /** Properties of an Operation. */ interface IOperation { /** Operation clientOperationId */ clientOperationId?: (string|null); /** Operation creationTimestamp */ creationTimestamp?: (string|null); /** Operation description */ description?: (string|null); /** Operation endTime */ endTime?: (string|null); /** Operation error */ error?: (google.cloud.compute.v1.IError|null); /** Operation httpErrorMessage */ httpErrorMessage?: (string|null); /** Operation httpErrorStatusCode */ httpErrorStatusCode?: (number|null); /** Operation id */ id?: (string|null); /** Operation insertTime */ insertTime?: (string|null); /** Operation kind */ kind?: (string|null); /** Operation name */ name?: (string|null); /** Operation operationType */ operationType?: (string|null); /** Operation progress */ progress?: (number|null); /** Operation region */ region?: (string|null); /** Operation selfLink */ selfLink?: (string|null); /** Operation startTime */ startTime?: (string|null); /** Operation status */ status?: (google.cloud.compute.v1.Operation.Status|null); /** Operation statusMessage */ statusMessage?: (string|null); /** Operation targetId */ targetId?: (string|null); /** Operation targetLink */ targetLink?: (string|null); /** Operation user */ user?: (string|null); /** Operation warnings */ warnings?: (google.cloud.compute.v1.IWarnings[]|null); /** Operation zone */ zone?: (string|null); } /** Represents an Operation. */ class Operation implements IOperation { /** * Constructs a new Operation. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IOperation); /** Operation clientOperationId. */ public clientOperationId?: (string|null); /** Operation creationTimestamp. */ public creationTimestamp?: (string|null); /** Operation description. */ public description?: (string|null); /** Operation endTime. */ public endTime?: (string|null); /** Operation error. */ public error?: (google.cloud.compute.v1.IError|null); /** Operation httpErrorMessage. */ public httpErrorMessage?: (string|null); /** Operation httpErrorStatusCode. */ public httpErrorStatusCode?: (number|null); /** Operation id. */ public id?: (string|null); /** Operation insertTime. */ public insertTime?: (string|null); /** Operation kind. */ public kind?: (string|null); /** Operation name. */ public name?: (string|null); /** Operation operationType. */ public operationType?: (string|null); /** Operation progress. */ public progress?: (number|null); /** Operation region. */ public region?: (string|null); /** Operation selfLink. */ public selfLink?: (string|null); /** Operation startTime. */ public startTime?: (string|null); /** Operation status. */ public status?: (google.cloud.compute.v1.Operation.Status|null); /** Operation statusMessage. */ public statusMessage?: (string|null); /** Operation targetId. */ public targetId?: (string|null); /** Operation targetLink. */ public targetLink?: (string|null); /** Operation user. */ public user?: (string|null); /** Operation warnings. */ public warnings: google.cloud.compute.v1.IWarnings[]; /** Operation zone. */ public zone?: (string|null); /** Operation _clientOperationId. */ public _clientOperationId?: "clientOperationId"; /** Operation _creationTimestamp. */ public _creationTimestamp?: "creationTimestamp"; /** Operation _description. */ public _description?: "description"; /** Operation _endTime. */ public _endTime?: "endTime"; /** Operation _error. */ public _error?: "error"; /** Operation _httpErrorMessage. */ public _httpErrorMessage?: "httpErrorMessage"; /** Operation _httpErrorStatusCode. */ public _httpErrorStatusCode?: "httpErrorStatusCode"; /** Operation _id. */ public _id?: "id"; /** Operation _insertTime. */ public _insertTime?: "insertTime"; /** Operation _kind. */ public _kind?: "kind"; /** Operation _name. */ public _name?: "name"; /** Operation _operationType. */ public _operationType?: "operationType"; /** Operation _progress. */ public _progress?: "progress"; /** Operation _region. */ public _region?: "region"; /** Operation _selfLink. */ public _selfLink?: "selfLink"; /** Operation _startTime. */ public _startTime?: "startTime"; /** Operation _status. */ public _status?: "status"; /** Operation _statusMessage. */ public _statusMessage?: "statusMessage"; /** Operation _targetId. */ public _targetId?: "targetId"; /** Operation _targetLink. */ public _targetLink?: "targetLink"; /** Operation _user. */ public _user?: "user"; /** Operation _zone. */ public _zone?: "zone"; /** * Creates a new Operation instance using the specified properties. * @param [properties] Properties to set * @returns Operation instance */ public static create(properties?: google.cloud.compute.v1.IOperation): google.cloud.compute.v1.Operation; /** * Encodes the specified Operation message. Does not implicitly {@link google.cloud.compute.v1.Operation.verify|verify} messages. * @param message Operation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Operation message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Operation.verify|verify} messages. * @param message Operation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Operation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Operation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Operation; /** * Decodes an Operation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Operation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Operation; /** * Verifies an Operation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Operation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Operation */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Operation; /** * Creates a plain object from an Operation message. Also converts values to other types if specified. * @param message Operation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Operation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Operation { /** Status enum. */ enum Status { UNDEFINED_STATUS = 0, DONE = 2104194, PENDING = 35394935, RUNNING = 121282975 } } /** Properties of an Errors. */ interface IErrors { /** Errors code */ code?: (string|null); /** Errors location */ location?: (string|null); /** Errors message */ message?: (string|null); } /** Represents an Errors. */ class Errors implements IErrors { /** * Constructs a new Errors. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IErrors); /** Errors code. */ public code?: (string|null); /** Errors location. */ public location?: (string|null); /** Errors message. */ public message?: (string|null); /** Errors _code. */ public _code?: "code"; /** Errors _location. */ public _location?: "location"; /** Errors _message. */ public _message?: "message"; /** * Creates a new Errors instance using the specified properties. * @param [properties] Properties to set * @returns Errors instance */ public static create(properties?: google.cloud.compute.v1.IErrors): google.cloud.compute.v1.Errors; /** * Encodes the specified Errors message. Does not implicitly {@link google.cloud.compute.v1.Errors.verify|verify} messages. * @param message Errors message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IErrors, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Errors message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Errors.verify|verify} messages. * @param message Errors message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IErrors, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Errors message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Errors * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Errors; /** * Decodes an Errors message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Errors * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Errors; /** * Verifies an Errors message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Errors message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Errors */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Errors; /** * Creates a plain object from an Errors message. Also converts values to other types if specified. * @param message Errors * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.Errors, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Errors to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Error. */ interface IError { /** Error errors */ errors?: (google.cloud.compute.v1.IErrors[]|null); } /** Represents an Error. */ class Error implements IError { /** * Constructs a new Error. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IError); /** Error errors. */ public errors: google.cloud.compute.v1.IErrors[]; /** * Creates a new Error instance using the specified properties. * @param [properties] Properties to set * @returns Error instance */ public static create(properties?: google.cloud.compute.v1.IError): google.cloud.compute.v1.Error; /** * Encodes the specified Error message. Does not implicitly {@link google.cloud.compute.v1.Error.verify|verify} messages. * @param message Error message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IError, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Error message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Error.verify|verify} messages. * @param message Error message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IError, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Error message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Error * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Error; /** * Decodes an Error message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Error * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Error; /** * Verifies an Error message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Error message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Error */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Error; /** * Creates a plain object from an Error message. Also converts values to other types if specified. * @param message Error * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.Error, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Error to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Warnings. */ interface IWarnings { /** Warnings code */ code?: (google.cloud.compute.v1.Warnings.Code|null); /** Warnings data */ data?: (google.cloud.compute.v1.IData[]|null); /** Warnings message */ message?: (string|null); } /** Represents a Warnings. */ class Warnings implements IWarnings { /** * Constructs a new Warnings. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IWarnings); /** Warnings code. */ public code?: (google.cloud.compute.v1.Warnings.Code|null); /** Warnings data. */ public data: google.cloud.compute.v1.IData[]; /** Warnings message. */ public message?: (string|null); /** Warnings _code. */ public _code?: "code"; /** Warnings _message. */ public _message?: "message"; /** * Creates a new Warnings instance using the specified properties. * @param [properties] Properties to set * @returns Warnings instance */ public static create(properties?: google.cloud.compute.v1.IWarnings): google.cloud.compute.v1.Warnings; /** * Encodes the specified Warnings message. Does not implicitly {@link google.cloud.compute.v1.Warnings.verify|verify} messages. * @param message Warnings message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IWarnings, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Warnings message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Warnings.verify|verify} messages. * @param message Warnings message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IWarnings, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Warnings message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Warnings * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Warnings; /** * Decodes a Warnings message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Warnings * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Warnings; /** * Verifies a Warnings message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Warnings message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Warnings */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Warnings; /** * Creates a plain object from a Warnings message. Also converts values to other types if specified. * @param message Warnings * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.Warnings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Warnings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Warnings { /** Code enum. */ enum Code { UNDEFINED_CODE = 0, CLEANUP_FAILED = 150308440, DEPRECATED_RESOURCE_USED = 391835586, DEPRECATED_TYPE_USED = 346526230, DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 369442967, EXPERIMENTAL_TYPE_USED = 451954443, EXTERNAL_API_WARNING = 175546307, FIELD_VALUE_OVERRIDEN = 329669423, INJECTED_KERNELS_DEPRECATED = 417377419, MISSING_TYPE_DEPENDENCY = 344505463, NEXT_HOP_ADDRESS_NOT_ASSIGNED = 324964999, NEXT_HOP_CANNOT_IP_FORWARD = 383382887, NEXT_HOP_INSTANCE_NOT_FOUND = 464250446, NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 243758146, NEXT_HOP_NOT_RUNNING = 417081265, NOT_CRITICAL_ERROR = 105763924, NO_RESULTS_ON_PAGE = 30036744, REQUIRED_TOS_AGREEMENT = 3745539, RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 496728641, RESOURCE_NOT_DELETED = 168598460, SCHEMA_VALIDATION_IGNORED = 275245642, SINGLE_INSTANCE_PROPERTY_TEMPLATE = 268305617, UNDECLARED_PROPERTIES = 390513439, UNREACHABLE = 13328052 } } /** Properties of a Warning. */ interface IWarning { /** Warning code */ code?: (google.cloud.compute.v1.Warning.Code|null); /** Warning data */ data?: (google.cloud.compute.v1.IData[]|null); /** Warning message */ message?: (string|null); } /** Represents a Warning. */ class Warning implements IWarning { /** * Constructs a new Warning. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IWarning); /** Warning code. */ public code?: (google.cloud.compute.v1.Warning.Code|null); /** Warning data. */ public data: google.cloud.compute.v1.IData[]; /** Warning message. */ public message?: (string|null); /** Warning _code. */ public _code?: "code"; /** Warning _message. */ public _message?: "message"; /** * Creates a new Warning instance using the specified properties. * @param [properties] Properties to set * @returns Warning instance */ public static create(properties?: google.cloud.compute.v1.IWarning): google.cloud.compute.v1.Warning; /** * Encodes the specified Warning message. Does not implicitly {@link google.cloud.compute.v1.Warning.verify|verify} messages. * @param message Warning message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IWarning, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Warning message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Warning.verify|verify} messages. * @param message Warning message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IWarning, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Warning message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Warning * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Warning; /** * Decodes a Warning message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Warning * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Warning; /** * Verifies a Warning message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Warning message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Warning */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Warning; /** * Creates a plain object from a Warning message. Also converts values to other types if specified. * @param message Warning * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.Warning, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Warning to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Warning { /** Code enum. */ enum Code { UNDEFINED_CODE = 0, CLEANUP_FAILED = 150308440, DEPRECATED_RESOURCE_USED = 391835586, DEPRECATED_TYPE_USED = 346526230, DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 369442967, EXPERIMENTAL_TYPE_USED = 451954443, EXTERNAL_API_WARNING = 175546307, FIELD_VALUE_OVERRIDEN = 329669423, INJECTED_KERNELS_DEPRECATED = 417377419, LARGE_DEPLOYMENT_WARNING = 481440678, MISSING_TYPE_DEPENDENCY = 344505463, NEXT_HOP_ADDRESS_NOT_ASSIGNED = 324964999, NEXT_HOP_CANNOT_IP_FORWARD = 383382887, NEXT_HOP_INSTANCE_NOT_FOUND = 464250446, NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 243758146, NEXT_HOP_NOT_RUNNING = 417081265, NOT_CRITICAL_ERROR = 105763924, NO_RESULTS_ON_PAGE = 30036744, PARTIAL_SUCCESS = 39966469, REQUIRED_TOS_AGREEMENT = 3745539, RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 496728641, RESOURCE_NOT_DELETED = 168598460, SCHEMA_VALIDATION_IGNORED = 275245642, SINGLE_INSTANCE_PROPERTY_TEMPLATE = 268305617, UNDECLARED_PROPERTIES = 390513439, UNREACHABLE = 13328052 } } /** Properties of a Data. */ interface IData { /** Data key */ key?: (string|null); /** Data value */ value?: (string|null); } /** Represents a Data. */ class Data implements IData { /** * Constructs a new Data. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IData); /** Data key. */ public key?: (string|null); /** Data value. */ public value?: (string|null); /** Data _key. */ public _key?: "key"; /** Data _value. */ public _value?: "value"; /** * Creates a new Data instance using the specified properties. * @param [properties] Properties to set * @returns Data instance */ public static create(properties?: google.cloud.compute.v1.IData): google.cloud.compute.v1.Data; /** * Encodes the specified Data message. Does not implicitly {@link google.cloud.compute.v1.Data.verify|verify} messages. * @param message Data message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Data message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Data.verify|verify} messages. * @param message Data message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Data message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Data * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Data; /** * Decodes a Data message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Data * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Data; /** * Verifies a Data message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Data message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Data */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Data; /** * Creates a plain object from a Data message. Also converts values to other types if specified. * @param message Data * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.Data, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Data to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an OperationsScopedList. */ interface IOperationsScopedList { /** OperationsScopedList operations */ operations?: (google.cloud.compute.v1.IOperation[]|null); /** OperationsScopedList warning */ warning?: (google.cloud.compute.v1.IWarning|null); } /** Represents an OperationsScopedList. */ class OperationsScopedList implements IOperationsScopedList { /** * Constructs a new OperationsScopedList. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IOperationsScopedList); /** OperationsScopedList operations. */ public operations: google.cloud.compute.v1.IOperation[]; /** OperationsScopedList warning. */ public warning?: (google.cloud.compute.v1.IWarning|null); /** OperationsScopedList _warning. */ public _warning?: "warning"; /** * Creates a new OperationsScopedList instance using the specified properties. * @param [properties] Properties to set * @returns OperationsScopedList instance */ public static create(properties?: google.cloud.compute.v1.IOperationsScopedList): google.cloud.compute.v1.OperationsScopedList; /** * Encodes the specified OperationsScopedList message. Does not implicitly {@link google.cloud.compute.v1.OperationsScopedList.verify|verify} messages. * @param message OperationsScopedList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IOperationsScopedList, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OperationsScopedList message, length delimited. Does not implicitly {@link google.cloud.compute.v1.OperationsScopedList.verify|verify} messages. * @param message OperationsScopedList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IOperationsScopedList, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OperationsScopedList message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OperationsScopedList * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.OperationsScopedList; /** * Decodes an OperationsScopedList message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OperationsScopedList * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.OperationsScopedList; /** * Verifies an OperationsScopedList message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OperationsScopedList message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OperationsScopedList */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.OperationsScopedList; /** * Creates a plain object from an OperationsScopedList message. Also converts values to other types if specified. * @param message OperationsScopedList * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.OperationsScopedList, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OperationsScopedList to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an OperationAggregatedList. */ interface IOperationAggregatedList { /** OperationAggregatedList id */ id?: (string|null); /** OperationAggregatedList items */ items?: ({ [k: string]: google.cloud.compute.v1.IOperationsScopedList }|null); /** OperationAggregatedList kind */ kind?: (string|null); /** OperationAggregatedList nextPageToken */ nextPageToken?: (string|null); /** OperationAggregatedList selfLink */ selfLink?: (string|null); /** OperationAggregatedList unreachables */ unreachables?: (string[]|null); /** OperationAggregatedList warning */ warning?: (google.cloud.compute.v1.IWarning|null); } /** Represents an OperationAggregatedList. */ class OperationAggregatedList implements IOperationAggregatedList { /** * Constructs a new OperationAggregatedList. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IOperationAggregatedList); /** OperationAggregatedList id. */ public id?: (string|null); /** OperationAggregatedList items. */ public items: { [k: string]: google.cloud.compute.v1.IOperationsScopedList }; /** OperationAggregatedList kind. */ public kind?: (string|null); /** OperationAggregatedList nextPageToken. */ public nextPageToken?: (string|null); /** OperationAggregatedList selfLink. */ public selfLink?: (string|null); /** OperationAggregatedList unreachables. */ public unreachables: string[]; /** OperationAggregatedList warning. */ public warning?: (google.cloud.compute.v1.IWarning|null); /** OperationAggregatedList _id. */ public _id?: "id"; /** OperationAggregatedList _kind. */ public _kind?: "kind"; /** OperationAggregatedList _nextPageToken. */ public _nextPageToken?: "nextPageToken"; /** OperationAggregatedList _selfLink. */ public _selfLink?: "selfLink"; /** OperationAggregatedList _warning. */ public _warning?: "warning"; /** * Creates a new OperationAggregatedList instance using the specified properties. * @param [properties] Properties to set * @returns OperationAggregatedList instance */ public static create(properties?: google.cloud.compute.v1.IOperationAggregatedList): google.cloud.compute.v1.OperationAggregatedList; /** * Encodes the specified OperationAggregatedList message. Does not implicitly {@link google.cloud.compute.v1.OperationAggregatedList.verify|verify} messages. * @param message OperationAggregatedList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IOperationAggregatedList, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OperationAggregatedList message, length delimited. Does not implicitly {@link google.cloud.compute.v1.OperationAggregatedList.verify|verify} messages. * @param message OperationAggregatedList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IOperationAggregatedList, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OperationAggregatedList message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OperationAggregatedList * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.OperationAggregatedList; /** * Decodes an OperationAggregatedList message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OperationAggregatedList * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.OperationAggregatedList; /** * Verifies an OperationAggregatedList message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OperationAggregatedList message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OperationAggregatedList */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.OperationAggregatedList; /** * Creates a plain object from an OperationAggregatedList message. Also converts values to other types if specified. * @param message OperationAggregatedList * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.OperationAggregatedList, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OperationAggregatedList to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetRegionOperationRequest. */ interface IGetRegionOperationRequest { /** GetRegionOperationRequest operation */ operation?: (string|null); /** GetRegionOperationRequest project */ project?: (string|null); /** GetRegionOperationRequest region */ region?: (string|null); } /** Represents a GetRegionOperationRequest. */ class GetRegionOperationRequest implements IGetRegionOperationRequest { /** * Constructs a new GetRegionOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IGetRegionOperationRequest); /** GetRegionOperationRequest operation. */ public operation: string; /** GetRegionOperationRequest project. */ public project: string; /** GetRegionOperationRequest region. */ public region: string; /** * Creates a new GetRegionOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetRegionOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IGetRegionOperationRequest): google.cloud.compute.v1.GetRegionOperationRequest; /** * Encodes the specified GetRegionOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.GetRegionOperationRequest.verify|verify} messages. * @param message GetRegionOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IGetRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetRegionOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.GetRegionOperationRequest.verify|verify} messages. * @param message GetRegionOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IGetRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetRegionOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetRegionOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.GetRegionOperationRequest; /** * Decodes a GetRegionOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetRegionOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.GetRegionOperationRequest; /** * Verifies a GetRegionOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetRegionOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetRegionOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.GetRegionOperationRequest; /** * Creates a plain object from a GetRegionOperationRequest message. Also converts values to other types if specified. * @param message GetRegionOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.GetRegionOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetRegionOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteRegionOperationRequest. */ interface IDeleteRegionOperationRequest { /** DeleteRegionOperationRequest operation */ operation?: (string|null); /** DeleteRegionOperationRequest project */ project?: (string|null); /** DeleteRegionOperationRequest region */ region?: (string|null); } /** Represents a DeleteRegionOperationRequest. */ class DeleteRegionOperationRequest implements IDeleteRegionOperationRequest { /** * Constructs a new DeleteRegionOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IDeleteRegionOperationRequest); /** DeleteRegionOperationRequest operation. */ public operation: string; /** DeleteRegionOperationRequest project. */ public project: string; /** DeleteRegionOperationRequest region. */ public region: string; /** * Creates a new DeleteRegionOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns DeleteRegionOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IDeleteRegionOperationRequest): google.cloud.compute.v1.DeleteRegionOperationRequest; /** * Encodes the specified DeleteRegionOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.DeleteRegionOperationRequest.verify|verify} messages. * @param message DeleteRegionOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IDeleteRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteRegionOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteRegionOperationRequest.verify|verify} messages. * @param message DeleteRegionOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IDeleteRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteRegionOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteRegionOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteRegionOperationRequest; /** * Decodes a DeleteRegionOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteRegionOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteRegionOperationRequest; /** * Verifies a DeleteRegionOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteRegionOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteRegionOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteRegionOperationRequest; /** * Creates a plain object from a DeleteRegionOperationRequest message. Also converts values to other types if specified. * @param message DeleteRegionOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.DeleteRegionOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteRegionOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteRegionOperationResponse. */ interface IDeleteRegionOperationResponse { } /** Represents a DeleteRegionOperationResponse. */ class DeleteRegionOperationResponse implements IDeleteRegionOperationResponse { /** * Constructs a new DeleteRegionOperationResponse. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IDeleteRegionOperationResponse); /** * Creates a new DeleteRegionOperationResponse instance using the specified properties. * @param [properties] Properties to set * @returns DeleteRegionOperationResponse instance */ public static create(properties?: google.cloud.compute.v1.IDeleteRegionOperationResponse): google.cloud.compute.v1.DeleteRegionOperationResponse; /** * Encodes the specified DeleteRegionOperationResponse message. Does not implicitly {@link google.cloud.compute.v1.DeleteRegionOperationResponse.verify|verify} messages. * @param message DeleteRegionOperationResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IDeleteRegionOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteRegionOperationResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteRegionOperationResponse.verify|verify} messages. * @param message DeleteRegionOperationResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IDeleteRegionOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteRegionOperationResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteRegionOperationResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteRegionOperationResponse; /** * Decodes a DeleteRegionOperationResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteRegionOperationResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteRegionOperationResponse; /** * Verifies a DeleteRegionOperationResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteRegionOperationResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteRegionOperationResponse */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteRegionOperationResponse; /** * Creates a plain object from a DeleteRegionOperationResponse message. Also converts values to other types if specified. * @param message DeleteRegionOperationResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.DeleteRegionOperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteRegionOperationResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListRegionOperationsRequest. */ interface IListRegionOperationsRequest { /** ListRegionOperationsRequest filter */ filter?: (string|null); /** ListRegionOperationsRequest maxResults */ maxResults?: (number|null); /** ListRegionOperationsRequest orderBy */ orderBy?: (string|null); /** ListRegionOperationsRequest pageToken */ pageToken?: (string|null); /** ListRegionOperationsRequest project */ project?: (string|null); /** ListRegionOperationsRequest region */ region?: (string|null); /** ListRegionOperationsRequest returnPartialSuccess */ returnPartialSuccess?: (boolean|null); } /** Represents a ListRegionOperationsRequest. */ class ListRegionOperationsRequest implements IListRegionOperationsRequest { /** * Constructs a new ListRegionOperationsRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IListRegionOperationsRequest); /** ListRegionOperationsRequest filter. */ public filter?: (string|null); /** ListRegionOperationsRequest maxResults. */ public maxResults?: (number|null); /** ListRegionOperationsRequest orderBy. */ public orderBy?: (string|null); /** ListRegionOperationsRequest pageToken. */ public pageToken?: (string|null); /** ListRegionOperationsRequest project. */ public project: string; /** ListRegionOperationsRequest region. */ public region: string; /** ListRegionOperationsRequest returnPartialSuccess. */ public returnPartialSuccess?: (boolean|null); /** ListRegionOperationsRequest _filter. */ public _filter?: "filter"; /** ListRegionOperationsRequest _maxResults. */ public _maxResults?: "maxResults"; /** ListRegionOperationsRequest _orderBy. */ public _orderBy?: "orderBy"; /** ListRegionOperationsRequest _pageToken. */ public _pageToken?: "pageToken"; /** ListRegionOperationsRequest _returnPartialSuccess. */ public _returnPartialSuccess?: "returnPartialSuccess"; /** * Creates a new ListRegionOperationsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListRegionOperationsRequest instance */ public static create(properties?: google.cloud.compute.v1.IListRegionOperationsRequest): google.cloud.compute.v1.ListRegionOperationsRequest; /** * Encodes the specified ListRegionOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.ListRegionOperationsRequest.verify|verify} messages. * @param message ListRegionOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IListRegionOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListRegionOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.ListRegionOperationsRequest.verify|verify} messages. * @param message ListRegionOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IListRegionOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListRegionOperationsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListRegionOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.ListRegionOperationsRequest; /** * Decodes a ListRegionOperationsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListRegionOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.ListRegionOperationsRequest; /** * Verifies a ListRegionOperationsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListRegionOperationsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListRegionOperationsRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.ListRegionOperationsRequest; /** * Creates a plain object from a ListRegionOperationsRequest message. Also converts values to other types if specified. * @param message ListRegionOperationsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.ListRegionOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListRegionOperationsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an OperationList. */ interface IOperationList { /** OperationList id */ id?: (string|null); /** OperationList items */ items?: (google.cloud.compute.v1.IOperation[]|null); /** OperationList kind */ kind?: (string|null); /** OperationList nextPageToken */ nextPageToken?: (string|null); /** OperationList selfLink */ selfLink?: (string|null); /** OperationList warning */ warning?: (google.cloud.compute.v1.IWarning|null); } /** Represents an OperationList. */ class OperationList implements IOperationList { /** * Constructs a new OperationList. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IOperationList); /** OperationList id. */ public id?: (string|null); /** OperationList items. */ public items: google.cloud.compute.v1.IOperation[]; /** OperationList kind. */ public kind?: (string|null); /** OperationList nextPageToken. */ public nextPageToken?: (string|null); /** OperationList selfLink. */ public selfLink?: (string|null); /** OperationList warning. */ public warning?: (google.cloud.compute.v1.IWarning|null); /** OperationList _id. */ public _id?: "id"; /** OperationList _kind. */ public _kind?: "kind"; /** OperationList _nextPageToken. */ public _nextPageToken?: "nextPageToken"; /** OperationList _selfLink. */ public _selfLink?: "selfLink"; /** OperationList _warning. */ public _warning?: "warning"; /** * Creates a new OperationList instance using the specified properties. * @param [properties] Properties to set * @returns OperationList instance */ public static create(properties?: google.cloud.compute.v1.IOperationList): google.cloud.compute.v1.OperationList; /** * Encodes the specified OperationList message. Does not implicitly {@link google.cloud.compute.v1.OperationList.verify|verify} messages. * @param message OperationList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IOperationList, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OperationList message, length delimited. Does not implicitly {@link google.cloud.compute.v1.OperationList.verify|verify} messages. * @param message OperationList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IOperationList, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OperationList message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OperationList * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.OperationList; /** * Decodes an OperationList message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OperationList * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.OperationList; /** * Verifies an OperationList message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OperationList message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OperationList */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.OperationList; /** * Creates a plain object from an OperationList message. Also converts values to other types if specified. * @param message OperationList * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.OperationList, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OperationList to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a WaitRegionOperationRequest. */ interface IWaitRegionOperationRequest { /** WaitRegionOperationRequest operation */ operation?: (string|null); /** WaitRegionOperationRequest project */ project?: (string|null); /** WaitRegionOperationRequest region */ region?: (string|null); } /** Represents a WaitRegionOperationRequest. */ class WaitRegionOperationRequest implements IWaitRegionOperationRequest { /** * Constructs a new WaitRegionOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IWaitRegionOperationRequest); /** WaitRegionOperationRequest operation. */ public operation: string; /** WaitRegionOperationRequest project. */ public project: string; /** WaitRegionOperationRequest region. */ public region: string; /** * Creates a new WaitRegionOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns WaitRegionOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IWaitRegionOperationRequest): google.cloud.compute.v1.WaitRegionOperationRequest; /** * Encodes the specified WaitRegionOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.WaitRegionOperationRequest.verify|verify} messages. * @param message WaitRegionOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IWaitRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified WaitRegionOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.WaitRegionOperationRequest.verify|verify} messages. * @param message WaitRegionOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IWaitRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a WaitRegionOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns WaitRegionOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.WaitRegionOperationRequest; /** * Decodes a WaitRegionOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns WaitRegionOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.WaitRegionOperationRequest; /** * Verifies a WaitRegionOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a WaitRegionOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns WaitRegionOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.WaitRegionOperationRequest; /** * Creates a plain object from a WaitRegionOperationRequest message. Also converts values to other types if specified. * @param message WaitRegionOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.WaitRegionOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this WaitRegionOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteZoneOperationRequest. */ interface IDeleteZoneOperationRequest { /** DeleteZoneOperationRequest operation */ operation?: (string|null); /** DeleteZoneOperationRequest project */ project?: (string|null); /** DeleteZoneOperationRequest zone */ zone?: (string|null); } /** Represents a DeleteZoneOperationRequest. */ class DeleteZoneOperationRequest implements IDeleteZoneOperationRequest { /** * Constructs a new DeleteZoneOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IDeleteZoneOperationRequest); /** DeleteZoneOperationRequest operation. */ public operation: string; /** DeleteZoneOperationRequest project. */ public project: string; /** DeleteZoneOperationRequest zone. */ public zone: string; /** * Creates a new DeleteZoneOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns DeleteZoneOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IDeleteZoneOperationRequest): google.cloud.compute.v1.DeleteZoneOperationRequest; /** * Encodes the specified DeleteZoneOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.DeleteZoneOperationRequest.verify|verify} messages. * @param message DeleteZoneOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IDeleteZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteZoneOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteZoneOperationRequest.verify|verify} messages. * @param message DeleteZoneOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IDeleteZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteZoneOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteZoneOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteZoneOperationRequest; /** * Decodes a DeleteZoneOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteZoneOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteZoneOperationRequest; /** * Verifies a DeleteZoneOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteZoneOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteZoneOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteZoneOperationRequest; /** * Creates a plain object from a DeleteZoneOperationRequest message. Also converts values to other types if specified. * @param message DeleteZoneOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.DeleteZoneOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteZoneOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteZoneOperationResponse. */ interface IDeleteZoneOperationResponse { } /** Represents a DeleteZoneOperationResponse. */ class DeleteZoneOperationResponse implements IDeleteZoneOperationResponse { /** * Constructs a new DeleteZoneOperationResponse. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IDeleteZoneOperationResponse); /** * Creates a new DeleteZoneOperationResponse instance using the specified properties. * @param [properties] Properties to set * @returns DeleteZoneOperationResponse instance */ public static create(properties?: google.cloud.compute.v1.IDeleteZoneOperationResponse): google.cloud.compute.v1.DeleteZoneOperationResponse; /** * Encodes the specified DeleteZoneOperationResponse message. Does not implicitly {@link google.cloud.compute.v1.DeleteZoneOperationResponse.verify|verify} messages. * @param message DeleteZoneOperationResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IDeleteZoneOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteZoneOperationResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteZoneOperationResponse.verify|verify} messages. * @param message DeleteZoneOperationResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IDeleteZoneOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteZoneOperationResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteZoneOperationResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteZoneOperationResponse; /** * Decodes a DeleteZoneOperationResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteZoneOperationResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteZoneOperationResponse; /** * Verifies a DeleteZoneOperationResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteZoneOperationResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteZoneOperationResponse */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteZoneOperationResponse; /** * Creates a plain object from a DeleteZoneOperationResponse message. Also converts values to other types if specified. * @param message DeleteZoneOperationResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.DeleteZoneOperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteZoneOperationResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetZoneOperationRequest. */ interface IGetZoneOperationRequest { /** GetZoneOperationRequest operation */ operation?: (string|null); /** GetZoneOperationRequest project */ project?: (string|null); /** GetZoneOperationRequest zone */ zone?: (string|null); } /** Represents a GetZoneOperationRequest. */ class GetZoneOperationRequest implements IGetZoneOperationRequest { /** * Constructs a new GetZoneOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IGetZoneOperationRequest); /** GetZoneOperationRequest operation. */ public operation: string; /** GetZoneOperationRequest project. */ public project: string; /** GetZoneOperationRequest zone. */ public zone: string; /** * Creates a new GetZoneOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetZoneOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IGetZoneOperationRequest): google.cloud.compute.v1.GetZoneOperationRequest; /** * Encodes the specified GetZoneOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.GetZoneOperationRequest.verify|verify} messages. * @param message GetZoneOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IGetZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetZoneOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.GetZoneOperationRequest.verify|verify} messages. * @param message GetZoneOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IGetZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetZoneOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetZoneOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.GetZoneOperationRequest; /** * Decodes a GetZoneOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetZoneOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.GetZoneOperationRequest; /** * Verifies a GetZoneOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetZoneOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetZoneOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.GetZoneOperationRequest; /** * Creates a plain object from a GetZoneOperationRequest message. Also converts values to other types if specified. * @param message GetZoneOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.GetZoneOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetZoneOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListZoneOperationsRequest. */ interface IListZoneOperationsRequest { /** ListZoneOperationsRequest filter */ filter?: (string|null); /** ListZoneOperationsRequest maxResults */ maxResults?: (number|null); /** ListZoneOperationsRequest orderBy */ orderBy?: (string|null); /** ListZoneOperationsRequest pageToken */ pageToken?: (string|null); /** ListZoneOperationsRequest project */ project?: (string|null); /** ListZoneOperationsRequest returnPartialSuccess */ returnPartialSuccess?: (boolean|null); /** ListZoneOperationsRequest zone */ zone?: (string|null); } /** Represents a ListZoneOperationsRequest. */ class ListZoneOperationsRequest implements IListZoneOperationsRequest { /** * Constructs a new ListZoneOperationsRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IListZoneOperationsRequest); /** ListZoneOperationsRequest filter. */ public filter?: (string|null); /** ListZoneOperationsRequest maxResults. */ public maxResults?: (number|null); /** ListZoneOperationsRequest orderBy. */ public orderBy?: (string|null); /** ListZoneOperationsRequest pageToken. */ public pageToken?: (string|null); /** ListZoneOperationsRequest project. */ public project: string; /** ListZoneOperationsRequest returnPartialSuccess. */ public returnPartialSuccess?: (boolean|null); /** ListZoneOperationsRequest zone. */ public zone: string; /** ListZoneOperationsRequest _filter. */ public _filter?: "filter"; /** ListZoneOperationsRequest _maxResults. */ public _maxResults?: "maxResults"; /** ListZoneOperationsRequest _orderBy. */ public _orderBy?: "orderBy"; /** ListZoneOperationsRequest _pageToken. */ public _pageToken?: "pageToken"; /** ListZoneOperationsRequest _returnPartialSuccess. */ public _returnPartialSuccess?: "returnPartialSuccess"; /** * Creates a new ListZoneOperationsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListZoneOperationsRequest instance */ public static create(properties?: google.cloud.compute.v1.IListZoneOperationsRequest): google.cloud.compute.v1.ListZoneOperationsRequest; /** * Encodes the specified ListZoneOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.ListZoneOperationsRequest.verify|verify} messages. * @param message ListZoneOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IListZoneOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListZoneOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.ListZoneOperationsRequest.verify|verify} messages. * @param message ListZoneOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IListZoneOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListZoneOperationsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListZoneOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.ListZoneOperationsRequest; /** * Decodes a ListZoneOperationsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListZoneOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.ListZoneOperationsRequest; /** * Verifies a ListZoneOperationsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListZoneOperationsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListZoneOperationsRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.ListZoneOperationsRequest; /** * Creates a plain object from a ListZoneOperationsRequest message. Also converts values to other types if specified. * @param message ListZoneOperationsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.ListZoneOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListZoneOperationsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a WaitZoneOperationRequest. */ interface IWaitZoneOperationRequest { /** WaitZoneOperationRequest operation */ operation?: (string|null); /** WaitZoneOperationRequest project */ project?: (string|null); /** WaitZoneOperationRequest zone */ zone?: (string|null); } /** Represents a WaitZoneOperationRequest. */ class WaitZoneOperationRequest implements IWaitZoneOperationRequest { /** * Constructs a new WaitZoneOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IWaitZoneOperationRequest); /** WaitZoneOperationRequest operation. */ public operation: string; /** WaitZoneOperationRequest project. */ public project: string; /** WaitZoneOperationRequest zone. */ public zone: string; /** * Creates a new WaitZoneOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns WaitZoneOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IWaitZoneOperationRequest): google.cloud.compute.v1.WaitZoneOperationRequest; /** * Encodes the specified WaitZoneOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.WaitZoneOperationRequest.verify|verify} messages. * @param message WaitZoneOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IWaitZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified WaitZoneOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.WaitZoneOperationRequest.verify|verify} messages. * @param message WaitZoneOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IWaitZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a WaitZoneOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns WaitZoneOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.WaitZoneOperationRequest; /** * Decodes a WaitZoneOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns WaitZoneOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.WaitZoneOperationRequest; /** * Verifies a WaitZoneOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a WaitZoneOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns WaitZoneOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.WaitZoneOperationRequest; /** * Creates a plain object from a WaitZoneOperationRequest message. Also converts values to other types if specified. * @param message WaitZoneOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.WaitZoneOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this WaitZoneOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an AggregatedListGlobalOperationsRequest. */ interface IAggregatedListGlobalOperationsRequest { /** AggregatedListGlobalOperationsRequest filter */ filter?: (string|null); /** AggregatedListGlobalOperationsRequest includeAllScopes */ includeAllScopes?: (boolean|null); /** AggregatedListGlobalOperationsRequest maxResults */ maxResults?: (number|null); /** AggregatedListGlobalOperationsRequest orderBy */ orderBy?: (string|null); /** AggregatedListGlobalOperationsRequest pageToken */ pageToken?: (string|null); /** AggregatedListGlobalOperationsRequest project */ project?: (string|null); /** AggregatedListGlobalOperationsRequest returnPartialSuccess */ returnPartialSuccess?: (boolean|null); } /** Represents an AggregatedListGlobalOperationsRequest. */ class AggregatedListGlobalOperationsRequest implements IAggregatedListGlobalOperationsRequest { /** * Constructs a new AggregatedListGlobalOperationsRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest); /** AggregatedListGlobalOperationsRequest filter. */ public filter?: (string|null); /** AggregatedListGlobalOperationsRequest includeAllScopes. */ public includeAllScopes?: (boolean|null); /** AggregatedListGlobalOperationsRequest maxResults. */ public maxResults?: (number|null); /** AggregatedListGlobalOperationsRequest orderBy. */ public orderBy?: (string|null); /** AggregatedListGlobalOperationsRequest pageToken. */ public pageToken?: (string|null); /** AggregatedListGlobalOperationsRequest project. */ public project: string; /** AggregatedListGlobalOperationsRequest returnPartialSuccess. */ public returnPartialSuccess?: (boolean|null); /** AggregatedListGlobalOperationsRequest _filter. */ public _filter?: "filter"; /** AggregatedListGlobalOperationsRequest _includeAllScopes. */ public _includeAllScopes?: "includeAllScopes"; /** AggregatedListGlobalOperationsRequest _maxResults. */ public _maxResults?: "maxResults"; /** AggregatedListGlobalOperationsRequest _orderBy. */ public _orderBy?: "orderBy"; /** AggregatedListGlobalOperationsRequest _pageToken. */ public _pageToken?: "pageToken"; /** AggregatedListGlobalOperationsRequest _returnPartialSuccess. */ public _returnPartialSuccess?: "returnPartialSuccess"; /** * Creates a new AggregatedListGlobalOperationsRequest instance using the specified properties. * @param [properties] Properties to set * @returns AggregatedListGlobalOperationsRequest instance */ public static create(properties?: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest): google.cloud.compute.v1.AggregatedListGlobalOperationsRequest; /** * Encodes the specified AggregatedListGlobalOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.AggregatedListGlobalOperationsRequest.verify|verify} messages. * @param message AggregatedListGlobalOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified AggregatedListGlobalOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.AggregatedListGlobalOperationsRequest.verify|verify} messages. * @param message AggregatedListGlobalOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an AggregatedListGlobalOperationsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns AggregatedListGlobalOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.AggregatedListGlobalOperationsRequest; /** * Decodes an AggregatedListGlobalOperationsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns AggregatedListGlobalOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.AggregatedListGlobalOperationsRequest; /** * Verifies an AggregatedListGlobalOperationsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an AggregatedListGlobalOperationsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns AggregatedListGlobalOperationsRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.AggregatedListGlobalOperationsRequest; /** * Creates a plain object from an AggregatedListGlobalOperationsRequest message. Also converts values to other types if specified. * @param message AggregatedListGlobalOperationsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.AggregatedListGlobalOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this AggregatedListGlobalOperationsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteGlobalOperationRequest. */ interface IDeleteGlobalOperationRequest { /** DeleteGlobalOperationRequest operation */ operation?: (string|null); /** DeleteGlobalOperationRequest project */ project?: (string|null); } /** Represents a DeleteGlobalOperationRequest. */ class DeleteGlobalOperationRequest implements IDeleteGlobalOperationRequest { /** * Constructs a new DeleteGlobalOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IDeleteGlobalOperationRequest); /** DeleteGlobalOperationRequest operation. */ public operation: string; /** DeleteGlobalOperationRequest project. */ public project: string; /** * Creates a new DeleteGlobalOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns DeleteGlobalOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IDeleteGlobalOperationRequest): google.cloud.compute.v1.DeleteGlobalOperationRequest; /** * Encodes the specified DeleteGlobalOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOperationRequest.verify|verify} messages. * @param message DeleteGlobalOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IDeleteGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteGlobalOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOperationRequest.verify|verify} messages. * @param message DeleteGlobalOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IDeleteGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteGlobalOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteGlobalOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteGlobalOperationRequest; /** * Decodes a DeleteGlobalOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteGlobalOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteGlobalOperationRequest; /** * Verifies a DeleteGlobalOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteGlobalOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteGlobalOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteGlobalOperationRequest; /** * Creates a plain object from a DeleteGlobalOperationRequest message. Also converts values to other types if specified. * @param message DeleteGlobalOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.DeleteGlobalOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteGlobalOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteGlobalOperationResponse. */ interface IDeleteGlobalOperationResponse { } /** Represents a DeleteGlobalOperationResponse. */ class DeleteGlobalOperationResponse implements IDeleteGlobalOperationResponse { /** * Constructs a new DeleteGlobalOperationResponse. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IDeleteGlobalOperationResponse); /** * Creates a new DeleteGlobalOperationResponse instance using the specified properties. * @param [properties] Properties to set * @returns DeleteGlobalOperationResponse instance */ public static create(properties?: google.cloud.compute.v1.IDeleteGlobalOperationResponse): google.cloud.compute.v1.DeleteGlobalOperationResponse; /** * Encodes the specified DeleteGlobalOperationResponse message. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOperationResponse.verify|verify} messages. * @param message DeleteGlobalOperationResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IDeleteGlobalOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteGlobalOperationResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOperationResponse.verify|verify} messages. * @param message DeleteGlobalOperationResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IDeleteGlobalOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteGlobalOperationResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteGlobalOperationResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteGlobalOperationResponse; /** * Decodes a DeleteGlobalOperationResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteGlobalOperationResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteGlobalOperationResponse; /** * Verifies a DeleteGlobalOperationResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteGlobalOperationResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteGlobalOperationResponse */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteGlobalOperationResponse; /** * Creates a plain object from a DeleteGlobalOperationResponse message. Also converts values to other types if specified. * @param message DeleteGlobalOperationResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.DeleteGlobalOperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteGlobalOperationResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetGlobalOperationRequest. */ interface IGetGlobalOperationRequest { /** GetGlobalOperationRequest operation */ operation?: (string|null); /** GetGlobalOperationRequest project */ project?: (string|null); } /** Represents a GetGlobalOperationRequest. */ class GetGlobalOperationRequest implements IGetGlobalOperationRequest { /** * Constructs a new GetGlobalOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IGetGlobalOperationRequest); /** GetGlobalOperationRequest operation. */ public operation: string; /** GetGlobalOperationRequest project. */ public project: string; /** * Creates a new GetGlobalOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetGlobalOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IGetGlobalOperationRequest): google.cloud.compute.v1.GetGlobalOperationRequest; /** * Encodes the specified GetGlobalOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.GetGlobalOperationRequest.verify|verify} messages. * @param message GetGlobalOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IGetGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetGlobalOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.GetGlobalOperationRequest.verify|verify} messages. * @param message GetGlobalOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IGetGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetGlobalOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetGlobalOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.GetGlobalOperationRequest; /** * Decodes a GetGlobalOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetGlobalOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.GetGlobalOperationRequest; /** * Verifies a GetGlobalOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetGlobalOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetGlobalOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.GetGlobalOperationRequest; /** * Creates a plain object from a GetGlobalOperationRequest message. Also converts values to other types if specified. * @param message GetGlobalOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.GetGlobalOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetGlobalOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListGlobalOperationsRequest. */ interface IListGlobalOperationsRequest { /** ListGlobalOperationsRequest filter */ filter?: (string|null); /** ListGlobalOperationsRequest maxResults */ maxResults?: (number|null); /** ListGlobalOperationsRequest orderBy */ orderBy?: (string|null); /** ListGlobalOperationsRequest pageToken */ pageToken?: (string|null); /** ListGlobalOperationsRequest project */ project?: (string|null); /** ListGlobalOperationsRequest returnPartialSuccess */ returnPartialSuccess?: (boolean|null); } /** Represents a ListGlobalOperationsRequest. */ class ListGlobalOperationsRequest implements IListGlobalOperationsRequest { /** * Constructs a new ListGlobalOperationsRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IListGlobalOperationsRequest); /** ListGlobalOperationsRequest filter. */ public filter?: (string|null); /** ListGlobalOperationsRequest maxResults. */ public maxResults?: (number|null); /** ListGlobalOperationsRequest orderBy. */ public orderBy?: (string|null); /** ListGlobalOperationsRequest pageToken. */ public pageToken?: (string|null); /** ListGlobalOperationsRequest project. */ public project: string; /** ListGlobalOperationsRequest returnPartialSuccess. */ public returnPartialSuccess?: (boolean|null); /** ListGlobalOperationsRequest _filter. */ public _filter?: "filter"; /** ListGlobalOperationsRequest _maxResults. */ public _maxResults?: "maxResults"; /** ListGlobalOperationsRequest _orderBy. */ public _orderBy?: "orderBy"; /** ListGlobalOperationsRequest _pageToken. */ public _pageToken?: "pageToken"; /** ListGlobalOperationsRequest _returnPartialSuccess. */ public _returnPartialSuccess?: "returnPartialSuccess"; /** * Creates a new ListGlobalOperationsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListGlobalOperationsRequest instance */ public static create(properties?: google.cloud.compute.v1.IListGlobalOperationsRequest): google.cloud.compute.v1.ListGlobalOperationsRequest; /** * Encodes the specified ListGlobalOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.ListGlobalOperationsRequest.verify|verify} messages. * @param message ListGlobalOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IListGlobalOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListGlobalOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.ListGlobalOperationsRequest.verify|verify} messages. * @param message ListGlobalOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IListGlobalOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListGlobalOperationsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListGlobalOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.ListGlobalOperationsRequest; /** * Decodes a ListGlobalOperationsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListGlobalOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.ListGlobalOperationsRequest; /** * Verifies a ListGlobalOperationsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListGlobalOperationsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListGlobalOperationsRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.ListGlobalOperationsRequest; /** * Creates a plain object from a ListGlobalOperationsRequest message. Also converts values to other types if specified. * @param message ListGlobalOperationsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.ListGlobalOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListGlobalOperationsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a WaitGlobalOperationRequest. */ interface IWaitGlobalOperationRequest { /** WaitGlobalOperationRequest operation */ operation?: (string|null); /** WaitGlobalOperationRequest project */ project?: (string|null); } /** Represents a WaitGlobalOperationRequest. */ class WaitGlobalOperationRequest implements IWaitGlobalOperationRequest { /** * Constructs a new WaitGlobalOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IWaitGlobalOperationRequest); /** WaitGlobalOperationRequest operation. */ public operation: string; /** WaitGlobalOperationRequest project. */ public project: string; /** * Creates a new WaitGlobalOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns WaitGlobalOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IWaitGlobalOperationRequest): google.cloud.compute.v1.WaitGlobalOperationRequest; /** * Encodes the specified WaitGlobalOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.WaitGlobalOperationRequest.verify|verify} messages. * @param message WaitGlobalOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IWaitGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified WaitGlobalOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.WaitGlobalOperationRequest.verify|verify} messages. * @param message WaitGlobalOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IWaitGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a WaitGlobalOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns WaitGlobalOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.WaitGlobalOperationRequest; /** * Decodes a WaitGlobalOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns WaitGlobalOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.WaitGlobalOperationRequest; /** * Verifies a WaitGlobalOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a WaitGlobalOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns WaitGlobalOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.WaitGlobalOperationRequest; /** * Creates a plain object from a WaitGlobalOperationRequest message. Also converts values to other types if specified. * @param message WaitGlobalOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.WaitGlobalOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this WaitGlobalOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteGlobalOrganizationOperationRequest. */ interface IDeleteGlobalOrganizationOperationRequest { /** DeleteGlobalOrganizationOperationRequest operation */ operation?: (string|null); /** DeleteGlobalOrganizationOperationRequest parentId */ parentId?: (string|null); } /** Represents a DeleteGlobalOrganizationOperationRequest. */ class DeleteGlobalOrganizationOperationRequest implements IDeleteGlobalOrganizationOperationRequest { /** * Constructs a new DeleteGlobalOrganizationOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest); /** DeleteGlobalOrganizationOperationRequest operation. */ public operation: string; /** DeleteGlobalOrganizationOperationRequest parentId. */ public parentId?: (string|null); /** DeleteGlobalOrganizationOperationRequest _parentId. */ public _parentId?: "parentId"; /** * Creates a new DeleteGlobalOrganizationOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns DeleteGlobalOrganizationOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest): google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest; /** * Encodes the specified DeleteGlobalOrganizationOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest.verify|verify} messages. * @param message DeleteGlobalOrganizationOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteGlobalOrganizationOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest.verify|verify} messages. * @param message DeleteGlobalOrganizationOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteGlobalOrganizationOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteGlobalOrganizationOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest; /** * Decodes a DeleteGlobalOrganizationOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteGlobalOrganizationOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest; /** * Verifies a DeleteGlobalOrganizationOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteGlobalOrganizationOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteGlobalOrganizationOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest; /** * Creates a plain object from a DeleteGlobalOrganizationOperationRequest message. Also converts values to other types if specified. * @param message DeleteGlobalOrganizationOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteGlobalOrganizationOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteGlobalOrganizationOperationResponse. */ interface IDeleteGlobalOrganizationOperationResponse { } /** Represents a DeleteGlobalOrganizationOperationResponse. */ class DeleteGlobalOrganizationOperationResponse implements IDeleteGlobalOrganizationOperationResponse { /** * Constructs a new DeleteGlobalOrganizationOperationResponse. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationResponse); /** * Creates a new DeleteGlobalOrganizationOperationResponse instance using the specified properties. * @param [properties] Properties to set * @returns DeleteGlobalOrganizationOperationResponse instance */ public static create(properties?: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationResponse): google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse; /** * Encodes the specified DeleteGlobalOrganizationOperationResponse message. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse.verify|verify} messages. * @param message DeleteGlobalOrganizationOperationResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteGlobalOrganizationOperationResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse.verify|verify} messages. * @param message DeleteGlobalOrganizationOperationResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteGlobalOrganizationOperationResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteGlobalOrganizationOperationResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse; /** * Decodes a DeleteGlobalOrganizationOperationResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteGlobalOrganizationOperationResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse; /** * Verifies a DeleteGlobalOrganizationOperationResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteGlobalOrganizationOperationResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteGlobalOrganizationOperationResponse */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse; /** * Creates a plain object from a DeleteGlobalOrganizationOperationResponse message. Also converts values to other types if specified. * @param message DeleteGlobalOrganizationOperationResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteGlobalOrganizationOperationResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetGlobalOrganizationOperationRequest. */ interface IGetGlobalOrganizationOperationRequest { /** GetGlobalOrganizationOperationRequest operation */ operation?: (string|null); /** GetGlobalOrganizationOperationRequest parentId */ parentId?: (string|null); } /** Represents a GetGlobalOrganizationOperationRequest. */ class GetGlobalOrganizationOperationRequest implements IGetGlobalOrganizationOperationRequest { /** * Constructs a new GetGlobalOrganizationOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest); /** GetGlobalOrganizationOperationRequest operation. */ public operation: string; /** GetGlobalOrganizationOperationRequest parentId. */ public parentId?: (string|null); /** GetGlobalOrganizationOperationRequest _parentId. */ public _parentId?: "parentId"; /** * Creates a new GetGlobalOrganizationOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetGlobalOrganizationOperationRequest instance */ public static create(properties?: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest): google.cloud.compute.v1.GetGlobalOrganizationOperationRequest; /** * Encodes the specified GetGlobalOrganizationOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.GetGlobalOrganizationOperationRequest.verify|verify} messages. * @param message GetGlobalOrganizationOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetGlobalOrganizationOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.GetGlobalOrganizationOperationRequest.verify|verify} messages. * @param message GetGlobalOrganizationOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetGlobalOrganizationOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetGlobalOrganizationOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.GetGlobalOrganizationOperationRequest; /** * Decodes a GetGlobalOrganizationOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetGlobalOrganizationOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.GetGlobalOrganizationOperationRequest; /** * Verifies a GetGlobalOrganizationOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetGlobalOrganizationOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetGlobalOrganizationOperationRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.GetGlobalOrganizationOperationRequest; /** * Creates a plain object from a GetGlobalOrganizationOperationRequest message. Also converts values to other types if specified. * @param message GetGlobalOrganizationOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.GetGlobalOrganizationOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetGlobalOrganizationOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListGlobalOrganizationOperationsRequest. */ interface IListGlobalOrganizationOperationsRequest { /** ListGlobalOrganizationOperationsRequest filter */ filter?: (string|null); /** ListGlobalOrganizationOperationsRequest maxResults */ maxResults?: (number|null); /** ListGlobalOrganizationOperationsRequest orderBy */ orderBy?: (string|null); /** ListGlobalOrganizationOperationsRequest pageToken */ pageToken?: (string|null); /** ListGlobalOrganizationOperationsRequest parentId */ parentId?: (string|null); /** ListGlobalOrganizationOperationsRequest returnPartialSuccess */ returnPartialSuccess?: (boolean|null); } /** Represents a ListGlobalOrganizationOperationsRequest. */ class ListGlobalOrganizationOperationsRequest implements IListGlobalOrganizationOperationsRequest { /** * Constructs a new ListGlobalOrganizationOperationsRequest. * @param [properties] Properties to set */ constructor(properties?: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest); /** ListGlobalOrganizationOperationsRequest filter. */ public filter?: (string|null); /** ListGlobalOrganizationOperationsRequest maxResults. */ public maxResults?: (number|null); /** ListGlobalOrganizationOperationsRequest orderBy. */ public orderBy?: (string|null); /** ListGlobalOrganizationOperationsRequest pageToken. */ public pageToken?: (string|null); /** ListGlobalOrganizationOperationsRequest parentId. */ public parentId?: (string|null); /** ListGlobalOrganizationOperationsRequest returnPartialSuccess. */ public returnPartialSuccess?: (boolean|null); /** ListGlobalOrganizationOperationsRequest _filter. */ public _filter?: "filter"; /** ListGlobalOrganizationOperationsRequest _maxResults. */ public _maxResults?: "maxResults"; /** ListGlobalOrganizationOperationsRequest _orderBy. */ public _orderBy?: "orderBy"; /** ListGlobalOrganizationOperationsRequest _pageToken. */ public _pageToken?: "pageToken"; /** ListGlobalOrganizationOperationsRequest _parentId. */ public _parentId?: "parentId"; /** ListGlobalOrganizationOperationsRequest _returnPartialSuccess. */ public _returnPartialSuccess?: "returnPartialSuccess"; /** * Creates a new ListGlobalOrganizationOperationsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListGlobalOrganizationOperationsRequest instance */ public static create(properties?: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest): google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest; /** * Encodes the specified ListGlobalOrganizationOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest.verify|verify} messages. * @param message ListGlobalOrganizationOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListGlobalOrganizationOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest.verify|verify} messages. * @param message ListGlobalOrganizationOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListGlobalOrganizationOperationsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListGlobalOrganizationOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest; /** * Decodes a ListGlobalOrganizationOperationsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListGlobalOrganizationOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest; /** * Verifies a ListGlobalOrganizationOperationsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListGlobalOrganizationOperationsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListGlobalOrganizationOperationsRequest */ public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest; /** * Creates a plain object from a ListGlobalOrganizationOperationsRequest message. Also converts values to other types if specified. * @param message ListGlobalOrganizationOperationsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListGlobalOrganizationOperationsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Represents a RegionOperations */ class RegionOperations extends $protobuf.rpc.Service { /** * Constructs a new RegionOperations service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new RegionOperations service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): RegionOperations; /** * Calls Delete. * @param request DeleteRegionOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and DeleteRegionOperationResponse */ public delete(request: google.cloud.compute.v1.IDeleteRegionOperationRequest, callback: google.cloud.compute.v1.RegionOperations.DeleteCallback): void; /** * Calls Delete. * @param request DeleteRegionOperationRequest message or plain object * @returns Promise */ public delete(request: google.cloud.compute.v1.IDeleteRegionOperationRequest): Promise<google.cloud.compute.v1.DeleteRegionOperationResponse>; /** * Calls Get. * @param request GetRegionOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public get(request: google.cloud.compute.v1.IGetRegionOperationRequest, callback: google.cloud.compute.v1.RegionOperations.GetCallback): void; /** * Calls Get. * @param request GetRegionOperationRequest message or plain object * @returns Promise */ public get(request: google.cloud.compute.v1.IGetRegionOperationRequest): Promise<google.cloud.compute.v1.Operation>; /** * Calls List. * @param request ListRegionOperationsRequest message or plain object * @param callback Node-style callback called with the error, if any, and OperationList */ public list(request: google.cloud.compute.v1.IListRegionOperationsRequest, callback: google.cloud.compute.v1.RegionOperations.ListCallback): void; /** * Calls List. * @param request ListRegionOperationsRequest message or plain object * @returns Promise */ public list(request: google.cloud.compute.v1.IListRegionOperationsRequest): Promise<google.cloud.compute.v1.OperationList>; /** * Calls Wait. * @param request WaitRegionOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public wait(request: google.cloud.compute.v1.IWaitRegionOperationRequest, callback: google.cloud.compute.v1.RegionOperations.WaitCallback): void; /** * Calls Wait. * @param request WaitRegionOperationRequest message or plain object * @returns Promise */ public wait(request: google.cloud.compute.v1.IWaitRegionOperationRequest): Promise<google.cloud.compute.v1.Operation>; } namespace RegionOperations { /** * Callback as used by {@link google.cloud.compute.v1.RegionOperations#delete_}. * @param error Error, if any * @param [response] DeleteRegionOperationResponse */ type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1.DeleteRegionOperationResponse) => void; /** * Callback as used by {@link google.cloud.compute.v1.RegionOperations#get}. * @param error Error, if any * @param [response] Operation */ type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; /** * Callback as used by {@link google.cloud.compute.v1.RegionOperations#list}. * @param error Error, if any * @param [response] OperationList */ type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationList) => void; /** * Callback as used by {@link google.cloud.compute.v1.RegionOperations#wait}. * @param error Error, if any * @param [response] Operation */ type WaitCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; } /** Represents a ZoneOperations */ class ZoneOperations extends $protobuf.rpc.Service { /** * Constructs a new ZoneOperations service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new ZoneOperations service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): ZoneOperations; /** * Calls Delete. * @param request DeleteZoneOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and DeleteZoneOperationResponse */ public delete(request: google.cloud.compute.v1.IDeleteZoneOperationRequest, callback: google.cloud.compute.v1.ZoneOperations.DeleteCallback): void; /** * Calls Delete. * @param request DeleteZoneOperationRequest message or plain object * @returns Promise */ public delete(request: google.cloud.compute.v1.IDeleteZoneOperationRequest): Promise<google.cloud.compute.v1.DeleteZoneOperationResponse>; /** * Calls Get. * @param request GetZoneOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public get(request: google.cloud.compute.v1.IGetZoneOperationRequest, callback: google.cloud.compute.v1.ZoneOperations.GetCallback): void; /** * Calls Get. * @param request GetZoneOperationRequest message or plain object * @returns Promise */ public get(request: google.cloud.compute.v1.IGetZoneOperationRequest): Promise<google.cloud.compute.v1.Operation>; /** * Calls List. * @param request ListZoneOperationsRequest message or plain object * @param callback Node-style callback called with the error, if any, and OperationList */ public list(request: google.cloud.compute.v1.IListZoneOperationsRequest, callback: google.cloud.compute.v1.ZoneOperations.ListCallback): void; /** * Calls List. * @param request ListZoneOperationsRequest message or plain object * @returns Promise */ public list(request: google.cloud.compute.v1.IListZoneOperationsRequest): Promise<google.cloud.compute.v1.OperationList>; /** * Calls Wait. * @param request WaitZoneOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public wait(request: google.cloud.compute.v1.IWaitZoneOperationRequest, callback: google.cloud.compute.v1.ZoneOperations.WaitCallback): void; /** * Calls Wait. * @param request WaitZoneOperationRequest message or plain object * @returns Promise */ public wait(request: google.cloud.compute.v1.IWaitZoneOperationRequest): Promise<google.cloud.compute.v1.Operation>; } namespace ZoneOperations { /** * Callback as used by {@link google.cloud.compute.v1.ZoneOperations#delete_}. * @param error Error, if any * @param [response] DeleteZoneOperationResponse */ type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1.DeleteZoneOperationResponse) => void; /** * Callback as used by {@link google.cloud.compute.v1.ZoneOperations#get}. * @param error Error, if any * @param [response] Operation */ type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; /** * Callback as used by {@link google.cloud.compute.v1.ZoneOperations#list}. * @param error Error, if any * @param [response] OperationList */ type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationList) => void; /** * Callback as used by {@link google.cloud.compute.v1.ZoneOperations#wait}. * @param error Error, if any * @param [response] Operation */ type WaitCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; } /** Represents a GlobalOperations */ class GlobalOperations extends $protobuf.rpc.Service { /** * Constructs a new GlobalOperations service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new GlobalOperations service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): GlobalOperations; /** * Calls AggregatedList. * @param request AggregatedListGlobalOperationsRequest message or plain object * @param callback Node-style callback called with the error, if any, and OperationAggregatedList */ public aggregatedList(request: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest, callback: google.cloud.compute.v1.GlobalOperations.AggregatedListCallback): void; /** * Calls AggregatedList. * @param request AggregatedListGlobalOperationsRequest message or plain object * @returns Promise */ public aggregatedList(request: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest): Promise<google.cloud.compute.v1.OperationAggregatedList>; /** * Calls Delete. * @param request DeleteGlobalOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and DeleteGlobalOperationResponse */ public delete(request: google.cloud.compute.v1.IDeleteGlobalOperationRequest, callback: google.cloud.compute.v1.GlobalOperations.DeleteCallback): void; /** * Calls Delete. * @param request DeleteGlobalOperationRequest message or plain object * @returns Promise */ public delete(request: google.cloud.compute.v1.IDeleteGlobalOperationRequest): Promise<google.cloud.compute.v1.DeleteGlobalOperationResponse>; /** * Calls Get. * @param request GetGlobalOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public get(request: google.cloud.compute.v1.IGetGlobalOperationRequest, callback: google.cloud.compute.v1.GlobalOperations.GetCallback): void; /** * Calls Get. * @param request GetGlobalOperationRequest message or plain object * @returns Promise */ public get(request: google.cloud.compute.v1.IGetGlobalOperationRequest): Promise<google.cloud.compute.v1.Operation>; /** * Calls List. * @param request ListGlobalOperationsRequest message or plain object * @param callback Node-style callback called with the error, if any, and OperationList */ public list(request: google.cloud.compute.v1.IListGlobalOperationsRequest, callback: google.cloud.compute.v1.GlobalOperations.ListCallback): void; /** * Calls List. * @param request ListGlobalOperationsRequest message or plain object * @returns Promise */ public list(request: google.cloud.compute.v1.IListGlobalOperationsRequest): Promise<google.cloud.compute.v1.OperationList>; /** * Calls Wait. * @param request WaitGlobalOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public wait(request: google.cloud.compute.v1.IWaitGlobalOperationRequest, callback: google.cloud.compute.v1.GlobalOperations.WaitCallback): void; /** * Calls Wait. * @param request WaitGlobalOperationRequest message or plain object * @returns Promise */ public wait(request: google.cloud.compute.v1.IWaitGlobalOperationRequest): Promise<google.cloud.compute.v1.Operation>; } namespace GlobalOperations { /** * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#aggregatedList}. * @param error Error, if any * @param [response] OperationAggregatedList */ type AggregatedListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationAggregatedList) => void; /** * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#delete_}. * @param error Error, if any * @param [response] DeleteGlobalOperationResponse */ type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1.DeleteGlobalOperationResponse) => void; /** * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#get}. * @param error Error, if any * @param [response] Operation */ type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; /** * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#list}. * @param error Error, if any * @param [response] OperationList */ type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationList) => void; /** * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#wait}. * @param error Error, if any * @param [response] Operation */ type WaitCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; } /** Represents a GlobalOrganizationOperations */ class GlobalOrganizationOperations extends $protobuf.rpc.Service { /** * Constructs a new GlobalOrganizationOperations service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new GlobalOrganizationOperations service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): GlobalOrganizationOperations; /** * Calls Delete. * @param request DeleteGlobalOrganizationOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and DeleteGlobalOrganizationOperationResponse */ public delete(request: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest, callback: google.cloud.compute.v1.GlobalOrganizationOperations.DeleteCallback): void; /** * Calls Delete. * @param request DeleteGlobalOrganizationOperationRequest message or plain object * @returns Promise */ public delete(request: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest): Promise<google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse>; /** * Calls Get. * @param request GetGlobalOrganizationOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public get(request: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest, callback: google.cloud.compute.v1.GlobalOrganizationOperations.GetCallback): void; /** * Calls Get. * @param request GetGlobalOrganizationOperationRequest message or plain object * @returns Promise */ public get(request: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest): Promise<google.cloud.compute.v1.Operation>; /** * Calls List. * @param request ListGlobalOrganizationOperationsRequest message or plain object * @param callback Node-style callback called with the error, if any, and OperationList */ public list(request: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest, callback: google.cloud.compute.v1.GlobalOrganizationOperations.ListCallback): void; /** * Calls List. * @param request ListGlobalOrganizationOperationsRequest message or plain object * @returns Promise */ public list(request: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest): Promise<google.cloud.compute.v1.OperationList>; } namespace GlobalOrganizationOperations { /** * Callback as used by {@link google.cloud.compute.v1.GlobalOrganizationOperations#delete_}. * @param error Error, if any * @param [response] DeleteGlobalOrganizationOperationResponse */ type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse) => void; /** * Callback as used by {@link google.cloud.compute.v1.GlobalOrganizationOperations#get}. * @param error Error, if any * @param [response] Operation */ type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; /** * Callback as used by {@link google.cloud.compute.v1.GlobalOrganizationOperations#list}. * @param error Error, if any * @param [response] OperationList */ type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationList) => void; } } } } /** Namespace api. */ namespace api { /** Properties of a Http. */ interface IHttp { /** Http rules */ rules?: (google.api.IHttpRule[]|null); /** Http fullyDecodeReservedExpansion */ fullyDecodeReservedExpansion?: (boolean|null); } /** Represents a Http. */ class Http implements IHttp { /** * Constructs a new Http. * @param [properties] Properties to set */ constructor(properties?: google.api.IHttp); /** Http rules. */ public rules: google.api.IHttpRule[]; /** Http fullyDecodeReservedExpansion. */ public fullyDecodeReservedExpansion: boolean; /** * Creates a new Http instance using the specified properties. * @param [properties] Properties to set * @returns Http instance */ public static create(properties?: google.api.IHttp): google.api.Http; /** * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. * @param message Http message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. * @param message Http message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Http message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Http * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; /** * Decodes a Http message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Http * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; /** * Verifies a Http message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Http message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Http */ public static fromObject(object: { [k: string]: any }): google.api.Http; /** * Creates a plain object from a Http message. Also converts values to other types if specified. * @param message Http * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Http to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a HttpRule. */ interface IHttpRule { /** HttpRule selector */ selector?: (string|null); /** HttpRule get */ get?: (string|null); /** HttpRule put */ put?: (string|null); /** HttpRule post */ post?: (string|null); /** HttpRule delete */ "delete"?: (string|null); /** HttpRule patch */ patch?: (string|null); /** HttpRule custom */ custom?: (google.api.ICustomHttpPattern|null); /** HttpRule body */ body?: (string|null); /** HttpRule responseBody */ responseBody?: (string|null); /** HttpRule additionalBindings */ additionalBindings?: (google.api.IHttpRule[]|null); } /** Represents a HttpRule. */ class HttpRule implements IHttpRule { /** * Constructs a new HttpRule. * @param [properties] Properties to set */ constructor(properties?: google.api.IHttpRule); /** HttpRule selector. */ public selector: string; /** HttpRule get. */ public get?: (string|null); /** HttpRule put. */ public put?: (string|null); /** HttpRule post. */ public post?: (string|null); /** HttpRule delete. */ public delete?: (string|null); /** HttpRule patch. */ public patch?: (string|null); /** HttpRule custom. */ public custom?: (google.api.ICustomHttpPattern|null); /** HttpRule body. */ public body: string; /** HttpRule responseBody. */ public responseBody: string; /** HttpRule additionalBindings. */ public additionalBindings: google.api.IHttpRule[]; /** HttpRule pattern. */ public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); /** * Creates a new HttpRule instance using the specified properties. * @param [properties] Properties to set * @returns HttpRule instance */ public static create(properties?: google.api.IHttpRule): google.api.HttpRule; /** * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. * @param message HttpRule message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. * @param message HttpRule message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a HttpRule message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns HttpRule * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; /** * Decodes a HttpRule message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns HttpRule * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; /** * Verifies a HttpRule message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns HttpRule */ public static fromObject(object: { [k: string]: any }): google.api.HttpRule; /** * Creates a plain object from a HttpRule message. Also converts values to other types if specified. * @param message HttpRule * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this HttpRule to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CustomHttpPattern. */ interface ICustomHttpPattern { /** CustomHttpPattern kind */ kind?: (string|null); /** CustomHttpPattern path */ path?: (string|null); } /** Represents a CustomHttpPattern. */ class CustomHttpPattern implements ICustomHttpPattern { /** * Constructs a new CustomHttpPattern. * @param [properties] Properties to set */ constructor(properties?: google.api.ICustomHttpPattern); /** CustomHttpPattern kind. */ public kind: string; /** CustomHttpPattern path. */ public path: string; /** * Creates a new CustomHttpPattern instance using the specified properties. * @param [properties] Properties to set * @returns CustomHttpPattern instance */ public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; /** * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. * @param message CustomHttpPattern message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. * @param message CustomHttpPattern message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CustomHttpPattern message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CustomHttpPattern * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; /** * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CustomHttpPattern * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; /** * Verifies a CustomHttpPattern message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CustomHttpPattern */ public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; /** * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. * @param message CustomHttpPattern * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CustomHttpPattern to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace protobuf. */ namespace protobuf { /** Properties of a FileDescriptorSet. */ interface IFileDescriptorSet { /** FileDescriptorSet file */ file?: (google.protobuf.IFileDescriptorProto[]|null); } /** Represents a FileDescriptorSet. */ class FileDescriptorSet implements IFileDescriptorSet { /** * Constructs a new FileDescriptorSet. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFileDescriptorSet); /** FileDescriptorSet file. */ public file: google.protobuf.IFileDescriptorProto[]; /** * Creates a new FileDescriptorSet instance using the specified properties. * @param [properties] Properties to set * @returns FileDescriptorSet instance */ public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet; /** * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. * @param message FileDescriptorSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. * @param message FileDescriptorSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FileDescriptorSet message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FileDescriptorSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet; /** * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FileDescriptorSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet; /** * Verifies a FileDescriptorSet message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FileDescriptorSet */ public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; /** * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. * @param message FileDescriptorSet * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FileDescriptorSet to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FileDescriptorProto. */ interface IFileDescriptorProto { /** FileDescriptorProto name */ name?: (string|null); /** FileDescriptorProto package */ "package"?: (string|null); /** FileDescriptorProto dependency */ dependency?: (string[]|null); /** FileDescriptorProto publicDependency */ publicDependency?: (number[]|null); /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); /** FileDescriptorProto enumType */ enumType?: (google.protobuf.IEnumDescriptorProto[]|null); /** FileDescriptorProto service */ service?: (google.protobuf.IServiceDescriptorProto[]|null); /** FileDescriptorProto extension */ extension?: (google.protobuf.IFieldDescriptorProto[]|null); /** FileDescriptorProto options */ options?: (google.protobuf.IFileOptions|null); /** FileDescriptorProto sourceCodeInfo */ sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); /** FileDescriptorProto syntax */ syntax?: (string|null); } /** Represents a FileDescriptorProto. */ class FileDescriptorProto implements IFileDescriptorProto { /** * Constructs a new FileDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFileDescriptorProto); /** FileDescriptorProto name. */ public name: string; /** FileDescriptorProto package. */ public package: string; /** FileDescriptorProto dependency. */ public dependency: string[]; /** FileDescriptorProto publicDependency. */ public publicDependency: number[]; /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; /** FileDescriptorProto enumType. */ public enumType: google.protobuf.IEnumDescriptorProto[]; /** FileDescriptorProto service. */ public service: google.protobuf.IServiceDescriptorProto[]; /** FileDescriptorProto extension. */ public extension: google.protobuf.IFieldDescriptorProto[]; /** FileDescriptorProto options. */ public options?: (google.protobuf.IFileOptions|null); /** FileDescriptorProto sourceCodeInfo. */ public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); /** FileDescriptorProto syntax. */ public syntax: string; /** * Creates a new FileDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns FileDescriptorProto instance */ public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto; /** * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. * @param message FileDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. * @param message FileDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FileDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FileDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto; /** * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FileDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto; /** * Verifies a FileDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FileDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; /** * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. * @param message FileDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FileDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DescriptorProto. */ interface IDescriptorProto { /** DescriptorProto name */ name?: (string|null); /** DescriptorProto field */ field?: (google.protobuf.IFieldDescriptorProto[]|null); /** DescriptorProto extension */ extension?: (google.protobuf.IFieldDescriptorProto[]|null); /** DescriptorProto nestedType */ nestedType?: (google.protobuf.IDescriptorProto[]|null); /** DescriptorProto enumType */ enumType?: (google.protobuf.IEnumDescriptorProto[]|null); /** DescriptorProto extensionRange */ extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); /** DescriptorProto oneofDecl */ oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); /** DescriptorProto options */ options?: (google.protobuf.IMessageOptions|null); /** DescriptorProto reservedRange */ reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); /** DescriptorProto reservedName */ reservedName?: (string[]|null); } /** Represents a DescriptorProto. */ class DescriptorProto implements IDescriptorProto { /** * Constructs a new DescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IDescriptorProto); /** DescriptorProto name. */ public name: string; /** DescriptorProto field. */ public field: google.protobuf.IFieldDescriptorProto[]; /** DescriptorProto extension. */ public extension: google.protobuf.IFieldDescriptorProto[]; /** DescriptorProto nestedType. */ public nestedType: google.protobuf.IDescriptorProto[]; /** DescriptorProto enumType. */ public enumType: google.protobuf.IEnumDescriptorProto[]; /** DescriptorProto extensionRange. */ public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; /** DescriptorProto oneofDecl. */ public oneofDecl: google.protobuf.IOneofDescriptorProto[]; /** DescriptorProto options. */ public options?: (google.protobuf.IMessageOptions|null); /** DescriptorProto reservedRange. */ public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; /** DescriptorProto reservedName. */ public reservedName: string[]; /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns DescriptorProto instance */ public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto; /** * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. * @param message DescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. * @param message DescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto; /** * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto; /** * Verifies a DescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; /** * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. * @param message DescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace DescriptorProto { /** Properties of an ExtensionRange. */ interface IExtensionRange { /** ExtensionRange start */ start?: (number|null); /** ExtensionRange end */ end?: (number|null); /** ExtensionRange options */ options?: (google.protobuf.IExtensionRangeOptions|null); } /** Represents an ExtensionRange. */ class ExtensionRange implements IExtensionRange { /** * Constructs a new ExtensionRange. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); /** ExtensionRange start. */ public start: number; /** ExtensionRange end. */ public end: number; /** ExtensionRange options. */ public options?: (google.protobuf.IExtensionRangeOptions|null); /** * Creates a new ExtensionRange instance using the specified properties. * @param [properties] Properties to set * @returns ExtensionRange instance */ public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange; /** * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. * @param message ExtensionRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. * @param message ExtensionRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExtensionRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExtensionRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange; /** * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExtensionRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange; /** * Verifies an ExtensionRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExtensionRange */ public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; /** * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. * @param message ExtensionRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExtensionRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ReservedRange. */ interface IReservedRange { /** ReservedRange start */ start?: (number|null); /** ReservedRange end */ end?: (number|null); } /** Represents a ReservedRange. */ class ReservedRange implements IReservedRange { /** * Constructs a new ReservedRange. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); /** ReservedRange start. */ public start: number; /** ReservedRange end. */ public end: number; /** * Creates a new ReservedRange instance using the specified properties. * @param [properties] Properties to set * @returns ReservedRange instance */ public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange; /** * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. * @param message ReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. * @param message ReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReservedRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange; /** * Decodes a ReservedRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange; /** * Verifies a ReservedRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReservedRange */ public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; /** * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. * @param message ReservedRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of an ExtensionRangeOptions. */ interface IExtensionRangeOptions { /** ExtensionRangeOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an ExtensionRangeOptions. */ class ExtensionRangeOptions implements IExtensionRangeOptions { /** * Constructs a new ExtensionRangeOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IExtensionRangeOptions); /** ExtensionRangeOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new ExtensionRangeOptions instance using the specified properties. * @param [properties] Properties to set * @returns ExtensionRangeOptions instance */ public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions; /** * Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. * @param message ExtensionRangeOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. * @param message ExtensionRangeOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExtensionRangeOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExtensionRangeOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions; /** * Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExtensionRangeOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions; /** * Verifies an ExtensionRangeOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExtensionRangeOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; /** * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. * @param message ExtensionRangeOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExtensionRangeOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FieldDescriptorProto. */ interface IFieldDescriptorProto { /** FieldDescriptorProto name */ name?: (string|null); /** FieldDescriptorProto number */ number?: (number|null); /** FieldDescriptorProto label */ label?: (google.protobuf.FieldDescriptorProto.Label|null); /** FieldDescriptorProto type */ type?: (google.protobuf.FieldDescriptorProto.Type|null); /** FieldDescriptorProto typeName */ typeName?: (string|null); /** FieldDescriptorProto extendee */ extendee?: (string|null); /** FieldDescriptorProto defaultValue */ defaultValue?: (string|null); /** FieldDescriptorProto oneofIndex */ oneofIndex?: (number|null); /** FieldDescriptorProto jsonName */ jsonName?: (string|null); /** FieldDescriptorProto options */ options?: (google.protobuf.IFieldOptions|null); /** FieldDescriptorProto proto3Optional */ proto3Optional?: (boolean|null); } /** Represents a FieldDescriptorProto. */ class FieldDescriptorProto implements IFieldDescriptorProto { /** * Constructs a new FieldDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFieldDescriptorProto); /** FieldDescriptorProto name. */ public name: string; /** FieldDescriptorProto number. */ public number: number; /** FieldDescriptorProto label. */ public label: google.protobuf.FieldDescriptorProto.Label; /** FieldDescriptorProto type. */ public type: google.protobuf.FieldDescriptorProto.Type; /** FieldDescriptorProto typeName. */ public typeName: string; /** FieldDescriptorProto extendee. */ public extendee: string; /** FieldDescriptorProto defaultValue. */ public defaultValue: string; /** FieldDescriptorProto oneofIndex. */ public oneofIndex: number; /** FieldDescriptorProto jsonName. */ public jsonName: string; /** FieldDescriptorProto options. */ public options?: (google.protobuf.IFieldOptions|null); /** FieldDescriptorProto proto3Optional. */ public proto3Optional: boolean; /** * Creates a new FieldDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns FieldDescriptorProto instance */ public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto; /** * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. * @param message FieldDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. * @param message FieldDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FieldDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FieldDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto; /** * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FieldDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto; /** * Verifies a FieldDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FieldDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; /** * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. * @param message FieldDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FieldDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace FieldDescriptorProto { /** Type enum. */ enum Type { TYPE_DOUBLE = 1, TYPE_FLOAT = 2, TYPE_INT64 = 3, TYPE_UINT64 = 4, TYPE_INT32 = 5, TYPE_FIXED64 = 6, TYPE_FIXED32 = 7, TYPE_BOOL = 8, TYPE_STRING = 9, TYPE_GROUP = 10, TYPE_MESSAGE = 11, TYPE_BYTES = 12, TYPE_UINT32 = 13, TYPE_ENUM = 14, TYPE_SFIXED32 = 15, TYPE_SFIXED64 = 16, TYPE_SINT32 = 17, TYPE_SINT64 = 18 } /** Label enum. */ enum Label { LABEL_OPTIONAL = 1, LABEL_REQUIRED = 2, LABEL_REPEATED = 3 } } /** Properties of an OneofDescriptorProto. */ interface IOneofDescriptorProto { /** OneofDescriptorProto name */ name?: (string|null); /** OneofDescriptorProto options */ options?: (google.protobuf.IOneofOptions|null); } /** Represents an OneofDescriptorProto. */ class OneofDescriptorProto implements IOneofDescriptorProto { /** * Constructs a new OneofDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IOneofDescriptorProto); /** OneofDescriptorProto name. */ public name: string; /** OneofDescriptorProto options. */ public options?: (google.protobuf.IOneofOptions|null); /** * Creates a new OneofDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns OneofDescriptorProto instance */ public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto; /** * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. * @param message OneofDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. * @param message OneofDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OneofDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OneofDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto; /** * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OneofDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto; /** * Verifies an OneofDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OneofDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; /** * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. * @param message OneofDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OneofDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EnumDescriptorProto. */ interface IEnumDescriptorProto { /** EnumDescriptorProto name */ name?: (string|null); /** EnumDescriptorProto value */ value?: (google.protobuf.IEnumValueDescriptorProto[]|null); /** EnumDescriptorProto options */ options?: (google.protobuf.IEnumOptions|null); /** EnumDescriptorProto reservedRange */ reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); } /** Represents an EnumDescriptorProto. */ class EnumDescriptorProto implements IEnumDescriptorProto { /** * Constructs a new EnumDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumDescriptorProto); /** EnumDescriptorProto name. */ public name: string; /** EnumDescriptorProto value. */ public value: google.protobuf.IEnumValueDescriptorProto[]; /** EnumDescriptorProto options. */ public options?: (google.protobuf.IEnumOptions|null); /** EnumDescriptorProto reservedRange. */ public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; /** EnumDescriptorProto reservedName. */ public reservedName: string[]; /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns EnumDescriptorProto instance */ public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto; /** * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. * @param message EnumDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. * @param message EnumDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto; /** * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto; /** * Verifies an EnumDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; /** * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. * @param message EnumDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace EnumDescriptorProto { /** Properties of an EnumReservedRange. */ interface IEnumReservedRange { /** EnumReservedRange start */ start?: (number|null); /** EnumReservedRange end */ end?: (number|null); } /** Represents an EnumReservedRange. */ class EnumReservedRange implements IEnumReservedRange { /** * Constructs a new EnumReservedRange. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); /** EnumReservedRange start. */ public start: number; /** EnumReservedRange end. */ public end: number; /** * Creates a new EnumReservedRange instance using the specified properties. * @param [properties] Properties to set * @returns EnumReservedRange instance */ public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. * @param message EnumReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. * @param message EnumReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumReservedRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Decodes an EnumReservedRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Verifies an EnumReservedRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumReservedRange */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. * @param message EnumReservedRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of an EnumValueDescriptorProto. */ interface IEnumValueDescriptorProto { /** EnumValueDescriptorProto name */ name?: (string|null); /** EnumValueDescriptorProto number */ number?: (number|null); /** EnumValueDescriptorProto options */ options?: (google.protobuf.IEnumValueOptions|null); } /** Represents an EnumValueDescriptorProto. */ class EnumValueDescriptorProto implements IEnumValueDescriptorProto { /** * Constructs a new EnumValueDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumValueDescriptorProto); /** EnumValueDescriptorProto name. */ public name: string; /** EnumValueDescriptorProto number. */ public number: number; /** EnumValueDescriptorProto options. */ public options?: (google.protobuf.IEnumValueOptions|null); /** * Creates a new EnumValueDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns EnumValueDescriptorProto instance */ public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto; /** * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. * @param message EnumValueDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. * @param message EnumValueDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumValueDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto; /** * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumValueDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto; /** * Verifies an EnumValueDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumValueDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; /** * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. * @param message EnumValueDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumValueDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ServiceDescriptorProto. */ interface IServiceDescriptorProto { /** ServiceDescriptorProto name */ name?: (string|null); /** ServiceDescriptorProto method */ method?: (google.protobuf.IMethodDescriptorProto[]|null); /** ServiceDescriptorProto options */ options?: (google.protobuf.IServiceOptions|null); } /** Represents a ServiceDescriptorProto. */ class ServiceDescriptorProto implements IServiceDescriptorProto { /** * Constructs a new ServiceDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IServiceDescriptorProto); /** ServiceDescriptorProto name. */ public name: string; /** ServiceDescriptorProto method. */ public method: google.protobuf.IMethodDescriptorProto[]; /** ServiceDescriptorProto options. */ public options?: (google.protobuf.IServiceOptions|null); /** * Creates a new ServiceDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns ServiceDescriptorProto instance */ public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto; /** * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. * @param message ServiceDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. * @param message ServiceDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ServiceDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ServiceDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto; /** * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ServiceDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto; /** * Verifies a ServiceDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ServiceDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; /** * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. * @param message ServiceDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ServiceDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MethodDescriptorProto. */ interface IMethodDescriptorProto { /** MethodDescriptorProto name */ name?: (string|null); /** MethodDescriptorProto inputType */ inputType?: (string|null); /** MethodDescriptorProto outputType */ outputType?: (string|null); /** MethodDescriptorProto options */ options?: (google.protobuf.IMethodOptions|null); /** MethodDescriptorProto clientStreaming */ clientStreaming?: (boolean|null); /** MethodDescriptorProto serverStreaming */ serverStreaming?: (boolean|null); } /** Represents a MethodDescriptorProto. */ class MethodDescriptorProto implements IMethodDescriptorProto { /** * Constructs a new MethodDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IMethodDescriptorProto); /** MethodDescriptorProto name. */ public name: string; /** MethodDescriptorProto inputType. */ public inputType: string; /** MethodDescriptorProto outputType. */ public outputType: string; /** MethodDescriptorProto options. */ public options?: (google.protobuf.IMethodOptions|null); /** MethodDescriptorProto clientStreaming. */ public clientStreaming: boolean; /** MethodDescriptorProto serverStreaming. */ public serverStreaming: boolean; /** * Creates a new MethodDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns MethodDescriptorProto instance */ public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto; /** * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. * @param message MethodDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. * @param message MethodDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MethodDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MethodDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto; /** * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MethodDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto; /** * Verifies a MethodDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MethodDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; /** * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. * @param message MethodDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MethodDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FileOptions. */ interface IFileOptions { /** FileOptions javaPackage */ javaPackage?: (string|null); /** FileOptions javaOuterClassname */ javaOuterClassname?: (string|null); /** FileOptions javaMultipleFiles */ javaMultipleFiles?: (boolean|null); /** FileOptions javaGenerateEqualsAndHash */ javaGenerateEqualsAndHash?: (boolean|null); /** FileOptions javaStringCheckUtf8 */ javaStringCheckUtf8?: (boolean|null); /** FileOptions optimizeFor */ optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); /** FileOptions goPackage */ goPackage?: (string|null); /** FileOptions ccGenericServices */ ccGenericServices?: (boolean|null); /** FileOptions javaGenericServices */ javaGenericServices?: (boolean|null); /** FileOptions pyGenericServices */ pyGenericServices?: (boolean|null); /** FileOptions phpGenericServices */ phpGenericServices?: (boolean|null); /** FileOptions deprecated */ deprecated?: (boolean|null); /** FileOptions ccEnableArenas */ ccEnableArenas?: (boolean|null); /** FileOptions objcClassPrefix */ objcClassPrefix?: (string|null); /** FileOptions csharpNamespace */ csharpNamespace?: (string|null); /** FileOptions swiftPrefix */ swiftPrefix?: (string|null); /** FileOptions phpClassPrefix */ phpClassPrefix?: (string|null); /** FileOptions phpNamespace */ phpNamespace?: (string|null); /** FileOptions phpMetadataNamespace */ phpMetadataNamespace?: (string|null); /** FileOptions rubyPackage */ rubyPackage?: (string|null); /** FileOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents a FileOptions. */ class FileOptions implements IFileOptions { /** * Constructs a new FileOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFileOptions); /** FileOptions javaPackage. */ public javaPackage: string; /** FileOptions javaOuterClassname. */ public javaOuterClassname: string; /** FileOptions javaMultipleFiles. */ public javaMultipleFiles: boolean; /** FileOptions javaGenerateEqualsAndHash. */ public javaGenerateEqualsAndHash: boolean; /** FileOptions javaStringCheckUtf8. */ public javaStringCheckUtf8: boolean; /** FileOptions optimizeFor. */ public optimizeFor: google.protobuf.FileOptions.OptimizeMode; /** FileOptions goPackage. */ public goPackage: string; /** FileOptions ccGenericServices. */ public ccGenericServices: boolean; /** FileOptions javaGenericServices. */ public javaGenericServices: boolean; /** FileOptions pyGenericServices. */ public pyGenericServices: boolean; /** FileOptions phpGenericServices. */ public phpGenericServices: boolean; /** FileOptions deprecated. */ public deprecated: boolean; /** FileOptions ccEnableArenas. */ public ccEnableArenas: boolean; /** FileOptions objcClassPrefix. */ public objcClassPrefix: string; /** FileOptions csharpNamespace. */ public csharpNamespace: string; /** FileOptions swiftPrefix. */ public swiftPrefix: string; /** FileOptions phpClassPrefix. */ public phpClassPrefix: string; /** FileOptions phpNamespace. */ public phpNamespace: string; /** FileOptions phpMetadataNamespace. */ public phpMetadataNamespace: string; /** FileOptions rubyPackage. */ public rubyPackage: string; /** FileOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new FileOptions instance using the specified properties. * @param [properties] Properties to set * @returns FileOptions instance */ public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions; /** * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. * @param message FileOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. * @param message FileOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FileOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FileOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions; /** * Decodes a FileOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FileOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions; /** * Verifies a FileOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FileOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; /** * Creates a plain object from a FileOptions message. Also converts values to other types if specified. * @param message FileOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FileOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace FileOptions { /** OptimizeMode enum. */ enum OptimizeMode { SPEED = 1, CODE_SIZE = 2, LITE_RUNTIME = 3 } } /** Properties of a MessageOptions. */ interface IMessageOptions { /** MessageOptions messageSetWireFormat */ messageSetWireFormat?: (boolean|null); /** MessageOptions noStandardDescriptorAccessor */ noStandardDescriptorAccessor?: (boolean|null); /** MessageOptions deprecated */ deprecated?: (boolean|null); /** MessageOptions mapEntry */ mapEntry?: (boolean|null); /** MessageOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents a MessageOptions. */ class MessageOptions implements IMessageOptions { /** * Constructs a new MessageOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IMessageOptions); /** MessageOptions messageSetWireFormat. */ public messageSetWireFormat: boolean; /** MessageOptions noStandardDescriptorAccessor. */ public noStandardDescriptorAccessor: boolean; /** MessageOptions deprecated. */ public deprecated: boolean; /** MessageOptions mapEntry. */ public mapEntry: boolean; /** MessageOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new MessageOptions instance using the specified properties. * @param [properties] Properties to set * @returns MessageOptions instance */ public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions; /** * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. * @param message MessageOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. * @param message MessageOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MessageOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MessageOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions; /** * Decodes a MessageOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MessageOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions; /** * Verifies a MessageOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MessageOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; /** * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. * @param message MessageOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MessageOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FieldOptions. */ interface IFieldOptions { /** FieldOptions ctype */ ctype?: (google.protobuf.FieldOptions.CType|null); /** FieldOptions packed */ packed?: (boolean|null); /** FieldOptions jstype */ jstype?: (google.protobuf.FieldOptions.JSType|null); /** FieldOptions lazy */ lazy?: (boolean|null); /** FieldOptions deprecated */ deprecated?: (boolean|null); /** FieldOptions weak */ weak?: (boolean|null); /** FieldOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents a FieldOptions. */ class FieldOptions implements IFieldOptions { /** * Constructs a new FieldOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFieldOptions); /** FieldOptions ctype. */ public ctype: google.protobuf.FieldOptions.CType; /** FieldOptions packed. */ public packed: boolean; /** FieldOptions jstype. */ public jstype: google.protobuf.FieldOptions.JSType; /** FieldOptions lazy. */ public lazy: boolean; /** FieldOptions deprecated. */ public deprecated: boolean; /** FieldOptions weak. */ public weak: boolean; /** FieldOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new FieldOptions instance using the specified properties. * @param [properties] Properties to set * @returns FieldOptions instance */ public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions; /** * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. * @param message FieldOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. * @param message FieldOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FieldOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FieldOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions; /** * Decodes a FieldOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FieldOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions; /** * Verifies a FieldOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FieldOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; /** * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. * @param message FieldOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FieldOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace FieldOptions { /** CType enum. */ enum CType { STRING = 0, CORD = 1, STRING_PIECE = 2 } /** JSType enum. */ enum JSType { JS_NORMAL = 0, JS_STRING = 1, JS_NUMBER = 2 } } /** Properties of an OneofOptions. */ interface IOneofOptions { /** OneofOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an OneofOptions. */ class OneofOptions implements IOneofOptions { /** * Constructs a new OneofOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IOneofOptions); /** OneofOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new OneofOptions instance using the specified properties. * @param [properties] Properties to set * @returns OneofOptions instance */ public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions; /** * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. * @param message OneofOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. * @param message OneofOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OneofOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OneofOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions; /** * Decodes an OneofOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OneofOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions; /** * Verifies an OneofOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OneofOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; /** * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. * @param message OneofOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OneofOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EnumOptions. */ interface IEnumOptions { /** EnumOptions allowAlias */ allowAlias?: (boolean|null); /** EnumOptions deprecated */ deprecated?: (boolean|null); /** EnumOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an EnumOptions. */ class EnumOptions implements IEnumOptions { /** * Constructs a new EnumOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumOptions); /** EnumOptions allowAlias. */ public allowAlias: boolean; /** EnumOptions deprecated. */ public deprecated: boolean; /** EnumOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new EnumOptions instance using the specified properties. * @param [properties] Properties to set * @returns EnumOptions instance */ public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions; /** * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. * @param message EnumOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. * @param message EnumOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions; /** * Decodes an EnumOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions; /** * Verifies an EnumOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; /** * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. * @param message EnumOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EnumValueOptions. */ interface IEnumValueOptions { /** EnumValueOptions deprecated */ deprecated?: (boolean|null); /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an EnumValueOptions. */ class EnumValueOptions implements IEnumValueOptions { /** * Constructs a new EnumValueOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumValueOptions); /** EnumValueOptions deprecated. */ public deprecated: boolean; /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new EnumValueOptions instance using the specified properties. * @param [properties] Properties to set * @returns EnumValueOptions instance */ public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions; /** * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. * @param message EnumValueOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. * @param message EnumValueOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumValueOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumValueOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions; /** * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumValueOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions; /** * Verifies an EnumValueOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumValueOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; /** * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. * @param message EnumValueOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumValueOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ServiceOptions. */ interface IServiceOptions { /** ServiceOptions deprecated */ deprecated?: (boolean|null); /** ServiceOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents a ServiceOptions. */ class ServiceOptions implements IServiceOptions { /** * Constructs a new ServiceOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IServiceOptions); /** ServiceOptions deprecated. */ public deprecated: boolean; /** ServiceOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new ServiceOptions instance using the specified properties. * @param [properties] Properties to set * @returns ServiceOptions instance */ public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions; /** * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. * @param message ServiceOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. * @param message ServiceOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ServiceOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ServiceOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions; /** * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ServiceOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions; /** * Verifies a ServiceOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ServiceOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; /** * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. * @param message ServiceOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ServiceOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MethodOptions. */ interface IMethodOptions { /** MethodOptions deprecated */ deprecated?: (boolean|null); /** MethodOptions idempotencyLevel */ idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); /** MethodOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); /** MethodOptions .google.api.http */ ".google.api.http"?: (google.api.IHttpRule|null); } /** Represents a MethodOptions. */ class MethodOptions implements IMethodOptions { /** * Constructs a new MethodOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IMethodOptions); /** MethodOptions deprecated. */ public deprecated: boolean; /** MethodOptions idempotencyLevel. */ public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; /** MethodOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new MethodOptions instance using the specified properties. * @param [properties] Properties to set * @returns MethodOptions instance */ public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions; /** * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. * @param message MethodOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. * @param message MethodOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MethodOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MethodOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions; /** * Decodes a MethodOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MethodOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions; /** * Verifies a MethodOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MethodOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; /** * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. * @param message MethodOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MethodOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace MethodOptions { /** IdempotencyLevel enum. */ enum IdempotencyLevel { IDEMPOTENCY_UNKNOWN = 0, NO_SIDE_EFFECTS = 1, IDEMPOTENT = 2 } } /** Properties of an UninterpretedOption. */ interface IUninterpretedOption { /** UninterpretedOption name */ name?: (google.protobuf.UninterpretedOption.INamePart[]|null); /** UninterpretedOption identifierValue */ identifierValue?: (string|null); /** UninterpretedOption positiveIntValue */ positiveIntValue?: (number|Long|null); /** UninterpretedOption negativeIntValue */ negativeIntValue?: (number|Long|null); /** UninterpretedOption doubleValue */ doubleValue?: (number|null); /** UninterpretedOption stringValue */ stringValue?: (Uint8Array|null); /** UninterpretedOption aggregateValue */ aggregateValue?: (string|null); } /** Represents an UninterpretedOption. */ class UninterpretedOption implements IUninterpretedOption { /** * Constructs a new UninterpretedOption. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IUninterpretedOption); /** UninterpretedOption name. */ public name: google.protobuf.UninterpretedOption.INamePart[]; /** UninterpretedOption identifierValue. */ public identifierValue: string; /** UninterpretedOption positiveIntValue. */ public positiveIntValue: (number|Long); /** UninterpretedOption negativeIntValue. */ public negativeIntValue: (number|Long); /** UninterpretedOption doubleValue. */ public doubleValue: number; /** UninterpretedOption stringValue. */ public stringValue: Uint8Array; /** UninterpretedOption aggregateValue. */ public aggregateValue: string; /** * Creates a new UninterpretedOption instance using the specified properties. * @param [properties] Properties to set * @returns UninterpretedOption instance */ public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption; /** * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. * @param message UninterpretedOption message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. * @param message UninterpretedOption message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an UninterpretedOption message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UninterpretedOption * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption; /** * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UninterpretedOption * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption; /** * Verifies an UninterpretedOption message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UninterpretedOption */ public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; /** * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. * @param message UninterpretedOption * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UninterpretedOption to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace UninterpretedOption { /** Properties of a NamePart. */ interface INamePart { /** NamePart namePart */ namePart: string; /** NamePart isExtension */ isExtension: boolean; } /** Represents a NamePart. */ class NamePart implements INamePart { /** * Constructs a new NamePart. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.UninterpretedOption.INamePart); /** NamePart namePart. */ public namePart: string; /** NamePart isExtension. */ public isExtension: boolean; /** * Creates a new NamePart instance using the specified properties. * @param [properties] Properties to set * @returns NamePart instance */ public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart; /** * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. * @param message NamePart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. * @param message NamePart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a NamePart message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns NamePart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart; /** * Decodes a NamePart message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns NamePart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart; /** * Verifies a NamePart message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a NamePart message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns NamePart */ public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; /** * Creates a plain object from a NamePart message. Also converts values to other types if specified. * @param message NamePart * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this NamePart to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a SourceCodeInfo. */ interface ISourceCodeInfo { /** SourceCodeInfo location */ location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); } /** Represents a SourceCodeInfo. */ class SourceCodeInfo implements ISourceCodeInfo { /** * Constructs a new SourceCodeInfo. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.ISourceCodeInfo); /** SourceCodeInfo location. */ public location: google.protobuf.SourceCodeInfo.ILocation[]; /** * Creates a new SourceCodeInfo instance using the specified properties. * @param [properties] Properties to set * @returns SourceCodeInfo instance */ public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo; /** * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. * @param message SourceCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. * @param message SourceCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SourceCodeInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns SourceCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo; /** * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns SourceCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo; /** * Verifies a SourceCodeInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns SourceCodeInfo */ public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; /** * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. * @param message SourceCodeInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SourceCodeInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace SourceCodeInfo { /** Properties of a Location. */ interface ILocation { /** Location path */ path?: (number[]|null); /** Location span */ span?: (number[]|null); /** Location leadingComments */ leadingComments?: (string|null); /** Location trailingComments */ trailingComments?: (string|null); /** Location leadingDetachedComments */ leadingDetachedComments?: (string[]|null); } /** Represents a Location. */ class Location implements ILocation { /** * Constructs a new Location. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); /** Location path. */ public path: number[]; /** Location span. */ public span: number[]; /** Location leadingComments. */ public leadingComments: string; /** Location trailingComments. */ public trailingComments: string; /** Location leadingDetachedComments. */ public leadingDetachedComments: string[]; /** * Creates a new Location instance using the specified properties. * @param [properties] Properties to set * @returns Location instance */ public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location; /** * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. * @param message Location message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. * @param message Location message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Location message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Location * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location; /** * Decodes a Location message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Location * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location; /** * Verifies a Location message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Location message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Location */ public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; /** * Creates a plain object from a Location message. Also converts values to other types if specified. * @param message Location * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Location to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a GeneratedCodeInfo. */ interface IGeneratedCodeInfo { /** GeneratedCodeInfo annotation */ annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); } /** Represents a GeneratedCodeInfo. */ class GeneratedCodeInfo implements IGeneratedCodeInfo { /** * Constructs a new GeneratedCodeInfo. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IGeneratedCodeInfo); /** GeneratedCodeInfo annotation. */ public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; /** * Creates a new GeneratedCodeInfo instance using the specified properties. * @param [properties] Properties to set * @returns GeneratedCodeInfo instance */ public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo; /** * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. * @param message GeneratedCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. * @param message GeneratedCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GeneratedCodeInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GeneratedCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo; /** * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GeneratedCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo; /** * Verifies a GeneratedCodeInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GeneratedCodeInfo */ public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; /** * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. * @param message GeneratedCodeInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GeneratedCodeInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace GeneratedCodeInfo { /** Properties of an Annotation. */ interface IAnnotation { /** Annotation path */ path?: (number[]|null); /** Annotation sourceFile */ sourceFile?: (string|null); /** Annotation begin */ begin?: (number|null); /** Annotation end */ end?: (number|null); } /** Represents an Annotation. */ class Annotation implements IAnnotation { /** * Constructs a new Annotation. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); /** Annotation path. */ public path: number[]; /** Annotation sourceFile. */ public sourceFile: string; /** Annotation begin. */ public begin: number; /** Annotation end. */ public end: number; /** * Creates a new Annotation instance using the specified properties. * @param [properties] Properties to set * @returns Annotation instance */ public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation; /** * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. * @param message Annotation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. * @param message Annotation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Annotation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Annotation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation; /** * Decodes an Annotation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Annotation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation; /** * Verifies an Annotation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Annotation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Annotation */ public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; /** * Creates a plain object from an Annotation message. Also converts values to other types if specified. * @param message Annotation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Annotation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } }
the_stack
import React from 'react'; import ReactDOM from 'react-dom/server'; import { renderToStringWithData } from '@apollo/client/react/ssr'; import { getUserFromReq, computeContextFromUser, configureSentryScope } from '../apollo-server/context'; import { wrapWithMuiTheme } from '../../material-ui/themeProvider'; import { Vulcan } from '../../../lib/vulcan-lib/config'; import { createClient } from './apolloClient'; import { cachedPageRender, recordCacheBypass} from './pageCache'; import { getAllUserABTestGroups, CompleteTestGroupAllocation, RelevantTestGroupAllocation } from '../../../lib/abTestImpl'; import Head from './components/Head'; import { embedAsGlobalVar } from './renderUtil'; import AppGenerator from './components/AppGenerator'; import { captureException } from '@sentry/core'; import { randomId } from '../../../lib/random'; import { getPublicSettings, getPublicSettingsLoaded } from '../../../lib/settingsCache' import { getMergedStylesheet } from '../../styleGeneration'; import { ServerRequestStatusContextType } from '../../../lib/vulcan-core/appContext'; import { getCookieFromReq, getPathFromReq } from '../../utils/httpUtil'; import { isValidSerializedThemeOptions, defaultThemeOptions, ThemeOptions } from '../../../themes/themeNames'; import { DatabaseServerSetting } from '../../databaseSettings'; import type { Request, Response } from 'express'; import type { TimeOverride } from '../../../lib/utils/timeUtil'; const slowSSRWarnThresholdSetting = new DatabaseServerSetting<number>("slowSSRWarnThreshold", 3000); type RenderTimings = { totalTime: number prerenderTime: number renderTime: number } export type RenderResult = { ssrBody: string headers: Array<string> serializedApolloState: string jssSheets: string status: number|undefined, redirectUrl: string|undefined relevantAbTestGroups: RelevantTestGroupAllocation allAbTestGroups: CompleteTestGroupAllocation themeOptions: ThemeOptions, renderedAt: Date, timings: RenderTimings } export const renderWithCache = async (req: Request, res: Response) => { const startTime = new Date(); const user = await getUserFromReq(req); let ipOrIpArray = req.headers['x-forwarded-for'] || req.headers["x-real-ip"] || req.connection.remoteAddress || "unknown"; let ip: string = typeof ipOrIpArray==="object" ? (ipOrIpArray[0]) : (ipOrIpArray as string); if (ip.indexOf(",")>=0) ip = ip.split(",")[0]; const userAgent = req.headers["user-agent"]; // Inject a tab ID into the page, by injecting a script fragment that puts // it into a global variable. In previous versions of Vulcan this would've // been handled by InjectData, but InjectData didn't surive the 1.12 version // upgrade (it injects into the page template in a way that requires a // response object, which the onPageLoad/sink API doesn't offer). const tabId = randomId(); const tabIdHeader = `<script>var tabId = "${tabId}"</script>`; const url = getPathFromReq(req); const clientId = getCookieFromReq(req, "clientId"); if (!getPublicSettingsLoaded()) throw Error('Failed to render page because publicSettings have not yet been initialized on the server') const publicSettingsHeader = `<script> var publicSettings = ${JSON.stringify(getPublicSettings())}</script>` const ssrEventParams = { url: url, clientId, tabId, userAgent: userAgent, }; if (user) { // When logged in, don't use the page cache (logged-in pages have notifications and stuff) recordCacheBypass(); //eslint-disable-next-line no-console const rendered = await renderRequest({ req, user, startTime, res, clientId, }); Vulcan.captureEvent("ssr", { ...ssrEventParams, userId: user._id, timings: rendered.timings, cached: false, abTestGroups: rendered.allAbTestGroups, }); // eslint-disable-next-line no-console console.log(`Rendered ${url} for ${user.username}: ${printTimings(rendered.timings)}`); return { ...rendered, headers: [...rendered.headers, tabIdHeader, publicSettingsHeader], }; } else { const abTestGroups = getAllUserABTestGroups(user, clientId); const rendered = await cachedPageRender(req, abTestGroups, (req: Request) => renderRequest({ req, user: null, startTime, res, clientId, })); if (rendered.cached) { // eslint-disable-next-line no-console console.log(`Served ${url} from cache for logged out ${ip} (${userAgent})`); } else { // eslint-disable-next-line no-console console.log(`Rendered ${url} for logged out ${ip}: ${printTimings(rendered.timings)} (${userAgent})`); } Vulcan.captureEvent("ssr", { ...ssrEventParams, userId: null, timings: { totalTime: new Date().valueOf()-startTime.valueOf(), }, abTestGroups: rendered.relevantAbTestGroups, cached: rendered.cached, }); return { ...rendered, headers: [...rendered.headers, tabIdHeader, publicSettingsHeader], }; } }; export const renderRequest = async ({req, user, startTime, res, clientId}: { req: Request, user: DbUser|null, startTime: Date, res: Response, clientId: string, }): Promise<RenderResult> => { const requestContext = await computeContextFromUser(user, req, res); configureSentryScope(requestContext); // according to the Apollo doc, client needs to be recreated on every request // this avoids caching server side const client = await createClient(requestContext); // Used by callbacks to handle side effects // E.g storing the stylesheet generated by styled-components const context: any = {}; // Allows components to set statuscodes and redirects that will get executed on the server let serverRequestStatus: ServerRequestStatusContextType = {} // TODO: req object does not seem to have been processed by the Express // middlewares at this point // @see https://github.com/meteor/meteor-feature-requests/issues/174#issuecomment-441047495 // abTestGroups will be given as context for the render, which will modify it // (side effects) by filling in any A/B test groups that turned out to be // used for the rendering. (Any A/B test group that was *not* relevant to // the render will be omitted, which is the point.) let abTestGroups: RelevantTestGroupAllocation = {}; const now = new Date(); const timeOverride: TimeOverride = {currentTime: now}; const App = <AppGenerator req={req} apolloClient={client} serverRequestStatus={serverRequestStatus} abTestGroupsUsed={abTestGroups} timeOverride={timeOverride} />; const themeCookie = getCookieFromReq(req, "theme"); const themeOptionsFromCookie = themeCookie && isValidSerializedThemeOptions(themeCookie) ? themeCookie : null; const themeOptionsFromUser = (user?.theme && isValidSerializedThemeOptions(user.theme)) ? user.theme : null; const serializedThemeOptions = themeOptionsFromCookie || themeOptionsFromUser || defaultThemeOptions; const themeOptions: ThemeOptions = (typeof serializedThemeOptions==="string") ? JSON.parse(serializedThemeOptions) : serializedThemeOptions; const WrappedApp = wrapWithMuiTheme(App, context, themeOptions); let htmlContent = ''; try { htmlContent = await renderToStringWithData(WrappedApp); } catch(err) { console.error(`Error while fetching Apollo Data. date: ${new Date().toString()} url: ${JSON.stringify(getPathFromReq(req))}`); // eslint-disable-line no-console console.error(err); // eslint-disable-line no-console } const afterPrerenderTime = new Date(); // TODO: there should be a cleaner way to set this wrapper // id must always match the client side start.jsx file const ssrBody = `<div id="react-app">${htmlContent}</div>`; // add headers using helmet const head = ReactDOM.renderToString(<Head />); // add Apollo state, the client will then parse the string const initialState = client.extract(); const serializedApolloState = embedAsGlobalVar("__APOLLO_STATE__", initialState); // HACK: The sheets registry was created in wrapWithMuiTheme and added to the // context. const sheetsRegistry = context.sheetsRegistry; // Experimental handling to make default theme (dark mode or not) depend on // the user's system setting. Currently doesn't work because, while this does // successfully customize everything that goes through our merged stylesheet, // it can't handle the material-UI stuff that gets stuck into the page header. /*const defaultStylesheet = getMergedStylesheet({name: "default", siteThemeOverride: {}}); const darkStylesheet = getMergedStylesheet({name: "dark", siteThemeOverride: {}}); const jssSheets = `<style id="jss-server-side">${sheetsRegistry.toString()}</style>` +'<style id="jss-insertion-point"></style>' +'<style>' +`@import url("${defaultStylesheet.url}") screen and (prefers-color-scheme: light);\n` +`@import url("${darkStylesheet.url}") screen and (prefers-color-scheme: dark);\n` +'</style>'*/ const stylesheet = getMergedStylesheet(themeOptions); const jssSheets = `<style id="jss-server-side">${sheetsRegistry.toString()}</style>` +'<style id="jss-insertion-point"></style>' +`<link rel="stylesheet" onerror="window.missingMainStylesheet=true" href="${stylesheet.url}">` const finishedTime = new Date(); const timings: RenderTimings = { prerenderTime: afterPrerenderTime.valueOf() - startTime.valueOf(), renderTime: finishedTime.valueOf() - afterPrerenderTime.valueOf(), totalTime: finishedTime.valueOf() - startTime.valueOf() }; // eslint-disable-next-line no-console const slowSSRWarnThreshold = slowSSRWarnThresholdSetting.get(); if (timings.totalTime > slowSSRWarnThreshold) { captureException(new Error(`SSR time above ${slowSSRWarnThreshold}ms`), { extra: { url: getPathFromReq(req), ssrTime: timings.totalTime, } }); } return { ssrBody, headers: [head], serializedApolloState, jssSheets, status: serverRequestStatus.status, redirectUrl: serverRequestStatus.redirectUrl, relevantAbTestGroups: abTestGroups, allAbTestGroups: getAllUserABTestGroups(user, clientId), themeOptions: themeOptions, renderedAt: now, timings, }; } const printTimings = (timings: RenderTimings): string => { return `${timings.totalTime}ms (prerender: ${timings.prerenderTime}ms, render: ${timings.renderTime}ms)`; }
the_stack
import {console as Console} from 'global/console'; import {TRIP_POINT_FIELDS, SORT_ORDER} from 'constants/default-settings'; import {ascending, descending} from 'd3-array'; // import {validateInputData} from 'processors/data-processor'; import {generateHashId} from 'utils/utils'; import {getGpuFilterProps, getDatasetFieldIndexForFilter} from 'utils/gpu-filter-utils'; import { getFilterProps, getFilterRecord, diffFilters, getFilterFunction, filterDataByFilterTypes, getNumericFieldDomain, getTimestampFieldDomain, FilterResult } from 'utils/filter-utils'; import {maybeToDate, getSortingFunction} from 'utils/data-utils'; import { getQuantileDomain, getOrdinalDomain, getLogDomain, getLinearDomain } from 'utils/data-scale-utils'; import {ALL_FIELD_TYPES, SCALE_TYPES} from 'constants/default-settings'; import {createDataContainer} from './data-container-utils'; import {RGBColor} from 'reducers/types'; import {Layer} from 'layers'; import {FieldDomain, Filter} from 'reducers/vis-state-updaters'; import {DataContainerInterface} from './data-container-interface'; import {ProtoDataset} from 'actions'; export type Field = { analyzerType: string; id?: string; name: string; displayName: string; format: string; type: string; fieldIdx: number; valueAccessor(v: {index: number}): any; filterProps?: any; metadata?: any; }; export type GpuFilter = { filterRange: number[][]; filterValueUpdateTriggers: any; filterValueAccessor: ( dc: DataContainerInterface ) => ( getIndex?: (any) => number, getData?: (dc: DataContainerInterface, d: any, fieldIndex: number) => any ) => (d: any) => number; }; export type FieldPair = { defaultName: string; pair: { [key: string]: { fieldIdx: number; value: string; }; }; suffix: string[]; }; export type FilterRecord = { dynamicDomain: Filter[]; fixedDomain: Filter[]; cpu: Filter[]; gpu: Filter[]; }; export type FilterDatasetOpt = { // only allow cpu filtering cpuOnly?: boolean; // ignore filter for domain calculation ignoreDomain?: boolean; }; // Unique identifier of each field const FID_KEY = 'name'; class KeplerTable { readonly id: string; type?: string; label: string; color: RGBColor; // fields and data fields: Field[]; dataContainer: DataContainerInterface; allIndexes: number[]; filteredIndex: number[]; filteredIdxCPU?: number[]; filteredIndexForDomain: number[]; fieldPairs: FieldPair[]; gpuFilter: GpuFilter; filterRecord?: FilterRecord; filterRecordCPU?: FilterRecord; changedFilters?: any; // table-injected metadata sortColumn?: { // column name: sorted idx [key: string]: string; // ASCENDING | DESCENDING | UNSORT }; sortOrder?: number[] | null; pinnedColumns?: string[]; supportedFilterTypes: string[] | undefined; // table-injected metadata metadata: object; constructor({ info = {}, data, color, metadata, supportedFilterTypes }: { info?: ProtoDataset['info']; data: ProtoDataset['data']; color: RGBColor; metadata?: ProtoDataset['metadata']; supportedFilterTypes?: ProtoDataset['supportedFilterTypes']; }) { // TODO - what to do if validation fails? Can kepler handle exceptions? // const validatedData = validateInputData(data); // if (!validatedData) { // return this; // } // @ts-expect-error const dataContainer = createDataContainer(data.rows, {fields: data.fields}); const datasetInfo = { id: generateHashId(4), label: 'new dataset', ...(info || {}) }; const dataId = datasetInfo.id; // @ts-expect-error const fields: Field[] = data.fields.map((f, i) => ({ ...f, fieldIdx: i, id: f.name, displayName: f.displayName || f.name, // @ts-expect-error valueAccessor: maybeToDate.bind( null, // is time f.type === ALL_FIELD_TYPES.timestamp, i, f.format, dataContainer ) })); const allIndexes = dataContainer.getPlainIndex(); this.id = datasetInfo.id; this.label = datasetInfo.label; this.color = color; this.metadata = { ...metadata, id: datasetInfo.id, label: datasetInfo.label }; this.dataContainer = dataContainer; this.allIndexes = allIndexes; this.filteredIndex = allIndexes; this.filteredIndexForDomain = allIndexes; this.fieldPairs = findPointFieldPairs(fields); this.fields = fields; this.gpuFilter = getGpuFilterProps([], dataId, fields); if (supportedFilterTypes) { this.supportedFilterTypes = supportedFilterTypes; } } /** * Get field * @param columnName */ getColumnField(columnName: string): Field | undefined { const field = this.fields.find(fd => fd[FID_KEY] === columnName); this._assetField(columnName, field); return field; } /** * Get fieldIdx * @param columnName */ getColumnFieldIdx(columnName: string): number { const fieldIdx = this.fields.findIndex(fd => fd[FID_KEY] === columnName); this._assetField(columnName, Boolean(fieldIdx > -1)); return fieldIdx; } /** * Get the value of a cell */ getValue(columnName: string, rowIdx: number): any { const field = this.getColumnField(columnName); return field ? field.valueAccessor({index: rowIdx}) : null; } /** * Updates existing field with a new object * @param fieldIdx * @param newField */ updateColumnField(fieldIdx: number, newField: Field): void { this.fields = Object.assign([...this.fields], {[fieldIdx]: newField}); } /** * Update dataset color by custom color * @param newColor */ updateTableColor(newColor: RGBColor): void { this.color = newColor; } /** * Save filterProps to field and retrieve it * @param columnName */ getColumnFilterProps(columnName: string): Field['filterProps'] | null | undefined { const fieldIdx = this.getColumnFieldIdx(columnName); if (fieldIdx < 0) { return null; } const field = this.fields[fieldIdx]; if (field.hasOwnProperty('filterProps')) { return field.filterProps; } const fieldDomain = this.getColumnFilterDomain(field); if (!fieldDomain) { return null; } const filterProps = getFilterProps(field, fieldDomain); const newField = { ...field, filterProps }; this.updateColumnField(fieldIdx, newField); return filterProps; } /** * Apply filters to dataset, return the filtered dataset with updated `gpuFilter`, `filterRecord`, `filteredIndex`, `filteredIndexForDomain` * @param filters * @param layers * @param opt */ filterTable(filters: Filter[], layers: Layer[], opt?: FilterDatasetOpt): KeplerTable { const {dataContainer, id: dataId, filterRecord: oldFilterRecord, fields} = this; // if there is no filters const filterRecord = getFilterRecord(dataId, filters, opt || {}); this.filterRecord = filterRecord; this.gpuFilter = getGpuFilterProps(filters, dataId, fields); // const newDataset = set(['filterRecord'], filterRecord, dataset); if (!filters.length) { this.filteredIndex = this.allIndexes; this.filteredIndexForDomain = this.allIndexes; return this; } this.changedFilters = diffFilters(filterRecord, oldFilterRecord); // generate 2 sets of filter result // filteredIndex used to calculate layer data // filteredIndexForDomain used to calculate layer Domain const shouldCalDomain = Boolean(this.changedFilters.dynamicDomain); const shouldCalIndex = Boolean(this.changedFilters.cpu); let filterResult: FilterResult = {}; if (shouldCalDomain || shouldCalIndex) { const dynamicDomainFilters = shouldCalDomain ? filterRecord.dynamicDomain : null; const cpuFilters = shouldCalIndex ? filterRecord.cpu : null; const filterFuncs = filters.reduce((acc, filter) => { const fieldIndex = getDatasetFieldIndexForFilter(this.id, filter); const field = fieldIndex !== -1 ? fields[fieldIndex] : null; return { ...acc, [filter.id]: getFilterFunction(field, this.id, filter, layers, dataContainer) }; }, {}); filterResult = filterDataByFilterTypes( {dynamicDomainFilters, cpuFilters, filterFuncs}, dataContainer ); } this.filteredIndex = filterResult.filteredIndex || this.filteredIndex; this.filteredIndexForDomain = filterResult.filteredIndexForDomain || this.filteredIndexForDomain; return this; } /** * Apply filters to a dataset all on CPU, assign to `filteredIdxCPU`, `filterRecordCPU` * @param filters * @param layers */ filterTableCPU(filters: Filter[], layers: Layer[]): KeplerTable { const opt = { cpuOnly: true, ignoreDomain: true }; // no filter if (!filters.length) { this.filteredIdxCPU = this.allIndexes; this.filterRecordCPU = getFilterRecord(this.id, filters, opt); return this; } // no gpu filter if (!filters.find(f => f.gpu)) { this.filteredIdxCPU = this.filteredIndex; this.filterRecordCPU = getFilterRecord(this.id, filters, opt); return this; } // make a copy for cpu filtering const copied = copyTable(this); copied.filterRecord = this.filterRecordCPU; copied.filteredIndex = this.filteredIdxCPU || []; const filtered = copied.filterTable(filters, layers, opt); this.filteredIdxCPU = filtered.filteredIndex; this.filterRecordCPU = filtered.filterRecord; return this; } /** * Calculate field domain based on field type and data * for Filter */ getColumnFilterDomain(field: Field): FieldDomain { const {dataContainer} = this; const {valueAccessor} = field; let domain; switch (field.type) { case ALL_FIELD_TYPES.real: case ALL_FIELD_TYPES.integer: // calculate domain and step return getNumericFieldDomain(dataContainer, valueAccessor); case ALL_FIELD_TYPES.boolean: return {domain: [true, false]}; case ALL_FIELD_TYPES.string: case ALL_FIELD_TYPES.date: domain = getOrdinalDomain(dataContainer, valueAccessor); return {domain}; case ALL_FIELD_TYPES.timestamp: return getTimestampFieldDomain(dataContainer, valueAccessor); default: return {domain: getOrdinalDomain(dataContainer, valueAccessor)}; } } /** * Get the domain of this column based on scale type */ getColumnLayerDomain( field: Field, scaleType: string ): number[] | string[] | [number, number] | null { const {dataContainer, filteredIndexForDomain} = this; if (!SCALE_TYPES[scaleType]) { Console.error(`scale type ${scaleType} not supported`); return null; } const {valueAccessor} = field; const indexValueAccessor = i => valueAccessor({index: i}); const sortFunction = getSortingFunction(field.type); switch (scaleType) { case SCALE_TYPES.ordinal: case SCALE_TYPES.point: // do not recalculate ordinal domain based on filtered data // don't need to update ordinal domain every time return getOrdinalDomain(dataContainer, valueAccessor); case SCALE_TYPES.quantile: return getQuantileDomain(filteredIndexForDomain, indexValueAccessor, sortFunction); case SCALE_TYPES.log: return getLogDomain(filteredIndexForDomain, indexValueAccessor); case SCALE_TYPES.quantize: case SCALE_TYPES.linear: case SCALE_TYPES.sqrt: default: return getLinearDomain(filteredIndexForDomain, indexValueAccessor); } } /** * Get a sample of rows to calculate layer boundaries */ // getSampleData(rows) /** * Parse cell value based on column type and return a string representation * Value the field value, type the field type */ // parseFieldValue(value, type) // sortDatasetByColumn() /** * Assert whether field exist * @param fieldName * @param condition */ _assetField(fieldName: string, condition: any): void { if (!condition) { Console.error(`${fieldName} doesnt exist in dataset ${this.id}`); } } } // HELPER FUNCTIONS (MAINLY EXPORTED FOR TEST...) export function removeSuffixAndDelimiters(layerName, suffix) { return layerName .replace(new RegExp(suffix, 'ig'), '') .replace(/[_,.]+/g, ' ') .trim(); } /** * Find point fields pairs from fields * * @param fields * @returns found point fields */ export function findPointFieldPairs(fields: Field[]): FieldPair[] { const allNames = fields.map(f => f.name.toLowerCase()); // get list of all fields with matching suffixes const acc: FieldPair[] = []; return allNames.reduce((carry, fieldName, idx) => { // This search for pairs will early exit if found. for (const suffixPair of TRIP_POINT_FIELDS) { // match first suffix``` if (fieldName.endsWith(suffixPair[0])) { // match second suffix const otherPattern = new RegExp(`${suffixPair[0]}\$`); const partner = fieldName.replace(otherPattern, suffixPair[1]); const partnerIdx = allNames.findIndex(d => d === partner); if (partnerIdx > -1) { const defaultName = removeSuffixAndDelimiters(fieldName, suffixPair[0]); carry.push({ defaultName, pair: { lat: { fieldIdx: idx, value: fields[idx].name }, lng: { fieldIdx: partnerIdx, value: fields[partnerIdx].name } }, suffix: suffixPair }); return carry; } } } return carry; }, acc); } /** * * @param dataset * @param column * @param mode * @type */ export function sortDatasetByColumn( dataset: KeplerTable, column: string, mode?: string ): KeplerTable { const {allIndexes, fields, dataContainer} = dataset; const fieldIndex = fields.findIndex(f => f.name === column); if (fieldIndex < 0) { return dataset; } const sortBy = SORT_ORDER[mode || ''] || SORT_ORDER.ASCENDING; if (sortBy === SORT_ORDER.UNSORT) { dataset.sortColumn = {}; dataset.sortOrder = null; return dataset; } const sortFunction = sortBy === SORT_ORDER.ASCENDING ? ascending : descending; const sortOrder = allIndexes .slice() .sort((a, b) => sortFunction(dataContainer.valueAt(a, fieldIndex), dataContainer.valueAt(b, fieldIndex)) ); dataset.sortColumn = { [column]: sortBy }; dataset.sortOrder = sortOrder; return dataset; } export function pinTableColumns(dataset: KeplerTable, column: string): KeplerTable { const field = dataset.getColumnField(column); if (!field) { return dataset; } let pinnedColumns; if (Array.isArray(dataset.pinnedColumns) && dataset.pinnedColumns.includes(field.name)) { // unpin it pinnedColumns = dataset.pinnedColumns.filter(co => co !== field.name); } else { pinnedColumns = (dataset.pinnedColumns || []).concat(field.name); } // @ts-ignore return copyTableAndUpdate(dataset, {pinnedColumns}); } export function copyTable<T extends {}>(original: T): T { return Object.assign(Object.create(Object.getPrototypeOf(original)), original); } /** * @type * @returns */ export function copyTableAndUpdate<T extends {}>(original: T, options: Partial<T> = {}): T { return Object.entries(options).reduce((acc, entry) => { acc[entry[0]] = entry[1]; return acc; }, copyTable(original)); } export default KeplerTable;
the_stack
import * as vscode from 'vscode'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import * as fs from 'fs-extra'; import * as path from 'path'; import { TektonYamlType, tektonYaml, pipelineYaml, pipelineRunYaml, DeclaredTask } from '../../src/yaml-support/tkn-yaml'; const expect = chai.expect; chai.use(sinonChai); suite('Tekton yaml', () => { suite('Tekton detection', () => { test('Should detect Pipeline', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters spec: params: - name: context type: string description: Path to context default: /some/where/or/other tasks: - name: build-skaffold-web taskRef: name: build-push params: - name: pathToDockerFile value: Dockerfile - name: pathToContext value: "$(params.context)" ` const tknType = tektonYaml.isTektonYaml({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///foo/bar.yaml') } as vscode.TextDocument); expect(tknType).is.not.undefined; expect(tknType).to.equals(TektonYamlType.Pipeline); }); test('Should not detect if kind not Pipeline', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: PipeFoo metadata: name: pipeline-with-parameters spec: params: - name: context type: string description: Path to context default: /some/where/or/other tasks: - name: build-skaffold-web taskRef: name: build-push params: - name: pathToDockerFile value: Dockerfile - name: pathToContext value: "$(params.context)" ` const tknType = tektonYaml.isTektonYaml({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///foo/NotBar.yaml') } as vscode.TextDocument); expect(tknType).is.undefined; }); test('"getTektonDocuments" should provide documents by type (Pipeline)', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/multitype.yaml')); const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 1, uri: vscode.Uri.parse('file:///foo/multitype.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); expect(docs).is.not.undefined; expect(docs).not.empty; expect(docs.length).be.equal(1); }); test('"getTektonDocuments" should provide documents by type (PipelineResource)', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/multitype.yaml')); const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///foo/multitype.yaml') } as vscode.TextDocument, TektonYamlType.PipelineResource); expect(docs).is.not.undefined; expect(docs).not.empty; expect(docs.length).be.equal(4); }); test('"getTektonDocuments" should return empty if no type match', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/multitype.yaml')); const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///foo/multitype.yaml') } as vscode.TextDocument, TektonYamlType.PipelineRun); expect(docs).is.not.undefined; expect(docs).is.empty; }); test('"getTektonDocuments" should return undefined if yaml', () => { const docs = tektonYaml.getTektonDocuments({ getText: () => 'Some string', version: 2, uri: vscode.Uri.parse('file:///foo/multitype.yaml') } as vscode.TextDocument, TektonYamlType.PipelineRun); expect(docs).is.not.undefined; expect(docs).is.empty; }); test('"getMetadataName" should return name', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters `; const docs = tektonYaml.getTektonDocuments({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///name/pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const name = tektonYaml.getMetadataName(docs[0]); expect(name).to.be.equal('pipeline-with-parameters'); }); test('"getPipelineTasks" should return tasks description', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters spec: tasks: - name: build-skaffold-web taskRef: name: build-push params: - name: pathToDockerFile value: Dockerfile - name: pathToContext value: "$(params.context)" runAfter: - fooTask ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///tasks/pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); expect(tasks).is.not.empty; const task = tasks[0]; expect(task.kind).to.equal('Task'); expect(task.name).equal('build-skaffold-web'); expect(task.taskRef).equal('build-push'); expect(task.runAfter).to.eql(['fooTask']); }); test('"getPipelineTasks" should return tasks runAfter with array', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters spec: tasks: - name: build-skaffold-web taskRef: name: build-push runAfter: ["git-clone"] ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///tasks/pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); expect(tasks).is.not.empty; const task = tasks[0]; expect(task.kind).to.equal('Task'); expect(task.name).equal('build-skaffold-web'); expect(task.taskRef).equal('build-push'); expect(task.runAfter[0]).to.equal('fooTask'); }); test('"getPipelineTasks" should return "from" statement', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/pipeline-ordering.yaml')); const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///ordering/multitype.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); const task = tasks.find(t => t.name === 'deploy-web'); expect(task.runAfter).eql(['build-skaffold-web']); }); test('"getPipelineTasks" should return "from" statement from conditions', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/conditional-pipeline.yaml')); const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///ordering/conditional-pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); const task = tasks.find(t => t.name === 'then-check'); expect(task.runAfter).eql(['file-exists']); const condition = tasks.find(t => t.name === 'file-exists'); expect(condition.runAfter).eql(['first-create-file']); }); }); suite('Tekton tasks detections', () => { test('should return Tekton tasks ref names', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters spec: tasks: - name: build-skaffold-web taskRef: name: build-push params: - name: pathToDockerFile value: Dockerfile - name: pathToContext value: "$(params.context)" ` const pipelineTasks = pipelineYaml.getPipelineTasksRefName({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///foo/pipeline/tasks.yaml') } as vscode.TextDocument); expect(pipelineTasks).is.not.empty; expect(pipelineTasks).to.eql(['build-push']); }); test('should return empty array if no tasks defined', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters spec: tasks: ` const pipelineTasks = pipelineYaml.getPipelineTasksRefName({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///foo/pipeline/empty/tasks.yaml') } as vscode.TextDocument); expect(pipelineTasks).is.empty; }); test('should return tekton pipeline tasks names', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters spec: tasks: - name: build-skaffold-web taskRef: name: build-push params: - name: pathToDockerFile value: Dockerfile - name: pathToContext value: "$(params.context)" ` const pipelineTasks = pipelineYaml.getPipelineTasksName({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///foo/pipeline/tasks.yaml') } as vscode.TextDocument); expect(pipelineTasks).is.not.empty; expect(pipelineTasks).to.eql(['build-skaffold-web']); }); test('should detect taskSpec tasks', ()=> { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-when spec: tasks: - name: build-skaffold-web taskSpec: steps: - name: echo image: ubuntu script: exit 1 ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///pipeline/task-spec-pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); expect(tasks).is.not.empty; const task = tasks.find(t => t.name === 'build-skaffold-web'); expect(task.kind).eq('TaskSpec'); }); test('should add steps name for taskSpec tasks', ()=> { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-when spec: tasks: - name: build-skaffold-web taskSpec: steps: - name: echo image: ubuntu script: exit 1 ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///pipeline/task-spec-pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); expect(tasks).is.not.empty; const task = tasks.find(t => t.name === 'build-skaffold-web'); expect(task.kind).eq('TaskSpec'); expect(task.steps).deep.eq([{name: 'echo'}]); }); }); suite('Tekton Declared resource detection', () => { test('Should return declared pipeline resources', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: build-and-deploy spec: resources: - name: api-repo type: git - name: api-image type: image tasks: - name: build-api taskRef: name: buildah kind: ClusterTask resources: inputs: - name: source resource: api-repo outputs: - name: image resource: api-image params: - name: TLSVERIFY value: "false" `; const pipelineResources = pipelineYaml.getDeclaredResources({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///foo/pipeline/resources.yaml') } as vscode.TextDocument); expect(pipelineResources).is.not.empty; expect(pipelineResources).to.eql([{ name: 'api-repo', type: 'git' }, { name: 'api-image', type: 'image' }]); }); test('"findTask" should return undefined if no task defined', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/pipeline-ordering.yaml')); const result = pipelineYaml.findTask({ getText: () => yaml.toString(), version: 1, uri: vscode.Uri.parse('file:///ordering/findTask.yaml') } as vscode.TextDocument, new vscode.Position(11, 19)); expect(result).is.undefined; }); test('"findTask" should return taskId when position in task name', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/pipeline-ordering.yaml')); const result = pipelineYaml.findTask({ getText: () => yaml.toString(), version: 1, uri: vscode.Uri.parse('file:///ordering/findTask.yaml') } as vscode.TextDocument, new vscode.Position(20, 10)); expect(result).equal('build-skaffold-web'); }); test('"findTask" should return taskId when position in task body', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/pipeline-ordering.yaml')); const result = pipelineYaml.findTask({ getText: () => yaml.toString(), version: 1, uri: vscode.Uri.parse('file:///ordering/findTask.yaml') } as vscode.TextDocument, new vscode.Position(17, 10)); expect(result).equal('skaffold-unit-tests'); }); test('"findTask" should return condition when position in condition body', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/conditional-pipeline.yaml')); const result = pipelineYaml.findTask({ getText: () => yaml.toString(), version: 1, uri: vscode.Uri.parse('file:///ordering/conditional-findTask.yaml') } as vscode.TextDocument, new vscode.Position(24, 25)); expect(result).equal('file-exists'); }); test('task should have other task in runAfter if task use output value from other task', async ()=> { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters spec: tasks: - name: foo-task taskRef: name: build - name: build-skaffold-web taskRef: name: build-push params: - name: pathToDockerFile value: Dockerfile - name: pathToContext value: "$(tasks.foo-task.results.product)" ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///tasks/with/variables/pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); expect(tasks).is.not.empty; const task = tasks.find(t => t.name === 'build-skaffold-web'); expect(task.runAfter).to.be.deep.equal(['foo-task']); }); }); suite('PipelineRun', () => { test('should return pipelinerun name', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/pipelinerun.yaml')); const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 1, uri: vscode.Uri.parse('file:///pipelinerun/pipelinerun.yaml') } as vscode.TextDocument, TektonYamlType.PipelineRun); const result = pipelineRunYaml.getPipelineRunName(docs[0]); expect(result).eql('nodejs-ex-git-twbd85-nlhww'); }); test('should return pipelinerun state', async () => { const yaml = await fs.readFile(path.join(__dirname, '..', '..', '..', 'test', '/yaml-support/pipelinerun.yaml')); const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 1, uri: vscode.Uri.parse('file:///pipelinerun/pipelinerun.yaml') } as vscode.TextDocument, TektonYamlType.PipelineRun); const result = pipelineRunYaml.getPipelineRunStatus(docs[0]); expect(result).eql('Failed'); }); test('should collect tasks from PipelineSpec', async () => { const yaml = ` apiVersion: tekton.dev/v1beta1 kind: PipelineRun metadata: name: pipelinerun-with-taskspec-to-echo-good-morning spec: pipelineSpec: tasks: - name: echo-good-morning taskSpec: metadata: labels: app: "example" steps: - name: echo image: ubuntu script: | #!/usr/bin/env bash echo "Good Morning!" `; const docs = tektonYaml.getTektonDocuments({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///pipelinespec/pipeline.yaml') } as vscode.TextDocument, TektonYamlType.PipelineRun); const result = pipelineRunYaml.getTektonPipelineRefOrSpec(docs[0]); expect(result).to.be.an('array'); expect((result[0] as DeclaredTask).name).to.be.equal('echo-good-morning'); }); test('getPipelineRunName should return undefined if task is not started', ()=> { const yaml = ` apiVersion: tekton.dev/v1beta1 kind: PipelineRun metadata: name: pipelinerun-with-taskspec-to-echo-good-morning spec: pipelineSpec: tasks: - name: echo-good-morning taskSpec: metadata: labels: app: "example" steps: - name: echo image: ubuntu script: | #!/usr/bin/env bash echo "Good Morning!" `; const docs = tektonYaml.getTektonDocuments({ getText: () => yaml, version: 2, uri: vscode.Uri.parse('file:///pipelinespec/pipeline.yaml') } as vscode.TextDocument, TektonYamlType.PipelineRun); const result = pipelineRunYaml.getPipelineRunName(docs[0]); expect(result).to.be.an('undefined'); }); }); suite('Finally tasks', () => { test('Should return finally tasks', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters spec: tasks: - name: build-skaffold-web taskRef: name: build-push finally: - name: final-ask taskRef: name: build-push ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///foo/pipeline/finally/tasks.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const pipelineTasks = pipelineYaml.getPipelineTasks(docs[0]); expect(pipelineTasks).is.not.empty; expect(pipelineTasks[1].name).equal('final-ask'); expect(pipelineTasks[1].runAfter).eql(['build-skaffold-web']); }); test('should set runAfter for finally tasks after last tasks', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-parameters spec: tasks: - name: build-skaffold-web taskRef: name: build-push - name: sub-task taskRef: name: build-push runAfter: ["build-skaffold-web"] - name: build-server taskRef: name: build-push finally: - name: final-task taskRef: name: build-push ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml, version: 1, uri: vscode.Uri.parse('file:///foo/pipeline/finally/several-tasks.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const pipelineTasks = pipelineYaml.getPipelineTasks(docs[0]); expect(pipelineTasks).is.not.empty; const finalTask = pipelineTasks.find(t => t.name === 'final-task'); expect(finalTask.runAfter).eql(['sub-task', 'build-server']); }); }); suite('When tasks', () => { test('should add when in to graph', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-when spec: tasks: - name: build-skaffold-web taskRef: name: build-push when: - input: "$(params.path)" operator: in values: ["README.md"] ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///pipeline/when-pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); expect(tasks).is.not.empty; const whenTask = tasks.find(t => t.id === 'build-skaffold-web:$(params.path)'); expect(whenTask).not.undefined; }); test('should add when to run after of task', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-when spec: tasks: - name: build-skaffold-web taskRef: name: build-push when: - input: "$(params.path)" operator: in values: ["README.md"] ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///pipeline/when-pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); expect(tasks).is.not.empty; const whenTask = tasks.find(t => t.id === 'build-skaffold-web:$(params.path)'); expect(whenTask).not.undefined; const buildTask = tasks.find(t => t.name === 'build-skaffold-web'); expect(buildTask.runAfter).contains('build-skaffold-web:$(params.path)'); }); test('should add when to run after of task with result ordering', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-when spec: tasks: - name: multiply-inputs taskRef: name: multiply params: - name: a value: "$(params.a)" - name: b value: "$(params.b)" - name: build taskRef: name: build-push when: - input: "$(tasks.multiply-inputs.results.product)" operator: in values: ["README.md"] ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///pipeline/when-pipeline-result.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); expect(tasks).is.not.empty; const whenTask = tasks.find(t => t.id === 'build:$(tasks.multiply-inputs.results.product)'); expect(whenTask.runAfter).contains('multiply-inputs'); }); test('should add when to run after of task with multiple result ordering', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-when spec: tasks: - name: multiply-inputs taskRef: name: multiply params: - name: a value: "$(params.a)" - name: b value: "$(params.b)" - name: build taskRef: name: build-push when: - input: "$(tasks.multiply-inputs.results.product)$(tasks.sum-inputs.results.sum)" operator: in values: ["README.md"] ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///pipeline/when-pipeline-multiple-result.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); expect(tasks).is.not.empty; const whenTask = tasks.find(t => t.id === 'build:$(tasks.multiply-inputs.results.product)$(tasks.sum-inputs.results.sum)'); expect(whenTask.runAfter).contains('multiply-inputs', 'sum-inputs'); }); test('should add runAfter to when instead of task itself', () => { const yaml = ` apiVersion: tekton.dev/v1alpha1 kind: Pipeline metadata: name: pipeline-with-when spec: tasks: - name: multiply-inputs taskRef: name: multiply - name: some taskRef: name: add - name: build taskRef: name: build-push when: - input: "$(tasks.multiply-inputs.results.product)" operator: in values: ["README.md"] runAfter: ["some"] ` const docs = tektonYaml.getTektonDocuments({ getText: () => yaml.toString(), version: 2, uri: vscode.Uri.parse('file:///pipeline/when-and-runAfter-pipeline.yaml') } as vscode.TextDocument, TektonYamlType.Pipeline); const tasks = pipelineYaml.getPipelineTasks(docs[0]); const buildTask = tasks.find(t => t.name === 'build'); expect(buildTask.runAfter).to.not.contain('some'); expect(buildTask.runAfter).to.contain('build:$(tasks.multiply-inputs.results.product)'); const whenTask = tasks.find(t => t.id === 'build:$(tasks.multiply-inputs.results.product)'); expect(whenTask.runAfter).to.eql(['multiply-inputs', 'some']); }); }); });
the_stack
import * as coreHttp from "@azure/core-http"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { StorageClientContext } from "../storageClientContext"; import { ContainerCreateOptionalParams, ContainerCreateResponse, ContainerGetPropertiesOptionalParams, ContainerGetPropertiesResponse, ContainerDeleteOptionalParams, ContainerDeleteResponse, ContainerSetMetadataOptionalParams, ContainerSetMetadataResponse, ContainerGetAccessPolicyOptionalParams, ContainerGetAccessPolicyResponse, ContainerSetAccessPolicyOptionalParams, ContainerSetAccessPolicyResponse, ContainerRestoreOptionalParams, ContainerRestoreResponse, ContainerRenameOptionalParams, ContainerRenameResponse, ContainerSubmitBatchOptionalParams, ContainerSubmitBatchResponse, ContainerAcquireLeaseOptionalParams, ContainerAcquireLeaseResponse, ContainerReleaseLeaseOptionalParams, ContainerReleaseLeaseResponse, ContainerRenewLeaseOptionalParams, ContainerRenewLeaseResponse, ContainerBreakLeaseOptionalParams, ContainerBreakLeaseResponse, ContainerChangeLeaseOptionalParams, ContainerChangeLeaseResponse, ContainerListBlobFlatSegmentOptionalParams, ContainerListBlobFlatSegmentResponse, ContainerListBlobHierarchySegmentOptionalParams, ContainerListBlobHierarchySegmentResponse, ContainerGetAccountInfoResponse } from "../models"; /** Class representing a Container. */ export class Container { private readonly client: StorageClientContext; /** * Initialize a new instance of the class Container class. * @param client Reference to the service client */ constructor(client: StorageClientContext) { this.client = client; } /** * creates a new container under the specified account. If the container with the same name already * exists, the operation fails * @param options The options parameters. */ create( options?: ContainerCreateOptionalParams ): Promise<ContainerCreateResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, createOperationSpec ) as Promise<ContainerCreateResponse>; } /** * returns all user-defined metadata and system properties for the specified container. The data * returned does not include the container's list of blobs * @param options The options parameters. */ getProperties( options?: ContainerGetPropertiesOptionalParams ): Promise<ContainerGetPropertiesResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getPropertiesOperationSpec ) as Promise<ContainerGetPropertiesResponse>; } /** * operation marks the specified container for deletion. The container and any blobs contained within * it are later deleted during garbage collection * @param options The options parameters. */ delete( options?: ContainerDeleteOptionalParams ): Promise<ContainerDeleteResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, deleteOperationSpec ) as Promise<ContainerDeleteResponse>; } /** * operation sets one or more user-defined name-value pairs for the specified container. * @param options The options parameters. */ setMetadata( options?: ContainerSetMetadataOptionalParams ): Promise<ContainerSetMetadataResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, setMetadataOperationSpec ) as Promise<ContainerSetMetadataResponse>; } /** * gets the permissions for the specified container. The permissions indicate whether container data * may be accessed publicly. * @param options The options parameters. */ getAccessPolicy( options?: ContainerGetAccessPolicyOptionalParams ): Promise<ContainerGetAccessPolicyResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getAccessPolicyOperationSpec ) as Promise<ContainerGetAccessPolicyResponse>; } /** * sets the permissions for the specified container. The permissions indicate whether blobs in a * container may be accessed publicly. * @param options The options parameters. */ setAccessPolicy( options?: ContainerSetAccessPolicyOptionalParams ): Promise<ContainerSetAccessPolicyResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, setAccessPolicyOperationSpec ) as Promise<ContainerSetAccessPolicyResponse>; } /** * Restores a previously-deleted container. * @param options The options parameters. */ restore( options?: ContainerRestoreOptionalParams ): Promise<ContainerRestoreResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, restoreOperationSpec ) as Promise<ContainerRestoreResponse>; } /** * Renames an existing container. * @param sourceContainerName Required. Specifies the name of the container to rename. * @param options The options parameters. */ rename( sourceContainerName: string, options?: ContainerRenameOptionalParams ): Promise<ContainerRenameResponse> { const operationArguments: coreHttp.OperationArguments = { sourceContainerName, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, renameOperationSpec ) as Promise<ContainerRenameResponse>; } /** * The Batch operation allows multiple API calls to be embedded into a single HTTP request. * @param contentLength The length of the request. * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch * boundary. Example header value: multipart/mixed; boundary=batch_<GUID> * @param body Initial data * @param options The options parameters. */ submitBatch( contentLength: number, multipartContentType: string, body: coreHttp.HttpRequestBody, options?: ContainerSubmitBatchOptionalParams ): Promise<ContainerSubmitBatchResponse> { const operationArguments: coreHttp.OperationArguments = { contentLength, multipartContentType, body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, submitBatchOperationSpec ) as Promise<ContainerSubmitBatchResponse>; } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ acquireLease( options?: ContainerAcquireLeaseOptionalParams ): Promise<ContainerAcquireLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, acquireLeaseOperationSpec ) as Promise<ContainerAcquireLeaseResponse>; } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ releaseLease( leaseId: string, options?: ContainerReleaseLeaseOptionalParams ): Promise<ContainerReleaseLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, releaseLeaseOperationSpec ) as Promise<ContainerReleaseLeaseResponse>; } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ renewLease( leaseId: string, options?: ContainerRenewLeaseOptionalParams ): Promise<ContainerRenewLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, renewLeaseOperationSpec ) as Promise<ContainerRenewLeaseResponse>; } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ breakLease( options?: ContainerBreakLeaseOptionalParams ): Promise<ContainerBreakLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, breakLeaseOperationSpec ) as Promise<ContainerBreakLeaseResponse>; } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor * (String) for a list of valid GUID string formats. * @param options The options parameters. */ changeLease( leaseId: string, proposedLeaseId: string, options?: ContainerChangeLeaseOptionalParams ): Promise<ContainerChangeLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { leaseId, proposedLeaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, changeLeaseOperationSpec ) as Promise<ContainerChangeLeaseResponse>; } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param options The options parameters. */ listBlobFlatSegment( options?: ContainerListBlobFlatSegmentOptionalParams ): Promise<ContainerListBlobFlatSegmentResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, listBlobFlatSegmentOperationSpec ) as Promise<ContainerListBlobFlatSegmentResponse>; } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param delimiter When the request includes this parameter, the operation returns a BlobPrefix * element in the response body that acts as a placeholder for all blobs whose names begin with the * same substring up to the appearance of the delimiter character. The delimiter may be a single * character or a string. * @param options The options parameters. */ listBlobHierarchySegment( delimiter: string, options?: ContainerListBlobHierarchySegmentOptionalParams ): Promise<ContainerListBlobHierarchySegmentResponse> { const operationArguments: coreHttp.OperationArguments = { delimiter, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, listBlobHierarchySegmentOperationSpec ) as Promise<ContainerListBlobHierarchySegmentResponse>; } /** * Returns the sku name and account kind * @param options The options parameters. */ getAccountInfo( options?: coreHttp.OperationOptions ): Promise<ContainerGetAccountInfoResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getAccountInfoOperationSpec ) as Promise<ContainerGetAccountInfoResponse>; } } // Operation Specifications const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true); const createOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.ContainerCreateHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerCreateExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.metadata, Parameters.access, Parameters.defaultEncryptionScope, Parameters.preventEncryptionScopeOverride ], isXML: true, serializer: xmlSerializer }; const getPropertiesOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { headersMapper: Mappers.ContainerGetPropertiesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerGetPropertiesExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const deleteOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "DELETE", responses: { 202: { headersMapper: Mappers.ContainerDeleteHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerDeleteExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.leaseId, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince ], isXML: true, serializer: xmlSerializer }; const setMetadataOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ContainerSetMetadataHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerSetMetadataExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp6 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.metadata, Parameters.leaseId, Parameters.ifModifiedSince ], isXML: true, serializer: xmlSerializer }; const getAccessPolicyOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier" } } }, serializedName: "SignedIdentifiers", xmlName: "SignedIdentifiers", xmlIsWrapped: true, xmlElementName: "SignedIdentifier" }, headersMapper: Mappers.ContainerGetAccessPolicyHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerGetAccessPolicyExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp7 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const setAccessPolicyOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ContainerSetAccessPolicyHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerSetAccessPolicyExceptionHeaders } }, requestBody: Parameters.containerAcl, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp7 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.contentType, Parameters.accept, Parameters.version, Parameters.requestId, Parameters.access, Parameters.leaseId, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer }; const restoreOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.ContainerRestoreHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerRestoreExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp8 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.deletedContainerName, Parameters.deletedContainerVersion ], isXML: true, serializer: xmlSerializer }; const renameOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ContainerRenameHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerRenameExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp9 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.sourceContainerName, Parameters.sourceLeaseId ], isXML: true, serializer: xmlSerializer }; const submitBatchOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "POST", responses: { 202: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: Mappers.ContainerSubmitBatchHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerSubmitBatchExceptionHeaders } }, requestBody: Parameters.body, queryParameters: [ Parameters.timeoutInSeconds, Parameters.comp4, Parameters.restype2 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.contentType, Parameters.accept, Parameters.version, Parameters.requestId, Parameters.contentLength, Parameters.multipartContentType ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer }; const acquireLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.ContainerAcquireLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerAcquireLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp10 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince, Parameters.action, Parameters.duration, Parameters.proposedLeaseId ], isXML: true, serializer: xmlSerializer }; const releaseLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ContainerReleaseLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerReleaseLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp10 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince, Parameters.action1, Parameters.leaseId1 ], isXML: true, serializer: xmlSerializer }; const renewLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ContainerRenewLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerRenewLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp10 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince, Parameters.leaseId1, Parameters.action2 ], isXML: true, serializer: xmlSerializer }; const breakLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 202: { headersMapper: Mappers.ContainerBreakLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerBreakLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp10 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince, Parameters.action3, Parameters.breakPeriod ], isXML: true, serializer: xmlSerializer }; const changeLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ContainerChangeLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerChangeLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype2, Parameters.comp10 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince, Parameters.leaseId1, Parameters.action4, Parameters.proposedLeaseId1 ], isXML: true, serializer: xmlSerializer }; const listBlobFlatSegmentOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ListBlobsFlatSegmentResponse, headersMapper: Mappers.ContainerListBlobFlatSegmentHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerListBlobFlatSegmentExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.comp2, Parameters.prefix, Parameters.marker, Parameters.maxPageSize, Parameters.restype2, Parameters.include1 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1 ], isXML: true, serializer: xmlSerializer }; const listBlobHierarchySegmentOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ListBlobsHierarchySegmentResponse, headersMapper: Mappers.ContainerListBlobHierarchySegmentHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerListBlobHierarchySegmentExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.comp2, Parameters.prefix, Parameters.marker, Parameters.maxPageSize, Parameters.restype2, Parameters.include1, Parameters.delimiter ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.accept1 ], isXML: true, serializer: xmlSerializer }; const getAccountInfoOperationSpec: coreHttp.OperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { headersMapper: Mappers.ContainerGetAccountInfoHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ContainerGetAccountInfoExceptionHeaders } }, queryParameters: [Parameters.comp, Parameters.restype1], urlParameters: [Parameters.url], headerParameters: [Parameters.version, Parameters.accept1], isXML: true, serializer: xmlSerializer };
the_stack
declare namespace AsTypedInternal { type SchemaBase = { $id?: string $ref?: string type?: string title?: string description?: string default?: any exmamples?: any[] } type DefinitionsBase = {[name: string]: SchemaBase} type SchemaWithDefinitions<SchemaDefinitions extends DefinitionsBase> = SchemaBase & { definitions: SchemaDefinitions } type TypeName<T> = T extends null ? "null" : T extends string ? "string" : T extends any[] ? "array" : T extends number ? "number" : T extends boolean ? "boolean" : T extends undefined ? "undefined" : T extends Function ? "function" : "object"; type WithID = {$id: string} type SchemaDeclaration<Type> = SchemaBase & {type: TypeName<Type>; $id?: string} type RefSchema<RefId extends string> = {$ref: RefId} type EnumSchema<BaseType, EnumType> = BaseType & {enum: EnumType[]} type UnionToIntersection<U> = (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never type UndefinedSchema = SchemaDeclaration<undefined> type NumberSchema = SchemaDeclaration<number>& { multipleOf?: number minimun?: number exclusiveMinimum?: number maximum?: number exclusiveMaximum?: number } type StringSchema = SchemaDeclaration<string> & { pattern?: RegExp maxLength?: number minLength?: number } type ConstSchema<ConstType> = { const?: ConstType, enum?: ConstType[] } & ( ConstType extends number ? NumberSchema : ConstType extends string ? StringSchema : ConstType extends boolean ? BoolSchema : never ) type BoolSchema = SchemaDeclaration<boolean> type NullSchema = SchemaDeclaration<null> type LeafSchema = NumberSchema | StringSchema | BoolSchema | NullSchema type ObjectSchema<Props, ReqProps, AdditionalProps extends SchemaBase|null = null> = SchemaDeclaration<{}> & { required?: ReqProps[] properties?: Props additionalProperties?: AdditionalProps maxProperties?: number minProperties?: number patternProperties?: {[name: string]: SchemaBase} dependencies?: {[name: string]: SchemaBase | SchemaBase[]} propertyNames?: StringSchema } type CombinerSchema<ValueType extends SchemaBase, Operator extends string> = {[operator in Operator] : ValueType[]} type OperatorSchema<ValueType extends SchemaBase, Operator extends string> = {[operator in Operator] : ValueType} type IfThenElseSchema<If extends SchemaBase, Then extends SchemaBase, Else extends SchemaBase> = SchemaBase & { If: If Then: Then Else?: Else } type AllOf<ValueType extends SchemaBase> = CombinerSchema<ValueType, 'allOf'> type OneOf<ValueType extends SchemaBase> = CombinerSchema<ValueType, 'oneOf'> type AnyOf<ValueType extends SchemaBase> = CombinerSchema<ValueType, 'anyOf'> type Not<ValueType extends SchemaBase> = OperatorSchema<ValueType, 'not'> type ArraySchemaBase = SchemaDeclaration<any[]> & { maxItems?: number minItems?: number uniqueItems?: boolean contains?: SchemaBase } type ArraySchema<ValueSchema> = ArraySchemaBase & {items: ValueSchema extends any[] ? never : ValueSchema} type TupleSchema<TupleAsArray extends any[], AdditionalItemsSchema = null> = ArraySchemaBase & { items: TupleAsArray additionalItems?: AdditionalItemsSchema } type ResolveObjectRequiredProps<Props, RequiredPropNames> = RequiredPropNames extends string ? {[name in RequiredPropNames]: name extends keyof Props ? ResolveRecursive<Props[name]> : never} : unknown type ResolveObjectOptionalProps<Props> =Props extends null ? unknown : {[optKey in keyof Props]?: ResolveRecursive<Props[optKey]>} type ResolveObjectAdditionalProps<AdditionalPropsSchema> = AdditionalPropsSchema extends null ? unknown : {[key: string]: ResolveRecursive<AdditionalPropsSchema>} type ResolveObject<ObjectSchemaType extends ObjectSchema<Props, RequiredPropNames, SchemaForAdditionalProperties>, Props, RequiredPropNames, SchemaForAdditionalProperties extends SchemaBase> = ResolveObjectRequiredProps<Props, RequiredPropNames> & ResolveObjectOptionalProps<Props> & ResolveObjectAdditionalProps<SchemaForAdditionalProperties> interface ResolveArray<ValueType> extends Array<ResolveRecursive<ValueType>> {} // TODO: find a variadic way to do this, not sure it's possible with current typescript. https://github.com/Microsoft/TypeScript/issues/5453 type AsTypedTupleSchema<Tuple> = Tuple extends [infer A, infer B] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>] : Tuple extends [infer A, infer B, infer C] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>] : Tuple extends [infer A, infer B, infer C, infer D] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>] : Tuple extends [infer A, infer B, infer C, infer D, infer E] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F, infer G] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>, ResolveRecursiveInternal<G>] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F, infer G, infer H] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>, ResolveRecursiveInternal<G>, ResolveRecursiveInternal<H>] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F, infer G, infer H, infer I] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>, ResolveRecursiveInternal<G>, ResolveRecursiveInternal<H>, ResolveRecursiveInternal<I>] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F, infer G, infer H, infer I, infer J] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>, ResolveRecursiveInternal<G>, ResolveRecursiveInternal<H>, ResolveRecursiveInternal<I>, ResolveRecursiveInternal<J>] : never type AsTypedTupleSchemaWithAdditional<Tuple, Additional> = Tuple extends [infer A, infer B] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ...(ResolveRecursiveInternal<Additional>[])] : Tuple extends [infer A, infer B, infer C] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ...(ResolveRecursiveInternal<Additional>[])] : Tuple extends [infer A, infer B, infer C, infer D] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ...(ResolveRecursiveInternal<Additional>[])] : Tuple extends [infer A, infer B, infer C, infer D, infer E] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ...(ResolveRecursiveInternal<Additional>[])] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>, ...(ResolveRecursiveInternal<Additional>[])] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F, infer G] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>, ResolveRecursiveInternal<G>, ...(ResolveRecursiveInternal<Additional>[])] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F, infer G, infer H] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>, ResolveRecursiveInternal<G>, ResolveRecursiveInternal<H>, ...(ResolveRecursiveInternal<Additional>[])] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F, infer G, infer H, infer I] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>, ResolveRecursiveInternal<G>, ResolveRecursiveInternal<H>, ResolveRecursiveInternal<I>, ...(ResolveRecursiveInternal<Additional>[])] : Tuple extends [infer A, infer B, infer C, infer D, infer E, infer F, infer G, infer H, infer I, infer J] ? [ResolveRecursiveInternal<A>, ResolveRecursiveInternal<B>, ResolveRecursiveInternal<C>, ResolveRecursiveInternal<D>, ResolveRecursiveInternal<E>, ResolveRecursiveInternal<F>, ResolveRecursiveInternal<G>, ResolveRecursiveInternal<H>, ResolveRecursiveInternal<I>, ResolveRecursiveInternal<J>, ...(ResolveRecursiveInternal<Additional>[])] : never // This is very crude type ResolveNot<ValueType> = // TODO: allow Not() for array/object types of specific schemas. Not easy. object | any[] | (ValueType extends NullSchema ? never : null) | (ValueType extends NumberSchema ? never : number) | (ValueType extends UndefinedSchema ? never : undefined) | (ValueType extends StringSchema ? never : string) | (ValueType extends BoolSchema ? never : boolean) type ResolveRecursiveInternal<SchemaType> = SchemaType extends SchemaDeclaration<null> ? null : SchemaType extends ConstSchema<infer Value> ? Value : SchemaType extends SchemaDeclaration<string> ? string : SchemaType extends SchemaDeclaration<boolean> ? boolean : SchemaType extends SchemaDeclaration<number> ? number : SchemaType extends Not<infer T> ? ResolveNot<T> : SchemaType extends ObjectSchema<infer Props, infer Required, infer Additional> ? ResolveObject<SchemaType, Props, Required, Additional> : SchemaType extends ArraySchema<infer ValueType> ? ResolveArray<ValueType> : SchemaType extends SchemaDeclaration<typeof undefined> ? undefined : never // TODO type ResolveOneOf<InnerSchema> = InnerSchema // High order resolution changes the schema before resolving it to typed type ResolveHighOrder<SchemaToResolve extends SchemaBase> = SchemaToResolve extends IfThenElseSchema<infer If, infer Then, infer Else> ? (If & Then) | Else : SchemaToResolve extends OneOf<infer Inner> ? ResolveOneOf<Inner> : SchemaToResolve extends AllOf<infer Inner> ? UnionToIntersection<Inner> : SchemaToResolve extends AnyOf<infer Inner> ? Inner : SchemaToResolve type ResolveRecursive<SchemaType> = SchemaType extends TupleSchema<infer TupleType, infer Additional> ? (Additional extends null ? AsTypedTupleSchema<TupleType> : AsTypedTupleSchemaWithAdditional<TupleType, Additional>) : ResolveRecursiveInternal<ResolveHighOrder<SchemaType>> type MapPropsToRefs<Props, Definitions extends DefinitionsBase> = Definitions extends {[name: string]: SchemaBase} ? {[name in keyof Props]: ResolveRefs<Props[name], Definitions>} : never type ResolveIfThenElseRefs<ITEType extends IfThenElseSchema<If, Then, Else>, If extends SchemaBase, Then extends SchemaBase, Else extends SchemaBase, Definitions extends DefinitionsBase> = SchemaBase & {If: ResolveRefs<If, Definitions>, Then: ResolveRefs<Then, Definitions>, Else: ResolveRefs<Else, Definitions>} type ResolveArrayRefs<ArrayType extends ArraySchema<ValueType>, ValueType extends SchemaBase, Definitions extends DefinitionsBase> = SchemaDeclaration<any[]> & {items: ResolveRefs<ValueType, Definitions>} type ResolveTupleRefs<TupleType extends TupleSchema<Tuple, Additional>, Tuple extends SchemaBase[], Additional extends SchemaBase, Definitions extends DefinitionsBase> = SchemaDeclaration<any[]> & {items: ResolveRefs<Tuple, Definitions>, additionalItems: ResolveRefs<Additional, Definitions>} type ResolveCombinerRefs<CombinerType extends CombinerSchema<ValueType, Operator>, ValueType extends SchemaBase, Operator extends string, Definitions extends DefinitionsBase> = {[name in Operator]: ResolveRefs<ValueType, Definitions>[]} type ResolveOperatorRefs<OperatorType extends OperatorSchema<ValueType, Operator>, ValueType extends SchemaBase, Operator extends string, Definitions extends DefinitionsBase> = {[name in Operator]: ResolveRefs<ValueType, Definitions>} type ResolveDefinitions<Definitions extends DefinitionsBase> = {[DefinitionName in keyof Definitions]: ResolveRefs<Definitions[DefinitionName], Definitions>} type ExtractDefinitionsById<Definitions extends DefinitionsBase> = { [key in Definitions[keyof Definitions]['$id']]: Definitions[keyof Definitions] } type ResolveRefs<SchemaToResolve, Definitions extends DefinitionsBase> = SchemaToResolve extends RefSchema<infer RefId> ? Definitions[RefId] : SchemaToResolve extends ObjectSchema<infer Props, infer Required> ? ObjectSchema<MapPropsToRefs<Props, Definitions>, Required>: SchemaToResolve extends TupleSchema<infer Tuple, infer Additional> ? (Tuple extends SchemaBase[] ? ResolveTupleRefs<SchemaToResolve, Tuple, Additional, Definitions> : never) : SchemaToResolve extends ArraySchema<infer ValueType> ? ResolveArrayRefs<SchemaToResolve, ValueType, Definitions> : SchemaToResolve extends CombinerSchema<infer ValueType, infer Operator> ? ResolveCombinerRefs<SchemaToResolve, ValueType, Operator, Definitions> : SchemaToResolve extends OperatorSchema<infer ValueType, infer Operator> ? ResolveOperatorRefs<SchemaToResolve, ValueType, Operator, Definitions> : SchemaToResolve extends IfThenElseSchema<infer If, infer Then, infer Else> ? ResolveIfThenElseRefs<SchemaToResolve, If, Then, Else, Definitions> : SchemaToResolve type ResolveRootSchemaDefinitions<Schema> = Schema extends SchemaWithDefinitions<infer D> ? ResolveDefinitions<ExtractDefinitionsById<D>> : null type ResolveRefsForRootSchema<RootSchema> = ResolveRefs<RootSchema, ResolveRootSchemaDefinitions<RootSchema>> export type ResolveRootSchema<RootSchema> = ResolveRecursive<ResolveRefsForRootSchema<RootSchema>> } export type AsTyped<Schema> = AsTypedInternal.ResolveRootSchema<Schema>
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * The policy definition. */ export interface PolicyDefinition extends BaseResource { /** * The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. Possible * values include: 'NotSpecified', 'BuiltIn', 'Custom' */ policyType?: PolicyType; /** * The policy definition mode. Possible values are NotSpecified, Indexed, and All. Possible * values include: 'NotSpecified', 'Indexed', 'All' */ mode?: PolicyMode; /** * The display name of the policy definition. */ displayName?: string; /** * The policy definition description. */ description?: string; /** * The policy rule. */ policyRule?: any; /** * The policy definition metadata. */ metadata?: any; /** * Required if a parameter is used in policy rule. */ parameters?: any; /** * The ID of the policy definition. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the policy definition. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; } /** * The policy assignment. */ export interface PolicyAssignment extends BaseResource { /** * The display name of the policy assignment. */ displayName?: string; /** * The ID of the policy definition. */ policyDefinitionId?: string; /** * The scope for the policy assignment. */ scope?: string; /** * Required if a parameter is used in policy rule. */ parameters?: any; /** * This message will be part of response in case of policy violation. */ description?: string; /** * The ID of the policy assignment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The type of the policy assignment. */ type?: string; /** * The name of the policy assignment. */ name?: string; } /** * Optional Parameters. */ export interface PolicyAssignmentsListForResourceGroupOptionalParams extends msRest.RequestOptionsBase { /** * The filter to apply on the operation. */ filter?: string; } /** * Optional Parameters. */ export interface PolicyAssignmentsListForResourceOptionalParams extends msRest.RequestOptionsBase { /** * The filter to apply on the operation. */ filter?: string; } /** * Optional Parameters. */ export interface PolicyAssignmentsListOptionalParams extends msRest.RequestOptionsBase { /** * The filter to apply on the operation. */ filter?: string; } /** * An interface representing PolicyClientOptions. */ export interface PolicyClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * List of policy definitions. * @extends Array<PolicyDefinition> */ export interface PolicyDefinitionListResult extends Array<PolicyDefinition> { /** * The URL to use for getting the next set of results. */ nextLink?: string; } /** * @interface * List of policy assignments. * @extends Array<PolicyAssignment> */ export interface PolicyAssignmentListResult extends Array<PolicyAssignment> { /** * The URL to use for getting the next set of results. */ nextLink?: string; } /** * Defines values for PolicyType. * Possible values include: 'NotSpecified', 'BuiltIn', 'Custom' * @readonly * @enum {string} */ export type PolicyType = 'NotSpecified' | 'BuiltIn' | 'Custom'; /** * Defines values for PolicyMode. * Possible values include: 'NotSpecified', 'Indexed', 'All' * @readonly * @enum {string} */ export type PolicyMode = 'NotSpecified' | 'Indexed' | 'All'; /** * Contains response data for the createOrUpdate operation. */ export type PolicyDefinitionsCreateOrUpdateResponse = PolicyDefinition & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinition; }; }; /** * Contains response data for the get operation. */ export type PolicyDefinitionsGetResponse = PolicyDefinition & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinition; }; }; /** * Contains response data for the getBuiltIn operation. */ export type PolicyDefinitionsGetBuiltInResponse = PolicyDefinition & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinition; }; }; /** * Contains response data for the createOrUpdateAtManagementGroup operation. */ export type PolicyDefinitionsCreateOrUpdateAtManagementGroupResponse = PolicyDefinition & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinition; }; }; /** * Contains response data for the getAtManagementGroup operation. */ export type PolicyDefinitionsGetAtManagementGroupResponse = PolicyDefinition & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinition; }; }; /** * Contains response data for the list operation. */ export type PolicyDefinitionsListResponse = PolicyDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinitionListResult; }; }; /** * Contains response data for the listBuiltIn operation. */ export type PolicyDefinitionsListBuiltInResponse = PolicyDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinitionListResult; }; }; /** * Contains response data for the listByManagementGroup operation. */ export type PolicyDefinitionsListByManagementGroupResponse = PolicyDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinitionListResult; }; }; /** * Contains response data for the listNext operation. */ export type PolicyDefinitionsListNextResponse = PolicyDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinitionListResult; }; }; /** * Contains response data for the listBuiltInNext operation. */ export type PolicyDefinitionsListBuiltInNextResponse = PolicyDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinitionListResult; }; }; /** * Contains response data for the listByManagementGroupNext operation. */ export type PolicyDefinitionsListByManagementGroupNextResponse = PolicyDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyDefinitionListResult; }; }; /** * Contains response data for the deleteMethod operation. */ export type PolicyAssignmentsDeleteMethodResponse = PolicyAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignment; }; }; /** * Contains response data for the create operation. */ export type PolicyAssignmentsCreateResponse = PolicyAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignment; }; }; /** * Contains response data for the get operation. */ export type PolicyAssignmentsGetResponse = PolicyAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignment; }; }; /** * Contains response data for the listForResourceGroup operation. */ export type PolicyAssignmentsListForResourceGroupResponse = PolicyAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignmentListResult; }; }; /** * Contains response data for the listForResource operation. */ export type PolicyAssignmentsListForResourceResponse = PolicyAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignmentListResult; }; }; /** * Contains response data for the list operation. */ export type PolicyAssignmentsListResponse = PolicyAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignmentListResult; }; }; /** * Contains response data for the deleteById operation. */ export type PolicyAssignmentsDeleteByIdResponse = PolicyAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignment; }; }; /** * Contains response data for the createById operation. */ export type PolicyAssignmentsCreateByIdResponse = PolicyAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignment; }; }; /** * Contains response data for the getById operation. */ export type PolicyAssignmentsGetByIdResponse = PolicyAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignment; }; }; /** * Contains response data for the listForResourceGroupNext operation. */ export type PolicyAssignmentsListForResourceGroupNextResponse = PolicyAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignmentListResult; }; }; /** * Contains response data for the listForResourceNext operation. */ export type PolicyAssignmentsListForResourceNextResponse = PolicyAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignmentListResult; }; }; /** * Contains response data for the listNext operation. */ export type PolicyAssignmentsListNextResponse = PolicyAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PolicyAssignmentListResult; }; };
the_stack
import { ProgressEvent, EventTarget, Event, AddEventListenerOptions, EventListenerOptions } from "../event"; export type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; export type XMLHttpRequestMethod = "GET" | "POST" | "DELETE"; export type BodyInit = string | Record<string, any>; export interface XMLHttpRequestEventTargetEventMap { "abort": ProgressEvent<XMLHttpRequestEventTarget>; "error": ProgressEvent<XMLHttpRequestEventTarget>; "load": ProgressEvent<XMLHttpRequestEventTarget>; "loadend": ProgressEvent<XMLHttpRequestEventTarget>; "loadstart": ProgressEvent<XMLHttpRequestEventTarget>; "progress": ProgressEvent<XMLHttpRequestEventTarget>; "timeout": ProgressEvent<XMLHttpRequestEventTarget>; } export interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; } export class XMLHttpRequestEventTarget extends EventTarget { onabort: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; onerror: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; onload: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; onloadstart: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; addEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void { super.addEventListener(type, listener, options); } removeEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void { super.addEventListener(type, listener, options); } } export class XMLHttpRequestUpload extends XMLHttpRequestEventTarget { } export enum XMLHttpRequestReadyState { UNSENT, OPENED, HEADERS_RECEIVED, LOADING, DONE, } /** Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. */ export class XMLHttpRequest extends XMLHttpRequestEventTarget { onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; /** * Returns client's state. */ get readyState(): XMLHttpRequestReadyState { return this._readyState; } set readyState(value: XMLHttpRequestReadyState) { if (value != this._readyState) { this._readyState = value; if (this.onreadystatechange) { let event = new Event('readystatechange'); this.onreadystatechange.call(this, event); this.dispatchEvent(event); } } } protected _readyState: XMLHttpRequestReadyState; /** * Returns the response's body. */ get response(): any { return this._response; } protected _response: any; /** * Returns the text response. * * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "text". */ readonly responseText: string; /** * Returns the response type. * * Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". * * When set: setting to "document" is ignored if current global object is not a Window object. * * When set: throws an "InvalidStateError" DOMException if state is loading or done. * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ responseType: XMLHttpRequestResponseType; readonly responseURL: string; /** * Returns the document response. * * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "document". */ readonly responseXML: string | null; readonly status: number; readonly statusText: string; /** * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the request has not yet completed, and the synchronous flag is unset, a timeout event will then be dispatched, or a "TimeoutError" DOMException will be thrown otherwise (for the send() method). * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ timeout: number; /** * Returns the associated XMLHttpRequestUpload object. It can be used to gather transmission information when data is transferred to a server. */ get upload(): XMLHttpRequestUpload { return this._upload; } protected _upload: XMLHttpRequestUpload; /** * True when credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. * * When set: throws an "InvalidStateError" DOMException if state is not unsent or opened, or if the send() flag is set. */ withCredentials: boolean; /** * Cancels any network activity. */ abort(): void { } getAllResponseHeaders(): string { return ""; } getResponseHeader(name: string): string | null { return null; } /** * Sets the request method, request URL, and synchronous flag. * * Throws a "SyntaxError" DOMException if either method is not a valid HTTP method or url cannot be parsed. * * Throws a "SecurityError" DOMException if method is a case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`. * * Throws an "InvalidAccessError" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string. */ open(method: XMLHttpRequestMethod, url: string, async?: boolean, username?: string | null, password?: string | null): void { } /** * Acts as if the `Content-Type` header value for response is mime. (It does not actually change the header though.) * * Throws an "InvalidStateError" DOMException if state is loading or done. */ overrideMimeType(mime: string): void { this._overrided_mime = mime; } protected _overrided_mime: string; /** * Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD. * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. */ send(body?: BodyInit | null): void { } /** * Combines a header in author request headers. * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. * * Throws a "SyntaxError" DOMException if name is not a header name or if value is not a header value. */ setRequestHeader(name: string, value: string): void { } addEventListener<K extends keyof XMLHttpRequestEventMap>(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void { super.addEventListener(type as any, listener, options); } removeEventListener<K extends keyof XMLHttpRequestEventMap>(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void { super.removeEventListener(type as any, listener, options); } } import { IURL, parse_url } from "./url"; import MIMEType from "./thirdpart/mimetype/mime-type"; import * as querystring from "./thirdpart/querystring/querystring"; const { ResponseCode, Status, Method } = godot.HTTPClient; const CRLF = '\r\n'; const RequestMethodMap: { [key: string]: number; } = { "GET": Method.METHOD_GET, "POST": Method.METHOD_POST, "DELETE": Method.METHOD_DELETE, }; interface InternalRequetTask { path: string; method: number; body?: BodyInit; length?: number; loaded_length?: number; update_time?: number; } interface InternalResponse { data: godot.PoolByteArray; headers: object; code: number; headers_list: string[]; } class GodotXMLHttpRequest extends XMLHttpRequest { readonly client: godot.HTTPClient; public get url(): Readonly<IURL> { return this._url; } protected _url: IURL; get internal_response(): Readonly<InternalResponse> { return this._internal_response; } protected _internal_response: InternalResponse; private _poll_task_id = -1; protected _method: XMLHttpRequestMethod; protected _request_headers: { [key: string]: string; } = {}; protected _pending_task: InternalRequetTask; protected _loading_task: InternalRequetTask; protected _connec_start_time: number; constructor() { super(); this.client = new godot.HTTPClient(); this.client.read_chunk_size = 81920; this._readyState = XMLHttpRequestReadyState.UNSENT; } get status(): number { return this._internal_response?.code; } get responseText(): string { if (this.responseType === 'text' || this.responseType === 'json' || this.responseType === '') { if (this.internal_response) { return this.internal_response.data.get_string_from_utf8(); } } return null; } open(method: XMLHttpRequestMethod, url: string, async?: boolean, username?: string | null, password?: string | null): void { this._url = parse_url(url); if (!this.url.port) { this._url.port = this.url.protocal === 'https' ? 443 : 80; } this._method = method; this._readyState = XMLHttpRequestReadyState.UNSENT; this._connec_start_time = Date.now(); this.client.connect_to_host(this.url.hostname, this.url.port, this.url.port === 443); this.start_poll(); } send(body?: BodyInit): void { this._pending_task = { path: '/' + this.url.path, method: RequestMethodMap[this._method], body }; } setRequestHeader(name: string, value: string): void { this._request_headers[name.toLowerCase()] = value; } protected start_poll() { this.stop_poll(); const tickLoop = () => { this.poll.bind(this); this._poll_task_id = requestAnimationFrame(tickLoop); }; this._poll_task_id = requestAnimationFrame(tickLoop); } protected stop_poll() { if (this._poll_task_id != -1) { cancelAnimationFrame(this._poll_task_id); this._poll_task_id = -1; } } public abort() { this.client.close(); this.dispatch_event('abort'); this.start_poll(); } getAllResponseHeaders(): string { return this.internal_response.headers_list.join(CRLF); } getResponseHeader(name: string): string | null { return this.internal_response.headers[name]; } public poll() { this.client.poll(); if (this._internal_response) this._internal_response.code = this.client.get_response_code(); const now = Date.now(); let status = this.client.get_status(); switch (status) { case Status.STATUS_CONNECTED: { switch (this.readyState) { case XMLHttpRequestReadyState.UNSENT: this.readyState = XMLHttpRequestReadyState.OPENED; break; case XMLHttpRequestReadyState.LOADING: { if (this._loading_task.loaded_length >= this._loading_task.length) { this.process_response(); this.readyState = XMLHttpRequestReadyState.DONE; if (this._internal_response.code >= ResponseCode.RESPONSE_OK && this._internal_response.code <= ResponseCode.RESPONSE_MULTIPLE_CHOICES) { this.dispatch_event('load'); } else if (this._internal_response.code >= ResponseCode.RESPONSE_BAD_REQUEST) { this.dispatch_event('error'); } this.dispatch_event('loadend'); } } break; } } break; case Status.STATUS_BODY: { this._internal_response.code = ResponseCode.RESPONSE_CONTINUE; if (this.readyState === XMLHttpRequestReadyState.OPENED) { const headers = this.client.get_response_headers(); if (headers.size()) { this._internal_response.headers = {}; for (let i = 0; i < headers.size(); i++) { const header = headers.get(i); this.internal_response.headers_list.push(header); let cidx = header.indexOf(":"); this.internal_response.headers[header.substring(0, cidx)] = header.substring(cidx + 1).trim(); } this.readyState = XMLHttpRequestReadyState.HEADERS_RECEIVED; } } else if (this.readyState === XMLHttpRequestReadyState.LOADING || this.readyState === XMLHttpRequestReadyState.HEADERS_RECEIVED) { this.readyState = XMLHttpRequestReadyState.LOADING; const chunk = this.client.read_response_body_chunk(); const size = chunk.size(); this._loading_task.length = this.client.get_response_body_length(); if (size) { this.internal_response.data.append_array(chunk); this._loading_task.loaded_length += size; this._loading_task.update_time = now; this.dispatch_event('progress'); } } } break; case Status.STATUS_CONNECTING: if (now - this._connec_start_time > this.timeout) { this.dispatch_event('timeout'); this.stop_poll(); } break; case Status.STATUS_CANT_CONNECT: case Status.STATUS_CANT_RESOLVE: case Status.STATUS_DISCONNECTED: if (this.readyState != XMLHttpRequestReadyState.DONE) { this.readyState = XMLHttpRequestReadyState.DONE; this.dispatch_event('error'); this.dispatch_event('loadend'); this.stop_poll(); } break; default: break; } // start load pending if (this.readyState == XMLHttpRequestReadyState.OPENED && this._pending_task) { if (this.start_load_task(this._pending_task)) { this._pending_task = null; } } if (this._loading_task) { if (this.readyState == XMLHttpRequestReadyState.LOADING && now - this._loading_task.update_time > this.timeout) { this.dispatch_event('timeout'); this.dispatch_event('loadend'); this.stop_poll(); } } } protected start_load_task(task: InternalRequetTask) { if (this.readyState == XMLHttpRequestReadyState.OPENED) { const headers: string[] = []; let body: string = ''; if (typeof task.body === 'object') { // this.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); // body = querystring.encode(task.body); this.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); body = JSON.stringify(task.body); } else if (task.body === 'string') { body = task.body; if (!('Content-Type' in this._request_headers)) { this.setRequestHeader('Content-Type', 'text/plain'); } } for (let key of Object.getOwnPropertyNames(this._request_headers)) { const value = this._request_headers[key]; const header = `${key}: ${value}`; headers.push(header); } if (godot.OK == this.client.request(task.method, task.path, headers as any, body)) { this.init_load_task(task); this.dispatch_event('loadstart'); return true; } } return false; } protected init_load_task(task: InternalRequetTask) { this._loading_task = task; this._loading_task.loaded_length = 0; this._loading_task.update_time = Date.now(); this._response = undefined; this._internal_response = { code: 0, data: new godot.PoolByteArray(), headers: {}, headers_list: [], }; } protected dispatch_event(type: keyof XMLHttpRequestEventTargetEventMap) { let event: Event = undefined; if (type === 'progress') { event = new ProgressEvent(type, { total: this._loading_task.length, loaded: this._loading_task.loaded_length, lengthComputable: this._loading_task.length > 0 }); } else { event = new Event(type); } switch (type) { case 'load': if (this.onload) this.onload.call(this, event); break; case 'loadend': if (this.onloadend) this.onloadend.call(this, event); break; case 'loadstart': if (this.onloadstart) this.onloadstart.call(this, event); break; case 'progress': if (this.onprogress) this.onprogress.call(this, event); break; case 'timeout': if (this.ontimeout) this.ontimeout.call(this, event); break; case 'abort': if (this.onabort) this.onabort.call(this, event); break; case 'error': if (this.onerror) this.onerror.call(this, event); break; default: break; } this.dispatchEvent(event); } protected process_response() { if (this.responseType === undefined) { const mime = new MIMEType(this._overrided_mime || this.getResponseHeader("Content-Type") || 'text/plain'); if (mime.type === 'application' && mime.subtype === 'json') { this.responseType = 'json'; } else if (mime.type === 'text') { this.responseType = 'text'; } else { this.responseType = 'arraybuffer'; } } switch (this.responseType) { case '': case 'document': case 'text': this._response = this.responseText; break; case 'json': const text = this.responseText; if (text) { this._response = JSON.parse(text); } else { this._response = null; } break; default: this._response = null; break; } } } export default { exports: { XMLHttpRequestEventTarget, XMLHttpRequestReadyState, XMLHttpRequestUpload, XMLHttpRequest: GodotXMLHttpRequest, } };
the_stack
import { Context, LLVMContext, X86Context } from '../environment/context' import ESTree from 'estree' import { walk } from 'estree-walker' import { NodeTypes } from './ast'; import { BinaryExpression, dispatchExpressionCompile, dispatchExpressionEvaluation, dispatchExpressionLLVMCompile } from './expression'; import { Tree } from './Tree' import { ExpressionStatement } from './expression' import { VariableDeclaration } from './VariableDeclaration' import { Environment, Kind } from '../environment/Environment'; import { incGlobalCounter } from './util' import { LLVMNamePointer } from '../backend/llvmAssemble' export class BlockStatement extends Tree { ast!: ESTree.BlockStatement constructor(ast: ESTree.BlockStatement) { super(ast) } toCode(): string {// Todos: finish function toCode return '' } evaluate(context: Context): boolean { return this.ast.body.every((statement: ESTree.Statement) => dispatchStatementEvaluation(statement, context)) } compile(context: X86Context, depth: number = 0) { let length = this.ast.body.length return this.ast.body.every((statement: ESTree.Statement, i: number) => { let result = dispatchStatementCompile(statement, context, depth) if (i < length - 1) { context.emit(depth, `POP RAX # Ignore non-final expression`); } return result }) } llvmCompile(context: LLVMContext, namePointer: LLVMNamePointer) { return this.ast.body.every((statement: ESTree.Statement, i: number) => { // const isLast = this.ast.body.length - 1 === i; /** * Todos: determine whether it is function definition last sentence * only affect this layer of tailCallTree */ const contextClone = context.env.copy(); contextClone.scope = context.env.scope; // if (!isLast || statement.type !== NodeTypes.ReturnStatement) { // contextClone.tailCallTree = []; // } return dispathStatementLLVMCompile(statement, context, namePointer) }) } } export class ReturnStatement extends Tree { ast!: ESTree.ReturnStatement; constructor(ast: ESTree.ReturnStatement) { super(ast) } evaluate(context: Context): false { if (this.ast.argument) { let result = dispatchExpressionEvaluation(this.ast.argument, context) context.env.setReturnValue(result) } return false } compile(context: X86Context, depth: number = 0) { if (this.ast.argument) { dispatchExpressionCompile(this.ast.argument, context, depth) /** * save whatever to RAX for return * TODOS: how to resolve function without a return */ // context.emit(depth,'MOV RAX, [RSP]'); // context.emit(depth, `POP RAX`); } return false; } llvmCompile(context: LLVMContext, retNamePointer: LLVMNamePointer) { /** * Todos * js ret could contain any object * here we only considered simple expression yet */ if (this.ast.argument) { if (this.ast.argument.type === NodeTypes.CallExpression) { /** * set tail_call_enabled = true * only when encounter return CallExpression */ context.env.tail_call_enabled = true; } dispatchExpressionLLVMCompile(this.ast.argument, context, retNamePointer) context.env.tail_call_enabled = false; context.emit(1, `ret ${retNamePointer.type} %${retNamePointer.value}`); } else { context.emit(1, `ret void`); } return false; } } export class WhileStatement extends Tree { ast!: ESTree.WhileStatement; constructor(ast: ESTree.WhileStatement) { super(ast) } evaluate(context: Context): boolean { if (this.ast.test.type === NodeTypes.BinaryExpression) { let binaryExpression = new BinaryExpression(this.ast.test); while (binaryExpression.evaluate(context)) { return dispatchStatementEvaluation(this.ast.body, context) } } return true } } export class IfStatement extends Tree { ast!: ESTree.IfStatement; constructor(ast: ESTree.IfStatement) { super(ast) } evaluate(context: Context): boolean { if (this.ast.test.type === NodeTypes.BinaryExpression) { let binaryExpression = new BinaryExpression(this.ast.test); if (binaryExpression.evaluate(context)) { if (this.ast.consequent.type === NodeTypes.BlockStatement) { return new BlockStatement(this.ast.consequent).evaluate(context) } } else { if (this.ast.alternate) { if (this.ast.alternate.type === NodeTypes.BlockStatement) { return new BlockStatement(this.ast.alternate).evaluate(context) } } } } return true } compile(context: X86Context, depth: number = 0): boolean { const { test, consequent, alternate } = this.ast context.emit(depth, '# If'); // Compile test dispatchExpressionCompile(test, context, depth) let branch = `else_branch` + incGlobalCounter(); // Must pop/use up argument in test context.emit(0, ''); context.emit(depth, `POP RAX`); context.emit(depth, `TEST RAX, RAX`); context.emit(depth, `JZ .${branch}\n`); // Compile then section context.emit(depth, `# If then`); dispatchStatementCompile(consequent, context, depth) context.emit(depth, `JMP .after_${branch}\n`); // Compile else section context.emit(depth, `# If else`); context.emit(0, `.${branch}:`); if (alternate) { dispatchStatementCompile(alternate, context, depth) } else { context.emit(1, 'PUSH 0 # Null else branch'); } context.emit(0, `.after_${branch}:`); context.emit(depth, '# End if'); return true } llvmCompile(context: LLVMContext, namePointer: LLVMNamePointer) { const { test, consequent, alternate } = this.ast const testVariable = context.env.scope.symbol(); const result = context.env.scope.symbol({ value: 'ifresult', type: 'i64*' }); // Space for result context.emit(1, `%${result.value} = alloca i64, align 4`); // Compile expression and branch dispatchExpressionLLVMCompile(test, context, testVariable); const trueLabel = context.env.scope.symbol('iftrue').value; const falseLabel = context.env.scope.symbol('iffalse').value; context.emit( 1, `br i1 %${testVariable.value}, label %${trueLabel}, label %${falseLabel}`, ); // Compile true section context.emit(0, trueLabel + ':'); const trueTempNamePointer = context.env.scope.symbol(); dispathStatementLLVMCompile(consequent, context, trueTempNamePointer); /** * trueTempNamePointer type will be reassigned void if statement is a void call */ trueTempNamePointer.type !== 'void' && context.emit( 1, `store ${trueTempNamePointer.type} %${trueTempNamePointer.value}, ${result.type} %${result.value}, align 4`, ); const endLabel = context.env.scope.symbol('ifend').value; context.emit(1, 'br label %' + endLabel); context.emit(0, falseLabel + ':'); let elseTempNamePointer = context.env.scope.symbol(); if (alternate) { dispathStatementLLVMCompile(alternate, context, elseTempNamePointer); elseTempNamePointer.type !== 'void' && context.emit( 1, `store ${elseTempNamePointer.type} %${elseTempNamePointer.value}, ${result.type} %${result.value}, align 4`, ); } context.emit(1, 'br label %' + endLabel); // Compile cleanup context.emit(0, endLabel + ':'); // context.emit( // 1, // `%${namePointer.value} = load ${namePointer.type}, ${result.type} %${result.value}, align 4`, // ); return true; } } export class FunctionDeclaration extends Tree { ast!: ESTree.FunctionDeclaration constructor(ast: ESTree.FunctionDeclaration) { super(ast) } toCode(): string {// Todos: finish function toCode return '' } evaluate(context: Context) { let { body, id, params } = this.ast if (id) { let makeFunction = function () { let env: Environment = context.env.extend() params.forEach((param, i) => { if (param.type === NodeTypes.Identifier && arguments[i]) { env.def(param.name, arguments[i]) } }) if (body.type === NodeTypes.BlockStatement) { new BlockStatement(body).evaluate({ ...context, env }) } } context.env.def(id.name, makeFunction, Kind.FunctionDeclaration) } } compile(context: X86Context, depth: number = 0) { depth++; let { body, id, params } = this.ast let safe = 'defaultFunctionName' // Add this function to outer scope if (id) { safe = context.env.assign(id.name); } else { throw Error('Do not support function name null yet!!') } // Copy outer scope so parameter mappings aren't exposed in outer scope. const childScope = context.env.copy(); context.emit(0, `${safe}:`); context.emit(depth, `PUSH RBP`); context.emit(depth, `MOV RBP, RSP\n`); // Copy params into local scope // NOTE: context doesn't actually copy into the local stack, it // just references them from the caller. They will need to // be copied in to support mutation of arguments if that's // ever a desire. params.forEach((param: ESTree.Pattern, i) => { if (param.type === NodeTypes.Identifier) { /** * keep param offset from RBP when invoked, * which will be used to fetch real value in function body(compiled in BlockStatement) */ childScope.map[param.name] = -1 * (params.length - i - 1 + 2); } else { throw Error('Unknown param type ' + param.type) } }); context.env = childScope // Pass childScope in for reference when body is compiled. new BlockStatement(body).compile(context, depth) // Save the return value context.emit(depth, `POP RAX`); context.emit(depth, `POP RBP\n`); context.emit(depth, 'RET\n'); } llvmCompile(context: LLVMContext, _: LLVMNamePointer) { function getRetInfo(ast: ESTree.FunctionDeclaration): { hasReturnStatement: boolean, voidTypeReturn: boolean } { let hasReturnStatement = false, voidTypeReturn = true; walk(ast, { enter(node) { if (node.type === NodeTypes.ReturnStatement) { hasReturnStatement = true; if ((node as ESTree.ReturnStatement).argument) { voidTypeReturn = false } } } }) return { hasReturnStatement, voidTypeReturn } } let { body, id, params } = this.ast, fn: LLVMNamePointer, { hasReturnStatement, voidTypeReturn } = getRetInfo(this.ast); // Add this function to outer context.scope if (id) { fn = context.env.scope.register({ value: id.name, type: voidTypeReturn ? 'void' : 'i64' }); } else { throw Error('Do not support function name null yet!!') } // Copy outer env.scope so parameter mappings aren't exposed in outer env.scope. const childEnv = context.env.copy(); // Pass childEnv in for reference when body is compiled. const resultNamePointer: LLVMNamePointer = childEnv.scope.symbol() childEnv.tailCallTree.push(fn.value); const safeParams: LLVMNamePointer[] = params.map((param: ESTree.Pattern) => { if (param.type === NodeTypes.Identifier) { // Store parameter mapped to associated local return childEnv.scope.register(param.name); } else { throw Error('[llvmCompile]: Unknown param type ' + param.type) } }); context.emit( 0, `define ${fn.type} @${fn.value}(${safeParams .map((p: LLVMNamePointer) => `${p.type} %${p.value}`) .join(', ')}) {`, ); new BlockStatement(body).llvmCompile({ ...context, env: childEnv }, resultNamePointer) !hasReturnStatement && context.emit(1, `ret void`); // moved to ReturnStatement compile context.emit(0, '}\n'); } } /** * statement which contains blockStatement evaluate should return boolean * to skip latter evaluation when encounter return interruption */ export function dispatchStatementEvaluation(statement: ESTree.Statement, context: Context): boolean { switch (statement.type) { case NodeTypes.ExpressionStatement: new ExpressionStatement(statement).evaluate(context); break; case NodeTypes.FunctionDeclaration: new FunctionDeclaration(statement).evaluate(context); break; case NodeTypes.VariableDeclaration: new VariableDeclaration(statement).evaluate(context); break; case NodeTypes.WhileStatement: return new WhileStatement(statement).evaluate(context) case NodeTypes.IfStatement: return new IfStatement(statement).evaluate(context) case NodeTypes.ReturnStatement: return new ReturnStatement(statement).evaluate(context) case NodeTypes.BlockStatement: return new BlockStatement(statement).evaluate(context) default: throw Error('Unknown statement ' + statement.type) } return true; } export function dispatchStatementCompile(statement: ESTree.Statement, context: X86Context, depth: number = 0): boolean { switch (statement.type) { case NodeTypes.ExpressionStatement: new ExpressionStatement(statement).compile(context, depth); break; case NodeTypes.FunctionDeclaration: new FunctionDeclaration(statement).compile(context, depth); break; // case NodeTypes.VariableDeclaration: new VariableDeclaration(statement).evaluate(context); break; // case NodeTypes.WhileStatement: return new WhileStatement(statement).evaluate(context) case NodeTypes.IfStatement: return new IfStatement(statement).compile(context, depth); case NodeTypes.ReturnStatement: return new ReturnStatement(statement).compile(context, depth); case NodeTypes.BlockStatement: return new BlockStatement(statement).compile(context, depth); default: throw Error('Unknown statement ' + statement.type) } return true; } export function dispathStatementLLVMCompile(statement: ESTree.Statement, context: LLVMContext, namePointer: LLVMNamePointer): boolean { switch (statement.type) { case NodeTypes.ExpressionStatement: new ExpressionStatement(statement).llvmCompile(context, namePointer); break; case NodeTypes.FunctionDeclaration: new FunctionDeclaration(statement).llvmCompile(context, namePointer); break; // case NodeTypes.VariableDeclaration: new VariableDeclaration(statement).evaluate(context); break; // case NodeTypes.WhileStatement: return new WhileStatement(statement).evaluate(context) case NodeTypes.IfStatement: return new IfStatement(statement).llvmCompile(context, namePointer); case NodeTypes.ReturnStatement: return new ReturnStatement(statement).llvmCompile(context, namePointer); case NodeTypes.BlockStatement: return new BlockStatement(statement).llvmCompile(context, namePointer); default: throw Error('Unknown statement ' + statement.type) } return true; }
the_stack
import React from "react"; import {render, fireEvent, cleanup, wait} from "@testing-library/react"; import CreateEditStep from "./create-edit-step"; import data from "../../../assets/mock-data/curation/create-edit-step.data"; import axiosMock from "axios"; import {stringSearchResponse} from "../../../assets/mock-data/explore/facet-props"; import {SecurityTooltips, CommonStepTooltips} from "../../../config/tooltips.config"; jest.mock("axios"); describe("Create Edit Step Dialog component", () => { afterEach(() => { cleanup(); jest.clearAllMocks(); }); test("Verify Edit Merging dialog renders correctly for a read only user", () => { const {getByText, getByPlaceholderText, getByLabelText} = render( <CreateEditStep {...data.editMerging} canReadWrite={false} /> ); const stepName = getByPlaceholderText("Enter name"); const description = getByPlaceholderText("Enter description"); const collection = getByLabelText("Collection"); const timestamp = getByPlaceholderText("Enter path to the timestamp"); expect(stepName).toHaveValue("mergeCustomers"); expect(stepName).toBeDisabled(); expect(description).toHaveValue("merge customer description"); expect(description).toBeDisabled(); expect(collection).toBeChecked(); expect(collection).toBeDisabled(); expect(getByLabelText("Query")).toBeDisabled(); const collInput = document.querySelector(("#collList .ant-input")); expect(collInput).toBeDisabled(); expect(timestamp).toHaveValue("/envelope/headers/createdOn"); expect(timestamp).toBeDisabled(); fireEvent.mouseOver(getByText("Save")); wait(() => expect(getByText(SecurityTooltips.missingPermission)).toBeInTheDocument()); expect(getByText("Save")).toBeDisabled(); expect(getByText("Cancel")).toBeEnabled(); }); test("Verify New Merging Dialog renders ", () => { const {getByText, getByLabelText, getByPlaceholderText} = render( <CreateEditStep {...data.newMerging} /> ); expect(getByPlaceholderText("Enter name")).toBeInTheDocument(); expect(getByPlaceholderText("Enter description")).toBeInTheDocument(); expect(getByLabelText("Collection")).toBeInTheDocument(); expect(getByLabelText("Query")).toBeInTheDocument(); expect(getByLabelText("collection-input")).toBeInTheDocument(); expect(getByPlaceholderText("Enter path to the timestamp")).toBeInTheDocument(); expect(getByText("Save")).toBeEnabled(); expect(getByText("Cancel")).toBeEnabled(); //Collection radio button should be selected by default expect(getByLabelText("Collection")).toBeChecked(); }); test("Verify save button is always enabled and error messaging appears as needed", async () => { const {getByText, getByPlaceholderText, queryByText} = render(<CreateEditStep {...data.newMerging} />); const nameInput = getByPlaceholderText("Enter name"); const saveButton = getByText("Save"); expect(saveButton).toBeEnabled(); // button should be enabled without any input fireEvent.change(nameInput, {target: {value: "testCreateMerging"}}); expect(nameInput).toHaveValue("testCreateMerging"); expect(saveButton).toBeEnabled(); //verify validation on name field //proper error message shows when field is empty fireEvent.change(nameInput, {target: {value: ""}}); expect(getByText("Name is required")).toBeInTheDocument(); //proper error message shows when field does not lead with a letter fireEvent.change(nameInput, {target: {value: "123testCreateStep"}}); expect(getByText("Names must start with a letter and can contain letters, numbers, hyphens, and underscores only.")).toBeInTheDocument(); //reset name field fireEvent.change(nameInput, {target: {value: ""}}); expect(getByText("Name is required")).toBeInTheDocument(); //proper error message shows when field contains special characters fireEvent.change(nameInput, {target: {value: "test Create Step"}}); expect(getByText("Names must start with a letter and can contain letters, numbers, hyphens, and underscores only.")).toBeInTheDocument(); //reset name field fireEvent.change(nameInput, {target: {value: ""}}); expect(getByText("Name is required")).toBeInTheDocument(); //enter in a valid name and verify error message disappears (test hyphen and underscores are allowed) fireEvent.change(nameInput, {target: {value: "test-Create-Step__"}}); await wait(() => { expect(queryByText("Name is required")).toBeNull(); expect(queryByText("Names must start with a letter and can contain letters, numbers, hyphens, and underscores only.")).toBeNull(); }); expect(saveButton).toBeEnabled(); }); test("Verify Save button requires all mandatory fields", async () => { const {getByText, getByPlaceholderText} = render(<CreateEditStep {...data.newMerging} />); const nameInput = getByPlaceholderText("Enter name"); const collInput = document.querySelector(("#collList .ant-input")); // click save without any input fireEvent.click(getByText("Save")); // both messages should show when both boxes are empty expect(getByText("Name is required")).toBeInTheDocument(); expect(getByText("Collection or Query is required")).toBeInTheDocument(); // enter name only fireEvent.change(nameInput, {target: {value: "testCreateMap"}}); expect(nameInput).toHaveValue("testCreateMap"); fireEvent.click(getByText("Save")); // error message for name should not appear expect(getByText("Collection or Query is required")).toBeInTheDocument(); // clear name and enter collection only fireEvent.change(nameInput, {target: {value: ""}}); await wait(() => { if (collInput) { fireEvent.change(collInput, {target: {value: "testCollection"}}); } }); expect(collInput).toHaveValue("testCollection"); fireEvent.click(getByText("Save")); // error message for empty collection should not appear expect(getByText("Name is required")).toBeInTheDocument(); }); test("Verify able to type in input fields and typeahead search in collections field", async () => { axiosMock.post["mockImplementationOnce"](jest.fn(() => Promise.resolve({status: 200, data: stringSearchResponse}))); const {getByText, getByLabelText, getByPlaceholderText} = render(<CreateEditStep {...data.newMerging} />); const descInput = getByPlaceholderText("Enter description"); const collInput = document.querySelector(("#collList .ant-input")); const saveButton = getByText("Save"); saveButton.onclick = jest.fn(); fireEvent.change(descInput, {target: {value: "test description"}}); expect(descInput).toHaveValue("test description"); await wait(() => { if (collInput) { fireEvent.change(collInput, {target: {value: "ada"}}); } }); let url = "/api/entitySearch/facet-values?database=final"; let payload = { "referenceType": "collection", "entityTypeId": " ", "propertyPath": " ", "limit": 10, "dataType": "string", "pattern": "ada" }; expect(axiosMock.post).toHaveBeenCalledWith(url, payload); expect(axiosMock.post).toHaveBeenCalledTimes(1); expect(getByText("Adams Cole")).toBeInTheDocument(); await wait(() => { if (collInput) { fireEvent.change(collInput, {target: {value: "testCollection"}}); } }); expect(collInput).toHaveValue("testCollection"); fireEvent.click(getByLabelText("Query")); const queryInput = getByPlaceholderText("Enter source query"); fireEvent.change(queryInput, {target: {value: "cts.collectionQuery([\"testCollection\"])"}}); expect(queryInput).toHaveTextContent("cts.collectionQuery([\"testCollection\"])"); fireEvent.click(saveButton); expect(saveButton.onclick).toHaveBeenCalled(); }); test("Verify able to type in input fields and typeahead search in collections field", async () => { axiosMock.post["mockImplementationOnce"](jest.fn(() => Promise.resolve({status: 200, data: stringSearchResponse}))); const {getByText, getByLabelText, getByPlaceholderText} = render(<CreateEditStep {...data.newMerging} />); const descInput = getByPlaceholderText("Enter description"); const collInput = document.querySelector(("#collList .ant-input")); const timestampInput = getByPlaceholderText("Enter path to the timestamp"); const saveButton = getByText("Save"); saveButton.onclick = jest.fn(); fireEvent.change(descInput, {target: {value: "test description"}}); expect(descInput).toHaveValue("test description"); await wait(() => { if (collInput) { fireEvent.change(collInput, {target: {value: "ada"}}); } }); let url = "/api/entitySearch/facet-values?database=final"; let payload = { "referenceType": "collection", "entityTypeId": " ", "propertyPath": " ", "limit": 10, "dataType": "string", "pattern": "ada" }; expect(axiosMock.post).toHaveBeenCalledWith(url, payload); expect(axiosMock.post).toHaveBeenCalledTimes(1); expect(getByText("Adams Cole")).toBeInTheDocument(); await wait(() => { if (collInput) { fireEvent.change(collInput, {target: {value: "testCollection"}}); } }); expect(collInput).toHaveValue("testCollection"); fireEvent.click(getByLabelText("Query")); const queryInput = getByPlaceholderText("Enter source query"); fireEvent.change(queryInput, {target: {value: "cts.collectionQuery([\"testCollection\"])"}}); expect(queryInput).toHaveTextContent("cts.collectionQuery([\"testCollection\"])"); fireEvent.change(timestampInput, {target: {value: "/test/path/to/timestamp"}}); expect(timestampInput).toHaveValue("/test/path/to/timestamp"); fireEvent.click(saveButton); expect(saveButton.onclick).toHaveBeenCalled(); }); test("Verify Edit Merging dialog renders correctly", () => { const {getByText, getByPlaceholderText, getByLabelText} = render(<CreateEditStep {...data.editMerging} />); expect(getByPlaceholderText("Enter name")).toHaveValue("mergeCustomers"); expect(getByPlaceholderText("Enter name")).toBeDisabled(); expect(getByPlaceholderText("Enter description")).toHaveValue("merge customer description"); expect(getByLabelText("Collection")).toBeChecked(); const collInput = document.querySelector(("#collList .ant-input")); expect(collInput).toHaveValue("matchCustomers"); fireEvent.click(getByLabelText("Query")); expect(getByPlaceholderText("Enter source query")).toHaveTextContent("cts.collectionQuery(['matchCustomers'])"); expect(getByPlaceholderText("Enter path to the timestamp")).toHaveValue("/envelope/headers/createdOn"); expect(getByText("Save")).toBeEnabled(); expect(getByText("Cancel")).toBeEnabled(); fireEvent.click(getByLabelText("Collection")); fireEvent.click(getByText("Save")); expect(data.editMerging.updateStepArtifact).toBeCalledWith({ name: "mergeCustomers", targetEntityType: "Customer", description: "merge customer description", collection: "matchCustomers", selectedSource: "collection", sourceQuery: "cts.collectionQuery(['matchCustomers'])", timestamp: "/envelope/headers/createdOn" }); }); test("Verify collection and query tooltips appear when hovered", () => { const {getByText, getByTestId} = render(<CreateEditStep {...data.editMerging} />); fireEvent.mouseOver(getByTestId("collectionTooltip")); wait(() => expect(getByText(CommonStepTooltips.radioCollection)).toBeInTheDocument()); fireEvent.mouseOver(getByTestId("queryTooltip")); wait(() => expect(getByText(CommonStepTooltips.radioQuery)).toBeInTheDocument()); }); });
the_stack
import {expect} from '@loopback/testlab'; import * as types from '../../../'; describe('types', () => { describe('string', () => { const stringType = new types.StringType(); it('checks isInstance', () => { expect(stringType.isInstance('str')).to.be.true(); expect(stringType.isInstance(null)).to.be.true(); expect(stringType.isInstance(undefined)).to.be.true(); expect(stringType.isInstance(true)).to.be.false(); expect(stringType.isInstance({x: 1})).to.be.false(); expect(stringType.isInstance([1, 2])).to.be.false(); expect(stringType.isInstance(1)).to.be.false(); expect(stringType.isInstance(new Date())).to.be.false(); }); it('checks isCoercible', () => { expect(stringType.isCoercible('str')).to.be.true(); expect(stringType.isCoercible(null)).to.be.true(); expect(stringType.isCoercible(undefined)).to.be.true(); expect(stringType.isCoercible(true)).to.be.true(); expect(stringType.isCoercible({x: 1})).to.be.true(); expect(stringType.isCoercible(1)).to.be.true(); expect(stringType.isCoercible(new Date())).to.be.true(); }); it('creates defaultValue', () => { expect(stringType.defaultValue()).to.be.equal(''); }); it('coerces values', () => { expect(stringType.coerce('str')).to.equal('str'); expect(stringType.coerce(null)).to.equal(null); expect(stringType.coerce(undefined)).to.equal(undefined); expect(stringType.coerce(true)).to.equal('true'); expect(stringType.coerce({x: 1})).to.equal('{"x":1}'); expect(stringType.coerce([1, '2'])).to.equal('[1,"2"]'); expect(stringType.coerce(1)).to.equal('1'); const date = new Date(); expect(stringType.coerce(date)).to.equal(date.toJSON()); }); it('serializes values', () => { expect(stringType.serialize('str')).to.eql('str'); expect(stringType.serialize(null)).null(); expect(stringType.serialize(undefined)).undefined(); }); }); describe('boolean', () => { const booleanType = new types.BooleanType(); it('checks isInstance', () => { expect(booleanType.isInstance('str')).to.be.false(); expect(booleanType.isInstance(null)).to.be.true(); expect(booleanType.isInstance(undefined)).to.be.true(); expect(booleanType.isInstance(true)).to.be.true(); expect(booleanType.isInstance(false)).to.be.true(); expect(booleanType.isInstance({x: 1})).to.be.false(); expect(booleanType.isInstance([1, 2])).to.be.false(); expect(booleanType.isInstance(1)).to.be.false(); expect(booleanType.isInstance(new Date())).to.be.false(); }); it('checks isCoercible', () => { expect(booleanType.isCoercible('str')).to.be.true(); expect(booleanType.isCoercible(null)).to.be.true(); expect(booleanType.isCoercible(undefined)).to.be.true(); expect(booleanType.isCoercible(true)).to.be.true(); expect(booleanType.isCoercible({x: 1})).to.be.true(); expect(booleanType.isCoercible(1)).to.be.true(); expect(booleanType.isCoercible(new Date())).to.be.true(); }); it('creates defaultValue', () => { expect(booleanType.defaultValue()).to.be.equal(false); }); it('coerces values', () => { expect(booleanType.coerce('str')).to.equal(true); expect(booleanType.coerce(null)).to.equal(null); expect(booleanType.coerce(undefined)).to.equal(undefined); expect(booleanType.coerce(true)).to.equal(true); expect(booleanType.coerce(false)).to.equal(false); expect(booleanType.coerce({x: 1})).to.equal(true); expect(booleanType.coerce([1, '2'])).to.equal(true); expect(booleanType.coerce('')).to.equal(false); expect(booleanType.coerce('true')).to.equal(true); // string 'false' is boolean true expect(booleanType.coerce('false')).to.equal(true); expect(booleanType.coerce(0)).to.equal(false); expect(booleanType.coerce(1)).to.equal(true); const date = new Date(); expect(booleanType.coerce(date)).to.equal(true); }); it('serializes values', () => { expect(booleanType.serialize(true)).to.eql(true); expect(booleanType.serialize(false)).to.eql(false); expect(booleanType.serialize(null)).null(); expect(booleanType.serialize(undefined)).undefined(); }); }); describe('number', () => { const numberType = new types.NumberType(); it('checks isInstance', () => { expect(numberType.isInstance('str')).to.be.false(); expect(numberType.isInstance(null)).to.be.true(); expect(numberType.isInstance(undefined)).to.be.true(); expect(numberType.isInstance(NaN)).to.be.false(); expect(numberType.isInstance(true)).to.be.false(); expect(numberType.isInstance({x: 1})).to.be.false(); expect(numberType.isInstance([1, 2])).to.be.false(); expect(numberType.isInstance(1)).to.be.true(); expect(numberType.isInstance(1.1)).to.be.true(); expect(numberType.isInstance(new Date())).to.be.false(); }); it('checks isCoercible', () => { expect(numberType.isCoercible('str')).to.be.false(); expect(numberType.isCoercible('1')).to.be.true(); expect(numberType.isCoercible('1.1')).to.be.true(); expect(numberType.isCoercible(null)).to.be.true(); expect(numberType.isCoercible(undefined)).to.be.true(); expect(numberType.isCoercible(true)).to.be.true(); expect(numberType.isCoercible(false)).to.be.true(); expect(numberType.isCoercible({x: 1})).to.be.false(); expect(numberType.isCoercible(1)).to.be.true(); expect(numberType.isCoercible(1.1)).to.be.true(); // Date can be converted to number expect(numberType.isCoercible(new Date())).to.be.true(); }); it('creates defaultValue', () => { expect(numberType.defaultValue()).to.be.equal(0); }); it('coerces values', () => { expect(() => numberType.coerce('str')).to.throw(/Invalid number/); expect(numberType.coerce('1')).to.equal(1); expect(numberType.coerce('1.1')).to.equal(1.1); expect(numberType.coerce(null)).to.equal(null); expect(numberType.coerce(undefined)).to.equal(undefined); expect(numberType.coerce(true)).to.equal(1); expect(numberType.coerce(false)).to.equal(0); expect(() => numberType.coerce({x: 1})).to.throw(/Invalid number/); expect(() => numberType.coerce([1, '2'])).to.throw(/Invalid number/); expect(numberType.coerce(1)).to.equal(1); expect(numberType.coerce(1.1)).to.equal(1.1); const date = new Date(); expect(numberType.coerce(date)).to.equal(date.getTime()); }); it('serializes values', () => { expect(numberType.serialize(1)).to.eql(1); expect(numberType.serialize(1.1)).to.eql(1.1); expect(numberType.serialize(null)).null(); expect(numberType.serialize(undefined)).undefined(); }); }); describe('date', () => { const dateType = new types.DateType(); it('checks isInstance', () => { expect(dateType.isInstance('str')).to.be.false(); expect(dateType.isInstance(null)).to.be.true(); expect(dateType.isInstance(undefined)).to.be.true(); expect(dateType.isInstance(NaN)).to.be.false(); expect(dateType.isInstance(true)).to.be.false(); expect(dateType.isInstance({x: 1})).to.be.false(); expect(dateType.isInstance([1, 2])).to.be.false(); expect(dateType.isInstance(1)).to.be.false(); expect(dateType.isInstance(1.1)).to.be.false(); expect(dateType.isInstance(new Date())).to.be.true(); }); it('checks isCoercible', () => { expect(dateType.isCoercible('str')).to.be.false(); expect(dateType.isCoercible('1')).to.be.true(); expect(dateType.isCoercible('1.1')).to.be.true(); expect(dateType.isCoercible(null)).to.be.true(); expect(dateType.isCoercible(undefined)).to.be.true(); expect(dateType.isCoercible(true)).to.be.true(); expect(dateType.isCoercible(false)).to.be.true(); expect(dateType.isCoercible({x: 1})).to.be.false(); expect(dateType.isCoercible(1)).to.be.true(); expect(dateType.isCoercible(1.1)).to.be.true(); // Date can be converted to number expect(dateType.isCoercible(new Date())).to.be.true(); }); it('creates defaultValue', () => { const d = new Date(); const v = dateType.defaultValue(); expect(v.getTime()).to.aboveOrEqual(d.getTime()); expect(v.getTime()).to.approximately(d.getTime(), 50); }); it('coerces values', () => { expect(() => dateType.coerce('str')).to.throw(/Invalid date/); // '1' will be parsed as local 2001-01-01 expect(dateType.coerce('1')).to.eql(new Date('01/01/2001')); // '1.1' will be parsed as local 2001-01-01 expect(dateType.coerce('1.1')).to.eql(new Date('01/01/2001')); expect(dateType.coerce(null)).to.equal(null); expect(dateType.coerce(undefined)).to.equal(undefined); expect(dateType.coerce(true)).to.eql(new Date(1)); expect(dateType.coerce(false)).to.eql(new Date(0)); expect(() => dateType.coerce({x: 1})).to.throw(/Invalid date/); expect(dateType.coerce([1, '2'])).to.eql(new Date('01/02/2001')); expect(dateType.coerce(1)).to.eql(new Date('1970-01-01T00:00:00.001Z')); expect(dateType.coerce(1.1)).to.eql(new Date('1970-01-01T00:00:00.001Z')); const date = new Date(); expect(dateType.coerce(date)).to.equal(date); }); it('serializes values', () => { const date = new Date(); expect(dateType.serialize(date)).to.eql(date.toJSON()); expect(dateType.serialize(null)).null(); expect(dateType.serialize(undefined)).undefined(); }); }); describe('buffer', () => { const bufferType = new types.BufferType(); it('checks isInstance', () => { expect(bufferType.isInstance(Buffer.from([1]))).to.be.true(); expect(bufferType.isInstance(Buffer.from('123'))).to.be.true(); expect(bufferType.isInstance('str')).to.be.false(); expect(bufferType.isInstance(null)).to.be.true(); expect(bufferType.isInstance(undefined)).to.be.true(); expect(bufferType.isInstance(true)).to.be.false(); expect(bufferType.isInstance({x: 1})).to.be.false(); expect(bufferType.isInstance([1, 2])).to.be.false(); expect(bufferType.isInstance(1)).to.be.false(); expect(bufferType.isInstance(new Date())).to.be.false(); expect(bufferType.isInstance([1])).to.be.false(); }); it('checks isCoercible', () => { expect(bufferType.isCoercible('str')).to.be.true(); expect(bufferType.isCoercible(null)).to.be.true(); expect(bufferType.isCoercible(undefined)).to.be.true(); expect(bufferType.isCoercible(Buffer.from('12'))).to.be.true(); expect(bufferType.isCoercible([1, 2])).to.be.true(); expect(bufferType.isCoercible({x: 1})).to.be.false(); expect(bufferType.isCoercible(1)).to.be.false(); expect(bufferType.isCoercible(new Date())).to.be.false(); }); it('creates defaultValue', () => { expect(bufferType.defaultValue().equals(Buffer.from([]))).to.be.true(); }); it('coerces values', () => { expect(bufferType.coerce('str').equals(Buffer.from('str'))).to.be.true(); expect(bufferType.coerce([1]).equals(Buffer.from([1]))).to.be.true(); expect(bufferType.coerce(null)).to.equal(null); expect(bufferType.coerce(undefined)).to.equal(undefined); const buf = Buffer.from('12'); expect(bufferType.coerce(buf)).exactly(buf); expect(() => bufferType.coerce(1)).to.throw(/Invalid buffer/); expect(() => bufferType.coerce(new Date())).to.throw(/Invalid buffer/); expect(() => bufferType.coerce(true)).to.throw(/Invalid buffer/); expect(() => bufferType.coerce(false)).to.throw(/Invalid buffer/); }); it('serializes values', () => { expect( bufferType.serialize(Buffer.from('str'), {encoding: 'utf-8'}), ).to.eql('str'); expect(bufferType.serialize(Buffer.from('str'))).to.eql('c3Ry'); expect(bufferType.serialize(null)).null(); expect(bufferType.serialize(undefined)).undefined(); }); }); describe('any', () => { const anyType = new types.AnyType(); it('checks isInstance', () => { expect(anyType.isInstance('str')).to.be.true(); expect(anyType.isInstance(null)).to.be.true(); expect(anyType.isInstance(undefined)).to.be.true(); expect(anyType.isInstance(true)).to.be.true(); expect(anyType.isInstance({x: 1})).to.be.true(); expect(anyType.isInstance([1, 2])).to.be.true(); expect(anyType.isInstance(1)).to.be.true(); expect(anyType.isInstance(new Date())).to.be.true(); expect(anyType.isInstance(Buffer.from('123'))).to.be.true(); }); it('checks isCoercible', () => { expect(anyType.isCoercible('str')).to.be.true(); expect(anyType.isCoercible(null)).to.be.true(); expect(anyType.isCoercible(undefined)).to.be.true(); expect(anyType.isCoercible(true)).to.be.true(); expect(anyType.isCoercible({x: 1})).to.be.true(); expect(anyType.isCoercible(1)).to.be.true(); expect(anyType.isCoercible([1, '2'])).to.be.true(); expect(anyType.isCoercible(new Date())).to.be.true(); expect(anyType.isCoercible(Buffer.from('123'))).to.be.true(); }); it('creates defaultValue', () => { expect(anyType.defaultValue()).to.equal(undefined); }); it('coerces values', () => { expect(anyType.coerce('str')).to.equal('str'); expect(anyType.coerce(null)).to.equal(null); expect(anyType.coerce(undefined)).to.equal(undefined); expect(anyType.coerce(true)).to.equal(true); const obj = {x: 1}; expect(anyType.coerce(obj)).to.equal(obj); const arr = [1, '2']; expect(anyType.coerce(arr)).to.equal(arr); expect(anyType.coerce(1)).to.equal(1); const date = new Date(); expect(anyType.coerce(date)).to.equal(date); const buf = Buffer.from('12'); expect(anyType.coerce(buf)).to.equal(buf); }); it('serializes values', () => { expect(anyType.serialize('str')).to.eql('str'); expect(anyType.serialize(1)).to.eql(1); expect(anyType.serialize([1, '2'])).to.eql([1, '2']); expect(anyType.serialize(null)).null(); expect(anyType.serialize(undefined)).undefined(); const date = new Date(); expect(anyType.serialize(date)).to.eql(date.toJSON()); const obj = {x: 1}; expect(anyType.serialize(obj)).to.eql(obj); const json = { x: 1, y: 2, toJSON() { return {a: json.x + json.y}; }, }; expect(anyType.serialize(json)).to.eql({a: 3}); }); }); describe('null', () => { const nullType = new types.NullType(); it('checks isInstance', () => { expect(nullType.isInstance('str')).to.be.false(); expect(nullType.isInstance(null)).to.be.true(); expect(nullType.isInstance(undefined)).to.be.false(); expect(nullType.isInstance(true)).to.be.false(); expect(nullType.isInstance(false)).to.be.false(); expect(nullType.isInstance({x: 1})).to.be.false(); expect(nullType.isInstance([1, 2])).to.be.false(); expect(nullType.isInstance(1)).to.be.false(); expect(nullType.isInstance(new Date())).to.be.false(); }); it('checks isCoercible', () => { expect(nullType.isCoercible('str')).to.be.false(); expect(nullType.isCoercible(null)).to.be.true(); expect(nullType.isCoercible(undefined)).to.be.true(); expect(nullType.isCoercible(true)).to.be.false(); expect(nullType.isCoercible({x: 1})).to.be.false(); expect(nullType.isCoercible(1)).to.be.false(); expect(nullType.isCoercible(new Date())).to.be.false(); }); it('creates defaultValue', () => { expect(nullType.defaultValue()).to.be.null(); }); it('coerces values', () => { expect(nullType.coerce(null)).to.null(); expect(nullType.coerce(undefined)).to.null(); }); it('serializes values', () => { expect(nullType.serialize(null)).null(); expect(nullType.serialize(undefined)).null(); }); }); describe('array', () => { const stringType = new types.StringType(); const arrayType = new types.ArrayType(stringType); it('checks isInstance', () => { expect(arrayType.isInstance('str')).to.be.false(); expect(arrayType.isInstance(null)).to.be.true(); expect(arrayType.isInstance(undefined)).to.be.true(); expect(arrayType.isInstance(NaN)).to.be.false(); expect(arrayType.isInstance(true)).to.be.false(); expect(arrayType.isInstance({x: 1})).to.be.false(); expect(arrayType.isInstance([1, 2])).to.be.false(); expect(arrayType.isInstance([1, '2'])).to.be.false(); expect(arrayType.isInstance(['1'])).to.be.true(); expect(arrayType.isInstance(['1', 'a'])).to.be.true(); expect(arrayType.isInstance(['1', 'a', null])).to.be.true(); expect(arrayType.isInstance(['1', 'a', undefined])).to.be.true(); expect(arrayType.isInstance([])).to.be.true(); expect(arrayType.isInstance(1)).to.be.false(); expect(arrayType.isInstance(1.1)).to.be.false(); expect(arrayType.isInstance(new Date())).to.be.false(); }); it('checks isCoercible', () => { expect(arrayType.isCoercible('str')).to.be.false(); expect(arrayType.isCoercible('1')).to.be.false(); expect(arrayType.isCoercible('1.1')).to.be.false(); expect(arrayType.isCoercible(null)).to.be.true(); expect(arrayType.isCoercible(undefined)).to.be.true(); expect(arrayType.isCoercible(true)).to.be.false(); expect(arrayType.isCoercible(false)).to.be.false(); expect(arrayType.isCoercible({x: 1})).to.be.false(); expect(arrayType.isCoercible(1)).to.be.false(); expect(arrayType.isCoercible(1.1)).to.be.false(); expect(arrayType.isCoercible(new Date())).to.be.false(); expect(arrayType.isCoercible([])).to.be.true(); expect(arrayType.isCoercible(['1'])).to.be.true(); expect(arrayType.isCoercible(['1', 2])).to.be.true(); }); it('creates defaultValue', () => { expect(arrayType.defaultValue()).to.be.eql([]); }); it('coerces values', () => { expect(() => arrayType.coerce('str')).to.throw(/Invalid array/); expect(() => arrayType.coerce('1')).to.throw(/Invalid array/); expect(() => arrayType.coerce('1.1')).to.throw(/Invalid array/); expect(arrayType.coerce(null)).to.equal(null); expect(arrayType.coerce(undefined)).to.equal(undefined); expect(() => arrayType.coerce(true)).to.throw(/Invalid array/); expect(() => arrayType.coerce(false)).to.throw(/Invalid array/); expect(() => arrayType.coerce({x: 1})).to.throw(/Invalid array/); expect(() => arrayType.coerce(1)).to.throw(/Invalid array/); const date = new Date(); expect(() => arrayType.coerce(date)).to.throw(/Invalid array/); expect(arrayType.coerce([1, '2'])).to.eql(['1', '2']); expect(arrayType.coerce(['2'])).to.eql(['2']); expect(arrayType.coerce([null, undefined, '2'])).to.eql([ null, undefined, '2', ]); expect(arrayType.coerce([true, '2'])).to.eql(['true', '2']); expect(arrayType.coerce([false, '2'])).to.eql(['false', '2']); expect(arrayType.coerce([date])).to.eql([date.toJSON()]); }); it('serializes values', () => { expect(arrayType.serialize(['a'])).to.eql(['a']); expect(arrayType.serialize(null)).null(); expect(arrayType.serialize(undefined)).undefined(); }); }); describe('union', () => { const numberType = new types.NumberType(); const booleanType = new types.BooleanType(); const unionType = new types.UnionType([numberType, booleanType]); it('checks isInstance', () => { expect(unionType.isInstance('str')).to.be.false(); expect(unionType.isInstance(null)).to.be.true(); expect(unionType.isInstance(undefined)).to.be.true(); expect(unionType.isInstance(NaN)).to.be.false(); expect(unionType.isInstance(true)).to.be.true(); expect(unionType.isInstance({x: 1})).to.be.false(); expect(unionType.isInstance([1, 2])).to.be.false(); expect(unionType.isInstance(1)).to.be.true(); expect(unionType.isInstance(1.1)).to.be.true(); expect(unionType.isInstance(new Date())).to.be.false(); }); it('checks isCoercible', () => { expect(unionType.isCoercible('str')).to.be.true(); expect(unionType.isCoercible('1')).to.be.true(); expect(unionType.isCoercible('1.1')).to.be.true(); expect(unionType.isCoercible(null)).to.be.true(); expect(unionType.isCoercible(undefined)).to.be.true(); expect(unionType.isCoercible(true)).to.be.true(); expect(unionType.isCoercible(false)).to.be.true(); expect(unionType.isCoercible({x: 1})).to.be.true(); expect(unionType.isCoercible(1)).to.be.true(); expect(unionType.isCoercible(1.1)).to.be.true(); // Date can be converted to number expect(unionType.isCoercible(new Date())).to.be.true(); }); it('creates defaultValue', () => { expect(unionType.defaultValue()).to.be.equal(0); }); it('coerces values', () => { expect(unionType.coerce('str')).to.equal(true); expect(unionType.coerce('1')).to.equal(1); expect(unionType.coerce('1.1')).to.equal(1.1); expect(unionType.coerce(null)).to.equal(null); expect(unionType.coerce(undefined)).to.equal(undefined); expect(unionType.coerce(true)).to.equal(true); expect(unionType.coerce(false)).to.equal(false); expect(unionType.coerce({x: 1})).to.equal(true); expect(unionType.coerce([1, '2'])).to.equal(true); expect(unionType.coerce(1)).to.equal(1); expect(unionType.coerce(1.1)).to.equal(1.1); const date = new Date(); expect(unionType.coerce(date)).to.equal(date.getTime()); // Create a new union type to test invalid value const dateType = new types.DateType(); const numberOrDateType = new types.UnionType([numberType, dateType]); expect(() => numberOrDateType.coerce('str')).to.throw(/Invalid union/); }); it('serializes values', () => { expect(unionType.serialize(1)).to.equal(1); expect(unionType.serialize(1.1)).to.equal(1.1); expect(unionType.serialize(true)).to.equal(true); expect(unionType.serialize(false)).to.equal(false); expect(unionType.serialize(null)).null(); expect(unionType.serialize(undefined)).undefined(); }); }); describe('model', () => { class Address extends types.ValueObject { street: string; city: string; zipCode: string; } class Customer extends types.Entity { id: string; email: string; address: Address; constructor(data?: types.AnyObject) { super(); if (data != null) { this.id = data.id; this.email = data.email; this.address = data.address; } } } const modelType = new types.ModelType(Customer); it('checks isInstance', () => { expect(modelType.isInstance('str')).to.be.false(); expect(modelType.isInstance(null)).to.be.true(); expect(modelType.isInstance(undefined)).to.be.true(); expect(modelType.isInstance(NaN)).to.be.false(); expect(modelType.isInstance(true)).to.be.false(); expect(modelType.isInstance({id: 'c1'})).to.be.false(); expect(modelType.isInstance([1, 2])).to.be.false(); expect(modelType.isInstance(1)).to.be.false(); expect(modelType.isInstance(1.1)).to.be.false(); expect(modelType.isInstance(new Customer())).to.be.true(); }); it('checks isCoercible', () => { expect(modelType.isCoercible('str')).to.be.false(); expect(modelType.isCoercible('1')).to.be.false(); expect(modelType.isCoercible('1.1')).to.be.false(); expect(modelType.isCoercible(null)).to.be.true(); expect(modelType.isCoercible(undefined)).to.be.true(); expect(modelType.isCoercible(true)).to.be.false(); expect(modelType.isCoercible(false)).to.be.false(); expect(modelType.isCoercible({x: 1})).to.be.true(); expect(modelType.isCoercible(1)).to.be.false(); expect(modelType.isCoercible(1.1)).to.be.false(); expect(modelType.isCoercible([1])).to.be.false(); expect(modelType.isCoercible(new Customer())).to.be.true(); }); it('creates defaultValue', () => { const d = new Customer(); const v = modelType.defaultValue(); expect(d).to.be.eql(v); }); it('coerces values', () => { expect(() => modelType.coerce('str')).to.throw(/Invalid model/); expect(modelType.coerce(null)).to.equal(null); expect(modelType.coerce(undefined)).to.equal(undefined); expect(() => modelType.coerce(true)).to.throw(/Invalid model/); expect(() => modelType.coerce(false)).to.throw(/Invalid model/); expect(() => modelType.coerce(1)).to.throw(/Invalid model/); expect(() => modelType.coerce(1.1)).to.throw(/Invalid model/); expect(() => modelType.coerce([1, '2'])).to.throw(/Invalid model/); const customer = modelType.coerce({id: 'c1'}); expect(customer instanceof Customer).to.be.true(); }); it('serializes values', () => { const customer = new Customer({id: 'c1'}); expect(modelType.serialize(customer)).to.eql(customer.toJSON()); expect(modelType.serialize(null)).null(); expect(modelType.serialize(undefined)).undefined(); }); }); });
the_stack
import * as path from 'path'; import { checkFilesExist, isNotWindows, isWindows, newProject, readFile, readJson, removeProject, runCLI, runCLIAsync, uniq, updateFile, } from '@nrwl/e2e/utils'; import { classify } from '@nrwl/workspace/src/utils/strings'; let proj: string; beforeAll(() => { proj = newProject(); }); describe('format', () => { it('should check and reformat the code', async () => { if (isNotWindows()) { const myapp = uniq('myapp'); const mylib = uniq('mylib'); runCLI(`generate @nrwl/angular:app ${myapp}`); runCLI(`generate @nrwl/angular:lib ${mylib}`); updateFile( `apps/${myapp}/src/main.ts`, ` const x = 1111; ` ); updateFile( `apps/${myapp}/src/app/app.module.ts`, ` const y = 1111; ` ); updateFile( `apps/${myapp}/src/app/app.component.ts`, ` const z = 1111; ` ); updateFile( `libs/${mylib}/index.ts`, ` const x = 1111; ` ); updateFile( `libs/${mylib}/src/${mylib}.module.ts`, ` const y = 1111; ` ); updateFile( `README.md`, ` my new readme; ` ); let stdout = runCLI( `format:check --files="libs/${mylib}/index.ts,package.json" --libs-and-apps`, { silenceError: true } ); expect(stdout).toContain(path.normalize(`libs/${mylib}/index.ts`)); expect(stdout).toContain( path.normalize(`libs/${mylib}/src/${mylib}.module.ts`) ); expect(stdout).not.toContain(path.normalize(`README.md`)); // It will be contained only in case of exception, that we fallback to all stdout = runCLI(`format:check --all`, { silenceError: true }); expect(stdout).toContain(path.normalize(`apps/${myapp}/src/main.ts`)); expect(stdout).toContain( path.normalize(`apps/${myapp}/src/app/app.module.ts`) ); expect(stdout).toContain( path.normalize(`apps/${myapp}/src/app/app.component.ts`) ); stdout = runCLI(`format:check --projects=${myapp}`, { silenceError: true, }); expect(stdout).toContain(path.normalize(`apps/${myapp}/src/main.ts`)); expect(stdout).toContain( path.normalize(`apps/${myapp}/src/app/app.module.ts`) ); expect(stdout).toContain( path.normalize(`apps/${myapp}/src/app/app.component.ts`) ); expect(stdout).not.toContain(path.normalize(`libs/${mylib}/index.ts`)); expect(stdout).not.toContain( path.normalize(`libs/${mylib}/src/${mylib}.module.ts`) ); expect(stdout).not.toContain(path.normalize(`README.md`)); stdout = runCLI(`format:check --projects=${myapp},${mylib}`, { silenceError: true, }); expect(stdout).toContain(path.normalize(`apps/${myapp}/src/main.ts`)); expect(stdout).toContain( path.normalize(`apps/${myapp}/src/app/app.module.ts`) ); expect(stdout).toContain( path.normalize(`apps/${myapp}/src/app/app.component.ts`) ); expect(stdout).toContain(path.normalize(`libs/${mylib}/index.ts`)); expect(stdout).toContain( path.normalize(`libs/${mylib}/src/${mylib}.module.ts`) ); expect(stdout).not.toContain(path.normalize(`README.md`)); const { stderr } = await runCLIAsync( `format:check --projects=${myapp},${mylib} --all`, { silenceError: true, } ); expect(stderr).toContain( 'Arguments all and projects are mutually exclusive' ); runCLI( `format:write --files="apps/${myapp}/src/app/app.module.ts,apps/${myapp}/src/app/app.component.ts"` ); stdout = runCLI('format:check --all', { silenceError: true }); expect(stdout).toContain(path.normalize(`apps/${myapp}/src/main.ts`)); expect(stdout).not.toContain( path.normalize(`apps/${myapp}/src/app/app.module.ts`) ); expect(stdout).not.toContain( path.normalize(`apps/${myapp}/src/app/app.component.ts`) ); runCLI('format:write --all'); expect(runCLI('format:check --all')).not.toContain( path.normalize(`apps/${myapp}/src/main.ts`) ); } }, 90000); }); describe('dep-graph', () => { let proj: string; let myapp: string; let myapp2: string; let myapp3: string; let myappE2e: string; let myapp2E2e: string; let myapp3E2e: string; let mylib: string; let mylib2: string; beforeAll(() => { proj = newProject(); myapp = uniq('myapp'); myapp2 = uniq('myapp2'); myapp3 = uniq('myapp3'); myappE2e = `${myapp}-e2e`; myapp2E2e = `${myapp2}-e2e`; myapp3E2e = `${myapp3}-e2e`; mylib = uniq('mylib'); mylib2 = uniq('mylib2'); runCLI(`generate @nrwl/angular:app ${myapp}`); runCLI(`generate @nrwl/angular:app ${myapp2}`); runCLI(`generate @nrwl/angular:app ${myapp3}`); runCLI(`generate @nrwl/angular:lib ${mylib}`); runCLI(`generate @nrwl/angular:lib ${mylib2}`); updateFile( `apps/${myapp}/src/main.ts`, ` import '@${proj}/${mylib}'; const s = {loadChildren: '@${proj}/${mylib2}'}; ` ); updateFile( `apps/${myapp2}/src/app/app.component.spec.ts`, `import '@${proj}/${mylib}';` ); updateFile( `libs/${mylib}/src/mylib.module.spec.ts`, `import '@${proj}/${mylib2}';` ); }); it('dep-graph should output json to file', () => { runCLI(`dep-graph --file=project-graph.json`); expect(() => checkFilesExist('project-graph.json')).not.toThrow(); const jsonFileContents = readJson('project-graph.json'); expect(jsonFileContents.graph.dependencies).toEqual( expect.objectContaining({ [myapp3E2e]: [ { source: myapp3E2e, target: myapp3, type: 'implicit', }, ], [myapp2]: [ { source: myapp2, target: mylib, type: 'static', }, ], [myapp2E2e]: [ { source: myapp2E2e, target: myapp2, type: 'implicit', }, ], [mylib]: [ { source: mylib, target: mylib2, type: 'static', }, ], [mylib2]: [], [myapp]: [ { source: myapp, target: mylib, type: 'static', }, { source: myapp, target: mylib2, type: 'static' }, ], [myappE2e]: [ { source: myappE2e, target: myapp, type: 'implicit', }, ], [myapp3]: [], }) ); runCLI( `affected:dep-graph --files="libs/${mylib}/src/index.ts" --file="project-graph.json"` ); expect(() => checkFilesExist('project-graph.json')).not.toThrow(); const jsonFileContents2 = readJson('project-graph.json'); expect(jsonFileContents2.criticalPath).toContain(myapp); expect(jsonFileContents2.criticalPath).toContain(myapp2); expect(jsonFileContents2.criticalPath).toContain(mylib); expect(jsonFileContents2.criticalPath).not.toContain(mylib2); }, 1000000); if (isNotWindows()) { it('dep-graph should output json to file by absolute path', () => { runCLI(`dep-graph --file=/tmp/project-graph.json`); expect(() => checkFilesExist('/tmp/project-graph.json')).not.toThrow(); }, 1000000); } if (isWindows()) { it('dep-graph should output json to file by absolute path in Windows', () => { runCLI(`dep-graph --file=C:\\tmp\\project-graph.json`); expect(() => checkFilesExist('C:\\tmp\\project-graph.json') ).not.toThrow(); }, 1000000); } it('dep-graph should focus requested project', () => { runCLI(`dep-graph --focus=${myapp} --file=project-graph.json`); expect(() => checkFilesExist('project-graph.json')).not.toThrow(); const jsonFileContents = readJson('project-graph.json'); const projectNames = Object.keys(jsonFileContents.graph.nodes); expect(projectNames).toContain(myapp); expect(projectNames).toContain(mylib); expect(projectNames).toContain(mylib2); expect(projectNames).toContain(myappE2e); expect(projectNames).not.toContain(myapp2); expect(projectNames).not.toContain(myapp3); expect(projectNames).not.toContain(myapp2E2e); expect(projectNames).not.toContain(myapp3E2e); }, 1000000); it('dep-graph should exclude requested projects', () => { runCLI( `dep-graph --exclude=${myappE2e},${myapp2E2e},${myapp3E2e} --file=project-graph.json` ); expect(() => checkFilesExist('project-graph.json')).not.toThrow(); const jsonFileContents = readJson('project-graph.json'); const projectNames = Object.keys(jsonFileContents.graph.nodes); expect(projectNames).toContain(myapp); expect(projectNames).toContain(mylib); expect(projectNames).toContain(mylib2); expect(projectNames).toContain(myapp2); expect(projectNames).toContain(myapp3); expect(projectNames).not.toContain(myappE2e); expect(projectNames).not.toContain(myapp2E2e); expect(projectNames).not.toContain(myapp3E2e); }, 1000000); it('dep-graph should exclude requested projects that were included by a focus', () => { runCLI( `dep-graph --focus=${myapp} --exclude=${myappE2e} --file=project-graph.json` ); expect(() => checkFilesExist('project-graph.json')).not.toThrow(); const jsonFileContents = readJson('project-graph.json'); const projectNames = Object.keys(jsonFileContents.graph.nodes); expect(projectNames).toContain(myapp); expect(projectNames).toContain(mylib); expect(projectNames).toContain(mylib2); expect(projectNames).not.toContain(myappE2e); expect(projectNames).not.toContain(myapp2); expect(projectNames).not.toContain(myapp3); expect(projectNames).not.toContain(myapp2E2e); expect(projectNames).not.toContain(myapp3E2e); }, 1000000); it('dep-graph should output a deployable static website in an html file accompanied by a folder with static assets', () => { runCLI(`dep-graph --file=project-graph.html`); expect(() => checkFilesExist('project-graph.html')).not.toThrow(); expect(() => checkFilesExist('static/styles.css')).not.toThrow(); expect(() => checkFilesExist('static/runtime.esm.js')).not.toThrow(); expect(() => checkFilesExist('static/polyfills.esm.js')).not.toThrow(); expect(() => checkFilesExist('static/main.esm.js')).not.toThrow(); }); }); describe('Move Angular Project', () => { let proj: string; let app1: string; let app2: string; let newPath: string; beforeEach(() => { proj = newProject(); app1 = uniq('app1'); app2 = uniq('app2'); newPath = `subfolder/${app2}`; runCLI(`generate @nrwl/angular:app ${app1}`); }); afterEach(() => removeProject({ onlyOnCI: true })); /** * Tries moving an app from ${app1} -> subfolder/${app2} */ it('should work for apps', () => { const moveOutput = runCLI( `generate @nrwl/angular:move --project ${app1} ${newPath}` ); // just check the output expect(moveOutput).toContain(`DELETE apps/${app1}`); expect(moveOutput).toContain(`CREATE apps/${newPath}/.browserslistrc`); expect(moveOutput).toContain(`CREATE apps/${newPath}/jest.config.js`); expect(moveOutput).toContain(`CREATE apps/${newPath}/tsconfig.app.json`); expect(moveOutput).toContain(`CREATE apps/${newPath}/tsconfig.json`); expect(moveOutput).toContain(`CREATE apps/${newPath}/tsconfig.spec.json`); expect(moveOutput).toContain(`CREATE apps/${newPath}/.eslintrc.json`); expect(moveOutput).toContain(`CREATE apps/${newPath}/src/favicon.ico`); expect(moveOutput).toContain(`CREATE apps/${newPath}/src/index.html`); expect(moveOutput).toContain(`CREATE apps/${newPath}/src/main.ts`); expect(moveOutput).toContain(`CREATE apps/${newPath}/src/polyfills.ts`); expect(moveOutput).toContain(`CREATE apps/${newPath}/src/styles.css`); expect(moveOutput).toContain(`CREATE apps/${newPath}/src/test-setup.ts`); expect(moveOutput).toContain( `CREATE apps/${newPath}/src/app/app.component.html` ); expect(moveOutput).toContain( `CREATE apps/${newPath}/src/app/app.module.ts` ); expect(moveOutput).toContain(`CREATE apps/${newPath}/src/assets/.gitkeep`); expect(moveOutput).toContain( `CREATE apps/${newPath}/src/environments/environment.prod.ts` ); expect(moveOutput).toContain( `CREATE apps/${newPath}/src/environments/environment.ts` ); expect(moveOutput).toContain(`UPDATE nx.json`); expect(moveOutput).toContain(`UPDATE workspace.json`); }); /** * Tries moving an e2e project from ${app1} -> ${newPath} */ it('should work for e2e projects', () => { const moveOutput = runCLI( `generate @nrwl/angular:move --projectName=${app1}-e2e --destination=${newPath}-e2e` ); // just check that the cypress.json is updated correctly const cypressJsonPath = `apps/${newPath}-e2e/cypress.json`; expect(moveOutput).toContain(`CREATE ${cypressJsonPath}`); checkFilesExist(cypressJsonPath); const cypressJson = readJson(cypressJsonPath); expect(cypressJson.videosFolder).toEqual( `../../../dist/cypress/apps/${newPath}-e2e/videos` ); expect(cypressJson.screenshotsFolder).toEqual( `../../../dist/cypress/apps/${newPath}-e2e/screenshots` ); }); /** * Tries moving a library from ${lib} -> shared/${lib} */ it('should work for libraries', () => { const lib1 = uniq('mylib'); const lib2 = uniq('mylib'); runCLI(`generate @nrwl/angular:lib ${lib1}`); /** * Create a library which imports the module from the other lib */ runCLI(`generate @nrwl/angular:lib ${lib2}`); updateFile( `libs/${lib2}/src/lib/${lib2}.module.ts`, `import { ${classify(lib1)}Module } from '@${proj}/${lib1}'; export class ExtendedModule extends ${classify(lib1)}Module { }` ); const moveOutput = runCLI( `generate @nrwl/angular:move --projectName=${lib1} --destination=shared/${lib1}` ); const newPath = `libs/shared/${lib1}`; const newModule = `Shared${classify(lib1)}Module`; const testSetupPath = `${newPath}/src/test-setup.ts`; expect(moveOutput).toContain(`CREATE ${testSetupPath}`); checkFilesExist(testSetupPath); const modulePath = `${newPath}/src/lib/shared-${lib1}.module.ts`; expect(moveOutput).toContain(`CREATE ${modulePath}`); checkFilesExist(modulePath); const moduleFile = readFile(modulePath); expect(moduleFile).toContain(`export class ${newModule}`); const indexPath = `${newPath}/src/index.ts`; expect(moveOutput).toContain(`CREATE ${indexPath}`); checkFilesExist(indexPath); const index = readFile(indexPath); expect(index).toContain(`export * from './lib/shared-${lib1}.module'`); /** * Check that the import in lib2 has been updated */ const lib2FilePath = `libs/${lib2}/src/lib/${lib2}.module.ts`; const lib2File = readFile(lib2FilePath); expect(lib2File).toContain( `import { ${newModule} } from '@${proj}/shared-${lib1}';` ); expect(lib2File).toContain(`extends ${newModule}`); }); });
the_stack
import {MeshStandardMaterial} from 'three/src/materials/MeshStandardMaterial.js'; import {Mesh} from 'three/src/objects/Mesh.js'; import {$lazyLoadGLTFInfo} from '../../../features/scene-graph/material.js'; import {$availableVariants, $materials, $primitivesList, $switchVariant, Model} from '../../../features/scene-graph/model.js'; import {$correlatedObjects} from '../../../features/scene-graph/three-dom-element.js'; import {$scene} from '../../../model-viewer-base.js'; import {ModelViewerElement} from '../../../model-viewer.js'; import {CorrelatedSceneGraph} from '../../../three-components/gltf-instance/correlated-scene-graph.js'; import {waitForEvent} from '../../../utilities.js'; import {assetPath, loadThreeGLTF, rafPasses} from '../../helpers.js'; const expect = chai.expect; const ASTRONAUT_GLB_PATH = assetPath('models/Astronaut.glb'); const KHRONOS_TRIANGLE_GLB_PATH = assetPath('models/glTF-Sample-Models/2.0/Triangle/glTF/Triangle.gltf'); const CUBES_GLTF_PATH = assetPath('models/cubes.gltf'); suite('scene-graph/model', () => { suite('Model', () => { test('creates a "default" material, when none is specified', async () => { const threeGLTF = await loadThreeGLTF(KHRONOS_TRIANGLE_GLB_PATH); const model = new Model(CorrelatedSceneGraph.from(threeGLTF)); expect(model.materials.length).to.be.eq(1); expect(model.materials[0].name).to.be.eq('Default'); }); test.skip('exposes a list of materials in the scene', async () => { // TODO: This test is skipped because [$correlatedObjects] can contain // unused materials, because it can contain a base material and the // derived material (from assignFinalMaterial(), if for instance // vertexTangents are used) even if only the derived material is assigned // to a mesh. These extras make the test fail. We may want to remove these // unused materials from [$correlatedObjects] at which point this test // will pass, but it's not hurting anything. const threeGLTF = await loadThreeGLTF(ASTRONAUT_GLB_PATH); const materials: Set<MeshStandardMaterial> = new Set(); threeGLTF.scene.traverse((object) => { if ((object as Mesh).isMesh) { const material = (object as Mesh).material; if (Array.isArray(material)) { material.forEach( (material) => materials.add(material as MeshStandardMaterial)); } else { materials.add(material as MeshStandardMaterial); } } }); const model = new Model(CorrelatedSceneGraph.from(threeGLTF)); const collectedMaterials = new Set<MeshStandardMaterial>(); model.materials.forEach((material) => { for (const threeMaterial of material[$correlatedObjects] as Set<MeshStandardMaterial>) { collectedMaterials.add(threeMaterial); expect(materials.has(threeMaterial)).to.be.true; } }); expect(collectedMaterials.size).to.be.equal(materials.size); }); suite('Model Variants', () => { test('Switch variant and lazy load', async () => { const threeGLTF = await loadThreeGLTF(CUBES_GLTF_PATH); const model = new Model(CorrelatedSceneGraph.from(threeGLTF)); expect(model[$materials][2][$correlatedObjects]).to.be.null; expect(model[$materials][2][$lazyLoadGLTFInfo]).to.be.ok; await model[$switchVariant]('Yellow Red'); expect(model[$materials][2][$correlatedObjects]).to.not.be.null; expect(model[$materials][2][$lazyLoadGLTFInfo]).to.not.be.ok; }); test( 'Switch back to default variant does not change correlations', async () => { const threeGLTF = await loadThreeGLTF(CUBES_GLTF_PATH); const model = new Model(CorrelatedSceneGraph.from(threeGLTF)); const sizeBeforeSwitch = model[$materials][0][$correlatedObjects]!.size; await model[$switchVariant]('Yellow Yellow'); // Switches back to default. await model[$switchVariant]('Purple Yellow'); expect(model[$materials][0][$correlatedObjects]!.size) .equals(sizeBeforeSwitch); }); test( 'Switching variant when model has no variants has not effect', async () => { const threeGLTF = await loadThreeGLTF(KHRONOS_TRIANGLE_GLB_PATH); const model = new Model(CorrelatedSceneGraph.from(threeGLTF)); const threeMaterial = model[$materials][0][$correlatedObjects]!.values().next().value; const sizeBeforeSwitch = model[$materials][0][$correlatedObjects]!.size; await model[$switchVariant]('Does not exist'); expect( model[$materials][0][$correlatedObjects]!.values().next().value) .equals(threeMaterial); expect(model[$materials][0][$correlatedObjects]!.size) .equals(sizeBeforeSwitch); }); }); suite('Model e2e test', () => { let element: ModelViewerElement; let model: Model; setup(async () => { element = new ModelViewerElement(); }); teardown(() => { document.body.removeChild(element); }); const loadModel = async (src: string) => { element.src = src; document.body.insertBefore(element, document.body.firstChild); await waitForEvent(element, 'load'); model = element.model!; }; test('getMaterialByName returns material when name exists', async () => { await loadModel(CUBES_GLTF_PATH); const material = model.getMaterialByName('red')!; expect(material).to.be.ok; expect(material.name).to.be.equal('red'); }); test( 'getMaterialByName returns null when name does not exists', async () => { await loadModel(CUBES_GLTF_PATH); const material = model.getMaterialByName('does-not-exist')!; expect(material).to.be.null; }); suite('Create Variant', () => { test( `createMaterialInstanceForVariant() adds new primitive variants mapping only to primitives that use the source material`, async () => { await loadModel(CUBES_GLTF_PATH); const primitive1 = model[$primitivesList].find(prim => { return prim.mesh.name === 'Box'; })!; const primitive2 = model[$primitivesList].find(prim => { return prim.mesh.name === 'Box_1'; })!; const startingSize = primitive1.variantInfo.size; const startingSize2 = primitive2.variantInfo.size; // Creates a variant from material 0. expect(model.createMaterialInstanceForVariant( 0, 'test-material', 'test-variant')) .to.be.ok; // primitive1 uses material '0' so it should have a vew variant. expect(primitive1.variantInfo.size).to.equal(startingSize + 1); // primitive2 to should remain unchanged. expect(primitive2.variantInfo.size).to.equal(startingSize2); }); test('Create variant and switch to it', async () => { await loadModel(CUBES_GLTF_PATH); const primitive = model[$primitivesList].find(prim => { return prim.mesh.name === 'Box'; })!; model.createMaterialInstanceForVariant( 0, 'test-material', 'test-variant'); element.variantName = 'test-variant'; await element.updateComplete; expect(primitive.getActiveMaterial().name).to.equal('test-material'); }); test('New variant is available to model-viewer', async () => { await loadModel(CUBES_GLTF_PATH); model.createMaterialInstanceForVariant( 0, 'test-material', 'test-variant'); expect(element.availableVariants.find(variant => { return variant === 'test-variant'; })).to.be.ok; }); test( `createMaterialInstanceForVariant() fails when there is a variant name collision`, async () => { await loadModel(CUBES_GLTF_PATH); expect(model.createMaterialInstanceForVariant( 0, 'test-material', 'Purple Yellow')) .to.be.null; }); test('createVariant() creates a variant', async () => { await loadModel(CUBES_GLTF_PATH); model.createVariant('test-variant'); expect(element.availableVariants.find(variant => { return variant === 'test-variant'; })).to.be.ok; }); test('createVariant() is a noop if the variant exists', async () => { await loadModel(CUBES_GLTF_PATH); const length = model[$availableVariants]().length; model.createVariant('Purple Yellow'); expect(length).to.equal(model[$availableVariants]().length); }); test( `setMaterialToVariant() adds variants mapping only to primitives that use the source material`, async () => { await loadModel(CUBES_GLTF_PATH); const primitive1 = model[$primitivesList].find(prim => { return prim.mesh.name === 'Box'; })!; const primitive2 = model[$primitivesList].find(prim => { return prim.mesh.name === 'Box_1'; })!; const startingSize = primitive1.variantInfo.size; const startingSize2 = primitive2.variantInfo.size; model.createVariant('test-variant'); // Adds material 0 to the variant. model.setMaterialToVariant(0, 'test-variant'); // primitive1 uses material '0' so it should have a vew variant. expect(primitive1.variantInfo.size).to.equal(startingSize + 1); // primitive2 to should remain unchanged. expect(primitive2.variantInfo.size).to.equal(startingSize2); }); test('updateVariantName() updates the variant name', async () => { await loadModel(CUBES_GLTF_PATH); element.variantName = 'Yellow Red'; await element.updateComplete; element.model!.updateVariantName('Yellow Red', 'NewName'); expect(element.availableVariants[2]).equal('NewName'); }); test( 'deleteVariant() removes variant from primitives, materials and available variants.', async () => { await loadModel(CUBES_GLTF_PATH); element.model!.deleteVariant('Yellow Red'); // Removed from the list of available variants. expect(element.availableVariants.length).equal(2); // No longer present in primitives for (const primitive of model[$primitivesList]) { if (primitive.variantInfo.size > 0) { expect(primitive.variantInfo.has(2)).to.be.false; } } // Materials do not reference the variant. for (const material of model.materials) { expect(material.hasVariant('Yellow Red')).to.be.false; } }); test('hasVariant() positive and negative test', async () => { await loadModel(CUBES_GLTF_PATH); expect(model.hasVariant('Yellow Red')).to.be.true; expect(model.hasVariant('DoesNotExist')).to.be.false; }); }); suite('Intersecting', () => { test('materialFromPoint returns material', async () => { await loadModel(ASTRONAUT_GLB_PATH); await rafPasses(); const material = element.materialFromPoint( element[$scene].width / 2, element[$scene].height / 2)!; expect(material).to.be.ok; }); test( 'materialFromPoint returns null when intersect fails', async () => { await loadModel(ASTRONAUT_GLB_PATH); await rafPasses(); const material = element.materialFromPoint( element[$scene].width, element[$scene].height)!; expect(material).to.be.null; }); }); }); }); });
the_stack
import React from 'react'; import { Animated, Dimensions, Image, ImageRequireSource, ImageURISource, PanResponder, PanResponderInstance, StyleSheet, Text, TouchableOpacity, View } from 'react-native' import {animateGenericNative, base, extra, large, small, tiny} from "./Utils"; import Ruler from "./Ruler"; import Grid, {GridLines, Guides} from "./Grid"; import ImageSelect, {ImageInfo, ImageInfoAsync} from "./ImageSelect"; const AnimatedTouchableOpacity = Animated.createAnimatedComponent(TouchableOpacity); const MAX_SLIDER_VALUE = large * 2; const dimentions = Dimensions.get('screen'); const screenWidth = dimentions.width; const screenHeight = dimentions.height; export type BlueprintProps = { /** * Desabilita completamente o Blueprint */ disabled?: boolean; /** * Add guides on screen. Percentual, points or pixel. Ex. v50%, h50%, v10px, v10p */ guides?: Guides| false; /** * Allows you to add regularly spaced marker lines on the screen */ grid?: GridLines | false; /** * Server images */ imagesAsync?: () => Promise<Array<ImageInfoAsync>>; /** * Add image to pixel-perfect */ images?: Array<ImageURISource | ImageRequireSource>; } type BlueprintState = { zoom: boolean; ruler: boolean; gridAlign: 'side' | 'center' | 'left' | 'right' | 'hidden'; showSelectImageModal: boolean; image?: ImageInfo; packagerRunning: boolean; }; const Slider = (props: { pan: PanResponderInstance, value: Animated.Value }) => { const height = large; const maxmin = (MAX_SLIDER_VALUE) / 4; return ( <View style={{ height: height, width: MAX_SLIDER_VALUE, borderRadius: height, justifyContent: 'center', alignItems: 'center', marginLeft: tiny, borderColor: '#18A0FB', backgroundColor: "#18A0FB33", borderWidth: 1, paddingHorizontal: tiny }} {...props.pan.panHandlers} pointerEvents={'auto'} > <Animated.View style={{ position: 'absolute', width: '100%', height: 1, backgroundColor: '#18A0FB' }} pointerEvents={'none'} /> <Animated.View style={{ width: height - 2, height: height - 2, borderRadius: height - 2, backgroundColor: '#18A0FB', transform: [ { translateX: props.value.interpolate({ inputRange: [0, MAX_SLIDER_VALUE], outputRange: [-maxmin, maxmin] }) } ] }} pointerEvents={'none'} /> </View> ) }; /** * Add guidelines on screen */ export default class Blueprint extends React.PureComponent<BlueprintProps, BlueprintState> { state: BlueprintState = { zoom: false, ruler: false, gridAlign: 'hidden', showSelectImageModal: false, packagerRunning: false }; private interacting = false; private zoomXValue = new Animated.Value(0); private zoomYValue = new Animated.Value(0); private zoomScaleValue = new Animated.Value(0); private zoomX = 0; private zoomY = 0; private zoomScale = 0; private zoomXInit = 0; private zoomYInit = 0; private zoomScaleInit = 0; private imageScaleValue = new Animated.Value(0); private imageOpacityValue = new Animated.Value(0); private imageXValue = new Animated.Value(0); private imageYValue = new Animated.Value(0); private imageX = 0; private imageY = 0; private imageScale = 0; private imageOpacity = 0; private imageXInit = 0; private imageYInit = 0; private imageScaleInit = 0; private imageOpacityInit = 0; private animatedVisibility = new Animated.Value(0); private visible = false; private ruler?: Ruler; private timeout: any; private zoomScalePan = PanResponder.create({ onPanResponderGrant: () => { this.zoomScaleInit = this.zoomScale; this.interacting = true; }, onPanResponderMove: (event, gestureState) => { this.zoomScale = Math.max(0, Math.min(MAX_SLIDER_VALUE, (this.zoomScaleInit + gestureState.dx * 0.8))); this.zoomScaleValue.setValue(this.zoomScale); }, onPanResponderEnd: e => { this.interacting = false; this.hideSchedule(); }, onStartShouldSetPanResponder: (event, gestureState) => true, }); private zoomXYPan = PanResponder.create({ onPanResponderGrant: () => { this.zoomXInit = this.zoomX; this.zoomYInit = this.zoomY; this.interacting = true; }, onPanResponderMove: (event, gestureState) => { // The higher the zoom, the slower the drag speed const speedMax = 1; const speedMin = 0.5; const speed = (this.zoomScale) * (speedMin - speedMax) / (MAX_SLIDER_VALUE) + speedMax; this.zoomX = Math.max(-(screenWidth / 2), Math.min((screenWidth / 2), (this.zoomXInit + gestureState.dx * speed))); this.zoomXValue.setValue(this.zoomX); this.zoomY = Math.max(-(screenHeight / 2), Math.min((screenHeight / 2), (this.zoomYInit + gestureState.dy * speed))); this.zoomYValue.setValue(this.zoomY); }, onPanResponderEnd: e => { this.interacting = false; this.hideSchedule(); }, onStartShouldSetPanResponder: (event, gestureState) => true, }); private imageOpacityPan = PanResponder.create({ onPanResponderGrant: () => { this.imageOpacityInit = this.imageOpacity; this.interacting = true; }, onPanResponderMove: (event, gestureState) => { this.imageOpacity = Math.max(0, Math.min(MAX_SLIDER_VALUE, (this.imageOpacityInit + gestureState.dx * 0.8))); this.imageOpacityValue.setValue(this.imageOpacity); }, onPanResponderEnd: e => { this.interacting = false; this.hideSchedule(); }, onStartShouldSetPanResponder: (event, gestureState) => true, }); private imageScalePan = PanResponder.create({ onPanResponderGrant: () => { this.imageScaleInit = this.imageScale; this.interacting = true; }, onPanResponderMove: (event, gestureState) => { // Reduces scale speed const reducer = 0.2; this.imageScale = Math.max(0, Math.min(MAX_SLIDER_VALUE, (this.imageScaleInit + gestureState.dx * reducer))); this.imageScaleValue.setValue(this.imageScale); }, onPanResponderEnd: e => { this.interacting = false; this.hideSchedule(); }, onStartShouldSetPanResponder: (event, gestureState) => true, }); private imageXYPan = PanResponder.create({ onPanResponderGrant: () => { this.imageXInit = this.imageX; this.imageYInit = this.imageY; this.interacting = true; }, onPanResponderMove: (event, gestureState) => { // Reduces drag speed const reducer = 0.5; // The higher the zoom, the slower the drag speed const speedMax = 1; const speedMin = 0.5; const speed = (this.zoomScale) * (speedMin - speedMax) / (MAX_SLIDER_VALUE) + speedMax; this.imageX = Math.max(-(screenWidth / 2), Math.min((screenWidth / 2), (this.imageXInit + gestureState.dx * speed * reducer))); this.imageXValue.setValue(this.imageX); this.imageY = Math.max(-(screenHeight / 2), Math.min((screenHeight / 2), (this.imageYInit + gestureState.dy * speed * reducer))); this.imageYValue.setValue(this.imageY); }, onPanResponderEnd: e => { this.interacting = false; this.hideSchedule(); }, onStartShouldSetPanResponder: (event, gestureState) => true, }); /** * Schedule to hide Buttons after 4 seconds */ private hideSchedule = () => { clearTimeout(this.timeout); this.timeout = setTimeout(() => { if (this.interacting) { // re schedule return this.hideSchedule(); } this.visible = false; animateGenericNative(this.animatedVisibility, 0); }, 4000); }; componentDidMount(): void { fetch('http://localhost:8081/') .then(value => { this.setState({ packagerRunning: true }) }) .catch(reason => { // ignore }) } render() { if (this.props.disabled) { return this.props.children; } const {width, height} = Dimensions.get('screen'); return ( <View style={[StyleSheet.absoluteFill, {backgroundColor: '#EDEDED'}]}> <Animated.View style={[ StyleSheet.absoluteFill, { backgroundColor: '#FFF', transform: [ { scale: this.zoomScaleValue.interpolate({ inputRange: [0, MAX_SLIDER_VALUE], outputRange: [1, 2] }) }, { translateX: this.zoomXValue.interpolate({ inputRange: [-screenWidth, screenWidth], outputRange: [-screenWidth, screenWidth] }) }, { translateY: this.zoomYValue.interpolate({ inputRange: [-screenHeight, screenHeight], outputRange: [-screenHeight, screenHeight] }) } ] } ]} pointerEvents={'box-none'} > {/* Content */} {this.props.children} { this.state.image ? ( <Animated.Image source={this.state.image} style={{ width: screenWidth, height: screenHeight, resizeMode: 'contain', opacity: this.imageOpacityValue.interpolate({ inputRange: [0, MAX_SLIDER_VALUE], outputRange: [0, 1] }), transform: [ { scale: this.imageScaleValue.interpolate({ inputRange: [0, MAX_SLIDER_VALUE], outputRange: [0.3, 2] }) }, { translateX: this.imageXValue.interpolate({ inputRange: [-screenWidth, screenWidth], outputRange: [-screenWidth, screenWidth] }) }, { translateY: this.imageYValue.interpolate({ inputRange: [-screenHeight, screenHeight], outputRange: [-screenHeight, screenHeight] }) } ] }} /> ) : null } { this.state.gridAlign !== 'hidden' ? ( <Grid grid={this.props.grid} guides={this.props.guides} align={this.state.gridAlign} /> ) : null } { this.state.ruler ? ( <Ruler ref={(ruler) => { this.ruler = ruler || undefined; }} /> ) : null } </Animated.View> {/* Buttons */} <Animated.View style={[ StyleSheet.absoluteFill, { opacity: this.animatedVisibility } ]} pointerEvents={'box-none'} > {/*Logo*/} <TouchableOpacity onPress={event => { clearTimeout(this.timeout); if (this.visible) { this.visible = false; animateGenericNative(this.animatedVisibility, 0); } else { this.visible = true; this.hideSchedule(); animateGenericNative(this.animatedVisibility, 1); } }} style={{ position: 'absolute', left: 0, bottom: large, height: extra, width: extra, marginLeft: tiny, borderRadius: extra, backgroundColor: '#18A0FB33', }} > <Image source={require('./../assets/logo.png')} style={{ width: extra, height: extra, resizeMode: 'stretch' }} width={extra} height={extra} /> </TouchableOpacity> {/*Grid*/} <AnimatedTouchableOpacity style={{ position: 'absolute', left: 0, bottom: large + extra + tiny, flexDirection: 'row', alignItems: 'center', height: large, width: large, borderRadius: large, justifyContent: 'center', borderColor: '#18A0FB', borderWidth: 1, transform: [ { translateX: this.animatedVisibility.interpolate({ inputRange: [0, 1], outputRange: [-large, small] }) } ] }} onPress={() => { const OPTIONS = ['side', 'center', 'left', 'right', 'hidden']; let index = OPTIONS.indexOf(this.state.gridAlign); let newPosition = OPTIONS[index + 1] || 'side'; this.setState({ gridAlign: newPosition as any }); this.hideSchedule(); }} > <View style={ this.state.gridAlign === 'center' ? { height: small, width: 2, alignSelf: 'center', backgroundColor: '#18A0FB', } : ( this.state.gridAlign === 'hidden' ? { opacity: 0 } : { height: small, width: small, borderColor: '#18A0FB', borderRightWidth: this.state.gridAlign === 'left' ? 0 : 2, borderLeftWidth: this.state.gridAlign === 'right' ? 0 : 2 } ) } /> </AnimatedTouchableOpacity> {/*Ruler*/} <Animated.View style={{ position: 'absolute', left: 0, bottom: large * 2 + extra + tiny * 2, flexDirection: 'row', alignItems: 'center', transform: [ { translateX: this.animatedVisibility.interpolate({ inputRange: [0, 1], outputRange: [-(large * 4), small] }) } ] }} > <TouchableOpacity onPress={() => { this.hideSchedule(); this.setState({ ruler: !this.state.ruler }); }} style={{ height: large, width: large, borderRadius: large, justifyContent: 'center', alignItems: 'center', borderColor: '#18A0FB', borderWidth: 1 }} > <View style={{ height: small, width: small, borderColor: '#18A0FB', backgroundColor: "#18A0FB33", borderWidth: 1, }} /> </TouchableOpacity> { this.state.ruler ? ( <React.Fragment> <TouchableOpacity onPress={() => { this.hideSchedule(); if (this.ruler) { this.ruler.changeUnit(); } }} style={{ height: large, width: large, borderRadius: large, justifyContent: 'center', alignItems: 'center', marginLeft: tiny, borderColor: '#18A0FB', borderWidth: 1 }} > <Text style={{ color: '#18A0FB', fontSize: base, fontFamily: 'System', lineHeight: large, textAlignVertical: 'center' }} >{'U'}</Text> </TouchableOpacity> <TouchableOpacity onPress={() => { this.hideSchedule(); if (this.ruler) { this.ruler.changeSensitivity(); } }} style={{ height: large, width: large, borderRadius: large, justifyContent: 'center', alignItems: 'center', marginLeft: tiny, borderColor: '#18A0FB', borderWidth: 1 }} > <Text style={{ color: '#18A0FB', fontSize: base, fontFamily: 'System', lineHeight: large, textAlignVertical: 'center' }} >{'S'}</Text> </TouchableOpacity> </React.Fragment> ) : null } </Animated.View> {/*Zoom*/} <Animated.View style={{ position: 'absolute', left: 0, bottom: large * 3 + extra + tiny * 3, flexDirection: 'row', alignItems: 'center', transform: [ { translateX: this.animatedVisibility.interpolate({ inputRange: [0, 1], outputRange: [-(large * 3 + extra * 2 + tiny), small] }) } ] }} > <TouchableOpacity onPress={() => { this.hideSchedule(); this.setState({ zoom: !this.state.zoom }); }} style={{ height: large, width: large, borderRadius: large, justifyContent: 'center', alignItems: 'center', borderColor: '#18A0FB', borderWidth: 1 }} > <View style={{ height: base, width: base, borderRadius: base, justifyContent: 'center', alignItems: 'center', borderColor: '#18A0FB', backgroundColor: "#18A0FB33", borderWidth: 1, }} > <Text style={{ fontFamily: 'System', lineHeight: base * 1.2, fontSize: base, textAlignVertical: 'center', color: '#18A0FB' }} >{'+'}</Text> </View> </TouchableOpacity> { this.state.zoom ? ( <React.Fragment> <Slider pan={this.zoomScalePan} value={this.zoomScaleValue} /> <Animated.View style={{ width: large, height: large, justifyContent: 'center', marginLeft: tiny, alignItems: 'center' }} pointerEvents={'box-only'} {...this.zoomXYPan.panHandlers} > <Image source={require('./../assets/move.png')} style={{ width: large, height: large, tintColor: '#18A0FB' }} width={large} height={large} /> </Animated.View> <Animated.View style={{ width: large, height: large, justifyContent: 'center', marginLeft: tiny, alignItems: 'center' }} > <TouchableOpacity onPress={() => { this.zoomX = this.zoomY = this.zoomScale = 0; animateGenericNative(this.zoomScaleValue, 0); animateGenericNative(this.zoomXValue, 0); animateGenericNative(this.zoomYValue, 0); }} > <Image source={require('./../assets/reset.png')} style={{ width: large, height: large, tintColor: '#18A0FB' }} width={large} height={large} /> </TouchableOpacity> </Animated.View> </React.Fragment> ) : null } </Animated.View> {/*Image*/} { (this.props.images || this.props.imagesAsync) ? ( <Animated.View style={{ position: 'absolute', left: 0, right: 0, bottom: large * 4 + extra + tiny * 4, flexDirection: 'row', alignItems: 'center', transform: [ { translateX: this.animatedVisibility.interpolate({ inputRange: [0, 1], outputRange: [-(large * 3 + MAX_SLIDER_VALUE * 2), small] }) } ] }} > <TouchableOpacity onPress={() => { this.hideSchedule(); if (this.state.image) { this.setState({ image: undefined }) } else { this.setState({ showSelectImageModal: !this.state.showSelectImageModal }, () => { this.interacting = this.state.showSelectImageModal; this.hideSchedule(); }); } }} style={{ height: large, width: large, borderRadius: large, justifyContent: 'center', alignItems: 'center', borderColor: '#18A0FB', borderWidth: 1 }} > <View style={{ height: small, width: small, borderColor: '#18A0FB', backgroundColor: "#18A0FB33", borderWidth: 1, opacity: 0.5, transform: [ {translateX: -2}, {translateY: -2}, ] }} /> <View style={{ position: 'absolute', height: small, width: small, borderColor: '#18A0FB', backgroundColor: "#18A0FB33", borderWidth: 1, opacity: 0.5, transform: [ {translateX: 2}, {translateY: 2}, ] }} /> </TouchableOpacity> { (this.state.image) ? ( <React.Fragment> <Slider pan={this.imageOpacityPan} value={this.imageOpacityValue} /> <Slider pan={this.imageScalePan} value={this.imageScaleValue} /> <Animated.View style={{ width: large, height: large, marginLeft: tiny, justifyContent: 'center', alignItems: 'center' }} pointerEvents={'box-only'} {...this.imageXYPan.panHandlers} > <Image source={require('./../assets/move.png')} style={{ width: large, height: large, tintColor: '#18A0FB' }} width={large} height={large} /> </Animated.View> </React.Fragment> ) : null } </Animated.View> ) : null } {/* Reload app */} { this.state.packagerRunning ? ( <Animated.View style={{ position: 'absolute', left: 0, bottom: large * 5 + extra + tiny * 5, flexDirection: 'row', alignItems: 'center', transform: [ { translateX: this.animatedVisibility.interpolate({ inputRange: [0, 1], outputRange: [-(large + small), small] }) } ] }} > <TouchableOpacity onPress={() => { fetch('http://localhost:8081/reload') .then(value => { }) .catch(reason => { }); }} > <Image source={require('./../assets/reset.png')} style={{ width: large, height: large, tintColor: '#18A0FB' }} width={large} height={large} /> </TouchableOpacity> </Animated.View> ) : null } { this.state.showSelectImageModal ? ( <Animated.View style={[ StyleSheet.absoluteFill, { opacity: this.animatedVisibility, transform: [ { translateX: this.animatedVisibility.interpolate({ inputRange: [0, 1], outputRange: [-screenWidth, 0] }) } ] } ]} pointerEvents={'box-none'} > <ImageSelect width={screenWidth - tiny * 2} bottom={large + extra + tiny - 2} left={tiny} height={large * 3 + tiny * 2 + 4} images={this.props.images} imagesAsync={this.props.imagesAsync} onSelect={image => { // Reset values this.imageX = 0; this.imageY = 0; this.imageScale = MAX_SLIDER_VALUE / 3; this.imageOpacity = MAX_SLIDER_VALUE / 3; this.imageXValue.setValue(this.imageX); this.imageYValue.setValue(this.imageY); this.imageScaleValue.setValue(this.imageScale); this.imageOpacityValue.setValue(this.imageOpacity); this.interacting = false; this.hideSchedule(); this.setState({ image: image, showSelectImageModal: false }) }} /> </Animated.View> ) : null } </Animated.View> </View> ) } }
the_stack
// MSSQL Client // ------- import _ from '../../deps/lodash@4.17.15/index.js'; const flatten = _.flatten; const map = _.map; const values = _.values; import inherits from '../../deps/inherits@2.0.4/inherits.js'; import Client from '../../client.js'; import Formatter from '../../formatter.js'; import Transaction from './transaction.js'; import QueryCompiler from './query/compiler.js'; import SchemaCompiler from './schema/compiler.js'; import TableCompiler from './schema/tablecompiler.js'; import ColumnCompiler from './schema/columncompiler.js'; const SQL_INT4 = { MIN: -2147483648, MAX: 2147483647 }; const SQL_BIGINT_SAFE = { MIN: -9007199254740991, MAX: 9007199254740991 }; // Always initialize with the "QueryBuilder" and "QueryCompiler" objects, which // extend the base 'lib/query/builder' and 'lib/query/compiler', respectively. function Client_MSSQL(config = {}) { // #1235 mssql module wants 'server', not 'host'. This is to enforce the same // options object across all dialects. if (config && config.connection && config.connection.host) { config.connection.server = config.connection.host; } // mssql always creates pool :( lets try to unpool it as much as possible this.mssqlPoolSettings = { min: 1, max: 1, idleTimeoutMillis: Number.MAX_SAFE_INTEGER, evictionRunIntervalMillis: 0, }; Client.call(this, config); } inherits(Client_MSSQL, Client); Object.assign(Client_MSSQL.prototype, { dialect: 'mssql', driverName: 'mssql', _driver() { const tds = require('tedious'); const mssqlTedious = require('mssql'); const base = require('mssql/lib/base'); // Monkey patch mssql's tedious driver _poolCreate method to fix problem with hanging acquire // connection, this should be removed when https://github.com/tediousjs/node-mssql/pull/614 is // merged and released. // Also since this dialect actually always uses tedious driver (msnodesqlv8 driver should be // required in different way), it might be better to use tedious directly, because mssql // driver uses always internally extra generic-pool and just adds one unnecessary layer of // indirection between database and knex and mssql driver has been lately without maintainer // (changing implementation to use tedious will be breaking change though). // TODO: remove mssql implementation all together and use tedious directly /* istanbul ignore next */ const mssqlVersion = require('mssql/package.json').version; /* istanbul ignore next */ if (mssqlVersion === '4.1.0') { mssqlTedious.ConnectionPool.prototype.release = release; mssqlTedious.ConnectionPool.prototype._poolCreate = _poolCreate; } else { const [major] = mssqlVersion.split('.'); // if version is not ^5.0.0 if (major < 5) { throw new Error( 'This knex version only supports mssql driver versions 4.1.0 and 5.0.0+' ); } } /* istanbul ignore next */ // in some rare situations release is called when stream is interrupted, but // after pool is already destroyed function release(connection) { if (this.pool) { this.pool.release(connection); } } /* istanbul ignore next */ function _poolCreate() { // implementation is copy-pasted from https://github.com/tediousjs/node-mssql/pull/614 return new base.Promise((resolve, reject) => { const cfg = { userName: this.config.user, password: this.config.password, server: this.config.server, options: Object.assign({}, this.config.options), domain: this.config.domain, }; cfg.options.database = this.config.database; cfg.options.port = this.config.port; cfg.options.connectTimeout = this.config.connectionTimeout || this.config.timeout || 15000; cfg.options.requestTimeout = this.config.requestTimeout != null ? this.config.requestTimeout : 15000; cfg.options.tdsVersion = cfg.options.tdsVersion || '7_4'; cfg.options.rowCollectionOnDone = false; cfg.options.rowCollectionOnRequestCompletion = false; cfg.options.useColumnNames = false; cfg.options.appName = cfg.options.appName || 'node-mssql'; // tedious always connect via tcp when port is specified if (cfg.options.instanceName) delete cfg.options.port; if (isNaN(cfg.options.requestTimeout)) cfg.options.requestTimeout = 15000; if (cfg.options.requestTimeout === Infinity) cfg.options.requestTimeout = 0; if (cfg.options.requestTimeout < 0) cfg.options.requestTimeout = 0; if (this.config.debug) { cfg.options.debug = { packet: true, token: true, data: true, payload: true, }; } const tedious = new tds.Connection(cfg); // prevent calling resolve again on end event let alreadyResolved = false; function safeResolve(err) { if (!alreadyResolved) { alreadyResolved = true; resolve(err); } } function safeReject(err) { if (!alreadyResolved) { alreadyResolved = true; reject(err); } } tedious.once('end', (evt) => { safeReject( new base.ConnectionError( 'Connection ended unexpectedly during connecting' ) ); }); tedious.once('connect', (err) => { if (err) { err = new base.ConnectionError(err); return safeReject(err); } safeResolve(tedious); }); tedious.on('error', (err) => { if (err.code === 'ESOCKET') { tedious.hasError = true; return; } this.emit('error', err); }); if (this.config.debug) { tedious.on('debug', this.emit.bind(this, 'debug', tedious)); } }); } return mssqlTedious; }, formatter() { return new MSSQL_Formatter(this, ...arguments); }, transaction() { return new Transaction(this, ...arguments); }, queryCompiler() { return new QueryCompiler(this, ...arguments); }, schemaCompiler() { return new SchemaCompiler(this, ...arguments); }, tableCompiler() { return new TableCompiler(this, ...arguments); }, columnCompiler() { return new ColumnCompiler(this, ...arguments); }, wrapIdentifierImpl(value) { if (value === '*') { return '*'; } return `[${value.replace(/[[\]']+/g, '')}]`; }, // Get a raw connection, called by the `pool` whenever a new // connection needs to be added to the pool. acquireRawConnection() { return new Promise((resolver, rejecter) => { const settings = Object.assign({}, this.connectionSettings); settings.pool = this.mssqlPoolSettings; const connection = new this.driver.ConnectionPool(settings); connection.connect((err) => { if (err) { return rejecter(err); } connection.on('error', (err) => { connection.__knex__disposed = err; }); resolver(connection); }); }); }, validateConnection(connection) { if (connection.connected === true) { return true; } return false; }, // Used to explicitly close a connection, called internally by the pool // when a connection times out or the pool is shutdown. destroyRawConnection(connection) { return connection.close().catch((err) => { // some times close will reject just because pool has already been destoyed // internally by the driver there is nothing we can do in this case }); }, // Position the bindings for the query. positionBindings(sql) { let questionCount = -1; return sql.replace(/\?/g, function () { questionCount += 1; return `@p${questionCount}`; }); }, // Grab a connection, run the query via the MSSQL streaming interface, // and pass that through to the stream we've sent back to the client. _stream(connection, obj, stream) { if (!obj || typeof obj === 'string') obj = { sql: obj }; return new Promise((resolver, rejecter) => { stream.on('error', (err) => { rejecter(err); }); stream.on('end', resolver); const { sql } = obj; if (!sql) return resolver(); const req = (connection.tx_ || connection).request(); //req.verbose = true; req.multiple = true; req.stream = true; if (obj.bindings) { for (let i = 0; i < obj.bindings.length; i++) { this._setReqInput(req, i, obj.bindings[i]); } } req.pipe(stream); req.query(sql); }); }, // Runs the query on the specified connection, providing the bindings // and any other necessary prep work. _query(connection, obj) { const client = this; if (!obj || typeof obj === 'string') obj = { sql: obj }; return new Promise((resolver, rejecter) => { const { sql } = obj; if (!sql) return resolver(); const req = (connection.tx_ || connection).request(); // req.verbose = true; req.multiple = true; if (obj.bindings) { for (let i = 0; i < obj.bindings.length; i++) { client._setReqInput(req, i, obj.bindings[i]); } } req.query(sql, (err, recordset) => { if (err) { return rejecter(err); } obj.response = recordset.recordsets[0]; resolver(obj); }); }); }, // sets a request input parameter. Detects bigints and decimals and sets type appropriately. _setReqInput(req, i, binding) { if (typeof binding == 'number') { if (binding % 1 !== 0) { req.input(`p${i}`, this.driver.Decimal(38, 10), binding); } else if (binding < SQL_INT4.MIN || binding > SQL_INT4.MAX) { if (binding < SQL_BIGINT_SAFE.MIN || binding > SQL_BIGINT_SAFE.MAX) { throw new Error( `Bigint must be safe integer or must be passed as string, saw ${binding}` ); } req.input(`p${i}`, this.driver.BigInt, binding); } else { req.input(`p${i}`, this.driver.Int, binding); } } else { req.input(`p${i}`, binding); } }, // Process the response as returned from the query. processResponse(obj, runner) { if (obj == null) return; const { response, method } = obj; if (obj.output) return obj.output.call(runner, response); switch (method) { case 'select': case 'pluck': case 'first': if (method === 'pluck') return map(response, obj.pluck); return method === 'first' ? response[0] : response; case 'insert': case 'del': case 'update': case 'counter': if (obj.returning) { if (obj.returning === '@@rowcount') { return response[0]['']; } if ( (Array.isArray(obj.returning) && obj.returning.length > 1) || obj.returning[0] === '*' ) { return response; } // return an array with values if only one returning value was specified return flatten(map(response, values)); } return response; default: return response; } }, }); class MSSQL_Formatter extends Formatter { // Accepts a string or array of columns to wrap as appropriate. columnizeWithPrefix(prefix, target) { const columns = typeof target === 'string' ? [target] : target; let str = '', i = -1; while (++i < columns.length) { if (i > 0) str += ', '; str += prefix + this.wrap(columns[i]); } return str; } } export default Client_MSSQL;
the_stack
import { ParserServices, TSESTree } from '@typescript-eslint/typescript-estree'; import { JSONSchema4 } from 'json-schema'; import { AST } from './AST'; import { Linter } from './Linter'; import { Scope } from './Scope'; import { SourceCode } from './SourceCode'; interface RuleMetaDataDocs { /** * The general category the rule falls within */ category: 'Best Practices' | 'Stylistic Issues' | 'Variables' | 'Possible Errors'; /** * Concise description of the rule */ description: string; /** * Extra information linking the rule to a tslint rule */ extraDescription?: string[]; /** * The recommendation level for the rule. * Used by the build tools to generate the recommended config. * Set to false to not include it as a recommendation */ recommended: 'error' | 'warn' | false; /** * The URL of the rule's docs */ url: string; } interface RuleMetaData<TMessageIds extends string> { /** * True if the rule is deprecated, false otherwise */ deprecated?: boolean; /** * Documentation for the rule */ docs: RuleMetaDataDocs; /** * The fixer category. Omit if there is no fixer */ fixable?: 'code' | 'whitespace'; /** * A map of messages which the rule can report. * The key is the messageId, and the string is the parameterised error string. * See: https://eslint.org/docs/developer-guide/working-with-rules#messageids */ messages: Record<TMessageIds, string>; /** * The type of rule. * - `"problem"` means the rule is identifying code that either will cause an error or may cause a confusing behavior. Developers should consider this a high priority to resolve. * - `"suggestion"` means the rule is identifying something that could be done in a better way but no errors will occur if the code isn’t changed. * - `"layout"` means the rule cares primarily about whitespace, semicolons, commas, and parentheses, all the parts of the program that determine how the code looks rather than how it executes. These rules work on parts of the code that aren’t specified in the AST. */ type: 'suggestion' | 'problem' | 'layout'; /** * The name of the rule this rule was replaced by, if it was deprecated. */ replacedBy?: string[]; /** * The options schema. Supply an empty array if there are no options. */ schema: JSONSchema4 | JSONSchema4[]; } interface RuleFix { range: AST.Range; text: string; } interface RuleFixer { insertTextAfter(nodeOrToken: TSESTree.Node | TSESTree.Token, text: string): RuleFix; insertTextAfterRange(range: AST.Range, text: string): RuleFix; insertTextBefore(nodeOrToken: TSESTree.Node | TSESTree.Token, text: string): RuleFix; insertTextBeforeRange(range: AST.Range, text: string): RuleFix; remove(nodeOrToken: TSESTree.Node | TSESTree.Token): RuleFix; removeRange(range: AST.Range): RuleFix; replaceText(nodeOrToken: TSESTree.Node | TSESTree.Token, text: string): RuleFix; replaceTextRange(range: AST.Range, text: string): RuleFix; } declare type ReportFixFunction = (fixer: RuleFixer) => null | RuleFix | RuleFix[] | IterableIterator<RuleFix>; interface ReportDescriptorBase<TMessageIds extends string> { /** * The parameters for the message string associated with `messageId`. */ data?: Record<string, any>; /** * The fixer function. */ fix?: ReportFixFunction | null; /** * The messageId which is being reported. */ messageId: TMessageIds; } interface ReportDescriptorNodeOptionalLoc { /** * The Node or AST Token which the report is being attached to */ node: TSESTree.Node | TSESTree.Comment | TSESTree.Token; /** * An override of the location of the report */ loc?: TSESTree.SourceLocation | TSESTree.LineAndColumnData; } interface ReportDescriptorLocOnly { /** * An override of the location of the report */ loc: TSESTree.SourceLocation | TSESTree.LineAndColumnData; } declare type ReportDescriptor<TMessageIds extends string> = ReportDescriptorBase<TMessageIds> & (ReportDescriptorNodeOptionalLoc | ReportDescriptorLocOnly); interface RuleContext<TMessageIds extends string, TOptions extends readonly any[]> { /** * The rule ID. */ id: string; /** * An array of the configured options for this rule. * This array does not include the rule severity. */ options: TOptions; /** * The shared settings from configuration. * We do not have any shared settings in this plugin. */ settings: {}; /** * The name of the parser from configuration. */ parserPath: string; /** * The parser options configured for this run */ parserOptions: Linter.ParserOptions; /** * An object containing parser-provided services for rules */ parserServices?: ParserServices; /** * Returns an array of the ancestors of the currently-traversed node, starting at * the root of the AST and continuing through the direct parent of the current node. * This array does not include the currently-traversed node itself. */ getAncestors(): TSESTree.Node[]; /** * Returns a list of variables declared by the given node. * This information can be used to track references to variables. */ getDeclaredVariables(node: TSESTree.Node): Scope.Variable[]; /** * Returns the filename associated with the source. */ getFilename(): string; /** * Returns the scope of the currently-traversed node. * This information can be used track references to variables. */ getScope(): Scope.Scope; /** * Returns a SourceCode object that you can use to work with the source that * was passed to ESLint. */ getSourceCode(): SourceCode; /** * Marks a variable with the given name in the current scope as used. * This affects the no-unused-vars rule. */ markVariableAsUsed(name: string): boolean; /** * Reports a problem in the code. */ report(descriptor: ReportDescriptor<TMessageIds>): void; } declare type RuleFunction<T extends TSESTree.BaseNode = never> = (node: T) => void; interface RuleListener { [nodeSelector: string]: RuleFunction | undefined; ArrayExpression?: RuleFunction<TSESTree.ArrayExpression>; ArrayPattern?: RuleFunction<TSESTree.ArrayPattern>; ArrowFunctionExpression?: RuleFunction<TSESTree.ArrowFunctionExpression>; AssignmentPattern?: RuleFunction<TSESTree.AssignmentPattern>; AssignmentExpression?: RuleFunction<TSESTree.AssignmentExpression>; AwaitExpression?: RuleFunction<TSESTree.AwaitExpression>; BlockStatement?: RuleFunction<TSESTree.BlockStatement>; BreakStatement?: RuleFunction<TSESTree.BreakStatement>; CallExpression?: RuleFunction<TSESTree.CallExpression>; CatchClause?: RuleFunction<TSESTree.CatchClause>; ClassBody?: RuleFunction<TSESTree.ClassBody>; ClassDeclaration?: RuleFunction<TSESTree.ClassDeclaration>; ClassExpression?: RuleFunction<TSESTree.ClassExpression>; ClassProperty?: RuleFunction<TSESTree.ClassProperty>; Comment?: RuleFunction<TSESTree.Comment>; ConditionalExpression?: RuleFunction<TSESTree.ConditionalExpression>; ContinueStatement?: RuleFunction<TSESTree.ContinueStatement>; DebuggerStatement?: RuleFunction<TSESTree.DebuggerStatement>; Decorator?: RuleFunction<TSESTree.Decorator>; DoWhileStatement?: RuleFunction<TSESTree.DoWhileStatement>; EmptyStatement?: RuleFunction<TSESTree.EmptyStatement>; ExportAllDeclaration?: RuleFunction<TSESTree.ExportAllDeclaration>; ExportDefaultDeclaration?: RuleFunction<TSESTree.ExportDefaultDeclaration>; ExportNamedDeclaration?: RuleFunction<TSESTree.ExportNamedDeclaration>; ExportSpecifier?: RuleFunction<TSESTree.ExportSpecifier>; ExpressionStatement?: RuleFunction<TSESTree.ExpressionStatement>; ForInStatement?: RuleFunction<TSESTree.ForInStatement>; ForOfStatement?: RuleFunction<TSESTree.ForOfStatement>; ForStatement?: RuleFunction<TSESTree.ForStatement>; Identifier?: RuleFunction<TSESTree.Identifier>; IfStatement?: RuleFunction<TSESTree.IfStatement>; Import?: RuleFunction<TSESTree.Import>; ImportDeclaration?: RuleFunction<TSESTree.ImportDeclaration>; ImportDefaultSpecifier?: RuleFunction<TSESTree.ImportDefaultSpecifier>; ImportNamespaceSpecifier?: RuleFunction<TSESTree.ImportNamespaceSpecifier>; ImportSpecifier?: RuleFunction<TSESTree.ImportSpecifier>; JSXAttribute?: RuleFunction<TSESTree.JSXAttribute>; JSXClosingElement?: RuleFunction<TSESTree.JSXClosingElement>; JSXClosingFragment?: RuleFunction<TSESTree.JSXClosingFragment>; JSXElement?: RuleFunction<TSESTree.JSXElement>; JSXEmptyExpression?: RuleFunction<TSESTree.JSXEmptyExpression>; JSXExpressionContainer?: RuleFunction<TSESTree.JSXExpressionContainer>; JSXFragment?: RuleFunction<TSESTree.JSXFragment>; JSXIdentifier?: RuleFunction<TSESTree.JSXIdentifier>; JSXMemberExpression?: RuleFunction<TSESTree.JSXMemberExpression>; JSXOpeningElement?: RuleFunction<TSESTree.JSXOpeningElement>; JSXOpeningFragment?: RuleFunction<TSESTree.JSXOpeningFragment>; JSXSpreadAttribute?: RuleFunction<TSESTree.JSXSpreadAttribute>; JSXSpreadChild?: RuleFunction<TSESTree.JSXSpreadChild>; JSXText?: RuleFunction<TSESTree.JSXText>; LabeledStatement?: RuleFunction<TSESTree.LabeledStatement>; LogicalExpression?: RuleFunction<TSESTree.LogicalExpression>; MemberExpression?: RuleFunction<TSESTree.MemberExpression>; MetaProperty?: RuleFunction<TSESTree.MetaProperty>; MethodDefinition?: RuleFunction<TSESTree.MethodDefinition>; NewExpression?: RuleFunction<TSESTree.NewExpression>; ObjectExpression?: RuleFunction<TSESTree.ObjectExpression>; ObjectPattern?: RuleFunction<TSESTree.ObjectPattern>; Program?: RuleFunction<TSESTree.Program>; Property?: RuleFunction<TSESTree.Property>; RestElement?: RuleFunction<TSESTree.RestElement>; ReturnStatement?: RuleFunction<TSESTree.ReturnStatement>; SequenceExpression?: RuleFunction<TSESTree.SequenceExpression>; SpreadElement?: RuleFunction<TSESTree.SpreadElement>; Super?: RuleFunction<TSESTree.Super>; SwitchCase?: RuleFunction<TSESTree.SwitchCase>; SwitchStatement?: RuleFunction<TSESTree.SwitchStatement>; TaggedTemplateExpression?: RuleFunction<TSESTree.TaggedTemplateExpression>; TemplateElement?: RuleFunction<TSESTree.TemplateElement>; TemplateLiteral?: RuleFunction<TSESTree.TemplateLiteral>; ThisExpression?: RuleFunction<TSESTree.ThisExpression>; ThrowStatement?: RuleFunction<TSESTree.ThrowStatement>; Token?: RuleFunction<TSESTree.Token>; TryStatement?: RuleFunction<TSESTree.TryStatement>; TSAbstractKeyword?: RuleFunction<TSESTree.TSAbstractKeyword>; TSAbstractMethodDefinition?: RuleFunction<TSESTree.TSAbstractMethodDefinition>; TSAnyKeyword?: RuleFunction<TSESTree.TSAnyKeyword>; TSArrayType?: RuleFunction<TSESTree.TSArrayType>; TSAsExpression?: RuleFunction<TSESTree.TSAsExpression>; TSAsyncKeyword?: RuleFunction<TSESTree.TSAsyncKeyword>; TSBigIntKeyword?: RuleFunction<TSESTree.TSBigIntKeyword>; TSBooleanKeyword?: RuleFunction<TSESTree.TSBooleanKeyword>; TSCallSignatureDeclaration?: RuleFunction<TSESTree.TSCallSignatureDeclaration>; TSConditionalType?: RuleFunction<TSESTree.TSConditionalType>; TSConstructSignatureDeclaration?: RuleFunction<TSESTree.TSConstructSignatureDeclaration>; TSDeclareKeyword?: RuleFunction<TSESTree.TSDeclareKeyword>; TSDeclareFunction?: RuleFunction<TSESTree.TSDeclareFunction>; TSEnumDeclaration?: RuleFunction<TSESTree.TSEnumDeclaration>; TSEnumMember?: RuleFunction<TSESTree.TSEnumMember>; TSExportAssignment?: RuleFunction<TSESTree.TSExportAssignment>; TSExportKeyword?: RuleFunction<TSESTree.TSExportKeyword>; TSExternalModuleReference?: RuleFunction<TSESTree.TSExternalModuleReference>; TSImportEqualsDeclaration?: RuleFunction<TSESTree.TSImportEqualsDeclaration>; TSImportType?: RuleFunction<TSESTree.TSImportType>; TSIndexedAccessType?: RuleFunction<TSESTree.TSIndexedAccessType>; TSIndexSignature?: RuleFunction<TSESTree.TSIndexSignature>; TSInferType?: RuleFunction<TSESTree.TSInferType>; TSInterfaceBody?: RuleFunction<TSESTree.TSInterfaceBody>; TSInterfaceDeclaration?: RuleFunction<TSESTree.TSInterfaceDeclaration>; TSIntersectionType?: RuleFunction<TSESTree.TSIntersectionType>; TSLiteralType?: RuleFunction<TSESTree.TSLiteralType>; TSMappedType?: RuleFunction<TSESTree.TSMappedType>; TSMethodSignature?: RuleFunction<TSESTree.TSMethodSignature>; TSModuleBlock?: RuleFunction<TSESTree.TSModuleBlock>; TSModuleDeclaration?: RuleFunction<TSESTree.TSModuleDeclaration>; TSNamespaceExportDeclaration?: RuleFunction<TSESTree.TSNamespaceExportDeclaration>; TSNeverKeyword?: RuleFunction<TSESTree.TSNeverKeyword>; TSNonNullExpression?: RuleFunction<TSESTree.TSNonNullExpression>; TSNullKeyword?: RuleFunction<TSESTree.TSNullKeyword>; TSNumberKeyword?: RuleFunction<TSESTree.TSNumberKeyword>; TSObjectKeyword?: RuleFunction<TSESTree.TSObjectKeyword>; TSOptionalType?: RuleFunction<TSESTree.TSOptionalType>; TSParameterProperty?: RuleFunction<TSESTree.TSParameterProperty>; TSParenthesizedType?: RuleFunction<TSESTree.TSParenthesizedType>; TSPrivateKeyword?: RuleFunction<TSESTree.TSPrivateKeyword>; TSPropertySignature?: RuleFunction<TSESTree.TSPropertySignature>; TSProtectedKeyword?: RuleFunction<TSESTree.TSProtectedKeyword>; TSPublicKeyword?: RuleFunction<TSESTree.TSPublicKeyword>; TSQualifiedName?: RuleFunction<TSESTree.TSQualifiedName>; TSReadonlyKeyword?: RuleFunction<TSESTree.TSReadonlyKeyword>; TSRestType?: RuleFunction<TSESTree.TSRestType>; TSStaticKeyword?: RuleFunction<TSESTree.TSStaticKeyword>; TSStringKeyword?: RuleFunction<TSESTree.TSStringKeyword>; TSSymbolKeyword?: RuleFunction<TSESTree.TSSymbolKeyword>; TSThisType?: RuleFunction<TSESTree.TSThisType>; TSTupleType?: RuleFunction<TSESTree.TSTupleType>; TSTypeAliasDeclaration?: RuleFunction<TSESTree.TSTypeAliasDeclaration>; TSTypeAnnotation?: RuleFunction<TSESTree.TSTypeAnnotation>; TSTypeAssertion?: RuleFunction<TSESTree.TSTypeAssertion>; TSTypeLiteral?: RuleFunction<TSESTree.TSTypeLiteral>; TSTypeOperator?: RuleFunction<TSESTree.TSTypeOperator>; TSTypeParameter?: RuleFunction<TSESTree.TSTypeParameter>; TSTypeParameterDeclaration?: RuleFunction<TSESTree.TSTypeParameterDeclaration>; TSTypeParameterInstantiation?: RuleFunction<TSESTree.TSTypeParameterInstantiation>; TSTypePredicate?: RuleFunction<TSESTree.TSTypePredicate>; TSTypeQuery?: RuleFunction<TSESTree.TSTypeQuery>; TSTypeReference?: RuleFunction<TSESTree.TSTypeReference>; TSUndefinedKeyword?: RuleFunction<TSESTree.TSUndefinedKeyword>; TSUnionType?: RuleFunction<TSESTree.TSUnionType>; TSUnknownKeyword?: RuleFunction<TSESTree.TSUnknownKeyword>; TSVoidKeyword?: RuleFunction<TSESTree.TSVoidKeyword>; UnaryExpression?: RuleFunction<TSESTree.UnaryExpression>; UpdateExpression?: RuleFunction<TSESTree.UpdateExpression>; VariableDeclaration?: RuleFunction<TSESTree.VariableDeclaration>; VariableDeclarator?: RuleFunction<TSESTree.VariableDeclarator>; WhileStatement?: RuleFunction<TSESTree.WhileStatement>; WithStatement?: RuleFunction<TSESTree.WithStatement>; YieldExpression?: RuleFunction<TSESTree.YieldExpression>; } interface RuleModule<TMessageIds extends string, TOptions extends readonly any[], TRuleListener extends RuleListener = RuleListener> { /** * Metadata about the rule */ meta: RuleMetaData<TMessageIds>; /** * Function which returns an object with methods that ESLint calls to “visit” * nodes while traversing the abstract syntax tree. */ create(context: RuleContext<TMessageIds, TOptions>): TRuleListener; } export { ReportDescriptor, ReportFixFunction, RuleContext, RuleFix, RuleFixer, RuleFunction, RuleListener, RuleMetaData, RuleMetaDataDocs, RuleModule, }; //# sourceMappingURL=Rule.d.ts.map
the_stack
import * as https from 'https'; import * as http from 'http'; import { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'; import * as url from 'url'; import { Readable, Writable } from 'stream'; import { EventEmitter } from 'events'; import { LookupFunction } from 'net'; export { IncomingHttpHeaders, OutgoingHttpHeaders }; export type HttpMethod = "GET" | "POST" | "DELETE" | "PUT" | "HEAD" | "OPTIONS" | "PATCH" | "TRACE" | "CONNECT"; export as namespace urllib; export interface RequestOptions { /** Request method, defaults to GET. Could be GET, POST, DELETE or PUT. Alias 'type'. */ method?: HttpMethod; /** Alias method */ type?: HttpMethod; /** Data to be sent. Will be stringify automatically. */ data?: any; /** Force convert data to query string. */ dataAsQueryString?: boolean; /** Manually set the content of payload. If set, data will be ignored. */ content?: string | Buffer; /** Stream to be pipe to the remote.If set, data and content will be ignored. */ stream?: Readable; /** * A writable stream to be piped by the response stream. * Responding data will be write to this stream and callback * will be called with data set null after finished writing. */ writeStream?: Writable; /** consume the writeStream, invoke the callback after writeStream close. */ consumeWriteStream?: boolean; /** * The files will send with multipart/form-data format, base on formstream. * If method not set, will use POST method by default. */ files?: Array<Readable | Buffer | string> | object | Readable | Buffer | string; /** Type of request data.Could be json.If it's json, will auto set Content-Type: application/json header. */ contentType?: string; /** * urllib default use querystring to stringify form data which don't support nested object, * will use qs instead of querystring to support nested object by set this option to true. */ nestedQuerystring?: boolean; /** * Type of response data. Could be text or json. * If it's text, the callbacked data would be a String. * If it's json, the data of callback would be a parsed JSON Object * and will auto set Accept: application/json header. Default callbacked data would be a Buffer. */ dataType?: string; /** Fix the control characters (U+0000 through U+001F) before JSON parse response. Default is false. */ fixJSONCtlChars?: boolean; /** Request headers. */ headers?: IncomingHttpHeaders; /** by default will convert header keys to lowercase */ keepHeaderCase?: boolean; /** * Request timeout in milliseconds for connecting phase and response receiving phase. * Defaults to exports. * TIMEOUT, both are 5s.You can use timeout: 5000 to tell urllib use same timeout on two phase or set them seperately such as * timeout: [3000, 5000], which will set connecting timeout to 3s and response 5s. */ timeout?: number | number[]; /** username:password used in HTTP Basic Authorization. */ auth?: string; /** username:password used in HTTP Digest Authorization. */ digestAuth?: string; /** HTTP Agent object.Set false if you does not use agent. */ agent?: http.Agent; /** HTTPS Agent object. Set false if you does not use agent. */ httpsAgent?: https.Agent; /** * An array of strings or Buffers of trusted certificates. * If this is omitted several well known "root" CAs will be used, like VeriSign. * These are used to authorize connections. * Notes: This is necessary only if the server uses the self - signed certificate */ ca?: string | Buffer | string[] | Buffer[]; /** * If true, the server certificate is verified against the list of supplied CAs. * An 'error' event is emitted if verification fails.Default: true. */ rejectUnauthorized?: boolean; /** A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. */ pfx?: string | Buffer; /** * A string or Buffer containing the private key of the client in PEM format. * Notes: This is necessary only if using the client certificate authentication */ key?: string | Buffer; /** * A string or Buffer containing the certificate key of the client in PEM format. * Notes: This is necessary only if using the client certificate authentication */ cert?: string | Buffer; /** A string of passphrase for the private key or pfx. */ passphrase?: string; /** A string describing the ciphers to use or exclude. */ ciphers?: string; /** The SSL method to use, e.g.SSLv3_method to force SSL version 3. */ secureProtocol?: string; /** follow HTTP 3xx responses as redirects. defaults to false. */ followRedirect?: boolean; /** The maximum number of redirects to follow, defaults to 10. */ maxRedirects?: number; /** Format the redirect url by your self. Default is url.resolve(from, to). */ formatRedirectUrl?: (a: any, b: any) => void; /** Before request hook, you can change every thing here. */ beforeRequest?: (...args: any[]) => void; /** let you get the res object when request connected, default false. alias customResponse */ streaming?: boolean; /** Accept gzip response content and auto decode it, default is false. */ gzip?: boolean; /** Enable timing or not, default is false. */ timing?: boolean; /** Enable proxy request, default is false. */ enableProxy?: boolean; /** proxy agent uri or options, default is null. */ proxy?: string | { [key: string]: any }; /** * Custom DNS lookup function, default is dns.lookup. * Require node >= 4.0.0(for http protocol) and node >=8(for https protocol) */ lookup?: LookupFunction; /** * check request address to protect from SSRF and similar attacks. * It receive two arguments(ip and family) and should return true or false to identified the address is legal or not. * It rely on lookup and have the same version requirement. */ checkAddress?: (ip: string, family: number | string) => boolean; /** * UNIX domain socket path. (Windows is not supported) */ socketPath?: string; } export interface HttpClientResponse<T> { data: T; status: number; headers: OutgoingHttpHeaders; res: http.IncomingMessage & { /** * https://eggjs.org/en/core/httpclient.html#timing-boolean */ timing?: { queuing: number; dnslookup: number; connected: number; requestSent: number; waiting: number; contentDownload: number; } }; } /** * @param data Outgoing message * @param res http response */ export type Callback<T> = (err: Error, data: T, res: http.IncomingMessage) => void; /** * Handle all http request, both http and https support well. * * @example * // GET http://httptest.cnodejs.net * urllib.request('http://httptest.cnodejs.net/test/get', function(err, data, res) {}); * // POST http://httptest.cnodejs.net * var args = { type: 'post', data: { foo: 'bar' } }; * urllib.request('http://httptest.cnodejs.net/test/post', args, function(err, data, res) {}); * * @param url The URL to request, either a String or a Object that return by url.parse. */ export function request<T = any>(url: string | url.URL, options?: RequestOptions): Promise<HttpClientResponse<T>>; /** * @param url The URL to request, either a String or a Object that return by url.parse. */ export function request<T = any>(url: string | url.URL, callback: Callback<T>): void; /** * @param url The URL to request, either a String or a Object that return by url.parse. */ export function request<T = any>(url: string | url.URL, options: RequestOptions, callback: Callback<T>): void; /** * Handle request with a callback. * @param url The URL to request, either a String or a Object that return by url.parse. */ export function requestWithCallback<T = any>(url: string | url.URL, callback: Callback<T>): void; /** * @param url The URL to request, either a String or a Object that return by url.parse. */ export function requestWithCallback<T = any>(url: string | url.URL, options: RequestOptions, callback: Callback<T>): void; /** * yield urllib.requestThunk(url, args) * @param url The URL to request, either a String or a Object that return by url.parse. */ export function requestThunk<T = any>(url: string | url.URL, options?: RequestOptions): (callback: Callback<T>) => void; /** * alias to request. * Handle all http request, both http and https support well. * * @example * // GET http://httptest.cnodejs.net * urllib.request('http://httptest.cnodejs.net/test/get', function(err, data, res) {}); * // POST http://httptest.cnodejs.net * var args = { type: 'post', data: { foo: 'bar' } }; * urllib.request('http://httptest.cnodejs.net/test/post', args, function(err, data, res) {}); * * @param url The URL to request, either a String or a Object that return by url.parse. * @param options Optional, @see RequestOptions. */ export function curl<T = any>(url: string | url.URL, options?: RequestOptions): Promise<HttpClientResponse<T>>; /** * @param url The URL to request, either a String or a Object that return by url.parse. */ export function curl<T = any>(url: string | url.URL, callback: Callback<T>): void; /** * @param url The URL to request, either a String or a Object that return by url.parse. */ export function curl<T = any>(url: string | url.URL, options: RequestOptions, callback: Callback<T>): void; /** * The default request timeout(in milliseconds). */ export const TIMEOUT: number; /** * The default request & response timeout(in milliseconds). */ export const TIMEOUTS: [number, number]; /** * Request user agent. */ export const USER_AGENT: string; /** * Request http agent. */ export const agent: http.Agent; /** * Request https agent. */ export const httpsAgent: https.Agent; export class HttpClient<O extends RequestOptions = RequestOptions> extends EventEmitter { request<T = any>(url: string | url.URL): Promise<HttpClientResponse<T>>; request<T = any>(url: string | url.URL, options: O): Promise<HttpClientResponse<T>>; request<T = any>(url: string | url.URL, callback: Callback<T>): void; request<T = any>(url: string | url.URL, options: O, callback: Callback<T>): void; curl<T = any>(url: string | url.URL, options: O): Promise<HttpClientResponse<T>>; curl<T = any>(url: string | url.URL): Promise<HttpClientResponse<T>>; curl<T = any>(url: string | url.URL, callback: Callback<T>): void; curl<T = any>(url: string | url.URL, options: O, callback: Callback<T>): void; requestThunk(url: string | url.URL, options?: O): (callback: (...args: any[]) => void) => void; } export interface RequestOptions2 extends RequestOptions { retry?: number; retryDelay?: number; isRetry?: (res: HttpClientResponse<any>) => boolean; } /** * request method only return a promise, * compatible with async/await and generator in co. */ export class HttpClient2 extends HttpClient<RequestOptions2> {} /** * Create a HttpClient instance. */ export function create(options?: RequestOptions): HttpClient;
the_stack
//% color=#7600A8 weight=31 icon="\uf03e" //% advanced=true declare namespace images { /** * Creates an image that fits on the LED screen. */ //% weight=75 help=images/create-image //% blockId=device_build_image block="create image" //% parts="ledmatrix" imageLiteral=1 shim=images::createImage function createImage(leds: string): Image; /** * Creates an image with 2 frames. */ //% weight=74 help=images/create-big-image //% blockId=device_build_big_image block="create big image" imageLiteral=2 //% parts="ledmatrix" shim=images::createBigImage function createBigImage(leds: string): Image; } declare interface Image { /** * Plots the image at a given column to the screen */ //% help=images/plot-image //% parts="ledmatrix" xOffset.defl=0 shim=ImageMethods::plotImage plotImage(xOffset?: int32): void; /** * Shows an frame from the image at offset ``x offset``. * @param xOffset column index to start displaying the image * @param interval time in milliseconds to pause after drawing */ //% help=images/show-image weight=80 blockNamespace=images //% blockId=device_show_image_offset block="show image %sprite(myImage)|at offset %offset ||and interval (ms) %interval" //% //% blockGap=8 parts="ledmatrix" async interval.defl=400 shim=ImageMethods::showImage showImage(xOffset: int32, interval?: int32): void; /** * Draws the ``index``-th frame of the image on the screen. * @param xOffset column index to start displaying the image */ //% help=images/plot-frame weight=80 //% parts="ledmatrix" shim=ImageMethods::plotFrame plotFrame(xOffset: int32): void; /** * Scrolls an image . * @param frameOffset x offset moved on each animation step, eg: 1, 2, 5 * @param interval time between each animation step in milli seconds, eg: 200 */ //% help=images/scroll-image weight=79 async blockNamespace=images //% blockId=device_scroll_image //% block="scroll image %sprite(myImage)|with offset %frameoffset|and interval (ms) %delay" //% blockGap=8 parts="ledmatrix" shim=ImageMethods::scrollImage scrollImage(frameOffset: int32, interval: int32): void; /** * Sets all pixels off. */ //% help=images/clear //% parts="ledmatrix" shim=ImageMethods::clear clear(): void; /** * Sets a specific pixel brightness at a given position */ //% //% parts="ledmatrix" shim=ImageMethods::setPixelBrightness setPixelBrightness(x: int32, y: int32, value: int32): void; /** * Gets the pixel brightness ([0..255]) at a given position */ //% //% parts="ledmatrix" shim=ImageMethods::pixelBrightness pixelBrightness(x: int32, y: int32): int32; /** * Gets the width in columns */ //% help=functions/width shim=ImageMethods::width width(): int32; /** * Gets the height in rows (always 5) */ //% shim=ImageMethods::height height(): int32; /** * Set a pixel state at position ``(x,y)`` * @param x pixel column * @param y pixel row * @param value pixel state */ //% help=images/set-pixel //% parts="ledmatrix" shim=ImageMethods::setPixel setPixel(x: int32, y: int32, value: boolean): void; /** * Get the pixel state at position ``(x,y)`` * @param x pixel column * @param y pixel row */ //% help=images/pixel //% parts="ledmatrix" shim=ImageMethods::pixel pixel(x: int32, y: int32): boolean; /** * Show a particular frame of the image strip. * @param frame image frame to show */ //% weight=70 help=images/show-frame //% parts="ledmatrix" interval.defl=400 shim=ImageMethods::showFrame showFrame(frame: int32, interval?: int32): void; } /** * Provides access to basic micro:bit functionality. */ //% color=#1E90FF weight=116 icon="\uf00a" declare namespace basic { /** * Draws an image on the LED screen. * @param leds the pattern of LED to turn on/off * @param interval time in milliseconds to pause after drawing */ //% help=basic/show-leds //% weight=95 blockGap=8 //% imageLiteral=1 async //% blockId=device_show_leds //% block="show leds" icon="\uf00a" //% parts="ledmatrix" interval.defl=400 shim=basic::showLeds function showLeds(leds: string, interval?: int32): void; /** * Display text on the display, one character at a time. If the string fits on the screen (i.e. is one letter), does not scroll. * @param text the text to scroll on the screen, eg: "Hello!" * @param interval how fast to shift characters; eg: 150, 100, 200, -100 */ //% help=basic/show-string //% weight=87 blockGap=16 //% block="show|string %text" //% async //% blockId=device_print_message //% parts="ledmatrix" //% text.shadowOptions.toString=true interval.defl=150 shim=basic::showString function showString(text: string, interval?: int32): void; /** * Turn off all LEDs */ //% help=basic/clear-screen weight=79 //% blockId=device_clear_display block="clear screen" //% parts="ledmatrix" shim=basic::clearScreen function clearScreen(): void; /** * Shows a sequence of LED screens as an animation. * @param leds pattern of LEDs to turn on/off * @param interval time in milliseconds between each redraw */ //% help=basic/show-animation imageLiteral=1 async //% parts="ledmatrix" interval.defl=400 shim=basic::showAnimation function showAnimation(leds: string, interval?: int32): void; /** * Draws an image on the LED screen. * @param leds pattern of LEDs to turn on/off */ //% help=basic/plot-leds weight=80 //% parts="ledmatrix" imageLiteral=1 shim=basic::plotLeds function plotLeds(leds: string): void; /** * Repeats the code forever in the background. On each iteration, allows other codes to run. * @param body code to execute */ //% help=basic/forever weight=55 blockGap=16 blockAllowMultiple=1 afterOnStart=true //% blockId=device_forever block="forever" icon="\uf01e" shim=basic::forever function forever(a: () => void): void; /** * Pause for the specified time in milliseconds * @param ms how long to pause for, eg: 100, 200, 500, 1000, 2000 */ //% help=basic/pause weight=54 //% async block="pause (ms) %pause" blockGap=16 //% blockId=device_pause icon="\uf110" //% pause.shadow=timePicker shim=basic::pause function pause(ms: int32): void; } //% color=#D400D4 weight=111 icon="\uf192" declare namespace input { /** * Do something when a button (A, B or both A+B) is pushed down and released again. * @param button the button that needs to be pressed * @param body code to run when event is raised */ //% help=input/on-button-pressed weight=85 blockGap=16 //% blockId=device_button_event block="on button|%NAME|pressed" //% parts="buttonpair" shim=input::onButtonPressed function onButtonPressed(button: Button, body: () => void): void; /** * Do something when when a gesture is done (like shaking the micro:bit). * @param gesture the type of gesture to track, eg: Gesture.Shake * @param body code to run when gesture is raised */ //% help=input/on-gesture weight=84 blockGap=16 //% blockId=device_gesture_event block="on |%NAME" //% parts="accelerometer" //% NAME.fieldEditor="gestures" NAME.fieldOptions.columns=4 shim=input::onGesture function onGesture(gesture: Gesture, body: () => void): void; /** * Tests if a gesture is currently detected. * @param gesture the type of gesture to detect, eg: Gesture.Shake */ //% help=input/is-gesture weight=10 blockGap=8 //% blockId=deviceisgesture block="is %gesture gesture" //% parts="accelerometer" //% gesture.fieldEditor="gestures" gesture.fieldOptions.columns=4 shim=input::isGesture function isGesture(gesture: Gesture): boolean; /** * Do something when a pin is touched and released again (while also touching the GND pin). * @param name the pin that needs to be pressed, eg: TouchPin.P0 * @param body the code to run when the pin is pressed */ //% help=input/on-pin-pressed weight=83 blockGap=32 //% blockId=device_pin_event block="on pin %name|pressed" shim=input::onPinPressed function onPinPressed(name: TouchPin, body: () => void): void; /** * Do something when a pin is released. * @param name the pin that needs to be released, eg: TouchPin.P0 * @param body the code to run when the pin is released */ //% help=input/on-pin-released weight=6 blockGap=16 //% blockId=device_pin_released block="on pin %NAME|released" //% advanced=true shim=input::onPinReleased function onPinReleased(name: TouchPin, body: () => void): void; /** * Get the button state (pressed or not) for ``A`` and ``B``. * @param button the button to query the request, eg: Button.A */ //% help=input/button-is-pressed weight=60 //% block="button|%NAME|is pressed" //% blockId=device_get_button2 //% icon="\uf192" blockGap=8 //% parts="buttonpair" shim=input::buttonIsPressed function buttonIsPressed(button: Button): boolean; /** * Get the pin state (pressed or not). Requires to hold the ground to close the circuit. * @param name pin used to detect the touch, eg: TouchPin.P0 */ //% help=input/pin-is-pressed weight=58 //% blockId="device_pin_is_pressed" block="pin %NAME|is pressed" //% blockGap=8 shim=input::pinIsPressed function pinIsPressed(name: TouchPin): boolean; /** * Get the acceleration value in milli-gravitys (when the board is laying flat with the screen up, x=0, y=0 and z=-1024) * @param dimension x, y, or z dimension, eg: Dimension.X */ //% help=input/acceleration weight=58 //% blockId=device_acceleration block="acceleration (mg)|%NAME" blockGap=8 //% parts="accelerometer" shim=input::acceleration function acceleration(dimension: Dimension): int32; /** * Reads the light level applied to the LED screen in a range from ``0`` (dark) to ``255`` bright. */ //% help=input/light-level weight=57 //% blockId=device_get_light_level block="light level" blockGap=8 //% parts="ledmatrix" shim=input::lightLevel function lightLevel(): int32; /** * Get the current compass heading in degrees. */ //% help=input/compass-heading //% weight=56 //% blockId=device_heading block="compass heading (°)" blockGap=8 //% parts="compass" shim=input::compassHeading function compassHeading(): int32; /** * Gets the temperature in Celsius degrees (°C). */ //% weight=55 //% help=input/temperature //% blockId=device_temperature block="temperature (°C)" blockGap=8 //% parts="thermometer" shim=input::temperature function temperature(): int32; /** * The pitch or roll of the device, rotation along the ``x-axis`` or ``y-axis``, in degrees. * @param kind pitch or roll */ //% help=input/rotation weight=52 //% blockId=device_get_rotation block="rotation (°)|%NAME" blockGap=8 //% parts="accelerometer" advanced=true shim=input::rotation function rotation(kind: Rotation): int32; /** * Get the magnetic force value in ``micro-Teslas`` (``µT``). This function is not supported in the simulator. * @param dimension the x, y, or z dimension, eg: Dimension.X */ //% help=input/magnetic-force weight=51 //% blockId=device_get_magnetic_force block="magnetic force (µT)|%NAME" blockGap=8 //% parts="compass" //% advanced=true shim=input::magneticForce function magneticForce(dimension: Dimension): number; /** * Obsolete, compass calibration is automatic. */ //% help=input/calibrate-compass advanced=true //% blockId="input_compass_calibrate" block="calibrate compass" //% weight=45 shim=input::calibrateCompass function calibrateCompass(): void; /** * Sets the accelerometer sample range in gravities. * @param range a value describe the maximum strengh of acceleration measured */ //% help=input/set-accelerometer-range //% blockId=device_set_accelerometer_range block="set accelerometer|range %range" //% weight=5 //% parts="accelerometer" //% advanced=true shim=input::setAccelerometerRange function setAccelerometerRange(range: AcceleratorRange): void; } //% weight=1 color="#333333" //% advanced=true declare namespace control { /** * Gets the number of milliseconds elapsed since power on. */ //% help=control/millis weight=50 //% blockId=control_running_time block="millis (ms)" shim=control::millis function millis(): int32; /** * Gets current time in microseconds. Overflows every ~18 minutes. */ //% shim=control::micros function micros(): int32; /** * Schedules code that run in the background. */ //% help=control/in-background blockAllowMultiple=1 afterOnStart=true //% blockId="control_in_background" block="run in background" blockGap=8 shim=control::inBackground function inBackground(a: () => void): void; /** * Blocks the calling thread until the specified event is raised. */ //% help=control/wait-for-event async //% blockId=control_wait_for_event block="wait for event|from %src|with value %value" shim=control::waitForEvent function waitForEvent(src: int32, value: int32): void; /** * Resets the BBC micro:bit. */ //% weight=30 async help=control/reset blockGap=8 //% blockId="control_reset" block="reset" shim=control::reset function reset(): void; /** * Blocks the current fiber for the given microseconds * @param micros number of micro-seconds to wait. eg: 4 */ //% help=control/wait-micros weight=29 async //% blockId="control_wait_us" block="wait (µs)%micros" //% micros.min=0 micros.max=6000 shim=control::waitMicros function waitMicros(micros: int32): void; /** * Raises an event in the event bus. * @param src ID of the MicroBit Component that generated the event e.g. MICROBIT_ID_BUTTON_A. * @param value Component specific code indicating the cause of the event. * @param mode optional definition of how the event should be processed after construction (default is CREATE_AND_FIRE). */ //% weight=21 blockGap=12 blockId="control_raise_event" block="raise event|from source %src=control_event_source_id|with value %value=control_event_value_id" blockExternalInputs=1 //% help=control/raise-event //% mode.defl=1 shim=control::raiseEvent function raiseEvent(src: int32, value: int32, mode?: EventCreationMode): void; /** * Registers an event handler. */ //% weight=20 blockGap=8 blockId="control_on_event" block="on event|from %src=control_event_source_id|with value %value=control_event_value_id" //% help=control/on-event //% blockExternalInputs=1 flags.defl=0 shim=control::onEvent function onEvent(src: int32, value: int32, handler: () => void, flags?: int32): void; /** * Gets the value of the last event executed on the bus */ //% blockId=control_event_value" block="event value" //% help=control/event-value //% weight=18 shim=control::eventValue function eventValue(): int32; /** * Gets the timestamp of the last event executed on the bus */ //% blockId=control_event_timestamp" block="event timestamp" //% help=control/event-timestamp //% weight=19 blockGap=8 shim=control::eventTimestamp function eventTimestamp(): int32; /** * Make a friendly name for the device based on its serial number */ //% blockId="control_device_name" block="device name" weight=10 blockGap=8 //% help=control/device-name //% advanced=true shim=control::deviceName function deviceName(): string; /** * Returns the major version of the microbit */ //% help=control/hardware-version shim=control::_hardwareVersion function _hardwareVersion(): string; /** * Derive a unique, consistent serial number of this device from internal data. */ //% blockId="control_device_serial_number" block="device serial number" weight=9 //% help=control/device-serial-number //% advanced=true shim=control::deviceSerialNumber function deviceSerialNumber(): int32; /** * Derive a unique, consistent 64-bit serial number of this device from internal data. */ //% help=control/device-long-serial-number //% advanced=true shim=control::deviceLongSerialNumber function deviceLongSerialNumber(): Buffer; /** * Informs simulator/runtime of a MIDI message * Internal function to support the simulator. */ //% part=midioutput blockHidden=1 shim=control::__midiSend function __midiSend(buffer: Buffer): void; /** * */ //% shim=control::__log function __log(priority: int32, text: string): void; /** * Allocates the next user notification event */ //% help=control/allocate-notify-event shim=control::allocateNotifyEvent function allocateNotifyEvent(): int32; /** Write a message to DMESG debugging buffer. */ //% shim=control::dmesg function dmesg(s: string): void; /** Write a message and value (pointer) to DMESG debugging buffer. */ //% shim=control::dmesgPtr function dmesgPtr(str: string, ptr: Object): void; } declare namespace control { /** * Force GC and dump basic information about heap. */ //% shim=control::gc function gc(): void; /** * Force GC and halt waiting for debugger to do a full heap dump. */ //% shim=control::heapDump function heapDump(): void; /** * Set flags used when connecting an external debugger. */ //% shim=control::setDebugFlags function setDebugFlags(flags: int32): void; /** * Record a heap snapshot to debug memory leaks. */ //% shim=control::heapSnapshot function heapSnapshot(): void; /** * Return true if profiling is enabled in the current build. */ //% shim=control::profilingEnabled function profilingEnabled(): boolean; } //% color=#7600A8 weight=101 icon="\uf205" declare namespace led { /** * Turn on the specified LED using x, y coordinates (x is horizontal, y is vertical). (0,0) is upper left. * @param x the horizontal coordinate of the LED starting at 0 * @param y the vertical coordinate of the LED starting at 0 */ //% help=led/plot weight=78 //% blockId=device_plot block="plot|x %x|y %y" blockGap=8 //% parts="ledmatrix" //% x.min=0 x.max=4 y.min=0 y.max=4 //% x.fieldOptions.precision=1 y.fieldOptions.precision=1 shim=led::plot function plot(x: int32, y: int32): void; /** * Turn on the specified LED with specific brightness using x, y coordinates (x is horizontal, y is vertical). (0,0) is upper left. * @param x the horizontal coordinate of the LED starting at 0 * @param y the vertical coordinate of the LED starting at 0 * @param brightness the brightness from 0 (off) to 255 (bright), eg:255 */ //% help=led/plot-brightness weight=78 //% blockId=device_plot_brightness block="plot|x %x|y %y|brightness %brightness" blockGap=8 //% parts="ledmatrix" //% x.min=0 x.max=4 y.min=0 y.max=4 brightness.min=0 brightness.max=255 //% x.fieldOptions.precision=1 y.fieldOptions.precision=1 //% advanced=true shim=led::plotBrightness function plotBrightness(x: int32, y: int32, brightness: int32): void; /** * Turn off the specified LED using x, y coordinates (x is horizontal, y is vertical). (0,0) is upper left. * @param x the horizontal coordinate of the LED * @param y the vertical coordinate of the LED */ //% help=led/unplot weight=77 //% blockId=device_unplot block="unplot|x %x|y %y" blockGap=8 //% parts="ledmatrix" //% x.min=0 x.max=4 y.min=0 y.max=4 //% x.fieldOptions.precision=1 y.fieldOptions.precision=1 shim=led::unplot function unplot(x: int32, y: int32): void; /** * Get the brightness state of the specified LED using x, y coordinates. (0,0) is upper left. * @param x the horizontal coordinate of the LED * @param y the vertical coordinate of the LED */ //% help=led/point-brightness weight=76 //% blockId=device_point_brightness block="point|x %x|y %y brightness" //% parts="ledmatrix" //% x.min=0 x.max=4 y.min=0 y.max=4 //% x.fieldOptions.precision=1 y.fieldOptions.precision=1 //% advanced=true shim=led::pointBrightness function pointBrightness(x: int32, y: int32): int32; /** * Get the screen brightness from 0 (off) to 255 (full bright). */ //% help=led/brightness weight=60 //% blockId=device_get_brightness block="brightness" blockGap=8 //% parts="ledmatrix" //% advanced=true shim=led::brightness function brightness(): int32; /** * Set the screen brightness from 0 (off) to 255 (full bright). * @param value the brightness value, eg:255, 127, 0 */ //% help=led/set-brightness weight=59 //% blockId=device_set_brightness block="set brightness %value" //% parts="ledmatrix" //% advanced=true //% value.min=0 value.max=255 shim=led::setBrightness function setBrightness(value: int32): void; /** * Cancels the current animation and clears other pending animations. */ //% weight=50 help=led/stop-animation //% blockId=device_stop_animation block="stop animation" //% parts="ledmatrix" //% advanced=true shim=led::stopAnimation function stopAnimation(): void; /** * Sets the display mode between black and white and greyscale for rendering LEDs. * @param mode mode the display mode in which the screen operates */ //% weight=1 help=led/set-display-mode //% parts="ledmatrix" advanced=true weight=1 //% blockId="led_set_display_mode" block="set display mode $mode" shim=led::setDisplayMode function setDisplayMode(mode: DisplayMode): void; /** * Gets the current display mode */ //% weight=1 parts="ledmatrix" advanced=true shim=led::displayMode function displayMode(): DisplayMode; /** * Turns on or off the display */ //% help=led/enable blockId=device_led_enable block="led enable %on" //% advanced=true parts="ledmatrix" shim=led::enable function enable(on: boolean): void; /** * Takes a screenshot of the LED screen and returns an image. */ //% help=led/screenshot //% parts="ledmatrix" shim=led::screenshot function screenshot(): Image; } declare namespace music { /** * Set the default output volume of the sound synthesizer. * @param volume the volume 0...255 */ //% blockId=synth_set_volume block="set volume %volume" //% volume.min=0 volume.max=255 //% //% help=music/set-volume //% weight=70 //% group="Volume" //% blockGap=8 volume.defl=127 shim=music::setVolume function setVolume(volume?: int32): void; /** * Returns the current output volume of the sound synthesizer. */ //% blockId=synth_get_volume block="volume" //% help=music/volume //% weight=69 //% group="Volume" //% blockGap=8 shim=music::volume function volume(): int32; /** * Turn the built-in speaker on or off. * Disabling the speaker resets the sound pin to the default of P0. * @param enabled whether the built-in speaker is enabled in addition to the sound pin */ //% blockId=music_set_built_in_speaker_enable block="set built-in speaker $enabled" //% group="micro:bit (V2)" //% parts=builtinspeaker //% help=music/set-built-in-speaker-enabled //% enabled.shadow=toggleOnOff //% weight=0 shim=music::setBuiltInSpeakerEnabled function setBuiltInSpeakerEnabled(enabled: boolean): void; /** * Defines an optional sample level to generate during periods of silence. **/ //% group="micro:bit (V2)" //% help=music/set-silence-level //% level.min=0 //% level.max=1024 //% //% weight=1 level.defl=0 shim=music::setSilenceLevel function setSilenceLevel(level?: int32): void; } declare namespace pins { /** * Read the specified pin or connector as either 0 or 1 * @param name pin to read from, eg: DigitalPin.P0 */ //% help=pins/digital-read-pin weight=30 //% blockId=device_get_digital_pin block="digital read|pin %name" blockGap=8 //% name.fieldEditor="gridpicker" name.fieldOptions.columns=4 //% name.fieldOptions.tooltips="false" name.fieldOptions.width="250" shim=pins::digitalReadPin function digitalReadPin(name: DigitalPin): int32; /** * Set a pin or connector value to either 0 or 1. * @param name pin to write to, eg: DigitalPin.P0 * @param value value to set on the pin, 1 eg,0 */ //% help=pins/digital-write-pin weight=29 //% blockId=device_set_digital_pin block="digital write|pin %name|to %value" //% value.min=0 value.max=1 //% name.fieldEditor="gridpicker" name.fieldOptions.columns=4 //% name.fieldOptions.tooltips="false" name.fieldOptions.width="250" shim=pins::digitalWritePin function digitalWritePin(name: DigitalPin, value: int32): void; /** * Read the connector value as analog, that is, as a value comprised between 0 and 1023. * @param name pin to write to, eg: AnalogPin.P0 */ //% help=pins/analog-read-pin weight=25 //% blockId=device_get_analog_pin block="analog read|pin %name" blockGap="8" //% name.fieldEditor="gridpicker" name.fieldOptions.columns=4 //% name.fieldOptions.tooltips="false" name.fieldOptions.width="250" shim=pins::analogReadPin function analogReadPin(name: AnalogPin): int32; /** * Set the connector value as analog. Value must be comprised between 0 and 1023. * @param name pin name to write to, eg: AnalogPin.P0 * @param value value to write to the pin between ``0`` and ``1023``. eg:1023,0 */ //% help=pins/analog-write-pin weight=24 //% blockId=device_set_analog_pin block="analog write|pin %name|to %value" blockGap=8 //% value.min=0 value.max=1023 //% name.fieldEditor="gridpicker" name.fieldOptions.columns=4 //% name.fieldOptions.tooltips="false" name.fieldOptions.width="250" shim=pins::analogWritePin function analogWritePin(name: AnalogPin, value: int32): void; /** * Configure the pulse-width modulation (PWM) period of the analog output in microseconds. * If this pin is not configured as an analog output (using `analog write pin`), the operation has no effect. * @param name analog pin to set period to, eg: AnalogPin.P0 * @param micros period in micro seconds. eg:20000 */ //% help=pins/analog-set-period weight=23 blockGap=8 //% blockId=device_set_analog_period block="analog set period|pin %pin|to (µs)%micros" //% pin.fieldEditor="gridpicker" pin.fieldOptions.columns=4 //% pin.fieldOptions.tooltips="false" shim=pins::analogSetPeriod function analogSetPeriod(name: AnalogPin, micros: int32): void; /** * Configure the pin as a digital input and generate an event when the pin is pulsed either high or low. * @param name digital pin to register to, eg: DigitalPin.P0 * @param pulse the value of the pulse, eg: PulseValue.High */ //% help=pins/on-pulsed advanced=true //% blockId=pins_on_pulsed block="on|pin %pin|pulsed %pulse" //% pin.fieldEditor="gridpicker" pin.fieldOptions.columns=4 //% pin.fieldOptions.tooltips="false" pin.fieldOptions.width="250" //% group="Pulse" //% weight=25 //% blockGap=8 shim=pins::onPulsed function onPulsed(name: DigitalPin, pulse: PulseValue, body: () => void): void; /** * Get the duration of the last pulse in microseconds. This function should be called from a ``onPulsed`` handler. */ //% help=pins/pulse-duration advanced=true //% blockId=pins_pulse_duration block="pulse duration (µs)" //% group="Pulse" //% weight=24 //% blockGap=8 shim=pins::pulseDuration function pulseDuration(): int32; /** * Return the duration of a pulse at a pin in microseconds. * @param name the pin which measures the pulse, eg: DigitalPin.P0 * @param value the value of the pulse, eg: PulseValue.High * @param maximum duration in microseconds */ //% blockId="pins_pulse_in" block="pulse in (µs)|pin %name|pulsed %value" //% advanced=true //% help=pins/pulse-in //% name.fieldEditor="gridpicker" name.fieldOptions.columns=4 //% name.fieldOptions.tooltips="false" name.fieldOptions.width="250" //% group="Pulse" //% weight=23 //% blockGap=8 maxDuration.defl=2000000 shim=pins::pulseIn function pulseIn(name: DigitalPin, value: PulseValue, maxDuration?: int32): int32; /** * Write a value to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with ``0`` being full-speed in one direction, ``180`` being full speed in the other, and a value near ``90`` being no movement). * @param name pin to write to, eg: AnalogPin.P0 * @param value angle or rotation speed, eg:180,90,0 */ //% help=pins/servo-write-pin weight=20 //% blockId=device_set_servo_pin block="servo write|pin %name|to %value" blockGap=8 //% parts=microservo trackArgs=0 //% value.min=0 value.max=180 //% name.fieldEditor="gridpicker" name.fieldOptions.columns=4 //% name.fieldOptions.tooltips="false" name.fieldOptions.width="250" //% group="Servo" shim=pins::servoWritePin function servoWritePin(name: AnalogPin, value: int32): void; /** * Specifies that a continuous servo is connected. */ //% shim=pins::servoSetContinuous function servoSetContinuous(name: AnalogPin, value: boolean): void; /** * Configure the IO pin as an analog/pwm output and set a pulse width. The period is 20 ms period and the pulse width is set based on the value given in **microseconds** or `1/1000` milliseconds. * @param name pin name * @param micros pulse duration in micro seconds, eg:1500 */ //% help=pins/servo-set-pulse weight=19 //% blockId=device_set_servo_pulse block="servo set pulse|pin %value|to (µs) %micros" //% value.fieldEditor="gridpicker" value.fieldOptions.columns=4 //% value.fieldOptions.tooltips="false" value.fieldOptions.width="250" //% group="Servo" shim=pins::servoSetPulse function servoSetPulse(name: AnalogPin, micros: int32): void; /** * Set the pin used when using analog pitch or music. * @param name pin to modulate pitch from */ //% blockId=device_analog_set_pitch_pin block="analog set pitch pin %name" //% help=pins/analog-set-pitch-pin advanced=true //% name.fieldEditor="gridpicker" name.fieldOptions.columns=4 //% name.fieldOptions.tooltips="false" name.fieldOptions.width="250" //% group="Pins" //% weight=12 //% blockGap=8 shim=pins::analogSetPitchPin function analogSetPitchPin(name: AnalogPin): void; /** * Sets the volume on the pitch pin * @param volume the intensity of the sound from 0..255 */ //% blockId=device_analog_set_pitch_volume block="analog set pitch volume $volume" //% help=pins/analog-set-pitch-volume weight=3 advanced=true //% volume.min=0 volume.max=255 //% deprecated shim=pins::analogSetPitchVolume function analogSetPitchVolume(volume: int32): void; /** * Gets the volume the pitch pin from 0..255 */ //% blockId=device_analog_pitch_volume block="analog pitch volume" //% help=pins/analog-pitch-volume weight=3 advanced=true //% deprecated shim=pins::analogPitchVolume function analogPitchVolume(): int32; /** * Emit a plse-width modulation (PWM) signal to the current pitch pin. Use `analog set pitch pin` to define the pitch pin. * @param frequency frequency to modulate in Hz. * @param ms duration of the pitch in milli seconds. */ //% blockId=device_analog_pitch block="analog pitch %frequency|for (ms) %ms" //% help=pins/analog-pitch async advanced=true //% group="Pins" //% weight=14 //% blockGap=8 shim=pins::analogPitch function analogPitch(frequency: int32, ms: int32): void; /** * Configure the pull direction of of a pin. * @param name pin to set the pull mode on, eg: DigitalPin.P0 * @param pull one of the mbed pull configurations, eg: PinPullMode.PullUp */ //% help=pins/set-pull advanced=true //% blockId=device_set_pull block="set pull|pin %pin|to %pull" //% pin.fieldEditor="gridpicker" pin.fieldOptions.columns=4 //% pin.fieldOptions.tooltips="false" pin.fieldOptions.width="250" //% group="Pins" //% weight=15 //% blockGap=8 shim=pins::setPull function setPull(name: DigitalPin, pull: PinPullMode): void; /** * Configure the events emitted by this pin. Events can be subscribed to * using ``control.onEvent()``. * @param name pin to set the event mode on, eg: DigitalPin.P0 * @param type the type of events for this pin to emit, eg: PinEventType.Edge */ //% help=pins/set-events advanced=true //% blockId=device_set_pin_events block="set pin %pin|to emit %type|events" //% pin.fieldEditor="gridpicker" pin.fieldOptions.columns=4 //% pin.fieldOptions.tooltips="false" pin.fieldOptions.width="250" //% group="Pins" //% weight=13 //% blockGap=8 shim=pins::setEvents function setEvents(name: DigitalPin, type: PinEventType): void; /** * Create a new zero-initialized buffer. * @param size number of bytes in the buffer */ //% shim=pins::createBuffer function createBuffer(size: int32): Buffer; /** * Set the matrix width for Neopixel strip (already assigned to a pin). * Should be used in conjunction with `set matrix width` from Neopixel package. * @param name pin of Neopixel strip, eg: DigitalPin.P1 * @param value width of matrix (at least ``2``) */ //% help=pins/neopixel-matrix-width advanced=true //% blockId=pin_neopixel_matrix_width block="neopixel matrix width|pin %pin %width" //% pin.fieldEditor="gridpicker" pin.fieldOptions.columns=4 //% pin.fieldOptions.tooltips="false" pin.fieldOptions.width="250" //% width.min=2 //% group="Pins" //% weight=11 //% blockGap=8 width.defl=5 shim=pins::setMatrixWidth function setMatrixWidth(pin: DigitalPin, width?: int32): void; /** * Read `size` bytes from a 7-bit I2C `address`. */ //% repeat.defl=0 shim=pins::i2cReadBuffer function i2cReadBuffer(address: int32, size: int32, repeat?: boolean): Buffer; /** * Write bytes to a 7-bit I2C `address`. */ //% repeat.defl=0 shim=pins::i2cWriteBuffer function i2cWriteBuffer(address: int32, buf: Buffer, repeat?: boolean): int32; /** * Write to the SPI slave and return the response * @param value Data to be sent to the SPI slave */ //% help=pins/spi-write advanced=true //% blockId=spi_write block="spi write %value" //% group="SPI" //% blockGap=8 //% weight=53 shim=pins::spiWrite function spiWrite(value: int32): int32; /** * Write to and read from the SPI slave at the same time * @param command Data to be sent to the SPI slave (can be null) * @param response Data received from the SPI slave (can be null) */ //% help=pins/spi-transfer argsNullable shim=pins::spiTransfer function spiTransfer(command: Buffer, response: Buffer): void; /** * Set the SPI frequency * @param frequency the clock frequency, eg: 1000000 */ //% help=pins/spi-frequency advanced=true //% blockId=spi_frequency block="spi frequency %frequency" //% group="SPI" //% blockGap=8 //% weight=55 shim=pins::spiFrequency function spiFrequency(frequency: int32): void; /** * Set the SPI bits and mode * @param bits the number of bits, eg: 8 * @param mode the mode, eg: 3 */ //% help=pins/spi-format advanced=true //% blockId=spi_format block="spi format|bits %bits|mode %mode" //% group="SPI" //% blockGap=8 //% weight=54 shim=pins::spiFormat function spiFormat(bits: int32, mode: int32): void; /** * Set the MOSI, MISO, SCK pins used by the SPI connection * */ //% help=pins/spi-pins advanced=true //% blockId=spi_pins block="spi set pins|MOSI %mosi|MISO %miso|SCK %sck" //% mosi.fieldEditor="gridpicker" mosi.fieldOptions.columns=4 //% mosi.fieldOptions.tooltips="false" mosi.fieldOptions.width="250" //% miso.fieldEditor="gridpicker" miso.fieldOptions.columns=4 //% miso.fieldOptions.tooltips="false" miso.fieldOptions.width="250" //% sck.fieldEditor="gridpicker" sck.fieldOptions.columns=4 //% sck.fieldOptions.tooltips="false" sck.fieldOptions.width="250" //% group="SPI" //% blockGap=8 //% weight=51 shim=pins::spiPins function spiPins(mosi: DigitalPin, miso: DigitalPin, sck: DigitalPin): void; /** * Mounts a push button on the given pin */ //% help=pins/push-button advanced=true shim=pins::pushButton function pushButton(pin: DigitalPin): void; /** * Set the pin used when producing sounds and melodies. Default is P0. * @param name pin to modulate pitch from */ //% blockId=pin_set_audio_pin block="set audio pin $name" //% help=pins/set-audio-pin //% name.fieldEditor="gridpicker" name.fieldOptions.columns=4 //% name.fieldOptions.tooltips="false" name.fieldOptions.width="250" //% weight=1 //% blockGap=8 shim=pins::setAudioPin function setAudioPin(name: AnalogPin): void; /** * Sets whether or not audio will be output using a pin on the edge * connector. */ //% blockId=pin_set_audio_pin_enabled //% block="set audio pin enabled $enabled" //% weight=0 shim=pins::setAudioPinEnabled function setAudioPinEnabled(enabled: boolean): void; } //% weight=2 color=#002050 icon="\uf287" //% advanced=true declare namespace serial { /** * Read a line of text from the serial port and return the buffer when the delimiter is met. * @param delimiter text delimiter that separates each text chunk */ //% help=serial/read-until //% blockId=serial_read_until block="serial|read until %delimiter=serial_delimiter_conv" //% weight=19 shim=serial::readUntil function readUntil(delimiter: string): string; /** * Read the buffered received data as a string */ //% help=serial/read-string //% blockId=serial_read_buffer block="serial|read string" //% weight=18 shim=serial::readString function readString(): string; /** * Register an event to be fired when one of the delimiter is matched. * @param delimiters the characters to match received characters against. */ //% help=serial/on-data-received //% weight=18 blockId=serial_on_data_received block="serial|on data received %delimiters=serial_delimiter_conv" shim=serial::onDataReceived function onDataReceived(delimiters: string, body: () => void): void; /** * Send a piece of text through the serial connection. */ //% help=serial/write-string //% weight=87 blockGap=8 //% blockId=serial_writestring block="serial|write string %text" //% text.shadowOptions.toString=true shim=serial::writeString function writeString(text: string): void; /** * Send a buffer through serial connection */ //% blockId=serial_writebuffer block="serial|write buffer %buffer=serial_readbuffer" //% help=serial/write-buffer advanced=true weight=6 shim=serial::writeBuffer function writeBuffer(buffer: Buffer): void; /** * Read multiple characters from the receive buffer. * If length is positive, pauses until enough characters are present. * @param length default buffer length */ //% blockId=serial_readbuffer block="serial|read buffer %length" //% help=serial/read-buffer advanced=true weight=5 shim=serial::readBuffer function readBuffer(length: int32): Buffer; /** * Set the serial input and output to use pins instead of the USB connection. * @param tx the new transmission pin, eg: SerialPin.P0 * @param rx the new reception pin, eg: SerialPin.P1 * @param rate the new baud rate. eg: 115200 */ //% weight=10 //% help=serial/redirect //% blockId=serial_redirect block="serial|redirect to|TX %tx|RX %rx|at baud rate %rate" //% blockExternalInputs=1 //% tx.fieldEditor="gridpicker" tx.fieldOptions.columns=3 //% tx.fieldOptions.tooltips="false" //% rx.fieldEditor="gridpicker" rx.fieldOptions.columns=3 //% rx.fieldOptions.tooltips="false" //% blockGap=8 shim=serial::redirect function redirect(tx: SerialPin, rx: SerialPin, rate: BaudRate): void; /** Set the baud rate of the serial port */ //% weight=10 //% blockId=serial_setbaudrate block="serial|set baud rate %rate" //% blockGap=8 inlineInputMode=inline //% help=serial/set-baud-rate //% group="Configuration" advanced=true shim=serial::setBaudRate function setBaudRate(rate: BaudRate): void; /** * Direct the serial input and output to use the USB connection. */ //% weight=9 help=serial/redirect-to-usb //% blockId=serial_redirect_to_usb block="serial|redirect to USB" shim=serial::redirectToUSB function redirectToUSB(): void; /** * Sets the size of the RX buffer in bytes * @param size length of the rx buffer in bytes, eg: 32 */ //% help=serial/set-rx-buffer-size //% blockId=serialSetRxBufferSize block="serial set rx buffer size to $size" //% advanced=true shim=serial::setRxBufferSize function setRxBufferSize(size: uint8): void; /** * Sets the size of the TX buffer in bytes * @param size length of the tx buffer in bytes, eg: 32 */ //% help=serial/set-tx-buffer-size //% blockId=serialSetTxBufferSize block="serial set tx buffer size to $size" //% advanced=true shim=serial::setTxBufferSize function setTxBufferSize(size: uint8): void; /** Send DMESG debug buffer over serial. */ //% shim=serial::writeDmesg function writeDmesg(): void; } //% indexerGet=BufferMethods::getByte indexerSet=BufferMethods::setByte declare interface Buffer { /** * Reads an unsigned byte at a particular location */ //% shim=BufferMethods::getUint8 getUint8(off: int32): int32; /** * Returns false when the buffer can be written to. */ //% shim=BufferMethods::isReadOnly isReadOnly(): boolean; /** * Writes an unsigned byte at a particular location */ //% shim=BufferMethods::setUint8 setUint8(off: int32, v: int32): void; /** * Write a number in specified format in the buffer. */ //% shim=BufferMethods::setNumber setNumber(format: NumberFormat, offset: int32, value: number): void; /** * Read a number in specified format from the buffer. */ //% shim=BufferMethods::getNumber getNumber(format: NumberFormat, offset: int32): number; /** Returns the length of a Buffer object. */ //% property shim=BufferMethods::length length: int32; /** * Fill (a fragment) of the buffer with given value. */ //% offset.defl=0 length.defl=-1 shim=BufferMethods::fill fill(value: int32, offset?: int32, length?: int32): void; /** * Return a copy of a fragment of a buffer. */ //% offset.defl=0 length.defl=-1 shim=BufferMethods::slice slice(offset?: int32, length?: int32): Buffer; /** * Shift buffer left in place, with zero padding. * @param offset number of bytes to shift; use negative value to shift right * @param start start offset in buffer. Default is 0. * @param length number of elements in buffer. If negative, length is set as the buffer length minus * start. eg: -1 */ //% start.defl=0 length.defl=-1 shim=BufferMethods::shift shift(offset: int32, start?: int32, length?: int32): void; /** * Convert a buffer to string assuming UTF8 encoding */ //% shim=BufferMethods::toString toString(): string; /** * Convert a buffer to its hexadecimal representation. */ //% shim=BufferMethods::toHex toHex(): string; /** * Rotate buffer left in place. * @param offset number of bytes to shift; use negative value to shift right * @param start start offset in buffer. Default is 0. * @param length number of elements in buffer. If negative, length is set as the buffer length minus * start. eg: -1 */ //% start.defl=0 length.defl=-1 shim=BufferMethods::rotate rotate(offset: int32, start?: int32, length?: int32): void; /** * Write contents of `src` at `dstOffset` in current buffer. */ //% shim=BufferMethods::write write(dstOffset: int32, src: Buffer): void; /** * Compute k-bit FNV-1 non-cryptographic hash of the buffer. */ //% shim=BufferMethods::hash hash(bits: int32): uint32; } declare namespace control { /** * Create a new zero-initialized buffer. * @param size number of bytes in the buffer */ //% deprecated=1 shim=control::createBuffer function createBuffer(size: int32): Buffer; /** * Create a new buffer with UTF8-encoded string * @param str the string to put in the buffer */ //% deprecated=1 shim=control::createBufferFromUTF8 function createBufferFromUTF8(str: string): Buffer; } declare namespace light { /** * Sends a color buffer to a light strip **/ //% advanced=true shim=light::sendWS2812Buffer function sendWS2812Buffer(buf: Buffer, pin: int32): void; /** * Sends a color buffer to a light strip **/ //% advanced=true shim=light::sendWS2812BufferWithBrightness function sendWS2812BufferWithBrightness(buf: Buffer, pin: int32, brightness: int32): void; /** * Sets the light mode of a pin **/ //% advanced=true //% shim=light::setMode function setMode(pin: int32, mode: int32): void; } declare namespace input { /** * Do something when the logo is touched and released again. * @param body the code to run when the logo is pressed */ //% weight=83 blockGap=32 //% blockId=input_logo_event block="on logo $action" //% group="micro:bit (V2)" //% parts="logotouch" //% help="input/on-logo-event" shim=input::onLogoEvent function onLogoEvent(action: TouchButtonEvent, body: () => void): void; /** * Get the logo state (pressed or not). */ //% weight=58 //% blockId="input_logo_is_pressed" block="logo is pressed" //% blockGap=8 //% group="micro:bit (V2)" //% parts="logotouch" //% help="input/logo-is-pressed" shim=input::logoIsPressed function logoIsPressed(): boolean; } declare namespace pins { /** * Configure the touch detection for the pins and logo. * P0, P1, P2 use resistive touch by default. * The logo uses capacitative touch by default. * @param name target to change the touch mode for * @param mode the touch mode to use */ //% weight=60 //% blockId=device_touch_set_type block="set %name to touch mode %mode" //% advanced=true //% group="micro:bit (V2)" //% help=pins/touch-set-mode shim=pins::touchSetMode function touchSetMode(name: TouchTarget, mode: TouchTargetMode): void; } declare namespace music { /** * Internal use only **/ //% async shim=music::__playSoundExpression function __playSoundExpression(nodes: string, waitTillDone: boolean): void; /** * Internal use only */ //% shim=music::__stopSoundExpressions function __stopSoundExpressions(): void; } // Auto-generated. Do not edit. Really.
the_stack
declare namespace MpxStore { type UnboxDepField<D, F> = F extends keyof D ? D[F] : {} interface Deps { [key: string]: Store | StoreWithThis } type UnboxDepsField<D extends Deps, F> = string extends keyof D ? {} : { [K in keyof D]: UnboxDepField<D[K], F> } type getMutation<M> = M extends (state: any, ...payload: infer P) => infer R ? (...payload: P) => R : never type getAction<A> = A extends (context: object, ...payload: infer P) => infer R ? (...payload: P) => R : never type Mutations<S> = { [key: string]: (this: void, state: S, ...payload: any[]) => any } interface Getters<S> { [key: string]: (this: void, state: S, getters: any, globalState: any) => any } type Actions<S, G extends Getters<S>> = { [key: string]: (this: void, context: { rootState: any, state: S, getters: GetGetters<G>, dispatch: (type: string, ...payload: any[]) => any, commit: (type: string, ...payload: any[]) => any }, ...payload: any[]) => any } type GetGetters<G> = { readonly [K in keyof G]: G[K] extends (state: any, getters: any, globalState: any) => infer R ? R : G[K] } type GetMutations<M> = { [K in keyof M]: getMutation<M[K]> } type GetActions<A> = { [K in keyof A]: getAction<A[K]> } type GetDispatch<A, D> = keyof D extends never ? (<T extends keyof A>(type: T, ...payload: A[T] extends (context: any, ...payload: infer P) => any ? P : never) => A[T] extends (context: any, ...payload: any[]) => infer R ? R : never) : ((type: string, ...payload: any[]) => any) type GetCommit<M, D> = keyof D extends never ? (<T extends keyof M>(type: T, ...payload: M[T] extends (state: any, ...payload: infer P) => any ? P : never) => M[T] extends (state: any, ...payload: any[]) => infer R ? R : never) : ((type: string, ...payload: any[]) => any) interface Store<S = {}, G = {}, M = {}, A = {}, D extends Deps = {}> { __deps: D __state: S __getters: GetGetters<G> state: S & UnboxDepsField<D, 'state'> getters: GetGetters<G> & UnboxDepsField<D, 'getters'> mutations: GetMutations<M> & UnboxDepsField<D, 'mutations'> actions: GetActions<A> & UnboxDepsField<D, 'actions'> dispatch: GetDispatch<A, D> commit: GetCommit<M, D> mapState<K extends keyof S>(maps: K[]): { [I in K]: () => S[I] } mapState(depPath: string, maps: string[]): object // mapState support object mapState<T extends { [key: string]: keyof GetAllMapKeys<S, D, 'state'> }>(obj: T): { [I in keyof T]: () => GetAllMapKeys<S, D, 'state'>[T[I]] } mapGetters<K extends keyof G>(maps: K[]): { [I in K]: () => GetGetters<G>[I] } mapGetters(depPath: string, maps: string[]): { [key: string]: () => any } mapMutations<K extends keyof M>(maps: K[]): Pick<GetMutations<M>, K> mapMutations(depPath: string, maps: string[]): { [key: string]: (...payloads: any[]) => any } mapActions<K extends keyof A>(maps: K[]): Pick<GetActions<A>, K> mapActions(depPath: string, maps: string[]): { [key: string]: (...payloads: any[]) => any } } type GetComputedSetKeys<T> = { [K in keyof T]: T[K] extends { get(): any, set(val: any): void } ? K : never }[keyof T] type GetComputedType<T> = { readonly [K in Exclude<keyof T, GetComputedSetKeys<T>>]: T[K] extends () => infer R ? R : T[K] } & { [K in GetComputedSetKeys<T>]: T[K] extends { get(): infer R, set(val: any): void } ? R : T[K] } interface MutationsAndActionsWithThis { [key: string]: (...payload: any[]) => any } type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never; interface mapStateFunctionType<S, G> { [key: string]: (state: S, getter: G) => any } interface DeeperMutationsAndActions { [key: string]: ((...payload: any[]) => any) | MutationsAndActionsWithThis } interface DeeperStateAndGetters { [key: string]: any | DeeperStateAndGetters } /** * remove compatible code in Mpx. * if you need using createStoreWithThis mix with createStore * you can add a global define file * use Declaration Merging(https://www.typescriptlang.org/docs/handbook/declaration-merging.html) on CompatibleDispatch: * @example * declare module MpxStore { * interface CompatibleDispatch { * dispatch(type: string, ...payload: any[]): any * commit(type: string, ...payload: any[]): any * } * } */ interface CompatibleDispatch { // dispatch(type: string, ...payload: any[]): any // commit(type: string, ...payload: any[]): any } // Store Type Bindings type StringKeyof<T> = Exclude<keyof T, symbol> type CombineStringKey<H extends string | number, L extends string | number> = H extends '' ? `${L}` : `${H}.${L}` type GetActionsKey<A, P extends string | number = ''> = UnionToIntersection<{ [K in StringKeyof<A>]: { [RK in CombineStringKey<P, K>]: A[K] extends DeeperMutationsAndActions ? GetActionsKey<A[K], RK> : Record<RK, A[K]> }[CombineStringKey<P, K>] }[StringKeyof<A>]> // {actA: () => void, storeB.actB: () => void} type GetStateAndGettersKey<D extends Deps, DK extends keyof D, T extends 'state' | 'getters', P extends string | number = ''> = UnionToIntersection<{ [K in StringKeyof<D[DK][`__${T}`]>]: { [RK in CombineStringKey<P, K>]: D[DK][`__${T}`][K] } }[StringKeyof<D[DK][`__${T}`]>] | { [K in StringKeyof<D[DK]['__deps']>]: GetStateAndGettersKey<D[DK]['__deps'], K, T, CombineStringKey<P, K>> }[StringKeyof<D[DK]['__deps']>]> // type GetStateAndGettersKey<S, P extends string | number = ''> = UnionToIntersection<{ // [K in StringKeyof<S>]: { // [RK in CombineStringKey<P, K>]: S[K] extends DeeperStateAndGetters ? GetStateAndGettersKey<S[K], RK> : Record<RK, S[K]> // }[CombineStringKey<P, K>] // }[StringKeyof<S>]> // {stateA: any, storeB.stateB: any} type GetAllDepsType<A, D extends Deps, AK extends 'state' | 'getters' | 'actions' | 'mutations'> = { [K in StringKeyof<A>]: A[K] } & UnionToIntersection<{ [K in StringKeyof<D>]: AK extends 'actions' | 'mutations' ? { [P in keyof GetActionsKey<D[K][AK], K>]: GetActionsKey<D[K][AK], K>[P] } : AK extends 'state' | 'getters' ? { // state, getters [P in keyof GetStateAndGettersKey<D, K, AK, K>]: GetStateAndGettersKey<D, K, AK, K>[P] // [P in keyof GetStateAndGettersKey<D[K][AK], K>]: GetStateAndGettersKey<D[K][AK], K>[P] } : {} }[StringKeyof<D>]> type GetDispatchAndCommitWithThis<A, D extends Deps, AK extends 'actions' | 'mutations'> = (<T extends keyof GetAllDepsType<A, D, AK>>(type: T, ...payload: GetAllDepsType<A, D, AK>[T] extends (...payload: infer P) => any ? P : never) => GetAllDepsType<A, D, AK>[T] extends (...payload: any[]) => infer R ? R : never) // type GetAllMapKeys<S, D extends Deps, SK extends 'state' | 'getters'> = GetAllDepsType<S, D, SK> & GetStateAndGettersKey<S> type GetAllMapKeys<S, D extends Deps, SK extends 'state' | 'getters'> = GetAllDepsType<S, D, SK> // 关闭对state、getters本身传入对象的深层次推导,因为过深的递归会导致ts推导直接挂掉 interface StoreOptWithThis<S, G, M, A, D extends Deps> { state?: S getters?: G & ThisType<{ state: S & UnboxDepsField<D, 'state'>, getters: GetComputedType<G> & UnboxDepsField<D, 'getters'>, rootState: any }> mutations?: M & ThisType<{ state: S & UnboxDepsField<D, 'state'> }> actions?: A & ThisType<{ rootState: any, state: S & UnboxDepsField<D, 'state'>, getters: GetComputedType<G> & UnboxDepsField<D, 'getters'>, dispatch: GetDispatchAndCommitWithThis<A, D, 'actions'>, commit: GetDispatchAndCommitWithThis<M, D, 'mutations'> } & CompatibleDispatch> deps?: D modules?: Record<string, StoreOptWithThis<{}, {}, {}, {}, {}>> } interface IStoreWithThis<S = {}, G = {}, M = {}, A = {}, D extends Deps = {}> { __deps: D __state: S __getters: GetComputedType<G> state: S & UnboxDepsField<D, 'state'> getters: GetComputedType<G> & UnboxDepsField<D, 'getters'> mutations: M & UnboxDepsField<D, 'mutations'> actions: A & UnboxDepsField<D, 'actions'> dispatch: GetDispatchAndCommitWithThis<A, D, 'actions'> commit: GetDispatchAndCommitWithThis<M, D, 'mutations'> mapState<K extends keyof S>(maps: K[]): { [I in K]: () => S[I] } mapState<T extends string, P extends string>(depPath: P, maps: readonly T[]): { [K in T]: () => (CombineStringKey<P, K> extends keyof GetAllMapKeys<S, D, 'state'> ? GetAllMapKeys<S, D, 'state'>[CombineStringKey<P, K>] : any) } mapState<T extends mapStateFunctionType<S & UnboxDepsField<D, 'state'>, GetComputedType<G> & UnboxDepsField<D, 'getters'>>>(obj: ThisType<any> & T): { [I in keyof T]: () => ReturnType<T[I]> } // Support chain derivation mapState<T extends { [key: string]: keyof GetAllMapKeys<S, D, 'state'> }>(obj: T): { [I in keyof T]: () => GetAllMapKeys<S, D, 'state'>[T[I]] } mapState<T extends { [key: string]: keyof S }>(obj: T): { [I in keyof T]: () => S[T[I]] } mapState<T extends { [key: string]: string }>(obj: T): { [I in keyof T]: (...payloads: any[]) => any } mapGetters<K extends keyof G>(maps: K[]): Pick<G, K> mapGetters<T extends string, P extends string>(depPath: P, maps: readonly T[]): { // use GetComputedType to get getters' returns [K in T]: () => (CombineStringKey<P, K> extends keyof GetAllMapKeys<GetComputedType<G>, D, 'getters'> ? GetAllMapKeys<GetComputedType<G>, D, 'getters'>[CombineStringKey<P, K>] : any) } // Support chain derivation mapGetters<T extends { [key: string]: keyof GetAllMapKeys<GetComputedType<G>, D, 'getters'> }>(obj: T): { [I in keyof T]: () => GetAllMapKeys<GetComputedType<G>, D, 'getters'>[T[I]] } mapGetters<T extends { [key: string]: keyof G }>(obj: T): { [I in keyof T]: G[T[I]] } // When importing js in ts file, use this method to be compatible mapGetters<T extends { [key: string]: string }>(obj: T): { [I in keyof T]: (...payloads: any[]) => any } mapMutations<K extends keyof M>(maps: K[]): Pick<M, K> mapMutations<T extends string, P extends string>(depPath: P, maps: readonly T[]): { [K in T]: CombineStringKey<P, K> extends keyof GetAllDepsType<M, D, 'mutations'> ? GetAllDepsType<M, D, 'mutations'>[CombineStringKey<P, K>] : (...payloads: any[]) => any } mapMutations<T extends { [key: string]: keyof M }>(obj: T): { [I in keyof T]: M[T[I]] } mapMutations<T extends { [key: string]: string }>(obj: T): { [I in keyof T]: (...payloads: any[]) => any } mapActions<K extends keyof A>(maps: K[]): Pick<A, K> mapActions<T extends string, P extends string>(depPath: P, maps: readonly T[]): { [K in T]: CombineStringKey<P, K> extends keyof GetAllDepsType<A, D, 'actions'> ? GetAllDepsType<A, D, 'actions'>[CombineStringKey<P, K>] : (...payloads: any[]) => any } mapActions<T extends { [key: string]: keyof A }>(obj: T): { [I in keyof T]: A[T[I]] } mapActions<T extends { [key: string]: string }>(obj: T): { [I in keyof T]: (...payloads: any[]) => any } } type StoreWithThis<S = {}, G = {}, M = {}, A = {}, D extends Deps = {}> = IStoreWithThis<S, G, M, A, D> & CompatibleDispatch interface StoreOpt<S, G, M, A, D extends Deps> { state?: S, getters?: G mutations?: M, actions?: A, deps?: D modules?: Record<string, StoreOpt<{}, {}, {}, {}, {}>> } }
the_stack
import Restful from '../../'; import { BulkEbayOfferDetailsWithKeys, BulkInventoryItem, BulkMigrateListing, BulkOffer, BulkPriceQuantity, Compatibility, EbayOfferDetailsWithId, EbayOfferDetailsWithKeys, InventoryItemGroup, InventoryLocation, InventoryLocationFull, OfferKeysWithId, PublishByInventoryItemGroupRequest, SellInventoryItem, WithdrawByInventoryItemGroupRequest, } from '../../../../types'; /** * The Inventory API is used to create and manage inventory, and then to publish and manage this inventory on an eBay * marketplace. */ export default class Inventory extends Restful { static id = 'Inventory'; get basePath(): string { return '/sell/inventory/v1'; } /** * This call retrieves all defined details of the inventory location that is specified by the * <b>merchantLocationKey</b> path parameter. * * @param merchantLocationKey A unique merchant-defined key (ID) for an inventory location. */ public getInventoryLocation(merchantLocationKey: string) { const key = encodeURIComponent(merchantLocationKey); return this.get(`/location/${key}`); } /** * <p>This call disables the inventory location that is specified in the <code>merchantLocationKey</code> path * parameter. * * @param merchantLocationKey A unique merchant-defined key (ID) for an inventory location. */ public disableInventoryLocation(merchantLocationKey: string) { const key = encodeURIComponent(merchantLocationKey); return this.post(`/location/${key}/disable`); } /** * <p>This call enables a disabled inventory location that is specified in the <code>merchantLocationKey</code> * path parameter. * * @param merchantLocationKey A unique merchant-defined key (ID) for an inventory location. */ public enableInventoryLocation(merchantLocationKey: string) { const key = encodeURIComponent(merchantLocationKey); return this.post(`/location/${key}/enable`); } /** * This call retrieves all defined details for every inventory location associated with the seller's account. * * @param limit The value passed in this query parameter sets the maximum number of records to return per page of * data. * @param offset The value passed in this query parameter sets the page number to retrieve. */ public getInventoryLocations({ limit, offset, }: { limit?: number; offset?: number } = {}) { return this.get(`/location`, { params: { limit, offset, }, }); } /** * <p>Use this call to create a new inventory location. * * @param merchantLocationKey A unique merchant-defined key (ID) for an inventory location. * @param body Inventory Location details */ public createInventoryLocation( merchantLocationKey: string, body: InventoryLocationFull ) { const key = encodeURIComponent(merchantLocationKey); return this.post(`/location/${key}`, body); } /** * <p>This call deletes the inventory location that is specified in the <code>merchantLocationKey</code> path * parameter. * * @param merchantLocationKey A unique merchant-defined key (ID) for an inventory location. */ public deleteInventoryLocation(merchantLocationKey: string) { const key = encodeURIComponent(merchantLocationKey); return this.delete(`/location/${key}`); } /** * <p>Use this call to update non-physical location details for an existing inventory location. * * @param merchantLocationKey A unique merchant-defined key (ID) for an inventory location. * @param body The inventory location details to be updated (other than the address and geo co-ordinates). */ public updateInventoryLocation( merchantLocationKey: string, body?: InventoryLocation ) { const key = encodeURIComponent(merchantLocationKey); return this.post(`/location/${key}/update_location_details`, body); } /** * This call retrieves the inventory item record for a given SKU. * * @param sku his is the seller-defined SKU value of the product whose inventory item record you wish to * retrieve.<br/><br/><strong>Max length</strong>: 50. */ public getInventoryItem(sku: string) { sku = encodeURIComponent(sku); return this.get(`/inventory_item/${sku}`); } /** * This call creates a new inventory item record or replaces an existing inventory item record. * * @param sku The seller-defined SKU value for the inventory item is required whether the seller is creating a new * inventory item, or updating an existing inventory item. * @param body Details of the inventory item record. */ public createOrReplaceInventoryItem(sku: string, body: SellInventoryItem) { sku = encodeURIComponent(sku); return this.put(`/inventory_item/${sku}`, body); } /** * This call is used to delete an inventory item record associated with a specified SKU. * * @param sku The seller-defined SKU value for the inventory item is required whether the seller is creating a new * inventory item, or updating an existing inventory item. */ public deleteInventoryItem(sku: string) { sku = encodeURIComponent(sku); return this.delete(`/inventory_item/${sku}`); } /** * This call retrieves all inventory item records defined for the seller's account. * * @param limit The value passed in this query parameter sets the maximum number of records to return per page of * data. * @param offset The value passed in this query parameter sets the page number to retrieve. */ public getInventoryItems({ limit, offset, }: { limit?: number; offset?: number } = {}) { return this.get(`/inventory_item`, { params: { limit, offset, }, }); } /** * This call is used by the seller to update the total ship-to-home quantity of one inventory item, * and/or to update the price and/or quantity of one or more offers associated with one inventory item. * * @param body BulkPriceQuantity */ public bulkUpdatePriceQuantity(body: BulkPriceQuantity) { return this.post(`/bulk_update_price_quantity`, body); } /** * This call can be used to create and/or update up to 25 new inventory item records. * * @param body BulkInventoryItem */ public bulkCreateOrReplaceInventoryItem(body: BulkInventoryItem) { return this.post(`/bulk_create_or_replace_inventory_item`, body); } /** * This call retrieves up to 25 inventory item records. The SKU value of each inventory item record to retrieve is * specified in the request payload. * * @param body BulkInventoryItem */ public bulkGetInventoryItem(body: BulkInventoryItem) { return this.post(`/bulk_get_inventory_item`, body); } /** * This call is used by the seller to retrieve the list of products that are compatible with the inventory item. * * @param sku A SKU (stock keeping unit) is an unique identifier defined by a seller for a product */ public getProductCompatibility(sku: string) { sku = encodeURIComponent(sku); return this.get(`/inventory_item/${sku}/product_compatibility`); } /** * This call is used by the seller to create or replace a list of products that are compatible with the inventory * item. * * @param sku A SKU (stock keeping unit) is an unique identifier defined by a seller for a product * @param body Details of the compatibility */ public createOrReplaceProductCompatibility(sku: string, body: Compatibility) { sku = encodeURIComponent(sku); return this.put(`/inventory_item/${sku}/product_compatibility`, body); } /** * This call is used by the seller to delete the list of products that are compatible with the inventory item that * is associated with the compatible product list. * * @param sku A SKU (stock keeping unit) is an unique identifier defined by a seller for a product */ public deleteProductCompatibility(sku: string) { sku = encodeURIComponent(sku); return this.delete(`/inventory_item/${sku}/product_compatibility`); } /** * This call retrieves all existing offers for the specified SKU value. * * @param sku The seller-defined SKU value is passed in as a query parameter. * @param marketplace_id The unique identifier of the eBay marketplace. * @param format This enumeration value sets the listing format for the offer. * @param limit The value passed in this query parameter sets the maximum number of records to return per page of * data. * @param offset The value passed in this query parameter sets the page number to retrieve. */ public getOffers({ sku, marketplaceId, format, limit, offset, }: { sku?: string; marketplaceId?: string; format?: string; limit?: number; offset?: number; } = {}) { return this.get(`/offer`, { params: { sku, marketplace_id: marketplaceId, format, limit, offset, }, }); } /** * This call retrieves a specific published or unpublished offer. * * @param offerId The unique identifier of the offer that is to be retrieved. */ public getOffer(offerId: string) { offerId = encodeURIComponent(offerId); return this.get(`/offer/${offerId}`); } /** * This call creates an offer for a specific inventory item on a specific eBay marketplace. * * @param body Details of the offer for the channel */ public createOffer(body: EbayOfferDetailsWithKeys) { return this.post(`/offer`, body); } /** * This call updates an existing offer. * * @param offerId The unique identifier of the offer that is being updated. * @param body Details of the offer for the channel */ public updateOffer(offerId: string, body: EbayOfferDetailsWithId) { offerId = encodeURIComponent(offerId); return this.put(`/offer/${offerId}`, body); } /** * If used against an unpublished offer, this call will permanently delete that offer. * * @param offerId The unique identifier of the offer to delete. */ public deleteOffer(offerId: string) { return this.delete(`/offer/${offerId}`); } /** * This call is used to convert an unpublished offer into a published offer, or live eBay listing. * * @param offerId The unique identifier of the offer that is to be published. */ public publishOffer(offerId: string) { const id = encodeURIComponent(offerId); return this.post(`/offer/${id}/publish/`); } /** * This call is used to convert all unpublished offers associated with an inventory item group into an active, * multiple-variation listing. * * @param body PublishByInventoryItemGroupRequest */ public publishOfferByInventoryItemGroup( body: PublishByInventoryItemGroupRequest ) { return this.post(`/offer/publish_by_inventory_item_group/`, body); } /** * This call is used to end a multiple-variation eBay listing that is associated with the specified inventory item * group. * * @param body WithdrawByInventoryItemGroupRequest */ public withdrawOfferByInventoryItemGroup( body: WithdrawByInventoryItemGroupRequest ) { return this.post(`/offer/withdraw_by_inventory_item_group`, body); } /** * This call is used to retrieve the expected listing fees for up to 250 unpublished offers. * * @param body OfferKeysWithId */ public getListingFees(body: OfferKeysWithId) { return this.post(`/offer/get_listing_fees`, body); } /** * This call creates multiple offers (up to 25) for specific inventory items on a specific eBay marketplace. * * @param body BulkEbayOfferDetailsWithKeys */ public bulkCreateOffer(body: BulkEbayOfferDetailsWithKeys) { return this.post(`/bulk_create_offer`, body); } /** * This call is used to convert unpublished offers (up to 25) into published offers, or live eBay listings. * * @param body BulkOffer */ public bulkPublishOffer(body: BulkOffer) { return this.post(`/bulk_publish_offer`, body); } /** * This call is used to end a single-variation listing that is associated with the specified offer. * * @param offerId he unique identifier of the offer that is to be withdrawn. */ public withdrawOffer(offerId: string) { const id = encodeURIComponent(offerId); return this.post(`/offer/${id}/withdraw`); } /** * This call retrieves the inventory item group for a given <strong>inventoryItemGroupKey</strong> value. * * @param inventoryItemGroupKey The unique identifier of an inventory item group. */ public getInventoryItemGroup(inventoryItemGroupKey: string) { inventoryItemGroupKey = encodeURIComponent(inventoryItemGroupKey); return this.get(`/inventory_item_group/${inventoryItemGroupKey}`); } /** * This call creates a new inventory item group or updates an existing inventory item group. * * @param inventoryItemGroupKey Unique identifier of the inventory item group. * @param body Details of the inventory Item Group */ public createOrReplaceInventoryItemGroup( inventoryItemGroupKey: string, body: InventoryItemGroup ) { inventoryItemGroupKey = encodeURIComponent(inventoryItemGroupKey); return this.put(`/inventory_item_group/${inventoryItemGroupKey}`, body); } /** * This call deletes the inventory item group for a given <strong>inventoryItemGroupKey</strong> value. * * @param inventoryItemGroupKey Unique identifier of the inventory item group. */ public deleteInventoryItemGroup(inventoryItemGroupKey: string) { return this.delete(`/inventory_item_group/${inventoryItemGroupKey}`); } /** * This call is used to convert existing eBay Listings to the corresponding Inventory API objects. * * @param body BulkMigrateListing */ public bulkMigrateListing(body: BulkMigrateListing) { return this.post(`/bulk_migrate_listing`, body); } }
the_stack
/// <reference types="node" /> export interface Box { x: number; y: number; width: number; height: number; } export interface Point { x: number; y: number; } export interface Segment { p1: Point; p2: Point; error: number; } export interface Skew { angle: number; confidence: number; } export interface Component { x: number; y: number; width: number; height: number; } export class Image { /** * Creates a copy of otherImage. */ constructor(otherImage: Image); /** * Creates a 32 bit imagen from three 8 bit images, where each image represents one channel of RGB or HSV. */ constructor(image1: Image, image2: Image, image3: Image); /** * Creates an empty image with the specified dimensions (!!! note: this constructor is experimental and likely to change). */ constructor(width: number, height: number, depth: number); /** * Creates an image from a Buffer object, that contains the PNG/JPG encoded image. */ constructor(type: 'png' | 'jpg', buffer: Buffer); constructor(type: 'rgba' | 'rgb' | 'gray', buffer: Buffer, width: number, height: number); readonly width: number; readonly height: number; /** * The depth of the image in bits per pixel, i.e. one of 32 (color), 8 (grayscale) or 1 (monochrome). */ readonly depth: number; /** * Returns the (boolean) inverse of this image. */ invert(): Image; /** * Returns the (boolean) union of two images with equal depth, aligning them to the upper left corner. */ or(otherImage: Image): Image; /** * Returns the (boolean) difference of two images with equal depth, aligning them to the upper left corner. */ and(otherImage: Image): Image; /** * Returns the (boolean) exclusive disjunction of two images with equal depth, aligning them to the upper left corner. */ xor(otherImage: Image): Image; /** * If the images are monochrome, dispatches to Leptonica's pixOr. Otherwise, returns the channelwise addition of b to a, clipped at 255. */ add(otherImage: Image): Image; /** * If the images are monochrome, dispatches to Leptonica's pixSubtract and is equivalent to a.and(b.invert()). * For grayscale images, returns the pixelwise subtraction of b from a, clipped at zero. * For color, the entire RGB value is subtracted instead of doing channelwise subtraction (ask Leptonica why). * @example: * redness = colorImage.toGray(1, 0, 0).subtract(colorImage.toGray(0, 0.5, 0.5)) */ subtract(otherImage: Image): Image; /** * Applies a convoltuion kernel with the specified dimensions. Image convolution is an operation where each destination pixel is computed based on a weighted sum of a set of nearby source pixels. */ convolve(halfWidth: number, halfHeight: number): Image; /** * Unsharp Masking creates an unsharp mask using halfWidth. * The fraction determines how much of the edge is added back into image. * The resulting image appears clearer, but it is generally less accurate. */ unsharp(halfWidth: number, fraction: number): Image; /** * Rotates the image around its center by the specified angle in degrees. */ rotate(angle: number): Image; /** * Scales an image proportionally by scale (1.0 = 100%). */ scale(scale: number): Image; /** * Scales an image by scaleX and scaleY (1.0 = 100%). */ scale(scaleX: number, scaleY: number): Image; /** * Crops an image from this image by the specified rectangle and returns the resulting image. */ crop(box: Box): Image; crop(x: number, y: number, width: number, height: number): Image; /** * Creates a mask by testing if pixels (RGB, HSV, ...) are between lower and upper. Formally speaking: * lower1 ≤ pixel1 ≤ upper1 * ∧ lower2 ≤ pixel2 ≤ upper2 * ∧ lower3 ≤ pixel3 ≤ upper3 */ inRange(lower1: number, lower2: number, lower3: number, upper1: number, upper2: number, upper3: number): Image; /** * Only available for grayscale images. Returns the histogram in an array of length 256, where each entry represents the fraction (0.0 to 1.0) of that color in the image. * The mask parameter is optional and must be a monochrome image of same width and height; only pixels where mask is 0 will be counted. */ histogram(mask?: Image): Image; /** * Computes the horizontal or vertical projection of an 1bpp or 8bpp image. */ projection(mode: 'horizontal' | 'vertical'): number[]; /** * Sets the specified value to each pixel set in the mask. */ setMasked(mask: Image, value: number): Image; /** * Available for grayscale and color images. Channelwise maps each pixel of image using mapping, which must be an array of length 256 with integer values between 0 and 255. * !!! !!! Note: this function actually changes the image! * The mask parameter is optional and must be a monochrome image of same width and height; only pixels where mask is 0 will be modified. */ applyCurve(mapping: number[], mask?: Image): this; /** * Applies a rank (0.0 ... 1.0) filter of the specified width * and height (think of it as radius) to this image * and returns the result. * If you set rank to 0.5 you'll get a Median Filter. * Note that this type of filter works best with odd sizes like 3 or 5. */ rankFilter(width: number, height: number, rank: number): Image; /** * Color image quantization using an octree based algorithm. * colors must be between 2 and 256. * Note that support for the resulting palette image is highly experimental at this point; * only toGray() and toBuffer('png') are guaranteed to work. */ octreeColorQuant(colors: number): Image; /** * Color image quantization using median cut algorithm. * colors must be between 2 and 256. * Note that support for the resulting palette image is highly experimental at this point; * only toGray() and toBuffer('png') are guaranteed to work. */ medianCutQuant(colors: number): Image; /** * Converts a grayscale image to monochrome using a global threshold. value must be between 0 and 255. */ threshold(value: number): Image; /** * Converts an image to grayscale using default settings. Can be used to convert monochrome images back to grayscale. */ toGray(): Image; /** * Converts an RGB image to grayscale using the specified widths for each channel. */ toGray(redWeight: number, greenWeight: number, blueWeight: number): Image; /** * Converts an RGB image to grayscale by selecting either the 'min' or 'max' channel. * This can act as a simple color filter: 'max' maps colored pixels towards white, * while 'min' maps colored pixels towards black. */ toGray(selector: 'min' | 'max'): Image; /** * Converts a grayscale image to a color image. */ toColor(): Image; /** * Converts from RGB to HSV color space. HSV has the following ranges: * Hue: [0 .. 239] * Saturation: [0 .. 255] * Value: [0 .. 255] */ toHSV(): Image; /** * Converts from HSV to RGB color space. */ toRGB(): Image; /** * Applies an Erode Filter and returns the result. */ erode(width: number, height: number): Image; /** * Applies a Dilate Filter and returns the result. */ dilate(width: number, height: number): Image; /** * Applies an Open Filter and returns the result. */ open(width: number, height: number): Image; /** * Applies a Close Filter and returns the result. */ close(width: number, height: number): Image; /** * Applies morphological thinning of type (fg or bg) with the specified connectivitiy (4 or 8) and maxIterations (0 to iterate until complete). */ thin(type: 'fg' | 'bg', connectivity: number, maxIterations: number): Image; /** * Scales an 8bpp image for maximum dynamic range. scale must be either log or linear. */ maxDynamicRange(scale: 'log' | 'linear'): Image; /** * Applies Otsu's Method for computing the threshold of a grayscale image. * It computes a threshold for each tile of the specified size and performs the threshold operation, * resulting in a binary image for each tile. These are stitched into the final result. * The smooth size controls the a convolution kernel applied to threshold array (use 0 for no smoothing). * The score factor controls the fraction of the max. Otsu score (typically 0.1; use 0.0 for standard Otsu). */ otsuAdaptiveThreshold(tileWidth: number, tileHeight: number, smoothWidth: number, smoothHeight: number, scoreFactor: number): Image; /** * Detects Line Segments with the specified accuracy (3 is a good start). The number of found line segments can be limited using maxLineSegments (0 is unlimited). */ lineSegments(accuracy: number, maxLineSegments: number, useWeightedMeanShift: boolean): Segment[]; /** * Only available for monochrome images. Tries to find the skew of this image. The resulting angle is in degree. The confidence is between 0.0 and 1.0. */ findSkew(): Skew; /** * Only available for monochrome images. Tries to extract connected components (think of flood fill). The connectivity can be specified as 4 or 8 directions. */ connectedComponents(connectivity: 4 | 8): Component[]; /** * The Distance Function works on 1bpp images. It labels each pixel with the largest distance between this and any other pixel in its connected component. The connectivity is either 4 or 8. */ distanceFunction(connectivity: 4 | 8): Image; /** * !!! Note: this function actually changes the image! * Fills a specified rectangle with white. */ clearBox(box: Box): this; clearBox(x: number, y: number, width: number, height: number): this; /** * !!! Note: this function actually changes the image! * Draws a filled rectangle to this image with the specified value. Works for 8bpp and 1bpp images. */ fillBox(box: Box, value: number): this; fillBox(x: number, y: number, width: number, height: number, value: number): this; /** * !!! Note: this function actually changes the image! * Draws a filled rectangle to this image in the specified color with an optional blending parameter (0.0: transparent; 1.0: no transparency). */ fillBox(box: Box, r: number, g: number, b: number, fraction?: number): this; fillBox(x: number, y: number, width: number, height: number, r: number, g: number, b: number, fraction?: number): this; /** * !!! Note: this function actually changes the image! * Draws a rectangle to this image with the specified border. The possible pixel manipulating operations are set, clear and flip. */ drawBox(box: Box, borderWidth: number, operation: 'set' | 'clear' | 'flip'): this; drawBox(x: number, y: number, width: number, height: number, borderWidth: number, operation: 'set' | 'clear' | 'flip'): this; /** * !!! Note: this function actually changes the image! * Draws a rectangle to this image with the specified border in the specified color with an optional blending parameter (0.0: transparent; 1.0: no transparency). */ drawBox(box: Box, borderWidth: number, red: number, green: number, blue: number, frac?: number): this; drawBox(x: number, y: number, width: number, height: number, borderWidth: number, red: number, green: number, blue: number, frac?: number): this; /** * !!! Note: this function actually changes the image! * Draws a line between p1 and p2 to this image with the specified line width. The possible pixel manipulating operations are set, clear and flip. */ drawLine(p1: Point, p2: Point, width: number, operation: 'set' | 'clear' | 'flip'): this; /** * !!! Note: this function actually changes the image! * Draws a line between p1 and p2 to this image with the specified line width in the specified color with an optional blending parameter (0.0: transparent; 1.0: no transparency). */ drawLine(p1: Point, p2: Point, width: number, red: number, green: number, blue: number, frac?: number): this; /** * !!! Note: this function actually changes the image! * Draws an image to this image with the specified destination box. */ drawImage(image: Image, box: Box): this; drawImage(image: Image, x: number, y: number, width: number, height: number): this; /** * Converts the Image in the specified format to a buffer. * Specifying raw returns the raw image data as buffer. * For color images, the result contains three bytes per pixel in the order R, G, B; * for grayscale and monochrome images, it contains one byte per pixel. * Specifying png returns a PNG encoded image as buffer. * Specifying jpg returns a JPG encoded image as buffer. */ toBuffer(format?: 'raw' | 'png' | 'jpg'): Buffer; } export interface Rect { x: number; y: number; width: number; height: number; } export interface Region { box: Box; text: string; confidence: number; } export type Paragaph = Region; export interface Textline { box: Box; } export type Word = Region; export interface Choice { text: string; confidence: number; } export interface Symbol extends Region { choices: Choice[]; } export type Text = Choice; /** * A Tesseract object represents an optical character recognition engine, that reads text using Tesseract from an image. * Tesseract supports many langauges and fonts (see Tesseract/Downloads). * New language files have to be installed in node-dv/tessdata. */ export class Tesseract { /** * Creates a Tesseract engine with language set to english. */ constructor(); constructor(datapath: string); /** * Creates a Tesseract engine with the specified language. */ constructor(lang: string, image: Image); /** * Creates a Tesseract engine with the specified language and image. */ constructor(datapath: string, lang: string, image: Image); /** * Accessor for the input image. */ image: Image; /** * Accessor for the rectangle that specifies a "visible" area on the image. */ rectangle: Rect; /** * Accessor for the page segmentation mode. */ pageSegMode: 'osd_only' | 'auto_osd' | 'auto_only' | 'auto' | 'single_column' | 'single_block_vert_text' | 'single_block' | 'single_line' | 'single_word' | 'circle_word' | 'single_char' | 'sparse_text' | 'sparse_text_osd'; [key: string]: unknown; /** * Clears the tesseract image and its last results. */ clear(): void; /** * Clears all adaptive classifiers (use this when results vary during scanning). */ clearAdaptiveClassifier(): void; /** * Returns the binarized image Tesseract uses for its recognition. */ thresholdImage(): Image; /** * Returns an array of objects, You can omit text information by setting recognize = false, which is considerably faster. */ findRegions(recognize: boolean): Region[]; /** * Returns an array of objects, You can omit text information by setting recognize = false, which is considerably faster. */ findParagraphs(recognize: boolean): Paragaph[]; /** * Returns an array of objects, You can omit text information by setting recognize = false, which is considerably faster. */ findTextLines(recognize: boolean): Textline[]; /** * Returns an array of objects, You can omit text information by setting recognize = false, which is considerably faster. */ findWords(recognize: boolean): Word[]; /** * Returns an array of objects, You can omit text information by setting recognize = false, which is considerably faster. */ findSymbols(recognize: boolean): symbol[]; /** * Returns text in the specified format. Valid formats are: plain, unlv. */ findText(format: 'plain' | 'unlv', withConfidence?: boolean): string; findText(format: 'hocr' | 'box', pageNumber: number): string; } export interface Barcodeformat { QR_CODE: boolean; DATA_MATRIX: boolean; PDF_417: boolean; UPC_E: boolean; UPC_A: boolean; EAN_8: boolean; EAN_13: boolean; CODE_128: boolean; CODE_39: boolean; ITF: boolean; AZTEC: boolean; } export interface BarCode { type: string; data: string; buffer: Buffer; points: Point[]; } /** * A ZXing object represents a barcode reader. By default it attempts to decode all barcode formats that ZXing supports. */ export class ZXing { constructor(image?: Image); /** * Accessor for the input image this barcode reader operates on. */ image: Image; /** * List of barcodes the reader tries to find. It's specified as an object and missing properties account as false */ formats: Barcodeformat; /** * If try harder is enabled, the barcode reader spends more time trying to find a barcode (optimize for accuracy, not speed). */ tryHarder: boolean; /** * Returns the first barcode found as an object with the following format: */ findCode(): BarCode; /** * enotes the barcodes type. */ readonly type: 'None' | 'QR_CODE' | 'DATA_MATRIX' | 'PDF_417' | 'UPC_E' | 'UPC_A' | 'EAN_8' | 'EAN_13' | 'CODE_128' | 'CODE_39' | 'ITF' | 'AZTEC'; /** * denotes the stringified data read from the barcode. */ readonly data: string; /** * denotes the decoded binary data of the barcode before conversion into another character encoding. */ readonly buffer: Buffer; /** * denotes the points in pixels which were used by the barcode reader to detect the barcode. */ readonly points: Point[]; }
the_stack
import React from "react"; import rpcService from "../../../app/service/rpc_service"; import { BuildBuddyError } from "../../../app/util/errors"; import { User } from "../../../app/auth/auth_service"; import { scheduler } from "../../../proto/scheduler_ts_proto"; import ExecutorCardComponent from "./executor_card"; import { Subscription } from "rxjs"; import capabilities from "../../../app/capabilities/capabilities"; import { api_key } from "../../../proto/api_key_ts_proto"; import { bazel_config } from "../../../proto/bazel_config_ts_proto"; import { FilledButton } from "../../../app/components/button/button"; import router from "../../../app/router/router"; import Select, { Option } from "../../../app/components/select/select"; enum FetchType { Executors, ApiKeys, BazelConfig, } function onClickLink(href: string, e: React.MouseEvent<HTMLAnchorElement>) { e.preventDefault(); router.navigateTo(href); } interface ExecutorDeployProps { executorKeys: api_key.IApiKey[]; schedulerUri: string; } interface ExecutorDeployState { selectedExecutorKeyIdx: number; } class ExecutorDeploy extends React.Component<ExecutorDeployProps, ExecutorDeployState> { state = { selectedExecutorKeyIdx: 0 }; onSelectExecutorApiKey(e: React.ChangeEvent<HTMLSelectElement>) { this.setState({ selectedExecutorKeyIdx: Number(e.target.value) }); } render() { return ( <> <p>Self-hosted executors can be deployed by running a simple Docker image on any machine.</p> <p>The example below shows how to run an executor manually using the Docker CLI.</p> API key: <Select title="Select API key" className="credential-picker" name="selectedCredential" value={this.state.selectedExecutorKeyIdx} onChange={this.onSelectExecutorApiKey.bind(this)}> {this.props.executorKeys.map((key, index) => ( <Option key={index} value={index}> {key.label || "Untitled key"} - {key.value} </Option> ))} </Select> <code> <pre> {`docker run --mount type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock \\ gcr.io/flame-public/buildbuddy-executor-enterprise:latest \\ --executor.docker_socket=/var/run/docker.sock \\ --executor.app_target=${this.props.schedulerUri} \\ --executor.api_key=${this.props.executorKeys[this.state.selectedExecutorKeyIdx]?.value}`} </pre> </code> </> ); } } interface ExecutorSetupProps { executorKeys: api_key.IApiKey[]; executors: scheduler.IExecutionNode[]; schedulerUri: string; } class ExecutorSetup extends React.Component<ExecutorSetupProps> { state = { selectedExecutorKeyIdx: 0 }; render() { return ( <> <hr /> <h2>1. Create an API key for executor registration</h2> {this.props.executorKeys.length == 0 && ( <div> <p>There are no API keys with the executor capability configured for your organization.</p> <p>API keys are used to authorize self-hosted executors.</p> <FilledButton className="manage-keys-button"> <a href="/settings/" onClick={onClickLink.bind("/settings")}> Manage keys </a> </FilledButton> </div> )} {this.props.executorKeys.length > 0 && ( <> <div> {this.props.executorKeys.length == 1 && <p>You have an Executor API key available.</p>} {this.props.executorKeys.length > 1 && ( <p>You have {this.props.executorKeys.length} Executor API keys available. </p> )} <p>These API keys can be used to deploy your executors.</p> </div> <h2>2. Deploy executors</h2> <ExecutorDeploy executorKeys={this.props.executorKeys} schedulerUri={this.props.schedulerUri} /> {this.props.executors.length == 1 && <p>You have 1 self-hosted executor connected.</p>} {this.props.executors.length != 1 && ( <p>You have {this.props.executors.length} self-hosted executors connected.</p> )} <h2>3. Switch to self-hosted executors in organization settings</h2> <p>Enable "Use self-hosted executors" on the Organization Settings page.</p> <FilledButton className="organization-settings-button"> <a href="/settings/" onClick={onClickLink.bind("/settings")}> Open settings </a> </FilledButton> </> )} </> ); } } interface ExecutorsListProps { executors: scheduler.IExecutionNode[]; } class ExecutorsList extends React.Component<ExecutorsListProps> { render() { let executorsByPool = new Map<string, scheduler.IExecutionNode[]>(); for (const e of this.props.executors) { const key = e.os + "-" + e.arch + "-" + e.pool; if (!executorsByPool.has(key)) { executorsByPool.set(key, []); } executorsByPool.get(key).push(e); } const keys = Array.from(executorsByPool.keys()).sort(); return ( <> <div className="executor-cards"> {} {keys .map((key) => executorsByPool.get(key)) .map((executors) => ( <> <h2> {executors[0].os}/{executors[0].arch} {executors[0].pool || "Default Pool"} </h2> {executors.length == 1 && <p>There is 1 self-hosted executor in this pool.</p>} {executors.length > 1 && <p>There are {executors.length} self-hosted executors in this pool.</p>} {executors.length < 3 && ( <p>For better performance and reliability, we suggest running a minimum of 3 executors per pool.</p> )} {executors.map((node) => ( <ExecutorCardComponent node={node} /> ))} </> ))} </div> </> ); } } interface Props { user: User; hash: string; search: URLSearchParams; } interface State { userOwnedExecutorsSupported: boolean; nodes: scheduler.IExecutionNode[]; executorKeys: api_key.IApiKey[]; loading: FetchType[]; schedulerUri: string; error: BuildBuddyError | null; } export default class ExecutorsComponent extends React.Component<Props, State> { state: State = { userOwnedExecutorsSupported: false, nodes: [], executorKeys: [], loading: [], schedulerUri: "", error: null, }; subscription: Subscription; componentWillMount() { document.title = `Executors | BuildBuddy`; } componentDidMount() { this.fetch(); this.subscription = rpcService.events.subscribe({ next: (name) => name == "refresh" && this.fetch(), }); } componentWillUnmount() { this.subscription?.unsubscribe(); } componentDidUpdate(prevProps: Props) { if (this.props.hash !== prevProps.hash || this.props.search != prevProps.search) { this.fetch(); } } async fetchApiKeys() { if (!this.props.user) return; this.setState((prevState) => ({ loading: [...prevState.loading, FetchType.ApiKeys], })); try { const response = await rpcService.service.getApiKeys({ groupId: this.props.user.selectedGroup.id }); const executorKeys = response.apiKey.filter((key) => key.capability.some((cap) => cap == api_key.ApiKey.Capability.REGISTER_EXECUTOR_CAPABILITY) ); this.setState({ executorKeys: executorKeys }); } catch (e) { this.setState({ error: BuildBuddyError.parse(e) }); } finally { this.setState((prevState) => ({ loading: [...prevState.loading].filter((f) => f != FetchType.ApiKeys), })); } } async fetchExecutors() { this.setState((prevState) => ({ loading: [...prevState.loading, FetchType.Executors], })); try { const response = await rpcService.service.getExecutionNodes({}); this.setState({ nodes: response.executionNode, userOwnedExecutorsSupported: response.userOwnedExecutorsSupported, }); if (response.userOwnedExecutorsSupported) { await this.fetchApiKeys(); await this.fetchBazelConfig(); } } catch (e) { this.setState({ error: BuildBuddyError.parse(e) }); } finally { this.setState((prevState) => ({ loading: [...prevState.loading].filter((f) => f != FetchType.Executors), })); } } async fetchBazelConfig() { this.setState((prevState) => ({ loading: [...prevState.loading, FetchType.BazelConfig], })); try { let request = new bazel_config.GetBazelConfigRequest(); request.host = window.location.host; request.protocol = window.location.protocol; const response = await rpcService.service.getBazelConfig(request); const schedulerUri = response.configOption.find((opt) => opt.flagName == "remote_executor"); this.setState({ schedulerUri: schedulerUri?.flagValue }); } catch (e) { this.setState({ error: BuildBuddyError.parse(e) }); } finally { this.setState((prevState) => ({ loading: [...prevState.loading].filter((f) => f != FetchType.BazelConfig), })); } } fetch() { this.fetchExecutors(); } // "bring your own runners" is enabled for the installation (i.e. BuildBuddy Cloud deployment). renderWithGroupOwnedExecutorsEnabled() { if (this.props.user?.selectedGroup?.useGroupOwnedExecutors) { if (this.state.nodes.length == 0) { return ( <div className="empty-state"> <h1>No self-hosted executors connected.</h1> <p>Self-hosted executors are enabled, but there are no executors connected.</p> <p>Follow the instructions below to deploy your executors.</p> <ExecutorSetup executorKeys={this.state.executorKeys} executors={this.state.nodes} schedulerUri={this.state.schedulerUri} /> </div> ); } return ( <> <h1>Self-hosted executors</h1> <ExecutorsList executors={this.state.nodes} /> <hr /> <h1>Deploying additional executors</h1> <ExecutorDeploy executorKeys={this.state.executorKeys} schedulerUri={this.state.schedulerUri} /> </> ); } else { return ( <div className="empty-state"> <h1>You're currently using BuildBuddy Cloud executors.</h1> <p>See the instructions below if you'd like to use self-hosted executors.</p> <ExecutorSetup executorKeys={this.state.executorKeys} executors={this.state.nodes} schedulerUri={this.state.schedulerUri} /> </div> ); } } // "bring your own runners" is not enabled for the installation (i.e. onprem deployment) renderWithoutGroupOwnedExecutorsEnabled() { if (this.state.nodes.length == 0) { return ( <div className="empty-state"> <h1>No remote execution nodes found!</h1> <p> Check out our documentation on deploying remote executors: <br /> <br /> <a className="button" href="https://docs.buildbuddy.io/docs/enterprise-rbe"> Click here for more information </a> </p> </div> ); } else { return <ExecutorsList executors={this.state.nodes} />; } } render() { return ( <div className="executors-page"> <div className="shelf"> <div className="container"> <div className="breadcrumbs"> {this.props.user && <span>{this.props.user?.selectedGroupName()}</span>} <span>Executors</span> </div> <div className="title">Executors</div> </div> </div> {this.state.error && <div className="error-message">{this.state.error.message}</div>} {this.state.loading.length > 0 && <div className="loading"></div>} {this.state.loading.length == 0 && this.state.error == null && ( <div className="container"> {this.state.userOwnedExecutorsSupported && this.renderWithGroupOwnedExecutorsEnabled()} {!this.state.userOwnedExecutorsSupported && this.renderWithoutGroupOwnedExecutorsEnabled()} </div> )} </div> ); } }
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; import { AbortConfig, Action, ActiveViolation, AggregationType, AlertTarget, AuditCheckConfiguration, AuditCheckDetails, AuditFinding, AuditFrequency, AuditMitigationActionExecutionMetadata, AuditMitigationActionsExecutionStatus, AuditMitigationActionsTaskMetadata, AuditMitigationActionsTaskStatus, AuditMitigationActionsTaskTarget, AuditNotificationTarget, AuditSuppression, AuditTaskMetadata, AuditTaskStatus, AuditTaskType, AuthorizerConfig, AuthorizerDescription, AuthorizerStatus, AuthorizerSummary, AutoRegistrationStatus, AwsJobExecutionsRolloutConfig, AwsJobPresignedUrlConfig, Behavior, BillingGroupProperties, CustomMetricType, DayOfWeek, DimensionType, FleetMetricUnit, JobExecutionsRolloutConfig, LogLevel, MetricToRetain, MitigationActionParams, OTAUpdateFile, OTAUpdateStatus, Policy, PresignedUrlConfig, Protocol, ProvisioningHook, ResourceIdentifier, ServiceType, StreamFile, Tag, TargetSelection, TaskStatisticsForAuditCheck, ThingGroupProperties, ThingTypeProperties, TimeoutConfig, TopicRuleDestination, VerificationState, } from "./models_0"; export interface DeleteSecurityProfileResponse {} export namespace DeleteSecurityProfileResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteSecurityProfileResponse): any => ({ ...obj, }); } export interface DeleteStreamRequest { /** * <p>The stream ID.</p> */ streamId: string | undefined; } export namespace DeleteStreamRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteStreamRequest): any => ({ ...obj, }); } export interface DeleteStreamResponse {} export namespace DeleteStreamResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteStreamResponse): any => ({ ...obj, }); } /** * <p>The input for the DeleteThing operation.</p> */ export interface DeleteThingRequest { /** * <p>The name of the thing to delete.</p> */ thingName: string | undefined; /** * <p>The expected version of the thing record in the registry. If the version of the * record in the registry does not match the expected version specified in the request, the * <code>DeleteThing</code> request is rejected with a * <code>VersionConflictException</code>.</p> */ expectedVersion?: number; } export namespace DeleteThingRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteThingRequest): any => ({ ...obj, }); } /** * <p>The output of the DeleteThing operation.</p> */ export interface DeleteThingResponse {} export namespace DeleteThingResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteThingResponse): any => ({ ...obj, }); } export interface DeleteThingGroupRequest { /** * <p>The name of the thing group to delete.</p> */ thingGroupName: string | undefined; /** * <p>The expected version of the thing group to delete.</p> */ expectedVersion?: number; } export namespace DeleteThingGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteThingGroupRequest): any => ({ ...obj, }); } export interface DeleteThingGroupResponse {} export namespace DeleteThingGroupResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteThingGroupResponse): any => ({ ...obj, }); } /** * <p>The input for the DeleteThingType operation.</p> */ export interface DeleteThingTypeRequest { /** * <p>The name of the thing type.</p> */ thingTypeName: string | undefined; } export namespace DeleteThingTypeRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteThingTypeRequest): any => ({ ...obj, }); } /** * <p>The output for the DeleteThingType operation.</p> */ export interface DeleteThingTypeResponse {} export namespace DeleteThingTypeResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteThingTypeResponse): any => ({ ...obj, }); } /** * <p>The input for the DeleteTopicRule operation.</p> */ export interface DeleteTopicRuleRequest { /** * <p>The name of the rule.</p> */ ruleName: string | undefined; } export namespace DeleteTopicRuleRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteTopicRuleRequest): any => ({ ...obj, }); } export interface DeleteTopicRuleDestinationRequest { /** * <p>The ARN of the topic rule destination to delete.</p> */ arn: string | undefined; } export namespace DeleteTopicRuleDestinationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteTopicRuleDestinationRequest): any => ({ ...obj, }); } export interface DeleteTopicRuleDestinationResponse {} export namespace DeleteTopicRuleDestinationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteTopicRuleDestinationResponse): any => ({ ...obj, }); } export enum LogTargetType { DEFAULT = "DEFAULT", THING_GROUP = "THING_GROUP", } export interface DeleteV2LoggingLevelRequest { /** * <p>The type of resource for which you are configuring logging. Must be * <code>THING_Group</code>.</p> */ targetType: LogTargetType | string | undefined; /** * <p>The name of the resource for which you are configuring logging.</p> */ targetName: string | undefined; } export namespace DeleteV2LoggingLevelRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteV2LoggingLevelRequest): any => ({ ...obj, }); } /** * <p>The input for the DeprecateThingType operation.</p> */ export interface DeprecateThingTypeRequest { /** * <p>The name of the thing type to deprecate.</p> */ thingTypeName: string | undefined; /** * <p>Whether to undeprecate a deprecated thing type. If <b>true</b>, the thing type will not be deprecated anymore and you can * associate it with things.</p> */ undoDeprecate?: boolean; } export namespace DeprecateThingTypeRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeprecateThingTypeRequest): any => ({ ...obj, }); } /** * <p>The output for the DeprecateThingType operation.</p> */ export interface DeprecateThingTypeResponse {} export namespace DeprecateThingTypeResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeprecateThingTypeResponse): any => ({ ...obj, }); } export interface DescribeAccountAuditConfigurationRequest {} export namespace DescribeAccountAuditConfigurationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAccountAuditConfigurationRequest): any => ({ ...obj, }); } export interface DescribeAccountAuditConfigurationResponse { /** * <p>The ARN of the role that grants permission to IoT to access information * about your devices, policies, certificates, and other items as required when * performing an audit.</p> * <p>On the first call to <code>UpdateAccountAuditConfiguration</code>, * this parameter is required.</p> */ roleArn?: string; /** * <p>Information about the targets to which audit notifications are sent for * this account.</p> */ auditNotificationTargetConfigurations?: { [key: string]: AuditNotificationTarget }; /** * <p>Which audit checks are enabled and disabled for this account.</p> */ auditCheckConfigurations?: { [key: string]: AuditCheckConfiguration }; } export namespace DescribeAccountAuditConfigurationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAccountAuditConfigurationResponse): any => ({ ...obj, }); } export interface DescribeAuditFindingRequest { /** * <p>A unique identifier for a single audit finding. You can use this identifier to apply mitigation actions to the finding.</p> */ findingId: string | undefined; } export namespace DescribeAuditFindingRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuditFindingRequest): any => ({ ...obj, }); } export interface DescribeAuditFindingResponse { /** * <p>The findings (results) of the audit.</p> */ finding?: AuditFinding; } export namespace DescribeAuditFindingResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuditFindingResponse): any => ({ ...obj, }); } export interface DescribeAuditMitigationActionsTaskRequest { /** * <p>The unique identifier for the audit mitigation task.</p> */ taskId: string | undefined; } export namespace DescribeAuditMitigationActionsTaskRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuditMitigationActionsTaskRequest): any => ({ ...obj, }); } /** * <p>Describes which changes should be applied as part of a mitigation action.</p> */ export interface MitigationAction { /** * <p>A user-friendly name for the mitigation action.</p> */ name?: string; /** * <p>A unique identifier for the mitigation action.</p> */ id?: string; /** * <p>The IAM role ARN used to apply this mitigation action.</p> */ roleArn?: string; /** * <p>The set of parameters for this mitigation action. The parameters vary, depending on the kind of action you apply.</p> */ actionParams?: MitigationActionParams; } export namespace MitigationAction { /** * @internal */ export const filterSensitiveLog = (obj: MitigationAction): any => ({ ...obj, }); } export interface DescribeAuditMitigationActionsTaskResponse { /** * <p>The current status of the task.</p> */ taskStatus?: AuditMitigationActionsTaskStatus | string; /** * <p>The date and time when the task was started.</p> */ startTime?: Date; /** * <p>The date and time when the task was completed or canceled.</p> */ endTime?: Date; /** * <p>Aggregate counts of the results when the mitigation tasks were applied to the findings for this audit mitigation actions task.</p> */ taskStatistics?: { [key: string]: TaskStatisticsForAuditCheck }; /** * <p>Identifies the findings to which the mitigation actions are applied. This can be by audit checks, by audit task, or a set of findings.</p> */ target?: AuditMitigationActionsTaskTarget; /** * <p>Specifies the mitigation actions that should be applied to specific audit checks.</p> */ auditCheckToActionsMapping?: { [key: string]: string[] }; /** * <p>Specifies the mitigation actions and their parameters that are applied as part of this task.</p> */ actionsDefinition?: MitigationAction[]; } export namespace DescribeAuditMitigationActionsTaskResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuditMitigationActionsTaskResponse): any => ({ ...obj, }); } export interface DescribeAuditSuppressionRequest { /** * <p>An audit check name. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the list * of all checks, including those that are enabled or use <code>UpdateAccountAuditConfiguration</code> * to select which checks are enabled.)</p> */ checkName: string | undefined; /** * <p>Information that identifies the noncompliant resource.</p> */ resourceIdentifier: ResourceIdentifier | undefined; } export namespace DescribeAuditSuppressionRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuditSuppressionRequest): any => ({ ...obj, }); } export interface DescribeAuditSuppressionResponse { /** * <p>An audit check name. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the list * of all checks, including those that are enabled or use <code>UpdateAccountAuditConfiguration</code> * to select which checks are enabled.)</p> */ checkName?: string; /** * <p>Information that identifies the noncompliant resource.</p> */ resourceIdentifier?: ResourceIdentifier; /** * <p> * The epoch timestamp in seconds at which this suppression expires. * </p> */ expirationDate?: Date; /** * <p> * Indicates whether a suppression should exist indefinitely or not. * </p> */ suppressIndefinitely?: boolean; /** * <p> * The description of the audit suppression. * </p> */ description?: string; } export namespace DescribeAuditSuppressionResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuditSuppressionResponse): any => ({ ...obj, }); } export interface DescribeAuditTaskRequest { /** * <p>The ID of the audit whose information you want to get.</p> */ taskId: string | undefined; } export namespace DescribeAuditTaskRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuditTaskRequest): any => ({ ...obj, }); } /** * <p>Statistics for the checks performed during the audit.</p> */ export interface TaskStatistics { /** * <p>The number of checks in this audit.</p> */ totalChecks?: number; /** * <p>The number of checks in progress.</p> */ inProgressChecks?: number; /** * <p>The number of checks waiting for data collection.</p> */ waitingForDataCollectionChecks?: number; /** * <p>The number of checks that found compliant resources.</p> */ compliantChecks?: number; /** * <p>The number of checks that found noncompliant resources.</p> */ nonCompliantChecks?: number; /** * <p>The number of checks.</p> */ failedChecks?: number; /** * <p>The number of checks that did not run because the audit was canceled.</p> */ canceledChecks?: number; } export namespace TaskStatistics { /** * @internal */ export const filterSensitiveLog = (obj: TaskStatistics): any => ({ ...obj, }); } export interface DescribeAuditTaskResponse { /** * <p>The status of the audit: one of "IN_PROGRESS", "COMPLETED", * "FAILED", or "CANCELED".</p> */ taskStatus?: AuditTaskStatus | string; /** * <p>The type of audit: "ON_DEMAND_AUDIT_TASK" or "SCHEDULED_AUDIT_TASK".</p> */ taskType?: AuditTaskType | string; /** * <p>The time the audit started.</p> */ taskStartTime?: Date; /** * <p>Statistical information about the audit.</p> */ taskStatistics?: TaskStatistics; /** * <p>The name of the scheduled audit (only if the audit was a scheduled audit).</p> */ scheduledAuditName?: string; /** * <p>Detailed information about each check performed during this audit.</p> */ auditDetails?: { [key: string]: AuditCheckDetails }; } export namespace DescribeAuditTaskResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuditTaskResponse): any => ({ ...obj, }); } export interface DescribeAuthorizerRequest { /** * <p>The name of the authorizer to describe.</p> */ authorizerName: string | undefined; } export namespace DescribeAuthorizerRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuthorizerRequest): any => ({ ...obj, }); } export interface DescribeAuthorizerResponse { /** * <p>The authorizer description.</p> */ authorizerDescription?: AuthorizerDescription; } export namespace DescribeAuthorizerResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAuthorizerResponse): any => ({ ...obj, }); } export interface DescribeBillingGroupRequest { /** * <p>The name of the billing group.</p> */ billingGroupName: string | undefined; } export namespace DescribeBillingGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeBillingGroupRequest): any => ({ ...obj, }); } /** * <p>Additional information about the billing group.</p> */ export interface BillingGroupMetadata { /** * <p>The date the billing group was created.</p> */ creationDate?: Date; } export namespace BillingGroupMetadata { /** * @internal */ export const filterSensitiveLog = (obj: BillingGroupMetadata): any => ({ ...obj, }); } export interface DescribeBillingGroupResponse { /** * <p>The name of the billing group.</p> */ billingGroupName?: string; /** * <p>The ID of the billing group.</p> */ billingGroupId?: string; /** * <p>The ARN of the billing group.</p> */ billingGroupArn?: string; /** * <p>The version of the billing group.</p> */ version?: number; /** * <p>The properties of the billing group.</p> */ billingGroupProperties?: BillingGroupProperties; /** * <p>Additional information about the billing group.</p> */ billingGroupMetadata?: BillingGroupMetadata; } export namespace DescribeBillingGroupResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeBillingGroupResponse): any => ({ ...obj, }); } /** * <p>The input for the DescribeCACertificate operation.</p> */ export interface DescribeCACertificateRequest { /** * <p>The CA certificate identifier.</p> */ certificateId: string | undefined; } export namespace DescribeCACertificateRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCACertificateRequest): any => ({ ...obj, }); } export enum CACertificateStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE", } /** * <p>When the certificate is valid.</p> */ export interface CertificateValidity { /** * <p>The certificate is not valid before this date.</p> */ notBefore?: Date; /** * <p>The certificate is not valid after this date.</p> */ notAfter?: Date; } export namespace CertificateValidity { /** * @internal */ export const filterSensitiveLog = (obj: CertificateValidity): any => ({ ...obj, }); } /** * <p>Describes a CA certificate.</p> */ export interface CACertificateDescription { /** * <p>The CA certificate ARN.</p> */ certificateArn?: string; /** * <p>The CA certificate ID.</p> */ certificateId?: string; /** * <p>The status of a CA certificate.</p> */ status?: CACertificateStatus | string; /** * <p>The CA certificate data, in PEM format.</p> */ certificatePem?: string; /** * <p>The owner of the CA certificate.</p> */ ownedBy?: string; /** * <p>The date the CA certificate was created.</p> */ creationDate?: Date; /** * <p>Whether the CA certificate configured for auto registration of device certificates. * Valid values are "ENABLE" and "DISABLE"</p> */ autoRegistrationStatus?: AutoRegistrationStatus | string; /** * <p>The date the CA certificate was last modified.</p> */ lastModifiedDate?: Date; /** * <p>The customer version of the CA certificate.</p> */ customerVersion?: number; /** * <p>The generation ID of the CA certificate.</p> */ generationId?: string; /** * <p>When the CA certificate is valid.</p> */ validity?: CertificateValidity; } export namespace CACertificateDescription { /** * @internal */ export const filterSensitiveLog = (obj: CACertificateDescription): any => ({ ...obj, }); } /** * <p>The registration configuration.</p> */ export interface RegistrationConfig { /** * <p>The template body.</p> */ templateBody?: string; /** * <p>The ARN of the role.</p> */ roleArn?: string; } export namespace RegistrationConfig { /** * @internal */ export const filterSensitiveLog = (obj: RegistrationConfig): any => ({ ...obj, }); } /** * <p>The output from the DescribeCACertificate operation.</p> */ export interface DescribeCACertificateResponse { /** * <p>The CA certificate description.</p> */ certificateDescription?: CACertificateDescription; /** * <p>Information about the registration configuration.</p> */ registrationConfig?: RegistrationConfig; } export namespace DescribeCACertificateResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCACertificateResponse): any => ({ ...obj, }); } /** * <p>The input for the DescribeCertificate operation.</p> */ export interface DescribeCertificateRequest { /** * <p>The ID of the certificate. (The last part of the certificate ARN contains the * certificate ID.)</p> */ certificateId: string | undefined; } export namespace DescribeCertificateRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCertificateRequest): any => ({ ...obj, }); } export enum CertificateMode { DEFAULT = "DEFAULT", SNI_ONLY = "SNI_ONLY", } export enum CertificateStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE", PENDING_ACTIVATION = "PENDING_ACTIVATION", PENDING_TRANSFER = "PENDING_TRANSFER", REGISTER_INACTIVE = "REGISTER_INACTIVE", REVOKED = "REVOKED", } /** * <p>Data used to transfer a certificate to an Amazon Web Services account.</p> */ export interface TransferData { /** * <p>The transfer message.</p> */ transferMessage?: string; /** * <p>The reason why the transfer was rejected.</p> */ rejectReason?: string; /** * <p>The date the transfer took place.</p> */ transferDate?: Date; /** * <p>The date the transfer was accepted.</p> */ acceptDate?: Date; /** * <p>The date the transfer was rejected.</p> */ rejectDate?: Date; } export namespace TransferData { /** * @internal */ export const filterSensitiveLog = (obj: TransferData): any => ({ ...obj, }); } /** * <p>Describes a certificate.</p> */ export interface CertificateDescription { /** * <p>The ARN of the certificate.</p> */ certificateArn?: string; /** * <p>The ID of the certificate.</p> */ certificateId?: string; /** * <p>The certificate ID of the CA certificate used to sign this certificate.</p> */ caCertificateId?: string; /** * <p>The status of the certificate.</p> */ status?: CertificateStatus | string; /** * <p>The certificate data, in PEM format.</p> */ certificatePem?: string; /** * <p>The ID of the Amazon Web Services account that owns the certificate.</p> */ ownedBy?: string; /** * <p>The ID of the Amazon Web Services account of the previous owner of the certificate.</p> */ previousOwnedBy?: string; /** * <p>The date and time the certificate was created.</p> */ creationDate?: Date; /** * <p>The date and time the certificate was last modified.</p> */ lastModifiedDate?: Date; /** * <p>The customer version of the certificate.</p> */ customerVersion?: number; /** * <p>The transfer data.</p> */ transferData?: TransferData; /** * <p>The generation ID of the certificate.</p> */ generationId?: string; /** * <p>When the certificate is valid.</p> */ validity?: CertificateValidity; /** * <p>The mode of the certificate.</p> */ certificateMode?: CertificateMode | string; } export namespace CertificateDescription { /** * @internal */ export const filterSensitiveLog = (obj: CertificateDescription): any => ({ ...obj, }); } /** * <p>The output of the DescribeCertificate operation.</p> */ export interface DescribeCertificateResponse { /** * <p>The description of the certificate.</p> */ certificateDescription?: CertificateDescription; } export namespace DescribeCertificateResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCertificateResponse): any => ({ ...obj, }); } export interface DescribeCustomMetricRequest { /** * <p> * The name of the custom metric. * </p> */ metricName: string | undefined; } export namespace DescribeCustomMetricRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCustomMetricRequest): any => ({ ...obj, }); } export interface DescribeCustomMetricResponse { /** * <p> * The name of the custom metric. * </p> */ metricName?: string; /** * <p> * The Amazon Resource Number (ARN) of the custom metric. * </p> */ metricArn?: string; /** * <p> * The type of the custom metric. Types include <code>string-list</code>, <code>ip-address-list</code>, <code>number-list</code>, and <code>number</code>. * </p> */ metricType?: CustomMetricType | string; /** * <p> * Field represents a friendly name in the console for the custom metric; doesn't have to be unique. Don't use this name as the metric identifier in the device metric report. Can be updated. * </p> */ displayName?: string; /** * <p> * The creation date of the custom metric in milliseconds since epoch. * </p> */ creationDate?: Date; /** * <p> * The time the custom metric was last modified in milliseconds since epoch. * </p> */ lastModifiedDate?: Date; } export namespace DescribeCustomMetricResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCustomMetricResponse): any => ({ ...obj, }); } export interface DescribeDefaultAuthorizerRequest {} export namespace DescribeDefaultAuthorizerRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDefaultAuthorizerRequest): any => ({ ...obj, }); } export interface DescribeDefaultAuthorizerResponse { /** * <p>The default authorizer's description.</p> */ authorizerDescription?: AuthorizerDescription; } export namespace DescribeDefaultAuthorizerResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDefaultAuthorizerResponse): any => ({ ...obj, }); } export interface DescribeDetectMitigationActionsTaskRequest { /** * <p> * The unique identifier of the task. * </p> */ taskId: string | undefined; } export namespace DescribeDetectMitigationActionsTaskRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDetectMitigationActionsTaskRequest): any => ({ ...obj, }); } /** * <p> * The target of a mitigation action task. * </p> */ export interface DetectMitigationActionsTaskTarget { /** * <p> * The unique identifiers of the violations. * </p> */ violationIds?: string[]; /** * <p> * The name of the security profile. * </p> */ securityProfileName?: string; /** * <p> * The name of the behavior. * </p> */ behaviorName?: string; } export namespace DetectMitigationActionsTaskTarget { /** * @internal */ export const filterSensitiveLog = (obj: DetectMitigationActionsTaskTarget): any => ({ ...obj, }); } /** * <p> * The statistics of a mitigation action task. * </p> */ export interface DetectMitigationActionsTaskStatistics { /** * <p> * The actions that were performed. * </p> */ actionsExecuted?: number; /** * <p> * The actions that were skipped. * </p> */ actionsSkipped?: number; /** * <p> * The actions that failed. * </p> */ actionsFailed?: number; } export namespace DetectMitigationActionsTaskStatistics { /** * @internal */ export const filterSensitiveLog = (obj: DetectMitigationActionsTaskStatistics): any => ({ ...obj, }); } export enum DetectMitigationActionsTaskStatus { CANCELED = "CANCELED", FAILED = "FAILED", IN_PROGRESS = "IN_PROGRESS", SUCCESSFUL = "SUCCESSFUL", } /** * <p> * Specifies the time period of which violation events occurred between. * </p> */ export interface ViolationEventOccurrenceRange { /** * <p> * The start date and time of a time period in which violation events occurred. * </p> */ startTime: Date | undefined; /** * <p> * The end date and time of a time period in which violation events occurred. * </p> */ endTime: Date | undefined; } export namespace ViolationEventOccurrenceRange { /** * @internal */ export const filterSensitiveLog = (obj: ViolationEventOccurrenceRange): any => ({ ...obj, }); } /** * <p> * The summary of the mitigation action tasks. * </p> */ export interface DetectMitigationActionsTaskSummary { /** * <p> * The unique identifier of the task. * </p> */ taskId?: string; /** * <p> * The status of the task. * </p> */ taskStatus?: DetectMitigationActionsTaskStatus | string; /** * <p> * The date the task started. * </p> */ taskStartTime?: Date; /** * <p> * The date the task ended. * </p> */ taskEndTime?: Date; /** * <p> * Specifies the ML Detect findings to which the mitigation actions are applied. * </p> */ target?: DetectMitigationActionsTaskTarget; /** * <p> * Specifies the time period of which violation events occurred between. * </p> */ violationEventOccurrenceRange?: ViolationEventOccurrenceRange; /** * <p> * Includes only active violations. * </p> */ onlyActiveViolationsIncluded?: boolean; /** * <p> * Includes suppressed alerts. * </p> */ suppressedAlertsIncluded?: boolean; /** * <p> * The definition of the actions. * </p> */ actionsDefinition?: MitigationAction[]; /** * <p> * The statistics of a mitigation action task. * </p> */ taskStatistics?: DetectMitigationActionsTaskStatistics; } export namespace DetectMitigationActionsTaskSummary { /** * @internal */ export const filterSensitiveLog = (obj: DetectMitigationActionsTaskSummary): any => ({ ...obj, }); } export interface DescribeDetectMitigationActionsTaskResponse { /** * <p> * The description of a task. * </p> */ taskSummary?: DetectMitigationActionsTaskSummary; } export namespace DescribeDetectMitigationActionsTaskResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDetectMitigationActionsTaskResponse): any => ({ ...obj, }); } export interface DescribeDimensionRequest { /** * <p>The unique identifier for the dimension.</p> */ name: string | undefined; } export namespace DescribeDimensionRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDimensionRequest): any => ({ ...obj, }); } export interface DescribeDimensionResponse { /** * <p>The unique identifier for the dimension.</p> */ name?: string; /** * <p>The Amazon Resource Name * (ARN) * for * the dimension.</p> */ arn?: string; /** * <p>The type of the dimension.</p> */ type?: DimensionType | string; /** * <p>The value or list of values used to scope the dimension. For example, for topic filters, this is the pattern used to match the MQTT topic name.</p> */ stringValues?: string[]; /** * <p>The date the dimension was created.</p> */ creationDate?: Date; /** * <p>The date the dimension was last modified.</p> */ lastModifiedDate?: Date; } export namespace DescribeDimensionResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDimensionResponse): any => ({ ...obj, }); } export interface DescribeDomainConfigurationRequest { /** * <p>The name of the domain configuration.</p> */ domainConfigurationName: string | undefined; } export namespace DescribeDomainConfigurationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDomainConfigurationRequest): any => ({ ...obj, }); } export enum DomainConfigurationStatus { DISABLED = "DISABLED", ENABLED = "ENABLED", } export enum DomainType { AWS_MANAGED = "AWS_MANAGED", CUSTOMER_MANAGED = "CUSTOMER_MANAGED", ENDPOINT = "ENDPOINT", } export enum ServerCertificateStatus { INVALID = "INVALID", VALID = "VALID", } /** * <p>An object that contains information about a server certificate.</p> */ export interface ServerCertificateSummary { /** * <p>The ARN of the server certificate.</p> */ serverCertificateArn?: string; /** * <p>The status of the server certificate.</p> */ serverCertificateStatus?: ServerCertificateStatus | string; /** * <p>Details that explain the status of the server certificate.</p> */ serverCertificateStatusDetail?: string; } export namespace ServerCertificateSummary { /** * @internal */ export const filterSensitiveLog = (obj: ServerCertificateSummary): any => ({ ...obj, }); } export interface DescribeDomainConfigurationResponse { /** * <p>The name of the domain configuration.</p> */ domainConfigurationName?: string; /** * <p>The ARN of the domain configuration.</p> */ domainConfigurationArn?: string; /** * <p>The name of the domain.</p> */ domainName?: string; /** * <p>A list containing summary information about the server certificate included in the domain configuration.</p> */ serverCertificates?: ServerCertificateSummary[]; /** * <p>An object that specifies the authorization service for a domain.</p> */ authorizerConfig?: AuthorizerConfig; /** * <p>A Boolean value that specifies the current state of the domain configuration.</p> */ domainConfigurationStatus?: DomainConfigurationStatus | string; /** * <p>The type of service delivered by the endpoint.</p> */ serviceType?: ServiceType | string; /** * <p>The type of the domain.</p> */ domainType?: DomainType | string; /** * <p>The date and time the domain configuration's status was last changed.</p> */ lastStatusChangeDate?: Date; } export namespace DescribeDomainConfigurationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDomainConfigurationResponse): any => ({ ...obj, }); } /** * <p>The input for the DescribeEndpoint operation.</p> */ export interface DescribeEndpointRequest { /** * <p>The endpoint type. Valid endpoint types include:</p> * <ul> * <li> * <p> * <code>iot:Data</code> - Returns a VeriSign signed data endpoint.</p> * </li> * </ul> * <ul> * <li> * <p> * <code>iot:Data-ATS</code> - Returns an ATS signed data endpoint.</p> * </li> * </ul> * <ul> * <li> * <p> * <code>iot:CredentialProvider</code> - Returns an IoT credentials provider API * endpoint.</p> * </li> * </ul> * <ul> * <li> * <p> * <code>iot:Jobs</code> - Returns an IoT device management Jobs API * endpoint.</p> * </li> * </ul> * <p>We strongly recommend that customers use the newer <code>iot:Data-ATS</code> endpoint type to avoid * issues related to the widespread distrust of Symantec certificate authorities.</p> */ endpointType?: string; } export namespace DescribeEndpointRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEndpointRequest): any => ({ ...obj, }); } /** * <p>The output from the DescribeEndpoint operation.</p> */ export interface DescribeEndpointResponse { /** * <p>The endpoint. The format of the endpoint is as follows: * <i>identifier</i>.iot.<i>region</i>.amazonaws.com.</p> */ endpointAddress?: string; } export namespace DescribeEndpointResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEndpointResponse): any => ({ ...obj, }); } export interface DescribeEventConfigurationsRequest {} export namespace DescribeEventConfigurationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEventConfigurationsRequest): any => ({ ...obj, }); } export enum EventType { CA_CERTIFICATE = "CA_CERTIFICATE", CERTIFICATE = "CERTIFICATE", JOB = "JOB", JOB_EXECUTION = "JOB_EXECUTION", POLICY = "POLICY", THING = "THING", THING_GROUP = "THING_GROUP", THING_GROUP_HIERARCHY = "THING_GROUP_HIERARCHY", THING_GROUP_MEMBERSHIP = "THING_GROUP_MEMBERSHIP", THING_TYPE = "THING_TYPE", THING_TYPE_ASSOCIATION = "THING_TYPE_ASSOCIATION", } /** * <p>Configuration.</p> */ export interface Configuration { /** * <p>True to enable the configuration.</p> */ Enabled?: boolean; } export namespace Configuration { /** * @internal */ export const filterSensitiveLog = (obj: Configuration): any => ({ ...obj, }); } export interface DescribeEventConfigurationsResponse { /** * <p>The event configurations.</p> */ eventConfigurations?: { [key: string]: Configuration }; /** * <p>The creation date of the event configuration.</p> */ creationDate?: Date; /** * <p>The date the event configurations were last modified.</p> */ lastModifiedDate?: Date; } export namespace DescribeEventConfigurationsResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEventConfigurationsResponse): any => ({ ...obj, }); } export interface DescribeFleetMetricRequest { /** * <p>The name of the fleet metric to describe.</p> */ metricName: string | undefined; } export namespace DescribeFleetMetricRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFleetMetricRequest): any => ({ ...obj, }); } export interface DescribeFleetMetricResponse { /** * <p>The name of the fleet metric to describe.</p> */ metricName?: string; /** * <p>The search query string.</p> */ queryString?: string; /** * <p>The type of the aggregation query.</p> */ aggregationType?: AggregationType; /** * <p>The time in seconds between fleet metric emissions. Range [60(1 min), 86400(1 day)] and must be multiple of 60.</p> */ period?: number; /** * <p>The field to aggregate.</p> */ aggregationField?: string; /** * <p>The fleet metric description.</p> */ description?: string; /** * <p>The query version.</p> */ queryVersion?: string; /** * <p>The name of the index to search.</p> */ indexName?: string; /** * <p>The date when the fleet metric is created.</p> */ creationDate?: Date; /** * <p>The date when the fleet metric is last modified.</p> */ lastModifiedDate?: Date; /** * <p>Used to support unit transformation such as milliseconds to seconds. The unit must be * supported by <a href="https://docs.aws.amazon.com/https:/docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW metric</a>.</p> */ unit?: FleetMetricUnit | string; /** * <p>The version of the fleet metric.</p> */ version?: number; /** * <p>The ARN of the fleet metric to describe.</p> */ metricArn?: string; } export namespace DescribeFleetMetricResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFleetMetricResponse): any => ({ ...obj, }); } export interface DescribeIndexRequest { /** * <p>The index name.</p> */ indexName: string | undefined; } export namespace DescribeIndexRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeIndexRequest): any => ({ ...obj, }); } export enum IndexStatus { ACTIVE = "ACTIVE", BUILDING = "BUILDING", REBUILDING = "REBUILDING", } export interface DescribeIndexResponse { /** * <p>The index name.</p> */ indexName?: string; /** * <p>The index status.</p> */ indexStatus?: IndexStatus | string; /** * <p>Contains a value that specifies the type of indexing performed. Valid values * are:</p> * <ul> * <li> * <p>REGISTRY – Your thing index contains only registry data.</p> * </li> * <li> * <p>REGISTRY_AND_SHADOW - Your thing index contains registry data and shadow data.</p> * </li> * <li> * <p>REGISTRY_AND_CONNECTIVITY_STATUS - Your thing index contains registry data and * thing connectivity status data.</p> * </li> * <li> * <p>REGISTRY_AND_SHADOW_AND_CONNECTIVITY_STATUS - Your thing index contains registry * data, shadow data, and thing connectivity status data.</p> * </li> * </ul> */ schema?: string; } export namespace DescribeIndexResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeIndexResponse): any => ({ ...obj, }); } export interface DescribeJobRequest { /** * <p>The unique identifier you assigned to this job when it was created.</p> */ jobId: string | undefined; } export namespace DescribeJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeJobRequest): any => ({ ...obj, }); } /** * <p>The job process details.</p> */ export interface JobProcessDetails { /** * <p>The target devices to which the job execution is being rolled out. This value will be null after the job execution has finished rolling out to all the target devices.</p> */ processingTargets?: string[]; /** * <p>The number of things that cancelled the job.</p> */ numberOfCanceledThings?: number; /** * <p>The number of things which successfully completed the job.</p> */ numberOfSucceededThings?: number; /** * <p>The number of things that failed executing the job.</p> */ numberOfFailedThings?: number; /** * <p>The number of things that rejected the job.</p> */ numberOfRejectedThings?: number; /** * <p>The number of things that are awaiting execution of the job.</p> */ numberOfQueuedThings?: number; /** * <p>The number of things currently executing the job.</p> */ numberOfInProgressThings?: number; /** * <p>The number of things that are no longer scheduled to execute the job because they have been deleted or * have been removed from the group that was a target of the job.</p> */ numberOfRemovedThings?: number; /** * <p>The number of things whose job execution status is <code>TIMED_OUT</code>.</p> */ numberOfTimedOutThings?: number; } export namespace JobProcessDetails { /** * @internal */ export const filterSensitiveLog = (obj: JobProcessDetails): any => ({ ...obj, }); } export enum JobStatus { CANCELED = "CANCELED", COMPLETED = "COMPLETED", DELETION_IN_PROGRESS = "DELETION_IN_PROGRESS", IN_PROGRESS = "IN_PROGRESS", } /** * <p>The <code>Job</code> object contains details about a job.</p> */ export interface Job { /** * <p>An ARN identifying the job with format "arn:aws:iot:region:account:job/jobId".</p> */ jobArn?: string; /** * <p>The unique identifier you assigned to this job when it was created.</p> */ jobId?: string; /** * <p>Specifies whether the job will continue to run (CONTINUOUS), or will be complete after all those things * specified as targets have completed the job (SNAPSHOT). If continuous, the job may also be run on a thing * when a change is detected in a target. For example, a job will run on a device when the thing representing * the device is added to a target group, even after the job was completed by all things originally in the * group. </p> */ targetSelection?: TargetSelection | string; /** * <p>The status of the job, one of <code>IN_PROGRESS</code>, <code>CANCELED</code>, * <code>DELETION_IN_PROGRESS</code> or <code>COMPLETED</code>. </p> */ status?: JobStatus | string; /** * <p>Will be <code>true</code> if the job was canceled with the optional <code>force</code> parameter set to * <code>true</code>.</p> */ forceCanceled?: boolean; /** * <p>If the job was updated, provides the reason code for the update.</p> */ reasonCode?: string; /** * <p>If the job was updated, describes the reason for the update.</p> */ comment?: string; /** * <p>A list of IoT things and thing groups to which the job should be sent.</p> */ targets?: string[]; /** * <p>A short text description of the job.</p> */ description?: string; /** * <p>Configuration for pre-signed S3 URLs.</p> */ presignedUrlConfig?: PresignedUrlConfig; /** * <p>Allows you to create a staged rollout of a job.</p> */ jobExecutionsRolloutConfig?: JobExecutionsRolloutConfig; /** * <p>Configuration for criteria to abort the job.</p> */ abortConfig?: AbortConfig; /** * <p>The time, in seconds since the epoch, when the job was created.</p> */ createdAt?: Date; /** * <p>The time, in seconds since the epoch, when the job was last updated.</p> */ lastUpdatedAt?: Date; /** * <p>The time, in seconds since the epoch, when the job was completed.</p> */ completedAt?: Date; /** * <p>Details about the job process.</p> */ jobProcessDetails?: JobProcessDetails; /** * <p>Specifies the amount of time each device has to finish its execution of the job. A timer * is started when the job execution status is set to <code>IN_PROGRESS</code>. If the job * execution status is not set to another terminal state before the timer expires, it will * be automatically set to <code>TIMED_OUT</code>.</p> */ timeoutConfig?: TimeoutConfig; /** * <p>The namespace used to indicate that a job is a customer-managed job.</p> * <p>When you specify a value for this parameter, Amazon Web Services IoT Core sends jobs notifications to MQTT topics that * contain the value in the following format.</p> * <p> * <code>$aws/things/<i>THING_NAME</i>/jobs/<i>JOB_ID</i>/notify-namespace-<i>NAMESPACE_ID</i>/</code> * </p> * <note> * <p>The <code>namespaceId</code> feature is in public preview.</p> * </note> */ namespaceId?: string; /** * <p>The ARN of the job template used to create the job.</p> */ jobTemplateArn?: string; } export namespace Job { /** * @internal */ export const filterSensitiveLog = (obj: Job): any => ({ ...obj, }); } export interface DescribeJobResponse { /** * <p>An S3 link to the job document.</p> */ documentSource?: string; /** * <p>Information about the job.</p> */ job?: Job; } export namespace DescribeJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeJobResponse): any => ({ ...obj, }); } export interface DescribeJobExecutionRequest { /** * <p>The unique identifier you assigned to this job when it was created.</p> */ jobId: string | undefined; /** * <p>The name of the thing on which the job execution is running.</p> */ thingName: string | undefined; /** * <p>A string (consisting of the digits "0" through "9" which is used to specify a particular job execution * on a particular device.</p> */ executionNumber?: number; } export namespace DescribeJobExecutionRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeJobExecutionRequest): any => ({ ...obj, }); } export enum JobExecutionStatus { CANCELED = "CANCELED", FAILED = "FAILED", IN_PROGRESS = "IN_PROGRESS", QUEUED = "QUEUED", REJECTED = "REJECTED", REMOVED = "REMOVED", SUCCEEDED = "SUCCEEDED", TIMED_OUT = "TIMED_OUT", } /** * <p>Details of the job execution status.</p> */ export interface JobExecutionStatusDetails { /** * <p>The job execution status.</p> */ detailsMap?: { [key: string]: string }; } export namespace JobExecutionStatusDetails { /** * @internal */ export const filterSensitiveLog = (obj: JobExecutionStatusDetails): any => ({ ...obj, }); } /** * <p>The job execution object represents the execution of a job on a particular device.</p> */ export interface JobExecution { /** * <p>The unique identifier you assigned to the job when it was created.</p> */ jobId?: string; /** * <p>The status of the job execution (IN_PROGRESS, QUEUED, FAILED, SUCCEEDED, TIMED_OUT, * CANCELED, or REJECTED).</p> */ status?: JobExecutionStatus | string; /** * <p>Will be <code>true</code> if the job execution was canceled with the optional <code>force</code> * parameter set to <code>true</code>.</p> */ forceCanceled?: boolean; /** * <p>A collection of name/value pairs that describe the status of the job execution.</p> */ statusDetails?: JobExecutionStatusDetails; /** * <p>The ARN of the thing on which the job execution is running.</p> */ thingArn?: string; /** * <p>The time, in seconds since the epoch, when the job execution was queued.</p> */ queuedAt?: Date; /** * <p>The time, in seconds since the epoch, when the job execution started.</p> */ startedAt?: Date; /** * <p>The time, in seconds since the epoch, when the job execution was last updated.</p> */ lastUpdatedAt?: Date; /** * <p>A string (consisting of the digits "0" through "9") which identifies this particular job execution on * this particular device. It can be used in commands which return or update job execution information. * </p> */ executionNumber?: number; /** * <p>The version of the job execution. Job execution versions are incremented each time they are updated * by a device.</p> */ versionNumber?: number; /** * <p>The estimated number of seconds that remain before the job execution status will be * changed to <code>TIMED_OUT</code>. The timeout interval can be anywhere between 1 minute and 7 days (1 to 10080 minutes). * The actual job execution timeout can occur up to 60 seconds later than the estimated duration. * This value will not be included if the job execution has reached a terminal status.</p> */ approximateSecondsBeforeTimedOut?: number; } export namespace JobExecution { /** * @internal */ export const filterSensitiveLog = (obj: JobExecution): any => ({ ...obj, }); } export interface DescribeJobExecutionResponse { /** * <p>Information about the job execution.</p> */ execution?: JobExecution; } export namespace DescribeJobExecutionResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeJobExecutionResponse): any => ({ ...obj, }); } export interface DescribeJobTemplateRequest { /** * <p>The unique identifier of the job template.</p> */ jobTemplateId: string | undefined; } export namespace DescribeJobTemplateRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeJobTemplateRequest): any => ({ ...obj, }); } export interface DescribeJobTemplateResponse { /** * <p>The ARN of the job template.</p> */ jobTemplateArn?: string; /** * <p>The unique identifier of the job template.</p> */ jobTemplateId?: string; /** * <p>A description of the job template.</p> */ description?: string; /** * <p>An S3 link to the job document.</p> */ documentSource?: string; /** * <p>The job document.</p> */ document?: string; /** * <p>The time, in seconds since the epoch, when the job template was created.</p> */ createdAt?: Date; /** * <p>Configuration for pre-signed S3 URLs.</p> */ presignedUrlConfig?: PresignedUrlConfig; /** * <p>Allows you to create a staged rollout of a job.</p> */ jobExecutionsRolloutConfig?: JobExecutionsRolloutConfig; /** * <p>The criteria that determine when and how a job abort takes place.</p> */ abortConfig?: AbortConfig; /** * <p>Specifies the amount of time each device has to finish its execution of the job. A timer * is started when the job execution status is set to <code>IN_PROGRESS</code>. If the job * execution status is not set to another terminal state before the timer expires, it will * be automatically set to <code>TIMED_OUT</code>.</p> */ timeoutConfig?: TimeoutConfig; } export namespace DescribeJobTemplateResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeJobTemplateResponse): any => ({ ...obj, }); } export interface DescribeMitigationActionRequest { /** * <p>The friendly name that uniquely identifies the mitigation action.</p> */ actionName: string | undefined; } export namespace DescribeMitigationActionRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeMitigationActionRequest): any => ({ ...obj, }); } export enum MitigationActionType { ADD_THINGS_TO_THING_GROUP = "ADD_THINGS_TO_THING_GROUP", ENABLE_IOT_LOGGING = "ENABLE_IOT_LOGGING", PUBLISH_FINDING_TO_SNS = "PUBLISH_FINDING_TO_SNS", REPLACE_DEFAULT_POLICY_VERSION = "REPLACE_DEFAULT_POLICY_VERSION", UPDATE_CA_CERTIFICATE = "UPDATE_CA_CERTIFICATE", UPDATE_DEVICE_CERTIFICATE = "UPDATE_DEVICE_CERTIFICATE", } export interface DescribeMitigationActionResponse { /** * <p>The friendly name that uniquely identifies the mitigation action.</p> */ actionName?: string; /** * <p>The type of mitigation action.</p> */ actionType?: MitigationActionType | string; /** * <p>The ARN that identifies this migration action.</p> */ actionArn?: string; /** * <p>A unique identifier for this action.</p> */ actionId?: string; /** * <p>The ARN of the IAM role used to apply this action.</p> */ roleArn?: string; /** * <p>Parameters that control how the mitigation action is applied, specific to the type of mitigation action.</p> */ actionParams?: MitigationActionParams; /** * <p>The date and time when the mitigation action was added to your Amazon Web Services accounts.</p> */ creationDate?: Date; /** * <p>The date and time when the mitigation action was last changed.</p> */ lastModifiedDate?: Date; } export namespace DescribeMitigationActionResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeMitigationActionResponse): any => ({ ...obj, }); } export interface DescribeProvisioningTemplateRequest { /** * <p>The name of the fleet provisioning template.</p> */ templateName: string | undefined; } export namespace DescribeProvisioningTemplateRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeProvisioningTemplateRequest): any => ({ ...obj, }); } export interface DescribeProvisioningTemplateResponse { /** * <p>The ARN of the fleet provisioning template.</p> */ templateArn?: string; /** * <p>The name of the fleet provisioning template.</p> */ templateName?: string; /** * <p>The description of the fleet provisioning template.</p> */ description?: string; /** * <p>The date when the fleet provisioning template was created.</p> */ creationDate?: Date; /** * <p>The date when the fleet provisioning template was last modified.</p> */ lastModifiedDate?: Date; /** * <p>The default fleet template version ID.</p> */ defaultVersionId?: number; /** * <p>The JSON formatted contents of the fleet provisioning template.</p> */ templateBody?: string; /** * <p>True if the fleet provisioning template is enabled, otherwise false.</p> */ enabled?: boolean; /** * <p>The ARN of the role associated with the provisioning template. This IoT role grants * permission to provision a device.</p> */ provisioningRoleArn?: string; /** * <p>Gets information about a pre-provisioned hook.</p> */ preProvisioningHook?: ProvisioningHook; } export namespace DescribeProvisioningTemplateResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeProvisioningTemplateResponse): any => ({ ...obj, }); } export interface DescribeProvisioningTemplateVersionRequest { /** * <p>The template name.</p> */ templateName: string | undefined; /** * <p>The fleet provisioning template version ID.</p> */ versionId: number | undefined; } export namespace DescribeProvisioningTemplateVersionRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeProvisioningTemplateVersionRequest): any => ({ ...obj, }); } export interface DescribeProvisioningTemplateVersionResponse { /** * <p>The fleet provisioning template version ID.</p> */ versionId?: number; /** * <p>The date when the fleet provisioning template version was created.</p> */ creationDate?: Date; /** * <p>The JSON formatted contents of the fleet provisioning template version.</p> */ templateBody?: string; /** * <p>True if the fleet provisioning template version is the default version.</p> */ isDefaultVersion?: boolean; } export namespace DescribeProvisioningTemplateVersionResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeProvisioningTemplateVersionResponse): any => ({ ...obj, }); } export interface DescribeRoleAliasRequest { /** * <p>The role alias to describe.</p> */ roleAlias: string | undefined; } export namespace DescribeRoleAliasRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRoleAliasRequest): any => ({ ...obj, }); } /** * <p>Role alias description.</p> */ export interface RoleAliasDescription { /** * <p>The role alias.</p> */ roleAlias?: string; /** * <p>The ARN of the role alias.</p> */ roleAliasArn?: string; /** * <p>The role ARN.</p> */ roleArn?: string; /** * <p>The role alias owner.</p> */ owner?: string; /** * <p>The number of seconds for which the credential is valid.</p> */ credentialDurationSeconds?: number; /** * <p>The UNIX timestamp of when the role alias was created.</p> */ creationDate?: Date; /** * <p>The UNIX timestamp of when the role alias was last modified.</p> */ lastModifiedDate?: Date; } export namespace RoleAliasDescription { /** * @internal */ export const filterSensitiveLog = (obj: RoleAliasDescription): any => ({ ...obj, }); } export interface DescribeRoleAliasResponse { /** * <p>The role alias description.</p> */ roleAliasDescription?: RoleAliasDescription; } export namespace DescribeRoleAliasResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRoleAliasResponse): any => ({ ...obj, }); } export interface DescribeScheduledAuditRequest { /** * <p>The name of the scheduled audit whose information you want to get.</p> */ scheduledAuditName: string | undefined; } export namespace DescribeScheduledAuditRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeScheduledAuditRequest): any => ({ ...obj, }); } export interface DescribeScheduledAuditResponse { /** * <p>How often the scheduled audit takes * place, either * one of <code>DAILY</code>, * <code>WEEKLY</code>, <code>BIWEEKLY</code>, or <code>MONTHLY</code>. The start time of each audit is determined by the * system.</p> */ frequency?: AuditFrequency | string; /** * <p>The day of the month on which the scheduled audit takes place. * This is * will be <code>1</code> * through <code>31</code> or <code>LAST</code>. If days * <code>29</code>-<code>31</code> * are specified, and the month does not have that many days, the audit takes place on the <code>LAST</code> * day of the month.</p> */ dayOfMonth?: string; /** * <p>The day of the week on which the scheduled audit takes * place, * either one of * <code>SUN</code>, <code>MON</code>, <code>TUE</code>, <code>WED</code>, <code>THU</code>, <code>FRI</code>, or <code>SAT</code>.</p> */ dayOfWeek?: DayOfWeek | string; /** * <p>Which checks are performed during the scheduled audit. Checks must be * enabled for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the list * of all checks, including those that are enabled or use <code>UpdateAccountAuditConfiguration</code> * to select which checks are enabled.)</p> */ targetCheckNames?: string[]; /** * <p>The name of the scheduled audit.</p> */ scheduledAuditName?: string; /** * <p>The ARN of the scheduled audit.</p> */ scheduledAuditArn?: string; } export namespace DescribeScheduledAuditResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeScheduledAuditResponse): any => ({ ...obj, }); } export interface DescribeSecurityProfileRequest { /** * <p>The name of the security profile * whose information you want to get.</p> */ securityProfileName: string | undefined; } export namespace DescribeSecurityProfileRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeSecurityProfileRequest): any => ({ ...obj, }); } export interface DescribeSecurityProfileResponse { /** * <p>The name of the security profile.</p> */ securityProfileName?: string; /** * <p>The ARN of the security profile.</p> */ securityProfileArn?: string; /** * <p>A description of the security profile (associated with the security profile * when it was created or updated).</p> */ securityProfileDescription?: string; /** * <p>Specifies the behaviors that, when violated by a device (thing), cause an alert.</p> */ behaviors?: Behavior[]; /** * <p>Where the alerts are sent. (Alerts are always sent to the console.)</p> */ alertTargets?: { [key: string]: AlertTarget }; /** * @deprecated * * <p> * <i>Please use * <a>DescribeSecurityProfileResponse$additionalMetricsToRetainV2</a> * instead.</i> * </p> * <p>A list of metrics * whose data is retained (stored). By default, data is retained for any metric * used in the profile's <code>behaviors</code>, but * it is * also retained for any metric specified here.</p> */ additionalMetricsToRetain?: string[]; /** * <p>A list of metrics whose data is retained (stored). By default, data is retained for any * metric used in the profile's behaviors, but * it is * also retained for any metric specified here.</p> */ additionalMetricsToRetainV2?: MetricToRetain[]; /** * <p>The version of the security profile. A new version is generated whenever the * security profile is updated.</p> */ version?: number; /** * <p>The time the security profile was created.</p> */ creationDate?: Date; /** * <p>The time the security profile was last modified.</p> */ lastModifiedDate?: Date; } export namespace DescribeSecurityProfileResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeSecurityProfileResponse): any => ({ ...obj, }); } export interface DescribeStreamRequest { /** * <p>The stream ID.</p> */ streamId: string | undefined; } export namespace DescribeStreamRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeStreamRequest): any => ({ ...obj, }); } /** * <p>Information about a stream.</p> */ export interface StreamInfo { /** * <p>The stream ID.</p> */ streamId?: string; /** * <p>The stream ARN.</p> */ streamArn?: string; /** * <p>The stream version.</p> */ streamVersion?: number; /** * <p>The description of the stream.</p> */ description?: string; /** * <p>The files to stream.</p> */ files?: StreamFile[]; /** * <p>The date when the stream was created.</p> */ createdAt?: Date; /** * <p>The date when the stream was last updated.</p> */ lastUpdatedAt?: Date; /** * <p>An IAM role IoT assumes to access your S3 files.</p> */ roleArn?: string; } export namespace StreamInfo { /** * @internal */ export const filterSensitiveLog = (obj: StreamInfo): any => ({ ...obj, }); } export interface DescribeStreamResponse { /** * <p>Information about the stream.</p> */ streamInfo?: StreamInfo; } export namespace DescribeStreamResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeStreamResponse): any => ({ ...obj, }); } /** * <p>The input for the DescribeThing operation.</p> */ export interface DescribeThingRequest { /** * <p>The name of the thing.</p> */ thingName: string | undefined; } export namespace DescribeThingRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeThingRequest): any => ({ ...obj, }); } /** * <p>The output from the DescribeThing operation.</p> */ export interface DescribeThingResponse { /** * <p>The default MQTT client ID. For a typical device, the thing name is also used as the default MQTT client ID. * Although we don’t require a mapping between a thing's registry name and its use of MQTT client IDs, certificates, or * shadow state, we recommend that you choose a thing name and use it as the MQTT client ID for the registry and the Device Shadow service.</p> * <p>This lets you better organize your IoT fleet without removing the flexibility of the underlying device certificate model or shadows.</p> */ defaultClientId?: string; /** * <p>The name of the thing.</p> */ thingName?: string; /** * <p>The ID of the thing to describe.</p> */ thingId?: string; /** * <p>The ARN of the thing to describe.</p> */ thingArn?: string; /** * <p>The thing type name.</p> */ thingTypeName?: string; /** * <p>The thing attributes.</p> */ attributes?: { [key: string]: string }; /** * <p>The current version of the thing record in the registry.</p> * <note> * <p>To avoid unintentional changes to the information in the registry, you can pass * the version information in the <code>expectedVersion</code> parameter of the * <code>UpdateThing</code> and <code>DeleteThing</code> calls.</p> * </note> */ version?: number; /** * <p>The name of the billing group the thing belongs to.</p> */ billingGroupName?: string; } export namespace DescribeThingResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeThingResponse): any => ({ ...obj, }); } export interface DescribeThingGroupRequest { /** * <p>The name of the thing group.</p> */ thingGroupName: string | undefined; } export namespace DescribeThingGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeThingGroupRequest): any => ({ ...obj, }); } export enum DynamicGroupStatus { ACTIVE = "ACTIVE", BUILDING = "BUILDING", REBUILDING = "REBUILDING", } /** * <p>The name and ARN of a group.</p> */ export interface GroupNameAndArn { /** * <p>The group name.</p> */ groupName?: string; /** * <p>The group ARN.</p> */ groupArn?: string; } export namespace GroupNameAndArn { /** * @internal */ export const filterSensitiveLog = (obj: GroupNameAndArn): any => ({ ...obj, }); } /** * <p>Thing group metadata.</p> */ export interface ThingGroupMetadata { /** * <p>The parent thing group name.</p> */ parentGroupName?: string; /** * <p>The root parent thing group.</p> */ rootToParentThingGroups?: GroupNameAndArn[]; /** * <p>The UNIX timestamp of when the thing group was created.</p> */ creationDate?: Date; } export namespace ThingGroupMetadata { /** * @internal */ export const filterSensitiveLog = (obj: ThingGroupMetadata): any => ({ ...obj, }); } export interface DescribeThingGroupResponse { /** * <p>The name of the thing group.</p> */ thingGroupName?: string; /** * <p>The thing group ID.</p> */ thingGroupId?: string; /** * <p>The thing group ARN.</p> */ thingGroupArn?: string; /** * <p>The version of the thing group.</p> */ version?: number; /** * <p>The thing group properties.</p> */ thingGroupProperties?: ThingGroupProperties; /** * <p>Thing group metadata.</p> */ thingGroupMetadata?: ThingGroupMetadata; /** * <p>The dynamic thing group index name.</p> */ indexName?: string; /** * <p>The dynamic thing group search query string.</p> */ queryString?: string; /** * <p>The dynamic thing group query version.</p> */ queryVersion?: string; /** * <p>The dynamic thing group status.</p> */ status?: DynamicGroupStatus | string; } export namespace DescribeThingGroupResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeThingGroupResponse): any => ({ ...obj, }); } export interface DescribeThingRegistrationTaskRequest { /** * <p>The task ID.</p> */ taskId: string | undefined; } export namespace DescribeThingRegistrationTaskRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeThingRegistrationTaskRequest): any => ({ ...obj, }); } export enum Status { Cancelled = "Cancelled", Cancelling = "Cancelling", Completed = "Completed", Failed = "Failed", InProgress = "InProgress", } export interface DescribeThingRegistrationTaskResponse { /** * <p>The task ID.</p> */ taskId?: string; /** * <p>The task creation date.</p> */ creationDate?: Date; /** * <p>The date when the task was last modified.</p> */ lastModifiedDate?: Date; /** * <p>The task's template.</p> */ templateBody?: string; /** * <p>The S3 bucket that contains the input file.</p> */ inputFileBucket?: string; /** * <p>The input file key.</p> */ inputFileKey?: string; /** * <p>The role ARN that grants access to the input file bucket.</p> */ roleArn?: string; /** * <p>The status of the bulk thing provisioning task.</p> */ status?: Status | string; /** * <p>The message.</p> */ message?: string; /** * <p>The number of things successfully provisioned.</p> */ successCount?: number; /** * <p>The number of things that failed to be provisioned.</p> */ failureCount?: number; /** * <p>The progress of the bulk provisioning task expressed as a percentage.</p> */ percentageProgress?: number; } export namespace DescribeThingRegistrationTaskResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeThingRegistrationTaskResponse): any => ({ ...obj, }); } /** * <p>The input for the DescribeThingType operation.</p> */ export interface DescribeThingTypeRequest { /** * <p>The name of the thing type.</p> */ thingTypeName: string | undefined; } export namespace DescribeThingTypeRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeThingTypeRequest): any => ({ ...obj, }); } /** * <p>The ThingTypeMetadata contains additional information about the thing type including: creation date and * time, a value indicating whether the thing type is deprecated, and a date and time when time was * deprecated.</p> */ export interface ThingTypeMetadata { /** * <p>Whether the thing type is deprecated. If <b>true</b>, no new things could be * associated with this type.</p> */ deprecated?: boolean; /** * <p>The date and time when the thing type was deprecated.</p> */ deprecationDate?: Date; /** * <p>The date and time when the thing type was created.</p> */ creationDate?: Date; } export namespace ThingTypeMetadata { /** * @internal */ export const filterSensitiveLog = (obj: ThingTypeMetadata): any => ({ ...obj, }); } /** * <p>The output for the DescribeThingType operation.</p> */ export interface DescribeThingTypeResponse { /** * <p>The name of the thing type.</p> */ thingTypeName?: string; /** * <p>The thing type ID.</p> */ thingTypeId?: string; /** * <p>The thing type ARN.</p> */ thingTypeArn?: string; /** * <p>The ThingTypeProperties contains information about the thing type including * description, and a list of searchable thing attribute names.</p> */ thingTypeProperties?: ThingTypeProperties; /** * <p>The ThingTypeMetadata contains additional information about the thing type * including: creation date and time, a value indicating whether the thing type is * deprecated, and a date and time when it was deprecated.</p> */ thingTypeMetadata?: ThingTypeMetadata; } export namespace DescribeThingTypeResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeThingTypeResponse): any => ({ ...obj, }); } export interface DetachPolicyRequest { /** * <p>The policy to detach.</p> */ policyName: string | undefined; /** * <p>The target from which the policy will be detached.</p> */ target: string | undefined; } export namespace DetachPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: DetachPolicyRequest): any => ({ ...obj, }); } /** * <p>The input for the DetachPrincipalPolicy operation.</p> */ export interface DetachPrincipalPolicyRequest { /** * <p>The name of the policy to detach.</p> */ policyName: string | undefined; /** * <p>The principal.</p> * <p>Valid principals are CertificateArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:cert/<i>certificateId</i>), thingGroupArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:thinggroup/<i>groupName</i>) and CognitoId (<i>region</i>:<i>id</i>).</p> */ principal: string | undefined; } export namespace DetachPrincipalPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: DetachPrincipalPolicyRequest): any => ({ ...obj, }); } export interface DetachSecurityProfileRequest { /** * <p>The security profile that is detached.</p> */ securityProfileName: string | undefined; /** * <p>The ARN of the thing group from which the security profile is detached.</p> */ securityProfileTargetArn: string | undefined; } export namespace DetachSecurityProfileRequest { /** * @internal */ export const filterSensitiveLog = (obj: DetachSecurityProfileRequest): any => ({ ...obj, }); } export interface DetachSecurityProfileResponse {} export namespace DetachSecurityProfileResponse { /** * @internal */ export const filterSensitiveLog = (obj: DetachSecurityProfileResponse): any => ({ ...obj, }); } /** * <p>The input for the DetachThingPrincipal operation.</p> */ export interface DetachThingPrincipalRequest { /** * <p>The name of the thing.</p> */ thingName: string | undefined; /** * <p>If the principal is a certificate, this value must be ARN of the certificate. If * the principal is an Amazon Cognito identity, this value must be the ID of the Amazon * Cognito identity.</p> */ principal: string | undefined; } export namespace DetachThingPrincipalRequest { /** * @internal */ export const filterSensitiveLog = (obj: DetachThingPrincipalRequest): any => ({ ...obj, }); } /** * <p>The output from the DetachThingPrincipal operation.</p> */ export interface DetachThingPrincipalResponse {} export namespace DetachThingPrincipalResponse { /** * @internal */ export const filterSensitiveLog = (obj: DetachThingPrincipalResponse): any => ({ ...obj, }); } /** * <p>The input for the DisableTopicRuleRequest operation.</p> */ export interface DisableTopicRuleRequest { /** * <p>The name of the rule to disable.</p> */ ruleName: string | undefined; } export namespace DisableTopicRuleRequest { /** * @internal */ export const filterSensitiveLog = (obj: DisableTopicRuleRequest): any => ({ ...obj, }); } /** * <p>The input for the EnableTopicRuleRequest operation.</p> */ export interface EnableTopicRuleRequest { /** * <p>The name of the topic rule to enable.</p> */ ruleName: string | undefined; } export namespace EnableTopicRuleRequest { /** * @internal */ export const filterSensitiveLog = (obj: EnableTopicRuleRequest): any => ({ ...obj, }); } export interface GetBehaviorModelTrainingSummariesRequest { /** * <p> * The name of the security profile. * </p> */ securityProfileName?: string; /** * <p> * The maximum number of results to return at one time. The default is 25. * </p> */ maxResults?: number; /** * <p> * The token for the next set of results. * </p> */ nextToken?: string; } export namespace GetBehaviorModelTrainingSummariesRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetBehaviorModelTrainingSummariesRequest): any => ({ ...obj, }); } export enum ModelStatus { ACTIVE = "ACTIVE", EXPIRED = "EXPIRED", PENDING_BUILD = "PENDING_BUILD", } /** * <p> * The summary of an ML Detect behavior model. * </p> */ export interface BehaviorModelTrainingSummary { /** * <p> * The name of the security profile. * </p> */ securityProfileName?: string; /** * <p> * The name of the behavior. * </p> */ behaviorName?: string; /** * <p> * The date a training model started collecting data. * </p> */ trainingDataCollectionStartDate?: Date; /** * <p> * The status of the behavior model. * </p> */ modelStatus?: ModelStatus | string; /** * <p> * The percentage of datapoints collected. * </p> */ datapointsCollectionPercentage?: number; /** * <p> * The date the model was last refreshed. * </p> */ lastModelRefreshDate?: Date; } export namespace BehaviorModelTrainingSummary { /** * @internal */ export const filterSensitiveLog = (obj: BehaviorModelTrainingSummary): any => ({ ...obj, }); } export interface GetBehaviorModelTrainingSummariesResponse { /** * <p> * A list of all ML Detect behaviors and their model status for a given Security Profile. * </p> */ summaries?: BehaviorModelTrainingSummary[]; /** * <p> * A token that can be used to retrieve the next set of results, or <code>null</code> if there are no additional results. * </p> */ nextToken?: string; } export namespace GetBehaviorModelTrainingSummariesResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetBehaviorModelTrainingSummariesResponse): any => ({ ...obj, }); } /** * <p>Performs an aggregation that will return a list of buckets. The list of buckets is a ranked list of the number of occurrences of an aggregation field value.</p> */ export interface TermsAggregation { /** * <p>The number of buckets to return in the response. Default to 10.</p> */ maxBuckets?: number; } export namespace TermsAggregation { /** * @internal */ export const filterSensitiveLog = (obj: TermsAggregation): any => ({ ...obj, }); } /** * <p>The type of bucketed aggregation performed.</p> */ export interface BucketsAggregationType { /** * <p>Performs an aggregation that will return a list of buckets. The list of buckets is a ranked list of the number of occurrences of an aggregation field value.</p> */ termsAggregation?: TermsAggregation; } export namespace BucketsAggregationType { /** * @internal */ export const filterSensitiveLog = (obj: BucketsAggregationType): any => ({ ...obj, }); } export interface GetBucketsAggregationRequest { /** * <p>The name of the index to search.</p> */ indexName?: string; /** * <p>The search query string.</p> */ queryString: string | undefined; /** * <p>The aggregation field.</p> */ aggregationField: string | undefined; /** * <p>The version of the query.</p> */ queryVersion?: string; /** * <p>The basic control of the response shape and the bucket aggregation type to perform. </p> */ bucketsAggregationType: BucketsAggregationType | undefined; } export namespace GetBucketsAggregationRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetBucketsAggregationRequest): any => ({ ...obj, }); } /** * <p>A count of documents that meets a specific aggregation criteria.</p> */ export interface Bucket { /** * <p>The value counted for the particular bucket.</p> */ keyValue?: string; /** * <p>The number of documents that have the value counted for the particular bucket.</p> */ count?: number; } export namespace Bucket { /** * @internal */ export const filterSensitiveLog = (obj: Bucket): any => ({ ...obj, }); } export interface GetBucketsAggregationResponse { /** * <p>The total number of documents that fit the query string criteria and contain a value for * the Aggregation field targeted in the request.</p> */ totalCount?: number; /** * <p>The main part of the response with a list of buckets. Each bucket contains a <code>keyValue</code> and a <code>count</code>.</p> * <p> * <code>keyValue</code>: The aggregation field value counted for the particular bucket.</p> * <p> * <code>count</code>: The number of documents that have that value.</p> */ buckets?: Bucket[]; } export namespace GetBucketsAggregationResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetBucketsAggregationResponse): any => ({ ...obj, }); } export interface GetCardinalityRequest { /** * <p>The name of the index to search.</p> */ indexName?: string; /** * <p>The search query string.</p> */ queryString: string | undefined; /** * <p>The field to aggregate.</p> */ aggregationField?: string; /** * <p>The query version.</p> */ queryVersion?: string; } export namespace GetCardinalityRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetCardinalityRequest): any => ({ ...obj, }); } export interface GetCardinalityResponse { /** * <p>The approximate count of unique values that match the query.</p> */ cardinality?: number; } export namespace GetCardinalityResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetCardinalityResponse): any => ({ ...obj, }); } export interface GetEffectivePoliciesRequest { /** * <p>The principal. Valid principals are CertificateArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:cert/<i>certificateId</i>), thingGroupArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:thinggroup/<i>groupName</i>) and CognitoId (<i>region</i>:<i>id</i>).</p> */ principal?: string; /** * <p>The Cognito identity pool ID.</p> */ cognitoIdentityPoolId?: string; /** * <p>The thing name.</p> */ thingName?: string; } export namespace GetEffectivePoliciesRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetEffectivePoliciesRequest): any => ({ ...obj, }); } /** * <p>The policy that has the effect on the authorization results.</p> */ export interface EffectivePolicy { /** * <p>The policy name.</p> */ policyName?: string; /** * <p>The policy ARN.</p> */ policyArn?: string; /** * <p>The IAM policy document.</p> */ policyDocument?: string; } export namespace EffectivePolicy { /** * @internal */ export const filterSensitiveLog = (obj: EffectivePolicy): any => ({ ...obj, }); } export interface GetEffectivePoliciesResponse { /** * <p>The effective policies.</p> */ effectivePolicies?: EffectivePolicy[]; } export namespace GetEffectivePoliciesResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetEffectivePoliciesResponse): any => ({ ...obj, }); } export interface GetIndexingConfigurationRequest {} export namespace GetIndexingConfigurationRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetIndexingConfigurationRequest): any => ({ ...obj, }); } export enum FieldType { BOOLEAN = "Boolean", NUMBER = "Number", STRING = "String", } /** * <p>Describes the name and data type at a field.</p> */ export interface Field { /** * <p>The name of the field.</p> */ name?: string; /** * <p>The data type of the field.</p> */ type?: FieldType | string; } export namespace Field { /** * @internal */ export const filterSensitiveLog = (obj: Field): any => ({ ...obj, }); } export enum ThingGroupIndexingMode { OFF = "OFF", ON = "ON", } /** * <p>Thing group indexing configuration.</p> */ export interface ThingGroupIndexingConfiguration { /** * <p>Thing group indexing mode.</p> */ thingGroupIndexingMode: ThingGroupIndexingMode | string | undefined; /** * <p>Contains fields that are indexed and whose types are already known by the Fleet Indexing * service.</p> */ managedFields?: Field[]; /** * <p>A list of thing group fields to index. This list cannot contain any managed fields. Use * the GetIndexingConfiguration API to get a list of managed fields.</p> * <p>Contains custom field names and their data type.</p> */ customFields?: Field[]; } export namespace ThingGroupIndexingConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: ThingGroupIndexingConfiguration): any => ({ ...obj, }); } export enum ThingConnectivityIndexingMode { OFF = "OFF", STATUS = "STATUS", } export enum ThingIndexingMode { OFF = "OFF", REGISTRY = "REGISTRY", REGISTRY_AND_SHADOW = "REGISTRY_AND_SHADOW", } /** * <p>The thing indexing configuration. For more information, see <a href="https://docs.aws.amazon.com/iot/latest/developerguide/managing-index.html">Managing * Thing Indexing</a>.</p> */ export interface ThingIndexingConfiguration { /** * <p>Thing indexing mode. Valid values are:</p> * <ul> * <li> * <p>REGISTRY – Your thing index contains registry data only.</p> * </li> * <li> * <p>REGISTRY_AND_SHADOW - Your thing index contains registry and shadow data.</p> * </li> * <li> * <p>OFF - Thing indexing is disabled.</p> * </li> * </ul> */ thingIndexingMode: ThingIndexingMode | string | undefined; /** * <p>Thing connectivity indexing mode. Valid values are: </p> * <ul> * <li> * <p>STATUS – Your thing index contains connectivity status. To enable thing * connectivity indexing, <i>thingIndexMode</i> must not be set to * OFF.</p> * </li> * <li> * <p>OFF - Thing connectivity status indexing is disabled.</p> * </li> * </ul> */ thingConnectivityIndexingMode?: ThingConnectivityIndexingMode | string; /** * <p>Contains fields that are indexed and whose types are already known by the Fleet Indexing * service.</p> */ managedFields?: Field[]; /** * <p>Contains custom field names and their data type.</p> */ customFields?: Field[]; } export namespace ThingIndexingConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: ThingIndexingConfiguration): any => ({ ...obj, }); } export interface GetIndexingConfigurationResponse { /** * <p>Thing indexing configuration.</p> */ thingIndexingConfiguration?: ThingIndexingConfiguration; /** * <p>The index configuration.</p> */ thingGroupIndexingConfiguration?: ThingGroupIndexingConfiguration; } export namespace GetIndexingConfigurationResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetIndexingConfigurationResponse): any => ({ ...obj, }); } export interface GetJobDocumentRequest { /** * <p>The unique identifier you assigned to this job when it was created.</p> */ jobId: string | undefined; } export namespace GetJobDocumentRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetJobDocumentRequest): any => ({ ...obj, }); } export interface GetJobDocumentResponse { /** * <p>The job document content.</p> */ document?: string; } export namespace GetJobDocumentResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetJobDocumentResponse): any => ({ ...obj, }); } /** * <p>The input for the GetLoggingOptions operation.</p> */ export interface GetLoggingOptionsRequest {} export namespace GetLoggingOptionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetLoggingOptionsRequest): any => ({ ...obj, }); } /** * <p>The output from the GetLoggingOptions operation.</p> */ export interface GetLoggingOptionsResponse { /** * <p>The ARN of the IAM role that grants access.</p> */ roleArn?: string; /** * <p>The logging level.</p> */ logLevel?: LogLevel | string; } export namespace GetLoggingOptionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetLoggingOptionsResponse): any => ({ ...obj, }); } export interface GetOTAUpdateRequest { /** * <p>The OTA update ID.</p> */ otaUpdateId: string | undefined; } export namespace GetOTAUpdateRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetOTAUpdateRequest): any => ({ ...obj, }); } /** * <p>Error information.</p> */ export interface ErrorInfo { /** * <p>The error code.</p> */ code?: string; /** * <p>The error message.</p> */ message?: string; } export namespace ErrorInfo { /** * @internal */ export const filterSensitiveLog = (obj: ErrorInfo): any => ({ ...obj, }); } /** * <p>Information about an OTA update.</p> */ export interface OTAUpdateInfo { /** * <p>The OTA update ID.</p> */ otaUpdateId?: string; /** * <p>The OTA update ARN.</p> */ otaUpdateArn?: string; /** * <p>The date when the OTA update was created.</p> */ creationDate?: Date; /** * <p>The date when the OTA update was last updated.</p> */ lastModifiedDate?: Date; /** * <p>A description of the OTA update.</p> */ description?: string; /** * <p>The targets of the OTA update.</p> */ targets?: string[]; /** * <p>The protocol used to transfer the OTA update image. Valid values are [HTTP], [MQTT], [HTTP, MQTT]. When both * HTTP and MQTT are specified, the target device can choose the protocol.</p> */ protocols?: (Protocol | string)[]; /** * <p>Configuration for the rollout of OTA updates.</p> */ awsJobExecutionsRolloutConfig?: AwsJobExecutionsRolloutConfig; /** * <p>Configuration information for pre-signed URLs. Valid when <code>protocols</code> * contains HTTP.</p> */ awsJobPresignedUrlConfig?: AwsJobPresignedUrlConfig; /** * <p>Specifies whether the OTA update will continue to run (CONTINUOUS), or will be complete after all those * things specified as targets have completed the OTA update (SNAPSHOT). If continuous, the OTA update may also * be run on a thing when a change is detected in a target. For example, an OTA update will run on a thing when * the thing is added to a target group, even after the OTA update was completed by all things originally in * the group. </p> */ targetSelection?: TargetSelection | string; /** * <p>A list of files associated with the OTA update.</p> */ otaUpdateFiles?: OTAUpdateFile[]; /** * <p>The status of the OTA update.</p> */ otaUpdateStatus?: OTAUpdateStatus | string; /** * <p>The IoT job ID associated with the OTA update.</p> */ awsIotJobId?: string; /** * <p>The IoT job ARN associated with the OTA update.</p> */ awsIotJobArn?: string; /** * <p>Error information associated with the OTA update.</p> */ errorInfo?: ErrorInfo; /** * <p>A collection of name/value pairs</p> */ additionalParameters?: { [key: string]: string }; } export namespace OTAUpdateInfo { /** * @internal */ export const filterSensitiveLog = (obj: OTAUpdateInfo): any => ({ ...obj, }); } export interface GetOTAUpdateResponse { /** * <p>The OTA update info.</p> */ otaUpdateInfo?: OTAUpdateInfo; } export namespace GetOTAUpdateResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetOTAUpdateResponse): any => ({ ...obj, }); } export interface GetPercentilesRequest { /** * <p>The name of the index to search.</p> */ indexName?: string; /** * <p>The search query string.</p> */ queryString: string | undefined; /** * <p>The field to aggregate.</p> */ aggregationField?: string; /** * <p>The query version.</p> */ queryVersion?: string; /** * <p>The percentile groups returned.</p> */ percents?: number[]; } export namespace GetPercentilesRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetPercentilesRequest): any => ({ ...obj, }); } /** * <p>Describes the percentile and percentile value.</p> */ export interface PercentPair { /** * <p>The percentile.</p> */ percent?: number; /** * <p>The value of the percentile.</p> */ value?: number; } export namespace PercentPair { /** * @internal */ export const filterSensitiveLog = (obj: PercentPair): any => ({ ...obj, }); } export interface GetPercentilesResponse { /** * <p>The percentile values of the aggregated fields.</p> */ percentiles?: PercentPair[]; } export namespace GetPercentilesResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetPercentilesResponse): any => ({ ...obj, }); } /** * <p>The input for the GetPolicy operation.</p> */ export interface GetPolicyRequest { /** * <p>The name of the policy.</p> */ policyName: string | undefined; } export namespace GetPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetPolicyRequest): any => ({ ...obj, }); } /** * <p>The output from the GetPolicy operation.</p> */ export interface GetPolicyResponse { /** * <p>The policy name.</p> */ policyName?: string; /** * <p>The policy ARN.</p> */ policyArn?: string; /** * <p>The JSON document that describes the policy.</p> */ policyDocument?: string; /** * <p>The default policy version ID.</p> */ defaultVersionId?: string; /** * <p>The date the policy was created.</p> */ creationDate?: Date; /** * <p>The date the policy was last modified.</p> */ lastModifiedDate?: Date; /** * <p>The generation ID of the policy.</p> */ generationId?: string; } export namespace GetPolicyResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetPolicyResponse): any => ({ ...obj, }); } /** * <p>The input for the GetPolicyVersion operation.</p> */ export interface GetPolicyVersionRequest { /** * <p>The name of the policy.</p> */ policyName: string | undefined; /** * <p>The policy version ID.</p> */ policyVersionId: string | undefined; } export namespace GetPolicyVersionRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetPolicyVersionRequest): any => ({ ...obj, }); } /** * <p>The output from the GetPolicyVersion operation.</p> */ export interface GetPolicyVersionResponse { /** * <p>The policy ARN.</p> */ policyArn?: string; /** * <p>The policy name.</p> */ policyName?: string; /** * <p>The JSON document that describes the policy.</p> */ policyDocument?: string; /** * <p>The policy version ID.</p> */ policyVersionId?: string; /** * <p>Specifies whether the policy version is the default.</p> */ isDefaultVersion?: boolean; /** * <p>The date the policy was created.</p> */ creationDate?: Date; /** * <p>The date the policy was last modified.</p> */ lastModifiedDate?: Date; /** * <p>The generation ID of the policy version.</p> */ generationId?: string; } export namespace GetPolicyVersionResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetPolicyVersionResponse): any => ({ ...obj, }); } /** * <p>The input to the GetRegistrationCode operation.</p> */ export interface GetRegistrationCodeRequest {} export namespace GetRegistrationCodeRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetRegistrationCodeRequest): any => ({ ...obj, }); } /** * <p>The output from the GetRegistrationCode operation.</p> */ export interface GetRegistrationCodeResponse { /** * <p>The CA certificate registration code.</p> */ registrationCode?: string; } export namespace GetRegistrationCodeResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetRegistrationCodeResponse): any => ({ ...obj, }); } export interface GetStatisticsRequest { /** * <p>The name of the index to search. The default value is <code>AWS_Things</code>.</p> */ indexName?: string; /** * <p>The query used to search. You can specify "*" for the query string to get the count of all * indexed things in your Amazon Web Services account.</p> */ queryString: string | undefined; /** * <p>The aggregation field name.</p> */ aggregationField?: string; /** * <p>The version of the query used to search.</p> */ queryVersion?: string; } export namespace GetStatisticsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetStatisticsRequest): any => ({ ...obj, }); } /** * <p>A map of key-value pairs for all supported statistics. Currently, only count is * supported.</p> */ export interface Statistics { /** * <p>The count of things that match the query.</p> */ count?: number; /** * <p>The average of the aggregated field values.</p> */ average?: number; /** * <p>The sum of the aggregated field values.</p> */ sum?: number; /** * <p>The minimum aggregated field value.</p> */ minimum?: number; /** * <p>The maximum aggregated field value.</p> */ maximum?: number; /** * <p>The sum of the squares of the aggregated field values.</p> */ sumOfSquares?: number; /** * <p>The variance of the aggregated field values.</p> */ variance?: number; /** * <p>The standard deviation of the aggregated field values.</p> */ stdDeviation?: number; } export namespace Statistics { /** * @internal */ export const filterSensitiveLog = (obj: Statistics): any => ({ ...obj, }); } export interface GetStatisticsResponse { /** * <p>The statistics returned by the Fleet Indexing service based on the query and aggregation * field.</p> */ statistics?: Statistics; } export namespace GetStatisticsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetStatisticsResponse): any => ({ ...obj, }); } /** * <p>The input for the GetTopicRule operation.</p> */ export interface GetTopicRuleRequest { /** * <p>The name of the rule.</p> */ ruleName: string | undefined; } export namespace GetTopicRuleRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetTopicRuleRequest): any => ({ ...obj, }); } /** * <p>Describes a rule.</p> */ export interface TopicRule { /** * <p>The name of the rule.</p> */ ruleName?: string; /** * <p>The SQL statement used to query the topic. When using a SQL query with multiple * lines, be sure to escape the newline characters.</p> */ sql?: string; /** * <p>The description of the rule.</p> */ description?: string; /** * <p>The date and time the rule was created.</p> */ createdAt?: Date; /** * <p>The actions associated with the rule.</p> */ actions?: Action[]; /** * <p>Specifies whether the rule is disabled.</p> */ ruleDisabled?: boolean; /** * <p>The version of the SQL rules engine to use when evaluating the rule.</p> */ awsIotSqlVersion?: string; /** * <p>The action to perform when an error occurs.</p> */ errorAction?: Action; } export namespace TopicRule { /** * @internal */ export const filterSensitiveLog = (obj: TopicRule): any => ({ ...obj, }); } /** * <p>The output from the GetTopicRule operation.</p> */ export interface GetTopicRuleResponse { /** * <p>The rule ARN.</p> */ ruleArn?: string; /** * <p>The rule.</p> */ rule?: TopicRule; } export namespace GetTopicRuleResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetTopicRuleResponse): any => ({ ...obj, }); } export interface GetTopicRuleDestinationRequest { /** * <p>The ARN of the topic rule destination.</p> */ arn: string | undefined; } export namespace GetTopicRuleDestinationRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetTopicRuleDestinationRequest): any => ({ ...obj, }); } export interface GetTopicRuleDestinationResponse { /** * <p>The topic rule destination.</p> */ topicRuleDestination?: TopicRuleDestination; } export namespace GetTopicRuleDestinationResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetTopicRuleDestinationResponse): any => ({ ...obj, }); } export interface GetV2LoggingOptionsRequest {} export namespace GetV2LoggingOptionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetV2LoggingOptionsRequest): any => ({ ...obj, }); } export interface GetV2LoggingOptionsResponse { /** * <p>The IAM role ARN IoT uses to write to your CloudWatch logs.</p> */ roleArn?: string; /** * <p>The default log level.</p> */ defaultLogLevel?: LogLevel | string; /** * <p>Disables all logs.</p> */ disableAllLogs?: boolean; } export namespace GetV2LoggingOptionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetV2LoggingOptionsResponse): any => ({ ...obj, }); } /** * <p>The resource is not configured.</p> */ export interface NotConfiguredException extends __SmithyException, $MetadataBearer { name: "NotConfiguredException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace NotConfiguredException { /** * @internal */ export const filterSensitiveLog = (obj: NotConfiguredException): any => ({ ...obj, }); } export enum BehaviorCriteriaType { MACHINE_LEARNING = "MACHINE_LEARNING", STATIC = "STATIC", STATISTICAL = "STATISTICAL", } export interface ListActiveViolationsRequest { /** * <p>The name of the thing whose active violations are listed.</p> */ thingName?: string; /** * <p>The name of the Device Defender security profile for which violations are listed.</p> */ securityProfileName?: string; /** * <p> * The criteria for a behavior. * </p> */ behaviorCriteriaType?: BehaviorCriteriaType | string; /** * <p> * A list of all suppressed alerts. * </p> */ listSuppressedAlerts?: boolean; /** * <p>The verification state of the violation (detect alarm).</p> */ verificationState?: VerificationState | string; /** * <p>The token for the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; } export namespace ListActiveViolationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListActiveViolationsRequest): any => ({ ...obj, }); } export interface ListActiveViolationsResponse { /** * <p>The list of active violations.</p> */ activeViolations?: ActiveViolation[]; /** * <p>A token that can be used to retrieve the next set of results, * or <code>null</code> if there are no additional results.</p> */ nextToken?: string; } export namespace ListActiveViolationsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListActiveViolationsResponse): any => ({ ...obj, }); } export interface ListAttachedPoliciesRequest { /** * <p>The group or principal for which the policies will be listed. Valid principals are CertificateArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:cert/<i>certificateId</i>), thingGroupArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:thinggroup/<i>groupName</i>) and CognitoId (<i>region</i>:<i>id</i>).</p> */ target: string | undefined; /** * <p>When true, recursively list attached policies.</p> */ recursive?: boolean; /** * <p>The token to retrieve the next set of results.</p> */ marker?: string; /** * <p>The maximum number of results to be returned per request.</p> */ pageSize?: number; } export namespace ListAttachedPoliciesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAttachedPoliciesRequest): any => ({ ...obj, }); } export interface ListAttachedPoliciesResponse { /** * <p>The policies.</p> */ policies?: Policy[]; /** * <p>The token to retrieve the next set of results, or ``null`` if there are no more * results.</p> */ nextMarker?: string; } export namespace ListAttachedPoliciesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListAttachedPoliciesResponse): any => ({ ...obj, }); } export interface ListAuditFindingsRequest { /** * <p>A filter to limit results to the audit with the specified ID. You must * specify either the taskId or the startTime and endTime, but not both.</p> */ taskId?: string; /** * <p>A filter to limit results to the findings for the specified audit check.</p> */ checkName?: string; /** * <p>Information identifying the noncompliant resource.</p> */ resourceIdentifier?: ResourceIdentifier; /** * <p>The maximum number of results to return at one time. The default is 25.</p> */ maxResults?: number; /** * <p>The token for the next set of results.</p> */ nextToken?: string; /** * <p>A filter to limit results to those found after the specified time. You must * specify either the startTime and endTime or the taskId, but not both.</p> */ startTime?: Date; /** * <p>A filter to limit results to those found before the specified time. You must * specify either the startTime and endTime or the taskId, but not both.</p> */ endTime?: Date; /** * <p> * Boolean flag indicating whether only the suppressed findings or the unsuppressed findings should be listed. If this parameter isn't provided, the response will list both suppressed and unsuppressed findings. * </p> */ listSuppressedFindings?: boolean; } export namespace ListAuditFindingsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditFindingsRequest): any => ({ ...obj, }); } export interface ListAuditFindingsResponse { /** * <p>The findings (results) of the audit.</p> */ findings?: AuditFinding[]; /** * <p>A token that can be used to retrieve the next set of results, or <code>null</code> * if there are no additional results.</p> */ nextToken?: string; } export namespace ListAuditFindingsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditFindingsResponse): any => ({ ...obj, }); } export interface ListAuditMitigationActionsExecutionsRequest { /** * <p>Specify this filter to limit results to actions for a specific audit mitigation actions task.</p> */ taskId: string | undefined; /** * <p>Specify this filter to limit results to those with a specific status.</p> */ actionStatus?: AuditMitigationActionsExecutionStatus | string; /** * <p>Specify this filter to limit results to those that were applied to a specific audit finding.</p> */ findingId: string | undefined; /** * <p>The maximum number of results to return at one time. The default is 25.</p> */ maxResults?: number; /** * <p>The token for the next set of results.</p> */ nextToken?: string; } export namespace ListAuditMitigationActionsExecutionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditMitigationActionsExecutionsRequest): any => ({ ...obj, }); } export interface ListAuditMitigationActionsExecutionsResponse { /** * <p>A set of task execution results based on the input parameters. Details include the mitigation action applied, start time, and task status.</p> */ actionsExecutions?: AuditMitigationActionExecutionMetadata[]; /** * <p>The token for the next set of results.</p> */ nextToken?: string; } export namespace ListAuditMitigationActionsExecutionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditMitigationActionsExecutionsResponse): any => ({ ...obj, }); } export interface ListAuditMitigationActionsTasksRequest { /** * <p>Specify this filter to limit results to tasks that were applied to results for a specific audit.</p> */ auditTaskId?: string; /** * <p>Specify this filter to limit results to tasks that were applied to a specific audit finding.</p> */ findingId?: string; /** * <p>Specify this filter to limit results to tasks that are in a specific state.</p> */ taskStatus?: AuditMitigationActionsTaskStatus | string; /** * <p>The maximum number of results to return at one time. The default is 25.</p> */ maxResults?: number; /** * <p>The token for the next set of results.</p> */ nextToken?: string; /** * <p>Specify this filter to limit results to tasks that began on or after a specific date and time.</p> */ startTime: Date | undefined; /** * <p>Specify this filter to limit results to tasks that were completed or canceled on or before a specific date and time.</p> */ endTime: Date | undefined; } export namespace ListAuditMitigationActionsTasksRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditMitigationActionsTasksRequest): any => ({ ...obj, }); } export interface ListAuditMitigationActionsTasksResponse { /** * <p>The collection of audit mitigation tasks that matched the filter criteria.</p> */ tasks?: AuditMitigationActionsTaskMetadata[]; /** * <p>The token for the next set of results.</p> */ nextToken?: string; } export namespace ListAuditMitigationActionsTasksResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditMitigationActionsTasksResponse): any => ({ ...obj, }); } export interface ListAuditSuppressionsRequest { /** * <p>An audit check name. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the list * of all checks, including those that are enabled or use <code>UpdateAccountAuditConfiguration</code> * to select which checks are enabled.)</p> */ checkName?: string; /** * <p>Information that identifies the noncompliant resource.</p> */ resourceIdentifier?: ResourceIdentifier; /** * <p> * Determines whether suppressions are listed in ascending order by expiration date or not. If parameter isn't provided, <code>ascendingOrder=true</code>. * </p> */ ascendingOrder?: boolean; /** * <p> * The token for the next set of results. * </p> */ nextToken?: string; /** * <p> * The maximum number of results to return at one time. The default is 25. * </p> */ maxResults?: number; } export namespace ListAuditSuppressionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditSuppressionsRequest): any => ({ ...obj, }); } export interface ListAuditSuppressionsResponse { /** * <p> * List of audit suppressions. * </p> */ suppressions?: AuditSuppression[]; /** * <p> * A token that can be used to retrieve the next set of results, or <code>null</code> if there are no additional results. * </p> */ nextToken?: string; } export namespace ListAuditSuppressionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditSuppressionsResponse): any => ({ ...obj, }); } export interface ListAuditTasksRequest { /** * <p>The beginning of the time period. Audit information is retained for a * limited time (90 days). Requesting a start time prior to what is retained * results in an "InvalidRequestException".</p> */ startTime: Date | undefined; /** * <p>The end of the time period.</p> */ endTime: Date | undefined; /** * <p>A filter to limit the output to the specified type of audit: can be one of * "ON_DEMAND_AUDIT_TASK" or "SCHEDULED__AUDIT_TASK".</p> */ taskType?: AuditTaskType | string; /** * <p>A filter to limit the output to audits with the specified completion * status: can be one of "IN_PROGRESS", "COMPLETED", "FAILED", or "CANCELED".</p> */ taskStatus?: AuditTaskStatus | string; /** * <p>The token for the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time. The default is 25.</p> */ maxResults?: number; } export namespace ListAuditTasksRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditTasksRequest): any => ({ ...obj, }); } export interface ListAuditTasksResponse { /** * <p>The audits that were performed during the specified time period.</p> */ tasks?: AuditTaskMetadata[]; /** * <p>A token that can be used to retrieve the next set of results, or <code>null</code> * if there are no additional results.</p> */ nextToken?: string; } export namespace ListAuditTasksResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListAuditTasksResponse): any => ({ ...obj, }); } export interface ListAuthorizersRequest { /** * <p>The maximum number of results to return at one time.</p> */ pageSize?: number; /** * <p>A marker used to get the next set of results.</p> */ marker?: string; /** * <p>Return the list of authorizers in ascending alphabetical order.</p> */ ascendingOrder?: boolean; /** * <p>The status of the list authorizers request.</p> */ status?: AuthorizerStatus | string; } export namespace ListAuthorizersRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAuthorizersRequest): any => ({ ...obj, }); } export interface ListAuthorizersResponse { /** * <p>The authorizers.</p> */ authorizers?: AuthorizerSummary[]; /** * <p>A marker used to get the next set of results.</p> */ nextMarker?: string; } export namespace ListAuthorizersResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListAuthorizersResponse): any => ({ ...obj, }); } export interface ListBillingGroupsRequest { /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return per request.</p> */ maxResults?: number; /** * <p>Limit the results to billing groups whose names have the given prefix.</p> */ namePrefixFilter?: string; } export namespace ListBillingGroupsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListBillingGroupsRequest): any => ({ ...obj, }); } export interface ListBillingGroupsResponse { /** * <p>The list of billing groups.</p> */ billingGroups?: GroupNameAndArn[]; /** * <p>The token to use to get the next set of results, or <b>null</b> if there are no additional results.</p> */ nextToken?: string; } export namespace ListBillingGroupsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListBillingGroupsResponse): any => ({ ...obj, }); } /** * <p>Input for the ListCACertificates operation.</p> */ export interface ListCACertificatesRequest { /** * <p>The result page size.</p> */ pageSize?: number; /** * <p>The marker for the next set of results.</p> */ marker?: string; /** * <p>Determines the order of the results.</p> */ ascendingOrder?: boolean; } export namespace ListCACertificatesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListCACertificatesRequest): any => ({ ...obj, }); } /** * <p>A CA certificate.</p> */ export interface CACertificate { /** * <p>The ARN of the CA certificate.</p> */ certificateArn?: string; /** * <p>The ID of the CA certificate.</p> */ certificateId?: string; /** * <p>The status of the CA certificate.</p> * <p>The status value REGISTER_INACTIVE is deprecated and should not be used.</p> */ status?: CACertificateStatus | string; /** * <p>The date the CA certificate was created.</p> */ creationDate?: Date; } export namespace CACertificate { /** * @internal */ export const filterSensitiveLog = (obj: CACertificate): any => ({ ...obj, }); } /** * <p>The output from the ListCACertificates operation.</p> */ export interface ListCACertificatesResponse { /** * <p>The CA certificates registered in your Amazon Web Services account.</p> */ certificates?: CACertificate[]; /** * <p>The current position within the list of CA certificates.</p> */ nextMarker?: string; } export namespace ListCACertificatesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListCACertificatesResponse): any => ({ ...obj, }); } /** * <p>The input for the ListCertificates operation.</p> */ export interface ListCertificatesRequest { /** * <p>The result page size.</p> */ pageSize?: number; /** * <p>The marker for the next set of results.</p> */ marker?: string; /** * <p>Specifies the order for results. If True, the results are returned in ascending * order, based on the creation date.</p> */ ascendingOrder?: boolean; } export namespace ListCertificatesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListCertificatesRequest): any => ({ ...obj, }); } /** * <p>Information about a certificate.</p> */ export interface Certificate { /** * <p>The ARN of the certificate.</p> */ certificateArn?: string; /** * <p>The ID of the certificate. (The last part of the certificate ARN contains the * certificate ID.)</p> */ certificateId?: string; /** * <p>The status of the certificate.</p> * <p>The status value REGISTER_INACTIVE is deprecated and should not be used.</p> */ status?: CertificateStatus | string; /** * <p>The mode of the certificate.</p> */ certificateMode?: CertificateMode | string; /** * <p>The date and time the certificate was created.</p> */ creationDate?: Date; } export namespace Certificate { /** * @internal */ export const filterSensitiveLog = (obj: Certificate): any => ({ ...obj, }); } /** * <p>The output of the ListCertificates operation.</p> */ export interface ListCertificatesResponse { /** * <p>The descriptions of the certificates.</p> */ certificates?: Certificate[]; /** * <p>The marker for the next set of results, or null if there are no additional * results.</p> */ nextMarker?: string; } export namespace ListCertificatesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListCertificatesResponse): any => ({ ...obj, }); } /** * <p>The input to the ListCertificatesByCA operation.</p> */ export interface ListCertificatesByCARequest { /** * <p>The ID of the CA certificate. This operation will list all registered device * certificate that were signed by this CA certificate.</p> */ caCertificateId: string | undefined; /** * <p>The result page size.</p> */ pageSize?: number; /** * <p>The marker for the next set of results.</p> */ marker?: string; /** * <p>Specifies the order for results. If True, the results are returned in ascending * order, based on the creation date.</p> */ ascendingOrder?: boolean; } export namespace ListCertificatesByCARequest { /** * @internal */ export const filterSensitiveLog = (obj: ListCertificatesByCARequest): any => ({ ...obj, }); } /** * <p>The output of the ListCertificatesByCA operation.</p> */ export interface ListCertificatesByCAResponse { /** * <p>The device certificates signed by the specified CA certificate.</p> */ certificates?: Certificate[]; /** * <p>The marker for the next set of results, or null if there are no additional * results.</p> */ nextMarker?: string; } export namespace ListCertificatesByCAResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListCertificatesByCAResponse): any => ({ ...obj, }); } export interface ListCustomMetricsRequest { /** * <p> * The token for the next set of results. * </p> */ nextToken?: string; /** * <p> * The maximum number of results to return at one time. The default is 25. * </p> */ maxResults?: number; } export namespace ListCustomMetricsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListCustomMetricsRequest): any => ({ ...obj, }); } export interface ListCustomMetricsResponse { /** * <p> * The name of the custom metric. * </p> */ metricNames?: string[]; /** * <p> * A token that can be used to retrieve the next set of results, * or <code>null</code> if there are no additional results. * </p> */ nextToken?: string; } export namespace ListCustomMetricsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListCustomMetricsResponse): any => ({ ...obj, }); } export interface ListDetectMitigationActionsExecutionsRequest { /** * <p> * The unique identifier of the task. * </p> */ taskId?: string; /** * <p> * The unique identifier of the violation. * </p> */ violationId?: string; /** * <p> * The name of the thing whose mitigation actions are listed. * </p> */ thingName?: string; /** * <p> * A filter to limit results to those found after the specified time. You must * specify either the startTime and endTime or the taskId, but not both. * </p> */ startTime?: Date; /** * <p> * The end of the time period for which ML Detect mitigation actions executions are returned. * </p> */ endTime?: Date; /** * <p> * The maximum number of results to return at one time. The default is 25. * </p> */ maxResults?: number; /** * <p> * The token for the next set of results. * </p> */ nextToken?: string; } export namespace ListDetectMitigationActionsExecutionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListDetectMitigationActionsExecutionsRequest): any => ({ ...obj, }); } export enum DetectMitigationActionExecutionStatus { FAILED = "FAILED", IN_PROGRESS = "IN_PROGRESS", SKIPPED = "SKIPPED", SUCCESSFUL = "SUCCESSFUL", } /** * <p> * Describes which mitigation actions should be executed. * </p> */ export interface DetectMitigationActionExecution { /** * <p> * The unique identifier of the task. * </p> */ taskId?: string; /** * <p> * The unique identifier of the violation. * </p> */ violationId?: string; /** * <p> * The friendly name that uniquely identifies the mitigation action. * </p> */ actionName?: string; /** * <p> * The name of the thing. * </p> */ thingName?: string; /** * <p> * The date a mitigation action was started. * </p> */ executionStartDate?: Date; /** * <p> * The date a mitigation action ended. * </p> */ executionEndDate?: Date; /** * <p> * The status of a mitigation action. * </p> */ status?: DetectMitigationActionExecutionStatus | string; /** * <p> * The error code of a mitigation action. * </p> */ errorCode?: string; /** * <p> * The message of a mitigation action. * </p> */ message?: string; } export namespace DetectMitigationActionExecution { /** * @internal */ export const filterSensitiveLog = (obj: DetectMitigationActionExecution): any => ({ ...obj, }); } export interface ListDetectMitigationActionsExecutionsResponse { /** * <p> * List of actions executions. * </p> */ actionsExecutions?: DetectMitigationActionExecution[]; /** * <p> * A token that can be used to retrieve the next set of results, or <code>null</code> if there are no additional results. * </p> */ nextToken?: string; } export namespace ListDetectMitigationActionsExecutionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListDetectMitigationActionsExecutionsResponse): any => ({ ...obj, }); } export interface ListDetectMitigationActionsTasksRequest { /** * <p>The maximum number of results to return at one time. The default is 25.</p> */ maxResults?: number; /** * <p> * The token for the next set of results. * </p> */ nextToken?: string; /** * <p> * A filter to limit results to those found after the specified time. You must * specify either the startTime and endTime or the taskId, but not both. * </p> */ startTime: Date | undefined; /** * <p> * The end of the time period for which ML Detect mitigation actions tasks are returned. * </p> */ endTime: Date | undefined; } export namespace ListDetectMitigationActionsTasksRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListDetectMitigationActionsTasksRequest): any => ({ ...obj, }); } export interface ListDetectMitigationActionsTasksResponse { /** * <p> * The collection of ML Detect mitigation tasks that matched the filter criteria. * </p> */ tasks?: DetectMitigationActionsTaskSummary[]; /** * <p> * A token that can be used to retrieve the next set of results, or <code>null</code> if there are no additional results. * </p> */ nextToken?: string; } export namespace ListDetectMitigationActionsTasksResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListDetectMitigationActionsTasksResponse): any => ({ ...obj, }); } export interface ListDimensionsRequest { /** * <p>The token for the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to retrieve at one time.</p> */ maxResults?: number; } export namespace ListDimensionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListDimensionsRequest): any => ({ ...obj, }); } export interface ListDimensionsResponse { /** * <p>A list of the names of the defined dimensions. Use <code>DescribeDimension</code> to get details for a dimension.</p> */ dimensionNames?: string[]; /** * <p>A token that can be used to retrieve the next set of results, or <code>null</code> if there are no additional results.</p> */ nextToken?: string; } export namespace ListDimensionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListDimensionsResponse): any => ({ ...obj, }); } export interface ListDomainConfigurationsRequest { /** * <p>The marker for the next set of results.</p> */ marker?: string; /** * <p>The result page size.</p> */ pageSize?: number; /** * <p>The type of service delivered by the endpoint.</p> */ serviceType?: ServiceType | string; } export namespace ListDomainConfigurationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListDomainConfigurationsRequest): any => ({ ...obj, }); } /** * <p>The summary of a domain configuration. A domain configuration specifies custom IoT-specific information about a domain. * A domain configuration can be associated with an Amazon Web Services-managed domain * (for example, dbc123defghijk.iot.us-west-2.amazonaws.com), a customer managed domain, or a default endpoint.</p> * <ul> * <li> * <p>Data</p> * </li> * <li> * <p>Jobs</p> * </li> * <li> * <p>CredentialProvider</p> * </li> * </ul> */ export interface DomainConfigurationSummary { /** * <p>The name of the domain configuration. This value must be unique to a region.</p> */ domainConfigurationName?: string; /** * <p>The ARN of the domain configuration.</p> */ domainConfigurationArn?: string; /** * <p>The type of service delivered by the endpoint.</p> */ serviceType?: ServiceType | string; } export namespace DomainConfigurationSummary { /** * @internal */ export const filterSensitiveLog = (obj: DomainConfigurationSummary): any => ({ ...obj, }); } export interface ListDomainConfigurationsResponse { /** * <p>A list of objects that contain summary information about the user's domain configurations.</p> */ domainConfigurations?: DomainConfigurationSummary[]; /** * <p>The marker for the next set of results.</p> */ nextMarker?: string; } export namespace ListDomainConfigurationsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListDomainConfigurationsResponse): any => ({ ...obj, }); } export interface ListFleetMetricsRequest { /** * <p>To retrieve the next set of results, the <code>nextToken</code> value from a previous response; * otherwise <code>null</code> to receive the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return in this operation.</p> */ maxResults?: number; } export namespace ListFleetMetricsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListFleetMetricsRequest): any => ({ ...obj, }); } /** * <p>The name and ARN of a fleet metric.</p> */ export interface FleetMetricNameAndArn { /** * <p>The fleet metric name.</p> */ metricName?: string; /** * <p>The fleet metric ARN.</p> */ metricArn?: string; } export namespace FleetMetricNameAndArn { /** * @internal */ export const filterSensitiveLog = (obj: FleetMetricNameAndArn): any => ({ ...obj, }); } export interface ListFleetMetricsResponse { /** * <p>The list of fleet metrics objects.</p> */ fleetMetrics?: FleetMetricNameAndArn[]; /** * <p>The token for the next set of results. Will not be returned if the operation has returned * all results.</p> */ nextToken?: string; } export namespace ListFleetMetricsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListFleetMetricsResponse): any => ({ ...obj, }); } export interface ListIndicesRequest { /** * <p>The token used to get the next set of results, or <code>null</code> if there are no additional * results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; } export namespace ListIndicesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListIndicesRequest): any => ({ ...obj, }); } export interface ListIndicesResponse { /** * <p>The index names.</p> */ indexNames?: string[]; /** * <p>The token used to get the next set of results, or <code>null</code> if there are no additional * results.</p> */ nextToken?: string; } export namespace ListIndicesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListIndicesResponse): any => ({ ...obj, }); } export interface ListJobExecutionsForJobRequest { /** * <p>The unique identifier you assigned to this job when it was created.</p> */ jobId: string | undefined; /** * <p>The status of the job.</p> */ status?: JobExecutionStatus | string; /** * <p>The maximum number of results to be returned per request.</p> */ maxResults?: number; /** * <p>The token to retrieve the next set of results.</p> */ nextToken?: string; } export namespace ListJobExecutionsForJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListJobExecutionsForJobRequest): any => ({ ...obj, }); } /** * <p>The job execution summary.</p> */ export interface JobExecutionSummary { /** * <p>The status of the job execution.</p> */ status?: JobExecutionStatus | string; /** * <p>The time, in seconds since the epoch, when the job execution was queued.</p> */ queuedAt?: Date; /** * <p>The time, in seconds since the epoch, when the job execution started.</p> */ startedAt?: Date; /** * <p>The time, in seconds since the epoch, when the job execution was last updated.</p> */ lastUpdatedAt?: Date; /** * <p>A string (consisting of the digits "0" through "9") which identifies this particular job execution on * this particular device. It can be used later in commands which return or update job execution * information.</p> */ executionNumber?: number; } export namespace JobExecutionSummary { /** * @internal */ export const filterSensitiveLog = (obj: JobExecutionSummary): any => ({ ...obj, }); } /** * <p>Contains a summary of information about job executions for a specific job.</p> */ export interface JobExecutionSummaryForJob { /** * <p>The ARN of the thing on which the job execution is running.</p> */ thingArn?: string; /** * <p>Contains a subset of information about a job execution.</p> */ jobExecutionSummary?: JobExecutionSummary; } export namespace JobExecutionSummaryForJob { /** * @internal */ export const filterSensitiveLog = (obj: JobExecutionSummaryForJob): any => ({ ...obj, }); } export interface ListJobExecutionsForJobResponse { /** * <p>A list of job execution summaries.</p> */ executionSummaries?: JobExecutionSummaryForJob[]; /** * <p>The token for the next set of results, or <b>null</b> if there are no * additional results.</p> */ nextToken?: string; } export namespace ListJobExecutionsForJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListJobExecutionsForJobResponse): any => ({ ...obj, }); } export interface ListJobExecutionsForThingRequest { /** * <p>The thing name.</p> */ thingName: string | undefined; /** * <p>An optional filter that lets you search for jobs that have the specified status.</p> */ status?: JobExecutionStatus | string; /** * <p>The namespace used to indicate that a job is a customer-managed job.</p> * <p>When you specify a value for this parameter, Amazon Web Services IoT Core sends jobs notifications to MQTT topics that * contain the value in the following format.</p> * <p> * <code>$aws/things/<i>THING_NAME</i>/jobs/<i>JOB_ID</i>/notify-namespace-<i>NAMESPACE_ID</i>/</code> * </p> * <note> * <p>The <code>namespaceId</code> feature is in public preview.</p> * </note> */ namespaceId?: string; /** * <p>The maximum number of results to be returned per request.</p> */ maxResults?: number; /** * <p>The token to retrieve the next set of results.</p> */ nextToken?: string; } export namespace ListJobExecutionsForThingRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListJobExecutionsForThingRequest): any => ({ ...obj, }); } /** * <p>The job execution summary for a thing.</p> */ export interface JobExecutionSummaryForThing { /** * <p>The unique identifier you assigned to this job when it was created.</p> */ jobId?: string; /** * <p>Contains a subset of information about a job execution.</p> */ jobExecutionSummary?: JobExecutionSummary; } export namespace JobExecutionSummaryForThing { /** * @internal */ export const filterSensitiveLog = (obj: JobExecutionSummaryForThing): any => ({ ...obj, }); } export interface ListJobExecutionsForThingResponse { /** * <p>A list of job execution summaries.</p> */ executionSummaries?: JobExecutionSummaryForThing[]; /** * <p>The token for the next set of results, or <b>null</b> if there are no * additional results.</p> */ nextToken?: string; } export namespace ListJobExecutionsForThingResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListJobExecutionsForThingResponse): any => ({ ...obj, }); } export interface ListJobsRequest { /** * <p>An optional filter that lets you search for jobs that have the specified status.</p> */ status?: JobStatus | string; /** * <p>Specifies whether the job will continue to run (CONTINUOUS), or will be complete after all those things * specified as targets have completed the job (SNAPSHOT). If continuous, the job may also be run on a thing * when a change is detected in a target. For example, a job will run on a thing when the thing is added to a * target group, even after the job was completed by all things originally in the group. </p> */ targetSelection?: TargetSelection | string; /** * <p>The maximum number of results to return per request.</p> */ maxResults?: number; /** * <p>The token to retrieve the next set of results.</p> */ nextToken?: string; /** * <p>A filter that limits the returned jobs to those for the specified group.</p> */ thingGroupName?: string; /** * <p>A filter that limits the returned jobs to those for the specified group.</p> */ thingGroupId?: string; /** * <p>The namespace used to indicate that a job is a customer-managed job.</p> * <p>When you specify a value for this parameter, Amazon Web Services IoT Core sends jobs notifications to MQTT topics that * contain the value in the following format.</p> * <p> * <code>$aws/things/<i>THING_NAME</i>/jobs/<i>JOB_ID</i>/notify-namespace-<i>NAMESPACE_ID</i>/</code> * </p> * <note> * <p>The <code>namespaceId</code> feature is in public preview.</p> * </note> */ namespaceId?: string; } export namespace ListJobsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListJobsRequest): any => ({ ...obj, }); } /** * <p>The job summary.</p> */ export interface JobSummary { /** * <p>The job ARN.</p> */ jobArn?: string; /** * <p>The unique identifier you assigned to this job when it was created.</p> */ jobId?: string; /** * <p>The ID of the thing group.</p> */ thingGroupId?: string; /** * <p>Specifies whether the job will continue to run (CONTINUOUS), or will be complete after all those things * specified as targets have completed the job (SNAPSHOT). If continuous, the job may also be run on a thing * when a change is detected in a target. For example, a job will run on a thing when the thing is added to a * target group, even after the job was completed by all things originally in the group.</p> */ targetSelection?: TargetSelection | string; /** * <p>The job summary status.</p> */ status?: JobStatus | string; /** * <p>The time, in seconds since the epoch, when the job was created.</p> */ createdAt?: Date; /** * <p>The time, in seconds since the epoch, when the job was last updated.</p> */ lastUpdatedAt?: Date; /** * <p>The time, in seconds since the epoch, when the job completed.</p> */ completedAt?: Date; } export namespace JobSummary { /** * @internal */ export const filterSensitiveLog = (obj: JobSummary): any => ({ ...obj, }); } export interface ListJobsResponse { /** * <p>A list of jobs.</p> */ jobs?: JobSummary[]; /** * <p>The token for the next set of results, or <b>null</b> if there are no * additional results.</p> */ nextToken?: string; } export namespace ListJobsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListJobsResponse): any => ({ ...obj, }); } export interface ListJobTemplatesRequest { /** * <p>The maximum number of results to return in the list.</p> */ maxResults?: number; /** * <p>The token to use to return the next set of results in the list.</p> */ nextToken?: string; } export namespace ListJobTemplatesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListJobTemplatesRequest): any => ({ ...obj, }); } /** * <p>An object that contains information about the job template.</p> */ export interface JobTemplateSummary { /** * <p>The ARN of the job template.</p> */ jobTemplateArn?: string; /** * <p>The unique identifier of the job template.</p> */ jobTemplateId?: string; /** * <p>A description of the job template.</p> */ description?: string; /** * <p>The time, in seconds since the epoch, when the job template was created.</p> */ createdAt?: Date; } export namespace JobTemplateSummary { /** * @internal */ export const filterSensitiveLog = (obj: JobTemplateSummary): any => ({ ...obj, }); } export interface ListJobTemplatesResponse { /** * <p>A list of objects that contain information about the job templates.</p> */ jobTemplates?: JobTemplateSummary[]; /** * <p>The token for the next set of results, or <b>null</b> if there are no * additional results.</p> */ nextToken?: string; } export namespace ListJobTemplatesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListJobTemplatesResponse): any => ({ ...obj, }); } export interface ListMitigationActionsRequest { /** * <p>Specify a value to limit the result to mitigation actions with a specific action type.</p> */ actionType?: MitigationActionType | string; /** * <p>The maximum number of results to return at one time. The default is 25.</p> */ maxResults?: number; /** * <p>The token for the next set of results.</p> */ nextToken?: string; } export namespace ListMitigationActionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListMitigationActionsRequest): any => ({ ...obj, }); } /** * <p>Information that identifies a mitigation action. This information is returned by ListMitigationActions.</p> */ export interface MitigationActionIdentifier { /** * <p>The friendly name of the mitigation action.</p> */ actionName?: string; /** * <p>The IAM role ARN used to apply this mitigation action.</p> */ actionArn?: string; /** * <p>The date when this mitigation action was created.</p> */ creationDate?: Date; } export namespace MitigationActionIdentifier { /** * @internal */ export const filterSensitiveLog = (obj: MitigationActionIdentifier): any => ({ ...obj, }); } export interface ListMitigationActionsResponse { /** * <p>A set of actions that matched the specified filter criteria.</p> */ actionIdentifiers?: MitigationActionIdentifier[]; /** * <p>The token for the next set of results.</p> */ nextToken?: string; } export namespace ListMitigationActionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListMitigationActionsResponse): any => ({ ...obj, }); } export interface ListOTAUpdatesRequest { /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; /** * <p>A token used to retrieve the next set of results.</p> */ nextToken?: string; /** * <p>The OTA update job status.</p> */ otaUpdateStatus?: OTAUpdateStatus | string; } export namespace ListOTAUpdatesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListOTAUpdatesRequest): any => ({ ...obj, }); } /** * <p>An OTA update summary.</p> */ export interface OTAUpdateSummary { /** * <p>The OTA update ID.</p> */ otaUpdateId?: string; /** * <p>The OTA update ARN.</p> */ otaUpdateArn?: string; /** * <p>The date when the OTA update was created.</p> */ creationDate?: Date; } export namespace OTAUpdateSummary { /** * @internal */ export const filterSensitiveLog = (obj: OTAUpdateSummary): any => ({ ...obj, }); } export interface ListOTAUpdatesResponse { /** * <p>A list of OTA update jobs.</p> */ otaUpdates?: OTAUpdateSummary[]; /** * <p>A token to use to get the next set of results.</p> */ nextToken?: string; } export namespace ListOTAUpdatesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListOTAUpdatesResponse): any => ({ ...obj, }); } /** * <p>The input to the ListOutgoingCertificates operation.</p> */ export interface ListOutgoingCertificatesRequest { /** * <p>The result page size.</p> */ pageSize?: number; /** * <p>The marker for the next set of results.</p> */ marker?: string; /** * <p>Specifies the order for results. If True, the results are returned in ascending * order, based on the creation date.</p> */ ascendingOrder?: boolean; } export namespace ListOutgoingCertificatesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListOutgoingCertificatesRequest): any => ({ ...obj, }); } /** * <p>A certificate that has been transferred but not yet accepted.</p> */ export interface OutgoingCertificate { /** * <p>The certificate ARN.</p> */ certificateArn?: string; /** * <p>The certificate ID.</p> */ certificateId?: string; /** * <p>The Amazon Web Services account to which the transfer was made.</p> */ transferredTo?: string; /** * <p>The date the transfer was initiated.</p> */ transferDate?: Date; /** * <p>The transfer message.</p> */ transferMessage?: string; /** * <p>The certificate creation date.</p> */ creationDate?: Date; } export namespace OutgoingCertificate { /** * @internal */ export const filterSensitiveLog = (obj: OutgoingCertificate): any => ({ ...obj, }); } /** * <p>The output from the ListOutgoingCertificates operation.</p> */ export interface ListOutgoingCertificatesResponse { /** * <p>The certificates that are being transferred but not yet accepted.</p> */ outgoingCertificates?: OutgoingCertificate[]; /** * <p>The marker for the next set of results.</p> */ nextMarker?: string; } export namespace ListOutgoingCertificatesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListOutgoingCertificatesResponse): any => ({ ...obj, }); } /** * <p>The input for the ListPolicies operation.</p> */ export interface ListPoliciesRequest { /** * <p>The marker for the next set of results.</p> */ marker?: string; /** * <p>The result page size.</p> */ pageSize?: number; /** * <p>Specifies the order for results. If true, the results are returned in ascending * creation order.</p> */ ascendingOrder?: boolean; } export namespace ListPoliciesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPoliciesRequest): any => ({ ...obj, }); } /** * <p>The output from the ListPolicies operation.</p> */ export interface ListPoliciesResponse { /** * <p>The descriptions of the policies.</p> */ policies?: Policy[]; /** * <p>The marker for the next set of results, or null if there are no additional * results.</p> */ nextMarker?: string; } export namespace ListPoliciesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListPoliciesResponse): any => ({ ...obj, }); } /** * <p>The input for the ListPolicyPrincipals operation.</p> */ export interface ListPolicyPrincipalsRequest { /** * <p>The policy name.</p> */ policyName: string | undefined; /** * <p>The marker for the next set of results.</p> */ marker?: string; /** * <p>The result page size.</p> */ pageSize?: number; /** * <p>Specifies the order for results. If true, the results are returned in ascending * creation order.</p> */ ascendingOrder?: boolean; } export namespace ListPolicyPrincipalsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPolicyPrincipalsRequest): any => ({ ...obj, }); } /** * <p>The output from the ListPolicyPrincipals operation.</p> */ export interface ListPolicyPrincipalsResponse { /** * <p>The descriptions of the principals.</p> */ principals?: string[]; /** * <p>The marker for the next set of results, or null if there are no additional * results.</p> */ nextMarker?: string; } export namespace ListPolicyPrincipalsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListPolicyPrincipalsResponse): any => ({ ...obj, }); } /** * <p>The input for the ListPolicyVersions operation.</p> */ export interface ListPolicyVersionsRequest { /** * <p>The policy name.</p> */ policyName: string | undefined; } export namespace ListPolicyVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPolicyVersionsRequest): any => ({ ...obj, }); } /** * <p>Describes a policy version.</p> */ export interface PolicyVersion { /** * <p>The policy version ID.</p> */ versionId?: string; /** * <p>Specifies whether the policy version is the default.</p> */ isDefaultVersion?: boolean; /** * <p>The date and time the policy was created.</p> */ createDate?: Date; } export namespace PolicyVersion { /** * @internal */ export const filterSensitiveLog = (obj: PolicyVersion): any => ({ ...obj, }); } /** * <p>The output from the ListPolicyVersions operation.</p> */ export interface ListPolicyVersionsResponse { /** * <p>The policy versions.</p> */ policyVersions?: PolicyVersion[]; } export namespace ListPolicyVersionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListPolicyVersionsResponse): any => ({ ...obj, }); } /** * <p>The input for the ListPrincipalPolicies operation.</p> */ export interface ListPrincipalPoliciesRequest { /** * <p>The principal. Valid principals are CertificateArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:cert/<i>certificateId</i>), thingGroupArn (arn:aws:iot:<i>region</i>:<i>accountId</i>:thinggroup/<i>groupName</i>) and CognitoId (<i>region</i>:<i>id</i>).</p> */ principal: string | undefined; /** * <p>The marker for the next set of results.</p> */ marker?: string; /** * <p>The result page size.</p> */ pageSize?: number; /** * <p>Specifies the order for results. If true, results are returned in ascending creation * order.</p> */ ascendingOrder?: boolean; } export namespace ListPrincipalPoliciesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPrincipalPoliciesRequest): any => ({ ...obj, }); } /** * <p>The output from the ListPrincipalPolicies operation.</p> */ export interface ListPrincipalPoliciesResponse { /** * <p>The policies.</p> */ policies?: Policy[]; /** * <p>The marker for the next set of results, or null if there are no additional * results.</p> */ nextMarker?: string; } export namespace ListPrincipalPoliciesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListPrincipalPoliciesResponse): any => ({ ...obj, }); } /** * <p>The input for the ListPrincipalThings operation.</p> */ export interface ListPrincipalThingsRequest { /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return in this operation.</p> */ maxResults?: number; /** * <p>The principal.</p> */ principal: string | undefined; } export namespace ListPrincipalThingsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPrincipalThingsRequest): any => ({ ...obj, }); } /** * <p>The output from the ListPrincipalThings operation.</p> */ export interface ListPrincipalThingsResponse { /** * <p>The things.</p> */ things?: string[]; /** * <p>The token to use to get the next set of results, or <b>null</b> if there are no additional results.</p> */ nextToken?: string; } export namespace ListPrincipalThingsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListPrincipalThingsResponse): any => ({ ...obj, }); } export interface ListProvisioningTemplatesRequest { /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; /** * <p>A token to retrieve the next set of results.</p> */ nextToken?: string; } export namespace ListProvisioningTemplatesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListProvisioningTemplatesRequest): any => ({ ...obj, }); } /** * <p>A summary of information about a fleet provisioning template.</p> */ export interface ProvisioningTemplateSummary { /** * <p>The ARN of the fleet provisioning template.</p> */ templateArn?: string; /** * <p>The name of the fleet provisioning template.</p> */ templateName?: string; /** * <p>The description of the fleet provisioning template.</p> */ description?: string; /** * <p>The date when the fleet provisioning template summary was created.</p> */ creationDate?: Date; /** * <p>The date when the fleet provisioning template summary was last modified.</p> */ lastModifiedDate?: Date; /** * <p>True if the fleet provision template is enabled, otherwise false.</p> */ enabled?: boolean; } export namespace ProvisioningTemplateSummary { /** * @internal */ export const filterSensitiveLog = (obj: ProvisioningTemplateSummary): any => ({ ...obj, }); } export interface ListProvisioningTemplatesResponse { /** * <p>A list of fleet provisioning templates</p> */ templates?: ProvisioningTemplateSummary[]; /** * <p>A token to retrieve the next set of results.</p> */ nextToken?: string; } export namespace ListProvisioningTemplatesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListProvisioningTemplatesResponse): any => ({ ...obj, }); } export interface ListProvisioningTemplateVersionsRequest { /** * <p>The name of the fleet provisioning template.</p> */ templateName: string | undefined; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; /** * <p>A token to retrieve the next set of results.</p> */ nextToken?: string; } export namespace ListProvisioningTemplateVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListProvisioningTemplateVersionsRequest): any => ({ ...obj, }); } /** * <p>A summary of information about a fleet provision template version.</p> */ export interface ProvisioningTemplateVersionSummary { /** * <p>The ID of the fleet privisioning template version.</p> */ versionId?: number; /** * <p>The date when the fleet provisioning template version was created</p> */ creationDate?: Date; /** * <p>True if the fleet provisioning template version is the default version, otherwise * false.</p> */ isDefaultVersion?: boolean; } export namespace ProvisioningTemplateVersionSummary { /** * @internal */ export const filterSensitiveLog = (obj: ProvisioningTemplateVersionSummary): any => ({ ...obj, }); } export interface ListProvisioningTemplateVersionsResponse { /** * <p>The list of fleet provisioning template versions.</p> */ versions?: ProvisioningTemplateVersionSummary[]; /** * <p>A token to retrieve the next set of results.</p> */ nextToken?: string; } export namespace ListProvisioningTemplateVersionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListProvisioningTemplateVersionsResponse): any => ({ ...obj, }); } export interface ListRoleAliasesRequest { /** * <p>The maximum number of results to return at one time.</p> */ pageSize?: number; /** * <p>A marker used to get the next set of results.</p> */ marker?: string; /** * <p>Return the list of role aliases in ascending alphabetical order.</p> */ ascendingOrder?: boolean; } export namespace ListRoleAliasesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListRoleAliasesRequest): any => ({ ...obj, }); } export interface ListRoleAliasesResponse { /** * <p>The role aliases.</p> */ roleAliases?: string[]; /** * <p>A marker used to get the next set of results.</p> */ nextMarker?: string; } export namespace ListRoleAliasesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListRoleAliasesResponse): any => ({ ...obj, }); } export interface ListScheduledAuditsRequest { /** * <p>The token for the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time. The default is 25.</p> */ maxResults?: number; } export namespace ListScheduledAuditsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListScheduledAuditsRequest): any => ({ ...obj, }); } /** * <p>Information about the scheduled audit.</p> */ export interface ScheduledAuditMetadata { /** * <p>The name of the scheduled audit.</p> */ scheduledAuditName?: string; /** * <p>The ARN of the scheduled audit.</p> */ scheduledAuditArn?: string; /** * <p>How often the scheduled audit occurs.</p> */ frequency?: AuditFrequency | string; /** * <p>The day of the month on which the scheduled audit is run (if the * <code>frequency</code> is "MONTHLY"). * If days 29-31 are specified, and the month does not have that many * days, the audit takes place on the "LAST" day of the month.</p> */ dayOfMonth?: string; /** * <p>The day of the week on which the scheduled audit is run (if the * <code>frequency</code> is "WEEKLY" or "BIWEEKLY").</p> */ dayOfWeek?: DayOfWeek | string; } export namespace ScheduledAuditMetadata { /** * @internal */ export const filterSensitiveLog = (obj: ScheduledAuditMetadata): any => ({ ...obj, }); } export interface ListScheduledAuditsResponse { /** * <p>The list of scheduled audits.</p> */ scheduledAudits?: ScheduledAuditMetadata[]; /** * <p>A token that can be used to retrieve the next set of results, * or <code>null</code> if there are no additional results.</p> */ nextToken?: string; } export namespace ListScheduledAuditsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListScheduledAuditsResponse): any => ({ ...obj, }); } export interface ListSecurityProfilesRequest { /** * <p>The token for the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; /** * <p>A filter to limit results to the security profiles that use the defined dimension. * Cannot be used with <code>metricName</code> * </p> */ dimensionName?: string; /** * <p> The name of the custom metric. * Cannot be used with <code>dimensionName</code>. </p> */ metricName?: string; } export namespace ListSecurityProfilesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListSecurityProfilesRequest): any => ({ ...obj, }); } /** * <p>Identifying information for a Device Defender security profile.</p> */ export interface SecurityProfileIdentifier { /** * <p>The name you've given to the security profile.</p> */ name: string | undefined; /** * <p>The ARN of the security profile.</p> */ arn: string | undefined; } export namespace SecurityProfileIdentifier { /** * @internal */ export const filterSensitiveLog = (obj: SecurityProfileIdentifier): any => ({ ...obj, }); } export interface ListSecurityProfilesResponse { /** * <p>A list of security profile identifiers (names and ARNs).</p> */ securityProfileIdentifiers?: SecurityProfileIdentifier[]; /** * <p>A token that can be used to retrieve the next set of results, or <code>null</code> if there are no * additional results.</p> */ nextToken?: string; } export namespace ListSecurityProfilesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListSecurityProfilesResponse): any => ({ ...obj, }); } export interface ListSecurityProfilesForTargetRequest { /** * <p>The token for the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; /** * <p>If true, return child groups too.</p> */ recursive?: boolean; /** * <p>The ARN of the target (thing group) whose attached security profiles you want to get.</p> */ securityProfileTargetArn: string | undefined; } export namespace ListSecurityProfilesForTargetRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListSecurityProfilesForTargetRequest): any => ({ ...obj, }); } /** * <p>A target to which an alert is sent when a security profile behavior is * violated.</p> */ export interface SecurityProfileTarget { /** * <p>The ARN of the security profile.</p> */ arn: string | undefined; } export namespace SecurityProfileTarget { /** * @internal */ export const filterSensitiveLog = (obj: SecurityProfileTarget): any => ({ ...obj, }); } /** * <p>Information about a security profile and the target associated with it.</p> */ export interface SecurityProfileTargetMapping { /** * <p>Information that identifies the security profile.</p> */ securityProfileIdentifier?: SecurityProfileIdentifier; /** * <p>Information about the target (thing group) associated with the security profile.</p> */ target?: SecurityProfileTarget; } export namespace SecurityProfileTargetMapping { /** * @internal */ export const filterSensitiveLog = (obj: SecurityProfileTargetMapping): any => ({ ...obj, }); } export interface ListSecurityProfilesForTargetResponse { /** * <p>A list of security profiles and their associated targets.</p> */ securityProfileTargetMappings?: SecurityProfileTargetMapping[]; /** * <p>A token that can be used to retrieve the next set of results, or <code>null</code> if there are no * additional results.</p> */ nextToken?: string; } export namespace ListSecurityProfilesForTargetResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListSecurityProfilesForTargetResponse): any => ({ ...obj, }); } export interface ListStreamsRequest { /** * <p>The maximum number of results to return at a time.</p> */ maxResults?: number; /** * <p>A token used to get the next set of results.</p> */ nextToken?: string; /** * <p>Set to true to return the list of streams in ascending order.</p> */ ascendingOrder?: boolean; } export namespace ListStreamsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListStreamsRequest): any => ({ ...obj, }); } /** * <p>A summary of a stream.</p> */ export interface StreamSummary { /** * <p>The stream ID.</p> */ streamId?: string; /** * <p>The stream ARN.</p> */ streamArn?: string; /** * <p>The stream version.</p> */ streamVersion?: number; /** * <p>A description of the stream.</p> */ description?: string; } export namespace StreamSummary { /** * @internal */ export const filterSensitiveLog = (obj: StreamSummary): any => ({ ...obj, }); } export interface ListStreamsResponse { /** * <p>A list of streams.</p> */ streams?: StreamSummary[]; /** * <p>A token used to get the next set of results.</p> */ nextToken?: string; } export namespace ListStreamsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListStreamsResponse): any => ({ ...obj, }); } export interface ListTagsForResourceRequest { /** * <p>The ARN of the resource.</p> */ resourceArn: string | undefined; /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; } export namespace ListTagsForResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({ ...obj, }); } export interface ListTagsForResourceResponse { /** * <p>The list of tags assigned to the resource.</p> */ tags?: Tag[]; /** * <p>The token to use to get the next set of results, or <b>null</b> if there are no additional results.</p> */ nextToken?: string; } export namespace ListTagsForResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({ ...obj, }); } export interface ListTargetsForPolicyRequest { /** * <p>The policy name.</p> */ policyName: string | undefined; /** * <p>A marker used to get the next set of results.</p> */ marker?: string; /** * <p>The maximum number of results to return at one time.</p> */ pageSize?: number; } export namespace ListTargetsForPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTargetsForPolicyRequest): any => ({ ...obj, }); } export interface ListTargetsForPolicyResponse { /** * <p>The policy targets.</p> */ targets?: string[]; /** * <p>A marker used to get the next set of results.</p> */ nextMarker?: string; } export namespace ListTargetsForPolicyResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTargetsForPolicyResponse): any => ({ ...obj, }); } export interface ListTargetsForSecurityProfileRequest { /** * <p>The security profile.</p> */ securityProfileName: string | undefined; /** * <p>The token for the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; } export namespace ListTargetsForSecurityProfileRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTargetsForSecurityProfileRequest): any => ({ ...obj, }); } export interface ListTargetsForSecurityProfileResponse { /** * <p>The thing groups to which the security profile is attached.</p> */ securityProfileTargets?: SecurityProfileTarget[]; /** * <p>A token that can be used to retrieve the next set of results, or <code>null</code> if there are no * additional results.</p> */ nextToken?: string; } export namespace ListTargetsForSecurityProfileResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTargetsForSecurityProfileResponse): any => ({ ...obj, }); } export interface ListThingGroupsRequest { /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; /** * <p>A filter that limits the results to those with the specified parent group.</p> */ parentGroup?: string; /** * <p>A filter that limits the results to those with the specified name prefix.</p> */ namePrefixFilter?: string; /** * <p>If true, return child groups as well.</p> */ recursive?: boolean; } export namespace ListThingGroupsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListThingGroupsRequest): any => ({ ...obj, }); } export interface ListThingGroupsResponse { /** * <p>The thing groups.</p> */ thingGroups?: GroupNameAndArn[]; /** * <p>The token to use to get the next set of results. Will not be returned if operation has returned all results.</p> */ nextToken?: string; } export namespace ListThingGroupsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListThingGroupsResponse): any => ({ ...obj, }); } export interface ListThingGroupsForThingRequest { /** * <p>The thing name.</p> */ thingName: string | undefined; /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; } export namespace ListThingGroupsForThingRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListThingGroupsForThingRequest): any => ({ ...obj, }); } export interface ListThingGroupsForThingResponse { /** * <p>The thing groups.</p> */ thingGroups?: GroupNameAndArn[]; /** * <p>The token to use to get the next set of results, or <b>null</b> if there are no additional results.</p> */ nextToken?: string; } export namespace ListThingGroupsForThingResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListThingGroupsForThingResponse): any => ({ ...obj, }); } /** * <p>The input for the ListThingPrincipal operation.</p> */ export interface ListThingPrincipalsRequest { /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return in this operation.</p> */ maxResults?: number; /** * <p>The name of the thing.</p> */ thingName: string | undefined; } export namespace ListThingPrincipalsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListThingPrincipalsRequest): any => ({ ...obj, }); } /** * <p>The output from the ListThingPrincipals operation.</p> */ export interface ListThingPrincipalsResponse { /** * <p>The principals associated with the thing.</p> */ principals?: string[]; /** * <p>The token to use to get the next set of results, or <b>null</b> if there are no additional results.</p> */ nextToken?: string; } export namespace ListThingPrincipalsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListThingPrincipalsResponse): any => ({ ...obj, }); } export enum ReportType { ERRORS = "ERRORS", RESULTS = "RESULTS", } export interface ListThingRegistrationTaskReportsRequest { /** * <p>The id of the task.</p> */ taskId: string | undefined; /** * <p>The type of task report.</p> */ reportType: ReportType | string | undefined; /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return per request.</p> */ maxResults?: number; } export namespace ListThingRegistrationTaskReportsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListThingRegistrationTaskReportsRequest): any => ({ ...obj, }); } export interface ListThingRegistrationTaskReportsResponse { /** * <p>Links to the task resources.</p> */ resourceLinks?: string[]; /** * <p>The type of task report.</p> */ reportType?: ReportType | string; /** * <p>The token to use to get the next set of results, or <b>null</b> if there are no additional results.</p> */ nextToken?: string; } export namespace ListThingRegistrationTaskReportsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListThingRegistrationTaskReportsResponse): any => ({ ...obj, }); } export interface ListThingRegistrationTasksRequest { /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; /** * <p>The status of the bulk thing provisioning task.</p> */ status?: Status | string; } export namespace ListThingRegistrationTasksRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListThingRegistrationTasksRequest): any => ({ ...obj, }); } export interface ListThingRegistrationTasksResponse { /** * <p>A list of bulk thing provisioning task IDs.</p> */ taskIds?: string[]; /** * <p>The token to use to get the next set of results, or <b>null</b> if there are no additional results.</p> */ nextToken?: string; } export namespace ListThingRegistrationTasksResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListThingRegistrationTasksResponse): any => ({ ...obj, }); } /** * <p>The input for the ListThings operation.</p> */ export interface ListThingsRequest { /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return in this operation.</p> */ maxResults?: number; /** * <p>The attribute name used to search for things.</p> */ attributeName?: string; /** * <p>The attribute value used to search for things.</p> */ attributeValue?: string; /** * <p>The name of the thing type used to search for things.</p> */ thingTypeName?: string; /** * <p>When <code>true</code>, the action returns the thing resources with attribute values * that start with the <code>attributeValue</code> provided.</p> * <p>When <code>false</code>, or not present, the action returns only the thing * resources with attribute values that match the entire <code>attributeValue</code> * provided. </p> */ usePrefixAttributeValue?: boolean; } export namespace ListThingsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListThingsRequest): any => ({ ...obj, }); } /** * <p>The properties of the thing, including thing name, thing type name, and a list of thing * attributes.</p> */ export interface ThingAttribute { /** * <p>The name of the thing.</p> */ thingName?: string; /** * <p>The name of the thing type, if the thing has been associated with a type.</p> */ thingTypeName?: string; /** * <p>The thing ARN.</p> */ thingArn?: string; /** * <p>A list of thing attributes which are name-value pairs.</p> */ attributes?: { [key: string]: string }; /** * <p>The version of the thing record in the registry.</p> */ version?: number; } export namespace ThingAttribute { /** * @internal */ export const filterSensitiveLog = (obj: ThingAttribute): any => ({ ...obj, }); } /** * <p>The output from the ListThings operation.</p> */ export interface ListThingsResponse { /** * <p>The things.</p> */ things?: ThingAttribute[]; /** * <p>The token to use to get the next set of results. Will not be returned if operation has returned all results.</p> */ nextToken?: string; } export namespace ListThingsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListThingsResponse): any => ({ ...obj, }); } export interface ListThingsInBillingGroupRequest { /** * <p>The name of the billing group.</p> */ billingGroupName: string | undefined; /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return per request.</p> */ maxResults?: number; } export namespace ListThingsInBillingGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListThingsInBillingGroupRequest): any => ({ ...obj, }); } export interface ListThingsInBillingGroupResponse { /** * <p>A list of things in the billing group.</p> */ things?: string[]; /** * <p>The token to use to get the next set of results. Will not be returned if operation has returned all results.</p> */ nextToken?: string; } export namespace ListThingsInBillingGroupResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListThingsInBillingGroupResponse): any => ({ ...obj, }); } export interface ListThingsInThingGroupRequest { /** * <p>The thing group name.</p> */ thingGroupName: string | undefined; /** * <p>When true, list things in this thing group and in all child groups as * well.</p> */ recursive?: boolean; /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; } export namespace ListThingsInThingGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListThingsInThingGroupRequest): any => ({ ...obj, }); } export interface ListThingsInThingGroupResponse { /** * <p>The things in the specified thing group.</p> */ things?: string[]; /** * <p>The token to use to get the next set of results, or <b>null</b> if there are no additional results.</p> */ nextToken?: string; } export namespace ListThingsInThingGroupResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListThingsInThingGroupResponse): any => ({ ...obj, }); } /** * <p>The input for the ListThingTypes operation.</p> */ export interface ListThingTypesRequest { /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return in this operation.</p> */ maxResults?: number; /** * <p>The name of the thing type.</p> */ thingTypeName?: string; } export namespace ListThingTypesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListThingTypesRequest): any => ({ ...obj, }); }
the_stack
import * as coreClient from "@azure/core-client"; /** The response of the List Available Clusters operation. */ export interface AvailableClustersList { /** The count of readily available and pre-provisioned Event Hubs Clusters per region. */ value?: AvailableCluster[]; } /** Pre-provisioned and readily available Event Hubs Cluster count per region. */ export interface AvailableCluster { /** Location fo the Available Cluster */ location?: string; } /** Error response indicates Event Hub service is not able to process the incoming request. The reason is provided in the error message. */ export interface ErrorResponse { /** The error object. */ error?: ErrorDetail; } /** The error detail. */ export interface ErrorDetail { /** * The error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * The error message. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** * The error target. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly target?: string; /** * The error details. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: ErrorDetail[]; /** * The error additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly info?: Record<string, unknown>; } /** The response of the List Event Hubs Clusters operation. */ export interface ClusterListResult { /** The Event Hubs Clusters present in the List Event Hubs operation results. */ value?: Cluster[]; /** Link to the next set of results. Empty unless the value parameter contains an incomplete list of Event Hubs Clusters. */ nextLink?: string; } /** SKU parameters particular to a cluster instance. */ export interface ClusterSku { /** Name of this SKU. */ name: ClusterSkuName; /** The quantity of Event Hubs Cluster Capacity Units contained in this cluster. */ capacity?: number; } /** Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** The identity that created the resource. */ createdBy?: string; /** The type of identity that created the resource. */ createdByType?: CreatedByType; /** The timestamp of resource creation (UTC). */ createdAt?: Date; /** The identity that last modified the resource. */ lastModifiedBy?: string; /** The type of identity that last modified the resource. */ lastModifiedByType?: CreatedByType; /** The type of identity that last modified the resource. */ lastModifiedAt?: Date; } /** Common fields that are returned in the response for all Azure Resource Manager resources */ export interface Resource { /** * Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the resource * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; } /** The response of the List Namespace IDs operation */ export interface EHNamespaceIdListResult { /** Result of the List Namespace IDs operation */ value?: EHNamespaceIdContainer[]; } /** The full ARM ID of an Event Hubs Namespace */ export interface EHNamespaceIdContainer { /** id parameter */ id?: string; } /** Contains all settings for the cluster. */ export interface ClusterQuotaConfigurationProperties { /** All possible Cluster settings - a collection of key/value paired settings which apply to quotas and configurations imposed on the cluster. */ settings?: { [propertyName: string]: string }; } /** The response of the List Namespace operation */ export interface EHNamespaceListResult { /** Result of the List Namespace operation */ value?: EHNamespace[]; /** Link to the next set of results. Not empty if Value contains incomplete list of namespaces. */ nextLink?: string; } /** SKU parameters supplied to the create namespace operation */ export interface Sku { /** Name of this SKU. */ name: SkuName; /** The billing tier of this particular SKU. */ tier?: SkuTier; /** The Event Hubs throughput units for Basic or Standard tiers, where value should be 0 to 20 throughput units. The Event Hubs premium units for Premium tier, where value should be 0 to 10 premium units. */ capacity?: number; } /** Properties to configure Identity for Bring your Own Keys */ export interface Identity { /** * ObjectId from the KeyVault * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly principalId?: string; /** * TenantId from the KeyVault * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly tenantId?: string; /** Type of managed service identity. */ type?: ManagedServiceIdentityType; /** Properties for User Assigned Identities */ userAssignedIdentities?: { [propertyName: string]: UserAssignedIdentity }; } /** Recognized Dictionary value. */ export interface UserAssignedIdentity { /** * Principal Id of user assigned identity * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly principalId?: string; /** * Client Id of user assigned identity * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly clientId?: string; } /** Properties to configure Encryption */ export interface Encryption { /** Properties of KeyVault */ keyVaultProperties?: KeyVaultProperties[]; /** Enumerates the possible value of keySource for Encryption */ keySource?: "Microsoft.KeyVault"; /** Enable Infrastructure Encryption (Double Encryption) */ requireInfrastructureEncryption?: boolean; } /** Properties to configure keyVault Properties */ export interface KeyVaultProperties { /** Name of the Key from KeyVault */ keyName?: string; /** Uri of KeyVault */ keyVaultUri?: string; /** Key Version */ keyVersion?: string; identity?: UserAssignedIdentityProperties; } export interface UserAssignedIdentityProperties { /** ARM ID of user Identity selected for encryption */ userAssignedIdentity?: string; } /** PrivateEndpoint information. */ export interface PrivateEndpoint { /** The ARM identifier for Private Endpoint. */ id?: string; } /** ConnectionState information. */ export interface ConnectionState { /** Status of the connection. */ status?: PrivateLinkConnectionStatus; /** Description of the connection state. */ description?: string; } /** Common fields that are returned in the response for all Azure Resource Manager resources */ export interface ProxyResource { /** * Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the resource * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the resource. E.g. "Microsoft.EventHub/Namespaces" or "Microsoft.EventHub/Namespaces/EventHubs" * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The geo-location where the resource lives * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly location?: string; } /** Result of the list of all private endpoint connections operation. */ export interface PrivateEndpointConnectionListResult { /** A collection of private endpoint connection resources. */ value?: PrivateEndpointConnection[]; /** A link for the next page of private endpoint connection resources. */ nextLink?: string; } /** Result of the List private link resources operation. */ export interface PrivateLinkResourcesListResult { /** A collection of private link resources */ value?: PrivateLinkResource[]; /** A link for the next page of private link resources. */ nextLink?: string; } /** Information of the private link resource. */ export interface PrivateLinkResource { /** Fully qualified identifier of the resource. */ id?: string; /** Name of the resource */ name?: string; /** Type of the resource */ type?: string; /** The private link resource group id. */ groupId?: string; /** The private link resource required member names. */ requiredMembers?: string[]; /** The private link resource Private link DNS zone name. */ requiredZoneNames?: string[]; } /** Result of the request to list Event Hub operations. It contains a list of operations and a URL link to get the next set of results. */ export interface OperationListResult { /** * List of Event Hub operations supported by the Microsoft.EventHub resource provider. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Operation[]; /** * URL to get the next set of operation list results if there are any. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** A Event Hub REST API operation */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** Indicates whether the operation is a data action */ isDataAction?: boolean; /** Display of the operation */ display?: OperationDisplay; /** Origin of the operation */ origin?: string; /** Properties of the operation */ properties?: Record<string, unknown>; } /** Operation display payload */ export interface OperationDisplay { /** * Resource provider of the operation * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provider?: string; /** * Resource of the operation * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resource?: string; /** * Localized friendly name for the operation * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly operation?: string; /** * Localized friendly description for the operation * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly description?: string; } /** The result of the List EventHubs operation. */ export interface EventHubListResult { /** Result of the List EventHubs operation. */ value?: Eventhub[]; /** Link to the next set of results. Not empty if Value contains incomplete list of EventHubs. */ nextLink?: string; } /** Properties to configure capture description for eventhub */ export interface CaptureDescription { /** A value that indicates whether capture description is enabled. */ enabled?: boolean; /** Enumerates the possible values for the encoding format of capture description. Note: 'AvroDeflate' will be deprecated in New API Version */ encoding?: EncodingCaptureDescription; /** The time window allows you to set the frequency with which the capture to Azure Blobs will happen, value should between 60 to 900 seconds */ intervalInSeconds?: number; /** The size window defines the amount of data built up in your Event Hub before an capture operation, value should be between 10485760 to 524288000 bytes */ sizeLimitInBytes?: number; /** Properties of Destination where capture will be stored. (Storage Account, Blob Names) */ destination?: Destination; /** A value that indicates whether to Skip Empty Archives */ skipEmptyArchives?: boolean; } /** Capture storage details for capture description */ export interface Destination { /** Name for capture destination */ name?: string; /** Resource id of the storage account to be used to create the blobs */ storageAccountResourceId?: string; /** Blob container Name */ blobContainer?: string; /** Blob naming convention for archive, e.g. {Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}. Here all the parameters (Namespace,EventHub .. etc) are mandatory irrespective of order */ archiveNameFormat?: string; /** Subscription Id of Azure Data Lake Store */ dataLakeSubscriptionId?: string; /** The Azure Data Lake Store name for the captured events */ dataLakeAccountName?: string; /** The destination folder path for the captured events */ dataLakeFolderPath?: string; } /** Parameter supplied to check Namespace name availability operation */ export interface CheckNameAvailabilityParameter { /** Name to check the namespace name availability */ name: string; } /** The Result of the CheckNameAvailability operation */ export interface CheckNameAvailabilityResult { /** * The detailed info regarding the reason associated with the Namespace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** Value indicating Namespace is availability, true if the Namespace is available; otherwise, false. */ nameAvailable?: boolean; /** The reason for unavailability of a Namespace. */ reason?: UnavailableReason; } /** The result of the List Alias(Disaster Recovery configuration) operation. */ export interface ArmDisasterRecoveryListResult { /** List of Alias(Disaster Recovery configurations) */ value?: ArmDisasterRecovery[]; /** * Link to the next set of results. Not empty if Value contains incomplete list of Alias(Disaster Recovery configuration) * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The response from the List namespace operation. */ export interface NWRuleSetVirtualNetworkRules { /** Subnet properties */ subnet?: Subnet; /** Value that indicates whether to ignore missing Vnet Service Endpoint */ ignoreMissingVnetServiceEndpoint?: boolean; } /** Properties supplied for Subnet */ export interface Subnet { /** Resource ID of Virtual Network Subnet */ id?: string; } /** The response from the List namespace operation. */ export interface NWRuleSetIpRules { /** IP Mask */ ipMask?: string; /** The IP Filter Action */ action?: NetworkRuleIPAction; } /** The response of the List NetworkRuleSet operation */ export interface NetworkRuleSetListResult { /** Result of the List NetworkRuleSet operation */ value?: NetworkRuleSet[]; /** Link to the next set of results. Not empty if Value contains incomplete list of NetworkRuleSet. */ nextLink?: string; } /** The response from the List namespace operation. */ export interface AuthorizationRuleListResult { /** Result of the List Authorization Rules operation. */ value?: AuthorizationRule[]; /** Link to the next set of results. Not empty if Value contains an incomplete list of Authorization Rules */ nextLink?: string; } /** Namespace/EventHub Connection String */ export interface AccessKeys { /** * Primary connection string of the created namespace AuthorizationRule. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly primaryConnectionString?: string; /** * Secondary connection string of the created namespace AuthorizationRule. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly secondaryConnectionString?: string; /** * Primary connection string of the alias if GEO DR is enabled * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly aliasPrimaryConnectionString?: string; /** * Secondary connection string of the alias if GEO DR is enabled * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly aliasSecondaryConnectionString?: string; /** * A base64-encoded 256-bit primary key for signing and validating the SAS token. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly primaryKey?: string; /** * A base64-encoded 256-bit primary key for signing and validating the SAS token. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly secondaryKey?: string; /** * A string that describes the AuthorizationRule. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly keyName?: string; } /** Parameters supplied to the Regenerate Authorization Rule operation, specifies which key needs to be reset. */ export interface RegenerateAccessKeyParameters { /** The access key to regenerate. */ keyType: KeyType; /** Optional, if the key value provided, is set for KeyType or autogenerated Key value set for keyType */ key?: string; } /** The result to the List Consumer Group operation. */ export interface ConsumerGroupListResult { /** Result of the List Consumer Group operation. */ value?: ConsumerGroup[]; /** Link to the next set of results. Not empty if Value contains incomplete list of Consumer Group */ nextLink?: string; } /** The result of the List SchemaGroup operation. */ export interface SchemaGroupListResult { /** Result of the List SchemaGroups operation. */ value?: SchemaGroup[]; /** Link to the next set of results. Not empty if Value contains incomplete list of Schema Groups. */ nextLink?: string; } /** Definition of resource. */ export type TrackedResource = Resource & { /** Resource location. */ location?: string; /** Resource tags. */ tags?: { [propertyName: string]: string }; }; /** Properties of the PrivateEndpointConnection. */ export type PrivateEndpointConnection = ProxyResource & { /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** The Private Endpoint resource for this Connection. */ privateEndpoint?: PrivateEndpoint; /** Details about the state of the connection. */ privateLinkServiceConnectionState?: ConnectionState; /** Provisioning state of the Private Endpoint Connection. */ provisioningState?: EndPointProvisioningState; }; /** Single item in List or Get Event Hub operation */ export type Eventhub = ProxyResource & { /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * Current number of shards on the Event Hub. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly partitionIds?: string[]; /** * Exact time the Event Hub was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdAt?: Date; /** * The exact time the message was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedAt?: Date; /** Number of days to retain the events for this Event Hub, value should be 1 to 7 days */ messageRetentionInDays?: number; /** Number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. */ partitionCount?: number; /** Enumerates the possible values for the status of the Event Hub. */ status?: EntityStatus; /** Properties of capture description */ captureDescription?: CaptureDescription; }; /** Single item in List or Get Alias(Disaster Recovery configuration) operation */ export type ArmDisasterRecovery = ProxyResource & { /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * Provisioning state of the Alias(Disaster Recovery configuration) - possible values 'Accepted' or 'Succeeded' or 'Failed' * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ProvisioningStateDR; /** ARM Id of the Primary/Secondary eventhub namespace name, which is part of GEO DR pairing */ partnerNamespace?: string; /** Alternate name specified when alias and namespace names are same. */ alternateName?: string; /** * role of namespace in GEO DR - possible values 'Primary' or 'PrimaryNotReplicating' or 'Secondary' * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly role?: RoleDisasterRecovery; /** * Number of entities pending to be replicated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly pendingReplicationOperationsCount?: number; }; /** Description of topic resource. */ export type NetworkRuleSet = ProxyResource & { /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** Value that indicates whether Trusted Service Access is Enabled or not. */ trustedServiceAccessEnabled?: boolean; /** Default Action for Network Rule Set */ defaultAction?: DefaultAction; /** List VirtualNetwork Rules */ virtualNetworkRules?: NWRuleSetVirtualNetworkRules[]; /** List of IpRules */ ipRules?: NWRuleSetIpRules[]; /** This determines if traffic is allowed over public network. By default it is enabled. */ publicNetworkAccess?: PublicNetworkAccessFlag; }; /** Single item in a List or Get AuthorizationRule operation */ export type AuthorizationRule = ProxyResource & { /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** The rights associated with the rule. */ rights?: AccessRights[]; }; /** Single item in List or Get Consumer group operation */ export type ConsumerGroup = ProxyResource & { /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * Exact time the message was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdAt?: Date; /** * The exact time the message was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedAt?: Date; /** User Metadata is a placeholder to store user-defined string data with maximum length 1024. e.g. it can be used to store descriptive data, such as list of teams and their contact information also user-defined configuration settings can be stored. */ userMetadata?: string; }; /** Single item in List or Get Schema Group operation */ export type SchemaGroup = ProxyResource & { /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * Exact time the Schema Group was updated * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedAtUtc?: Date; /** * Exact time the Schema Group was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdAtUtc?: Date; /** * The ETag value. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly eTag?: string; /** dictionary object for SchemaGroup group properties */ groupProperties?: { [propertyName: string]: string }; schemaCompatibility?: SchemaCompatibility; schemaType?: SchemaType; }; /** Single Event Hubs Cluster resource in List or Get operations. */ export type Cluster = TrackedResource & { /** Properties of the cluster SKU. */ sku?: ClusterSku; /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * The UTC time when the Event Hubs Cluster was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdAt?: string; /** * The UTC time when the Event Hubs Cluster was last updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedAt?: string; /** * The metric ID of the cluster resource. Provided by the service and not modifiable by the user. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly metricId?: string; /** * Status of the Cluster resource * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly status?: string; }; /** Single Namespace item in List or Get Operation */ export type EHNamespace = TrackedResource & { /** Properties of sku resource */ sku?: Sku; /** Properties of BYOK Identity description */ identity?: Identity; /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * Provisioning state of the Namespace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** * Status of the Namespace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly status?: string; /** * The time the Namespace was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdAt?: Date; /** * The time the Namespace was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedAt?: Date; /** * Endpoint you can use to perform Service Bus operations. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly serviceBusEndpoint?: string; /** Cluster ARM ID of the Namespace. */ clusterArmId?: string; /** * Identifier for Azure Insights metrics. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly metricId?: string; /** Value that indicates whether AutoInflate is enabled for eventhub namespace. */ isAutoInflateEnabled?: boolean; /** Upper limit of throughput units when AutoInflate is enabled, value should be within 0 to 20 throughput units. ( '0' if AutoInflateEnabled = true) */ maximumThroughputUnits?: number; /** Value that indicates whether Kafka is enabled for eventhub namespace. */ kafkaEnabled?: boolean; /** Enabling this property creates a Standard Event Hubs Namespace in regions supported availability zones. */ zoneRedundant?: boolean; /** Properties of BYOK Encryption description */ encryption?: Encryption; /** List of private endpoint connections. */ privateEndpointConnections?: PrivateEndpointConnection[]; /** This property disables SAS authentication for the Event Hubs namespace. */ disableLocalAuth?: boolean; /** Alternate name specified when alias and namespace names are same. */ alternateName?: string; }; /** Known values of {@link ClusterSkuName} that the service accepts. */ export enum KnownClusterSkuName { Dedicated = "Dedicated" } /** * Defines values for ClusterSkuName. \ * {@link KnownClusterSkuName} can be used interchangeably with ClusterSkuName, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Dedicated** */ export type ClusterSkuName = string; /** Known values of {@link CreatedByType} that the service accepts. */ export enum KnownCreatedByType { User = "User", Application = "Application", ManagedIdentity = "ManagedIdentity", Key = "Key" } /** * Defines values for CreatedByType. \ * {@link KnownCreatedByType} can be used interchangeably with CreatedByType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **User** \ * **Application** \ * **ManagedIdentity** \ * **Key** */ export type CreatedByType = string; /** Known values of {@link SkuName} that the service accepts. */ export enum KnownSkuName { Basic = "Basic", Standard = "Standard", Premium = "Premium" } /** * Defines values for SkuName. \ * {@link KnownSkuName} can be used interchangeably with SkuName, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Basic** \ * **Standard** \ * **Premium** */ export type SkuName = string; /** Known values of {@link SkuTier} that the service accepts. */ export enum KnownSkuTier { Basic = "Basic", Standard = "Standard", Premium = "Premium" } /** * Defines values for SkuTier. \ * {@link KnownSkuTier} can be used interchangeably with SkuTier, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Basic** \ * **Standard** \ * **Premium** */ export type SkuTier = string; /** Known values of {@link PrivateLinkConnectionStatus} that the service accepts. */ export enum KnownPrivateLinkConnectionStatus { Pending = "Pending", Approved = "Approved", Rejected = "Rejected", Disconnected = "Disconnected" } /** * Defines values for PrivateLinkConnectionStatus. \ * {@link KnownPrivateLinkConnectionStatus} can be used interchangeably with PrivateLinkConnectionStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pending** \ * **Approved** \ * **Rejected** \ * **Disconnected** */ export type PrivateLinkConnectionStatus = string; /** Known values of {@link EndPointProvisioningState} that the service accepts. */ export enum KnownEndPointProvisioningState { Creating = "Creating", Updating = "Updating", Deleting = "Deleting", Succeeded = "Succeeded", Canceled = "Canceled", Failed = "Failed" } /** * Defines values for EndPointProvisioningState. \ * {@link KnownEndPointProvisioningState} can be used interchangeably with EndPointProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Updating** \ * **Deleting** \ * **Succeeded** \ * **Canceled** \ * **Failed** */ export type EndPointProvisioningState = string; /** Known values of {@link DefaultAction} that the service accepts. */ export enum KnownDefaultAction { Allow = "Allow", Deny = "Deny" } /** * Defines values for DefaultAction. \ * {@link KnownDefaultAction} can be used interchangeably with DefaultAction, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Allow** \ * **Deny** */ export type DefaultAction = string; /** Known values of {@link NetworkRuleIPAction} that the service accepts. */ export enum KnownNetworkRuleIPAction { Allow = "Allow" } /** * Defines values for NetworkRuleIPAction. \ * {@link KnownNetworkRuleIPAction} can be used interchangeably with NetworkRuleIPAction, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Allow** */ export type NetworkRuleIPAction = string; /** Known values of {@link PublicNetworkAccessFlag} that the service accepts. */ export enum KnownPublicNetworkAccessFlag { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for PublicNetworkAccessFlag. \ * {@link KnownPublicNetworkAccessFlag} can be used interchangeably with PublicNetworkAccessFlag, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type PublicNetworkAccessFlag = string; /** Known values of {@link AccessRights} that the service accepts. */ export enum KnownAccessRights { Manage = "Manage", Send = "Send", Listen = "Listen" } /** * Defines values for AccessRights. \ * {@link KnownAccessRights} can be used interchangeably with AccessRights, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Manage** \ * **Send** \ * **Listen** */ export type AccessRights = string; /** Known values of {@link KeyType} that the service accepts. */ export enum KnownKeyType { PrimaryKey = "PrimaryKey", SecondaryKey = "SecondaryKey" } /** * Defines values for KeyType. \ * {@link KnownKeyType} can be used interchangeably with KeyType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **PrimaryKey** \ * **SecondaryKey** */ export type KeyType = string; /** Known values of {@link SchemaCompatibility} that the service accepts. */ export enum KnownSchemaCompatibility { None = "None", Backward = "Backward", Forward = "Forward" } /** * Defines values for SchemaCompatibility. \ * {@link KnownSchemaCompatibility} can be used interchangeably with SchemaCompatibility, * this enum contains the known values that the service supports. * ### Known values supported by the service * **None** \ * **Backward** \ * **Forward** */ export type SchemaCompatibility = string; /** Known values of {@link SchemaType} that the service accepts. */ export enum KnownSchemaType { Unknown = "Unknown", Avro = "Avro" } /** * Defines values for SchemaType. \ * {@link KnownSchemaType} can be used interchangeably with SchemaType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Unknown** \ * **Avro** */ export type SchemaType = string; /** Defines values for ManagedServiceIdentityType. */ export type ManagedServiceIdentityType = | "SystemAssigned" | "UserAssigned" | "SystemAssigned, UserAssigned" | "None"; /** Defines values for EntityStatus. */ export type EntityStatus = | "Active" | "Disabled" | "Restoring" | "SendDisabled" | "ReceiveDisabled" | "Creating" | "Deleting" | "Renaming" | "Unknown"; /** Defines values for EncodingCaptureDescription. */ export type EncodingCaptureDescription = "Avro" | "AvroDeflate"; /** Defines values for UnavailableReason. */ export type UnavailableReason = | "None" | "InvalidName" | "SubscriptionIsDisabled" | "NameInUse" | "NameInLockdown" | "TooManyNamespaceInCurrentSubscription"; /** Defines values for ProvisioningStateDR. */ export type ProvisioningStateDR = "Accepted" | "Succeeded" | "Failed"; /** Defines values for RoleDisasterRecovery. */ export type RoleDisasterRecovery = | "Primary" | "PrimaryNotReplicating" | "Secondary"; /** Optional parameters. */ export interface ClustersListAvailableClusterRegionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAvailableClusterRegion operation. */ export type ClustersListAvailableClusterRegionResponse = AvailableClustersList; /** Optional parameters. */ export interface ClustersListBySubscriptionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscription operation. */ export type ClustersListBySubscriptionResponse = ClusterListResult; /** Optional parameters. */ export interface ClustersListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type ClustersListByResourceGroupResponse = ClusterListResult; /** Optional parameters. */ export interface ClustersGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ClustersGetResponse = Cluster; /** Optional parameters. */ export interface ClustersCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type ClustersCreateOrUpdateResponse = Cluster; /** Optional parameters. */ export interface ClustersUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type ClustersUpdateResponse = Cluster; /** Optional parameters. */ export interface ClustersDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ClustersListNamespacesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNamespaces operation. */ export type ClustersListNamespacesResponse = EHNamespaceIdListResult; /** Optional parameters. */ export interface ClustersListBySubscriptionNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscriptionNext operation. */ export type ClustersListBySubscriptionNextResponse = ClusterListResult; /** Optional parameters. */ export interface ClustersListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type ClustersListByResourceGroupNextResponse = ClusterListResult; /** Optional parameters. */ export interface ConfigurationPatchOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the patch operation. */ export type ConfigurationPatchResponse = ClusterQuotaConfigurationProperties; /** Optional parameters. */ export interface ConfigurationGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ConfigurationGetResponse = ClusterQuotaConfigurationProperties; /** Optional parameters. */ export interface NamespacesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type NamespacesListResponse = EHNamespaceListResult; /** Optional parameters. */ export interface NamespacesListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type NamespacesListByResourceGroupResponse = EHNamespaceListResult; /** Optional parameters. */ export interface NamespacesCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type NamespacesCreateOrUpdateResponse = EHNamespace; /** Optional parameters. */ export interface NamespacesDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface NamespacesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type NamespacesGetResponse = EHNamespace; /** Optional parameters. */ export interface NamespacesUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the update operation. */ export type NamespacesUpdateResponse = EHNamespace; /** Optional parameters. */ export interface NamespacesCreateOrUpdateNetworkRuleSetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdateNetworkRuleSet operation. */ export type NamespacesCreateOrUpdateNetworkRuleSetResponse = NetworkRuleSet; /** Optional parameters. */ export interface NamespacesGetNetworkRuleSetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getNetworkRuleSet operation. */ export type NamespacesGetNetworkRuleSetResponse = NetworkRuleSet; /** Optional parameters. */ export interface NamespacesListNetworkRuleSetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNetworkRuleSet operation. */ export type NamespacesListNetworkRuleSetResponse = NetworkRuleSetListResult; /** Optional parameters. */ export interface NamespacesListAuthorizationRulesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRules operation. */ export type NamespacesListAuthorizationRulesResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface NamespacesCreateOrUpdateAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdateAuthorizationRule operation. */ export type NamespacesCreateOrUpdateAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface NamespacesDeleteAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface NamespacesGetAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAuthorizationRule operation. */ export type NamespacesGetAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface NamespacesListKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listKeys operation. */ export type NamespacesListKeysResponse = AccessKeys; /** Optional parameters. */ export interface NamespacesRegenerateKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the regenerateKeys operation. */ export type NamespacesRegenerateKeysResponse = AccessKeys; /** Optional parameters. */ export interface NamespacesCheckNameAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkNameAvailability operation. */ export type NamespacesCheckNameAvailabilityResponse = CheckNameAvailabilityResult; /** Optional parameters. */ export interface NamespacesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type NamespacesListNextResponse = EHNamespaceListResult; /** Optional parameters. */ export interface NamespacesListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type NamespacesListByResourceGroupNextResponse = EHNamespaceListResult; /** Optional parameters. */ export interface NamespacesListAuthorizationRulesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRulesNext operation. */ export type NamespacesListAuthorizationRulesNextResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface PrivateEndpointConnectionsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type PrivateEndpointConnectionsListResponse = PrivateEndpointConnectionListResult; /** Optional parameters. */ export interface PrivateEndpointConnectionsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type PrivateEndpointConnectionsCreateOrUpdateResponse = PrivateEndpointConnection; /** Optional parameters. */ export interface PrivateEndpointConnectionsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface PrivateEndpointConnectionsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection; /** Optional parameters. */ export interface PrivateEndpointConnectionsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type PrivateEndpointConnectionsListNextResponse = PrivateEndpointConnectionListResult; /** Optional parameters. */ export interface PrivateLinkResourcesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type PrivateLinkResourcesGetResponse = PrivateLinkResourcesListResult; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult; /** Optional parameters. */ export interface OperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult; /** Optional parameters. */ export interface EventHubsListByNamespaceOptionalParams extends coreClient.OperationOptions { /** Skip is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skip parameter that specifies a starting point to use for subsequent calls. */ skip?: number; /** May be used to limit the number of results to the most recent N usageDetails. */ top?: number; } /** Contains response data for the listByNamespace operation. */ export type EventHubsListByNamespaceResponse = EventHubListResult; /** Optional parameters. */ export interface EventHubsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type EventHubsCreateOrUpdateResponse = Eventhub; /** Optional parameters. */ export interface EventHubsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface EventHubsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type EventHubsGetResponse = Eventhub; /** Optional parameters. */ export interface EventHubsListAuthorizationRulesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRules operation. */ export type EventHubsListAuthorizationRulesResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface EventHubsCreateOrUpdateAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdateAuthorizationRule operation. */ export type EventHubsCreateOrUpdateAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface EventHubsGetAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAuthorizationRule operation. */ export type EventHubsGetAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface EventHubsDeleteAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface EventHubsListKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listKeys operation. */ export type EventHubsListKeysResponse = AccessKeys; /** Optional parameters. */ export interface EventHubsRegenerateKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the regenerateKeys operation. */ export type EventHubsRegenerateKeysResponse = AccessKeys; /** Optional parameters. */ export interface EventHubsListByNamespaceNextOptionalParams extends coreClient.OperationOptions { /** Skip is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skip parameter that specifies a starting point to use for subsequent calls. */ skip?: number; /** May be used to limit the number of results to the most recent N usageDetails. */ top?: number; } /** Contains response data for the listByNamespaceNext operation. */ export type EventHubsListByNamespaceNextResponse = EventHubListResult; /** Optional parameters. */ export interface EventHubsListAuthorizationRulesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRulesNext operation. */ export type EventHubsListAuthorizationRulesNextResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface DisasterRecoveryConfigsCheckNameAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkNameAvailability operation. */ export type DisasterRecoveryConfigsCheckNameAvailabilityResponse = CheckNameAvailabilityResult; /** Optional parameters. */ export interface DisasterRecoveryConfigsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type DisasterRecoveryConfigsListResponse = ArmDisasterRecoveryListResult; /** Optional parameters. */ export interface DisasterRecoveryConfigsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type DisasterRecoveryConfigsCreateOrUpdateResponse = ArmDisasterRecovery; /** Optional parameters. */ export interface DisasterRecoveryConfigsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DisasterRecoveryConfigsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type DisasterRecoveryConfigsGetResponse = ArmDisasterRecovery; /** Optional parameters. */ export interface DisasterRecoveryConfigsBreakPairingOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DisasterRecoveryConfigsFailOverOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DisasterRecoveryConfigsListAuthorizationRulesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRules operation. */ export type DisasterRecoveryConfigsListAuthorizationRulesResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface DisasterRecoveryConfigsGetAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAuthorizationRule operation. */ export type DisasterRecoveryConfigsGetAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface DisasterRecoveryConfigsListKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listKeys operation. */ export type DisasterRecoveryConfigsListKeysResponse = AccessKeys; /** Optional parameters. */ export interface DisasterRecoveryConfigsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type DisasterRecoveryConfigsListNextResponse = ArmDisasterRecoveryListResult; /** Optional parameters. */ export interface DisasterRecoveryConfigsListAuthorizationRulesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRulesNext operation. */ export type DisasterRecoveryConfigsListAuthorizationRulesNextResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface ConsumerGroupsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type ConsumerGroupsCreateOrUpdateResponse = ConsumerGroup; /** Optional parameters. */ export interface ConsumerGroupsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface ConsumerGroupsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ConsumerGroupsGetResponse = ConsumerGroup; /** Optional parameters. */ export interface ConsumerGroupsListByEventHubOptionalParams extends coreClient.OperationOptions { /** Skip is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skip parameter that specifies a starting point to use for subsequent calls. */ skip?: number; /** May be used to limit the number of results to the most recent N usageDetails. */ top?: number; } /** Contains response data for the listByEventHub operation. */ export type ConsumerGroupsListByEventHubResponse = ConsumerGroupListResult; /** Optional parameters. */ export interface ConsumerGroupsListByEventHubNextOptionalParams extends coreClient.OperationOptions { /** Skip is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skip parameter that specifies a starting point to use for subsequent calls. */ skip?: number; /** May be used to limit the number of results to the most recent N usageDetails. */ top?: number; } /** Contains response data for the listByEventHubNext operation. */ export type ConsumerGroupsListByEventHubNextResponse = ConsumerGroupListResult; /** Optional parameters. */ export interface SchemaRegistryListByNamespaceOptionalParams extends coreClient.OperationOptions { /** Skip is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skip parameter that specifies a starting point to use for subsequent calls. */ skip?: number; /** May be used to limit the number of results to the most recent N usageDetails. */ top?: number; } /** Contains response data for the listByNamespace operation. */ export type SchemaRegistryListByNamespaceResponse = SchemaGroupListResult; /** Optional parameters. */ export interface SchemaRegistryCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type SchemaRegistryCreateOrUpdateResponse = SchemaGroup; /** Optional parameters. */ export interface SchemaRegistryDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface SchemaRegistryGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type SchemaRegistryGetResponse = SchemaGroup; /** Optional parameters. */ export interface SchemaRegistryListByNamespaceNextOptionalParams extends coreClient.OperationOptions { /** Skip is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skip parameter that specifies a starting point to use for subsequent calls. */ skip?: number; /** May be used to limit the number of results to the most recent N usageDetails. */ top?: number; } /** Contains response data for the listByNamespaceNext operation. */ export type SchemaRegistryListByNamespaceNextResponse = SchemaGroupListResult; /** Optional parameters. */ export interface EventHubManagementClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack