text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { ASMStateField } from '@defasm/codemirror'; import LZString from 'lz-string'; import { EditorState, EditorView, extensions } from './_codemirror.js'; import './_copy-as-json'; import diffTable from './_diff'; import pbm from './_pbm.js'; import { $, $$, byteLen, charLen, comma, ord } from './_util'; const experimental = JSON.parse($('#experimental').innerText); const hole = decodeURI(location.pathname.slice(1)); const langs = JSON.parse($('#langs').innerText); const scorings = ['Bytes', 'Chars']; const solutions = JSON.parse($('#solutions').innerText); const sortedLangs = Object.values(langs).sort((a: any, b: any) => a.name.localeCompare(b.name)); const darkMode = matchMedia(JSON.parse($('#darkModeMediaQuery').innerText)).matches; const baseExtensions = darkMode ? [...extensions.dark, ...extensions.base] : extensions.base; let lang = ''; let latestSubmissionID = 0; let solution = scorings.indexOf(localStorage.getItem('solution') ?? 'Bytes') as 0 | 1; let scoring = scorings.indexOf(localStorage.getItem('scoring') ?? 'Bytes') as 0 | 1; // The savedInDB state is used to avoid saving solutions in localStorage when // those solutions match the solutions in the database. It's used to avoid // restoring a solution from localStorage when the user has improved that // solution on a different browser. Assume the user is logged-in by default // for non-experimental holes. At this point, it doesn't matter whether the // user is actually logged-in, because solutions dictionaries will be empty // for users who aren't logged-in, so the savedInDB state won't be used. // By the time they are non-empty, the savedInDB state will have been updated. let savedInDB = !experimental; const editor = new EditorView({ dispatch: tr => { const result = editor.update([tr]) as unknown; const code = tr.state.doc.toString(); const scorings: {byte?: number, char?: number} = {}; const scoringKeys = ['byte', 'char'] as const; if (lang == 'assembly') scorings.byte = (editor.state.field(ASMStateField) as any).head.length(); else { scorings.byte = byteLen(code); scorings.char = charLen(code); } $('#strokes').innerText = scoringKeys .filter(s => s in scorings) .map(s => `${comma(scorings[s])} ${s}${scorings[s] != 1 ? 's' : ''}`) .join(', '); // Avoid future conflicts by only storing code locally that's // different from the server's copy. const serverCode = getSolutionCode(lang, solution); const key = getAutoSaveKey(lang, solution); if (code && (code !== serverCode || !savedInDB) && code !== langs[lang].example) localStorage.setItem(key, code); else localStorage.removeItem(key); updateRestoreLinkVisibility(); return result; }, parent: $('#editor'), }); editor.contentDOM.setAttribute('data-gramm', 'false'); // Disable Grammarly. // Set/clear the hide-details cookie on details toggling. $('#details').ontoggle = (e: Event) => document.cookie = 'hide-details=;SameSite=Lax;Secure' + ((e.target as HTMLDetailsElement).open ? ';Max-Age=0' : ''); $('#restoreLink').onclick = e => { setState(getSolutionCode(lang, solution)); e.preventDefault(); }; (onhashchange = () => { const hashLang = location.hash.slice(1) || localStorage.getItem('lang'); // Kick 'em to Python if we don't know the chosen language, or if there is no given language. lang = hashLang && langs[hashLang] ? hashLang : 'python'; // Assembly only has bytes. if (lang == 'assembly') setSolution(0); localStorage.setItem('lang', lang); history.replaceState(null, '', '#' + lang); setCodeForLangAndSolution(); })(); // Wire submit to clicking a button and a keyboard shortcut. $('#runBtn').onclick = submit; onkeydown = e => (e.ctrlKey || e.metaKey) && e.key == 'Enter' ? submit() : undefined; $('#deleteBtn')?.addEventListener('click', () => { $('dialog b').innerText = langs[lang].name; $<HTMLInputElement>('dialog [name=lang]').value = lang; $<HTMLInputElement>('dialog [name=text]').value = ''; // Dialog typings are not available yet $<any>('dialog').showModal(); }); $('dialog [name=text]').addEventListener('input', (e: Event) => { const target = e.target as HTMLInputElement; target.form!.confirm.toggleAttribute('disabled', target.value !== target.placeholder); }); $$('#rankingsView a').forEach(a => a.onclick = e => { e.preventDefault(); $$<HTMLAnchorElement>('#rankingsView a').forEach(a => a.href = ''); a.removeAttribute('href'); document.cookie = `rankings-view=${a.innerText.toLowerCase()};SameSite=Lax;Secure`; refreshScores(); }); function getAutoSaveKey(lang: string, solution: 0 | 1) { return `code_${hole}_${lang}_${solution}`; } function getOtherScoring(value: 0 | 1) { return 1 - value as 0 | 1; } function getScoring(str: string, index: 0 | 1) { return scorings[index] == 'Bytes' ? byteLen(str) : charLen(str); } function getSolutionCode(lang: string, solution: 0 | 1) { return lang in solutions[solution] ? solutions[solution][lang] : ''; } async function refreshScores() { // Populate the language picker with accurate stroke counts. $('#picker').replaceChildren(...sortedLangs.map((l: any) => { const tab = <a href={l.id == lang ? null : '#'+l.id}>{l.name}</a>; if (getSolutionCode(l.id, 0)) { const bytes = byteLen(getSolutionCode(l.id, 0)); const chars = charLen(getSolutionCode(l.id, 1)); let text = comma(bytes); if (chars && bytes != chars) text += '/' + comma(chars); tab.append(' ', <sup>{text}</sup>); } return tab; })); // Populate (and show) the solution picker if necessary. // // We have two database solutions (or local solutions) and they differ. // Or if a logged-in user has an auto-saved solution for the other metric, // that they have not submitted since logging in, they must be allowed to // switch to it, so they can submit it. const dbBytes = getSolutionCode(lang, 0); const dbChars = getSolutionCode(lang, 1); const lsBytes = localStorage.getItem(getAutoSaveKey(lang, 0)); const lsChars = localStorage.getItem(getAutoSaveKey(lang, 1)); if ((dbBytes && dbChars && dbBytes != dbChars) || (lsBytes && lsChars && lsBytes != lsChars) || (dbBytes && lsChars && dbBytes != lsChars && solution == 0) || (lsBytes && dbChars && lsBytes != dbChars && solution == 1)) { $('#solutionPicker').replaceChildren(...scorings.map((scoring, iNumber) => { const i = iNumber as 0 | 1; const a = <a>Fewest {scoring}</a>; const code = getSolutionCode(lang, i); if (code) a.append(' ', <sup>{comma(getScoring(code, i))}</sup>); if (i != solution) { a.href = ''; a.onclick = (e: MouseEvent) => { e.preventDefault(); setSolution(i); setCodeForLangAndSolution(); }; } return a; })); $('#solutionPicker').classList.remove('hide'); } else $('#solutionPicker').classList.add('hide'); // Hide the delete button for exp holes or if we have no solutions. $('#deleteBtn')?.classList.toggle('hide', experimental || (!dbBytes && !dbChars)); // Populate the rankings table. const scoringID = scorings[scoring].toLowerCase(); const path = `/${hole}/${lang}/${scoringID}`; const view = $('#rankingsView a:not([href])').innerText.toLowerCase(); const res = await fetch(`/api/mini-rankings${path}/${view}`); const rows = res.ok ? await res.json() : []; $<HTMLAnchorElement>('#allLink').href = '/rankings/holes' + path; $('#scores').replaceChildren(<tbody class={scoringID}>{ // Rows. rows.map((r: any) => <tr class={r.me ? 'me' : ''}> <td>{r.rank}<sup>{ord(r.rank)}</sup></td> <td> <a href={`/golfers/${r.golfer.name}`}> <img src={`//avatars.githubusercontent.com/${r.golfer.name}?s=24`}/> <span>{r.golfer.name}</span> </a> </td> <td data-tooltip={tooltip(r, 'Bytes')}>{comma(r.bytes)}</td> <td data-tooltip={tooltip(r, 'Chars')}>{comma(r.chars)}</td> </tr>) }{ // Padding. [...Array(7 - rows.length).keys()].map(() => <tr><td colspan="4">&nbsp;</td></tr>) }</tbody>); $$<HTMLAnchorElement>('#scoringTabs a').forEach((tab, i) => { if (tab.innerText == scorings[scoring]) { tab.removeAttribute('href'); tab.onclick = () => {}; } else { tab.href = ''; tab.onclick = e => { e.preventDefault(); // Moving `scoring = i` to the line above, outside the list access, // causes legacy CodeMirror (UMD) to be imported improperly. // Leave as-is to avoid "CodeMirror is not a constructor". localStorage.setItem('scoring', scorings[scoring = i as 0 | 1]); refreshScores(); }; } }); } function setCodeForLangAndSolution() { if (solution != 0 && getSolutionCode(lang, 0) == getSolutionCode(lang, 1)) { const autoSave0 = localStorage.getItem(getAutoSaveKey(lang, 0)); const autoSave1 = localStorage.getItem(getAutoSaveKey(lang, 1)); if (autoSave0 && !autoSave1) setSolution(0); } setState(localStorage.getItem(getAutoSaveKey(lang, solution)) || getSolutionCode(lang, solution) || langs[lang].example); if (lang == 'assembly') scoring = 0; $('#scoringTabs a:last-child').classList.toggle('hide', lang == 'assembly'); refreshScores(); $$('main .info').forEach( i => i.classList.toggle('hide', !i.classList.contains(lang))); } function setSolution(value: 0 | 1) { // Moving `solution = value` to the line above, outside the list access, // causes legacy CodeMirror (UMD) to be imported improperly. // Leave as-is to avoid "CodeMirror is not a constructor". localStorage.setItem('solution', scorings[solution = value]); } function setState(code: string) { editor.setState( EditorState.create({ doc: code, extensions: [ ...baseExtensions, extensions[lang as keyof typeof extensions] || [], // These languages shouldn't match brackets. ['brainfuck', 'fish', 'j', 'hexagony'].includes(lang) ? [] : extensions.bracketMatching, // These languages shouldn't wrap lines. ['assembly', 'fish', 'hexagony'].includes(lang) ? [] : EditorView.lineWrapping, ], }), ); editor.dispatch(); // Dispatch to update strokes. } async function submit() { $('h2').innerText = '…'; $('#status').className = 'grey'; $$('canvas').forEach(e => e.remove()); const code = editor.state.doc.toString(); const codeLang = lang; const submissionID = ++latestSubmissionID; const res = await fetch('/solution', { method: 'POST', body: JSON.stringify({ Code: code, Hole: hole, Lang: lang, }), }); if (res.status != 200) { alert('Error ' + res.status); return; } const data = await res.json() as { Pass: boolean, Out: string, Exp: string, Err: string, Argv: string[], Cheevos: { emoji: string, name: string }[], LoggedIn: boolean }; savedInDB = data.LoggedIn && !experimental; if (submissionID != latestSubmissionID) return; if (data.Pass) { for (const i of [0, 1] as const) { const solutionCode = getSolutionCode(codeLang, i); if (!solutionCode || getScoring(code, i) <= getScoring(solutionCode, i)) { solutions[i][codeLang] = code; // Don't need to keep solution in local storage because it's // stored on the site. This prevents conflicts when the // solution is improved on another browser. if (savedInDB && localStorage.getItem(getAutoSaveKey(codeLang, i)) == code) localStorage.removeItem(getAutoSaveKey(codeLang, i)); } } } for (const i of [0, 1] as const) { const key = getAutoSaveKey(codeLang, i); if (savedInDB) { // If the auto-saved code matches either solution, remove it to // avoid prompting the user to restore it. const autoSaveCode = localStorage.getItem(key); for (const j of [0, 1] as const) { if (getSolutionCode(codeLang, j) == autoSaveCode) localStorage.removeItem(key); } } else if (getSolutionCode(codeLang, i)) { // Autosave the best solution for each scoring metric, but don't // save two copies of the same solution, because that can lead to // the solution picker being show unnecessarily. if ((i == 0 || getSolutionCode(codeLang, 0) != getSolutionCode(codeLang, i)) && getSolutionCode(codeLang, i) !== langs[codeLang].example) localStorage.setItem(key, getSolutionCode(codeLang, i)); else localStorage.removeItem(key); } } // Automatically switch to the solution whose code matches the current // code after a new solution is submitted. Don't change scoring, // refreshScores will update the solution picker. if (data.Pass && getSolutionCode(codeLang, solution) != code && getSolutionCode(codeLang, getOtherScoring(solution)) == code) setSolution(getOtherScoring(solution)); // Update the restore link visibility, after possibly changing the active // solution. updateRestoreLinkVisibility(); $('h2').innerText = data.Pass ? 'Pass 😀' : 'Fail ☹️'; // Hige arguments unless we have some. $('#arg div').replaceChildren(...data.Argv.map(a => <span>{a}</span>)); $('#arg').classList.toggle('hide', !data.Argv.length); // Hide stderr if we're passing of have no stderr output. $('#err div').innerHTML = data.Err.replace(/\n/g, '<br>'); $('#err').classList.toggle('hide', data.Pass || !data.Err); // Always show exp & out. $('#exp div').innerText = data.Exp; $('#out div').innerText = data.Out; const diff = diffTable(hole, data.Exp, data.Out, data.Argv); $('#diff-content').replaceChildren(diff); $('#diff').classList.toggle('hide', !diff); $('#status').className = data.Pass ? 'green' : 'red'; // 3rd party integrations. let thirdParty = ''; if (lang == 'hexagony') { const payload = LZString.compressToBase64(JSON.stringify({ code, input: data.Argv.join('\0') + '\0', inputMode: 'raw' })); thirdParty = <a href={'//hexagony.net#lz' + payload}> Run on Hexagony.net </a>; } $('#thirdParty').replaceChildren(thirdParty); if (hole == 'julia-set') $('main').append(pbm(data.Exp) as Node, pbm(data.Out) ?? [] as any); // Show cheevos. $('#popups').replaceChildren(...data.Cheevos.map(c => <div> <h3>Achievement Earned!</h3> { c.emoji }<p>{ c.name }</p> </div>)); refreshScores(); } function tooltip(row: any, scoring: 'Bytes' | 'Chars') { const bytes = scoring === 'Bytes' ? row.bytes : row.chars_bytes; const chars = scoring === 'Chars' ? row.chars : row.bytes_chars; if (bytes === null) return; return `${scoring} solution is ${comma(bytes)} bytes` + (chars !== null ? `, ${comma(chars)} chars.` : '.'); } function updateRestoreLinkVisibility() { const serverCode = getSolutionCode(lang, solution); $('#restoreLink').classList.toggle('hide', !serverCode || editor.state.doc.toString() == serverCode); }
the_stack
import * as React from 'react'; import { mount } from 'enzyme'; import { Provider } from 'react-redux'; import configureStore from 'redux-mock-store'; import { mocked } from 'ts-jest/utils'; import { SortDirection } from 'interfaces'; import { BadgeStyle } from 'config/config-types'; import * as ConfigUtils from 'config/config-utils'; import globalState from 'fixtures/globalState'; import ColumnList, { ColumnListProps } from '.'; import ColumnType from './ColumnType'; import { EMPTY_MESSAGE } from './constants'; import TestDataBuilder from './testDataBuilder'; jest.mock('config/config-utils'); const mockedNotificationsEnabled = mocked( ConfigUtils.notificationsEnabled, true ); const mockedGetTableSortCriterias = mocked( ConfigUtils.getTableSortCriterias, true ); const dataBuilder = new TestDataBuilder(); const middlewares = []; const mockStore = configureStore(middlewares); const setup = (propOverrides?: Partial<ColumnListProps>) => { const props = { editText: 'Click to edit description in the data source site', editUrl: 'https://test.datasource.site/table', database: 'testDatabase', columns: [], tableKey: 'test-key', openRequestDescriptionDialog: jest.fn(), ...propOverrides, }; // Update state const testState = globalState; testState.tableMetadata.tableData.columns = props.columns; const wrapper = mount<ColumnListProps>( <Provider store={mockStore(testState)}> <ColumnList {...props} /> </Provider> ); return { props, wrapper }; }; describe('ColumnList', () => { mockedGetTableSortCriterias.mockReturnValue({ sort_order: { name: 'Table Default', key: 'sort_order', direction: SortDirection.ascending, }, usage: { name: 'Usage Count', key: 'usage', direction: SortDirection.descending, }, }); mockedNotificationsEnabled.mockReturnValue(true); describe('render', () => { it('renders without issues', () => { expect(() => { setup(); }).not.toThrow(); }); describe('when empty columns are passed', () => { const { columns } = dataBuilder.withEmptyColumns().build(); it('should render the custom empty messagee', () => { const { wrapper } = setup({ columns }); const expected = EMPTY_MESSAGE; const actual = wrapper .find('.table-detail-table .ams-empty-message-cell') .text(); expect(actual).toEqual(expected); }); }); describe('when simple type columns are passed', () => { const { columns } = dataBuilder.build(); it('should render the rows', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find('.table-detail-table .ams-table-row') .length; expect(actual).toEqual(expected); }); it('should render the usage column', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find('.table-detail-table .usage-value').length; expect(actual).toEqual(expected); }); it('should render the actions column', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find('.table-detail-table .actions').length; expect(actual).toEqual(expected); }); describe('when usage sorting is passed', () => { it('should sort the data by that value', () => { const { wrapper } = setup({ columns, sortBy: { name: 'Usage', key: 'usage', direction: SortDirection.descending, }, }); const expected = 'simple_column_name_timestamp'; const actual = wrapper .find('.table-detail-table .ams-table-row') .at(0) .find('.column-name') .text(); expect(actual).toEqual(expected); }); }); describe('when default sorting is passed', () => { it('should sort the data by that value', () => { const { wrapper } = setup({ columns, sortBy: { name: 'Default', key: 'sort_order', direction: SortDirection.ascending, }, }); const expected = 'simple_column_name_string'; const actual = wrapper .find('.table-detail-table .ams-table-row') .at(0) .find('.column-name') .text(); expect(actual).toEqual(expected); }); }); describe('when name sorting is passed', () => { it('should sort the data by name', () => { const { wrapper } = setup({ columns, sortBy: { name: 'Name', key: 'name', direction: SortDirection.descending, }, }); const expected = 'simple_column_name_bigint'; const actual = wrapper .find('.table-detail-table .ams-table-row') .at(0) .find('.column-name') .text(); expect(actual).toEqual(expected); }); }); }); describe('when complex type columns are passed', () => { const { columns } = dataBuilder.withAllComplexColumns().build(); it('should render the rows', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find('.table-detail-table .ams-table-row') .length; expect(actual).toEqual(expected); }); it('should render ColumnType components', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find(ColumnType).length; expect(actual).toEqual(expected); }); }); describe('when columns with no usage data are passed', () => { const { columns } = dataBuilder.withComplexColumnsNoStats().build(); it('should render the rows', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find('.table-detail-table .ams-table-row') .length; expect(actual).toEqual(expected); }); it('should not render the usage column', () => { const { wrapper } = setup({ columns }); const expected = 0; const actual = wrapper.find('.table-detail-table .usage-value').length; expect(actual).toEqual(expected); }); }); describe('when columns with one usage data entry are passed', () => { const { columns } = dataBuilder.withComplexColumnsOneStat().build(); it('should render the usage column', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find('.table-detail-table .usage-value').length; expect(actual).toEqual(expected); }); }); describe('when columns with several stats including usage are passed', () => { const { columns } = dataBuilder.withSeveralStats().build(); it('should render the usage column', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find('.table-detail-table .usage-value').length; expect(actual).toEqual(expected); }); describe('when usage sorting is passed', () => { it('should sort the data by that value', () => { const { wrapper } = setup({ columns, sortBy: { name: 'Usage', key: 'usage', direction: SortDirection.ascending, }, }); const expected = 'complex_column_name_2'; const actual = wrapper .find('.table-detail-table .ams-table-row') .at(0) .find('.column-name') .text(); expect(actual).toEqual(expected); }); }); }); describe('when notifications are not enabled', () => { const { columns } = dataBuilder.build(); it('should not render the actions column', () => { mockedNotificationsEnabled.mockReturnValue(false); const { wrapper } = setup({ columns }); const expected = 0; const actual = wrapper.find('.table-detail-table .actions').length; expect(actual).toEqual(expected); }); }); describe('when columns with badges are passed', () => { const { columns } = dataBuilder.withBadges().build(); const getBadgeConfigSpy = jest.spyOn(ConfigUtils, 'getBadgeConfig'); getBadgeConfigSpy.mockImplementation((badgeName: string) => ({ displayName: badgeName + ' test name', style: BadgeStyle.PRIMARY, })); it('should render the rows', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find('.table-detail-table .ams-table-row') .length; expect(actual).toEqual(expected); }); it('should render the badge column', () => { const { wrapper } = setup({ columns }); const expected = columns.length; const actual = wrapper.find('.badge-list').length; expect(actual).toEqual(expected); }); describe('number of bages', () => { it('should render no badges in the first cell', () => { const { wrapper } = setup({ columns }); const expected = 0; const actual = wrapper.find('.badge-list').at(0).find('.flag').length; expect(actual).toEqual(expected); }); it('should render one badge in the second cell', () => { const { wrapper } = setup({ columns }); const expected = 1; const actual = wrapper.find('.badge-list').at(1).find('.flag').length; expect(actual).toEqual(expected); }); it('should render three badges in the third cell', () => { const { wrapper } = setup({ columns }); const expected = 3; const actual = wrapper.find('.badge-list').at(2).find('.flag').length; expect(actual).toEqual(expected); }); }); }); }); });
the_stack
import { GeoCoordinates, sphereProjection, Vector2Like } from "@here/harp-geoutils"; import { expect } from "chai"; import { MathUtils, PerspectiveCamera, Vector3 } from "three"; import { CameraUtils } from "../lib/CameraUtils"; import { CanvasSide, previousCanvasSide, SphereHorizon } from "../lib/SphereHorizon"; import { MapViewUtils } from "../lib/Utils"; describe("SphereHorizon", function () { const eps = 1e-10; const projection = sphereProjection; let camera: PerspectiveCamera; const camXAxis = new Vector3(); const camYAxis = new Vector3(); const camZAxis = new Vector3(); let horizon: SphereHorizon; function setCamera( zoomLevel: number, tilt: number = 0, ppalPoint: Vector2Like = { x: 0, y: 0 }, canvasCorners: boolean[] = new Array(4).fill(false) // corners intersecting the world ) { const geoTarget = new GeoCoordinates(0, 0); const heading = 0; const canvasHeight = 800; camera.fov = 40; CameraUtils.setPrincipalPoint(camera, ppalPoint); const vFovRad = MathUtils.degToRad(camera.fov); CameraUtils.setVerticalFov(camera, vFovRad, canvasHeight); const focalLength = CameraUtils.getFocalLength(camera)!; MapViewUtils.getCameraRotationAtTarget( projection, geoTarget, -heading, tilt, camera.quaternion ); const distance = MapViewUtils.calculateDistanceFromZoomLevel({ focalLength }, zoomLevel); MapViewUtils.getCameraPositionFromTargetCoordinates( geoTarget, distance, -heading, tilt, projection, camera.position ); camera.updateMatrixWorld(true); camera.matrix.extractBasis(camXAxis, camYAxis, camZAxis); horizon = new SphereHorizon(camera, canvasCorners); } function checkPointInHorizon(point: Vector3) { const tangent = new Vector3().subVectors(camera.position, point); expect(Math.abs(tangent.angleTo(point))).closeTo(Math.PI / 2, eps); } function getHorizonPointT(point: Vector3) { checkPointInHorizon(point); const pointVec = point.clone().normalize(); const x = pointVec.dot(camXAxis); const y = pointVec.dot(camYAxis); const angle = Math.atan2(y, x); return angle >= 0 ? angle / (2 * Math.PI) : 1 + angle / (2 * Math.PI); } function checkSideTangent(side: CanvasSide) { const expectedTangents = [0.75, 0, 0.25, 0.5]; // ccw order starting with bottom side. expect(horizon.getSideIntersections(side)).has.members([expectedTangents[side]]); } // Check that intersections are on the expected canvas side when projected and that their // parameters at the horizon circle are in the expected ranges. function checkSideIntersections( side: CanvasSide, expectIntersections: [boolean, boolean] = [true, true] // [start, end] ): number[] { let ndc: { x?: number; y?: number }; let tRanges: Array<[number, number]>; // first range for start intersection, then for end. switch (side) { case CanvasSide.Bottom: ndc = { y: -1 }; tRanges = [ [0.5, 0.75], [0.75, 1] ]; break; case CanvasSide.Right: ndc = { x: 1 }; tRanges = [ [0.75, 1], [0, 0.25] ]; break; case CanvasSide.Top: ndc = { y: 1 }; tRanges = [ [0, 0.25], [0.25, 0.5] ]; break; case CanvasSide.Left: ndc = { x: -1 }; tRanges = [ [0.25, 0.5], [0.5, 0.75] ]; break; } tRanges = tRanges.filter((val, index) => expectIntersections[index]); const intersections = horizon.getSideIntersections(side); expect(intersections).has.lengthOf(tRanges.length); if (intersections.length === 0) { return intersections; } // Horizon intersection computations are done in horizon space, then transformed to world // space and projected when needed. This introduces a noticeable loss of precision in NDC // space, due to which canvas side intersections end up sometimes slightly out of the // clipping volume. Worst case happens in off-center projections, with an error ~1.5%. const ndcEps = 0.031; for (let i = 0; i < intersections.length; ++i) { const intersection = intersections[i]; if (ndc.x !== undefined) { expect(horizon.getPoint(intersection).project(camera).x).closeTo(ndc.x, ndcEps); } if (ndc.y !== undefined) { expect(horizon.getPoint(intersection).project(camera).y).closeTo(ndc.y, ndcEps); } const tRange = tRanges[i]; expect(intersection).gt(tRange[0]).and.lt(tRange[1]); } if (side !== CanvasSide.Right) { const prevIntersections = horizon.getSideIntersections(previousCanvasSide(side)); if ( (side !== CanvasSide.Top && prevIntersections.length > 0) || prevIntersections.length > 1 ) { expect(intersections[0]).gt(prevIntersections[prevIntersections.length - 1]); } } return intersections; } beforeEach(function () { camera = new PerspectiveCamera(); setCamera(3); }); describe("getPoint", function () { it("returns point in horizon at the specified angular parameter", function () { for (let t = 0; t <= 1; t += 0.05) { expect(getHorizonPointT(horizon.getPoint(t))).closeTo(t, eps); } }); it("uses the passed angle range if specified", function () { expect(getHorizonPointT(horizon.getPoint(0, 0.25, 0.75))).closeTo(0.25, eps); expect(getHorizonPointT(horizon.getPoint(0.5, 0.25, 0.75))).closeTo(0.5, eps); expect(getHorizonPointT(horizon.getPoint(1, 0.25, 0.75))).closeTo(0.75, eps); }); it("wraps around arcEnd when it's less than the arcStart", function () { expect(getHorizonPointT(horizon.getPoint(0.5, 0.25, -0.25))).closeTo(0.5, eps); }); }); describe("getDivisionPoints", function () { it("returns horizon subdivided with multiple equidistant points", function () { const points: number[] = []; horizon.getDivisionPoints(point => { points.push(getHorizonPointT(point)); }); expect(points).has.length.greaterThan(4); const diffT = points[1] - points[0]; for (let i = 1; i < points.length - 1; i++) { expect(points[i + 1] - points[i]).closeTo(diffT, eps); } }); it("uses by the default the whole horizon circle", function () { const points: number[] = []; horizon.getDivisionPoints(point => { points.push(getHorizonPointT(point)); }); expect(points[0]).closeTo(0, eps); const diffT = points[1] - points[0]; // last point (corresponding to t = 1 is omitted). expect(points[points.length - 1] + diffT).closeTo(1, eps); }); it("uses the passed parameter range if specified", function () { const points: number[] = []; horizon.getDivisionPoints( point => { points.push(getHorizonPointT(point)); }, 0.66, 0.9 ); expect(points[0]).closeTo(0.66, eps); const diffT = points[1] - points[0]; // last point (corresponding to t = 1 is omitted). expect(points[points.length - 1] + diffT).closeTo(0.9, eps); }); it("wraps around tEnd when it's less than the tStart", function () { const points: number[] = []; horizon.getDivisionPoints( point => { points.push(getHorizonPointT(point)); }, 0.66, -0.1 ); expect(points[0]).closeTo(0.66, eps); const diffT = points[1] - points[0]; // last point (corresponding to t = 1 is omitted). expect(points[points.length - 1] + diffT).closeTo(0.9, eps); }); }); describe("isFullyVisible", function () { it("returns true only when globe is fully in view", function () { setCamera(3); expect(horizon.isFullyVisible).to.be.true; setCamera(3, 80); expect(horizon.isFullyVisible).to.be.false; setCamera(4); expect(horizon.isFullyVisible).to.be.false; }); }); describe("getSideIntersections", function () { // Left intersections different from right onese for off-center projection. // made tangent points visible/invisible by offsetting ppal point. it("returns middle tangent point if horizon is fully visible", function () { setCamera(3); checkSideTangent(CanvasSide.Bottom); checkSideTangent(CanvasSide.Right); checkSideTangent(CanvasSide.Top); checkSideTangent(CanvasSide.Left); }); it("returns 1 side intersection if start corner hits world", function () { setCamera(6, 80); const rightIntersections = checkSideIntersections(CanvasSide.Right, [false, true]); const leftIntersections = checkSideIntersections(CanvasSide.Left, [true, false]); expect(leftIntersections[0]).equals(0.5 - rightIntersections[0]); }); it("returns 2 side intersections if corners out of world", function () { setCamera(4); const bottomIntersections = checkSideIntersections(CanvasSide.Bottom); expect(bottomIntersections[1]).closeTo(1.5 - bottomIntersections[0], eps); const rightIntersections = checkSideIntersections(CanvasSide.Right); expect(rightIntersections[1]).closeTo(1 - rightIntersections[0], eps); const topIntersections = checkSideIntersections(CanvasSide.Top); expect(topIntersections[1]).closeTo(0.5 - topIntersections[0], eps); const leftIntersections = checkSideIntersections(CanvasSide.Left); expect(leftIntersections[1]).closeTo(1 - leftIntersections[0], eps); // Left intersections are symmetric to right ones. expect(leftIntersections[0]).equals(0.5 - rightIntersections[1]); expect(leftIntersections[1]).equals(0.5 + (1 - rightIntersections[0])); }); describe("off-center projection", function () { describe("no canvas corner intersections", function () { it("hidden left tangent", function () { setCamera(3, 0, { x: -0.5, y: 0 }); checkSideTangent(CanvasSide.Bottom); checkSideTangent(CanvasSide.Right); checkSideTangent(CanvasSide.Top); checkSideIntersections(CanvasSide.Left); }); it("hidden right tangent", function () { setCamera(3, 0, { x: 0.5, y: 0 }); checkSideTangent(CanvasSide.Bottom); checkSideIntersections(CanvasSide.Right); checkSideTangent(CanvasSide.Top); checkSideTangent(CanvasSide.Left); }); it("hidden bottom tangent", function () { setCamera(3, 0, { x: 0, y: -0.5 }); checkSideIntersections(CanvasSide.Bottom); checkSideTangent(CanvasSide.Right); checkSideTangent(CanvasSide.Top); checkSideTangent(CanvasSide.Left); }); it("hidden top tangent", function () { setCamera(3, 0, { x: 0, y: 0.5 }); checkSideTangent(CanvasSide.Bottom); checkSideTangent(CanvasSide.Right); checkSideIntersections(CanvasSide.Top); checkSideTangent(CanvasSide.Left); }); }); describe("2 canvas corner intersections", function () { it("hidden left side intersections", function () { setCamera(4.3, 0, { x: -0.5, y: 0 }, [true, false, false, true]); checkSideIntersections(CanvasSide.Bottom, [false, true]); checkSideTangent(CanvasSide.Right); checkSideIntersections(CanvasSide.Top, [true, false]); checkSideIntersections(CanvasSide.Left, [false, false]); }); it("hidden right side intersections", function () { setCamera(4.3, 0, { x: 0.5, y: 0 }, [false, true, true, false]); checkSideIntersections(CanvasSide.Bottom, [true, false]); checkSideIntersections(CanvasSide.Right, [false, false]); checkSideIntersections(CanvasSide.Top, [false, true]); checkSideTangent(CanvasSide.Left); }); it("hidden bottom side intersections", function () { setCamera(4.3, 0, { x: 0, y: -0.5 }, [true, true, false, false]); checkSideIntersections(CanvasSide.Bottom, [false, false]); checkSideIntersections(CanvasSide.Right, [false, true]); checkSideTangent(CanvasSide.Top); checkSideIntersections(CanvasSide.Left, [true, false]); }); it("hidden top side intersections", function () { setCamera(4.3, 0, { x: 0, y: 0.5 }, [false, false, true, true]); checkSideTangent(CanvasSide.Bottom); checkSideIntersections(CanvasSide.Right, [true, false]); checkSideIntersections(CanvasSide.Top, [false, false]); checkSideIntersections(CanvasSide.Left, [false, true]); }); }); describe("1 canvas corner intersection", function () { it("bottom-left corner intersection", function () { setCamera(3, 0, { x: -0.8, y: -0.8 }, [true, false, false, false]); checkSideIntersections(CanvasSide.Bottom, [false, true]); checkSideTangent(CanvasSide.Right); checkSideTangent(CanvasSide.Top); checkSideIntersections(CanvasSide.Left, [true, false]); }); it("bottom-right corner intersection", function () { setCamera(3, 0, { x: 0.8, y: -0.8 }, [false, true, false, false]); checkSideIntersections(CanvasSide.Bottom, [true, false]); checkSideIntersections(CanvasSide.Right, [false, true]); checkSideTangent(CanvasSide.Top); checkSideTangent(CanvasSide.Left); }); it("top-right corner intersection", function () { setCamera(3, 0, { x: 0.8, y: 0.8 }, [false, false, true, false]); checkSideTangent(CanvasSide.Bottom); checkSideIntersections(CanvasSide.Right, [true, false]); checkSideIntersections(CanvasSide.Top, [false, true]); checkSideTangent(CanvasSide.Left); }); it("top-left corner intersection", function () { setCamera(3, 0, { x: -0.8, y: 0.8 }, [false, false, false, true]); checkSideTangent(CanvasSide.Bottom); checkSideTangent(CanvasSide.Right); checkSideIntersections(CanvasSide.Top, [true, false]); checkSideIntersections(CanvasSide.Left, [false, true]); }); }); }); }); });
the_stack
export const description = ` Test the operation of buffer mapping, specifically the data contents written via map-write/mappedAtCreation, and the contents of buffers returned by getMappedRange on buffers which are mapped-read/mapped-write/mappedAtCreation. range: used for getMappedRange mapRegion: used for mapAsync mapRegionBoundModes is used to get mapRegion from range: - default-expand: expand mapRegion to buffer bound by setting offset/size to undefined - explicit-expand: expand mapRegion to buffer bound by explicitly calculating offset/size - minimal: make mapRegion to be the same as range which is the minimal range to make getMappedRange input valid `; import { makeTestGroup } from '../../../../common/framework/test_group.js'; import { assert, memcpy } from '../../../../common/util/util.js'; import { checkElementsEqual } from '../../../util/check_contents.js'; import { MappingTest } from './mapping_test.js'; export const g = makeTestGroup(MappingTest); const kSubcases = [ { size: 0, range: [] }, { size: 0, range: [undefined] }, { size: 0, range: [undefined, undefined] }, { size: 0, range: [0] }, { size: 0, range: [0, undefined] }, { size: 0, range: [0, 0] }, { size: 12, range: [] }, { size: 12, range: [undefined] }, { size: 12, range: [undefined, undefined] }, { size: 12, range: [0] }, { size: 12, range: [0, undefined] }, { size: 12, range: [0, 12] }, { size: 12, range: [0, 0] }, { size: 12, range: [8] }, { size: 12, range: [8, undefined] }, { size: 12, range: [8, 4] }, { size: 28, range: [8, 8] }, { size: 28, range: [8, 12] }, { size: 512 * 1024, range: [] }, ] as const; function reifyMapRange(bufferSize: number, range: readonly [number?, number?]): [number, number] { const offset = range[0] ?? 0; return [offset, range[1] ?? bufferSize - offset]; } const mapRegionBoundModes = ['default-expand', 'explicit-expand', 'minimal'] as const; type MapRegionBoundMode = typeof mapRegionBoundModes[number]; function getRegionForMap( bufferSize: number, range: [number, number], { mapAsyncRegionLeft, mapAsyncRegionRight, }: { mapAsyncRegionLeft: MapRegionBoundMode; mapAsyncRegionRight: MapRegionBoundMode; } ) { const regionLeft = mapAsyncRegionLeft === 'minimal' ? range[0] : 0; const regionRight = mapAsyncRegionRight === 'minimal' ? range[0] + range[1] : bufferSize; return [ mapAsyncRegionLeft === 'default-expand' ? undefined : regionLeft, mapAsyncRegionRight === 'default-expand' ? undefined : regionRight - regionLeft, ] as const; } g.test('mapAsync,write') .desc( `Use map-write to write to various ranges of variously-sized buffers, then expectContents (which does copyBufferToBuffer + map-read) to ensure the contents were written.` ) .params(u => u .combine('mapAsyncRegionLeft', mapRegionBoundModes) .combine('mapAsyncRegionRight', mapRegionBoundModes) .beginSubcases() .combineWithParams(kSubcases) ) .fn(async t => { const { size, range } = t.params; const [rangeOffset, rangeSize] = reifyMapRange(size, range); const buffer = t.device.createBuffer({ size, usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.MAP_WRITE, }); const mapRegion = getRegionForMap(size, [rangeOffset, rangeSize], t.params); await buffer.mapAsync(GPUMapMode.WRITE, ...mapRegion); const arrayBuffer = buffer.getMappedRange(...range); t.checkMapWrite(buffer, rangeOffset, arrayBuffer, rangeSize); }); g.test('mapAsync,write,unchanged_ranges_preserved') .desc( `Use mappedAtCreation or mapAsync to write to various ranges of variously-sized buffers, then use mapAsync to map a different range and zero it out. Finally use expectGPUBufferValuesEqual (which does copyBufferToBuffer + map-read) to verify that contents originally written outside the second mapped range were not altered.` ) .params(u => u .beginSubcases() .combine('mappedAtCreation', [false, true]) .combineWithParams([ { size: 12, range1: [], range2: [8] }, { size: 12, range1: [], range2: [0, 8] }, { size: 12, range1: [0, 8], range2: [8] }, { size: 12, range1: [8], range2: [0, 8] }, { size: 28, range1: [], range2: [8, 8] }, { size: 28, range1: [8, 16], range2: [16, 8] }, { size: 32, range1: [16, 12], range2: [8, 16] }, { size: 32, range1: [8, 8], range2: [24, 4] }, ] as const) ) .fn(async t => { const { size, range1, range2, mappedAtCreation } = t.params; const [rangeOffset1, rangeSize1] = reifyMapRange(size, range1); const [rangeOffset2, rangeSize2] = reifyMapRange(size, range2); const buffer = t.device.createBuffer({ mappedAtCreation, size, usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.MAP_WRITE, }); // If the buffer is not mappedAtCreation map it now. if (!mappedAtCreation) { await buffer.mapAsync(GPUMapMode.WRITE); } // Set the initial contents of the buffer. const init = buffer.getMappedRange(...range1); assert(init.byteLength === rangeSize1); const expectedBuffer = new ArrayBuffer(size); const expected = new Uint32Array( expectedBuffer, rangeOffset1, rangeSize1 / Uint32Array.BYTES_PER_ELEMENT ); const data = new Uint32Array(init); for (let i = 0; i < data.length; ++i) { data[i] = expected[i] = i + 1; } buffer.unmap(); // Write to a second range of the buffer await buffer.mapAsync(GPUMapMode.WRITE, ...range2); const init2 = buffer.getMappedRange(...range2); assert(init2.byteLength === rangeSize2); const expected2 = new Uint32Array( expectedBuffer, rangeOffset2, rangeSize2 / Uint32Array.BYTES_PER_ELEMENT ); const data2 = new Uint32Array(init2); for (let i = 0; i < data2.length; ++i) { data2[i] = expected2[i] = 0; } buffer.unmap(); // Verify that the range of the buffer which was not overwritten was preserved. t.expectGPUBufferValuesEqual(buffer, expected, rangeOffset1); }); g.test('mapAsync,read') .desc( `Use mappedAtCreation to initialize various ranges of variously-sized buffers, then map-read and check the read-back result.` ) .params(u => u .combine('mapAsyncRegionLeft', mapRegionBoundModes) .combine('mapAsyncRegionRight', mapRegionBoundModes) .beginSubcases() .combineWithParams(kSubcases) ) .fn(async t => { const { size, range } = t.params; const [rangeOffset, rangeSize] = reifyMapRange(size, range); const buffer = t.device.createBuffer({ mappedAtCreation: true, size, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, }); const init = buffer.getMappedRange(...range); assert(init.byteLength === rangeSize); const expected = new Uint32Array(new ArrayBuffer(rangeSize)); const data = new Uint32Array(init); for (let i = 0; i < data.length; ++i) { data[i] = expected[i] = i + 1; } buffer.unmap(); const mapRegion = getRegionForMap(size, [rangeOffset, rangeSize], t.params); await buffer.mapAsync(GPUMapMode.READ, ...mapRegion); const actual = new Uint8Array(buffer.getMappedRange(...range)); t.expectOK(checkElementsEqual(actual, new Uint8Array(expected.buffer))); }); g.test('mapAsync,read,typedArrayAccess') .desc(`Use various TypedArray types to read back from a mapped buffer`) .params(u => u .combine('mapAsyncRegionLeft', mapRegionBoundModes) .combine('mapAsyncRegionRight', mapRegionBoundModes) .beginSubcases() .combineWithParams([ { size: 80, range: [] }, { size: 160, range: [] }, { size: 160, range: [0, 80] }, { size: 160, range: [80] }, { size: 160, range: [40, 120] }, { size: 160, range: [40] }, ] as const) ) .fn(async t => { const { size, range } = t.params; const [rangeOffset, rangeSize] = reifyMapRange(size, range); // Fill an array buffer with a variety of values of different types. const expectedArrayBuffer = new ArrayBuffer(80); const uint8Expected = new Uint8Array(expectedArrayBuffer, 0, 2); uint8Expected[0] = 1; uint8Expected[1] = 255; const int8Expected = new Int8Array(expectedArrayBuffer, 2, 2); int8Expected[0] = -1; int8Expected[1] = 127; const uint16Expected = new Uint16Array(expectedArrayBuffer, 4, 2); uint16Expected[0] = 1; uint16Expected[1] = 65535; const int16Expected = new Int16Array(expectedArrayBuffer, 8, 2); int16Expected[0] = -1; int16Expected[1] = 32767; const uint32Expected = new Uint32Array(expectedArrayBuffer, 12, 2); uint32Expected[0] = 1; uint32Expected[1] = 4294967295; const int32Expected = new Int32Array(expectedArrayBuffer, 20, 2); int32Expected[2] = -1; int32Expected[3] = 2147483647; const float32Expected = new Float32Array(expectedArrayBuffer, 28, 3); float32Expected[0] = 1; float32Expected[1] = -1; float32Expected[2] = 12345.6789; const float64Expected = new Float64Array(expectedArrayBuffer, 40, 5); float64Expected[0] = 1; float64Expected[1] = -1; float64Expected[2] = 12345.6789; float64Expected[3] = Number.MAX_VALUE; float64Expected[4] = Number.MIN_VALUE; const buffer = t.device.createBuffer({ mappedAtCreation: true, size, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, }); const init = buffer.getMappedRange(...range); // Copy the expected values into the mapped range. assert(init.byteLength === rangeSize); memcpy({ src: expectedArrayBuffer }, { dst: init }); buffer.unmap(); const mapRegion = getRegionForMap(size, [rangeOffset, rangeSize], t.params); await buffer.mapAsync(GPUMapMode.READ, ...mapRegion); const mappedArrayBuffer = buffer.getMappedRange(...range); t.expectOK(checkElementsEqual(new Uint8Array(mappedArrayBuffer, 0, 2), uint8Expected)); t.expectOK(checkElementsEqual(new Int8Array(mappedArrayBuffer, 2, 2), int8Expected)); t.expectOK(checkElementsEqual(new Uint16Array(mappedArrayBuffer, 4, 2), uint16Expected)); t.expectOK(checkElementsEqual(new Int16Array(mappedArrayBuffer, 8, 2), int16Expected)); t.expectOK(checkElementsEqual(new Uint32Array(mappedArrayBuffer, 12, 2), uint32Expected)); t.expectOK(checkElementsEqual(new Int32Array(mappedArrayBuffer, 20, 2), int32Expected)); t.expectOK(checkElementsEqual(new Float32Array(mappedArrayBuffer, 28, 3), float32Expected)); t.expectOK(checkElementsEqual(new Float64Array(mappedArrayBuffer, 40, 5), float64Expected)); }); g.test('mappedAtCreation') .desc( `Use mappedAtCreation to write to various ranges of variously-sized buffers created either with or without the MAP_WRITE usage (since this could affect the mappedAtCreation upload path), then expectContents (which does copyBufferToBuffer + map-read) to ensure the contents were written.` ) .params(u => u // .combine('mappable', [false, true]) .beginSubcases() .combineWithParams(kSubcases) ) .fn(async t => { const { size, range, mappable } = t.params; const [, rangeSize] = reifyMapRange(size, range); const buffer = t.device.createBuffer({ mappedAtCreation: true, size, usage: GPUBufferUsage.COPY_SRC | (mappable ? GPUBufferUsage.MAP_WRITE : 0), }); const arrayBuffer = buffer.getMappedRange(...range); t.checkMapWrite(buffer, range[0] ?? 0, arrayBuffer, rangeSize); }); g.test('remapped_for_write') .desc( `Use mappedAtCreation or mapAsync to write to various ranges of variously-sized buffers created with the MAP_WRITE usage, then mapAsync again and ensure that the previously written values are still present in the mapped buffer.` ) .params(u => u // .combine('mapAsyncRegionLeft', mapRegionBoundModes) .combine('mapAsyncRegionRight', mapRegionBoundModes) .beginSubcases() .combine('mappedAtCreation', [false, true]) .combineWithParams(kSubcases) ) .fn(async t => { const { size, range, mappedAtCreation } = t.params; const [rangeOffset, rangeSize] = reifyMapRange(size, range); const buffer = t.device.createBuffer({ mappedAtCreation, size, usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.MAP_WRITE, }); // If the buffer is not mappedAtCreation map it now. if (!mappedAtCreation) { await buffer.mapAsync(GPUMapMode.WRITE); } // Set the initial contents of the buffer. const init = buffer.getMappedRange(...range); assert(init.byteLength === rangeSize); const expected = new Uint32Array(new ArrayBuffer(rangeSize)); const data = new Uint32Array(init); for (let i = 0; i < data.length; ++i) { data[i] = expected[i] = i + 1; } buffer.unmap(); // Check that upon remapping the for WRITE the values in the buffer are // still the same. const mapRegion = getRegionForMap(size, [rangeOffset, rangeSize], t.params); await buffer.mapAsync(GPUMapMode.WRITE, ...mapRegion); const actual = new Uint8Array(buffer.getMappedRange(...range)); t.expectOK(checkElementsEqual(actual, new Uint8Array(expected.buffer))); });
the_stack
import * as fc from 'fast-check'; import * as secp from '..'; import { readFileSync } from 'fs'; import * as sysPath from 'path'; import * as ecdsa from './vectors/ecdsa.json'; import * as ecdh from './vectors/ecdh.json'; import * as privates from './vectors/privates.json'; import * as points from './vectors/points.json'; import * as wp from './vectors/wychenproof.json'; const privatesTxt = readFileSync(sysPath.join(__dirname, 'vectors', 'privates-2.txt'), 'utf-8'); const schCsv = readFileSync(sysPath.join(__dirname, 'vectors', 'schnorr.csv'), 'utf-8'); const FC_BIGINT = fc.bigInt(1n, secp.CURVE.n - 1n); const toBEHex = (n: number | bigint) => n.toString(16).padStart(64, '0'); function hexToArray(hex: string): Uint8Array { hex = hex.length & 1 ? `0${hex}` : hex; const array = new Uint8Array(hex.length / 2); for (let i = 0; i < array.length; i++) { let j = i * 2; array[i] = Number.parseInt(hex.slice(j, j + 2), 16); } return array; } describe('secp256k1', () => { it('.getPublicKey()', () => { const data = privatesTxt .split('\n') .filter((line) => line) .map((line) => line.split(':')); for (let [priv, x, y] of data) { const point = secp.Point.fromPrivateKey(BigInt(priv)); expect(toBEHex(point.x)).toBe(x); expect(toBEHex(point.y)).toBe(y); const point2 = secp.Point.fromHex(secp.getPublicKey(toBEHex(BigInt(priv)))); expect(toBEHex(point2.x)).toBe(x); expect(toBEHex(point2.y)).toBe(y); const point3 = secp.Point.fromHex(secp.getPublicKey(hexToArray(toBEHex(BigInt(priv))))); expect(toBEHex(point3.x)).toBe(x); expect(toBEHex(point3.y)).toBe(y); } }); it('.getPublicKey() rejects invalid keys', () => { const invalid = [0, true, false, undefined, null, 1.1, -5, 'deadbeef', Math.pow(2, 53), [1], 'xyzxyzxyxyzxyzxyxyzxyzxyxyzxyzxyxyzxyzxyxyzxyzxyxyzxyzxyxyzxyzxy', secp.CURVE.n + 2n]; for (const item of invalid) { expect(() => secp.getPublicKey(item as any)).toThrowError(); } }); it('precompute', () => { secp.utils.precompute(4); const data = privatesTxt .split('\n') .filter((line) => line) .map((line) => line.split(':')); for (let [priv, x, y] of data) { const point = secp.Point.fromPrivateKey(BigInt(priv)); expect(toBEHex(point.x)).toBe(x); expect(toBEHex(point.y)).toBe(y); const point2 = secp.Point.fromHex(secp.getPublicKey(toBEHex(BigInt(priv)))); expect(toBEHex(point2.x)).toBe(x); expect(toBEHex(point2.y)).toBe(y); const point3 = secp.Point.fromHex(secp.getPublicKey(hexToArray(toBEHex(BigInt(priv))))); expect(toBEHex(point3.x)).toBe(x); expect(toBEHex(point3.y)).toBe(y); } }); describe('Point', () => { it('.isValidPoint()', () => { for (const vector of points.valid.isPoint) { const { P, expected } = vector; if (expected) { secp.Point.fromHex(P); } else { expect(() => secp.Point.fromHex(P)).toThrowError(); } } }); it('.fromPrivateKey()', () => { for (const vector of points.valid.pointFromScalar) { const { d, expected } = vector; let p = secp.Point.fromPrivateKey(d); expect(p.toHex(true)).toBe(expected); } }); it('#toHex(compressed)', () => { for (const vector of points.valid.pointCompress) { const { P, compress, expected } = vector; let p = secp.Point.fromHex(P); expect(p.toHex(compress)).toBe(expected); } }); it('#toHex() roundtrip', () => { fc.assert( fc.property(FC_BIGINT, (x) => { const point1 = secp.Point.fromPrivateKey(x); const hex = point1.toHex(true); expect(secp.Point.fromHex(hex).toHex(true)).toBe(hex); }) ); }); it('#add(other)', () => { for (const vector of points.valid.pointAdd) { const { P, Q, expected } = vector; let p = secp.Point.fromHex(P); let q = secp.Point.fromHex(Q); if (expected) { expect(p.add(q).toHex(true)).toBe(expected); } else { // console.log(p, q); if (!p.equals(q.negate())) { expect(() => p.add(q).toHex(true)).toThrowError(); } } } }); it('#multiply(privateKey)', () => { function hexToNumber(hex: string): bigint { if (typeof hex !== 'string') { throw new TypeError('hexToNumber: expected string, got ' + typeof hex); } // Big Endian return BigInt(`0x${hex}`); } for (const vector of points.valid.pointMultiply) { const { P, d, expected } = vector; const p = secp.Point.fromHex(P); if (expected) { expect(p.multiply(hexToNumber(d)).toHex(true)).toBe(expected); } else { expect(() => { p.multiply(hexToNumber(d)).toHex(true); }).toThrowError(); } } for (const vector of points.invalid.pointMultiply) { const { P, d } = vector; if (hexToNumber(d) < secp.CURVE.n) { expect(() => { const p = secp.Point.fromHex(P); p.multiply(hexToNumber(d)).toHex(true); }).toThrowError(); } } for (const num of [0n, 0, -1n, -1, 1.1]) { expect(() => secp.Point.BASE.multiply(num)).toThrowError(); } }); }); describe('Signature', () => { it('.fromHex() roundtrip', () => { fc.assert( fc.property(FC_BIGINT, FC_BIGINT, (r, s) => { const signature = new secp.Signature(r, s); const hex = signature.toDERHex(); expect(secp.Signature.fromDER(hex)).toEqual(signature); }) ); }); it('.fromHex() roundtrip', () => { fc.assert( fc.property(FC_BIGINT, FC_BIGINT, (r, s) => { const signature = new secp.Signature(r, s); const hex = signature.toDERHex(); expect(secp.Signature.fromDER(hex)).toEqual(signature); }) ); }); }); describe('.sign()', () => { it('should create deterministic signatures with RFC 6979', async () => { for (const vector of ecdsa.valid) { const full = await secp.sign(vector.m, vector.d, { canonical: true }); const vsig = vector.signature; const [vecR, vecS] = [vsig.slice(0, 64), vsig.slice(64, 128)]; const res = secp.Signature.fromDER(full).toCompactHex(); const [r, s] = [res.slice(0, 64), res.slice(64, 128)]; expect(r).toBe(vecR); expect(s).toBe(vecS); } }); it('edge cases', () => { // @ts-ignore expect(async () => await secp.sign()).rejects.toThrowError(); // @ts-ignore expect(async () => await secp.sign('')).rejects.toThrowError(); }); it('should create correct DER encoding against libsecp256k1', async () => { const CASES = [ [ 'd1a9dc8ed4e46a6a3e5e594615ca351d7d7ef44df1e4c94c1802f3592183794b', '304402203de2559fccb00c148574997f660e4d6f40605acc71267ee38101abf15ff467af02200950abdf40628fd13f547792ba2fc544681a485f2fdafb5c3b909a4df7350e6b' ], [ '5f97983254982546d3976d905c6165033976ee449d300d0e382099fa74deaf82', '3045022100c046d9ff0bd2845b9aa9dff9f997ecebb31e52349f80fe5a5a869747d31dcb88022011f72be2a6d48fe716b825e4117747b397783df26914a58139c3f4c5cbb0e66c' ], [ '0d7017a96b97cd9be21cf28aada639827b2814a654a478c81945857196187808', '3045022100d18990bba7832bb283e3ecf8700b67beb39acc73f4200ed1c331247c46edccc602202e5c8bbfe47ae159512c583b30a3fa86575cddc62527a03de7756517ae4c6c73' ] ]; const privKey = hexToArray( '0101010101010101010101010101010101010101010101010101010101010101' ); for (let [msg, exp] of CASES) { const res = await secp.sign(msg, privKey, { canonical: true }); expect(res).toBe(exp); const rs = secp.Signature.fromDER(res).toCompactHex(); expect(secp.Signature.fromCompact(rs).toDERHex()).toBe(exp); } }); }); describe('.verify()', () => { it('should verify signature', async () => { const MSG = '1'; const PRIV_KEY = 0x2n; const signature = await secp.sign(MSG, PRIV_KEY); const publicKey = secp.getPublicKey(PRIV_KEY); expect(publicKey.length).toBe(65); expect(secp.verify(signature, MSG, publicKey)).toBe(true); }); it('should not verify signature with wrong public key', async () => { const MSG = '1'; const PRIV_KEY = 0x2n; const WRONG_PRIV_KEY = 0x22n; const signature = await secp.sign(MSG, PRIV_KEY); const publicKey = secp.Point.fromPrivateKey(WRONG_PRIV_KEY).toHex(); expect(publicKey.length).toBe(130); expect(secp.verify(signature, MSG, publicKey)).toBe(false); }); it('should not verify signature with wrong hash', async () => { const MSG = '1'; const PRIV_KEY = 0x2n; const WRONG_MSG = '11'; const signature = await secp.sign(MSG, PRIV_KEY); const publicKey = secp.getPublicKey(PRIV_KEY); expect(publicKey.length).toBe(65); expect(secp.verify(signature, WRONG_MSG, publicKey)).toBe(false); }); it('should verify random signatures', async () => { fc.assert( fc.asyncProperty(FC_BIGINT, fc.hexaString(64, 64), async (privKey, msg) => { const pub = secp.getPublicKey(privKey); const sig = await secp.sign(msg, privKey); expect(secp.verify(sig, msg, pub)).toBeTruthy(); }) ); }); it('should not verify signature with invalid r/s', () => { const msg = new Uint8Array([0xbb, 0x5a, 0x52, 0xf4, 0x2f, 0x9c, 0x92, 0x61, 0xed, 0x43, 0x61, 0xf5, 0x94, 0x22, 0xa1, 0xe3, 0x00, 0x36, 0xe7, 0xc3, 0x2b, 0x27, 0x0c, 0x88, 0x07, 0xa4, 0x19, 0xfe, 0xca, 0x60, 0x50, 0x23]); const x = 100260381870027870612475458630405506840396644859280795015145920502443964769584n; const y = 41096923727651821103518389640356553930186852801619204169823347832429067794568n; const r = 1n; const s = 115792089237316195423570985008687907852837564279074904382605163141518162728904n; const pub = new secp.Point(x, y); const signature = new secp.Signature(r, s); const verified = secp.verify(signature, msg, pub); // Verifies, but it shouldn't, because signature S > curve order expect(verified).toBeFalsy(); }); it('should not verify msg = curve order', async() => { const msg = 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141' const x = 55066263022277343669578718895168534326250603453777594175500187360389116729240n; const y = 32670510020758816978083085130507043184471273380659243275938904335757337482424n; const r = 104546003225722045112039007203142344920046999340768276760147352389092131869133n; const s = 96900796730960181123786672629079577025401317267213807243199432755332205217369n; const pub = new secp.Point(x, y); const sig = new secp.Signature(r, s); expect(secp.verify(sig, msg, pub)).toBeFalsy(); }); it('should verify msg bb5a...', async() => { const msg = 'bb5a52f42f9c9261ed4361f59422a1e30036e7c32b270c8807a419feca605023'; const x = 3252872872578928810725465493269682203671229454553002637820453004368632726370n const y = 17482644437196207387910659778872952193236850502325156318830589868678978890912n; const r = 432420386565659656852420866390673177323n; const s = 115792089237316195423570985008687907852837564279074904382605163141518161494334n; const pub = new secp.Point(x, y); const sig = new secp.Signature(r, s); expect(secp.verify(sig, msg, pub)).toBeTruthy(); }) }); describe('schnorr', () => { // index,secret key,public key,aux_rand,message,signature,verification result,comment const vectors = schCsv.split('\n').map((line: string) => line.split(',')).slice(1, -1); for (let vec of vectors) { const [index, sec, pub, rnd, msg, expSig, passes, comment] = vec; if (index == '4' && !sec) continue; // pass test for now — it has invalid private key? it(`should sign with Schnorr scheme vector ${index}`, async () => { if (passes === 'TRUE') { const sig = await secp.schnorr.sign(msg, sec, rnd); expect(secp.schnorr.getPublicKey(sec)).toBe(pub.toLowerCase()); expect(sig).toBe(expSig.toLowerCase()); expect(await secp.schnorr.verify(sig, msg, pub)).toBe(true); } else { try { await secp.schnorr.sign(msg, sec, rnd); expect(false); } catch (error) { expect(error).toBeInstanceOf(Error); } } }); } }); describe('.recoverPublicKey()', () => { it('should recover public key from recovery bit', async () => { const message = '00000000000000000000000000000000000000000000000000000000deadbeef'; const privateKey = 123456789n; const publicKey = secp.Point.fromHex(secp.getPublicKey(privateKey)).toHex(false); const [signature, recovery] = await secp.sign(message, privateKey, { recovered: true }); const recoveredPubkey = secp.recoverPublicKey(message, signature, recovery); expect(recoveredPubkey).not.toBe(null); expect(recoveredPubkey).toBe(publicKey); expect(secp.verify(signature, message, publicKey)).toBe(true); }); }); describe('.getSharedSecret()', () => { // TODO: Real implementation. function derToPub(der: string) { return der.slice(46); } it('should produce correct results', () => { // TODO: Once der is there, run all tests. for (const vector of ecdh.testGroups[0].tests.slice(0, 230)) { if (vector.result === 'invalid' || vector.private.length !== 64) { expect(() => { secp.getSharedSecret(vector.private, derToPub(vector.public), true); }).toThrowError(); } else if (vector.result === 'valid') { const res = secp.getSharedSecret(vector.private, derToPub(vector.public), true); expect(res.slice(2)).toBe(`${vector.shared}`); } } }); it('priv/pub order matters', () => { for (const vector of ecdh.testGroups[0].tests.slice(0, 100)) { if (vector.result === 'valid') { let priv = vector.private; priv = priv.length === 66 ? priv.slice(2) : priv; expect(() => secp.getSharedSecret(derToPub(vector.public), priv, true)).toThrowError(); } } }); it('rejects invalid keys', () => { expect(() => secp.getSharedSecret('01', '02')).toThrowError(); }); }); describe('utils', () => { it('isValidPrivateKey()', () => { for (const vector of privates.valid.isPrivate) { const { d, expected } = vector; // const privateKey = hexToNumber(d); expect(secp.utils.isValidPrivateKey(d)).toBe(expected); } }); }); describe('wychenproof vectors', () => { it('should pass all tests', async () => { for (let group of wp.testGroups) { const pubKey = secp.Point.fromHex(group.key.uncompressed); for (let test of group.tests) { if (test.result === 'valid') { const hash = await secp.utils.sha256(hexToArray(test.msg)); expect(secp.verify(test.sig, hash, pubKey)).toBeTruthy() } else if (test.result === 'invalid') { let fail = false; const hash = await secp.utils.sha256(hexToArray(test.msg)); try { if (!secp.verify(test.sig, hash, pubKey)) fail = true; } catch (error) { fail = true; } expect(fail).toBeTruthy(); } else { expect(true).toBeTruthy(); } } } }) }) });
the_stack
import { Controller } from './Controller' import { flushMicroTasks } from 'flush-microtasks' import { getFinishedResult } from './AnimationResult' const frameLength = 1000 / 60 describe('Controller', () => { it('can animate a number', async () => { const ctrl = new Controller({ x: 0 }) ctrl.start({ x: 100 }) await global.advanceUntilIdle() const frames = global.getFrames(ctrl) expect(frames).toMatchSnapshot() // The first frame should *not* be the from value. expect(frames[0]).not.toEqual({ x: 0 }) // The last frame should be the goal value. expect(frames.slice(-1)[0]).toEqual({ x: 100 }) }) it('can animate an array of numbers', async () => { const config = { precision: 0.005 } const ctrl = new Controller<{ x: [number, number] }>({ x: [1, 2], config }) ctrl.start({ x: [5, 10] }) await global.advanceUntilIdle() const frames = global.getFrames(ctrl) expect(frames).toMatchSnapshot() // The last frame should be the goal value. expect(frames.slice(-1)[0]).toEqual({ x: [5, 10] }) // The 2nd value is always ~2x the 1st value (within the defined precision). const factors = frames.map(frame => frame.x[1] / frame.x[0]) expect( factors.every(factor => Math.abs(2 - factor) < config.precision) ).toBeTruthy() }) describe('when the "to" prop is an async function', () => { it('respects the "cancel" prop', async () => { const ctrl = new Controller({ from: { x: 0 } }) const promise = ctrl.start({ to: async next => { while (true) { await next({ x: 1, reset: true }) } }, }) const { x } = ctrl.springs await global.advanceUntilValue(x, 0.5) ctrl.start({ cancel: true }) await flushMicroTasks() expect(ctrl.idle).toBeTruthy() expect((await promise).cancelled).toBeTruthy() }) it('respects the "stop" method', async () => { const ctrl = new Controller({ from: { x: 0 } }) const promise = ctrl.start({ to: async next => { while (true) { await next({ x: 1, reset: true }) } }, }) const { x } = ctrl.springs await global.advanceUntilValue(x, 0.5) ctrl.stop() expect(ctrl.idle).toBeTruthy() expect((await promise).finished).toBeFalsy() }) it('respects the "pause" prop', async () => { const ctrl = new Controller({ from: { x: 0 } }) ctrl.start({ pause: true }) let n = 0 ctrl.start({ to: async animate => { while (true) { n += 1 await animate({ x: 1, reset: true }) } }, }) await flushMicroTasks() expect(n).toBe(0) ctrl.start({ pause: false }) await flushMicroTasks() expect(n).toBe(1) }) describe('when the "to" prop is changed', () => { it('stops the old "to" prop', async () => { const ctrl = new Controller({ from: { x: 0 } }) let n = 0 const promise = ctrl.start({ to: async next => { while (++n < 5) { await next({ x: 1, reset: true }) } }, }) await global.advance() expect(n).toBe(1) ctrl.start({ to: () => {}, }) await global.advanceUntilIdle() expect(n).toBe(1) expect(await promise).toMatchObject({ finished: false, }) }) }) // This function is the "to" prop's 1st argument. describe('the "animate" function', () => { it('inherits any default props', async () => { const ctrl = new Controller({ from: { x: 0 } }) const onStart = jest.fn() ctrl.start({ onStart, to: async animate => { expect(onStart).toBeCalledTimes(0) await animate({ x: 1 }) expect(onStart).toBeCalledTimes(1) await animate({ x: 0 }) }, }) await global.advanceUntilIdle() expect(onStart).toBeCalledTimes(2) }) it('can start its own async animation', async () => { const ctrl = new Controller({ from: { x: 0 } }) // Call this from inside the nested "to" prop. const nestedFn = jest.fn() // Call this after the nested "to" prop is done. const afterFn = jest.fn() ctrl.start({ to: async animate => { await animate({ to: async animate => { nestedFn() await animate({ x: 1 }) }, }) afterFn() }, }) await global.advanceUntilIdle() await flushMicroTasks() expect(nestedFn).toBeCalledTimes(1) expect(afterFn).toBeCalledTimes(1) }) }) describe('nested async animation', () => { it('stops the parent on bail', async () => { const ctrl = new Controller({ from: { x: 0 } }) const { x } = ctrl.springs const afterFn = jest.fn() ctrl.start({ to: async animate => { await animate({ to: async animate => { await animate({ x: 1 }) }, }) afterFn() }, }) await global.advanceUntilValue(x, 0.5) ctrl.start({ cancel: true }) await flushMicroTasks() expect(ctrl.idle).toBeTruthy() expect(afterFn).not.toHaveBeenCalled() }) }) describe('while paused', () => { it('stays paused when its values are force-finished', () => { const ctrl = new Controller<{ t: number }>({ t: 0 }) const { t } = ctrl.springs const onRest = jest.fn() ctrl.start({ to: next => next({ t: 1 }), onRest, }) global.mockRaf.step() ctrl.pause() t.finish() global.mockRaf.step() expect(ctrl['_state'].paused).toBeTruthy() expect(onRest).not.toBeCalled() }) }) it('acts strangely without the "from" prop', async () => { const ctrl = new Controller<{ x: number }>() const { springs } = ctrl const promise = ctrl.start({ to: async update => { // The spring does not exist yet! expect(springs.x).toBeUndefined() // Any values passed here are treated as "from" values, // because no "from" prop was ever given. const p1 = update({ x: 1 }) // Now the spring exists! expect(springs.x).toBeDefined() // But the spring is idle! expect(springs.x.idle).toBeTruthy() // This call *will* start an animation! const p2 = update({ x: 2 }) expect(springs.x.idle).toBeFalsy() await Promise.all([p1, p2]) }, }) await Promise.all([global.advanceUntilIdle(), promise]) expect(ctrl.idle).toBeTruthy() // Since we call `update` twice, frames are generated! expect(global.getFrames(ctrl)).toMatchSnapshot() }) describe('when skipAnimations is true', () => { it('should not run at all', async () => { const ctrl = new Controller({ from: { x: 0 } }) let n = 0 global.setSkipAnimation(true) ctrl.start({ to: async next => { while (true) { n += 1 await next({ x: 1, reset: true }) } }, }) await flushMicroTasks() expect(n).toBe(0) }) it('should stop running and push the animation to the finished state when called mid animation', async () => { const ctrl = new Controller({ from: { x: 0 } }) let n = 0 ctrl.start({ to: async next => { while (n < 5) { n++ await next({ x: 10, reset: true }) } }, }) await global.advance() expect(n).toBe(1) global.setSkipAnimation(true) await global.advanceUntilIdle() const { x } = ctrl.springs expect(n).toBe(2) expect(x.get()).toEqual(10) }) }) }) describe('when the "onStart" prop is defined', () => { it('is called once per "start" call maximum', async () => { const ctrl = new Controller({ x: 0, y: 0 }) const onStart = jest.fn() ctrl.start({ x: 1, y: 1, onStart, }) await global.advanceUntilIdle() expect(onStart).toBeCalledTimes(1) }) it('can be different per key', async () => { const ctrl = new Controller({ x: 0, y: 0 }) const onStart1 = jest.fn() ctrl.start({ x: 1, onStart: onStart1 }) const onStart2 = jest.fn() ctrl.start({ y: 1, onStart: onStart2 }) await global.advanceUntilIdle() expect(onStart1).toBeCalledTimes(1) expect(onStart2).toBeCalledTimes(1) }) }) describe('the "loop" prop', () => { it('can be combined with the "reverse" prop', async () => { const ctrl = new Controller({ t: 1, from: { t: 0 }, config: { duration: frameLength * 3 }, }) const { t } = ctrl.springs expect(t.get()).toBe(0) await global.advanceUntilIdle() expect(t.get()).toBe(1) ctrl.start({ loop: { reverse: true }, }) await global.advanceUntilValue(t, 0) await global.advanceUntilValue(t, 1) expect(global.getFrames(t)).toMatchSnapshot() }) describe('used with multiple values', () => { it('loops all values at the same time', async () => { const ctrl = new Controller() ctrl.start({ to: { x: 1, y: 1 }, from: { x: 0, y: 0 }, config: key => ({ frequency: key == 'x' ? 0.3 : 1 }), loop: true, }) const { x, y } = ctrl.springs for (let i = 0; i < 2; i++) { await global.advanceUntilValue(y, 1) // Both values should equal their "from" value at the same time. expect(x.get()).toBe(x.animation.from) expect(y.get()).toBe(y.animation.from) } }) }) describe('used when "to" is', () => { describe('an async function', () => { it('calls the "to" function repeatedly', async () => { const ctrl = new Controller({ t: 0 }) const { t } = ctrl.springs let loop = true let times = 2 // Note: This example is silly, since you could use a for-loop // to more easily achieve the same result, but it tests the ability // to halt a looping script via the "loop" function prop. ctrl.start({ loop: () => loop, to: async next => { await next({ t: 1 }) await next({ t: 0 }) if (times--) return loop = false }, }) await global.advanceUntilValue(t, 1) expect(t.idle).toBeFalsy() for (let i = 0; i < 2; i++) { await global.advanceUntilValue(t, 0) expect(t.idle).toBeFalsy() await global.advanceUntilValue(t, 1) expect(t.idle).toBeFalsy() } await global.advanceUntilValue(t, 0) expect(t.idle).toBeTruthy() }) }) describe('an array', () => { it('repeats the chain of updates', async () => { const ctrl = new Controller({ t: 0 }) const { t } = ctrl.springs let loop = true const promise = ctrl.start({ loop: () => { return loop }, from: { t: 0 }, to: [{ t: 1 }, { t: 2 }], config: { duration: 3000 / 60 }, }) for (let i = 0; i < 3; i++) { await global.advanceUntilValue(t, 2) expect(t.idle).toBeFalsy() // Run the first frame of the next loop. global.mockRaf.step() } loop = false await global.advanceUntilValue(t, 2) expect(t.idle).toBeTruthy() expect(await promise).toMatchObject({ value: { t: 2 }, finished: true, }) }) }) }) describe('used on a noop update', () => { it('does not loop', async () => { const ctrl = new Controller({ t: 0 }) const loop = jest.fn(() => true) ctrl.start({ t: 0, loop }) await global.advanceUntilIdle() expect(loop).toBeCalledTimes(0) }) }) describe('when "finish" is called while paused', () => { async function getPausedLoop() { const ctrl = new Controller<{ t: number }>({ from: { t: 0 }, // FIXME: replace this line with `t: 0,` for a stack overflow loop: { async to(start) { await start({ t: 1, reset: true, }) }, }, }) // Ensure `loop.to` has been called. await flushMicroTasks() // Apply the first frame. global.mockRaf.step() ctrl.pause() return ctrl } it('finishes immediately', async () => { const ctrl = await getPausedLoop() const { t } = ctrl.springs expect(t.get()).toBeLessThan(1) t.finish() expect(t.get()).toBe(1) }) it('does not loop until resumed', async () => { const ctrl = await getPausedLoop() const { t } = ctrl.springs t.finish() expect(t.idle).toBeTruthy() expect(t.get()).toBe(1) // HACK: The internal promise is undefined once resolved. const expectResolved = (isResolved: boolean) => !ctrl['_state'].promise == isResolved // Resume the paused loop. ctrl.resume() // Its promise is not resolved yet.. expectResolved(false) expect(t.idle).toBeTruthy() expect(t.get()).toBe(1) // ..but in the next microtask, it will be.. await flushMicroTasks() expectResolved(true) // ..which means the loop restarts! expect(t.idle).toBeFalsy() expect(t.get()).toBe(0) }) }) }) describe('the "stop" method', () => { it('prevents any updates with pending delays', async () => { const ctrl = new Controller<{ t: number }>({ t: 0 }) const { t } = ctrl.springs ctrl.start({ t: 1, delay: 100 }) ctrl.stop() await global.advanceUntilIdle() expect(ctrl['_state'].timeouts.size).toBe(0) expect(t['_state'].timeouts.size).toBe(0) }) it('stops the active runAsync call', async () => { const ctrl = new Controller<{ t: number }>({ t: 0 }) ctrl.start({ to: async animate => { await animate({ t: 1 }) }, }) ctrl.stop() await global.advanceUntilIdle() expect(ctrl['_state'].asyncTo).toBeUndefined() }) }) describe('events', () => { test('events recieve an AnimationResult and the Controller as the first two args', async () => { const ctrl = new Controller<{ t: number }>({ t: 0 }) const onRest = jest.fn() const onStart = jest.fn() const onChange = jest.fn() ctrl.start({ to: next => next({ t: 1 }), onRest, onStart, onChange, }) global.mockRaf.step() expect(onStart).toBeCalledWith( getFinishedResult({ t: 0.022634843307857987 }, false), ctrl, undefined ) expect(onChange).toBeCalledWith( getFinishedResult(ctrl.get(), false), ctrl, undefined ) await global.advanceUntilIdle() expect(onRest).toBeCalledWith( getFinishedResult(ctrl.get(), true), ctrl, undefined ) }) test('events recieve also recieve the item if set as the third', async () => { const ctrl = new Controller<{ t: number }>({ t: 0 }) const item = { msg: 'hello world', key: 1 } ctrl.item = item const onRest = jest.fn() const onStart = jest.fn() const onChange = jest.fn() ctrl.start({ to: next => next({ t: 1 }), onRest, onStart, onChange, }) global.mockRaf.step() expect(onStart).toBeCalledWith( getFinishedResult({ t: 0.022634843307857987 }, false), ctrl, item ) expect(onChange).toBeCalledWith( getFinishedResult(ctrl.get(), false), ctrl, item ) await global.advanceUntilIdle() expect(onRest).toBeCalledWith( getFinishedResult(ctrl.get(), true), ctrl, item ) }) test('onStart & onRest are flushed even if the `immediate` prop is true', async () => { const onRest = jest.fn() const onStart = jest.fn() const ctrl = new Controller<{ t: number }>({ t: 0, onStart, onRest, }) ctrl.start({ t: 1, immediate: true, }) await global.advanceUntilIdle() expect(ctrl.get().t).toBe(1) expect(onStart).toHaveBeenCalled() expect(onRest).toHaveBeenCalled() }) }) })
the_stack
import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as SDK from '../../core/sdk/sdk.js'; import * as TextUtils from '../../models/text_utils/text_utils.js'; import * as ObjectUI from '../../ui/legacy/components/object_ui/object_ui.js'; import * as TextEditor from '../../ui/legacy/components/text_editor/text_editor.js'; import * as UI from '../../ui/legacy/legacy.js'; import {ConsolePanel} from './ConsolePanel.js'; import consolePromptStyles from './consolePrompt.css.js'; const UIStrings = { /** *@description Text in Console Prompt of the Console panel */ consolePrompt: 'Console prompt', }; const str_ = i18n.i18n.registerUIStrings('panels/console/ConsolePrompt.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class ConsolePrompt extends Common.ObjectWrapper.eventMixin<EventTypes, typeof UI.Widget.Widget>( UI.Widget.Widget) { private addCompletionsFromHistory: boolean; private historyInternal: ConsoleHistoryManager; private initialText: string; private editor: UI.TextEditor.TextEditor|null; private readonly eagerPreviewElement: HTMLDivElement; private textChangeThrottler: Common.Throttler.Throttler; private readonly formatter: ObjectUI.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter; private requestPreviewBound: () => Promise<void>; private readonly innerPreviewElement: HTMLElement; private readonly promptIcon: UI.Icon.Icon; private readonly iconThrottler: Common.Throttler.Throttler; private readonly eagerEvalSetting: Common.Settings.Setting<boolean>; private previewRequestForTest: Promise<void>|null; private defaultAutocompleteConfig: UI.TextEditor.AutocompleteConfig|null; private highlightingNode: boolean; constructor() { super(); this.addCompletionsFromHistory = true; this.historyInternal = new ConsoleHistoryManager(); this.initialText = ''; this.editor = null; this.eagerPreviewElement = document.createElement('div'); this.eagerPreviewElement.classList.add('console-eager-preview'); this.textChangeThrottler = new Common.Throttler.Throttler(150); this.formatter = new ObjectUI.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter(); this.requestPreviewBound = this.requestPreview.bind(this); this.innerPreviewElement = this.eagerPreviewElement.createChild('div', 'console-eager-inner-preview'); this.eagerPreviewElement.appendChild(UI.Icon.Icon.create('smallicon-command-result', 'preview-result-icon')); const editorContainerElement = this.element.createChild('div', 'console-prompt-editor-container'); this.element.appendChild(this.eagerPreviewElement); this.promptIcon = UI.Icon.Icon.create('smallicon-text-prompt', 'console-prompt-icon'); this.element.appendChild(this.promptIcon); this.iconThrottler = new Common.Throttler.Throttler(0); this.eagerEvalSetting = Common.Settings.Settings.instance().moduleSetting('consoleEagerEval'); this.eagerEvalSetting.addChangeListener(this.eagerSettingChanged.bind(this)); this.eagerPreviewElement.classList.toggle('hidden', !this.eagerEvalSetting.get()); this.element.tabIndex = 0; this.previewRequestForTest = null; this.defaultAutocompleteConfig = null; this.highlightingNode = false; const factory = TextEditor.CodeMirrorTextEditor.CodeMirrorTextEditorFactory.instance(); const options = { devtoolsAccessibleName: (i18nString(UIStrings.consolePrompt) as string), lineNumbers: false, lineWrapping: true, mimeType: 'javascript', autoHeight: true, }; this.editor = factory.createEditor((options as UI.TextEditor.Options)); this.defaultAutocompleteConfig = ObjectUI.JavaScriptAutocomplete.JavaScriptAutocompleteConfig.createConfigForEditor(this.editor); this.editor.configureAutocomplete(Object.assign({}, this.defaultAutocompleteConfig, { suggestionsCallback: this.wordsWithQuery.bind(this), anchorBehavior: UI.GlassPane.AnchorBehavior.PreferTop, })); this.editor.widget().element.addEventListener('keydown', this.editorKeyDown.bind(this), true); this.editor.widget().show(editorContainerElement); this.editor.addEventListener(UI.TextEditor.Events.CursorChanged, this.updatePromptIcon, this); this.editor.addEventListener(UI.TextEditor.Events.TextChanged, this.onTextChanged, this); this.editor.addEventListener(UI.TextEditor.Events.SuggestionChanged, this.onTextChanged, this); this.setText(this.initialText); this.initialText = ''; if (this.hasFocus()) { this.focus(); } this.element.removeAttribute('tabindex'); this.editor.widget().element.tabIndex = -1; this.editorSetForTest(); // Record the console tool load time after the console prompt constructor is complete. Host.userMetrics.panelLoaded('console', 'DevTools.Launch.Console'); } private eagerSettingChanged(): void { const enabled = this.eagerEvalSetting.get(); this.eagerPreviewElement.classList.toggle('hidden', !enabled); if (enabled) { this.requestPreview(); } } belowEditorElement(): Element { return this.eagerPreviewElement; } private onTextChanged(): void { // ConsoleView and prompt both use a throttler, so we clear the preview // ASAP to avoid inconsistency between a fresh viewport and stale preview. if (this.eagerEvalSetting.get()) { const asSoonAsPossible = !this.editor || !this.editor.textWithCurrentSuggestion(); this.previewRequestForTest = this.textChangeThrottler.schedule(this.requestPreviewBound, asSoonAsPossible); } this.updatePromptIcon(); this.dispatchEventToListeners(Events.TextChanged); } private async requestPreview(): Promise<void> { if (!this.editor) { return; } const text = this.editor.textWithCurrentSuggestion().trim(); const executionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext); const {preview, result} = await ObjectUI.JavaScriptREPL.JavaScriptREPL.evaluateAndBuildPreview( text, true /* throwOnSideEffect */, true /* replMode */, 500 /* timeout */); this.innerPreviewElement.removeChildren(); if (preview.deepTextContent() !== this.editor.textWithCurrentSuggestion().trim()) { this.innerPreviewElement.appendChild(preview); } if (result && 'object' in result && result.object && result.object.subtype === 'node') { this.highlightingNode = true; SDK.OverlayModel.OverlayModel.highlightObjectAsDOMNode(result.object); } else if (this.highlightingNode) { this.highlightingNode = false; SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight(); } if (result && executionContext) { executionContext.runtimeModel.releaseEvaluationResult(result); } } wasShown(): void { super.wasShown(); this.registerCSSFiles([consolePromptStyles]); } willHide(): void { if (this.highlightingNode) { this.highlightingNode = false; SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight(); } } history(): ConsoleHistoryManager { return this.historyInternal; } clearAutocomplete(): void { if (this.editor) { this.editor.clearAutocomplete(); } } private isCaretAtEndOfPrompt(): boolean { return this.editor !== null && this.editor.selection().collapseToEnd().equal(this.editor.fullRange().collapseToEnd()); } moveCaretToEndOfPrompt(): void { if (this.editor) { this.editor.setSelection(TextUtils.TextRange.TextRange.createFromLocation(Infinity, Infinity)); } } setText(text: string): void { if (this.editor) { this.editor.setText(text); } else { this.initialText = text; } this.dispatchEventToListeners(Events.TextChanged); } text(): string { return this.editor ? this.editor.text() : this.initialText; } setAddCompletionsFromHistory(value: boolean): void { this.addCompletionsFromHistory = value; } private editorKeyDown(event: Event): void { if (!this.editor) { return; } const keyboardEvent = (event as KeyboardEvent); let newText; let isPrevious; // Check against visual coordinates in case lines wrap. const selection = this.editor.selection(); const cursorY = this.editor.visualCoordinates(selection.endLine, selection.endColumn).y; switch (keyboardEvent.keyCode) { case UI.KeyboardShortcut.Keys.Up.code: { const startY = this.editor.visualCoordinates(0, 0).y; if (keyboardEvent.shiftKey || !selection.isEmpty() || cursorY !== startY) { break; } newText = this.historyInternal.previous(this.text()); isPrevious = true; break; } case UI.KeyboardShortcut.Keys.Down.code: { const fullRange = this.editor.fullRange(); const endY = this.editor.visualCoordinates(fullRange.endLine, fullRange.endColumn).y; if (keyboardEvent.shiftKey || !selection.isEmpty() || cursorY !== endY) { break; } newText = this.historyInternal.next(); break; } case UI.KeyboardShortcut.Keys.P.code: { // Ctrl+P = Previous if (Host.Platform.isMac() && keyboardEvent.ctrlKey && !keyboardEvent.metaKey && !keyboardEvent.altKey && !keyboardEvent.shiftKey) { newText = this.historyInternal.previous(this.text()); isPrevious = true; } break; } case UI.KeyboardShortcut.Keys.N.code: { // Ctrl+N = Next if (Host.Platform.isMac() && keyboardEvent.ctrlKey && !keyboardEvent.metaKey && !keyboardEvent.altKey && !keyboardEvent.shiftKey) { newText = this.historyInternal.next(); } break; } case UI.KeyboardShortcut.Keys.Enter.code: { this.enterKeyPressed(keyboardEvent); break; } case UI.KeyboardShortcut.Keys.Tab.code: { if (!this.text()) { keyboardEvent.consume(); } break; } } if (newText === undefined) { return; } keyboardEvent.consume(true); this.setText(newText); if (isPrevious) { this.editor.setSelection(TextUtils.TextRange.TextRange.createFromLocation(0, Infinity)); } else { this.moveCaretToEndOfPrompt(); } } private async enterWillEvaluate(): Promise<boolean> { if (!this.isCaretAtEndOfPrompt()) { return true; } return await ObjectUI.JavaScriptAutocomplete.JavaScriptAutocomplete.isExpressionComplete(this.text()); } private updatePromptIcon(): void { this.iconThrottler.schedule(async () => { const canComplete = await this.enterWillEvaluate(); this.promptIcon.classList.toggle('console-prompt-incomplete', !canComplete); }); } private async enterKeyPressed(event: KeyboardEvent): Promise<void> { if (event.altKey || event.ctrlKey || event.shiftKey) { return; } event.consume(true); // Since we prevent default, manually emulate the native "scroll on key input" behavior. this.element.scrollIntoView(); this.clearAutocomplete(); const str = this.text(); if (!str.length) { return; } if (await this.enterWillEvaluate()) { await this.appendCommand(str, true); } else if (this.editor) { this.editor.newlineAndIndent(); } this.enterProcessedForTest(); } private async appendCommand(text: string, useCommandLineAPI: boolean): Promise<void> { this.setText(''); const currentExecutionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext); if (currentExecutionContext) { const executionContext = currentExecutionContext; const message = SDK.ConsoleModel.ConsoleModel.instance().addCommandMessage(executionContext, text); const expression = ObjectUI.JavaScriptREPL.JavaScriptREPL.preprocessExpression(text); SDK.ConsoleModel.ConsoleModel.instance().evaluateCommandInConsole( executionContext, message, expression, useCommandLineAPI); if (ConsolePanel.instance().isShowing()) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.CommandEvaluatedInConsolePanel); } } } private enterProcessedForTest(): void { } private historyCompletions(prefix: string, force?: boolean): UI.SuggestBox.Suggestions { const text = this.text(); if (!this.addCompletionsFromHistory || !this.isCaretAtEndOfPrompt() || (!text && !force)) { return []; } const result = []; const set = new Set<string>(); const data = this.historyInternal.historyData(); for (let i = data.length - 1; i >= 0 && result.length < 50; --i) { const item = data[i]; if (!item.startsWith(text)) { continue; } if (set.has(item)) { continue; } set.add(item); result.push( {text: item.substring(text.length - prefix.length), iconType: 'smallicon-text-prompt', isSecondary: true}); } return result as UI.SuggestBox.Suggestions; } focus(): void { if (this.editor) { this.editor.widget().focus(); } else { this.element.focus(); } } private async wordsWithQuery( queryRange: TextUtils.TextRange.TextRange, substituteRange: TextUtils.TextRange.TextRange, force?: boolean): Promise<UI.SuggestBox.Suggestions> { if (!this.editor || !this.defaultAutocompleteConfig || !this.defaultAutocompleteConfig.suggestionsCallback) { return []; } const query = this.editor.text(queryRange); const words = await this.defaultAutocompleteConfig.suggestionsCallback(queryRange, substituteRange, force); const historyWords = this.historyCompletions(query, force); return words ? words.concat(historyWords) : historyWords; } private editorSetForTest(): void { } } export class ConsoleHistoryManager { private data: string[]; private historyOffset: number; private uncommittedIsTop?: boolean; constructor() { this.data = []; /** * 1-based entry in the history stack. */ this.historyOffset = 1; } historyData(): string[] { return this.data; } setHistoryData(data: string[]): void { this.data = data.slice(); this.historyOffset = 1; } /** * Pushes a committed text into the history. */ pushHistoryItem(text: string): void { if (this.uncommittedIsTop) { this.data.pop(); delete this.uncommittedIsTop; } this.historyOffset = 1; if (text === this.currentHistoryItem()) { return; } this.data.push(text); } /** * Pushes the current (uncommitted) text into the history. */ private pushCurrentText(currentText: string): void { if (this.uncommittedIsTop) { this.data.pop(); } // Throw away obsolete uncommitted text. this.uncommittedIsTop = true; this.data.push(currentText); } previous(currentText: string): string|undefined { if (this.historyOffset > this.data.length) { return undefined; } if (this.historyOffset === 1) { this.pushCurrentText(currentText); } ++this.historyOffset; return this.currentHistoryItem(); } next(): string|undefined { if (this.historyOffset === 1) { return undefined; } --this.historyOffset; return this.currentHistoryItem(); } private currentHistoryItem(): string|undefined { return this.data[this.data.length - this.historyOffset]; } } export const enum Events { TextChanged = 'TextChanged', } export type EventTypes = { [Events.TextChanged]: void, };
the_stack
import { Menu, MenuTrigger } from "@components/menu"; import { act, fireEvent, waitFor } from "@testing-library/react"; import { Button } from "@components/button"; import { Item } from "@components/collection"; import { Keys } from "@components/shared"; import { Transition } from "@components/transition"; import { createRef } from "react"; import { renderWithTheme } from "@jest-utils"; import userEvent from "@testing-library/user-event"; // Using "beforeEach" instead of "beforeAll" because the restore focus tests currently need the fade out animation to works properly. beforeEach(() => { // @ts-ignore Transition.disableAnimation = true; }); // ***** Behaviors ***** test("when a menu open and there is no selected item, the first item is focused", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("earth-item")).toHaveFocus()); }); test("when a menu open and there is a selected item, the selected item is focused", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu defaultSelectedKeys={["mars"]} selectionMode="single"> <Item key="earth">Earth</Item> <Item key="mars" data-testid="mars-item">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("mars-item")).toHaveFocus()); }); test("when a menu open with arrow down keypress and there is no selected item, the first item is focused", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.arrowDown }); }); await waitFor(() => expect(getByTestId("earth-item")).toHaveFocus()); }); test("when a menu open with arrow down keypress and there is a selected item, the selected item is focused", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu defaultSelectedKeys={["mars"]} selectionMode="single"> <Item key="earth">Earth</Item> <Item key="mars" data-testid="mars-item">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.arrowDown }); }); await waitFor(() => expect(getByTestId("mars-item")).toHaveFocus()); }); test("when a menu open with arrow up keypress and there is no selected item, the last item is focused", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn" data-testid="saturn-item">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.arrowUp }); }); await waitFor(() => expect(getByTestId("saturn-item")).toHaveFocus()); }); test("when a menu open with arrow up keypress and there is a selected item, the selected item is focused", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu defaultSelectedKeys={["mars"]} selectionMode="single"> <Item key="earth">Earth</Item> <Item key="mars" data-testid="mars-item">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.arrowUp }); }); await waitFor(() => expect(getByTestId("mars-item")).toHaveFocus()); }); test("when selectionMode is \"none\", selecting an item close the menu", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu selectionMode="none" data-testid="menu"> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { userEvent.click(getByTestId("trigger")); }); act(() => { userEvent.click(getByTestId("earth-item")); }); await waitFor(() => expect(queryByTestId("menu")).not.toBeInTheDocument()); }); test("when selectionMode is \"single\", selecting an item close the menu", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu selectionMode="single" data-testid="menu"> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { userEvent.click(getByTestId("trigger")); }); act(() => { userEvent.click(getByTestId("earth-item")); }); await waitFor(() => expect(queryByTestId("menu")).not.toBeInTheDocument()); }); test("when selectionMode is \"multiple\", selecting an item close the menu", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu selectionMode="single" data-testid="menu"> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { userEvent.click(getByTestId("trigger")); }); act(() => { userEvent.click(getByTestId("earth-item")); }); await waitFor(() => expect(queryByTestId("menu")).not.toBeInTheDocument()); }); test("selecting an item focus the trigger", async () => { // @ts-ignore Transition.disableAnimation = false; const { getByTestId } = renderWithTheme( <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu selectionMode="single" data-testid="menu"> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { userEvent.click(getByTestId("trigger")); }); act(() => { userEvent.click(getByTestId("earth-item")); }); await waitFor(() => expect(getByTestId("trigger")).toHaveFocus()); }); test("when closeOnSelect is false, selecting an item doesn't close the menu", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger closeOnSelect={false} defaultOpen> <Button>Trigger</Button> <Menu data-testid="menu"> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { userEvent.click(getByTestId("earth-item")); }); await waitFor(() => expect(getByTestId("menu")).toBeInTheDocument()); }); test("when opened, on tab keydown, close and select the next tabbable element", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <> <Button>Previous</Button> <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu data-testid="menu"> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> <Button data-testid="after">After</Button> </> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("menu")).toBeInTheDocument()); act(() => { getByTestId("earth-item").focus(); }); act(() => { userEvent.tab(); }); await waitFor(() => expect(queryByTestId("menu")).not.toBeInTheDocument()); await waitFor(() => expect(getByTestId("after")).toHaveFocus()); }); test("when opened, on shift+tab keydown close and select the previous tabbable element", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <> <Button data-testid="previous">Previous</Button> <MenuTrigger> <Button data-testid="trigger">Trigger</Button> <Menu data-testid="menu"> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> <Button>After</Button> </> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("menu")).toBeInTheDocument()); act(() => { getByTestId("earth-item").focus(); }); act(() => { userEvent.tab({ shift: true }); }); await waitFor(() => expect(queryByTestId("menu")).not.toBeInTheDocument()); await waitFor(() => expect(getByTestId("previous")).toHaveFocus()); }); // ***** Aria ***** test("a menu trigger have an aria-haspopup attribute", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger defaultOpen> <Button data-testid="trigger">Trigger</Button> <Menu> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); await waitFor(() => expect(getByTestId("trigger")).toHaveAttribute("aria-haspopup", "menu")); }); test("when a trigger have an aria-labelledby attribute, the menu aria-labelledby match the trigger aria-labelledby attribute", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger defaultOpen> <Button aria-labelledby="trigger-label">Trigger</Button> <Menu data-testid="menu"> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); await waitFor(() => expect(getByTestId("menu")).toHaveAttribute("aria-labelledby", "trigger-label")); }); test("when a trigger doesn't have a aria-labelledby attribute, the menu aria-labelledby match the trigger id", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger defaultOpen> <Button id="trigger-id">Trigger</Button> <Menu data-testid="menu"> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); await waitFor(() => expect(getByTestId("menu")).toHaveAttribute("aria-labelledby", "trigger-id")); }); test("when a trigger have a aria-describedby attribute, the menu aria-describedby match the trigger aria-describedby attribute", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger defaultOpen> <Button aria-describedby="trigger-description">Trigger</Button> <Menu data-testid="menu"> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); await waitFor(() => expect(getByTestId("menu")).toHaveAttribute("aria-describedby", "trigger-description")); }); test("when a trigger have an id, use this id for the trigger", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger> <Button id="trigger-id" data-testid="trigger">Trigger</Button> <Menu> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); await waitFor(() => expect(getByTestId("trigger")).toHaveAttribute("id", "trigger-id")); }); test("when a trigger doesn't have an id, a trigger id is autogenerated", async () => { const { getByTestId } = renderWithTheme( <MenuTrigger> <Button id="trigger-id" data-testid="trigger">Trigger</Button> <Menu> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); await waitFor(() => expect(getByTestId("trigger")).toHaveAttribute("id")); }); // ***** Api ***** test("call onOpenChange when the menu open", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <MenuTrigger onOpenChange={handler}> <Button data-testid="trigger">Trigger</Button> <Menu data-testid="menu"> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything(), true)); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("call onOpenChange when the menu close", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <MenuTrigger onOpenChange={handler} defaultOpen > <Button data-testid="trigger">Trigger</Button> <Menu data-testid="menu"> <Item key="earth" data-testid="earth-item">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); act(() => { getByTestId("earth-item").focus(); }); act(() => { fireEvent.keyDown(getByTestId("earth-item"), { key: Keys.esc }); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything(), false)); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); // ***** Refs ***** test("ref is a DOM element", async () => { const ref = createRef<HTMLElement>(); renderWithTheme( <MenuTrigger defaultOpen ref={ref}> <Button>Trigger</Button> <Menu> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); await waitFor(() => expect(ref.current).not.toBeNull()); expect(ref.current instanceof HTMLElement).toBeTruthy(); expect(ref.current.tagName).toBe("DIV"); }); test("when using a callback ref, ref is a DOM element", async () => { let refNode: HTMLElement = null; renderWithTheme( <MenuTrigger defaultOpen ref={node => { refNode = node; }} > <Button>Trigger</Button> <Menu> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); await waitFor(() => expect(refNode).not.toBeNull()); expect(refNode instanceof HTMLElement).toBeTruthy(); expect(refNode.tagName).toBe("DIV"); }); test("set ref once", async () => { const handler = jest.fn(); renderWithTheme( <MenuTrigger defaultOpen ref={handler} > <Button>Trigger</Button> <Menu> <Item key="earth">Earth</Item> <Item key="mars">Mars</Item> <Item key="saturn">Saturn</Item> </Menu> </MenuTrigger> ); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); });
the_stack
import { Annotation, AnnotationType, ImageSize, NewAnnotation, Position2D } from "./common"; import SVGControls from "./controls"; import Element from "./element"; import ElementCreate from "./element-create"; import EpipolarPoint from "./epipolar-point"; import "./main.css"; import Point from "./point"; import PointCreate from "./point-create"; import Polygon from "./polygon"; import PolygonCreate from "./polygon-create"; import Rect from "./rect"; import RectCreate from "./rect-create"; import { getImageSize, getNode, getSVGPoint } from "./util"; const createElement = (type: AnnotationType, parent: ImageAnnotation) => { switch (type) { case "POINT": return new Point(parent); case "RECTANGLE": return new Rect(parent); case "POLYGON": return new Polygon(parent); case "EPIPOLAR_POINT": return new EpipolarPoint(parent); default: } }; const createNewElement = ( annotation: NewAnnotation, parent: ImageAnnotation, drawCanvas: SVGRectElement ) => { switch (annotation.type) { case "POINT": return new PointCreate(annotation, parent, drawCanvas); case "RECTANGLE": return new RectCreate(annotation, parent, drawCanvas); case "POLYGON": return new PolygonCreate(annotation, parent, drawCanvas); default: } }; interface Elements { svg: SVGSVGElement; container: SVGGElement; drawCanvas: SVGRectElement; annotationsContainer: SVGGElement; drawingAnnotationsContainer: SVGGElement; outsideCanvas: SVGRectElement; image: SVGImageElement; defs: SVGDefsElement; filterBrightness: { feFuncR: SVGFEFuncRElement; feFuncG: SVGFEFuncGElement; feFuncB: SVGFEFuncBElement; }; } interface Options { image: string; annotations?: Annotation[]; imageBrightness?: number; controlled?: boolean; showControls?: boolean; showLabels?: boolean | "always" | "hover"; scale?: number; minScale?: number; maxScale?: number; maxScaleClick?: number; outsideCanvas?: number; strokeWidth?: number; selectedAnnotationStrokeWidth?: number; outsideCanvasColor?: string; selectedAnnotation?: null; annotationChanged?: any; annotationCreated?: any; annotationSelected?: any; zoomSensibility?: number; } interface OptionsUpdate { image?: string; annotations?: Annotation[]; imageBrightness?: number; controlled?: boolean; showControls?: boolean; showLabels?: boolean; scale?: number; minScale?: number; maxScale?: number; maxScaleClick?: number; outsideCanvas?: number; strokeWidth?: number; selectedAnnotationStrokeWidth?: number; outsideCanvasColor?: string; selectedAnnotation?: null; annotationChanged?: any; annotationCreated?: any; annotationSelected?: any; zoomSensibility?: number; } interface Status { annotations: Annotation[]; imageSize: ImageSize; scale: number; translateX: number; translateY: number; drawing: ElementCreate<NewAnnotation>; ready: boolean; id: number; selectedAnnotation: string; busy: number; centered: boolean; } type AnnotationCache = { [key: string]: Element<Annotation> }; class ImageAnnotation { annotationCache: AnnotationCache = {}; controls: SVGControls = null; elements: Elements = { svg: null, container: null, drawCanvas: null, annotationsContainer: null, drawingAnnotationsContainer: null, outsideCanvas: null, image: null, defs: null, filterBrightness: null }; options: Options = { image: null, annotations: [], imageBrightness: 0, controlled: false, showControls: true, showLabels: false, scale: 1, minScale: 0.5, maxScale: 2, maxScaleClick: 2, outsideCanvas: 0, strokeWidth: 1, selectedAnnotationStrokeWidth: 2, outsideCanvasColor: "rgba(0,0,255,0.1)", selectedAnnotation: null, annotationChanged: null, annotationCreated: null, annotationSelected: null, zoomSensibility: 1 }; status: Status = { annotations: null, imageSize: null, scale: null, translateX: 0, translateY: 0, drawing: null, ready: false, id: null, selectedAnnotation: null, busy: null, centered: false }; constructor(svg: SVGSVGElement, options: Options) { if (!svg || !options || !options.image) { throw new Error("svg and options.image are required"); } this.elements.svg = svg; this.elements.svg.style.width = "100%"; this.elements.svg.style.height = "100%"; this.elements.svg.style.fontSize = "8pt"; this.status.id = Math.random(); this.elements.defs = getNode("defs") as SVGDefsElement; const filterBrightness = getNode("filter", { id: this.status.id + "_imageBrightness" }); const feComponentTransfer = getNode("feComponentTransfer"); this.elements.filterBrightness = { feFuncR: getNode("feFuncR", { type: "gamma", exponent: "1" }) as SVGFEFuncRElement, feFuncG: getNode("feFuncG", { type: "gamma", exponent: "1" }) as SVGFEFuncGElement, feFuncB: getNode("feFuncB", { type: "gamma", exponent: "1" }) as SVGFEFuncBElement }; feComponentTransfer.appendChild(this.elements.filterBrightness.feFuncR); feComponentTransfer.appendChild(this.elements.filterBrightness.feFuncG); feComponentTransfer.appendChild(this.elements.filterBrightness.feFuncB); filterBrightness.appendChild(feComponentTransfer); this.elements.defs.appendChild(filterBrightness); this.options = { ...this.options, ...options }; this.status.scale = this.options.scale; this.status.annotations = this.options.annotations; this.status.selectedAnnotation = this.options.selectedAnnotation; this.controls = new SVGControls(this); getImageSize(this.options.image).then(this._setup); } _setup = (imageSize: ImageSize) => { this.status.imageSize = imageSize; this.elements.container = getNode("g") as SVGGElement; this.elements.annotationsContainer = getNode("g") as SVGGElement; this.elements.drawingAnnotationsContainer = getNode("g") as SVGGElement; this._setupOutsideCanvas(); this._setupImage(); this._setupDrawCanvas(); this._setupListeners(); this._centerAndScale(); this.status.ready = true; }; _setupOutsideCanvas() { const { outsideCanvas, outsideCanvasColor } = this.options; const { imageSize } = this.status; this.elements.outsideCanvas = getNode("rect", { x: "0", y: "0", width: (imageSize.width + imageSize.width * outsideCanvas).toString(), height: (imageSize.height + imageSize.height * outsideCanvas).toString(), fill: outsideCanvasColor }) as SVGRectElement; } _setupImage() { const { image, outsideCanvas } = this.options; const { imageSize, id } = this.status; const { annotationsContainer } = this.elements; const translateX = (imageSize.width * outsideCanvas) / 2; const translateY = (imageSize.height * outsideCanvas) / 2; const transform = `translate(${translateX},${translateY})`; annotationsContainer.setAttributeNS(null, "transform", transform); this.elements.image = getNode("image", { x: "0", y: "0", width: imageSize.width.toString(), height: imageSize.height.toString(), "xlink:href": image, filter: `url(#${id}_imageBrightness)` }) as SVGImageElement; annotationsContainer.appendChild(this.elements.image); } _setupDrawCanvas() { const { outsideCanvas } = this.options; const { imageSize } = this.status; const { drawingAnnotationsContainer } = this.elements; const translateX = (imageSize.width * outsideCanvas) / 2; const translateY = (imageSize.height * outsideCanvas) / 2; const transform = `translate(${translateX},${translateY})`; drawingAnnotationsContainer.setAttributeNS(null, "transform", transform); this.elements.drawCanvas = getNode("rect", { x: "0", y: "0", width: (imageSize.width + imageSize.width * outsideCanvas).toString(), height: (imageSize.height + imageSize.height * outsideCanvas).toString(), fill: "rgba(0,0,0,0.0001)" }) as SVGRectElement; this.elements.drawCanvas.style.cursor = "crosshair"; } _svgSize() { const { svg } = this.elements; const parentStyle = getComputedStyle(svg); const width = parseFloat(parentStyle.getPropertyValue("width")); const height = parseFloat(parentStyle.getPropertyValue("height")); return { width, height }; } _calculateMinScale() { const { imageSize } = this.status; const { outsideCanvas, minScale, maxScale } = this.options; const svgSize = this._svgSize(); const canvasWidth = imageSize.width * (1 + outsideCanvas / 3); const canvasHeight = imageSize.height * (1 + outsideCanvas / 3); const scale = Math.max( Math.min( svgSize.width / canvasWidth, svgSize.height / canvasHeight, maxScale ), minScale ); return scale; } _centerAndScale() { const svgSize = this._svgSize(); const { imageSize } = this.status; const { outsideCanvas } = this.options; const scale = this._calculateMinScale(); const offsetX = (svgSize.width - (imageSize.width + imageSize.width * outsideCanvas) * scale) / 2; const offsetY = (svgSize.height - (imageSize.height + imageSize.height * outsideCanvas) * scale) / 2; const ctm = this._getCTM(); ctm.a = scale; ctm.d = scale; ctm.e = offsetX; ctm.f = offsetY; this._setCTM(ctm); this.status.centered = true; } _setupListeners() { this._setupKeyboardListeners(); this._setupMouseListeners(); this._setupWheelZoom(); this._setupDrag(); } _handleMousedown = (evt: MouseEvent) => { if (evt.ctrlKey) { const { svg } = this.elements; const { maxScaleClick } = this.options; const { scale, centered } = this.status; if (!centered) { this._centerAndScale(); } else { const svgpoint = getSVGPoint(svg, evt); const position = svgpoint.matrixTransform(svg.getScreenCTM().inverse()); this._zoomAndPan(maxScaleClick / scale, position); } } }; _setupMouseListeners() { this.elements.svg.addEventListener("mousedown", this._handleMousedown); } _handleKeydownEvent = (evt: KeyboardEvent) => { const { container } = this.elements; if (evt.shiftKey) { container.setAttribute("class", "shift-key"); } if (evt.altKey) { container.setAttribute("class", "alt-key"); } }; _handleKeyupEvent = (evt: KeyboardEvent) => { const { container } = this.elements; container.setAttribute("class", ""); }; _setupKeyboardListeners() { window.addEventListener("keydown", this._handleKeydownEvent); window.addEventListener("keyup", this._handleKeyupEvent); } _cleanListeners() { window.removeEventListener("keydown", this._handleKeydownEvent); window.removeEventListener("keyup", this._handleKeyupEvent); this.elements.svg.removeEventListener("mousedown", this._handleMousedown); } _calculateZoom(sign: number) { return 1 + 0.1 * Math.sign(sign) * this.options.zoomSensibility; } _setupWheelZoom() { const { svg } = this.elements; svg.onwheel = evt => { const { maxScale } = this.options; const { scale } = this.status; evt.stopPropagation(); evt.preventDefault(); const svgpoint = getSVGPoint(svg, evt); const position = svgpoint.matrixTransform(svg.getScreenCTM().inverse()); let zoom = this._calculateZoom(evt.deltaY > 0 ? 1 : -1); const newScale = zoom * scale; const minScale = this._calculateMinScale(); if (newScale > maxScale) { zoom = maxScale / scale; } else if (newScale < minScale) { zoom = minScale / scale; } this._zoomAndPan(zoom, position); }; } _setupDrag() { const { svg } = this.elements; svg.onmousedown = evt => { if (evt.button !== 0) { return; } evt.stopPropagation(); evt.preventDefault(); let up = false; let previousX = evt.clientX; let previousY = evt.clientY; const mouseMoveHandler = (evt: MouseEvent) => { evt.stopPropagation(); evt.preventDefault(); this._pan({ x: evt.clientX - previousX, y: evt.clientY - previousY }); previousX = evt.clientX; previousY = evt.clientY; }; const mouseUpHandler = (evt: MouseEvent) => { evt.stopPropagation(); evt.preventDefault(); up = true; window.removeEventListener("mousemove", mouseMoveHandler); window.removeEventListener("mouseup", mouseUpHandler); }; window.addEventListener("mouseup", mouseUpHandler); setTimeout(() => { if (!up) { window.addEventListener("mousemove", mouseMoveHandler); } }, 150); }; } _zoom(zoom: number) { const { svg } = this.elements; const { scale } = this.status; const { maxScale } = this.options; const minScale = this._calculateMinScale(); const newScale = zoom * scale; if (newScale > maxScale) { zoom = maxScale / scale; } else if (newScale < minScale) { zoom = minScale / scale; } const parentStyle = getComputedStyle(svg); const svgWidth = parseFloat(parentStyle.getPropertyValue("width")); const svgHeight = parseFloat(parentStyle.getPropertyValue("height")); const svgpoint = svg.createSVGPoint(); svgpoint.x = svgWidth / 2; svgpoint.y = svgHeight / 2; this._zoomAndPan(zoom, svgpoint); } _pan(position: Position2D) { const ctm = this._getCTM(); ctm.e = ctm.e + position.x; ctm.f = ctm.f + position.y; this._setCTM(ctm); this.status.centered = false; } _zoomAndPan(zoom: number, position: SVGPoint) { const { svg } = this.elements; const ctm = this._getCTM(); const relativePosition = position.matrixTransform(ctm.inverse()); const modifier = svg .createSVGMatrix() .translate(relativePosition.x, relativePosition.y) .scale(zoom) .translate(-relativePosition.x, -relativePosition.y); const newCTM = ctm.multiply(modifier); this._setCTM(newCTM); this.status.centered = false; } _getCTM() { const { svg } = this.elements; const { scale, translateX, translateY } = this.status; const ctm = svg.createSVGMatrix(); ctm.a = scale; ctm.b = 0; ctm.c = 0; ctm.d = scale; ctm.e = translateX; ctm.f = translateY; return ctm; } _setCTM(ctm: SVGMatrix) { const status = this.status; status.scale = ctm.a; status.translateX = ctm.e; status.translateY = ctm.f; this._render(); } _getContainerTransform() { const { scale, translateX, translateY } = this.status; return `translate(${translateX}, ${translateY}) scale(${scale})`; } _getImagePosition(evt: MouseEvent) { const { svg, outsideCanvas, image } = this.elements; const svgpoint = getSVGPoint(svg, evt); const positionOffset = svgpoint.matrixTransform( outsideCanvas.getScreenCTM().inverse() ); positionOffset.x = Math.min( positionOffset.x, parseFloat(outsideCanvas.getAttributeNS(null, "width")) ); positionOffset.x = Math.max(positionOffset.x, 0); positionOffset.y = Math.min( positionOffset.y, parseFloat(outsideCanvas.getAttributeNS(null, "height")) ); positionOffset.y = Math.max(positionOffset.y, 0); svgpoint.x = positionOffset.x; svgpoint.y = positionOffset.y; const fixedScreenPosition = svgpoint.matrixTransform( outsideCanvas.getScreenCTM() ); svgpoint.x = fixedScreenPosition.x; svgpoint.y = fixedScreenPosition.y; const position = svgpoint.matrixTransform(image.getScreenCTM().inverse()); return position; } _annotationChanged(changed: Annotation) { const { annotationChanged, controlled } = this.options; const { annotations } = this.status; let update = !controlled; if (annotationChanged) { if (annotationChanged(changed) === false) { update = false; } } if (update) { const index = annotations.findIndex( annotation => annotation.id === changed.id ); if (index !== -1) { annotations.splice(index, 1, changed); } } this._render(); } _annotationCreated(created: Annotation) { const { annotationCreated, controlled } = this.options; const { annotations } = this.status; let update = !controlled; this.status.drawing.destroy(); this.status.drawing = null; if (annotationCreated) { if (annotationCreated(created) === false) { update = false; } } if (update) { annotations.push(created); } this._render(); } _annotationSelected(selected: Annotation) { const { annotationSelected, controlled } = this.options; let update = !controlled; if (annotationSelected) { if (annotationSelected(selected) === false) { update = false; } } if (update) { this.status.selectedAnnotation = selected.id; } this._render(); } _sortAnnotations(annotations: Annotation[], selectedAnnotation: string) { const sorted = annotations.sort((a, b) => { // Annotations with higher index are rendered on higher positions if (a.id === selectedAnnotation) { return 1; } else if (b.id === selectedAnnotation) { return -1; } else if (a.selectable && !b.selectable) { return 1; } else if (!a.selectable && b.selectable) { return -1; } else { return 0; } }); return sorted; } _updateBrightness() { const { imageBrightness } = this.options; const { filterBrightness } = this.elements; const exponent = imageBrightness === 0 ? 1 : imageBrightness > 0 ? 1 - imageBrightness * 0.1 : 1 + Math.abs(imageBrightness) * 0.15; filterBrightness.feFuncR.setAttributeNS( null, "exponent", exponent.toString() ); filterBrightness.feFuncG.setAttributeNS( null, "exponent", exponent.toString() ); filterBrightness.feFuncB.setAttributeNS( null, "exponent", exponent.toString() ); } _render() { if (this.status.busy) { window.cancelAnimationFrame(this.status.busy); } this.status.busy = window.requestAnimationFrame(() => this._renderExecute() ); } _renderExecute() { const { container, defs, outsideCanvas, annotationsContainer, image, svg, drawCanvas, drawingAnnotationsContainer } = this.elements; const { showControls } = this.options; const { drawing, selectedAnnotation } = this.status; container.setAttributeNS(null, "transform", this._getContainerTransform()); const annotations = this._sortAnnotations( this.status.annotations, selectedAnnotation ); while (svg.firstChild) { svg.removeChild(svg.firstChild); } svg.appendChild(defs); svg.appendChild(container); while (container.firstChild) { container.removeChild(container.firstChild); } container.appendChild(outsideCanvas); container.appendChild(annotationsContainer); while (annotationsContainer.firstChild) { annotationsContainer.removeChild(annotationsContainer.firstChild); } annotationsContainer.appendChild(image); while (drawingAnnotationsContainer.firstChild) { drawingAnnotationsContainer.removeChild( drawingAnnotationsContainer.firstChild ); } container.setAttributeNS(null, "transform", this._getContainerTransform()); this._updateBrightness(); for (let annotation of annotations) { const element = this.annotationCache[annotation.id] || createElement(annotation.type, this); element.setSelected(selectedAnnotation === annotation.id); element.setAnnotation(annotation); this.annotationCache[annotation.id] = element; const rendered = element.getDomElement(); if (element instanceof Point) { element.update(); } rendered && annotationsContainer.appendChild(rendered); } if (drawing) { if (drawing instanceof PointCreate) { drawing.update(); } container.appendChild(drawCanvas); drawingAnnotationsContainer.appendChild(drawing.getDomElement()); container.appendChild(drawingAnnotationsContainer); } if (showControls) { svg.appendChild(this.controls.getDomElement()); } } drawAnnotation(annotation: NewAnnotation) { const { ready } = this.status; if (ready) { this._drawAnnotation(annotation); } else { setTimeout(() => { this.drawAnnotation(annotation); }, 10); } } _drawAnnotation(annotation: NewAnnotation) { const { drawCanvas } = this.elements; const status = this.status; if (status.drawing) { this._stopDrawing(); } if (annotation === null) { this._render(); return; } annotation.properties = annotation.properties || {}; annotation.properties.style = annotation.properties.style || {}; this.status.drawing = createNewElement(annotation, this, drawCanvas); this._render(); } _stopDrawing() { const status = this.status; if (status.drawing) { status.drawing.destroy(); } status.drawing = null; } setAnnotations(annotations: Annotation[]) { this.setOptions({ annotations }); } getAnnotations() { return this.status.annotations; } setOptions(newOptions: OptionsUpdate = {}) { const { ready } = this.status; if (ready) { this._setOptions(newOptions); } else { setTimeout(() => { this.setOptions(newOptions); }, 10); } } _setOptions(newOptions: OptionsUpdate = {}) { const options = this.options; const status = this.status; let renderCanvas = false; let render = false; // annotations if ( newOptions.annotations && newOptions.annotations !== options.annotations ) { render = true; options.annotations = newOptions.annotations; status.annotations = newOptions.annotations; // Update cache of elements const newCache: AnnotationCache = {}; newOptions.annotations.forEach(annotation => { const cached = this.annotationCache[annotation.id]; if (cached) { newCache[annotation.id] = cached; } }); Object.keys(this.annotationCache) .filter(key => !newCache[key]) .forEach(key => this.annotationCache[key].destroy()); this.annotationCache = newCache; } // imageBrightness if ( newOptions.imageBrightness !== undefined && newOptions.imageBrightness !== options.imageBrightness ) { render = true; options.imageBrightness = newOptions.imageBrightness; } // strokeWidth if ( newOptions.strokeWidth !== undefined && newOptions.strokeWidth !== options.strokeWidth ) { render = true; options.strokeWidth = newOptions.strokeWidth; } // selectedAnnotationStrokeWidth if ( newOptions.selectedAnnotationStrokeWidth !== undefined && newOptions.selectedAnnotationStrokeWidth !== options.selectedAnnotationStrokeWidth ) { render = true; options.selectedAnnotationStrokeWidth = newOptions.selectedAnnotationStrokeWidth; } // controlled if ( newOptions.controlled !== undefined && newOptions.controlled !== options.controlled ) { options.controlled = newOptions.controlled; } // showControls if ( newOptions.showControls !== undefined && newOptions.showControls !== options.showControls ) { render = true; options.showControls = newOptions.showControls; } // scale if (newOptions.scale !== undefined && newOptions.scale !== options.scale) { render = true; options.scale = newOptions.scale; status.scale = newOptions.scale; } // minScale if ( newOptions.minScale !== undefined && newOptions.minScale !== options.minScale ) { options.minScale = newOptions.minScale; } // maxScale if ( newOptions.maxScale !== undefined && newOptions.maxScale !== options.maxScale ) { options.maxScale = newOptions.maxScale; } // maxScaleClick if ( newOptions.maxScaleClick !== undefined && newOptions.maxScaleClick !== options.maxScaleClick ) { options.maxScaleClick = newOptions.maxScaleClick; } // zoomSensibility if ( newOptions.zoomSensibility !== undefined && newOptions.zoomSensibility !== options.zoomSensibility ) { options.zoomSensibility = newOptions.zoomSensibility; } // outsideCanvas if ( newOptions.outsideCanvas !== undefined && newOptions.outsideCanvas !== options.outsideCanvas ) { renderCanvas = true; options.outsideCanvas = newOptions.outsideCanvas; } // selectedAnnotation if ( newOptions.selectedAnnotation !== undefined && newOptions.selectedAnnotation !== options.selectedAnnotation ) { render = true; options.selectedAnnotation = newOptions.selectedAnnotation; status.selectedAnnotation = newOptions.selectedAnnotation; } // annotationChanged if ( newOptions.annotationChanged !== undefined && newOptions.annotationChanged !== options.annotationChanged ) { options.annotationChanged = newOptions.annotationChanged; } // annotationCreated if ( newOptions.annotationCreated !== undefined && newOptions.annotationCreated !== options.annotationCreated ) { options.annotationCreated = newOptions.annotationCreated; } // annotationSelected if ( newOptions.annotationSelected !== undefined && newOptions.annotationSelected !== options.annotationSelected ) { options.annotationSelected = newOptions.annotationSelected; } // showLabels if ( newOptions.showLabels !== undefined && newOptions.showLabels !== options.showLabels ) { options.showLabels = newOptions.showLabels; } // image if (newOptions.image !== undefined && options.image !== newOptions.image) { options.image = newOptions.image; getImageSize(options.image).then(this._setup); } else if (renderCanvas) { this._setup(status.imageSize); } else if (render) { this._render(); } } destroy() { this._stopDrawing(); this._cleanListeners(); } } export default ImageAnnotation;
the_stack
import debugFactory from 'debug'; import getRawBody from 'raw-body'; import crypto from 'crypto'; import timingSafeCompare from 'tsscmp'; import { IncomingMessage, ServerResponse } from 'http'; import { packageIdentifier, isFalsy } from './util'; import SlackEventAdapter from './adapter'; const debug = debugFactory('@slack/events-api:http-handler'); /** * A dictionary of codes for errors produced by this package. */ export enum ErrorCode { SignatureVerificationFailure = 'SLACKHTTPHANDLER_REQUEST_SIGNATURE_VERIFICATION_FAILURE', RequestTimeFailure = 'SLACKHTTPHANDLER_REQUEST_TIMELIMIT_FAILURE', BodyParserNotPermitted = 'SLACKADAPTER_BODY_PARSER_NOT_PERMITTED_FAILURE', } /** Some HTTP response statuses. */ enum ResponseStatus { Ok = 200, Redirect = 302, NotFound = 404, Failure = 500, } /** * Verifies the signature of a request. Throws a {@link CodedError} if the signature is invalid. * * @remarks * See [Verifying requests from Slack](https://api.slack.com/docs/verifying-requests-from-slack#sdk_support) for more * information. * * @param params - See {@link VerifyRequestSignatureParams}. * @returns `true` when the signature is valid. */ export function verifyRequestSignature({ signingSecret, requestSignature, requestTimestamp, body, }: VerifyRequestSignatureParams): true { // convert the current time to seconds (to match the API's `ts` format), then subtract 5 minutes' worth of seconds. const fiveMinutesAgo = Math.floor(Date.now() / 1000) - (60 * 5); if (requestTimestamp < fiveMinutesAgo) { debug('request is older than 5 minutes'); throw errorWithCode(new Error('Slack request signing verification outdated'), ErrorCode.RequestTimeFailure); } const hmac = crypto.createHmac('sha256', signingSecret); const [version, hash] = requestSignature.split('='); hmac.update(`${version}:${requestTimestamp}:${body}`); if (!timingSafeCompare(hash, hmac.digest('hex'))) { debug('request signature is not valid'); throw errorWithCode(new Error('Slack request signing verification failed'), ErrorCode.SignatureVerificationFailure); } debug('request signing verification success'); return true; } export function createHTTPHandler(adapter: SlackEventAdapter): HTTPHandler { const poweredBy = packageIdentifier(); /** * Binds a response handler to the given response. * * @param res - The response object. * @returns The responder function bound to the input response. */ function sendResponse(res: ServerResponse): ResponseHandler { // This function is the completion handler for sending a response to an event. It can either // be invoked by automatically or by the user (when using the `waitForResponse` option). return (err, responseOptions) => { debug('sending response - error: %s, responseOptions: %o', err, responseOptions); // Deal with errors up front if (!isFalsy(err)) { if ('status' in err && typeof err.status === 'number') { res.statusCode = err.status; } else if ( (err as CodedError).code === ErrorCode.SignatureVerificationFailure || (err as CodedError).code === ErrorCode.RequestTimeFailure ) { res.statusCode = ResponseStatus.NotFound; } else { res.statusCode = ResponseStatus.Failure; } } else { // First determine the response status if (!isFalsy(responseOptions)) { if (responseOptions.failWithNoRetry) { res.statusCode = ResponseStatus.Failure; } else if (responseOptions.redirectLocation) { res.statusCode = ResponseStatus.Redirect; } else { // URL Verification res.statusCode = ResponseStatus.Ok; } } else { res.statusCode = ResponseStatus.Ok; } // Next determine the response headers if (!isFalsy(responseOptions) && responseOptions.failWithNoRetry) { res.setHeader('X-Slack-No-Retry', '1'); } res.setHeader('X-Slack-Powered-By', poweredBy); } // Lastly, send the response if (!isFalsy(responseOptions) && responseOptions.content) { res.end(responseOptions.content); } else { res.end(); } }; } /** * Handles making responses for errors. * * @param error - The error that occurred. * @param respond - The {@link ResponseHandler | response handler}. */ function handleError(error: CodedError, respond: ResponseHandler): void { debug('handling error - message: %s, code: %s', error.message, error.code); try { if (adapter.waitForResponse) { adapter.emit('error', error, respond); } else if (process.env.NODE_ENV === 'development') { adapter.emit('error', error); respond({ status: ResponseStatus.Failure } as ResponseError, { content: error.message }); } else { adapter.emit('error', error); respond(error); } } catch (userError) { process.nextTick(() => { throw userError; }); } } /** * Request listener used to handle Slack requests and send responses and * verify request signatures * * @param req - The incoming request. * @param res - The outgoing response. */ return (req, res) => { debug('request received - method: %s, path: %s', req.method, req.url); // Bind a response function to this request's respond object. const respond = sendResponse(res); if (isFalsy(req.headers['x-slack-signature']) || isFalsy(req.headers['x-slack-request-timestamp'])) { handleError( errorWithCode( new Error('Slack request signing verification failed'), ErrorCode.SignatureVerificationFailure, ), respond, ); return; } // If parser is being used and we don't receive the raw payload via `rawBody`, // we can't verify request signature if (!isFalsy(req.body) && isFalsy(req.rawBody)) { handleError( errorWithCode( new Error('Parsing request body prohibits request signature verification'), ErrorCode.BodyParserNotPermitted, ), respond, ); return; } // Some serverless cloud providers (e.g. Google Firebase Cloud Functions) might populate // the request with a bodyparser before it can be populated by the SDK. // To prevent throwing an error here, we check the `rawBody` field before parsing the request // through the `raw-body` module (see Issue #85 - https://github.com/slackapi/node-slack-events-api/issues/85) let parseRawBody: Promise<Buffer>; if (!isFalsy(req.rawBody)) { debug('Parsing request with a rawBody attribute'); parseRawBody = Promise.resolve(req.rawBody); } else { debug('Parsing raw request'); parseRawBody = getRawBody(req); } parseRawBody .then((bodyBuf) => { const rawBody = bodyBuf.toString(); if (verifyRequestSignature({ signingSecret: adapter.signingSecret, requestSignature: req.headers['x-slack-signature'] as string, requestTimestamp: parseInt(req.headers['x-slack-request-timestamp'] as string, 10), body: rawBody, })) { // Request signature is verified // Parse raw body const body = JSON.parse(rawBody); // Handle URL verification challenge if (body.type === 'url_verification') { debug('handling url verification'); respond(undefined, { content: body.challenge }); return; } const emitArguments = [body.event]; if (adapter.includeBody) { emitArguments.push(body); } if (adapter.includeHeaders) { emitArguments.push(req.headers); } if (adapter.waitForResponse) { emitArguments.push(respond); } else { respond(); } debug('emitting event - type: %s, arguments: %o', body.event.type, emitArguments); adapter.emit(body.event.type, ...emitArguments); } }).catch((error) => { handleError(error, respond); }); }; } /** * A RequestListener-compatible callback for creating response information from an incoming request. * * @remarks * See RequestListener in the `http` module. */ type HTTPHandler = (req: IncomingMessage & { body?: any, rawBody?: Buffer }, res: ServerResponse) => void; /** * A Node-style response handler that takes an error (if any occurred) and a few response-related options. */ export type ResponseHandler = (err?: ResponseError, responseOptions?: { failWithNoRetry?: boolean; redirectLocation?: boolean; content?: any; }) => void; /** * An error (that may or may not have a status code) in response to a request. */ export interface ResponseError extends Error { status?: number; } /** * Parameters for calling {@link verifyRequestSignature}. */ export interface VerifyRequestSignatureParams { /** * The signing secret used to verify request signature. */ signingSecret: string; /** * Signature from the `X-Slack-Signature` header. */ requestSignature: string; /** * Timestamp from the `X-Slack-Request-Timestamp` header. */ requestTimestamp: number; /** * Full, raw body string. */ body: string; } /** * All errors produced by this package are regular * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error | Error} objects with * an extra {@link CodedError.code | `error`} field. */ export interface CodedError extends Error { /** * What kind of error occurred. */ code: ErrorCode; } /** * Factory for producing a {@link CodedError} from a generic error. */ function errorWithCode(error: Error, code: ErrorCode): CodedError { const codedError = error as CodedError; codedError.code = code; return codedError; } // legacy export export const errorCodes = { /* eslint-disable @typescript-eslint/naming-convention */ SIGNATURE_VERIFICATION_FAILURE: ErrorCode.SignatureVerificationFailure, REQUEST_TIME_FAILURE: ErrorCode.RequestTimeFailure, BODY_PARSER_NOT_PERMITTED: ErrorCode.BodyParserNotPermitted, /* eslint-enable @typescript-eslint/naming-convention */ };
the_stack
import { IGroup, IShape } from '@antv/g-base'; import { registerNode, Item, NodeConfig, ShapeStyle, ShapeOptions, BaseGlobal as Global, } from '@antv/f6-core'; import { mix } from '@antv/util'; // 五角星shape registerNode( 'star', { // 自定义节点时的配置 options: { size: 60, style: { stroke: Global.defaultNode.style.stroke, fill: Global.defaultNode.style.fill, lineWidth: Global.defaultNode.style.lineWidth, }, labelCfg: { style: { fill: Global.nodeLabel.style.fill, fontSize: Global.nodeLabel.style.fontSize, }, }, // 节点上左右上下四个方向上的链接circle配置 linkPoints: { top: false, right: false, bottom: false, left: false, // circle的大小 size: Global.defaultNode.linkPoints.size, lineWidth: Global.defaultNode.linkPoints.lineWidth, fill: Global.defaultNode.linkPoints.fill, stroke: Global.defaultNode.linkPoints.stroke, }, // 节点中icon配置 icon: { // 是否显示icon,值为 false 则不渲染icon show: false, // icon的地址,字符串类型 img: 'https://gw.alipayobjects.com/zos/bmw-prod/5d015065-8505-4e7a-baec-976f81e3c41d.svg', width: 20, height: 20, }, stateStyles: { ...Global.nodeStateStyles, }, }, shapeType: 'star', // 文本位置 labelPosition: 'center', drawShape(cfg: NodeConfig, group: IGroup): IShape { const { icon = {} } = this.getOptions(cfg) as NodeConfig; const style = this.getShapeStyle!(cfg); const keyShape = group.addShape('path', { attrs: style, className: `${this.type}-keyShape`, name: `${this.type}-keyShape`, draggable: true, }); const { width: w, height: h, show, text } = icon; if (show) { if (text) { group.addShape('text', { attrs: { x: 0, y: 0, fontSize: 12, fill: '#000', stroke: '#000', textBaseline: 'middle', textAlign: 'center', ...icon, }, className: `${this.type}-icon`, name: `${this.type}-icon`, draggable: true, }); } else { group.addShape('image', { attrs: { x: -w! / 2, y: -h! / 2, ...icon, }, className: `${this.type}-icon`, name: `${this.type}-icon`, draggable: true, }); } } (this as any).drawLinkPoints(cfg, group); return keyShape; }, /** * 绘制节点上的LinkPoints * @param {Object} cfg data数据配置项 * @param {Group} group Group实例 */ drawLinkPoints(cfg: NodeConfig, group: IGroup) { const { linkPoints = {} } = this.getOptions(cfg) as NodeConfig; const { top, left, right, leftBottom, rightBottom, size: markSize, r: markR, ...markStyle } = linkPoints; const size = (this as ShapeOptions).getSize!(cfg); const outerR = size[0]; if (right) { // right circle // up down left right 四个方向的坐标均不相同 const x1 = Math.cos(((18 + 72 * 0) / 180) * Math.PI) * outerR; const y1 = Math.sin(((18 + 72 * 0) / 180) * Math.PI) * outerR; group.addShape('circle', { attrs: { ...markStyle, x: x1, y: -y1, r: markSize / 2 || markR || 5, }, className: 'link-point-right', name: 'link-point-right', }); } if (top) { // up down left right 四个方向的坐标均不相同 const x1 = Math.cos(((18 + 72 * 1) / 180) * Math.PI) * outerR; const y1 = Math.sin(((18 + 72 * 1) / 180) * Math.PI) * outerR; // top circle group.addShape('circle', { attrs: { ...markStyle, x: x1, y: -y1, r: markSize / 2 || markR || 5, }, className: 'link-point-top', name: 'link-point-top', }); } if (left) { // up down left right 四个方向的坐标均不相同 const x1 = Math.cos(((18 + 72 * 2) / 180) * Math.PI) * outerR; const y1 = Math.sin(((18 + 72 * 2) / 180) * Math.PI) * outerR; // left circle group.addShape('circle', { attrs: { ...markStyle, x: x1, y: -y1, r: markSize / 2 || markR || 5, }, className: 'link-point-left', name: 'link-point-left', }); } if (leftBottom) { // up down left right 四个方向的坐标均不相同 const x1 = Math.cos(((18 + 72 * 3) / 180) * Math.PI) * outerR; const y1 = Math.sin(((18 + 72 * 3) / 180) * Math.PI) * outerR; // left bottom circle group.addShape('circle', { attrs: { ...markStyle, x: x1, y: -y1, r: markSize / 2 || markR || 5, }, className: 'link-point-left-bottom', name: 'link-point-left-bottom', }); } if (rightBottom) { // up down left right 四个方向的坐标均不相同 const x1 = Math.cos(((18 + 72 * 4) / 180) * Math.PI) * outerR; const y1 = Math.sin(((18 + 72 * 4) / 180) * Math.PI) * outerR; // left bottom circle group.addShape('circle', { attrs: { ...markStyle, x: x1, y: -y1, r: markSize / 2 || markR || 5, }, className: 'link-point-right-bottom', name: 'link-point-right-bottom', }); } }, getPath(cfg: NodeConfig) { const size = (this as ShapeOptions).getSize!(cfg); const outerR = size[0]; const defaultInnerR = (outerR * 3) / 8; const innerR = cfg.innerR || defaultInnerR; const path = []; for (let i = 0; i < 5; i++) { const x1 = Math.cos(((18 + 72 * i) / 180) * Math.PI) * outerR; const y1 = Math.sin(((18 + 72 * i) / 180) * Math.PI) * outerR; const x2 = Math.cos(((54 + 72 * i) / 180) * Math.PI) * innerR; const y2 = Math.sin(((54 + 72 * i) / 180) * Math.PI) * innerR; if (i === 0) { path.push(['M', x1, -y1]); } else { path.push(['L', x1, -y1]); } path.push(['L', x2, -y2]); } path.push(['Z']); return path; }, /** * 获取节点的样式,供基于该节点自定义时使用 * @param {Object} cfg 节点数据模型 * @return {Object} 节点的样式 */ getShapeStyle(cfg: NodeConfig): ShapeStyle { const { style: defaultStyle } = this.getOptions(cfg) as NodeConfig; const strokeStyle: ShapeStyle = { stroke: cfg.color, }; // 如果设置了color,则覆盖原来默认的 stroke 属性。但 cfg 中但 stroke 属性优先级更高 const style = mix({}, defaultStyle, strokeStyle); const path = (this as any).getPath(cfg); const styles = { path, ...style }; return styles; }, update(cfg: NodeConfig, item: Item) { const group = item.getContainer(); // 这里不传 cfg 参数是因为 cfg.style 需要最后覆盖样式 const { style: defaultStyle } = this.getOptions({}) as NodeConfig; const path = (this as any).getPath(cfg); // 下面这些属性需要覆盖默认样式与目前样式,但若在 cfg 中有指定则应该被 cfg 的相应配置覆盖。 const strokeStyle = { stroke: cfg.color, path, }; // 与 getShapeStyle 不同在于,update 时需要获取到当前的 style 进行融合。即新传入的配置项中没有涉及的属性,保留当前的配置。 const keyShape = item.get('keyShape'); let style = mix({}, defaultStyle, keyShape.attr(), strokeStyle); style = mix(style, cfg.style); (this as any).updateShape(cfg, item, style, true); (this as any).updateLinkPoints(cfg, group); }, /** * 更新linkPoints * @param {Object} cfg 节点数据配置项 * @param {Group} group Item所在的group */ updateLinkPoints(cfg: NodeConfig, group: IGroup) { const { linkPoints: defaultLinkPoints } = this.getOptions({}) as NodeConfig; const markLeft = group.find((element) => element.get('className') === 'link-point-left'); const markRight = group.find((element) => element.get('className') === 'link-point-right'); const markTop = group.find((element) => element.get('className') === 'link-point-top'); const markLeftBottom = group.find( (element) => element.get('className') === 'link-point-left-bottom', ); const markRightBottom = group.find( (element) => element.get('className') === 'link-point-right-bottom', ); let currentLinkPoints = defaultLinkPoints; const existLinkPoint = markLeft || markRight || markTop || markLeftBottom || markRightBottom; if (existLinkPoint) { currentLinkPoints = existLinkPoint.attr(); } const linkPoints = mix({}, currentLinkPoints, cfg.linkPoints); const { fill: markFill, stroke: markStroke, lineWidth: borderWidth } = linkPoints; let markSize = linkPoints.size / 2; if (!markSize) markSize = linkPoints.r; const { left, right, top, leftBottom, rightBottom } = cfg.linkPoints ? cfg.linkPoints : { left: undefined, right: undefined, top: undefined, leftBottom: undefined, rightBottom: undefined, }; const size = (this as ShapeOptions).getSize!(cfg); const outerR = size[0]; const styles = { r: markSize, fill: markFill, stroke: markStroke, lineWidth: borderWidth, }; let x = Math.cos(((18 + 72 * 0) / 180) * Math.PI) * outerR; let y = Math.sin(((18 + 72 * 0) / 180) * Math.PI) * outerR; if (markRight) { if (!right && right !== undefined) { markRight.remove(); } else { markRight.attr({ ...styles, x, y: -y, }); } } else if (right) { group.addShape('circle', { attrs: { ...styles, x, y: -y, }, className: 'link-point-right', name: 'link-point-right', isAnchorPoint: true, }); } x = Math.cos(((18 + 72 * 1) / 180) * Math.PI) * outerR; y = Math.sin(((18 + 72 * 1) / 180) * Math.PI) * outerR; if (markTop) { if (!top && top !== undefined) { markTop.remove(); } else { markTop.attr({ ...styles, x, y: -y, }); } } else if (top) { group.addShape('circle', { attrs: { ...styles, x, y: -y, }, className: 'link-point-top', name: 'link-point-top', isAnchorPoint: true, }); } x = Math.cos(((18 + 72 * 2) / 180) * Math.PI) * outerR; y = Math.sin(((18 + 72 * 2) / 180) * Math.PI) * outerR; if (markLeft) { if (!left && left !== undefined) { markLeft.remove(); } else { markLeft.attr({ ...styles, x, y: -y, }); } } else if (left) { group.addShape('circle', { attrs: { ...styles, x, y: -y, }, className: 'link-point-left', name: 'link-point-left', isAnchorPoint: true, }); } x = Math.cos(((18 + 72 * 3) / 180) * Math.PI) * outerR; y = Math.sin(((18 + 72 * 3) / 180) * Math.PI) * outerR; if (markLeftBottom) { if (!leftBottom && leftBottom !== undefined) { markLeftBottom.remove(); } else { markLeftBottom.attr({ ...styles, x, y: -y, }); } } else if (leftBottom) { group.addShape('circle', { attrs: { ...styles, x, y: -y, }, className: 'link-point-left-bottom', name: 'link-point-left-bottom', isAnchorPoint: true, }); } x = Math.cos(((18 + 72 * 4) / 180) * Math.PI) * outerR; y = Math.sin(((18 + 72 * 4) / 180) * Math.PI) * outerR; if (markRightBottom) { if (!rightBottom && rightBottom !== undefined) { markLeftBottom.remove(); } else { markRightBottom.attr({ ...styles, x, y: -y, }); } } else if (rightBottom) { group.addShape('circle', { attrs: { ...styles, x, y: -y, }, className: 'link-point-right-bottom', name: 'link-point-right-bottom', isAnchorPoint: true, }); } }, }, 'single-node', );
the_stack
/// <reference path="Autosuggest.d.ts" /> /// <reference path="Clustering.d.ts" /> /// <reference path="Contour.d.ts" /> /// <reference path="DataBinning.d.ts" /> /// <reference path="Directions.d.ts" /> /// <reference path="DrawingTools.d.ts" /> /// <reference path="GeoJson.d.ts" /> /// <reference path="HeatMapLayer.d.ts" /> /// <reference path="Search.d.ts" /> /// <reference path="SpatialDataService.d.ts" /> /// <reference path="SpatialMath.d.ts" /> /// <reference path="Traffic.d.ts" /> /// <reference path="WellKnownText.d.ts" /> /** * The Bing Maps V8 developer API. */ declare module Microsoft.Maps { ////////////////////////////////////////////// /// Custom Map Styles ////////////////////////////////////////////// /** The styles options that can be applied to map elements. */ export interface IMapElementStyle { /** * Hex color used for filling polygons, the background of point icons, and for the center of lines if they have split. */ fillColor?: string; /** * The hex color of a map label. */ labelColor?: string; /** * The outline hex color of a map label. */ labelOutlineColor?: string; /** * Species if a map label type is visible or not. */ labelVisible?: boolean; /** * Hex color used for the outline around polygons, the outline around point icons, and the color of lines. */ strokeColor?: string; /** * Specifies if the map element is visible or not. */ visible?: boolean; } /** The style options that can be appliction to bordered map elements. */ export interface IBorderedMapElementStyle extends IMapElementStyle { /** * Secondary/casing line hex color of the border of a filled polygon. */ borderOutlineColor?: string; /** * Primary line hex color of the border of a filled polygon. */ borderStrokeColor?: string; /** * Specifies if a border is visible or not. */ borderVisible?: boolean; } /** Global style settings */ export interface ISettingsStyle { /** A hex color value that all land is first flushed to before things are drawn on it. */ landColor?: string; /** Specifies whether or not to draw elevation shading on the map. */ shadedReliefVisible?: boolean; } /** Map Elements which can be styled. */ export interface IMapElements { /** Admin1, state, province, etc. */ adminDistrict?: IBorderedMapElementStyle; /** Icon representing the capital of a state/province. */ adminDistrictCapital?: IMapElementStyle; /** Area of land encompassing an airport. */ airport?: IMapElementStyle; /** Area of land use, not to be confused with Structure */ area?: IMapElementStyle; /** An arterial road is a high-capacity urban road. Its primary function is to deliver traffic from collector roads to freeways or expressways, and between urban centers efficiently. */ arterialRoad?: IMapElementStyle; /** A structure such as a house, store, factory. */ building?: IMapElementStyle; /** Restaurant, hospital, school, etc. */ business?: IMapElementStyle; /** Icon representing the capital populated place. */ capital?: IMapElementStyle; /** Area of a cemetery */ cemetery?: IMapElementStyle; /** Area of a whole continent */ continent?: IMapElementStyle; /** A controlled-access highway is a type of road which has been designed for high-speed vehicular traffic, with all traffic flow and ingress/egress regulated. Also known as a highway, freeway, motorway, expressway, interstate, parkway. */ controlledAccessHighway?: IMapElementStyle; /** A country or independent sovereign state. */ countryRegion?: IBorderedMapElementStyle; /** Icon representing the capital of a country/region. */ countryRegionCapital?: IMapElementStyle; /** Admin2, county, etc. */ district?: IBorderedMapElementStyle; /** An area of land used for educational purposes such as a school campus. */ education?: IMapElementStyle; /** A school or other educational building. */ educationBuilding?: IMapElementStyle; /** Restaurant, caf�, etc. */ foodPoint?: IMapElementStyle; /** Area of forest land. */ forest?: IMapElementStyle; /** An area of land where the game of golf is played. */ golfCourse?: IMapElementStyle; /** Lines representing ramps typically alongside ControlledAccessHighways */ highSpeedRamp?: IMapElementStyle; /** A highway. */ highway?: IMapElementStyle; /** An area of land reserved for Indigenous people. */ indigenousPeoplesReserve?: IMapElementStyle; /** Labeling of area of an island. */ island?: IMapElementStyle; /** Major roads. */ majorRoad?: IMapElementStyle; /** The base map element in which all other map elements inherit from. */ mapElement?: IMapElementStyle; /** Area of land used for medical purposes. Generally, hospital campuses. */ medical?: IMapElementStyle; /** A building which provides medical services. */ medicalBuilding?: IMapElementStyle; /** A military area. */ military?: IMapElementStyle; /** A natural point of interest. */ naturalPoint?: IMapElementStyle; /** Area of land used for nautical purposes. */ nautical?: IMapElementStyle; /** Area defined as a neighborhood. Labels only. */ neighborhood?: IMapElementStyle; /** Area of any kind of park. */ park?: IMapElementStyle; /** Icon representing the peak of a mountain. */ peak?: IMapElementStyle; /** All point features that are rendered with an icon of some sort */ point?: IMapElementStyle; /** Restaurant, hospital, school, marina, ski area, etc. */ pointOfInterest?: IMapElementStyle; /** A political border. */ political?: IBorderedMapElementStyle; /** Icon representing size of populated place (city, town, etc). */ populatedPlace?: IMapElementStyle; /** Railway lines */ railway?: IMapElementStyle; /** Line representing the connecting entrance/exit to a highway. */ ramp?: IMapElementStyle; /** Area of nature reserve. */ reserve?: IMapElementStyle; /** River, stream, or other passage. Note that this may be a line or polygon and may connect to non-river water bodies. */ river?: IMapElementStyle; /** Lines that represent all roads */ road?: IMapElementStyle; /** Icon representing the exit, typically from a controlled access highway. */ roadExit?: IMapElementStyle; /** Sign representing a compact name for a road. For example, I-5. */ //roadShield?: IMapElementStyle; /** Land area covered by a runway. See also Airport for the land area of the whole airport. */ runway?: IMapElementStyle; /** Area generally used for beaches, but could be used for sandy areas/golf bunkers in the future. */ sand?: IMapElementStyle; /** A shopping center or mall. */ shoppingCenter?: IMapElementStyle; /** Area of a stadium. */ stadium?: IMapElementStyle; /** A street. */ street?: IMapElementStyle; /** Buildings and other building-like structures */ structure?: IMapElementStyle; /** A toll road. */ tollRoad?: IMapElementStyle; /** Walking trail, either through park or hiking trail */ trail?: IMapElementStyle; /** Icon representing a bus stop, train stop, airport, etc. */ transit?: IMapElementStyle; /** A transit building. */ transitBuilding?: IMapElementStyle; /** Lines that are part of the transportation network (roads, trains, ferries, etc) */ transportation?: IMapElementStyle; /** An unpaved street. */ unpavedStreet?: IMapElementStyle; /** Forests, grassy areas, etc. */ vegetation?: IMapElementStyle; /** Icon representing the peak of a volcano. */ volcanicPeak?: IMapElementStyle; /** Anything that looks like water */ water?: IMapElementStyle; /** Icon representing a water feature location such as a waterfall. */ waterPoint?: IMapElementStyle; /** Ferry route lines */ waterRoute?: IMapElementStyle; } /** Defines a custom map style. */ export interface ICustomMapStyle { /** A list of map elements to be styled. */ elements?: IMapElements; /** Global Settings. */ settings?: ISettingsStyle; /** The version of the style syntax used. */ version: string; } ////////////////////////////////////////////// /// Enumerations ////////////////////////////////////////////// /** This enumeration defines how the map labels are displayed. */ export enum LabelOverlay { /** * Map labels are hidden. Note that this will have no effect on road maps unless the allowHidingLabelsOfRoad map option * is set to true. */ hidden, /** Map labels are visible. */ visible } /** This enumeration is used to specify the type of map style that should be displayed by the map. */ export enum MapTypeId { /** The aerial map type which uses top-down satellite & airplane imagery. */ aerial, /** High resolution aerial imagery taken at 45 degrees to the ground, from 4 different directions. */ birdseye, /** A darker version of the road maps. */ canvasDark, /** A lighter version of the road maps which also has some of the details such as hill shading disabled. */ canvasLight, /** A grayscale version of the road maps. */ grayscale, /** Displays a blank canvas that uses the mercator map project. It basically removed the base maps layer. */ mercator, /** Ordnance survey map type (en-gb only). */ ordnanceSurvey, /** Road map type. */ road, /** Provides streetside panoramas from the street level. */ streetside } /** The NavigationBarMode can be used to customize the layout and style of the navigation bar. */ export enum NavigationBarMode { /** * A compact navigation bar that includes a smaller drop down for the map type and zoom buttons. Recommended for small * maps or screen such as a mobile device. */ compact, /** * The default navigation bar that has a drop down for the map type, a locate me button, and zoom buttons. Recommended for * medium to large maps in desktop browsers. */ default, /** * A minified navigation bar that has a button to toggle between road and aerial maps, zoom buttons, and a button to turn * traffic information on and off. Recommended for small maps or screen such as a mobile device. */ minified } /** The NavigationBarOrientation enumeration is used to define how the navigation bar controls are laid out. */ export enum NavigationBarOrientation { /** Repositions the buttons in the navigation bar such that they are aligned horizontally. */ horizontal, /** Repositions the buttons in the navigation bar such that they are aligned vertically. */ vertical } /** This enumeration is used to specify how the overview map for the streetside map mode should be displayed. */ export enum OverviewMapMode { /** Shows the overview map in an expanded state. */ expanded, /** Hides the overview map. */ hidden, /** Shows the overview map in a minimized state. */ minimized } /** Contains enum to show how pixels are defined. */ export enum PixelReference { /** The pixel is defined relative to the map control�s root element, where the top left corner of the map control is (0, 0). */ control, /** The pixel is defined relative to the page, where the top left corner of the HTML page is (0, 0). */ page, /** The pixel is defined in viewport coordinates, relative to the center of the map, where the center of the map is (0, 0). */ viewport } ////////////////////////////////////////////// /// Interfaces ////////////////////////////////////////////// /** Represents a structured address object. */ export interface IAddress { /** * The street line of an address. The addressLine property is the most precise, official line for an address relative to the postal agency * servicing the area specified by the locality or postalCode properties. */ addressLine: string; /** * The subdivision name within the country or region for an address. This element is also commonly treated as the first order administrative * subdivision. An example is a US state, such as �Oregon�. */ adminDistrict: string; /** The country or region name of the address. */ countryRegion: string; /** A string specifying the two-letter ISO country code. */ countryRegionISO2: string; /** The second, third, or fourth order subdivision within a country, dependency, or region. An example is a US county, such as �King�. */ district: string; /** A nicely formatted address string for the result. */ formattedAddress: string; /** The locality, such as the primary city, that corresponds to an address. An example is �Seattle�. */ locality: string; /** The post code, postal code, or ZIP code of an address. An example is a US ZIP code, such as �98152�. */ postalCode: string; } /** The event args for when a layer frame is being loaded in an AnimtedTileLayer. **/ export interface IAnimatedFrameEventArgs { /** The animated tile layer that the frame belongs to. **/ animatedTileLayer: AnimatedTileLayer; /** The index of the frame being loaded. **/ index: number; } /** An object that defines the options for an AnimatedTileLayer. **/ export interface IAnimatedTileLayerOptions { /** A boolean that specifies whether the animation should auto-start when it is added to the map or not. Default: true **/ autoPlay?: boolean; /** The number of miliseconds between two layer frames. Default: 1000 **/ frameRate?: number; /** A custom loading screen to show on the map when the map tiles are being fetched. **/ loadingScreen?: CustomOverlay; /** The max amount of total loading time of all tiles in a viewport in milliseconds. Default: 15000 **/ maxTotalLoadTime?: number; /** The array of tile layer sources to animate through. **/ mercator: TileSource[]; /** A boolean specifying if the animated tile layer is visible or not. **/ visible?: boolean; } /** Represents the options that can be used when initializing a custom overlay. **/ export interface ICustomOverlayOptions { /** * Specifies if the custom overlay should eb rendered above or below the label layer of the map. When above, * elements in the overlay can be clickable. Default: True */ beneathLabels?: boolean; } /** Base data layer interface. */ export interface IDataLayer extends ILayer { /** Clears all data in the layer. */ clear(): void; } /** Event args included in entity collection events. */ export interface IEntityCollectionChangedEventArgs { /** The entity collection the event was triggered from. */ collection: EntityCollection; /** The IPrimitive object that the event occurred for. */ data: IPrimitive; } /** An object the identifies an event that has been attached to an object. */ export interface IHandlerId { } /** Base layer interface. */ export interface ILayer { } /** * @deprecated use IMouseEventArgs * A LayerMouseEventArgs object is returned by many the mouse event handlers attached to a Layer. */ export interface ILayerMouseEventArgs { /** * @deprecated use target * The IPrimitive shape (pushpin, polyline, polygon) that the event occurred on. */ primitive: IPrimitive; } /** The options that can be used to customize an infobox. */ export interface IInfoboxOptions { /** * @deprecated Use HTML buttons and links in description instead. */ actions?: IInfoboxActions[]; /** The string displayed inside the infobox. */ description?: string; /** * The HTML that represents the infobox. Note that infobox options are ignored if custom HTML is set. Also, if custom HTML is used to represent the * infobox, the infobox is anchored at the top-left corner. */ htmlContent?: string; /** The location on the map where the infobox�s anchor is attached. */ location?: Location; /** The maximium size that the infobox height can expand to based on it�s content. Default: 126 **/ maxHeight?: number; /** The maximium size that the infobox width can expand to based on it�s content. Default: 256 **/ maxWidth?: number; /** * The amount the infobox pointer is shifted from the location of the infobox, or if showPointer is false, then it is the amount the info box bottom * left edge is shifted from the location of the infobox. If custom HTML is set, it is the amount the top-left corner of the infobox is shifted from * its location. The default offset value is (0,0), which means there is no offset. */ offset?: Point; /** * A boolean indicating whether to show the close dialog button on the infobox. The default value is true. By default, the close button is displayed * as an X in the top right corner of the infobox. This property is ignored if custom HTML is used to represent the infobox. */ showCloseButton?: boolean; /** * A boolean indicating whether to display the infobox with a pointer. The default value is true. In this case the infobox is anchored at the bottom * point of the pointer. If this property is set to false, the infobox is anchored at the bottom left corner. This property is ignored if custom HTML * is used to represent the infobox. */ showPointer?: boolean; /** The title of the infobox. */ title?: string; /** * A boolean indicating whether to show or hide the infobox. The default value is true. A value of false indicates that the infobox is hidden, * although it is still an entity on the map. */ visible?: boolean; /** The z-index of the infobox with respect to other items on the map. */ zIndex?: number; } /** * @deprecated Use HTML buttons and links in description instead. */ export interface IInfoboxActions { /** The text to display for the action. */ label: string; /** The function to call when the label is clicked. */ eventHandler: (eventArg?: MouseEvent) => void; } /** An object that contains information about an infobox event. **/ export interface IInfoboxEventArgs { /** The event that occurred. **/ eventName: string; /** The x-value of the pixel coordinate on the page of the mouse cursor. **/ pageX: number; /** The y-value of the pixel coordinate on the page of the mouse cursor. **/ pageY: number; /** The infobox object that fired the event. **/ target: Infobox; /** The type of the object that fired the event.This will always be 'infobox'. **/ targetType: string; /** Original mouse event from the browser. */ originalEvent?: MouseEvent; } /** Map or View options */ export interface IMapLoadOptions extends IMapOptions, IViewOptions { /** The Bing Maps Key used to authenticate the application. This property can only be set when using the Map constructor. */ credentials: string; } /** * An object that can be used to customize the map. Some of the map options can be changed after the map has loaded by using * the setOptions function on the map. */ export interface IMapOptions { /** * A boolean that, when set to true, allows the road labels to be hidden. Default: false * This property can only be set when using the Map constructor. This property can only be set when using the Map constructor. */ allowHidingLabelsOfRoad?: boolean; /** A boolean indicating if the infobox is allowed to overflow outside the bounds of the map. Default: false. */ allowInfoboxOverflow?: boolean; /** The color to use for the map control background. The default color is #EAE8E1. This property can only be set when using the Map constructor. */ backgroundColor?: string | Color; /** Custom map styles used to modify the look and feel of the base map. */ customMapStyle?: ICustomMapStyle; /** A boolean value indicating whether to disable the user�s ability to control the using the keyboard. Default: false */ disableKeyboardInput?: boolean; /** A boolean value indicating if mousing over the map type selector should open it or not. Default: true */ disableMapTypeSelectorMouseOver?: boolean; /** A boolean value indicating whether to disable the user's ability to pan the map. Default: false */ disablePanning?: boolean; /** * Scrolling the mouse wheel over the map will zoom it in or out, but will not scroll the page. * Setting this property to true disables the zooming of the map and instead reverts back to scrolling the page instea. * Default: false */ disableScrollWheelZoom?: boolean; /** * A boolean indicating whether to disable streetside mode.If this property is set to true, streetside will be removed from * the navigation bar, and the automatic coverage overlay will be disabled when zoomed in at lower zoom levels. Default false * This property can only be set when using the Map constructor. */ disableStreetside?: boolean; /** * A boolean indicating whether to disable the automatic streetside coverage layer that appears when zoomed in at lower zoom * levels. Default false * This property can only be set when using the Map constructor. **/ disableStreetsideAutoCoverage?: boolean; /** A boolean value indicating whether to disable the user's ability to zoom in or out. Default: false */ disableZooming?: boolean; /** * A boolean value indicating whether the Bing(TM) logo on the map is clickable. Default: true. * This property can only be set when using the Map constructor. */ enableClickableLogo?: boolean; /** * A boolean value indicating whether to use the inertia animation effect during map navigation. Default: true * This property can only be set when using the Map constructor. */ enableInertia?: boolean; /** * A boolean that indicates if the map should be rendered using lite mode. When set to true vector map labels are * disabled and map labels are rendered directly into the map tiles. This offers improved performance, but will result * in the labels being rendered behind data on the map and the labels will also not use collision dection with pushpins. * If this property is not set, the map set this value based on the target device and browser as vector labels perform * better in some scenrarios than others. * This property can only be set when using the Map constructor. */ liteMode?: boolean; /** A bounding area that restricts the map view. */ maxBounds?: LocationRect; /** The maximum zoom level that the map can be zoomed into. */ maxZoom?: number; /** The minimum zoom level that the map cab be zoomed out to. */ minZoom?: number; /** Specifies how the navigation bar should be rendered on the map. */ navigationBarMode?: NavigationBarMode; /** A boolean whether what orientation should be used when laying out the navigation controls. */ navigationBarOrientation?: NavigationBarOrientation; /** * A boolean value indicating whether to display the �breadcrumb control�. The breadcrumb control shows the current center location�s geography hierarchy. * The default value is false. Requires the showLocateMeButton map option to be set to true. The breadcrumb control displays best when the width of the map * is at least 400 pixels. */ showBreadcrumb?: boolean; /** * A boolean value indicating whether to show the map navigation control. Default: true�This property can only be set when using the Map constructor. */ showDashboard?: boolean; /** * A boolean value indicating whether to show a button that centers the map over the user's location in the map navigation control. Default: true * This property can only be set when using the Map constructor. */ showLocateMeButton?: boolean; /** * A boolean value indicating whether or not to show the map Bing logo. The default value is true. * This property can only be set when using the Map constructor. */ showLogo?: boolean; /** * A boolean value indicating whether to show the map type selector in the map navigation control. Default: true * This property can only be set when using the Map constructor. */ showMapTypeSelector?: boolean; /** * A boolean value indicating whether to show the scale bar. Default: true * This property can only be set when using the Map constructor. */ showScalebar?: boolean; /** When using the minified navigation bar, a traffic button is displayed. Setting this option to false will hide this button. */ showTrafficButton?: boolean; /** * A boolean value indicating whether to show a link to the End User Terms of Use, which appears to the right of the copyrights, or not. Default: true * This property can only be set when using the Map constructor. */ showTermsLink?: boolean; /** * A boolean value indicating whether to show the zoom buttons in the map navigation control. Default: true * This property can only be set when using the Map constructor. */ showZoomButtons?: boolean; /** A set of properties for the streetside mode of the map. */ streetsideOptions?: IStreetsideOptions; /** Additional support map types that should be added to the navigaiton bar such as canvasDark, canvasLight, and grayscale.*/ supportedMapTypes?: MapTypeId[]; } /** A MapTypeChangeEventArgs object is returned by the map when using the mapTypeChanged event. */ export interface IMapTypeChangeEventArgs { /** The map type that map has changed to. */ newMapTypeId: MapTypeId; /** The map type that the map has changed from. */ oldMapTypeId: MapTypeId; /** The map instance the event occured on */ target: Map; /** The type of object the event was attached to. Should always be "map" */ targetType: string; } /** Interface for module options. */ export interface IModuleOptions { /** A callback function that is fired after the module has loaded. */ callback?: () => void; /** A function that is called if there is an error loading the module. */ errorCallback?: () => void; /** A Bing Maps key that is used with the module when the module is loaded without a map. */ credentials?: string; } /** A MouseEventArgs object is returned by many the mouse event handlers. */ export interface IMouseEventArgs extends ILayerMouseEventArgs { /** The event that occurred. */ eventName: string; /** A boolean indicating if the primary button, such as the left mouse button or a tap on a touch screen, was used during a mouse down or up event. */ isPrimary: boolean; /** A boolean indicating if the secondary mouse button, such as the right mouse button, was used during a mouse down or up event. */ isSecondary: boolean; /** If the target is a shape, this will be the layer that the shape is in. */ layer: Layer; /** The map location of where the event occurred. */ location: Location; /** The x-value of the pixel coordinate on the page of the mouse cursor. */ pageX: number; /** The y-value of the pixel coordinate on the page of the mouse cursor. */ pageY: number; /** The pixel coordinate of the mouse cusrsor relative to the top left corner of the map div. */ point: Point; /** The object that triggered the event. */ target: Map | IPrimitive; /** The type of the object that the event is attached to. Valid values include the following: �map�, 'layer', �polygon�, �polyline�, or �pushpin� */ targetType: string; /** * Returns the x-value of the pixel coordinate, relative to the map, of the mouse. * @returns The x-value of the pixel coordinate, relative to the map, of the mouse. */ getX(): number; /** * Returns the y-value of the pixel coordinate, relative to the map, of the mouse. * @returns The y-value of the pixel coordinate, relative to the map, of the mouse. */ getY(): number; } /** * An object tthat contains information about a streetside scene. */ export interface IPanoramaInfo { /** The capture date of the streetside scene. */ cd?: string; } /** * All shapes; Pushpins, Polylines and Polygons, derive from the IPrimitive interface. This means that they can be * passed into any function that takes in an IPrimitive object. Also, any function that returns an IPrimitive is capable * of returning any of these shapes. */ export interface IPrimitive { /** Optional property to store any additional metadata for this primitive. */ metadata?: any; /** * Gets the css cursor value when the primitive has events on it. * @returns css cursor string when primitive has events on it. */ getCursor(): string; /** * Gets whether the primitive is visible. * @returns A boolean indicating whether the primitive is visible or not. */ getVisible(): boolean; /** * Sets the options for customizing the IPrimitive. * @param options The options for customizing the IPrimitive. */ setOptions(options: IPrimitiveOptions): void; } /** A IPrimitiveChangedEventArgs object is returned by the changed event on IPrimitive shapes. */ export interface IPrimitiveChangedEventArgs { /** The IPrimitive shape the event occured on. */ sender: IPrimitive; /** The name of the change that occured; 'locations' or 'options'. */ name: string; } /** Options used for customizing IPrimitive objects. */ export interface IPrimitiveOptions { /** The css cursor to show when the IPrimitive has mouse events on it. Default value is pointer (hand). */ cursor?: string; /** Boolean indicating whether the IPrimitive is visible. */ visible?: boolean; } /** Options used for customizing Polylines. */ export interface IPolylineOptions extends IPrimitiveOptions { /** Indicates if drawn shape should be generalized based on the zoom level to improve rendering performance. Default true **/ generalizable?: boolean; /** CSS string or Color object as the poly's color. */ strokeColor?: string | Color; /** An array of numbers separated by spaces, or a string separated by spaces/commas specifying the repetitive stroke pattern. */ strokeDashArray?: number[] | string; /** The thickness of the poly stroke. */ strokeThickness?: number; } /** Options used for customizing Polygons. */ export interface IPolygonOptions extends IPolylineOptions { /** CSS string or Color object as the polygon's filling color. */ fillColor?: string | Color; } /** Options used for customizing Pushpins. */ export interface IPushpinOptions extends IPrimitiveOptions { /** The point on the pushpin icon, in pixels, which is anchored to the pushpin location. An anchor of (0,0) is the top left corner of the icon. */ anchor?: Point; /** Specifies what color to make the default pushpin. */ color?: string | Color; /** A boolean indicating whether the pushpin can be dragged to a new position with the mouse or by touch. */ draggable?: boolean; /** Specifies whether to enable the clicked style on the pushpin. */ enableClickedStyle?: boolean; /** Specifies whether to enable the hover style on the pushpin. */ enableHoverStyle?: boolean; /** * Defines the the icon to use for the pushpin.This can be a URL to an Image or SVG file, an image data URI, or an inline SVG string. * Tip: When using inline SVG, you can pass in placeholders `{color}` and `{text}` in your SVG string. This placeholder will be replaced by the pushpins color or text property value when rendered. */ icon?: string; /** Whether the clickable area of pushpin should be an ellipse instead of a rectangle. */ roundClickableArea?: boolean; /** * A secondary title label value to display under the pushpin. Uses label collision detection. This label automatically changes color between white * and dark grey depending on which map style is selected. Requires the title label to be set. */ subTitle?: string; /** * The title label value to display under the pushpin. This label automatically changes color between white and dark grey depending on which map * style is selected. Pushpin Titles support label collision detection, as described below. */ title?: string; /** A short string of text that is overlaid on top of the pushpin. */ text?: string; /** The amount the text is shifted from the pushpin icon. The default value is (0,5). */ textOffset?: Point; } /** An object that represents a min and max value range. */ export interface IRange { /** The minimum value. */ min: number; /** The maximum value. */ max: number; } /** The options that can be used to customize how the streetside map mode is displayed to the user. */ export interface IStreetsideOptions { /** A boolean indicating if the ability to navigate between image bubbles should be disabled in streetside map mode. Default: false */ disablePanoramaNavigation?: boolean; /** The location that the streetside panorama should be looking towards. This can be used instead of a heading. */ locationToLookAt?: Location; /** A callback function that is triggered after the streetside view has not loaded successfully. */ onErrorLoading?: () => void; /** A callback function that is triggered after the streetside view has loaded successfully. */ onSuccessLoading?: () => void; /** * Specifies how to render the overview map when in streetside mode. * Default: Microsoft.Maps.OverviewMapMode.expanded */ overviewMapMode?: OverviewMapMode; /** * Information for a streetside panorama scene to load. */ panoramaInfo?: IPanoramaInfo; /** The radius to search in for available streetside panoramas. */ panoramaLookupRadius?: number; /** A boolean indicating if the current address being viewed should be hidden when in streetside map mode. Default: true */ showCurrentAddress?: boolean; /** A boolean indicating if the exit button should be hidden when in streetside map mode. Default: true */ showExitButton?: boolean; /** A boolean indicating if the heading compass button is hidden when in streetside map mode. Default: true */ showHeadingCompass?: boolean; /** A boolean indicating if the link to report a problem with a streetside image is hidden when in streetside map mode. Default: true */ showProblemReporting?: boolean; /** A boolean indicating if the zoom buttons should be displayed when in streetside map mode. Default: true */ showZoomButtons?: boolean; } /** Defines a set of styles for pushpins, polylines, and polygons. */ export interface IStylesOptions { /** Sets the options for all pushpins. */ pushpinOptions?: IPushpinOptions; /** Sets the options for all polylines. */ polylineOptions?: IPolylineOptions; /** Sets the options for all polygons. */ polygonOptions?: IPolygonOptions; } /** Interface to specify style css while registering a module */ export interface IStyleUrl { /** List of style css urls o be downloaded */ styleURLs: string[]; } /** Represents options that can be used to customize a tile layer. */ export interface ITileLayerOptions { /** * The number of milliseconds allowed for the tile layer image download. If the timeout occurs before the image is fully * downloaded, the map control considers the download a failure. The default value is 10000. */ downloadTimeout?: number; /** The tile source for the tile layer. */ mercator: TileSource; /** The opacity of the tile layer, defined by a number between 0 (not visible) and 1. */ opacity?: number; /** * A boolean indicating whether to show or hide the tile layer. The default value is true. A value of false indicates that * the tile layer is hidden, although it is still an entity on the map. */ visible?: boolean; /** The z-index of the tile layer. */ zIndex?: number; } /** Represents options that can be used to define a tile source. */ export interface ITileSourceOptions { /** * A bounding box that specifies where tiles are available. * Note: This will not crop tiles to the specific bounding box, it limits the tiles it loads to those that intersect this bounding box. */ bounds?: LocationRect; /** The maximum zoom level tiles that tiles should be rendered at. */ maxZoom?: number; /** The minimum zoom level tiles that tiles should be rendered at. */ minZoom?: number; /** * Required. This can be a string or a callback function that constructs the URLs used to retrieve tiles from the tile source. * When using a string, the uriConstructor will allow you to specify placeholders that will be replaced with the tiles value (i.e. {quadkey}). * See the Tile URL Parameters section for a list of supported parameters. * Besides using formatted tile URLs, you can also specify a callback function as the uriConstructor. This is useful if you need to be able to * build custom tile URL�s that may require some additional calculations for a tile. */ uriConstructor: string | ((tile: PyramidTileId) => string); } /** Represents options that can be used to set the view of the map. */ export interface IViewOptions { /** The bounding rectangle of the map view. If both bounds and center are specified, bounds takes precedence over center. */ bounds?: LocationRect; /** The location of the center of the map view. If both bounds and center are specified, bounds takes precedence over center. */ center?: Location; /** * The directional heading of the map. The heading is represented in geometric degrees with 0 or 360 = North, 90 = East, * 180 = South, and 270 = West. */ heading?: number; /** Indicates how the map labels are displayed. */ labelOverlay?: LabelOverlay; /** The map type of the view. */ mapTypeId?: MapTypeId; /** The amount of padding in pixels to be added to each side of the bounds of the map view. */ padding?: number; /** The angle relative to the horizon to tilt a streetside panorama image. */ pitch?: number; /** The zoom level of the map view. */ zoom?: number; } ////////////////////////////////////////////// /// Modular Framework ////////////////////////////////////////////// /** * Loads the specified registered module, making its functionality available. You can provide the name of a single module or an array of names in. * Options or a callback function that is called when the module is loaded can be specified. * @param moduleName Name of the module to load. Can be the name of a custom module or a built in module name. Built in modules: * Microsoft.Maps.Autosuggest, Microsoft.Maps.Clustering, Microsoft.Maps.Directions, Microsoft.Maps.DrawingTools, Microsoft.Maps.GeoJSON, * Microsoft.Maps.HeatMap, Microsoft.Maps.Search, Microsoft.Maps.SpatialDataService, Microsoft.Maps.SpatialMath, Microsoft.Maps.Traffic, * Microsoft.Maps.WellKnownText * @param options A callback function or options containing additional information and a callback to call once a module is loaded */ export function loadModule(moduleName: string | string[], options?: (() => void) | IModuleOptions): void; /** * Registers a module with the map control. The name of the module is specified in moduleKey, the module script is defined in scriptURL, and the * options provides the location of a *.css file to load with the module. * @param moduleName Name of the module to load. * @param url Url to where the module code is located. * @param styles List of css files to download. */ export function registerModule(moduleName: string, url: string, styles?: IStyleUrl): void; /** * Signals that the specified module has been loaded and if specified, calls the callback function in loadModule. Call this method at the end of your custom module script. * @param moduleName Name of the module that is loaded. */ export function moduleLoaded(moduleName: string): void; ////////////////////////////////////////////// /// Classes ////////////////////////////////////////////// /** * Provides a layer which can smoothly animate through an array of tile layer sources. */ export class AnimatedTileLayer { /** * @contstructor * @param options Options that define how to animate between the specified tile layers. */ constructor(options?: IAnimatedTileLayerOptions); /** * Gets the frame rate of this animated tile layer. * @returns The frame rate of this animated tile layer. **/ public getFrameRate(): number; /** * Gets the loading screen overlay when tiles are being fetched. * @returns The loading screen overlay when tiles are being fetched. **/ public getLoadingScreen(): CustomOverlay; /** * Gets the maximum total tile fetching time of this animated tile layer. * @returns The maximum total tile fetching time of this animated tile layer **/ public getMaxTotalLoadTime(): number; /** * Gets the tile sources associated with this layer. * @returns The tile sources associated with this layer. **/ public getTileSources(): TileSource[]; /** * Gets the visibility of this animated tile layer. * @returns The visibility of this animated tile layer. **/ public getVisible(): boolean; /** Pause the tile layer animation. **/ public pause(): void; /** Play the animation either from start or where it was paused. **/ public play(): void; /** * Sets the options for the animated tile layer. * @params Options that define how to animate between the specified tile layers. **/ public setOptions(options: IAnimatedTileLayerOptions): void; /** Stop the layer animation, hide layer, and reset frame to the beginning. **/ public stop(): void; } /** Class that represents a color */ export class Color { /** The opacity of the color. The range of valid values are an interger between 0 and 255, or a decimal between 0 and 1. */ public a: number; /** The red value of the color. The range of valid values is 0 to 255 */ public r: number; /** The green value of the color. The range of valid values is 0 to 255 */ public g: number; /** The blue value of the color. The range of valid values is 0 to 255 */ public b: number; /** * @constructor * @param a The alpha value in argb format * @param r The r value in argb format * @param g The g value in argb format * @param b The b value in argb format */ constructor(a: number, r: number, g: number, b: number); /** * Clones the color. * @param color The color class that needs to be clones. * @returns The colne of the color. */ public static clone(color: Color): Color; /** * Creates the color from a hex string. * @param hex The color represented as '#rrggbb' format. * @returns The color object. */ public static fromHex(hex: string): Color; /** * Clones the color. * @returns The clone of the color. */ public clone(): Color; /** * Gets the opacity of this color. * @returns The opacity between 0 and 1 of this color. */ public getOpacity(): number; /** * Converts the color to hex notation. * @returns The hex notation as '#rrggbb' (ignores a). */ public toHex(): string; /** * Converts the color to rgba notation. * @returns The rgba notation as rgba(rr, gg, bb, aa) */ public toRgba(): string; } /** * You can use this class to create custom overlays on top of the map. These can be static overlays such as custom * navigation bars, or dynamic overlays such as custom visualization layers. CustomOverlays can be added to the map * just like any other layer using the map.layers property. */ export class CustomOverlay implements ILayer { /** A reference the the map instance that the overlay was added to. This will be null until the onLoad function has fired. **/ _map: Map; /** * @constructor * @param options The options to use when initializing the custom overlay. */ constructor(options?: ICustomOverlayOptions); /** * Gets the html element of this custom overlay. * @returns The htmlElement of this overlay. */ public getHtmlElement(): HTMLElement; /** * Gets the map that this overlay is attached to. * @returns The map that this overlay is attached to. */ public getMap(): Map; /** * Updates the html element of this custom overlay. * @param htmlElement The new htmlElement to set for the overlay. */ public setHtmlElement(htmlElement: HTMLElement): void; /** * Implement this method to perform any task that should be done when the overlay is added to the map. */ public onAdd(): void; /** * Implement this methof to perform any task that should be done after the overlay has been added to the map. */ public onRemove(): void; /** * Implement this method to perform any tasks that should be done when the overlay is removed from the map. */ public onLoad(): void; } /** * Use the Layer class. * @deprecated in V8 */ export class EntityCollection extends Layer { /** * @constructor Deprecated. Use the Layer class. * @deprecated in V8 */ constructor(); /** * Removes all shapes from the collection. */ public clear(): void; /** * Gets the item at a specified index. * @param index Index of the item to get. * @returns The item at a specified index. */ public get(index: number): IPrimitive; /** * Gets the number of items in this collection. * @returns The count of the items. */ public getLength(): number; /** * Gets the index of the item in the list. * @param primitive The item to get the index of. * @returns The index of the item in the list. */ public indexOf(primitive: IPrimitive): number; /** * Inserts the item into the list at a specific index. * @param primitive The item to insert. * @param index Index of the item to be inserted. */ public insert(primitive: IPrimitive, index: number): void; /** * Returns the last element in the list after removing it. * @returns The last element in the list after removing it. */ public pop(): IPrimitive; /** * Adds the item to the end of the list. * @param primitive Item to be added. */ public push(primitive: IPrimitive | IPrimitive[]): void; /** * Removes the item from the list. * @param primitive Item to be removed. * @returns The item to be removed. */ public remove(primitive: IPrimitive): IPrimitive; /** * Removes the item from the list at a specified index. * @param index Index of the item that needs to be removed. * @returns The item to be removed at a specified index. */ public removeAt(index: number): IPrimitive; } /** A static class that manages events within the map SDK. */ export module Events { ///////////////////////////////////// /// addHandler Definitions //////////////////////////////////// /** * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported events: * click, dblclick, maptypechanged, mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel, rightclick, viewchange, viewchangeend, viewchangestart * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addHandler(target: Map, eventName: string, handler: (eventArg?: IMouseEventArgs | IMapTypeChangeEventArgs) => void): IHandlerId; /** * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * changed, click, dblclick, drag, dragend, dragstart, mousedown, mouseout, mouseover, mouseup * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addHandler(target: Pushpin, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): IHandlerId; /** * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * changed, click, dblclick, mousedown, mouseout, mouseover, mouseup * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addHandler(target: Polyline | Polygon, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): IHandlerId; /** * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * click, infoboxChanged, mouseenter, mouseleave * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addHandler(target: Infobox, eventName: string, handler: (eventArg?: IInfoboxEventArgs) => void): IHandlerId; /** * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addHandler(target: Layer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void): IHandlerId; /** * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * � entityadded * � entityremoved * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addHandler(target: EntityCollection, eventName: string, handler: (eventArg?: IEntityCollectionChangedEventArgs) => void): IHandlerId; /** * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addHandler(target: any, eventName: string, handler: (eventArg?: any) => void): IHandlerId; ///////////////////////////////////// /// addOne Definitions //////////////////////////////////// /** * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported events: * click, dblclick, maptypechanged, mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel, rightclick, viewchange, viewchangeend, viewchangestart * @param handler The callback function to handle the event when triggered. */ export function addOne(target: Map, eventName: string, handler: (eventArg?: IMouseEventArgs | IMapTypeChangeEventArgs) => void): void; /** * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * changed, click, dblclick, drag, dragend, dragstart, mousedown, mouseout, mouseover, mouseup * @param handler The callback function to handle the event when triggered. */ export function addOne(target: Pushpin, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): void; /** * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * changed, click, dblclick, mousedown, mouseout, mouseover, mouseup * @param handler The callback function to handle the event when triggered. */ export function addOne(target: Polyline | Polygon, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): void; /** * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * click, infoboxChanged, mouseenter, mouseleave * @param handler The callback function to handle the event when triggered. */ export function addOne(target: Infobox, eventName: string, handler: (eventArg?: IInfoboxEventArgs) => void): void; /** * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick * @param handler The callback function to handle the event when triggered. */ export function addOne(target: Layer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void): void; /** * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * � entityadded * � entityremoved * @param handler The callback function to handle the event when triggered. */ export function addOne(target: EntityCollection, eventName: string, handler: (eventArg?: IEntityCollectionChangedEventArgs) => void): void; /** * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. * @param handler The callback function to handle the event when triggered. */ export function addOne(target: any, eventName: string, handler: (eventArg?: any) => void): void; ///////////////////////////////////// /// addThrottledHandler Definitions //////////////////////////////////// /** * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported events: * click, dblclick, maptypechanged, mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel, rightclick, viewchange, viewchangeend, viewchangestart * @param handler The callback function to handle the event when triggered. * @param throttleInterval throttle interval (in ms) * @returns The handler id. */ export function addThrottledHandler(target: Map, eventName: string, handler: (eventArg?: IMouseEventArgs | IMapTypeChangeEventArgs) => void, throttleInterval: number): IHandlerId; /** * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * changed, click, dblclick, drag, dragend, dragstart, mousedown, mouseout, mouseover, mouseup * @param handler The callback function to handle the event when triggered. * @param throttleInterval throttle interval (in ms) * @returns The handler id. */ export function addThrottledHandler(target: Pushpin, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void, throttleInterval: number): IHandlerId; /** * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * changed, click, dblclick, mousedown, mouseout, mouseover, mouseup * @param handler The callback function to handle the event when triggered. * @param throttleInterval throttle interval (in ms) * @returns The handler id. */ export function addThrottledHandler(target: Polyline | Polygon, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void, throttleInterval: number): IHandlerId; /** * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * click, infoboxChanged, mouseenter, mouseleave * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addThrottledHandler(target: Infobox, eventName: string, handler: (eventArg?: IInfoboxEventArgs) => void): IHandlerId; /** * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick * @param handler The callback function to handle the event when triggered. * @param throttleInterval throttle interval (in ms) * @returns The handler id. */ export function addThrottledHandler(target: Layer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void, throttleInterval: number): IHandlerId; /** * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * � entityadded * � entityremoved * @param handler The callback function to handle the event when triggered. * @param throttleInterval throttle interval (in ms) * @returns The handler id. */ export function addThrottledHandler(target: EntityCollection, eventName: string, handler: (eventArg?: IEntityCollectionChangedEventArgs) => void, throttleInterval: number): IHandlerId; /** * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. * @param handler The callback function to handle the event when triggered. * @param throttleInterval throttle interval (in ms) * @returns The handler id. */ export function addThrottledHandler(target: any, eventName: string, handler: (eventArg?: any) => void, throttleInterval: number): IHandlerId; ///////////////////////////////////// /// All other definitions //////////////////////////////////// /** * Checks if the target has any attached event handler. * @param target The object to check if an event is attached to it. * @param eventName The name of the event to check to see is attached. * @returns A boolean indicating if the specified event type is attached to the object. */ export function hasHandler(target: any, eventName: string): boolean; /** * Invokes an event on the target. This causes all handlers for the specified event name to be called. * @param target The object to invoke the event on. * @param eventName The name of the event to invoke. * @param args Arguments for the event handler. */ export function invoke(target: any, evenName: string, args: any): void; /** * Detaches the specified handler from the event. The handlerId is returned by the addHandler and addThrottledHandler methods. * @param handlerId The handler id of the event to remove. */ export function removeHandler(handlerId: IHandlerId): void; } /** * Standard compass headings; north, south, east, west. */ export class Heading { /** A heading pointing north, 0 degrees. */ static North: number; /** A heading pointing south, 180 degrees. */ static South: number; /** A heading pointing east, 90 degrees. */ static East: number; /** A heading pointing west, 270 degrees. */ static West: number; } /** * An infobox, also sometimes refer to as an info window or popup, is a simple panel that displays information over top the map. This is * often used to display information linked to a location after clicking on a pushpin. */ export class Infobox { /** * @constructor * @param location The location to display the infobox at. * @param options Options for rendering the infobox. */ constructor(location: Location, options?: IInfoboxOptions); /** * @deprecated Use HTML buttons and links in description instead. */ public getActions(): IInfoboxActions[]; /** * Gets the point on the infobox which is anchored to the map. An anchor of (0,0) is the top left corner of the infobox. * @returns The anchor point of the infobox. */ public getAnchor(): Point; /** * Gets the string that is printed inside the infobox. * @returns The description value of the infobox options. */ public getDescription(): string; /** * Gets the height of the infobox. * @returns The height of the infobox. */ public getHeight(): number; /** * Gets the infobox as HTML. * @returns The HTML string used to create a custom infobox. */ public getHtmlContent(): string; /** * Gets the location on the map where the infobox�s anchor is attached. * @returns The location of the infobox. */ public getLocation(): Location; /** * Gets the maximium height setting for the infobox. * @returns the maximium height setting for the infobox. */ public getMaxHeight(): number; /** * Gets the maximium width setting for the infobox. * @returns the maximium width setting for the infobox. */ public getMaxWidth(): number; /** * Gets the amount the infobox pointer is shifted from the location of the infobox, or if showPointer is false, then it is the amount the infobox * bottom left edge is shifted from the location of the infobox. The default value is (0,0), which means there is no offset. * @returns The offset of the infobox. */ public getOffset(): Point; /** * Gets the infobox options. * @returns The infobox options currently used by the infobox. */ public getOptions(): IInfoboxOptions; /** * Gets a boolean indicating whether the infobox close button is shown. * @returns A boolean indicating if the close button is shown or not. */ public getShowCloseButton(): boolean; /** * Gets a boolean indicating whether the infobox is drawn with a pointer. * @returns A boolean indicating if the pointer of the infobox is shown or not. */ public getShowPointer(): boolean; /** * Gets a string that is the title of the infobox. * @returns The title property of the infobox. */ public getTitle(): string; /** * Gets whether the infobox is visible. A value of false indicates that the infobox is hidden, although it is still an entity on the map. * @returns A boolean indicating if the infobox is visible or not. */ public getVisible(): boolean; /** * Gets the width of the infobox. * @returns The width of the infobox. */ public getWidth(): number; /** * Gets the z-index of the infobox. * @returns The z-index of the infobox. */ public getZIndex(): number; /** * Sets the HTML content of the infobox. You can use this method to change the look of the infobox. Note that infobox options are ignored if * custom HTML is set. Also, when custom HTML is used to represent the infobox, the infobox is anchored at the bottom-left corner. * @param content The HTML string to use to generate the infobox. */ public setHtmlContent(content: string): void; /** * Sets the location on the map where the anchor of the infobox is attached. * @param loc The location to display the infobox at. */ public setLocation(loc: Location): void; /** * Adds the infobox to the map. To remove an Infobox from the map, simply pass null into this function. * @param map A map instance to display the infoboox on, or null if removing infobox from map. */ public setMap(map: Map): void; /** * Sets options for the infobox. * @param options The options to assign to the infobox. */ public setOptions(options: IInfoboxOptions): void; } /** * The Layer class makes it easy to organize groups of data by storing them in separate layers on the map. Grouping your data into layers * provides a number of benefits such as the ability to hide or attach events to all IPrimitive shapes in a layer with a single line of code, * while also providing providing a performance benefit over manually looping through each shape and performing these tasks. */ export class Layer implements IDataLayer { /** Optional property to store any additional metadata for this layer. */ public metadata: any; /** * @constructor * @param id Unique string identifier for the layer. */ constructor(id?: string); /** * Adds a shapes to the layer, at the specified index if specified. * @param primitive The shape(s) to be added to the layer. * @param index The index at which to insert the shape into the layer. */ public add(primitive: IPrimitive | IPrimitive[], index?: number): void; /** * Clears all the data */ public clear(): void; /** * Cleans up any resources this object is consuming */ public dispose(): void; /** * Gets the id of the layer. * @returns The id assigned to the layer. */ public getId(): string; /** * Gets an array of shapes that are in the layer. This can be used to iterate over the individual shapes. * @returns An array of shapes that are in the layer. */ public getPrimitives(): IPrimitive[]; /** * Gets a value indicating whether the layer is visible or not. * @returns A boolean indicating if the layer is visible or not. */ public getVisible(): boolean; /** * Gets the zIndex of the layer. * @returns The zIndex of the layer. */ public getZIndex(): number; /** * Removes a primitive * @param primitive primitive that needs to be removed * @returns The primitive that needs to be removed */ public remove(primitive: IPrimitive): IPrimitive; /** * Removes a primitive at a specified index * @param index index of the primitive that needs to be removed * @returns The primitive that needs to be removed at this index */ public removeAt(index: number): IPrimitive; /** * Replaces all shapes in the layer with the new array of shapes that have been provided. * @param primitives The array of shapes to add to the layer. */ public setPrimitives(primitives: IPrimitive[]): void; /** * Sets whether the layer is visible or not. * @param value A value indicating if the layer should be displayed or not. */ public setVisible(value: boolean): void; /** * Sets the zIndex of the layer. * @param zIndex The zIndex value to assign to the layer. */ public setZIndex(zIndex: number): void; } /** * The layers property of the map is a LayerCollection object and contains all the layers that have been added to the map. * Note: This class is only exposed in the map.layers property. No other instance of this class can be created. */ export class LayerCollection extends Array { /** The number of layers in the collection. */ public length: number; /** * Removes all layers from the map. */ public clear(): void; /** * Gets the index of a layer in the collection. * @param layer The layer to get the index of. * @returns The index of the specified layer. */ public indexOf(layer: ILayer): number; /** * Adds a layer to the map. * @param layer The layer to insert into the collection. */ public insert(layer: ILayer): void; /** * Adds an array of layers to the map. * @param layers The layers to insert into the collection. */ public insertAll(layers: ILayer[]): void; /** * Removes a layer from the map. * @param layer The layer to remove from the collection. */ public remove(layer: ILayer): void; /** * Removes a layer from the map at the specified index in the collection. * @param idx The index of the layer to remove. */ public removeAt(idx: number): void; } /** * This class stores the coordinate information needed to mark locations on a map. The Location class consists of two properties: * latitude and longitude. */ export class Location { /** The location north or south of the equator from +90 to -90 */ public latitude: number; /** The location east or west of the prime meridian +180 to -180 */ public longitude: number; /** * @constructor * @param latitude The location north or south of the equator from +90 to -90 * @param longitude The location east or west of the prime meridian +180 to -180 */ constructor(latitude: any, longitude: any); /** * Determines if two locations are equal. * @param location1 The first location to test. * @param location2 The second location to test. * @returns True if both locations are equivalent. */ static areEqual(location1: Location, location2: Location): boolean; /** * Creates a deep copy of the map location. * @returns A deep copy of the map location. */ public clone(): Location; /** * Creates a proper Location from an object that has the same signature. * @param source A Location or Location-like object that contains the same properties. * @returns A copy of the map location. */ static cloneFrom(source: Location): Location; /** * Normalizes the longitude by wrapping it around the earth. * @param longitude The input longitude. * @returns The longitude normalized to within -180 and +180. */ static normalizeLongitude(longitude: number): number; /** * Parses a location string of the form "lat,long". * @param str The location string. * @returns The parsed location or null otherwise. */ static parseLatLong(str: string): Location; /** * Converts the Location to a string representation. * @returns A string representation of the location. */ public toString(): string; } /** * The LocationRect class, also known as a bounding box, consists of a set of coordinates that are used to represent rectangular area on the map. */ export class LocationRect { /** The location that defines the center of the rectangle. */ public center: Location; /** The height, in degrees, of the rectangle. */ public height: number; /** The width, in degrees, of the rectangle. */ public width: number; /** * @constructor * @param center The center of the LocationRect. * @param width The width of the LocationRect in degrees. * @param height The height of the LocationRect in degrees. */ constructor(center: Location, width: number, height: number); /** * Gets a LocationRect using the specified locations for the northwest and southeast corners. * @param northwest The north west corner of the LocationRect. * @param southeast The south east corner of the LocationRect. * @returns A LocationRect using the specified locations for the northwest and southeast corners. */ static fromCorners(northwest: Location, southeast: Location): LocationRect; /** * Gets a LocationRect using the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries. * @param north The northern latitude of the LocationRect. * @param west The western longitude of the LocationRect. * @param south The southern latitude of the LocationRect. * @param east The eastern longitude of the LocationRect. * @returns A LocationRect defined by the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries. */ static fromEdges(north: number, west: number, south: number, east: number): LocationRect; /** * Gets a LocationRect using a list of locations. * @param locations A list of locations. * @returns A LocationRect that encloses all the specified locations. */ static fromLocations(...locations: Location[]): LocationRect; /** * Gets a LocationRect using an array of locations. * @param locations An array of locations. * @returns A LocationRect that encloses all the specified locations. */ static fromLocations(locations: Location[]): LocationRect; /** * Creates a LocationRect from a string with the following format: "north,west,south,east". North, west, south and east specify the coordinate number values. * @param str A string that repsents a LocationRect with the format "north,west,south,east". * @returns A LocationRect defined by the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries that have been parsed by the string. */ static fromString(str: string): LocationRect; /** * Gets a copy of the LocationRect object. * @retruns A copy of the LocationRect object. */ public clone(): LocationRect; /** * Gets whether the specified Location is within the LocationRect. * @returns A boolean indicating if a location is within a LocationRect. */ public contains(location: Location): boolean; /** * Determines if the LocationRect crosses the 180th meridian. * @returns A boolean indicating if the LocationRect crosses the international date line (-180/180 degrees longitude). */ public crossesInternationalDateLine(): boolean; /** * Gets the longitude that defines the eastern edge of the LocationRect. * @returns The eastern longitude value of the LocationRect. */ public getEast(): number; /** * Gets the latitude that defines the northern edge of the LocationRect. * @returns The northern latitude value of the LocationRect. */ public getNorth(): number; /** * Gets the Location that defines the northwest corner of the LocationRect. * @returns The northwest corner location of the LocationRect. */ public getNorthwest(): Location; /** * Gets the latitude that defines the southern edge of the LocationRect. * @returns The southern latitude value of the LocationRect. */ public getSouth(): number; /** * Gets the Location that defines the southeast corner of the LocationRect. * @returns The southeast corner location of the LocationRect. */ public getSoutheast(): Location; /** * Gets the latitude that defines the western edge of the LocationRect. * @returns The western longitude value of the LocationRect. */ public getWest(): number; /** * Gets whether the specified LocationRect intersects with this LocationRect. * @param rect A second LocationRect to test for intersection with. * @returns A boolean indicating if a second LocationRect interests with this LocationRect. */ public intersects(rect: LocationRect): boolean; /** * Scales the size of a LocationRect by multiplying the width and height properties by a percentage. * @param percentage A percentage value to increase the size of the LocationRect by. */ public inflate(percentage: number): void; /** * If a LocationRect crosses the international date line, this method splits it into two LocationRect objects and returns them as an array. * @returns An array of LocationRects, that are split by the international date line (-180/180 degrees longitude) */ public splitByInternationalDateLine(): LocationRect[]; /** * Converts the LocationRect object to a string. * @returns A string version of the LocationRect. */ public toString(): string; } /** The map object generates an interactive map within a specified DOM element. */ export class Map { /** Entities of the map */ public entities: EntityCollection; /** Set of map layers */ public layers: LayerCollection; /** * @constructor * @param parentElement The parent element of the map as a CSS selector string or HTMLElement. * @param options Options used when creating the map. */ constructor(parentElement: string | HTMLElement, options: IMapLoadOptions); /** * Gets the streetside panorama information closest to the specified bounding box and returns using a success callback function. * This information can then be used to set the map view to that streetside panorama. */ public static getClosestPanorama(bounds: LocationRect, success: (panoramaInfo: IPanoramaInfo) => void, missingCoverage: () => void): void; /** Returns the branch name; release, experimental, frozen. */ public static getVersion(): string; /** Deletes the Map object and releases any associated resources. */ public dispose(): void; /** * Gets the location rectangle that defines the boundaries of the current map view. * @returns The location rectangle that defines the boundaries of the current map view. */ public getBounds(): LocationRect; /** * Gets the location of the center of the current map view. * @returns The location of the center of the current map view. */ public getCenter(): Location; /** * Gets to the specified callback an array of strings representing the attributions of the imagery currently displayed on the map. * @param callback The callback function that needs to be called after retrieving the copyright information. */ public getCopyrights(callback: (copyrights: string[]) => void): void; /** * Gets the session ID. This method calls the callback function with the session ID as the first parameter * @param callback The callback function that needs to be called with the session id. */ public getCredentials(callback: (creds: string) => void): void; /** * Gets the current culture. * @returns The current culture. */ public getCulture(): string; /** * Gets the height of the map control. * @returns The height of the map control. */ public getHeight(): number; /** * Returns the heading of the current map view. * @returns Returns the heading of the current map view. */ public getHeading(): number; /** * Gets the string that represents the imagery currently displayed on the map. * @returns The string that represents the imagery currently displayed on the map. */ public getImageryId(): string; /** * Gets a string that represents the current map type displayed on the map. * @returns A string that represents the current map type displayed on the map. */ public getMapTypeId(): MapTypeId; /** * Gets the current scale in meters per pixel of the center of the map. * @returns The current scale in meters per pixel of the center of the map. */ public getMetersPerPixel(): number; /** * Gets the map options that have been set. * @returns the map options that have been set. */ public getOptions(): IMapOptions; /** * Gets the x coordinate of the top left corner of the map control, relative to the page. * @returns The x coordinate of the top left corner of the map control, relative to the page. */ public getPageX(): number; /** * Gets the y coordinate of the top left corner of the map control, relative to the page. * @returns The y coordinate of the top left corner of the map control, relative to the page. */ public getPageY(): number; /** * Returns the pitch of the current streetside map view. * @returns Returns the pitch of the current streetside map view. */ public getPitch(): number; /** * Gets the map root node. * @returns the map root node. */ public getRootElement(): HTMLElement; /** * Gets the user region. * @returns The user region. */ public getUserRegion(): string; /** * Gets the width of the map control. * @returns the width of the map control. */ public getWidth(): number; /** * Gets the zoom level of the current map view. * @returns Returns the zoom level of the current map view. */ public getZoom(): number; /** * Gets the range of valid zoom levels for the current map view. * @returns The range of valid zoom levels for the current map view. */ public getZoomRange(): IRange; /** * Gets a boolean indicating whether the map is in a regular Mercator nadir mode. * @returns A boolean indicating whether the map is in a regular Mercator nadir mode. */ public isMercator(): boolean; /** * Gets a boolean indicating if the current map type allows the heading to change; false if the display heading is fixed. * @returns true if the current map type allows the heading to change; false if the display heading is fixed. */ public isRotationEnabled(): boolean; /** * Sets the current map type. * @param mapTypeId The map imagery type of the map to set. */ public setMapType(mapTypeId: MapTypeId): void; /** * Sets the map options. * @param options The map options to be set. */ public setOptions(options: IMapOptions): void; /** * Sets the view of the map. * @param viewOptions The view options to be set. */ public setView(viewOptions: IViewOptions): void; /** * Converts a specified Location or a Location array to a Point or Point array on the map * relative to the specified PixelReference. If no reference is specified, PixelReference.viewport * is taken. * @param location The given Location or Location[] to convert. * @param reference The PixelReference to specify the reference point. * @returns The converted Point or Point[], or null if the conversion fails. */ public tryLocationToPixel(location: Location | Location[], reference?: any): Point | Point[]; /** * Converts a specified Point or a Point array to a Location or Location array on the map * relative to the specified PixelReference. If no reference is specified, PixelReference.viewport * is taken. * @param point The given Point or Point[] to convert. * @param reference The PixelReference to specify the reference point. * @returns The converted Location or Location[], or null if the conversion fails. */ public tryPixelToLocation(point: Point | Point[], reference?: any): Location | Location[]; } /** * This class is used to represent a pixel coordinate or offset. This is often used by pushpin anchors, and map location to pixel conversion calculations. */ export class Point { /** The x coordinate */ public x: number; /** The y coordinate */ public y: number; /** * @constructor * @param x The x coordinate. * @param y The y coordinate. */ constructor(x: number, y: number); /** * Adds the x and y values of two points and returns a new Point. * @param point The point to add. * @returns A new point created by the sum of two points. */ public add(point: Point): Point; /** * Creates a copy of the current point. * @returns A new instance of the current point. */ public clone(): Point; /** * Compares the x and y values of two points to see if they are equal. If a tolerance value is specified, it checks to see if the linear distance between the points is less than or equal to the tolerance value. * @param point The point to compare to. * @param tolerance Optional, tolerance (>= 0) to avoid false result because of floating point errors. * @returns true if this point equals point, false otherwise */ public equals(point: Point, tolerance?: number): boolean; /** * Subtracts the x and y values of a points and returns a new Point. * @param point The point to subtract. * @returns A new point created by the subtraction of two points. */ public subtract(point: Point): Point; /** * Converts the Point to a string representation. * @returns A string representation of the point. */ public toString(): string; } /** * This compression algorithm encodes/decodes an array of locations into a string. * This algorithm is used for generating a compressed collection of locations for use * with the Bing Maps REST Elevation Service. This algorithm is also used for decoding * the compressed coordinates returned by the GeoData API. * * These algorithms come from the following documentation: * http://msdn.microsoft.com/en-us/library/jj158958.aspx * http://msdn.microsoft.com/en-us/library/dn306801.aspx */ export class PointCompression { /** * Decodes a collection of locations from a compressed string. * @param value Compressed string to decode. * @returns An array of locations that have been decoded from the compressed string. */ public static decode(value: string): Location[]; /** * Compresses an array of locations into a string. * @param locations Collection of coordinates to compress. * @returns A compressed string representing an array of locations. */ public static encode(locations: Location[]): string; } /** * A polygon is an area defined by a closed ring of locations. A simple polygon consists of an array of Location objects that form a boundary. * A complex polygon consists of several arrays of Locations, where the first array is the outline of the polygon, and the subsequent arrays are holes in the polygon. * The Polygon class derives from the IPrimitive interface. */ export class Polygon implements IPrimitive { /** * Information that is linked to the polygon. * Some modules such as the GeoJSON, and Spatial Data Service modules will also often add information to this property. */ public metadata: any; /** * @constructor * @param rings A Location array for basic polygon with single outer perimeter, * or an array of Location arrays for advanced polygon (multi-polygon, polygon with holes, or combination of polygons). * @param options Options used to customize polygon. */ constructor(rings: Location[] | Location[][], options?: IPolygonOptions); /** * Gets the css cursor value when polygon has events on it. * @returns CSS cursor string when polygon has events on it. */ public getCursor(): string; /** * Gets the fill color of the inside of the polygon. Will be string or Color object depending on the the what method was used in the pushpin options. * @returns The fill color of the inside of the polygon. */ public getFillColor(): string | Color; /** * Returns whether the polygon is generalizable based on zoom level or not. * @returns whether the polygon is generalizable based on zoom level or not. */ public getGeneralizable(): boolean; /** * Gets the first ring of the polygon (for V7 compatability). * @returns An array of Locations that is the first ring of the polygon; or an empty array if the polygon has no ring at all. */ public getLocations(): Location[]; /** * Gets an array of location arrays, where each location array defines a ring of the polygon. * @returns An array of location arrays, where each location array defines a ring of the polygon. */ public getRings(): Location[][]; /** * Gets the color of the border stroke of the polygon. Will be string or Color object depending on the the what method was used in the pushpin options. * @returns The color of the border stroke of the polygon. */ public getStrokeColor(): string | Color; /** * Gets the stroke dash array of the polygon, in format of either array or string, whichever user provides. * @returns The stroke dash array of the polygon. */ public getStrokeDashArray(): number[] | string; /** * Gets the thickness of the border stroke of the polygon. * @returns The thickness of the border stroke of the polygon as a number. */ public getStrokeThickness(): number; /** * Gets whether the polygon is visible. * @returns A boolean indicating whether the polygon is visible or not. */ public getVisible(): boolean; /** * Sets locations (single ring) of the polygon. (for V7 compatability) * @param locations A Location[] that defines the only ring of the polygon */ public setLocations(locations: Location[]): void; /** * Sets the properties for the polygon. * @param options The IPolygonOptions object containing the options to customize the polygon. */ public setOptions(options: IPolygonOptions): void; /** * Sets rings of the polygon. * @param rings A Location[][] where each Location[] defines a ring of the polygon. */ public setRings(rings: Location[] | Location[][]): void; } /** * Polylines allow you to draw connected lines on a map. In many spatial database systems, this is also known as a LineString. * The Polyline class derives from the IPrimitive interface. */ export class Polyline implements IPrimitive { /** * Information that is linked to the polyline. * Some modules such as the GeoJSON, and Spatial Data Service modules will also often add information to this property. */ public metadata: any; /** * @constructor * @param locations An array of locations that make up the path of the polyine. * @param options Options used to customize polyline. */ constructor(locations: Location[], options?: IPolylineOptions); /** * Gets the css cursor value when polyline has events on it. * @returns CSS cursor string when polyline has events on it. */ public getCursor(): string; /** * Returns whether the polyline is generalizable based on zoom level or not. * @returns whether the polyline is generalizable based on zoom level or not. */ public getGeneralizable(): boolean; /** * Gets the locations that make up the polyline. * @returns An array that defines the path of the polyline. */ public getLocations(): Location[]; /** * Gets the color of the border stroke of the polyline. Will be string or Color object depending on the the what method was used in the polyline options. * @returns The stroke color of the polyline. */ public getStrokeColor(): string | Color; /** * Gets the stroke dash array of the polyline, in format of either array or string, whichever user provides. * @returns The stroke dash array of the polyline. */ public getStrokeDashArray(): number[] | string; /** * Gets the thickness of the border stroke of the polyline. * @returns The thickness of the border stroke of the polyline as a number. */ public getStrokeThickness(): number; /** * Gets whether the polyline is visible. * @returns A boolean indicating whether the polyline is visible or not. */ public getVisible(): boolean; /** * Sets locations of the polyline. * @param locations A Location[] that defines path of the polyline */ public setLocations(locations: Location[]): void; /** * Sets the properties for the polyline. * @param options The IPolylineOptions object containing the options to customize the polyline. */ public setOptions(options: IPolylineOptions): void; } /** * Pushpins, sometimes also referred to as markers or MapIcons on other mapping platforms, are one of the primary ways of marking a location on a map. * The Pushpin class derives from the IPrimitive interface. */ export class Pushpin implements IPrimitive { /** * Information that is linked to the pushpin. * Some modules such as the GeoJSON, and Spatial Data Service modules will also often add information to this property. */ public metadata: any; /** * @constructor * @param location A Location object that specifies where to display the pushpin. * @param options Options used when creating the Pushpin. */ constructor(location: Location, options?: IPushpinOptions); /** * Gets the point on the Pushpin icon which is anchored to the pushpin location. * An anchor of (0,0) is the top left corner of the icon. * @returns The point on the Pushpin icon which is anchored to the pushpin location. */ public getAnchor(): Point; /** * Gets whether the pushpin clicked style is enabled * @returns Whether the pushpin clicked style is enabled. */ public getClickedStyleEnabled(): boolean; /** * Gets the color option of the pushpin. * @returns The color option of the pushpin. */ public getColor(): string | Color; /** * Gets the css cursor value when pushpin has events on it. * @returns CSS cursor string when pushpin has events on it. */ public getCursor(): string; /** * Gets a boolean indicating if the pushpin is draggable or not. * @returns A boolean indicating if the pushpin is draggable or not. */ public getDraggable(): boolean; /** * Gets whether the pushpin hover style is enabled * @returns Whether the pushpin hover style is enabled. */ public getHoverStyleEnabled(): boolean; /** * Gets the custom Pushpin source icon string which can be a url to an image or SVG, inline SVG string, or data URI. * @returns the custom Pushpin icon source string, which can be a url to an image or SVG, inline SVG string, or data URI. */ public getIcon(): string; /** * Returns the location of the pushpin. * @returns The location of the pushpin. */ public getLocation(): Location; /** * Returns whether the clickable area of the pushpin is an ellipse. * @returns A boolean indicating whether the clickable area of the pushpin is an ellipse. */ public getRoundClickableArea(): boolean; /** * Gets the subtitle label of the Pushpin. * @returns The subtitle label of the Pushpin. */ public getSubTitle(): string; /** * Gets the text within the Pushpin icon. * @returns The text within the Pushpin icon. */ public getText(): string; /** * Gets the amount the text is shifted from the Pushpin icon. * @returns the amount the text is shifted from the Pushpin icon. */ public getTextOffset(): Point; /** * Gets the title label of the Pushpin. * @returns the title label of the Pushpin. */ public getTitle(): string; /** * Gets whether the pushpin is visible. * @returns A boolean indicating whether the pushpin is visible or not. */ public getVisible(): boolean; /** * Sets the location of the Pushpin. * @param location The location of the Pushpin. */ public setLocation(location: Location): void; /** * Sets the properties for the pushpin. * @param options The IPushpinOptions object containing the options to customize the pushpin. */ public setOptions(options: IPushpinOptions): void; } /** * Used to represent the location of a map tile in the quadkey tile pyramid system used by the map. * If using a tile source where the uriConstructor property is set to a callback function, that callback function will recieve * an instance of the PyramidTileId class. */ export class PyramidTileId { /** The height of the tile. */ public pixelHeight: number; /** The width of the tile. */ public pixelWidth: number; /** The quadkey ID of the tile. */ public quadKey: string; /** The x tile coordinate. */ public x: number; /** The y tile coordinate. */ public y: number; /** The zoom level of the tile. */ public zoom: number; /** * @constructor * @param x The integer x position of the tile within the tile layer at the specified zoom level. * @param y The integer y position of the tile within the tile layer at the specified zoom level. * @param zoom The zoom level of the tile. * @param width The tile's width in pixels. Default value: 256 * @param height The tile's height in pixels. Default value: 256 */ constructor(x: number, y: number, zoom: number, width?: number, height?: number) /** * Compares two PyramidTileId objects and returns a boolean indicating if the two PyramidTileId are equal. * @param tileId1 The first PyramidTileId to compare to the second. * @param tileId2 The second PyramidTileId to compare to the first. * @returns A boolean indicating if the two PyramidTileId are equal. */ public static areEqual(tileId1: PyramidTileId, tileId2: PyramidTileId): boolean; /** * Generates a PyramidTileId from a quadkey tile id string. * @param quadkey The quadkey tile id string to convert into a PyramidTileId object. * @param width The tile's width in pixels. Default value: 256 * @param height The tile's height in pixels. Default value: 256 */ public static fromQuadKey(quadkey: string, width?: number, height?: number): PyramidTileId; } /** Provides static functions for generating random test data. */ export class TestDataGenerator { /** * Generates a random hex or rgba color string. * @param withAlpha A boolean indicating if the color should have an alpha value or not. if set to true, a rgba value will be returned with an alpha value of 0.5. * @returns A css color string, hex or rgba. */ public static getColor(withAlpha?: boolean): string; /** * Generates random Location objects. * @param num The number of locations to generate. If set to one a single Location will be returned. If greater than one and array will be returned. * @param bounds The bounding box in which all the locations should fall within. * @returns One or more random Locations. */ public static getLocations(num?: number, bounds?: LocationRect): Location | Location[]; /** * Generates random pushpins. * @param num The number of pushpins to generate. If set to one a single Pushpin will be returned. If greater than one and array will be returned. * @param bounds The bounding box in which all the pushpins should fall within. * @param options The options to use for rendering the pushpins. Default is random. * @returns One or more random Pushpins. */ public static getPushpins(num?: number, bounds?: LocationRect, options?: IPushpinOptions): Pushpin | Pushpin[]; /** * Generates random polylines. * @param num The number of polylines to generate. If set to one a single Polyline will be returned. If greater than one and array will be returned. * @param bounds The bounding box in which all the locations of the polylines should fall within. * @param size The number of locations each polylines should have. Default: random between 3 and 10. * @param scaleFactor A number that scales the size of the polylines based on size of the bounding box. A value of 0.1 would generate polylines that are no larger than 10% of the width/height of the map. Default: 0.1 * @param options The options to use for rendering the polylines. Default is random. * @returns One or more random Polylines. */ public static getPolylines(num?: number, bounds?: LocationRect, size?: number, scaleFactor?: number, options?: IPolylineOptions): Polyline | Polyline[]; /** * Generates random polygons. * @param num The number of polygons to generate. If set to one a single Polygon will be returned. If greater than one and array will be returned. * @param bounds The bounding box in which all the locations of the polygon should fall within. * @param size The number of locations each polygon should have. Default: random between 3 and 10. * @param scaleFactor A number that scales the size of the polygons based on the size of the bounding box. A value of 0.1 would generate polygons that are no larger than 10% of the width/height of the map. Default: 0.1 * @param options The options to use for rendering the polygons. Default is random. * @param addHole A boolean indicating if the generated polygon should have a hole or not. Note that this will double the number of Location objects that are in the Polygon. Default: false * @returns One or more random polygons. */ public static getPolygons(num?: number, bounds?: LocationRect, size?: number, scaleFactor?: number, options?: IPolygonOptions, addHole?: boolean): Polygon | Polygon[]; } /** Represents a tile layer that can be overlaid on top of the map. */ export class TileLayer implements ILayer { /** * @constructor * @param options The options to use to define the tile layer. */ constructor(options: ITileLayerOptions); /** * Gets the opacity of the tile layer, defined as a double between 0 (not visible) and 1. * @returns The opacity of the tile layer, defined as a double between 0 (not visible) and 1. */ public getOpacity(): number; /** * Gets the tile source of the tile layer. * @returns The tile source of the tile layer. */ public getTileSource(): TileSource; /** * Gets a boolean that indicates if the tile layer is visible or not. * @returns A boolean that indicates if the tile layer is visible or not. */ public getVisible(): boolean; /** * Gets the zIndex of the tile layer. * @returns The zIndex of the tile layer. */ public getZIndex(): number; /** * Sets the opacity of the tile layer. Value must be a number between 0 and 1. * @param opacity The opacity of the tile layer. Value must be a number between 0 and 1. */ public setOpacity(opacity: number): void; /** * Sets options for the tile layer. * @param options The options for the tile layer. */ public setOptions(options: ITileLayerOptions): void; /** * Sets the visibility of the tile layer. * @param show A boolean indicating if the tile layer should be visible or not. */ public setVisible(show: boolean): void; /** * Sets the zIndex of the tile layer. * @param idx The zIndex of the tile layer. */ public setZIndex(idx: number): void; } /** Defines the data source for a tile layer. */ export class TileSource { /** * @constructor * @param options The options to use to define the tile source. */ constructor(options: ITileSourceOptions); /** * Gets the specified bounding box of the of the tile source. * @returns The specified bounding box of the of the tile source. */ public getBounds(): LocationRect; /** * Gets the pixel height of each tile in the tile source. * @returns The pixel height of each tile in the tile source. */ public getHeight(): number; /** * Gets the maximum zoom level specified for the tile source. * @returns The maximum zoom level specified for the tile source. */ public getMaxZoom(): number; /** * Gets the minimum zoom level specified for the tile source. * @returns The minimum zoom level specified for the tile source. */ public getMinZoom(): number; /** * Gets a string that constructs tile URLs used to retrieve tiles for the tile layer. * @returns A string that constructs tile URLs used to retrieve tiles for the tile layer. */ public getUriConstructor(): string | ((tile: PyramidTileId) => string); /** * Gets the pixel width of each tile in the tile source. * @returns The pixel width of each tile in the tile source. */ public getWidth(): number; } }
the_stack
import { ChatManager } from './../../../../chat21-core/providers/chat-manager'; import { ConversationFooterComponent } from './../conversation-footer/conversation-footer.component'; // tslint:disable-next-line:max-line-length import { ElementRef, Component, OnInit, OnChanges, AfterViewInit, Input, Output, ViewChild, EventEmitter, SimpleChanges, ChangeDetectorRef } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { Globals } from '../../../utils/globals'; import { ConversationsService } from '../../../providers/conversations.service'; import { AppConfigService } from '../../../providers/app-config.service'; import { CHANNEL_TYPE_DIRECT, CHANNEL_TYPE_GROUP, TYPE_MSG_TEXT, MSG_STATUS_SENT, MSG_STATUS_RETURN_RECEIPT, MSG_STATUS_SENT_SERVER, UID_SUPPORT_GROUP_MESSAGES } from '../../../utils/constants'; import { StarRatingWidgetService } from '../../star-rating-widget/star-rating-widget.service'; // models import { MessageModel } from '../../../../chat21-core/models/message'; // utils import { isJustRecived, getUrlImgProfile, isPopupUrl, searchIndexInArrayForUid} from '../../../utils/utils'; import { v4 as uuidv4 } from 'uuid'; // Import the resized event model import {DomSanitizer} from '@angular/platform-browser'; import { AppComponent } from '../../../app.component'; import { CustomTranslateService } from '../../../../chat21-core/providers/custom-translate.service'; import { ConversationHandlerService } from '../../../../chat21-core/providers/abstract/conversation-handler.service'; import { ConversationHandlerBuilderService } from '../../../../chat21-core/providers/abstract/conversation-handler-builder.service'; import { popupUrl } from '../../../../chat21-core/utils/utils'; import { ConversationContentComponent } from '../conversation-content/conversation-content.component'; import { ConversationsHandlerService } from '../../../../chat21-core/providers/abstract/conversations-handler.service'; import { ArchivedConversationsHandlerService } from '../../../../chat21-core/providers/abstract/archivedconversations-handler.service'; import { ConversationModel } from '../../../../chat21-core/models/conversation'; import { AppStorageService } from '../../../../chat21-core/providers/abstract/app-storage.service'; import { LoggerService } from '../../../../chat21-core/providers/abstract/logger.service'; import { LoggerInstance } from '../../../../chat21-core/providers/logger/loggerInstance'; import { takeUntil } from 'rxjs/operators'; import { Subject } from 'rxjs'; // import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'chat-conversation', templateUrl: './conversation.component.html', styleUrls: ['./conversation.component.scss'], // tslint:disable-next-line:use-host-property-decorator host: {'(window:resize)': 'onResize($event)'} }) export class ConversationComponent implements OnInit, AfterViewInit, OnChanges { @ViewChild('afConversationComponent') private afConversationComponent: ElementRef; // l'ID del div da scrollare // @HostListener('window:resize', ['$event']) // ========= begin:: Input/Output values // @Input() elRoot: ElementRef; @Input() conversationId: string; @Input() stylesMap: Map<string, string>; @Input() isOpen: boolean; @Input() senderId: string; // uid utente ex: JHFFkYk2RBUn87LCWP2WZ546M7d2 @Input() isConversationArchived: boolean; @Output() onBackHome = new EventEmitter(); @Output() onCloseWidget = new EventEmitter(); @Output() onSoundChange = new EventEmitter(); @Output() onBeforeMessageSent = new EventEmitter(); @Output() onAfterSendMessage = new EventEmitter(); @Output() onNewConversationInit = new EventEmitter(); @Output() onBeforeMessageRender = new EventEmitter(); @Output() onAfterMessageRender = new EventEmitter(); @Output() onNewMessageCreated = new EventEmitter(); @Output() onNewConversationButtonClicked = new EventEmitter(); // ========= end:: Input/Output values // projectid: string; // uid progetto passato come parametro getVariablesFromSettings o getVariablesFromAttributeHtml // channelType: string; // tipo di conversazione ( group / direct ) a seconda che recipientId contenga o meno 'group' // writingMessage = ''; // messaggio sta scrivendo... // isTypings = false; conversation: ConversationModel conversationWith: string; isMenuShow = false; isButtonsDisabled = true; // isConversationArchived = false; hideFooterTextReply: boolean = false; footerMessagePlaceholder: string = ''; isTrascriptDownloadEnabled = false; audio: any; // ========= begin:: gestione scroll view messaggi ======= // //startScroll = true; // indica lo stato dello scroll: true/false -> è in movimento/ è fermo isScrolling = false; idDivScroll = 'c21-contentScroll'; // id div da scrollare showBadgeScroollToBottom = false; messagesBadgeCount = 0; // ========= end:: gestione scroll view messaggi ======= // // ========= begin:: send image ======= // selectedFiles: FileList; // isFilePendingToUpload: Boolean = false; arrayFilesLoad: Array<any>; isFileSelected: Boolean = false; isOpenAttachmentPreview: Boolean = false; attachments: Array<{ file: Array<any>, metadata: {}}> // userEmail: string; // userFullname: string; preChatForm = false; textInputTextArea: String; HEIGHT_DEFAULT = '20px'; isPopupUrl = isPopupUrl; popupUrl = popupUrl; IMG_PROFILE_SUPPORT = 'https://user-images.githubusercontent.com/32448495/39111365-214552a0-46d5-11e8-9878-e5c804adfe6a.png'; // availableAgentsStatus = false; // indica quando è impostato lo stato degli agenti nel subscribe messages: Array<MessageModel> = []; // recipient_fullname: string; // attributes: any; // GUEST_LABEL = ''; CLIENT_BROWSER: string = navigator.userAgent; // devo inserirle nel globals obsTyping: Subscription; subscriptions: Array<any> = []; private unsubscribe$: Subject<any> = new Subject<any>(); showMessageWelcome: boolean; // ========= begin::agent availability // public areAgentsAvailableText: string; // public areAgentsAvailable: Boolean = false; // ========= end::agent availability // ========== begin:: set icon status message MSG_STATUS_SENT = MSG_STATUS_SENT; MSG_STATUS_SENT_SERVER = MSG_STATUS_SENT_SERVER; MSG_STATUS_RETURN_RECEIPT = MSG_STATUS_RETURN_RECEIPT; // ========== end:: icon status message lastMsg = false; // _LABEL_PLACEHOLDER: string; isIE = /msie\s|trident\//i.test(window.navigator.userAgent); firstScroll = true; setTimeoutSound: NodeJS.Timer; public showSpinner = true; getUrlImgProfile = getUrlImgProfile; tooltipOptions = { 'show-delay': 1500, 'tooltip-class': 'chat-tooltip', 'theme': 'light', 'shadow': false, 'hide-delay-mobile': 0, 'hideDelayAfterClick': 3000, 'hide-delay': 200 }; translationMapHeader: Map<string, string>; translationMapFooter: Map<string, string>; translationMapContent: Map<string, string>; translationMapPreview: Map<string, string>; @ViewChild(ConversationFooterComponent) conversationFooter: ConversationFooterComponent @ViewChild(ConversationContentComponent) conversationContent: ConversationContentComponent conversationHandlerService: ConversationHandlerService conversationsHandlerService: ConversationsHandlerService archivedConversationsHandlerService: ArchivedConversationsHandlerService public isButtonUrl: boolean = false; public buttonClicked: any; private logger: LoggerService = LoggerInstance.getInstance(); constructor( //public el: ElementRef, public g: Globals, public starRatingWidgetService: StarRatingWidgetService, public sanitizer: DomSanitizer, public appComponent: AppComponent, public appStorageService: AppStorageService, public conversationsService: ConversationsService, public conversationHandlerBuilderService: ConversationHandlerBuilderService, public appConfigService: AppConfigService, private customTranslateService: CustomTranslateService, private chatManager: ChatManager, private changeDetectorRef: ChangeDetectorRef, private elementRef: ElementRef ) { } onResize(event){ this.logger.debug('[CONV-COMP] resize event', event) } ngOnInit() { // this.initAll(); this.logger.debug('[CONV-COMP] ngOnInit: ', this.senderId); this.showMessageWelcome = false; this.elementRef.nativeElement.style.setProperty('--themeColor', this.stylesMap.get('themeColor')) this.elementRef.nativeElement.style.setProperty('--foregroundColor', this.stylesMap.get('foregroundColor')) // const subscriptionEndRenderMessage = this.appComponent.obsEndRenderMessage.subscribe(() => { // this.ngZone.run(() => { // // that.scrollToBottom(); // }); // }); // this.subscriptions.push(subscriptionEndRenderMessage); // this.attributes = this.setAttributes(); // this.getTranslation(); this.translations(); //this.initAll(); } public translations() { const keysHeader = [ //'LABEL_AVAILABLE', //'LABEL_NOT_AVAILABLE', //'LABEL_TODAY', //'LABEL_TOMORROW', //'LABEL_TO', 'LABEL_LAST_ACCESS', //'ARRAY_DAYS', //'LABEL_ACTIVE_NOW', 'LABEL_WRITING', 'BUTTON_CLOSE_TO_ICON', 'OPTIONS', 'PREV_CONVERSATIONS', 'SOUND_OFF', 'SOUND_ON', 'DOWNLOAD_TRANSCRIPT', 'BACK', 'CLOSE' ]; const keysFooter = [ 'LABEL_PLACEHOLDER', 'GUEST_LABEL', 'LABEL_START_NW_CONV' ]; const keysContent = [ 'INFO_SUPPORT_USER_ADDED_SUBJECT', 'INFO_SUPPORT_USER_ADDED_YOU_VERB', 'INFO_SUPPORT_USER_ADDED_COMPLEMENT', 'INFO_SUPPORT_USER_ADDED_VERB', 'INFO_SUPPORT_CHAT_REOPENED', 'INFO_SUPPORT_CHAT_CLOSED', 'LABEL_TODAY', 'LABEL_TOMORROW', 'LABEL_LOADING', 'LABEL_TO', 'ARRAY_DAYS', ]; const keysPreview= [ 'BACK', 'CLOSE', 'LABEL_PLACEHOLDER', 'LABEL_PREVIEW' ]; this.translationMapHeader = this.customTranslateService.translateLanguage(keysHeader); this.translationMapFooter = this.customTranslateService.translateLanguage(keysFooter); this.translationMapContent = this.customTranslateService.translateLanguage(keysContent); this.translationMapPreview = this.customTranslateService.translateLanguage(keysPreview); } ngAfterViewInit() { // this.isShowSpinner(); this.logger.debug('[CONV-COMP] --------ngAfterViewInit: conversation-------- '); // this.storageService.setItem('activeConversation', this.conversation.uid); // --------------------------- // // after animation intro setTimeout(() => { this.initAll(); // this.setFocusOnId('chat21-main-message-context'); //this.updateConversationBadge(); this.g.currentConversationComponent = this; if (this.g.newConversationStart === true) { this.onNewConversationComponentInit(); this.g.newConversationStart = false; } this.setSubscriptions(); if (this.afConversationComponent) { this.afConversationComponent.nativeElement.focus(); } this.isButtonsDisabled = false; }, 300); // this.g.currentConversationComponent = this; // if (this.g.newConversationStart === true) { // this.onNewConversationComponentInit(); // // this.g.setParameter('newConversationStart', null) // this.g.newConversationStart = false; // // console.log('reset newconv ' + this.g.newConversationStart); // // do not send message hello // } // // ------------------------------------------------ // // this.g.wdLog([' --------ngAfterViewInit-------- ']); // // console.log('attributes: ', this.g.attributes); // //this.scrollToBottom(true); // this.setSubscriptions(); // setTimeout(() => { // if (this.afConversationComponent) { // this.afConversationComponent.nativeElement.focus(); // } // }, 1000); } ngAfterViewChecked(){ this.changeDetectorRef.detectChanges(); } ngOnChanges(changes: SimpleChanges) { this.logger.debug('[CONV-COMP] onChagnges', changes) if (this.isOpen === true) { //this.updateConversationBadge(); // this.scrollToBottom(); } } updateConversationBadge() { this.logger.debug('[CONV-COMP] updateConversationBadge', this.conversationId, this.isConversationArchived) if(this.isConversationArchived && this.conversationId && this.archivedConversationsHandlerService){ this.archivedConversationsHandlerService.setConversationRead(this.conversationId) } if (!this.isConversationArchived && this.conversationId && this.conversationsHandlerService) { this.conversationsHandlerService.setConversationRead(this.conversationId) const badgeNewConverstionNumber = this.conversationsHandlerService.countIsNew() this.g.setParameter('conversationsBadge', badgeNewConverstionNumber); } } // ngAfterViewChecked() { // this.isShowSpinner(); // this.cdRef.detectChanges(); // } // public isShowSpinner() { // const that = this; // setTimeout(() => { // that.showSpinner = false; // }, 5000); // } /** * do per scontato che this.userId esiste!!! */ initAll() { this.logger.debug('[CONV-COMP] ------ 2: setConversation ------ '); this.setConversation(); this.logger.debug('[CONV-COMP] ------ 3: connectConversation ------ '); // this.connectConversation(); this.initConversationHandler(); this.logger.debug('[CONV-COMP] ------ 4: initializeChatManager ------ '); //this.initializeChatManager(); // sponziello, commentato // this.logger.debug('[CONV-COMP] ------ 5: setAvailableAgentsStatus ------ '); // this.setAvailableAgentsStatus(); // this.logger.debug('[CONV-COMP] ------ 5: updateConversationbage ------ '); // this.updateConversationBadge(); this.logger.debug('[CONV-COMP] ------ 6: getConversationDetail ------ ', this.conversationId); this.getConversationDetail((isConversationArchived) => { this.logger.debug('[CONV-COMP] ------ 6: updateConversationbage ------ '); this.updateConversationBadge(); return; }) //check if conv is archived or not // this.checkListMessages(); if (this.g.customAttributes && this.g.customAttributes.recipient_fullname) { this.g.recipientFullname = this.g.customAttributes.recipient_fullname; } // try { // JSON.parse(this.g.customAttributes, (key, value) => { // if (key === 'recipient_fullname') { // this.g.recipientFullname = value; // } // }); // } catch (error) { // this.g.wdLog(['> Error :' + error]); // } } /** * @description get detail of conversation by uid and then return callback with conversation status * @param callback * @returns isConversationArchived (status conversation archived: boolean) */ getConversationDetail(callback:(isConversationArchived: boolean)=>void){ // if(!this.isConversationArchived){ //get conversation from 'conversations' firebase node this.logger.debug('[CONV-COMP] getConversationDetail: isConversationArchived???', this.isConversationArchived, this.conversationWith) this.conversationsHandlerService.getConversationDetail(this.conversationWith, (conv)=>{ this.logger.debug('[CONV-COMP] getConversationDetail: conversationsHandlerService ', this.conversationWith, conv, this.isConversationArchived) if(conv){ this.conversation = conv; this.isConversationArchived = false; callback(this.isConversationArchived) } if(!conv){ //get conversation from 'archivedconversations' firebase node this.logger.debug('[CONV-COMP] getConversationDetail: conv not exist --> search in archived list') this.archivedConversationsHandlerService.getConversationDetail(this.conversationWith, (conv)=>{ this.logger.debug('[CONV-COMP] getConversationDetail: archivedConversationsHandlerService', this.conversationWith, conv, this.isConversationArchived) if(conv){ this.conversation = conv; this.isConversationArchived = true; callback(this.isConversationArchived) }else if(!conv) { callback(null); } }) } }) // } else { //get conversation from 'conversations' firebase node // this.archivedConversationsHandlerService.getConversationDetail(this.conversationId, (conv)=>{ // this.logger.debug('[CONV-COMP] archivedConversationsHandlerService getConversationDetail', this.conversationId, conv, this.isConversationArchived) // if(conv){ // this.conversation = conv; // this.isConversationArchived = true; // callback(this.isConversationArchived) // } // if(!conv){ // this.conversationsHandlerService.getConversationDetail(this.conversationId, (conv)=>{ // this.logger.debug('[CONV-COMP] conversationsHandlerService getConversationDetail', this.conversationId, conv, this.isConversationArchived) // conv? this.isConversationArchived = false : null // this.conversation = conv; // callback(this.isConversationArchived) // }) // } // }) // } // if(!this.isConversationArchived){ //get conversation from 'conversations' firebase node // this.conversationsHandlerService.getConversationDetail(this.conversationId, (conv)=>{ // this.logger.debug('[CONV-COMP] conversationsHandlerService getConversationDetail', this.conversationId, conv) // this.conversation = conv; // callback(this.isConversationArchived) // }) // }else { //get conversation from 'conversations' firebase node // this.archivedConversationsHandlerService.getConversationDetail(this.conversationId, (conv)=>{ // this.logger.debug('[CONV-COMP] archivedConversationsHandlerService getConversationDetail', this.conversationId, conv) // this.conversation = conv; // callback(this.isConversationArchived) // }) // } // this.updateConversationBadge() } // onResize(event) { // // tslint:disable-next-line:no-unused-expression // this.g.wdLog(['RESIZE ----------> ' + event.target.innerWidth]); // } /** * OLD: mi sottoscrivo al nodo /projects/' + projectId + '/users/availables * i dipartimenti e gli agenti disponibili sono già stati impostati nello step precedente * recuperati dal server (/widget) e settati in global * imposto il messaggio online/offline a seconda degli agenti disponibili * aggiungo il primo messaggio alla conversazione */ // public setAvailableAgentsStatus() { // const departmentDefault: DepartmentModel = this.g.departmentDefault; // this.g.wdLog(['departmentDefault', departmentDefault]); // this.g.wdLog(['messages1: ', this.g.online_msg, this.g.offline_msg]); // if (!this.g.online_msg || this.g.online_msg === 'undefined' || this.g.online_msg === '') { // this.g.online_msg = this.g.LABEL_FIRST_MSG; // } // if (!this.g.offline_msg || this.g.offline_msg === 'undefined' || this.g.offline_msg === '') { // this.g.offline_msg = this.g.LABEL_FIRST_MSG_NO_AGENTS; // } // this.g.wdLog(['messages2: ', this.g.online_msg, this.g.offline_msg]); // const availableAgentsForDep = this.g.availableAgents; // if (availableAgentsForDep && availableAgentsForDep.length <= 0) { // this.addFirstMessage(this.g.offline_msg); // this.g.areAgentsAvailableText = this.g.AGENT_NOT_AVAILABLE; // // no more used g.areAgentsAvailableText - g.AGENT_NOT_AVAILABLE is managed in the template // } else { // this.addFirstMessage(this.g.online_msg); // this.g.areAgentsAvailableText = this.g.AGENT_AVAILABLE; // // no more used g.areAgentsAvailableText - g.AGENT_AVAILABLE is managed in the template // } // if ( this.g.recipientId.includes('_bot') || this.g.recipientId.includes('bot_') ) { // this.g.areAgentsAvailableText = ''; // } // this.g.wdLog(['messages: ', this.g.online_msg, this.g.offline_msg]); // // this.getAvailableAgentsForDepartment(); // } /** * mi sottoscrivo al nodo /departments/' + idDepartmentSelected + '/operators/'; * per verificare se c'è un agent disponibile */ // private getAvailableAgentsForDepartment() { // const that = this; // const projectid = this.g.projectid; // const departmentSelectedId = this.g.attributes.departmentId; // this.g.wdLog(['departmentSelectedId: ', departmentSelectedId, 'projectid: ', projectid]); // this.agentAvailabilityService // .getAvailableAgentsForDepartment(projectid, departmentSelectedId) // .subscribe( (availableAgents) => { // const availableAgentsForDep = availableAgents['available_agents']; // if (availableAgentsForDep && availableAgentsForDep.length <= 0) { // that.addFirstMessage(that.g.LABEL_FIRST_MSG_NO_AGENTS); // } else { // that.addFirstMessage(that.g.LABEL_FIRST_MSG); // } // }, (error) => { // console.error('2 setOnlineStatus::setAvailableAgentsStatus', error); // }, () => { // }); // } /** * mi sottoscrivo al nodo /projects/' + projectId + '/users/availables * per verificare se c'è un agent disponibile */ // private setAvailableAgentsStatus() { // const that = this; // this.agentAvailabilityService // .getAvailableAgents(this.g.projectid) // .subscribe( (availableAgents) => { // that.g.wdLog(['availableAgents->', availableAgents]); // if (availableAgents.length <= 0) { // that.areAgentsAvailable = false; // that.areAgentsAvailableText = that.g.AGENT_NOT_AVAILABLE; // that.addFirstMessage(that.g.LABEL_FIRST_MSG_NO_AGENTS); // } else { // that.areAgentsAvailable = true; // that.areAgentsAvailableText = that.g.AGENT_AVAILABLE; // // add first message // this.g.availableAgents = availableAgents; // that.addFirstMessage(that.g.LABEL_FIRST_MSG); // } // that.availableAgentsStatus = true; // that.g.wdLog(['AppComponent::setAvailableAgentsStatus::areAgentsAvailable:', that.areAgentsAvailableText]); // }, (error) => { // console.error('setOnlineStatus::setAvailableAgentsStatus', error); // }, () => { // }); // } // addFirstMessage(text) { // const lang = this.g.lang; // const channelType = this.g.channelType; // const projectid = this.g.projectid; // text = replaceBr(text); // const timestampSendingMessage = new Date('01/01/2000').getTime(); // const msg = new MessageModel( // '000000', // lang, // this.conversationWith, // 'Bot', // '', // sender // 'Bot', // sender fullname // '200', // status // '', // metadata // text, // timestampSendingMessage, // '', // TYPE_MSG_TEXT, // '', // attributes // channelType, // projectid // ); // this.g.wdLog(['addFirstMessage ----------> ' + text]); // this.messages.unshift(msg); // } /** * this.g.recipientId: * this.g.senderId: * this.g.channelType: * this.g.tenant * 1 - setto channelTypeTEMP ( group / direct ) * a seconda che recipientId contenga o meno 'group' * 2 - setto conversationWith * 2 - setto conversationWith * uguale a recipientId se esiste * uguale al senderId nel this.storageService se esiste * generateUidConversation */ private setConversation() { const recipientId = this.g.recipientId; const channelType = this.g.channelType; this.logger.debug('[CONV-COMP] setConversation recipientId::: ', recipientId, channelType); if ( !recipientId ) { this.g.setParameter('recipientId', this.setRecipientId()); } if ( !channelType ) { this.g.setParameter('channelType', this.setChannelType()); } this.conversationWith = recipientId as string; this.logger.debug('[CONV-COMP] setConversation conversation::: ', this.conversation); if (!this.conversation) { // this.conversation = new ConversationModel( // recipientId, // {}, // channelType, // true, // '', // recipientId, // this.g.recipientFullname, // this.senderId, // this.g.userFullname, // '0', // 0, // TYPE_MSG_TEXT, // '', // '', // '', // '', // 0, // false // ); this.conversation = new ConversationModel( recipientId, this.g.attributes, channelType, this.g.recipientFullname, this.conversationWith, recipientId, this.g.recipientFullname, '', true, '', '', this.senderId, '', this.g.userFullname, '0', '', true, '', '', false, 'text') } } /** * */ private setRecipientId() { let recipientIdTEMP: string; const senderId = this.senderId; recipientIdTEMP = this.appStorageService.getItem(senderId); if (!recipientIdTEMP) { // questa deve essere sincrona!!!! // recipientIdTEMP = UID_SUPPORT_GROUP_MESSAGES + uuidv4(); >>>>>OLD recipientIdTEMP = UID_SUPPORT_GROUP_MESSAGES + this.g.projectid + '-' + uuidv4().replace(/-/g, ''); this.logger.debug('[CONV-COMP] recipitent', recipientIdTEMP) //recipientIdTEMP = this.messagingService.generateUidConversation(senderId); } return recipientIdTEMP; } /** * */ private setChannelType() { let channelTypeTEMP = CHANNEL_TYPE_GROUP; const projectid = this.g.projectid; if (this.g.recipientId && this.g.recipientId.indexOf('group') !== -1) { channelTypeTEMP = CHANNEL_TYPE_GROUP; } else if (!projectid) { channelTypeTEMP = CHANNEL_TYPE_DIRECT; } return channelTypeTEMP; } /** * 1 - init messagingService * 2 - connect: recupero ultimi X messaggi */ // private connectConversation() { // const senderId = this.g.senderId; // const tenant = this.g.tenant; // const channelType = this.g.channelType; // if (!this.conversationWith && this.g.recipientId) { // this.conversationWith = this.g.recipientId; // } // // console.log('connectConversation -- >: ', senderId, tenant, channelType, this.conversationWith, this.g.recipientId); // this.messagingService.initialize( senderId, tenant, channelType ); // this.messagingService.initWritingMessages(this.conversationWith); // this.messagingService.getWritingMessages(); // // this.upSvc.initialize(senderId, tenant, this.conversationWith); // // his.contactService.initialize(senderId, tenant, this.conversationWith); // this.messagingService.connect( this.conversationWith ); // this.messages = this.messagingService.messages; // // this.scrollToBottomStart(); // // this.messages.concat(this.messagingService.messages); // // this.messagingService.resetBadge(this.conversationWith); // } /** * recupero da chatManager l'handler * se NON ESISTE creo un handler e mi connetto e lo memorizzo nel chatmanager * se ESISTE mi connetto * carico messaggi * attendo x sec se nn arrivano messaggi visualizzo msg welcome */ initConversationHandler() { const tenant = this.g.tenant; this.messages = []; //TODO-GAB: da sistemare loggedUser in firebase-conversation-handler.service const loggedUser = { uid: this.senderId} const conversationWithFullname = this.g.recipientFullname; // TODO-GAB: risulta null a questo punto this.logger.debug('[CONV-COMP] initconversation NEWWW', loggedUser, conversationWithFullname, tenant) this.showMessageWelcome = false; const handler: ConversationHandlerService = this.chatManager.getConversationHandlerByConversationId(this.conversationWith); this.logger.debug('[CONV-COMP] DETTAGLIO CONV - handler **************', handler, this.conversationWith); if (!handler) { this.conversationHandlerService = this.conversationHandlerBuilderService.build(); this.conversationHandlerService.initialize( this.conversationWith, conversationWithFullname, loggedUser, tenant, this.translationMapContent ); this.conversationHandlerService.connect(); this.logger.debug('[CONV-COMP] DETTAGLIO CONV - NEW handler **************', this.conversationHandlerService); this.messages = this.conversationHandlerService.messages; /* SEND FIRST MESSAGE if preChatForm has 'firstMessage' key */ this.sendFirstMessagePreChatForm() this.logger.debug('[CONV-COMP] DETTAGLIO CONV - messages **************', this.messages); this.chatManager.addConversationHandler(this.conversationHandlerService); // attendo un secondo e poi visualizzo il messaggio se nn ci sono messaggi const that = this; setTimeout( () => { if (!that.messages || that.messages.length === 0) { //this.showIonContent = true; that.showMessageWelcome = true; // that.sendFirstMessage() that.logger.debug('[CONV-COMP] setTimeout ***', that.showMessageWelcome); } }, 8000); } else { this.logger.debug('[CONV-COMP] NON ENTRO ***', this.conversationHandlerService, handler); this.conversationHandlerService = handler; this.messages = this.conversationHandlerService.messages; // sicuramente ci sono messaggi // la conversazione l'ho già caricata precedentemente // mi arriva sempre notifica dell'ultimo msg (tramite BehaviorSubject) // scrollo al bottom della pagina } this.logger.debug('[CONV-COMP] CONVERSATION MESSAGES ' + this.messages ); //retrive active and archived conversations-handler service this.conversationsHandlerService = this.chatManager.conversationsHandlerService this.archivedConversationsHandlerService = this.chatManager.archivedConversationsService } /** * se nel preChatForm c'è una chiave 'firstMessage' * e la conversazione non ha altri messaggi, invio il firstMessage * del preChatForm appena compilato */ sendFirstMessagePreChatForm(){ setTimeout(() => { if(this.messages && this.messages.length === 0){ this.logger.debug('[CONV-COMP] sendFirstMessage: messages + attributes ',this.messages, this.g.attributes) if(this.g.attributes && this.g.attributes.preChatForm && this.g.attributes.preChatForm.firstMessage){ const firstMessage = this.g.attributes.preChatForm.firstMessage this.conversationFooter.sendMessage(firstMessage, TYPE_MSG_TEXT, this.g.attributes) } } }, 1000); } /** * inizializzo variabili * effettuo il login anonimo su firebase * se il login è andato a buon fine recupero id utente */ // initializeChatManager() { // this.arrayFilesLoad = []; // // this.setSubscriptions(); // // this.checkWritingMessages(); // } /** * */ // setAttributes(): any { // if (!this.g.attributes || this.g.attributes === 'undefined') { // let attributes: any = JSON.parse(this.storageService.getItem('attributes')); // if (!attributes || attributes === 'undefined') { // attributes = { // client: this.CLIENT_BROWSER, // sourcePage: location.href, // projectId: this.g.projectid // }; // } // if (this.g.userEmail) { // attributes['userEmail'] = this.g.userEmail; // } // if (this.g.userFullname) { // attributes['userFullname'] = this.g.userFullname; // } // if (this.g.senderId) { // attributes['requester_id'] = this.g.senderId; // } // that.g.wdLog(['>>>>>>>>>>>>>> setAttributes: ', JSON.stringify(attributes)]); // this.storageService.setItem('attributes', JSON.stringify(attributes)); // return attributes; // } // return this.g.attributes; // } /** * imposto le sottoscrizioni * 1 - conversazione chiusa (CHAT CHIUSA) * 2 - nuovo messaggio */ setSubscriptions() { const that = this; let subscribtion: any; let subscribtionKey: string; subscribtionKey = 'starRating'; subscribtion = this.subscriptions.find(item => item.key === subscribtionKey); if (!subscribtion) { this.starRatingWidgetService.setOsservable(false); // CHIUSURA CONVERSAZIONE (ELIMINAZIONE UTENTE DAL GRUPPO) // tslint:disable-next-line:max-line-length this.logger.debug('[CONV-COMP] setSubscriptions!!!! StartRating', this.starRatingWidgetService.obsCloseConversation.value); subscribtion = this.starRatingWidgetService.obsCloseConversation.pipe(takeUntil(this.unsubscribe$)).subscribe(isOpenStartRating => { this.logger.debug('[CONV-COMP] startratingggg', isOpenStartRating) that.g.setParameter('isOpenStartRating', isOpenStartRating); if (isOpenStartRating === false) { this.logger.debug('[CONV-COMP] NOT OPEN StartRating **'); } else if (isOpenStartRating === true) { this.logger.debug('[CONV-COMP] OPEN StartRating **'); } }); const subscribe = {key: subscribtionKey, value: subscribtion }; this.subscriptions.push(subscribe); } subscribtionKey = 'messageAdded'; subscribtion = this.subscriptions.find(item => item.key === subscribtionKey); if (!subscribtion) { this.logger.debug('[CONV-COMP] ***** add messageAdded *****', this.conversationHandlerService); subscribtion = this.conversationHandlerService.messageAdded.pipe(takeUntil(this.unsubscribe$)).subscribe((msg: MessageModel) => { this.logger.debug('[CONV-COMP] ***** DATAIL messageAdded *****', msg); if (msg) { that.newMessageAdded(msg); this.onNewMessageCreated.emit(msg) this.checkMessagesLegntForTranscriptDownloadMenuOption(); } }); const subscribe = {key: subscribtionKey, value: subscribtion }; this.subscriptions.push(subscribe); } subscribtionKey = 'conversationsRemoved'; subscribtion = this.subscriptions.find(item => item.key === subscribtionKey); if(!subscribtion){ subscribtion = this.chatManager.conversationsHandlerService.conversationRemoved.pipe(takeUntil(this.unsubscribe$)).subscribe((conversation) => { this.logger.debug('[CONV-COMP] ***** DATAIL conversationsRemoved *****', conversation, this.conversationWith, this.isConversationArchived); if(conversation && conversation.uid === this.conversationWith && !this.isConversationArchived){ this.starRatingWidgetService.setOsservable(true) this.isConversationArchived = true; } }); const subscribe = {key: subscribtionKey, value: subscribtion }; this.subscriptions.push(subscribe); } subscribtionKey = 'conversationsChanged'; subscribtion = this.subscriptions.find(item => item.key === subscribtionKey); if(!subscribtion){ subscribtion = this.chatManager.conversationsHandlerService.conversationChanged.pipe(takeUntil(this.unsubscribe$)).subscribe((conversation) => { this.logger.debug('[CONV-COMP] ***** DATAIL conversationsChanged *****', conversation, this.conversationWith, this.isConversationArchived); if(conversation && conversation.sender !== this.senderId){ const checkContentScrollPosition = that.conversationContent.checkContentScrollPosition(); if(checkContentScrollPosition && conversation.is_new){ //update conversation if scroolToBottom is to the end this.logger.debug('[CONV-COMP] updateConversationBadge...') that.updateConversationBadge(); } } }); const subscribe = {key: subscribtionKey, value: subscribtion }; this.subscriptions.push(subscribe); } // this.starRatingWidgetService.setOsservable(false); // // CHIUSURA CONVERSAZIONE (ELIMINAZIONE UTENTE DAL GRUPPO) // // tslint:disable-next-line:max-line-length // that.g.wdLog(['setSubscriptions!!!! StartRating', this.starRatingWidgetService.obsCloseConversation, this.starRatingWidgetService]); // const subscriptionisOpenStartRating: Subscription = this.starRatingWidgetService.obsCloseConversation // .subscribe(isOpenStartRating => { // that.g.setParameter('isOpenStartRating', isOpenStartRating); // if (isOpenStartRating === false) { // that.g.wdLog(['CHIUDOOOOO!!!! StartRating']); // } else if (isOpenStartRating === true) { // that.g.wdLog(['APROOOOOOOO!!!! StartRating']); // } // }); // this.subscriptions.push(subscriptionisOpenStartRating); // console.log('---------------------->', this.subscriptions); // NUOVO MESSAGGIO!! /** * se: non sto già scrollando oppure il messaggio l'ho inviato io -> scrollToBottom * altrimenti: se esiste scrollMe (div da scrollare) verifico la posizione * se: sono alla fine della pagina scrollo alla fine * altrimenti: aumento il badge */ // const obsAddedMessage: Subscription = this.messagingService.obsAdded // .subscribe(newMessage => { // that.g.wdLog(['Subscription NEW MSG', newMessage]); // const senderId = that.g.senderId; // if ( that.startScroll || newMessage.sender === senderId) { // that.g.wdLog(['*A 1-------']); // setTimeout(function () { // that.scrollToBottom(); // }, 200); // } else if (that.scrollMe) { // const divScrollMe = that.scrollMe.nativeElement; // const checkContentScrollPosition = that.checkContentScrollPosition(divScrollMe); // if (checkContentScrollPosition) { // that.g.wdLog(['*A2-------']); // // https://developer.mozilla.org/it/docs/Web/API/Element/scrollHeight // setTimeout(function () { // that.scrollToBottom(); // }, 0); // } else { // that.g.wdLog(['*A3-------']); // that.NUM_BADGES++; // // that.soundMessage(newMessage.timestamp); // } // } // /** // * // */ // if (newMessage && newMessage.text && that.lastMsg) { // setTimeout(function () { // let messaggio = ''; // const testFocus = ((document.getElementById('testFocus') as HTMLInputElement)); // const altTextArea = ((document.getElementById('altTextArea') as HTMLInputElement)); // if (altTextArea && testFocus) { // setTimeout(function () { // if (newMessage.sender !== that.g.senderId) { // messaggio += 'messaggio ricevuto da operatore: ' + newMessage.sender_fullname; // altTextArea.innerHTML = messaggio + ', testo messaggio: ' + newMessage.text; // testFocus.focus(); // } // }, 1000); // } // }, 1000); // } // }); // this.subscriptions.push(obsAddedMessage); //this.subscriptionTyping(); } checkMessagesLegntForTranscriptDownloadMenuOption(){ if(this.messages.length > 1 && this.g.allowTranscriptDownload){ this.isTrascriptDownloadEnabled = true } } // NUOVO MESSAGGIO!! /** * se: non sto già scrollando oppure il messaggio l'ho inviato io -> scrollToBottom * altrimenti: se esiste scrollMe (div da scrollare) verifico la posizione * se: sono alla fine della pagina scrollo alla fine * altrimenti: aumento il badge */ newMessageAdded(msg){ const that = this; const senderId = that.senderId; if (msg.sender === senderId) { //caso in cui sender manda msg that.logger.debug('[CONV-COMP] *A1-------'); setTimeout(function () { that.conversationContent.scrollToBottom(); }, 200); } else if (msg.sender !== senderId) { //caso in cui operatore manda msg const checkContentScrollPosition = that.conversationContent.checkContentScrollPosition(); if (checkContentScrollPosition) { that.logger.debug('[CONV-COMP] *A2-------'); // https://developer.mozilla.org/it/docs/Web/API/Element/scrollHeight setTimeout(function () { that.conversationContent.scrollToBottom(); }, 0); } else { that.logger.debug('[CONV-COMP] *A3-------'); that.messagesBadgeCount++; // that.soundMessage(msg.timestamp); } // check if sender can reply --> set footer active/disabled if(msg.attributes && msg.attributes['disableInputMessage']){ this.hideFooterTextReply = msg.attributes['disableInputMessage'] } else if (msg.attributes && !msg.attributes['disableInputMessage']) { this.hideFooterTextReply = false } // check if footer text placebolder exist --> set new footer text placeholder if(msg.attributes && msg.attributes['inputMessagePlaceholder']) { this.footerMessagePlaceholder = msg.attributes['inputMessagePlaceholder'] }else { this.footerMessagePlaceholder = ''; } //check if user has changed userFullName and userEmail if (msg.attributes && msg.attributes['updateUserFullname']) { const userFullname = msg.attributes['updateUserFullname']; that.logger.debug('[CONV-COMP] newMessageAdded --> updateUserFullname', userFullname) that.g.setAttributeParameter('userFullname', userFullname); that.g.setParameter('userFullname', userFullname); that.appStorageService.setItem('attributes', JSON.stringify(that.g.attributes)); } if (msg.attributes && msg.attributes['updateUserEmail']) { const userEmail = msg.attributes['updateUserEmail']; that.logger.debug('[CONV-COMP] newMessageAdded --> userEmail', userEmail) that.g.setAttributeParameter('userEmail', userEmail); that.g.setParameter('userEmail', userEmail); that.appStorageService.setItem('attributes', JSON.stringify(that.g.attributes)); } } } /** * */ // private checkWritingMessages() { // const that = this; // const tenant = this.g.tenant; // try { // const messagesRef = this.messagingService.checkWritingMessages(tenant, this.conversationWith); // if (messagesRef) { // messagesRef.on('value', function (writing) { // if (writing.exists()) { // that.writingMessage = that.g.LABEL_WRITING; // } else { // that.writingMessage = ''; // } // }); // } // } catch (e) { // this.g.wdLog(['> Error :' + e]); // } // } /** * */ //checkListMessages() { // const that = this; // this.messagingService.checkListMessages(this.conversationWith) // .then(function (snapshot) { // that.g.wdLog(['checkListMessages: ', snapshot); // if (snapshot.exists()) { // that.isNewConversation = false; // that.g.wdLog(['IS NOT NEW CONVERSATION ?', that.isNewConversation); // setTimeout(function () { // if (that.messages.length === 0) { // that.isNewConversation = true; // } // }, 2000); // // that.isLogged = true; // // that.g.wdLog(['IS_LOGGED', 'AppComponent:createConversation:snapshot.exists-if', that.isLogged); // // that.setFocusOnId('chat21-main-message-context'); // } else { // /** // * se è una nuova conversazione: // * verifico se departmentId e projectid sono settati // * focus sul input messaggio // */ // that.isNewConversation = true; // that.g.wdLog(['IS NEW CONVERSATION ?', that.isNewConversation); // //if (that.g.projectid && !that.g.attributes.departmentId) { // // that.isLogged = false; // // that.g.wdLog(["IS_LOGGED", "AppComponent:createConversation:snapshot.exists-else-!department", that.isLogged); // //that.getMongDbDepartments(); // //} else { // that.setFocusOnId('chat21-main-message-context'); // //that.isLogged = true; // // that.g.wdLog(['IS_LOGGED', 'AppComponent:createConversation:snapshot.exists-else-department', that.isLogged); // //} // } // setTimeout(function () { // that.g.wdLog(['GET listMessages: ', that.conversationWith); // that.messagingService.listMessages(that.conversationWith); // }, 500); // }).catch(function (error) { // console.error('checkListMessages ERROR: ', error); // }); //} // setFocusOnId(id) { // setTimeout(function () { // const textarea = document.getElementById(id); // if (textarea) { // // that.g.wdLog(['1--------> FOCUSSSSSS : ', textarea); // textarea.setAttribute('value', ' '); // textarea.focus(); // } // }, 500); // } // /** // * quando premo un tasto richiamo questo metodo che: // * verifica se è stato premuto 'invio' // * se si azzera testo // * imposta altezza campo come min di default // * leva il focus e lo reimposta dopo pochi attimi // * (questa è una toppa per mantenere il focus e eliminare il br dell'invio!!!) // * invio messaggio // * @param event // */ // onkeypress(event) { // const keyCode = event.which || event.keyCode; // this.textInputTextArea = ((document.getElementById('chat21-main-message-context') as HTMLInputElement).value); // // this.g.wdLog(['onkeypress **************', this.textInputTextArea]); // if (keyCode === 13) { // this.performSendingMessage(); // } else if (keyCode === 9) { // event.preventDefault(); // } // } // private performSendingMessage() { // // const msg = document.getElementsByClassName('f21textarea')[0]; // let msg = ((document.getElementById('chat21-main-message-context') as HTMLInputElement).value); // if (msg && msg.trim() !== '') { // // that.g.wdLog(['sendMessage -> ', this.textInputTextArea); // // this.resizeInputField(); // // this.messagingService.sendMessage(msg, TYPE_MSG_TEXT); // // this.setDepartment(); // msg = replaceBr(msg); // this.sendMessage(msg, TYPE_MSG_TEXT); // // this.restoreTextArea(); // } // // (<HTMLInputElement>document.getElementById('chat21-main-message-context')).value = ''; // // this.textInputTextArea = ''; // // this.restoreTextArea(); // } // private restoreTextArea() { // // that.g.wdLog(['AppComponent:restoreTextArea::restoreTextArea'); // this.resizeInputField(); // const textArea = (<HTMLInputElement>document.getElementById('chat21-main-message-context')); // this.textInputTextArea = ''; // clear the textarea // if (textArea) { // textArea.value = ''; // clear the textarea // textArea.placeholder = this.g.LABEL_PLACEHOLDER; // restore the placholder // this.g.wdLog(['AppComponent:restoreTextArea::restoreTextArea::textArea:', 'restored']); // } else { // console.error('AppComponent:restoreTextArea::restoreTextArea::textArea:', 'not restored'); // } // this.setFocusOnId('chat21-main-message-context'); // } // /** // * invio del messaggio // * @param msg // * @param type // * @param metadata // * @param additional_attributes // */ // sendMessage(msg, type, metadata?, additional_attributes?) { // sponziello // (metadata) ? metadata = metadata : metadata = ''; // this.g.wdLog(['SEND MESSAGE: ', msg, type, metadata, additional_attributes]); // if (msg && msg.trim() !== '' || type === TYPE_MSG_IMAGE || type === TYPE_MSG_FILE ) { // let recipientFullname = this.g.GUEST_LABEL; // // sponziello: adds ADDITIONAL ATTRIBUTES TO THE MESSAGE // const g_attributes = this.g.attributes; // // added <any> to resolve the Error occurred during the npm installation: Property 'userFullname' does not exist on type '{}' // const attributes = <any>{}; // if (g_attributes) { // for (const [key, value] of Object.entries(g_attributes)) { // attributes[key] = value; // } // } // if (additional_attributes) { // for (const [key, value] of Object.entries(additional_attributes)) { // attributes[key] = value; // } // } // // fine-sponziello // const projectid = this.g.projectid; // const channelType = this.g.channelType; // const userFullname = this.g.userFullname; // const userEmail = this.g.userEmail; // const widgetTitle = this.g.widgetTitle; // const conversationWith = this.conversationWith; // this.triggerBeforeSendMessageEvent( // recipientFullname, // msg, // type, // metadata, // conversationWith, // recipientFullname, // attributes, // projectid, // channelType // ); // if (userFullname) { // recipientFullname = userFullname; // } else if (userEmail) { // recipientFullname = userEmail; // } else if (attributes && attributes['userFullname']) { // recipientFullname = attributes['userFullname']; // } else { // recipientFullname = this.g.GUEST_LABEL; // } // const messageSent = this.messagingService.sendMessage( // recipientFullname, // msg, // type, // metadata, // conversationWith, // recipientFullname, // attributes, // projectid, // channelType // ); // this.triggerAfterSendMessageEvent(messageSent); // this.isNewConversation = false; // try { // const target = document.getElementById('chat21-main-message-context') as HTMLInputElement; // target.value = ''; // target.style.height = this.HEIGHT_DEFAULT; // // console.log('target.style.height: ', target.style.height); // } catch (e) { // this.g.wdLog(['> Error :' + e]); // } // this.restoreTextArea(); // } // } // printMessage(message, messageEl, component) { // const messageOBJ = { message: message, sanitizer: this.sanitizer, messageEl: messageEl, component: component} // this.onBeforeMessageRender.emit(messageOBJ) // const messageText = message.text; // this.onAfterMessageRender.emit(messageOBJ) // // this.triggerBeforeMessageRender(message, messageEl, component); // // const messageText = message.text; // // this.triggerAfterMessageRender(message, messageEl, component); // return messageText; // } /** * */ // onSendPressed(event) { // this.g.wdLog(['onSendPressed:event', event]); // this.g.wdLog(['AppComponent::onSendPressed::isFilePendingToUpload:', this.isFilePendingToUpload]); // if (this.isFilePendingToUpload) { // this.g.wdLog(['AppComponent::onSendPressed', 'is a file']); // // its a file // this.loadFile(); // this.isFilePendingToUpload = false; // // disabilito pulsanti // this.g.wdLog(['AppComponent::onSendPressed::isFilePendingToUpload:', this.isFilePendingToUpload]); // } else { // if ( this.textInputTextArea.length > 0 ) { // this.g.wdLog(['AppComponent::onSendPressed', 'is a message']); // // its a message // this.performSendingMessage(); // // restore the text area // // this.restoreTextArea(); // } // } // } /** * recupero url immagine profilo * @param uid // */ // getUrlImgProfile(uid: string) { // const baseLocation = this.g.baseLocation; // if (!uid || uid === 'system' ) { // return baseLocation + IMG_PROFILE_BOT; // } else if ( uid === 'error') { // return baseLocation + IMG_PROFILE_DEFAULT; // } else { // return getImageUrlThumb(uid); // } // // if (!uid) { // // return this.IMG_PROFILE_SUPPORT; // // } // // const profile = this.contactService.getContactProfile(uid); // // if (profile && profile.imageurl) { // // that.g.wdLog(['profile::', profile, ' - profile.imageurl', profile.imageurl); // // return profile.imageurl; // // } else { // // return this.IMG_PROFILE_SUPPORT; // // } // } /** * ridimensiona la textarea * chiamato ogni volta che cambia il contenuto della textarea * imposto stato 'typing' */ // resizeInputField() { // try { // const target = document.getElementById('chat21-main-message-context') as HTMLInputElement; // // tslint:disable-next-line:max-line-length // // that.g.wdLog(['H:: this.textInputTextArea', (document.getElementById('chat21-main-message-context') as HTMLInputElement).value , target.style.height, target.scrollHeight, target.offsetHeight, target.clientHeight); // target.style.height = '100%'; // if (target.value === '\n') { // target.value = ''; // target.style.height = this.HEIGHT_DEFAULT; // } else if (target.scrollHeight > target.offsetHeight) { // target.style.height = target.scrollHeight + 2 + 'px'; // target.style.minHeight = this.HEIGHT_DEFAULT; // } else { // // that.g.wdLog(['PASSO 3'); // target.style.height = this.HEIGHT_DEFAULT; // // segno sto scrivendo // // target.offsetHeight - 15 + 'px'; // } // this.setWritingMessages(target.value); // } catch (e) { // this.g.wdLog(['> Error :' + e]); // } // // tslint:disable-next-line:max-line-length // // that.g.wdLog(['H:: this.textInputTextArea', this.textInputTextArea, target.style.height, target.scrollHeight, target.offsetHeight, target.clientHeight); // } // ========= begin:: typing ======= // /** * * @param str */ // setWritingMessages(str) { // //this.messagingService.setWritingMessages(str, this.g.channelType); // this.typingService.setTyping(this.conversation.uid, str, this.g.senderId, this.getUserFUllName() ) // } /** * * @param memberID */ // checkMemberId(memberID) { // const that = this; // // && memberID.trim() !== 'system' // if ( memberID.trim() !== '' && memberID.trim() !== this.g.senderId // ) { // if (that.isTypings === false) { // that.isTypings = true; // } // } else { // that.isTypings = false; // } // } // ================================ // // ========= begin:: functions scroll position ======= // /** * */ // LISTEN TO SCROLL POSITION // onScroll(event: any): void { // // console.log('************** SCROLLLLLLLLLL *****************'); // this.startScroll = false; // if (this.scrollMe) { // const divScrollMe = this.scrollMe.nativeElement; // const checkContentScrollPosition = this.checkContentScrollPosition(divScrollMe); // if (checkContentScrollPosition) { // this.showBadgeScroollToBottom = false; // this.NUM_BADGES = 0; // } else { // this.showBadgeScroollToBottom = true; // } // } // } /** * */ // checkContentScrollPosition(divScrollMe): boolean { // // that.g.wdLog(['checkContentScrollPosition ::', divScrollMe); // // that.g.wdLog(['divScrollMe.diff ::', divScrollMe.scrollHeight - divScrollMe.scrollTop); // // that.g.wdLog(['divScrollMe.clientHeight ::', divScrollMe.clientHeight); // if (divScrollMe.scrollHeight - divScrollMe.scrollTop <= (divScrollMe.clientHeight + 40)) { // this.g.wdLog(['SONO ALLA FINE ::']); // return true; // } else { // this.g.wdLog([' NON SONO ALLA FINE ::']); // return true; // } // } /** * scrollo la lista messaggi all'ultimo * chiamato in maniera ricorsiva sino a quando non risponde correttamente */ // scrollToBottomStart() { // const that = this; // if ( this.isScrolling === false ) { // setTimeout(function () { // try { // that.isScrolling = true; // const objDiv = document.getElementById(that.idDivScroll); // setTimeout(function () { // that.g.wdLog(['objDiv::', objDiv.scrollHeight]); // //objDiv.scrollIntoView(false); // objDiv.style.opacity = '1'; // }, 200); // that.isScrolling = false; // } catch (err) { // that.g.wdLog(['> Error :' + err]); // } // }, 0); // } // } /** * scrollo la lista messaggi all'ultimo * chiamato in maniera ricorsiva sino a quando non risponde correttamente */ scrollToBottom() { this.conversationContent.scrollToBottom(); // const that = this; // try { // that.isScrolling = true; // const objDiv = document.getElementById(that.idDivScroll) as HTMLElement; // console.log('divto scrool', objDiv); // // const element = objDiv[0] as HTMLElement; // setTimeout(function () { // if (that.isIE === true || withoutAnimation === true || that.firstScroll === true) { // objDiv.parentElement.classList.add('withoutAnimation'); // } else { // objDiv.parentElement.classList.remove('withoutAnimation'); // } // objDiv.parentElement.scrollTop = objDiv.scrollHeight; // objDiv.style.opacity = '1'; // that.firstScroll = false; // }, 0); // } catch (err) { // that.g.wdLog(['> Error :' + err]); // } // that.isScrolling = false; } // scrollToBottom_old(withoutAnimation?: boolean) { // this.g.wdLog([' scrollToBottom: ', this.isScrolling]); // const that = this; // // const divScrollMe = this.scrollMe.nativeElement; // if ( this.isScrolling === false ) { // // const divScrollMe = this.scrollMe.nativeElement; // setTimeout(function () { // try { // that.isScrolling = true; // const objDiv = document.getElementById(that.idDivScroll); // setTimeout(function () { // try { // if (that.isIE === true || withoutAnimation === true) { // objDiv.scrollIntoView(false); // } else { // objDiv.scrollIntoView({behavior: 'smooth', block: 'end'}); // } // that.g.wdLog(['objDiv::', objDiv.scrollHeight]); // } catch (err) { // that.g.wdLog(['> Error :' + err]); // } // // objDiv.scrollIntoView(false); // }, 0); // that.isScrolling = false; // //// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView // // setTimeout(function () { // // objDiv.scrollIntoView({behavior: 'smooth', block: 'end'}); // // }, 500); // // let checkContentScrollPosition = false; // // do { // // setTimeout(function () { // // that.g.wdLog(['RIPROVO dopo 1 sec::']); // // objDiv.scrollIntoView({behavior: 'smooth', block: 'end'}); // // checkContentScrollPosition = that.checkContentScrollPosition(divScrollMe); // // }, 1000); // // } // // while (checkContentScrollPosition === false); // // that.isScrolling = false; // // that.g.wdLog(['checkContentScrollPosition ::', this.divScrollMe); // // that.g.wdLog(['divScrollMe.diff ::', this.divScrollMe.scrollHeight - this.divScrollMe.scrollTop); // // that.g.wdLog(['divScrollMe.clientHeight ::', this.divScrollMe.clientHeight); // // try { // // this.divScrollMe.nativeElement.scrollToTop = this.divScrollMe.nativeElement.scrollHeight; // // } catch ( err ) { } // // // that.badgeNewMessages = 0; // // console.log(objDiv); // } catch (err) { // that.g.wdLog(['> Error :' + err]); // setTimeout(function () { // that.isScrolling = false; // }, 0); // } // }, 0); // } // } // ========= end:: functions scroll position ======= // // ========= begin:: functions send image ======= // // START LOAD IMAGE // /** * carico in locale l'immagine selezionata e apro pop up anteprima */ // detectFiles(event) { // this.g.wdLog(['detectFiles: ', event]); // if (event) { // this.selectedFiles = event.target.files; // this.g.wdLog(['AppComponent:detectFiles::selectedFiles', this.selectedFiles]); // if (this.selectedFiles == null) { // this.isFilePendingToUpload = false; // } else { // this.isFilePendingToUpload = true; // } // this.g.wdLog(['AppComponent:detectFiles::selectedFiles::isFilePendingToUpload', this.isFilePendingToUpload]); // this.g.wdLog(['fileChange: ', event.target.files]); // if (event.target.files.length <= 0) { // this.isFilePendingToUpload = false; // } else { // this.isFilePendingToUpload = true; // } // const that = this; // if (event.target.files && event.target.files[0]) { // const nameFile = event.target.files[0].name; // const typeFile = event.target.files[0].type; // const reader = new FileReader(); // that.g.wdLog(['OK preload: ', nameFile, typeFile, reader]); // reader.addEventListener('load', function () { // that.g.wdLog(['addEventListener load', reader.result]); // that.isFileSelected = true; // // se inizia con image // if (typeFile.startsWith('image')) { // const imageXLoad = new Image; // that.g.wdLog(['onload ', imageXLoad]); // imageXLoad.src = reader.result.toString(); // imageXLoad.title = nameFile; // imageXLoad.onload = function () { // that.g.wdLog(['onload immagine']); // // that.arrayFilesLoad.push(imageXLoad); // const uid = (new Date().getTime()).toString(36); // imageXLoad.src.substring(imageXLoad.src.length - 16); // that.arrayFilesLoad[0] = { uid: uid, file: imageXLoad, type: typeFile }; // that.g.wdLog(['OK: ', that.arrayFilesLoad[0]]); // // INVIO MESSAGGIO // that.loadFile(); // }; // } else { // that.g.wdLog(['onload file']); // const fileXLoad = { // src: reader.result.toString(), // title: nameFile // }; // // that.arrayFilesLoad.push(imageXLoad); // const uid = (new Date().getTime()).toString(36); // imageXLoad.src.substring(imageXLoad.src.length - 16); // that.arrayFilesLoad[0] = { uid: uid, file: fileXLoad, type: typeFile }; // that.g.wdLog(['OK: ', that.arrayFilesLoad[0]]); // // INVIO MESSAGGIO // that.loadFile(); // } // }, false); // if (event.target.files[0]) { // reader.readAsDataURL(event.target.files[0]); // that.g.wdLog(['reader-result: ', event.target.files[0]]); // } // } // } // } // loadFile() { // this.g.wdLog(['that.fileXLoad: ', this.arrayFilesLoad]); // // al momento gestisco solo il caricamento di un'immagine alla volta // if (this.arrayFilesLoad[0] && this.arrayFilesLoad[0].file) { // const fileXLoad = this.arrayFilesLoad[0].file; // const uid = this.arrayFilesLoad[0].uid; // const type = this.arrayFilesLoad[0].type; // this.g.wdLog(['that.fileXLoad: ', type]); // let metadata; // if (type.startsWith('image')) { // metadata = { // 'name': fileXLoad.title, // 'src': fileXLoad.src, // 'width': fileXLoad.width, // 'height': fileXLoad.height, // 'type': type, // 'uid': uid // }; // } else { // metadata = { // 'name': fileXLoad.title, // 'src': fileXLoad.src, // 'type': type, // 'uid': uid // }; // } // this.g.wdLog(['metadata -------> ', metadata]); // // this.scrollToBottom(); // // 1 - aggiungo messaggio localmente // // this.addLocalMessageImage(metadata); // // 2 - carico immagine // const file = this.selectedFiles.item(0); // this.uploadSingle(metadata, file); // // this.isSelected = false; // } // } /** * */ // uploadSingle(metadata, file) { // const that = this; // const send_order_btn = <HTMLInputElement>document.getElementById('chat21-start-upload-doc'); // send_order_btn.disabled = true; // that.g.wdLog(['AppComponent::uploadSingle::', metadata, file]); // // const file = this.selectedFiles.item(0); // const currentUpload = new UploadModel(file); // // console.log(currentUpload.file); // const uploadTask = this.upSvc.pushUpload(currentUpload); // uploadTask.then(snapshot => { // return snapshot.ref.getDownloadURL(); // Will return a promise with the download link // }) // .then(downloadURL => { // that.g.wdLog(['AppComponent::uploadSingle:: downloadURL', downloadURL]); // that.g.wdLog([`Successfully uploaded file and got download link - ${downloadURL}`]); // metadata.src = downloadURL; // let type_message = TYPE_MSG_TEXT; // let message = 'File: ' + metadata.src; // if (metadata.type.startsWith('image')) { // type_message = TYPE_MSG_IMAGE; // message = ''; // 'Image: ' + metadata.src; // } // that.sendMessage(message, type_message, metadata); // that.isFilePendingToUpload = false; // // return downloadURL; // }) // .catch(error => { // // Use to signal error if something goes wrong. // console.error(`AppComponent::uploadSingle:: Failed to upload file and get link - ${error}`); // }); // // this.resetLoadImage(); // that.g.wdLog(['reader-result: ', file]); // } /** * * @param message */ // getSizeImg(message): any { // const metadata = message.metadata; // // const MAX_WIDTH_IMAGES = 300; // const sizeImage = { // width: metadata.width, // height: metadata.height // }; // // that.g.wdLog(['message::: ', metadata); // if (metadata.width && metadata.width > MAX_WIDTH_IMAGES) { // const rapporto = (metadata['width'] / metadata['height']); // sizeImage.width = MAX_WIDTH_IMAGES; // sizeImage.height = MAX_WIDTH_IMAGES / rapporto; // } // return sizeImage; // h.toString(); // } /** * aggiorno messaggio: uid, status, timestamp, headerDate * richiamata alla sottoscrizione dell'aggiunta di un nw messaggio * in caso in cui il messaggio è un'immagine ed è stata inviata dall'utente */ updateMessage(message) { this.logger.debug('[CONV-COMP] UPDATE MSG:', message.metadata.uid); const index = searchIndexInArrayForUid(this.messages, message.metadata.uid); if (index > -1) { this.messages[index].uid = message.uid; this.messages[index].status = message.status; this.messages[index].timestamp = message.timestamp; this.logger.debug('[CONV-COMP] UPDATE ok:', this.messages[index]); } else { this.messages.push(message); } } /** * */ // resetLoadImage() { // this.nameFile = ''; // this.selectedFiles = null; // that.g.wdLog(['1 selectedFiles: ', this.selectedFiles); // delete this.arrayFiles4Load[0]; // document.getElementById('chat21-file').nodeValue = null; // // event.target.files[0].name, event.target.files // this.isSelected = false; // this.isFilePendingToUpload = false; // that.g.wdLog(['AppComponent::resetLoadImage::isFilePendingToUpload:', this.isFilePendingToUpload); // // this.restoreTextArea(); // } /** * salvo un messaggio localmente nell'array dei msg * @param metadata */ // addLocalMessageImage(metadata) { // const now: Date = new Date(); // const timestamp = now.valueOf(); // const language = document.documentElement.lang; // let recipientFullname; // if (this.userFullname) { // recipientFullname = this.userFullname; // } else if (this.userEmail) { // recipientFullname = this.userEmail; // } else { // recipientFullname = this.GUEST_LABEL; // } // // const projectname = (this.projectname) ? this.projectname : this.projectid; // // set senderFullname // const senderFullname = recipientFullname; // const message = new MessageModel( // metadata.uid, // uid // language, // language // this.conversationWith, // recipient // recipientFullname, // recipient_fullname // this.senderId, // sender // senderFullname, // sender_fullname // '', // status // metadata, // metadata // '', // text // timestamp, // timestamp // '', // headerDate // TYPE_MSG_IMAGE, // type // '', // this.channelType, // this.projectid // ); // // this.messages.push(message); // // message.metadata.uid = message.uid; // that.g.wdLog(['addLocalMessageImage: ', this.messages); // this.isSelected = true; // } // ========= end:: functions send image ======= // // =========== BEGIN: event emitter function ====== // returnHome() { //this.storageService.removeItem('activeConversation'); //this.g.setParameter('activeConversation', null, false); this.onBackHome.emit(); } returnCloseWidget() { //this.g.setParameter('activeConversation', null, false); this.onCloseWidget.emit(); } returnAfterSendMessage(message: MessageModel){ this.onAfterSendMessage.emit(message) } returnSoundChange(soundEnabled){ this.onSoundChange.emit(soundEnabled) } returnOnBeforeMessangeSent(messageModel){ this.onBeforeMessageSent.emit(messageModel) } returnOnBeforeMessageRender(event){ this.onBeforeMessageRender.emit(event) } returnOnAfterMessageRender(event){ this.onAfterMessageRender.emit(event) } returnOnScrollContent(event: boolean){ this.showBadgeScroollToBottom = !event; this.logger.debug('[CONV-COMP] scroool eventtt', event) //se sono alla fine (showBadgeScroollBottom === true) allora imposto messageBadgeCount a 0 if(!this.showBadgeScroollToBottom){ this.messagesBadgeCount = 0; this.updateConversationBadge(); } } returnOnMenuOption(event:boolean){ this.isMenuShow = event; this.conversationFooter.removeFocusOnId('chat21-main-message-context') } /** CALLED BY: conv-footer component */ onAttachmentButtonClicked(event: any){ this.logger.debug('[CONV-COMP] onAttachmentButtonClicked::::', event) this.attachments = event.attachments this.textInputTextArea= event.message this.logger.debug('[CONV-COMP] onAttachmentButtonClicked::::', this.textInputTextArea) this.isOpenAttachmentPreview = true } /** CALLED BY: conv-preview component */ onCloseModalPreview(){ this.isOpenAttachmentPreview = false this.conversationFooter.isFilePendingToUpload = false; this.logger.debug('[CONV-COMP] onCloseModalPreview::::', this.isOpenAttachmentPreview, this.conversationFooter) } /** CALLED BY: conv-preview component */ onSendAttachment(messageText: string){ this.isOpenAttachmentPreview = false this.conversationFooter.uploadSingle(this.attachments[0].metadata, this.attachments[0].file, messageText) // send message to footer-component } returnChangeTextArea(event){ if(event && event.textAreaEl){ const scrollDiv = this.conversationContent.scrollMe const height = +event.textAreaEl.style.height.substring(0, event.textAreaEl.style.height.length - 2); if(height > 20 && height < 110){ scrollDiv.nativeElement.style.height = 'calc(100% - ' + (height - 20)+'px' document.getElementById('chat21-button-send').style.right = '18px' this.scrollToBottom() } else if(height <= 20) { scrollDiv.nativeElement.style.height = '100%' } else if(height > 110){ document.getElementById('chat21-button-send').style.right = '18px' } } } /** CALLED BY: floating-button footer component */ onNewConversationButtonClickedFN(event){ console.log('floating onNewConversationButtonClicked') this.onNewConversationButtonClicked.emit() } // =========== END: event emitter function ====== // // dowloadTranscript() { // const url = this.API_URL + 'public/requests/' + this.conversationWith + '/messages.html'; // const windowContext = this.g.windowContext; // windowContext.open(url, '_blank'); // this.isMenuShow = false; // } openInputFiles() { alert('ok'); if (document.getElementById('chat21-file')) { const docInput = document.getElementById('chat21-file'); docInput.style.display = 'block'; } } // ========= begin:: DESTROY ALL SUBSCRIPTIONS ============// /** * elimino tutte le sottoscrizioni */ // tslint:disable-next-line:use-life-cycle-interface ngOnDestroy() { this.logger.debug('[CONV-COMP] ngOnDestroy ------------------> this.subscriptions', this.subscriptions); //this.storageService.removeItem('activeConversation'); this.unsubscribe(); } /** */ unsubscribe() { this.logger.debug('[CONV-COMP] ******* unsubscribe *******'); this.unsubscribe$.next(); this.unsubscribe$.complete(); this.chatManager.conversationsHandlerService.conversationRemoved.next(null) // TODO-GAB: da verificare se eliminarlo this.subscriptions.forEach(function (subscription) { subscription.value.unsubscribe(); }); this.subscriptions = []; this.subscriptions.length = 0; //this.messagingService.unsubscribeAllReferences(); this.logger.debug('[CONV-COMP]this.subscriptions', this.subscriptions); } // ========= end:: DESTROY ALL SUBSCRIPTIONS ============// /** * regola sound message: * se lo invio io -> NO SOUND * se non sono nella conversazione -> SOUND * se sono nella conversazione in fondo alla pagina -> NO SOUND * altrimenti -> SOUND */ soundMessage(timestamp?) { if (!isJustRecived(this.g.startedAt.getTime(), timestamp)) { return; } const soundEnabled = this.g.soundEnabled; const baseLocation = this.g.baseLocation; if ( soundEnabled ) { const that = this; this.audio = new Audio(); this.audio.src = baseLocation + '/assets/sounds/justsaying.mp3'; this.audio.load(); // console.log('conversation play'); clearTimeout(this.setTimeoutSound); this.setTimeoutSound = setTimeout(function () { that.audio.play(); that.logger.debug('[CONV-COMP] ****** soundMessage 1 *****', that.audio.src); }, 1000); } } // isLastMessage(idMessage: string) { // // console.log('idMessage: ' + idMessage + 'id LAST Message: ' + this.messages[this.messages.length - 1].uid); // if (idMessage === this.messages[this.messages.length - 1].uid) { // return true; // } // return false; // } /** */ // returnOnTextActionButtonClicked(event: string) { // if (event) { // const metadata = { // 'button': true // }; // this.conversationFooter.sendMessage(event, TYPE_MSG_TEXT, metadata); // // this.sendMessage($event, TYPE_MSG_TEXT); // } // } /** */ returnOnAttachmentButtonClicked(event: any) { this.logger.debug('[CONV-COMP] eventbutton', event) if (!event || !event.target.type) { return; } switch (event.target.type) { case 'url': try { this.openLink(event.target.button); } catch (err) { this.logger.error('[CONV-COMP] url > Error :' + err); } return; case 'action': try { this.actionButton(event.target.button); } catch (err) { this.logger.error('[CONV-COMP] action > Error :' + err); } return false; case 'text': try{ const text = event.target.button.value const metadata = { 'button': true }; this.conversationFooter.sendMessage(text, TYPE_MSG_TEXT, metadata); }catch(err){ this.logger.error('[CONV-COMP] text > Error :' + err); } default: return; } } onOpenExternalFrame(event){ window.open(event.link, '_blank'); } onCloseInternalFrame(){ this.isButtonUrl = false this.buttonClicked = null; } /** */ private openLink(event: any) { const link = event.link ? event.link : ''; const target = event.target ? event.target : ''; if (target === 'self') { // window.open(link, '_self'); this.isButtonUrl= true; this.buttonClicked = event } else if (target === 'parent') { window.open(link, '_parent'); } else { window.open(link, '_blank'); } } /** */ private actionButton(event: any) { // console.log(event); const action = event.action ? event.action : ''; const message = event.value ? event.value : ''; const subtype = event.show_echo ? '' : 'info'; const attributes = { action: action, subtype: subtype }; this.conversationFooter.sendMessage(message, TYPE_MSG_TEXT, null, attributes); this.logger.debug('[CONV-COMP] > action :'); } // ========= START:: TRIGGER FUNCTIONS ============// private onNewConversationComponentInit() { this.logger.debug('[CONV-COMP] ------- onNewConversationComponentInit ------- '); this.setConversation(); // this.connectConversation(); const newConvId = this.conversationWith; const default_settings = this.g.default_settings; const appConfigs = this.appConfigService.getConfig(); this.onNewConversationInit.emit({ global: this.g, default_settings: default_settings, newConvId: newConvId, appConfigs: appConfigs }) } // triggerBeforeMessageRender(message, messageEl, component) { // // console.log('triggerBeforeMessageRender'); // try { // // tslint:disable-next-line:max-line-length // const beforeMessageRender = new CustomEvent('beforeMessageRender', // { detail: { message: message, sanitizer: this.sanitizer, messageEl: messageEl, component: component} }); // const windowContext = this.g.windowContext; // if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) { // windowContext.tiledesk.tiledeskroot.dispatchEvent(beforeMessageRender); // this.g.windowContext = windowContext; // } else { // const returnEventValue = this.elRoot.nativeElement.dispatchEvent(beforeMessageRender); // } // } catch (e) { // this.g.wdLog(['> Error :' + e]); // } // } // triggerAfterMessageRender(message, messageEl, component) { // // console.log('triggerBeforeMessageRender'); // try { // // tslint:disable-next-line:max-line-length // const afterMessageRender = new CustomEvent('afterMessageRender', // { detail: { message: message, sanitizer: this.sanitizer, messageEl: messageEl, component: component} }); // const windowContext = this.g.windowContext; // if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) { // windowContext.tiledesk.tiledeskroot.dispatchEvent(afterMessageRender); // this.g.windowContext = windowContext; // } else { // const returnEventValue = this.elRoot.nativeElement.dispatchEvent(afterMessageRender); // } // } catch (e) { // this.g.wdLog(['> Error :' + e]); // } // } // tslint:disable-next-line:max-line-length // private triggerBeforeSendMessageEvent(senderFullname, text, type, metadata, conversationWith, recipientFullname, attributes, projectid, channel_type) { // try { // // tslint:disable-next-line:max-line-length // const onBeforeMessageSend = new CustomEvent('onBeforeMessageSend', { detail: { senderFullname: senderFullname, text: text, type: type, metadata, conversationWith: conversationWith, recipientFullname: recipientFullname, attributes: attributes, projectid: projectid, channelType: channel_type } }); // const windowContext = this.g.windowContext; // if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) { // windowContext.tiledesk.tiledeskroot.dispatchEvent(onBeforeMessageSend); // this.g.windowContext = windowContext; // } else { // this.el.nativeElement.dispatchEvent(onBeforeMessageSend); // } // } catch (e) { // this.g.wdLog(['> Error :' + e]); // } // } // tslint:disable-next-line:max-line-length // private triggerAfterSendMessageEvent(message) { // try { // // tslint:disable-next-line:max-line-length // const onAfterMessageSend = new CustomEvent('onAfterMessageSend', { detail: { message: message } }); // const windowContext = this.g.windowContext; // if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) { // windowContext.tiledesk.tiledeskroot.dispatchEvent(onAfterMessageSend); // this.g.windowContext = windowContext; // } else { // this.el.nativeElement.dispatchEvent(onAfterMessageSend); // } // } catch (e) { // this.g.wdLog(['> Error :' + e]); // } // } // ========= END:: TRIGGER FUNCTIONS ============// /** * function customize tooltip */ // handleTooltipEvents(event) { // const that = this; // const showDelay = this.tooltipOptions['showDelay']; // // console.log(this.tooltipOptions); // setTimeout(function () { // try { // const domRepresentation = document.getElementsByClassName('chat-tooltip'); // if (domRepresentation) { // const item = domRepresentation[0] as HTMLInputElement; // // console.log(item); // if (!item.classList.contains('tooltip-show')) { // item.classList.add('tooltip-show'); // } // setTimeout(function () { // if (item.classList.contains('tooltip-show')) { // item.classList.remove('tooltip-show'); // } // }, that.tooltipOptions['hideDelayAfterClick']); // } // } catch (err) { // that.g.wdLog(['> Error :' + err]); // } // }, showDelay); // } }
the_stack
declare const describe: any; declare const it: any; declare const expect: any; import * as Immutable from "immutable"; import Moment = moment.Moment; import * as _ from "lodash"; import * as moment from "moment"; import { Collection } from "../src/collection"; import { duration } from "../src/duration"; import { event, Event } from "../src/event"; import { avg, count, sum } from "../src/functions"; import { Index } from "../src/index"; import { period } from "../src/period"; import { stream } from "../src/stream"; import { time, Time } from "../src/time"; import { Trigger } from "../src/types"; import { window } from "../src/window"; import { AlignmentMethod } from "../src/types"; const streamingEvents = [ event(time(0), Immutable.Map({ count: 5, value: 1 })), event(time(30000), Immutable.Map({ count: 3, value: 3 })), event(time(60000), Immutable.Map({ count: 4, value: 10 })), event(time(90000), Immutable.Map({ count: 1, value: 40 })), event(time(120000), Immutable.Map({ count: 5, value: 70 })), event(time(150000), Immutable.Map({ count: 3, value: 130 })), event(time(180000), Immutable.Map({ count: 2, value: 190 })), event(time(210000), Immutable.Map({ count: 6, value: 220 })), event(time(240000), Immutable.Map({ count: 1, value: 300 })), event(time(270000), Immutable.Map({ count: 0, value: 390 })), event(time(300000), Immutable.Map({ count: 2, value: 510 })) ]; describe("Streaming", () => { it("can do streaming of just events", () => { const SIMPLE_GAP_DATA = [ [1471824030000, 0.75], // 00:00:30 [1471824105000, 2], // 00:01:45 [1471824210000, 1], // 00:03:30 [1471824390000, 1], // 00:06:30 [1471824510000, 3], // 00:08:30 [1471824525000, 5] // 00:08:45 ]; const list = SIMPLE_GAP_DATA.map(e => { return event(time(e[0]), Immutable.Map({ value: e[1] })); }); const result = []; const everyMinute = period(duration("1m")); const s = stream() .align({ fieldSpec: "value", period: everyMinute, method: AlignmentMethod.Linear }) .rate({ fieldSpec: "value", allowNegative: false }) .output(e => result.push(e)); list.forEach(e => { s.addEvent(e); }); expect(result[0].get("value_rate")).toEqual(0.01011904761904762); expect(result[1].get("value_rate")).toBeNull(); expect(result[2].get("value_rate")).toBeNull(); expect(result[3].get("value_rate")).toEqual(0); expect(result[4].get("value_rate")).toEqual(0); expect(result[5].get("value_rate")).toEqual(0.008333333333333333); expect(result[6].get("value_rate")).toEqual(0.016666666666666666); }); it("can do build keyed collection pairs", () => { const eventsIn = [ event(time(Date.UTC(2015, 2, 14, 7, 57, 0)), Immutable.Map({ in: 3, out: 1 })), event(time(Date.UTC(2015, 2, 14, 7, 58, 0)), Immutable.Map({ in: 9, out: 2 })), event(time(Date.UTC(2015, 2, 14, 7, 59, 0)), Immutable.Map({ in: 6, out: 6 })), event(time(Date.UTC(2015, 2, 14, 8, 0, 0)), Immutable.Map({ in: 4, out: 7 })), event(time(Date.UTC(2015, 2, 14, 8, 1, 0)), Immutable.Map({ in: 5, out: 9 })) ]; const result: { [key: string]: Collection<Time> } = {}; const everyThirtyMinutes = window(duration("30m")); let calls = 0; const source = stream<Time>() .groupByWindow({ window: everyThirtyMinutes, trigger: Trigger.perEvent }) .output((c, key) => { result[key] = c; calls += 1; }); eventsIn.forEach(e => source.addEvent(e)); expect(result["30m-792399"].size()).toEqual(3); expect(result["30m-792400"].size()).toEqual(2); expect(calls).toEqual(eventsIn.length); }); it("can do streaming aggregation per event", () => { const eventsIn = [ event(time(Date.UTC(2015, 2, 14, 7, 57, 0)), Immutable.Map({ in: 3, out: 1 })), event(time(Date.UTC(2015, 2, 14, 7, 58, 0)), Immutable.Map({ in: 9, out: 2 })), event(time(Date.UTC(2015, 2, 14, 7, 59, 0)), Immutable.Map({ in: 6, out: 6 })), event(time(Date.UTC(2015, 2, 14, 8, 0, 0)), Immutable.Map({ in: 4, out: 7 })), event(time(Date.UTC(2015, 2, 14, 8, 1, 0)), Immutable.Map({ in: 5, out: 9 })) ]; const result: { [key: string]: Event<Index> } = {}; const everyThirtyMinutes = window(duration("30m")); let calls = 0; const source = stream<Time>() .groupByWindow({ window: everyThirtyMinutes, trigger: Trigger.perEvent }) .aggregate({ in_avg: ["in", avg()], out_avg: ["out", avg()] }) .output(e => { result[e.getKey().toString()] = e; calls += 1; }); eventsIn.forEach(e => source.addEvent(e)); expect(result["30m-792399"].get("in_avg")).toEqual(6); expect(result["30m-792399"].get("out_avg")).toEqual(3); expect(result["30m-792400"].get("in_avg")).toEqual(4.5); expect(result["30m-792400"].get("out_avg")).toEqual(8); expect(calls).toEqual(eventsIn.length); }); it("can do streaming aggregation on discards", () => { const eventsIn = [ event(time(Date.UTC(2015, 2, 14, 7, 57, 0)), Immutable.Map({ in: 3, out: 1 })), event(time(Date.UTC(2015, 2, 14, 7, 58, 0)), Immutable.Map({ in: 9, out: 2 })), event(time(Date.UTC(2015, 2, 14, 7, 59, 0)), Immutable.Map({ in: 6, out: 6 })), event(time(Date.UTC(2015, 2, 14, 8, 0, 0)), Immutable.Map({ in: 4, out: 7 })), event(time(Date.UTC(2015, 2, 14, 8, 1, 0)), Immutable.Map({ in: 5, out: 9 })), event(time(Date.UTC(2015, 2, 14, 8, 31, 0)), Immutable.Map({ in: 0, out: 0 })) ]; const result: { [key: string]: Event<Index> } = {}; let outputCalls = 0; const everyThirtyMinutes = window(duration("30m")); const source = stream<Time>() .groupByWindow({ window: everyThirtyMinutes, trigger: Trigger.onDiscardedWindow }) .aggregate({ in_avg: ["in", avg()], out_avg: ["out", avg()] }) .output(evt => { const e = evt as Event<Index>; result[e.getKey().toString()] = e; outputCalls += 1; }); eventsIn.forEach(e => source.addEvent(e)); expect(outputCalls).toBe(2); // .output should be called twice expect(result["30m-792399"].get("in_avg")).toEqual(6); expect(result["30m-792399"].get("out_avg")).toEqual(3); expect(result["30m-792400"].get("in_avg")).toEqual(4.5); expect(result["30m-792400"].get("out_avg")).toEqual(8); }); it("can do streaming event remapping", () => { const eventsIn = [ event(time(Date.UTC(2015, 2, 14, 7, 57, 0)), Immutable.Map({ a: 1 })), event(time(Date.UTC(2015, 2, 14, 7, 58, 0)), Immutable.Map({ a: 2 })), event(time(Date.UTC(2015, 2, 14, 7, 59, 0)), Immutable.Map({ a: 3 })) ]; const result: Event[] = []; const source = stream<Time>() .map(e => event(e.getKey(), Immutable.Map({ a: e.get("a") * 2 }))) .output(e => result.push(e)); eventsIn.forEach(e => source.addEvent(e)); expect(result[0].get("a")).toEqual(2); expect(result[1].get("a")).toEqual(4); expect(result[2].get("a")).toEqual(6); }); it("can do streaming event flatmap", () => { const eventsIn = [ event(time(Date.UTC(2015, 2, 14, 7, 57, 0)), Immutable.Map({ a: 1 })), event(time(Date.UTC(2015, 2, 14, 7, 58, 0)), Immutable.Map({ a: 2 })), event(time(Date.UTC(2015, 2, 14, 7, 59, 0)), Immutable.Map({ a: 3 })) ]; const result: Event[] = []; const source = stream<Time>() .flatMap(e => { let eventList = Immutable.List<Event<Time>>(); const num = e.get("a"); for (let i = 0; i < num; i++) { eventList = eventList.push( event(e.getKey(), Immutable.Map({ a: num * 10 + i })) ); } return eventList; }) .output(e => result.push(e)); eventsIn.forEach(e => source.addEvent(e)); expect(result[0].get("a")).toEqual(10); expect(result[1].get("a")).toEqual(20); expect(result[2].get("a")).toEqual(21); expect(result[3].get("a")).toEqual(30); expect(result[4].get("a")).toEqual(31); expect(result[5].get("a")).toEqual(32); }); it("can do filtering on a stream of events", () => { const eventsIn = [ event(time(Date.UTC(2015, 2, 14, 7, 31, 0)), Immutable.Map({ a: 1 })), event(time(Date.UTC(2015, 2, 14, 7, 32, 0)), Immutable.Map({ a: 2 })), event(time(Date.UTC(2015, 2, 14, 7, 33, 0)), Immutable.Map({ a: 3 })), event(time(Date.UTC(2015, 2, 14, 7, 34, 0)), Immutable.Map({ a: 4 })), event(time(Date.UTC(2015, 2, 14, 7, 35, 0)), Immutable.Map({ a: 5 })) ]; const result: Event[] = []; const source = stream<Time>() .filter(e => e.get("a") % 2 !== 0) .output(e => result.push(e)); eventsIn.forEach(e => source.addEvent(e)); expect(result[0].get("a")).toEqual(1); expect(result[1].get("a")).toEqual(3); expect(result[2].get("a")).toEqual(5); }); it("can selection of specific event fields", () => { const DATA = [[1471824030000, 1, 2, 3], [1471824105000, 4, 5, 6], [1471824210000, 7, 8, 9]]; const list = DATA.map(e => { return event(time(e[0]), Immutable.Map({ a: e[1], b: e[2], c: e[3] })); }); const result = []; const s = stream() .select({ fields: ["b", "c"] }) .output(e => result.push(e)); list.forEach(e => { s.addEvent(e); }); expect(result.length).toBe(3); expect(result[0].get("a")).toBeUndefined(); expect(result[0].get("b")).toBe(2); expect(result[0].get("c")).toBe(3); expect(result[2].get("a")).toBeUndefined(); expect(result[2].get("b")).toBe(8); expect(result[2].get("c")).toBe(9); }); it("can collapse of specific event fields", () => { const DATA = [[1471824030000, 1, 2, 3], [1471824105000, 4, 5, 6], [1471824210000, 7, 8, 9]]; const list = DATA.map(e => { return event(time(e[0]), Immutable.Map({ a: e[1], b: e[2], c: e[3] })); }); const result = []; const s = stream() .collapse({ fieldSpecList: ["a", "b"], fieldName: "ab", reducer: sum(), append: false }) .output(e => { result.push(e); }); list.forEach(e => { s.addEvent(e); }); expect(result.length).toBe(3); expect(result[0].get("ab")).toBe(3); expect(result[1].get("ab")).toBe(9); expect(result[2].get("ab")).toBe(15); }); it("can process a sliding window", () => { const eventsIn = [ event(time(Date.UTC(2015, 2, 14, 1, 15, 0)), Immutable.Map({ in: 1, out: 6 })), event(time(Date.UTC(2015, 2, 14, 1, 16, 0)), Immutable.Map({ in: 2, out: 7 })), event(time(Date.UTC(2015, 2, 14, 1, 17, 0)), Immutable.Map({ in: 3, out: 8 })), event(time(Date.UTC(2015, 2, 14, 1, 18, 0)), Immutable.Map({ in: 4, out: 9 })), event(time(Date.UTC(2015, 2, 14, 1, 19, 0)), Immutable.Map({ in: 5, out: 10 })) ]; const result: { [key: string]: Collection<Time> } = {}; const slidingWindow = window(duration("3m"), period(duration("1m"))); const fixedHourlyWindow = window(duration("1h")); let calls = 0; const source = stream() .groupByWindow({ window: slidingWindow, trigger: Trigger.onDiscardedWindow }) .aggregate({ in_avg: ["in", avg()], out_avg: ["out", avg()], count: ["in", count()] }) .map(e => new Event<Time>(time(e.timerange().end()), e.getData())) .groupByWindow({ window: fixedHourlyWindow, trigger: Trigger.perEvent }) .output((col, key) => { result[key] = col as Collection<Time>; calls += 1; }); eventsIn.forEach(e => source.addEvent(e)); const c = result["1h-396193"]; expect(c.size()).toBe(4); expect(+c.at(0).timestamp()).toBe(1426295760000); expect(c.at(0).get("in_avg")).toBe(1); expect(c.at(0).get("count")).toBe(1); expect(+c.at(1).timestamp()).toBe(1426295820000); expect(c.at(1).get("in_avg")).toBe(1.5); expect(c.at(1).get("count")).toBe(2); expect(+c.at(2).timestamp()).toBe(1426295880000); expect(c.at(2).get("in_avg")).toBe(2); expect(c.at(2).get("count")).toBe(3); expect(+c.at(3).timestamp()).toBe(1426295940000); expect(c.at(3).get("in_avg")).toBe(3); expect(c.at(3).get("count")).toBe(3); }); it("can process a running total using the straeam reduce() function", () => { const results = []; const source = stream() .reduce({ count: 1, accumulator: event(time(), Immutable.Map({ total: 0 })), iteratee(accum, eventList) { const current = eventList.get(0); const total = accum.get("total") + current.get("count"); return event(time(current.timestamp()), Immutable.Map({ total })); } }) .output(e => results.push(e)); // Stream events streamingEvents.forEach(e => source.addEvent(e)); expect(results[0].get("total")).toBe(5); expect(results[5].get("total")).toBe(21); expect(results[10].get("total")).toBe(32); }); it("can process a rolling average of the last 5 points", () => { const results = []; const source = stream() .reduce({ count: 5, iteratee(accum, eventList) { const values = eventList.map(e => e.get("value")).toJS(); return event( time(eventList.last().timestamp()), Immutable.Map({ avg: avg()(values) }) ); } }) .output(e => results.push(e)); // Stream events streamingEvents.forEach(e => source.addEvent(e)); expect(results[0].get("avg")).toBe(1); expect(results[5].get("avg")).toBe(50.6); expect(results[10].get("avg")).toBe(322); }); it("can do a split from the root", () => { const eventsIn = [ event(time(Date.UTC(2015, 2, 14, 7, 57, 0)), Immutable.Map({ a: 1 })), event(time(Date.UTC(2015, 2, 14, 7, 58, 0)), Immutable.Map({ a: 2 })), event(time(Date.UTC(2015, 2, 14, 7, 59, 0)), Immutable.Map({ a: 3 })) ]; const result1: Event[] = []; const result2: Event[] = []; const source = stream<Time>(); const branch1 = source .map(e => event(e.getKey(), Immutable.Map({ a: e.get("a") * 2 }))) // 2, 4, 6 .output(e => result1.push(e)); const branch2 = source .map(e => event(e.getKey(), Immutable.Map({ a: e.get("a") * 3 }))) // 3, 6, 9 .output(e => result2.push(e)); eventsIn.forEach(e => source.addEvent(e)); expect(result1[0].get("a")).toBe(2); expect(result1[1].get("a")).toBe(4); expect(result1[2].get("a")).toBe(6); expect(result2[0].get("a")).toBe(3); expect(result2[1].get("a")).toBe(6); expect(result2[2].get("a")).toBe(9); }); it("can do a split of two streams", () => { const eventsIn = [ event(time(Date.UTC(2015, 2, 14, 7, 57, 0)), Immutable.Map({ a: 1 })), event(time(Date.UTC(2015, 2, 14, 7, 58, 0)), Immutable.Map({ a: 2 })), event(time(Date.UTC(2015, 2, 14, 7, 59, 0)), Immutable.Map({ a: 3 })) ]; const result1: Event[] = []; const result2: Event[] = []; const source = stream<Time>().map(e => event(e.getKey(), Immutable.Map({ a: e.get("a") * 2 })) ); // 2, 4, 6 const branch1 = source .map(e => event(e.getKey(), Immutable.Map({ a: e.get("a") * 3 }))) // 6, 12, 18 .output(e => result1.push(e)); const branch2 = source .map(e => event(e.getKey(), Immutable.Map({ a: e.get("a") * 4 }))) // 8, 16, 24 .output(e => result2.push(e)); eventsIn.forEach(e => source.addEvent(e)); expect(result1[0].get("a")).toBe(6); expect(result1[1].get("a")).toBe(12); expect(result1[2].get("a")).toBe(18); expect(result2[0].get("a")).toBe(8); expect(result2[1].get("a")).toBe(16); expect(result2[2].get("a")).toBe(24); }); it("can coalese two streams", () => { const results = []; const streamIn = [ event(time(Date.UTC(2015, 2, 14, 1, 15, 0)), Immutable.Map({ in: 1 })), event(time(Date.UTC(2015, 2, 14, 1, 16, 0)), Immutable.Map({ in: 2 })), event(time(Date.UTC(2015, 2, 14, 1, 17, 0)), Immutable.Map({ in: 3 })), event(time(Date.UTC(2015, 2, 14, 1, 18, 0)), Immutable.Map({ in: 4 })), event(time(Date.UTC(2015, 2, 14, 1, 19, 0)), Immutable.Map({ in: 5 })) ]; const streamOut = [ event(time(Date.UTC(2015, 2, 14, 1, 15, 0)), Immutable.Map({ out: 9, count: 2 })), event(time(Date.UTC(2015, 2, 14, 1, 16, 0)), Immutable.Map({ out: 10, count: 3 })), event(time(Date.UTC(2015, 2, 14, 1, 17, 0)), Immutable.Map({ count: 4 })), event(time(Date.UTC(2015, 2, 14, 1, 18, 0)), Immutable.Map({ out: 12, count: 5 })), event(time(Date.UTC(2015, 2, 14, 1, 19, 0)), Immutable.Map({ out: 13, count: 6 })) ]; const source = stream() .coalesce({ fields: ["in", "out"] }) .output((e: Event) => results.push(e)); // Stream events for (let i = 0; i < 5; i++) { source.addEvent(streamIn[i]); source.addEvent(streamOut[i]); } expect(results.length).toBe(10); expect(results[5].get("in")).toBe(3); expect(results[5].get("out")).toBe(10); expect(results[8].get("in")).toBe(5); expect(results[8].get("out")).toBe(12); expect(results[9].get("in")).toBe(5); expect(results[9].get("out")).toBe(13); }); });
the_stack
import { resolveNameBank } from '../../../util'; import itemID from '../../../util/itemID'; import { Plant } from '../../types'; const specialPlants: Plant[] = [ { level: 23, plantXp: 19, checkXp: 0, harvestXp: 21, inputItems: resolveNameBank({ 'Seaweed spore': 1 }), outputCrop: itemID('Giant seaweed'), name: 'Seaweed', aliases: ['seaweed'], petChance: 7500, seedType: 'seaweed', growthTime: 40, numOfStages: 4, chance1: 149, chance99: 208, chanceOfDeath: 20, protectionPayment: resolveNameBank({ Numulite: 200 }), needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 0, canPayFarmer: true, canCompostPatch: true, canCompostandPay: true, // [QP, Patches Gained] additionalPatchesByQP: [ [3, 2] // Underwater Fossil Island (2) ], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [], timePerPatchTravel: 20, timePerHarvest: 10 }, { level: 26, plantXp: 21.5, checkXp: 0, harvestXp: 120, inputItems: resolveNameBank({ 'Limpwurt seed': 1 }), outputCrop: itemID('Limpwurt root'), variableYield: true, name: 'Limpwurt', aliases: ['limpwurt', 'limp'], petChance: 224_832, seedType: 'flower', growthTime: 20, numOfStages: 4, chance1: 0, chance99: 0, chanceOfDeath: 25, needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 4, canPayFarmer: false, canCompostPatch: true, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [ [1, 1], // Canifs Patch [33, 1] // Prif Patch ], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [ [45, 1] // Farming Guild ], timePerPatchTravel: 20, timePerHarvest: 5 }, { level: 35, plantXp: 35, checkXp: 7290, harvestXp: 0, inputItems: resolveNameBank({ 'Teak seed': 1 }), outputLogs: itemID('Teak logs'), treeWoodcuttingLevel: 35, name: 'Teak tree', aliases: ['teak tree', 'teak', 'teaks'], petChance: 5000, seedType: 'hardwood', growthTime: 3840, numOfStages: 8, chance1: 0, chance99: 0, chanceOfDeath: 15, protectionPayment: resolveNameBank({ 'Limpwurt root': 15 }), woodcuttingXp: 85, needsChopForHarvest: true, fixedOutput: false, givesLogs: true, givesCrops: false, defaultNumOfPatches: 0, canPayFarmer: true, canCompostPatch: true, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [ [3, 3] // Fossil Island (3) ], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [], timePerPatchTravel: 7, timePerHarvest: 10 }, { level: 36, plantXp: 31.5, checkXp: 625, harvestXp: 40, inputItems: resolveNameBank({ 'Grape seed': 1, Saltpetre: 1 }), outputCrop: itemID('Grapes'), name: 'Grape', aliases: ['grape', 'grapes'], petChance: 385_426, seedType: 'vine', growthTime: 35, numOfStages: 7, chance1: 139.8, chance99: 206.36, chanceOfDeath: 0, needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 12, canPayFarmer: false, canCompostPatch: false, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [], timePerPatchTravel: 2, timePerHarvest: 15 }, { level: 48, plantXp: 50.5, checkXp: 284.5, harvestXp: 19, inputItems: resolveNameBank({ 'Jangerberry seed': 1 }), outputCrop: itemID('Jangerberries'), name: 'Jangerberry', aliases: ['jangerberry', 'jangerberries'], petChance: 28_104, seedType: 'bush', growthTime: 160, numOfStages: 8, chance1: 88.6, chance99: 154.9, chanceOfDeath: 17, // needs data protectionPayment: resolveNameBank({ Watermelon: 6 }), needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 3, canPayFarmer: true, canCompostPatch: true, canCompostandPay: true, // [QP, Patches Gained] additionalPatchesByQP: [ [3, 1] // Etceteria patch (1) ], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [ [45, 1] // Farming Guild Low (1) ], timePerPatchTravel: 20, timePerHarvest: 10 }, { level: 53, plantXp: 61.5, checkXp: 0, harvestXp: 57.7, inputItems: resolveNameBank({ 'Mushroom spore': 1 }), outputCrop: itemID('Mushroom'), name: 'Mushroom', aliases: ['mushroom', 'mush'], petChance: 7500, seedType: 'mushroom', growthTime: 240, numOfStages: 6, chance1: 0, chance99: 0, chanceOfDeath: 17, needsChopForHarvest: false, fixedOutput: true, fixedOutputAmount: 6, givesLogs: false, givesCrops: true, defaultNumOfPatches: 0, canPayFarmer: false, canCompostPatch: true, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [ [1, 1] // Canifs patch (1) ], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [], timePerPatchTravel: 10, timePerHarvest: 5 }, { level: 55, plantXp: 66.5, checkXp: 374, harvestXp: 25, inputItems: resolveNameBank({ 'Cactus seed': 1 }), outputCrop: itemID('Cactus spine'), name: 'Cactus', aliases: ['cactus'], petChance: 7000, seedType: 'cactus', growthTime: 560, numOfStages: 7, chance1: -78.38, chance99: 178.2, chanceOfDeath: 15, protectionPayment: resolveNameBank({ 'Cadava berries': 6 }), needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 1, canPayFarmer: true, canCompostPatch: true, canCompostandPay: true, // [QP, Patches Gained] additionalPatchesByQP: [], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [ [45, 1] // Farming Guide Low (1) ], timePerPatchTravel: 20, timePerHarvest: 10 }, { level: 55, plantXp: 63, checkXp: 15_720, harvestXp: 0, inputItems: resolveNameBank({ 'Mahogany seed': 1 }), outputLogs: itemID('Mahogany logs'), treeWoodcuttingLevel: 50, name: 'Mahogany tree', aliases: ['mahogany tree', 'mahogany', 'mahog'], petChance: 5000, seedType: 'hardwood', growthTime: 5120, numOfStages: 8, chance1: 0, chance99: 0, chanceOfDeath: 12, protectionPayment: resolveNameBank({ 'Yanillian hops': 25 }), woodcuttingXp: 125, needsChopForHarvest: true, fixedOutput: false, givesLogs: true, givesCrops: false, defaultNumOfPatches: 0, canPayFarmer: true, canCompostPatch: true, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [ [3, 3] // Fossil Island (3) ], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [], timePerPatchTravel: 7, timePerHarvest: 10 }, { level: 59, plantXp: 78, checkXp: 437.5, harvestXp: 29, inputItems: resolveNameBank({ 'Whiteberry seed': 1 }), outputCrop: itemID('White berries'), name: 'Whiteberry', aliases: ['whiteberry', 'whiteberries'], petChance: 28_104, seedType: 'bush', growthTime: 160, numOfStages: 8, chance1: 88.6, chance99: 154.9, chanceOfDeath: 15, protectionPayment: resolveNameBank({ Mushroom: 8 }), needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 3, canPayFarmer: true, canCompostPatch: true, canCompostandPay: true, // [QP, Patches Gained] additionalPatchesByQP: [ [3, 1] // Etceteria patch (1) ], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [ [45, 1] // Farming Guild Low (1) ], timePerPatchTravel: 20, timePerHarvest: 10 }, { level: 63, plantXp: 91, checkXp: 0, harvestXp: 512, inputItems: resolveNameBank({ 'Belladonna seed': 1 }), outputCrop: itemID('Cave nightshade'), variableYield: true, name: 'Belladonna', aliases: ['belladonna', 'bella', 'nightshade'], petChance: 8000, seedType: 'belladonna', growthTime: 320, numOfStages: 4, chance1: 0, chance99: 0, chanceOfDeath: 17, needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 1, canPayFarmer: false, canCompostPatch: true, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [], timePerPatchTravel: 15, timePerHarvest: 5 }, { level: 64, plantXp: 68, checkXp: 230, harvestXp: 68, inputItems: resolveNameBank({ 'Potato cactus seed': 1 }), outputCrop: itemID('Potato cactus'), name: 'Potato cactus', aliases: ['potato cactus'], petChance: 160_594, seedType: 'cactus', growthTime: 70, numOfStages: 7, chance1: 88.6, chance99: 154.9, chanceOfDeath: 12, protectionPayment: resolveNameBank({ 'Snape grass': 8 }), needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 1, canPayFarmer: true, canCompostPatch: true, canCompostandPay: true, // [QP, Patches Gained] additionalPatchesByQP: [], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [ [45, 1] // Farming Guide Low (1) ], timePerPatchTravel: 20, timePerHarvest: 10 }, { level: 65, plantXp: 62, checkXp: 12_600, harvestXp: 0, inputItems: resolveNameBank({ 'Hespori seed': 1 }), name: 'Hespori', aliases: ['hespori'], petChance: 7000, seedType: 'hespori', growthTime: 1920, numOfStages: 4, chance1: 0, chance99: 0, chanceOfDeath: 0, protectionPayment: {}, needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: false, defaultNumOfPatches: 0, canPayFarmer: false, canCompostPatch: false, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [ [65, 1] // Farming Guide Medium (1) ], timePerPatchTravel: 20, timePerHarvest: 90 }, { level: 70, plantXp: 120, checkXp: 675, harvestXp: 45, inputItems: resolveNameBank({ 'Poison ivy seed': 1 }), outputCrop: itemID('Poison ivy berries'), name: 'Poison ivy', aliases: ['poison ivy'], petChance: 28_104, seedType: 'bush', growthTime: 160, numOfStages: 8, chance1: 88.6, chance99: 154.9, chanceOfDeath: 0, needsChopForHarvest: false, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 3, canPayFarmer: false, canCompostPatch: false, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [ [3, 1] // Etceteria patch (1) ], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [ [45, 1] // Farming Guild Low (1) ], timePerPatchTravel: 20, timePerHarvest: 10 }, { level: 72, plantXp: 129.5, checkXp: 12_096, harvestXp: 48.5, inputItems: resolveNameBank({ 'Calquat tree seed': 1 }), outputCrop: itemID('Calquat fruit'), treeWoodcuttingLevel: 1, name: 'Calquat tree', aliases: ['calquat tree', 'calquat'], petChance: 6000, seedType: 'calquat', growthTime: 1280, numOfStages: 8, chance1: 0, chance99: 0, chanceOfDeath: 17, protectionPayment: resolveNameBank({ 'Poison ivy berries': 8 }), needsChopForHarvest: true, fixedOutput: true, fixedOutputAmount: 6, givesLogs: false, givesCrops: true, defaultNumOfPatches: 1, canPayFarmer: true, canCompostPatch: true, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [], timePerPatchTravel: 20, timePerHarvest: 10 }, { level: 74, plantXp: 126, checkXp: 13_240, harvestXp: 0, inputItems: resolveNameBank({ 'Crystal acorn': 1 }), outputCrop: itemID('Crystal shard'), variableYield: true, variableOutputAmount: [ [null, 8, 10], ['compost', 10, 12], ['supercompost', 12, 14], ['ultracompost', 14, 16] ], treeWoodcuttingLevel: 1, name: 'Crystal tree', aliases: ['crystal tree', 'crystal'], petChance: 9000, seedType: 'crystal', growthTime: 480, numOfStages: 6, chance1: 0, chance99: 0, chanceOfDeath: 0, needsChopForHarvest: true, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 0, canPayFarmer: false, canCompostPatch: true, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [ [33, 1] // Prifddinas (1) ], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [], timePerPatchTravel: 20, timePerHarvest: 5 }, { level: 83, plantXp: 199.5, checkXp: 19_301, harvestXp: 0, inputItems: resolveNameBank({ 'Spirit seed': 1 }), treeWoodcuttingLevel: 1, name: 'Spirit tree', aliases: ['spirit tree', 'spirit'], petChance: 5000, seedType: 'spirit', growthTime: 3840, numOfStages: 12, chance1: 0, chance99: 0, chanceOfDeath: 8, protectionPayment: resolveNameBank({ 'Monkey nuts': 5, 'Monkey bar': 1, 'Ground tooth': 1 }), needsChopForHarvest: true, fixedOutput: false, givesLogs: false, givesCrops: false, defaultNumOfPatches: 1, canPayFarmer: true, canCompostPatch: true, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [ [99, 3] // Plant in all patches at lvl 99 ], additionalPatchesByFarmGuildAndLvl: [ [91, 1] // Plant up to 2 seeds at lvl 91 with farm guild ], timePerPatchTravel: 20, timePerHarvest: 1 }, { level: 85, plantXp: 204, checkXp: 14_130, harvestXp: 23.5, inputItems: resolveNameBank({ 'Celastrus seed': 1 }), outputCrop: itemID('Celastrus bark'), treeWoodcuttingLevel: 1, name: 'Celastrus tree', aliases: ['celastrus tree', 'celastrus'], petChance: 9000, seedType: 'celastrus', growthTime: 800, numOfStages: 5, chance1: -26.6, chance99: 63, chanceOfDeath: 15, protectionPayment: resolveNameBank({ 'Potato cactus': 8 }), needsChopForHarvest: true, fixedOutput: false, givesLogs: false, givesCrops: true, defaultNumOfPatches: 0, canPayFarmer: true, canCompostPatch: true, canCompostandPay: true, // [QP, Patches Gained] additionalPatchesByQP: [], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [ [85, 1] // Farming Guild High (1) ], timePerPatchTravel: 10, timePerHarvest: 10 }, { level: 90, plantXp: 230, checkXp: 22_450, harvestXp: 0, inputItems: resolveNameBank({ 'Redwood tree seed': 1 }), outputLogs: itemID('Redwood logs'), treeWoodcuttingLevel: 90, name: 'Redwood tree', aliases: ['redwood tree', 'redwood'], petChance: 5000, seedType: 'redwood', growthTime: 6400, numOfStages: 11, chance1: 0, chance99: 0, chanceOfDeath: 8, protectionPayment: resolveNameBank({ Dragonfruit: 6 }), woodcuttingXp: 380, needsChopForHarvest: true, fixedOutput: false, givesLogs: true, givesCrops: false, defaultNumOfPatches: 0, canPayFarmer: true, canCompostPatch: true, canCompostandPay: false, // [QP, Patches Gained] additionalPatchesByQP: [], // [Farm Lvl, Patches Gained] additionalPatchesByFarmLvl: [], additionalPatchesByFarmGuildAndLvl: [ [85, 1] // Farming Guild High (1) ], timePerPatchTravel: 10, timePerHarvest: 15 } ]; export default specialPlants;
the_stack
type decimal = number | string; /** * An integer which can be serialized as either a floating point value, or a * string value. */ type int64 = number | string; /** * A Shopify [Order][]. * * [Order]: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04 */ interface Order { app_id: int64, billing_address: Address | null, browser_ip: string | null, buyer_accepts_marketing: string | null, cancel_reason: string | null, cancelled_at: Date | null, // ISO 8601 cart_token: string | null, client_details: ClientDetails | null, closed_at: Date | null, created_at: Date | null, currency: string | null, current_total_duties_set: string | null, customer: Customer | null, customer_local: string | null, discount_applications: DiscountApplication[] | null, discount_codes: DiscountCode[] | null, email: string | null, financial_status: string | null, fulfillments: Fulfillment[] | null, fulfillment_status: string | null, gateway: string | null, // Deprecated. id: int64, landing_site: string | null, line_items: LineItem[] | null, location_id: int64 | null, name: string | null, note: string | null, note_attributes: Property[] | null, number: int64 | null, order_number: int64 | null, original_total_duties_set: PriceSet | null, payment_details: PaymentDetails | null, // Deprecated. payment_gateway_names: string[] | null, phone: string | null, presentment_currency: string | null, processed_at: Date | null, processing_method: string | null, referring_site: string | null, refunds: Refund[] | null, shipping_address: Address | null, // Optional. shipping_lines: ShippingLine[] | null, source_name: string | null, subtotal_price: number | null, subtotal_price_set: PriceSet | null, tags: string | null, // Comma-separated. tax_lines: TaxLine[] | null, // May not have `price_set` here? taxes_included: boolean | null, test: boolean | null, token: string | null, total_discounts: decimal | null, total_discounts_set: PriceSet | null, total_line_items_price: decimal | null, total_line_items_price_set: PriceSet | null, total_price_set: PriceSet | null, total_tax: decimal | null, total_tax_set: PriceSet | null, total_tip_received: decimal | null, total_weight: number | null, updated_at: Date | null, user_id: int64 | null, order_status_url: string | null, } /** * An address in an [Order][]. * * [Order]: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04 */ interface Address { address1: string | null, address2: string | null, city: string | null, company: string | null, country: string | null, first_name: string | null, last_name: string | null, phone: string | null, province: string | null, zip: string | null, name: string | null, province_code: string | null, country_code: string | null, // We could treat these as decimal values instead. latitude: string | null, longitude: string | null, } /** * Information about the browser used to place an [Order][]. * * [Order]: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04 */ interface ClientDetails { accepts_language: string | null, browser_height: number | null, browser_ip: string | null, browser_width: number | null, session_hash: string | null, user_agent: string | null, } /** * A Shopify [Customer][]. * * [Customer]: https://shopify.dev/docs/admin-api/rest/reference/customers/customer?api[version]=2020-04 */ interface Customer { accepts_marketing: boolean | null, accepts_marketing_updated_at: Date | null, addresses: CustomerAddress[] | null, admin_graphql_api_id: string | null, created_at: string | null, currency: string | null, default_address: CustomerAddress | null, email: string | null, first_name: string | null, id: int64, last_name: string | null, last_order_id: int64 | null, last_order_name: string | null, //metafield: Metafield | null, multipass_identifier: string | null, note: string | null, orders_count: int64 | null, // String as integer. phone: string | null, state: string | null, // "disabled" is a valid value. tags: string | null, tax_exempt: boolean | null, tax_exemptions: string[] | null, total_spent: decimal | null, updated_at: Date | null, verified_email: boolean | null, } /** * An address associated with a Shopify [Customer][]. * * This is not actually the same as the `Address` type on `Order`. * * [Customer]: https://shopify.dev/docs/admin-api/rest/reference/customers/customer?api[version]=2020-04 */ interface CustomerAddress { address1: string | null, address2: string | null, city: string | null, company: string | null, country_code: string | null, country: string | null, country_name: string | null, customer_id: int64 | null, default: boolean | null, first_name: string | null, id: int64, last_name: string | null, name: string | null, phone: string | null, province_code: string | null, province: string | null, zip: string | null, } /** * A discount application. Part of an [Order][]. * * [Order]: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04 */ interface DiscountApplication { type: string | null, description: string | null, value: decimal | null, value_type: string | null, allocation_method: string | null, target_selection: string | null, target_type: string | null, } /** * A discount applied to an [Order][]. * * [Order]: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04 */ interface DiscountCode { code: string | null, amount: decimal | null, type: string | null, } /** * A Shopify [Fulfillment][]. * * [Fulfillment]: https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/fulfillment?api[version]=2020-04 */ interface Fulfillment { created_at: Date | null, id: int64, line_items: LineItem[] | null, location_id: number | null, name: string | null, notify_customer: boolean | null, order_id: string | null, receipt: Receipt | null, service: string | null, shipment_status: string | null, status: string | null, tracking_company: string | null, tracking_numbers: string[] | null, tracking_urls: string[] | null, updated_at: string | null, variant_inventory_management: string | null, } /** * A line item in an [Order][] or a [Fulfillment][]. * * [Order]: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04 * [Fulfillment]: https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/fulfillment?api[version]=2020-04 */ interface LineItem { fulfillable_quantity: number | null, fulfillment_service: string | null, fulfillment_status: string | null, grams: number | null, id: int64, price: decimal | null, product_id: int64 | null, quantity: int64 | null, // Let's hope this is an integer. requires_shipping: boolean | null, sku: string | null, title: string | null, variant_id: int64 | null, variant_title: string | null, vendor: string | null, name: string | null, gift_card: boolean | null, price_set: PriceSet | null, properties: Property[] | null, taxable: boolean | null, tax_lines: TaxLine[] | null, total_discount: decimal | null, total_discount_set: PriceSet | null, discount_allocations: DiscountAllocation[] | null, duties: Duty[] | null, tip_payment_gateway?: string | null, tip_payment_method?: string | null, // These are seen on the fulfillment page, but not the order page. variant_inventory_management?: string | null, product_exists?: boolean | null, } /** * A receipt for a Shopify [Fulfillment][]. * * [Fulfillment]: https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/fulfillment?api[version]=2020-04 */ interface Receipt { testcase: boolean | null, // In the example, this is a string containing an integer value, but I'm not sure that's guaranteed. authorization: string | null, } /** * Prices in the shop's internal currency and the customer-facing currency. * * Used widely throughout the API. */ interface PriceSet { shop_money: Money | null, presentement_money: Money | null, } /** * A sum of money and a currency. Used in `PriceSet`. */ interface Money { // This appears as decimal strings or floating point numbers, depending on // the example. amount: decimal | null, currency_code: string | null, } /** * A key/value property attached to another object. Appears in several places. */ interface Property { name: string, value: string, // Well, we hope that's the only possibility. } /** * Tax information. Appears in many places. */ interface TaxLine { title: string | null, price: decimal | null, price_set?: PriceSet | null, // Present in some examples, not others. rate: number | null, } /** * A discount allocation to a line item in an [Order][]. * * [Order]: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04 */ interface DiscountAllocation { amount: decimal | null, discount_application_index: int64 | null, amount_set: PriceSet | null, } /** * Duty information. Appears in several places. */ interface Duty { id: string, // Shown as string in example, but we could treat it as int64. harmonized_system_code: string | null, country_code_of_origin: string | null, shop_money: Money | null, presentment_money: Money | null, tax_lines: TaxLine[] | null, admin_graphql_api_id: string | null, } /** * How an [Order][] was paid for. * * [Order]: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04 */ interface PaymentDetails { avs_result_code: string | null, credit_card_bin: string | null, cvv_result_code: string | null, credit_card_number: string | null, credit_card_company: string | null, } /** * A Shopify [Refund][]. * * [Refund]: https://shopify.dev/docs/admin-api/rest/reference/orders/refund?api[version]=2020-04 */ interface Refund { created_at: Date | null, duties: Duty[] | null, id: int64, note: string | null, order_adjustments: OrderAdjustment[] | null, processed_at: Date | null, refund_line_items: RefundLineItem[] | null, restock: boolean | null, transactions: Transaction[] | null, user_id: number | null, } /** * An order adjustment in a Shopify [Refund][]. * * [Refund]: https://shopify.dev/docs/admin-api/rest/reference/orders/refund?api[version]=2020-04 */ interface OrderAdjustment { id: int64, order_id: int64, refund_id: int64 | null, amount: decimal | null, tax_amount: decimal | null, kind: string | null, reason: string | null, amount_set: PriceSet | null, tax_amount_set: PriceSet | null, } /** * A line-item in a Shopify [Refund][]. * * [Refund]: https://shopify.dev/docs/admin-api/rest/reference/orders/refund?api[version]=2020-04 */ interface RefundLineItem { id: int64, line_item: LineItem | null, line_item_id: int64 | null, quantity: int64 | null, location_id: int64 | null, restock_type: string | null, subtotal: decimal | null, total_tax: decimal | null, subtotal_set: PriceSet | null, total_tax_set: PriceSet | null, } /** * A Shopify [Transaction][]. * * [Transaction]: https://shopify.dev/docs/admin-api/rest/reference/orders/transaction?api[version]=2020-04 */ interface Transaction { amount: decimal | null, authorization: string | null, created_at: Date | null, currency: string | null, device_id: int64 | null, error_code: string | null, gateway: string | null, id: int64, kind: string | null, location_id: int64 | null, message: string | null, order_id: int64 | null, payment_details: string | null, parent_id: int64 | null, processed_at: Date | null, receipt: any | null, // "The value of this field depends on which gateway the shop is using." source_name: string | null, status: string | null, test: boolean | null, user_id: int64 | null, currency_exchange_adjustment: CurrencyExchangeAdjustment | null, } /** * An adjustment to a Shopify [Transaction][] due to currency exhange rates. * * [Transaction]: https://shopify.dev/docs/admin-api/rest/reference/orders/transaction?api[version]=2020-04 */ interface CurrencyExchangeAdjustment { id: int64, adjustment: decimal | null, original_amount: decimal | null, final_amount: decimal | null, currency: string | null, } /** * Shipping fees for an [Order][]. * * [Order]: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04 */ interface ShippingLine { code: string | null, price: decimal | null, price_set: PriceSet | null, discounted_price: decimal | null, discounted_price_set: PriceSet | null, source: string | null, title: string | null, tax_lines: TaxLine[] | null, carrier_identifier: string | null, requested_fulfillment_service_id: string | null, }
the_stack
import type { AccessibilityProps, GestureResponderEvent, StyleProp, TextProps, TextStyle, TouchableHighlightProps, ViewProps, ViewStyle } from 'react-native'; import type { CSSPropertyNameList, CustomElementModel, Document, DocumentContext as TREDocumentContext, DomVisitorCallbacks, Element, EmbeddedTagNames, HTMLContentModel, HTMLElementModel, MixedStyleDeclaration, MixedStyleRecord, NativeBlockStyles, NativeTextStyles, Node, NodeWithChildren, SetMarkersForTNode, StylessReactNativeProps, TDocument, TNode, TPhrasing, TRenderEngineOptions, TText } from '@native-html/transient-render-engine'; import type { CounterStyleRenderer } from '@jsamr/counter-style'; import type { ComponentType, ReactElement, ReactNode } from 'react'; import type { CustomTagRendererRecord } from './render/render-types'; import type { ParserOptions as HtmlParserOptions } from 'htmlparser2'; /** * A record of HTMLElementModels. * * @public */ export type HTMLElementModelRecord = Record< string, | CustomElementModel<string, HTMLContentModel> | HTMLElementModel<string, HTMLContentModel> >; /** * @public */ export interface ImageDimensions { height: number; width: number; } /** * Props for custom Pressable components. * * @public */ export interface GenericPressableProps extends AccessibilityProps { borderless?: boolean; onPress?: TouchableHighlightProps['onPress']; style?: StyleProp<ViewStyle>; } /** * Configuration for ol and ul. * * @public */ export interface ListElementConfig { /** * When `true`, the width of the marker box will be adapted depending on * `fontSize` and the highest number of characters in the printed range. * * If this length is superior than the left (or right in ltr mode) padding, * a supplemental space will be added before every list child. * * When `false`, the left (or right in ltr mode) padding will be invariable. * * @defaultValue false */ enableDynamicMarkerBoxWidth?: boolean; /** * If `true` and the direction is set to `'rtl'` (either via `dir` attribute * or `direction` CSS property): * * - lists markers will be flushed to the right when `I18nManager.isRtl` is `false`. * - list markers prefixes and suffixes print order will be reversed. * * @remarks Beware that left and right padding of li elements *will not* * be switched. * * @defaultValue false */ enableExperimentalRtl?: boolean; /** * Remove bottom margin if this element parent is an `li` element and it * is its last child. * * @defaultValue true */ enableRemoveBottomMarginIfNested?: boolean; /** * Remove top margin if this element parent is an `li` element and it * is its first child. * * @defaultValue true */ enableRemoveTopMarginIfNested?: boolean; /** * Get default list-style-type given the number of nest level for this list. * * @remarks This function will not be used when a list element has its own * `list-style-type` CSS property, or has inherited this property from * parents. * * @param nestLevel - The number of parents elements with the same tag name. */ getFallbackListStyleTypeFromNestLevel?: ( nestLevel: number ) => DefaultSupportedListStyleType; /** * Customize the marker box appearance (the `View` containing the marker, * e.g. the symbol prefixing list elements). * * @remarks This is useful to set some right padding or a different background for example. * * @warning **Do not**: * - Use margin (since the width will match the `<ol>` / `<ul>` padding left) * - Set width constraints (since the width will match the `<ol>` / `<ul>` padding left) */ markerBoxStyle?: StyleProp<ViewStyle>; /** * Customize the marker text appearance (the `Text` component in which the marker, * e.g. the symbol prefixing list elements). * * @remarks Useful to set the color, fontFamily, fontSize of the marker. * Avoid using padding here, take advantage of `markerBoxStyle` instead. * * @warning This style must be a style object! Arrays, and `Stylesheet` styles will not work. */ markerTextStyle?: TextStyle; } /** * Props for custom renderers. The convention is to declare a field per tag name. * In doing so, you can benefit from `useRendererProps('tagname')` in custom renderers. * * @remarks **Typescript users**: If you need to add fields to the {@link RenderersProps} interface, * you should use {@link https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation | module augmentation}: * * ```ts * declare module 'react-native-render-html' { * interface RenderersProps { * div?: { * customProp: boolean; * }; * } * } * @public */ export interface RenderersProps extends Record<string, any> { a: { /** * A callback to handle anchors presses. * * @remarks The `href` argument has been normalized, see {@link useNormalizedUrl}. * * @defaultValue A function using React Native `Linking.onpenUrl`. * @param event - The {@link GestureResponderEvent} event. * @param href - The normalized href, see {@link useNormalizedUrl}. * @param htmlAttribs - The attributes of the underlying {@link Element}. * @param target - The normalized `target` for this hyperlink. */ onPress?: ( event: GestureResponderEvent, href: string, htmlAttribs: Record<string, string>, target: '_blank' | '_self' | '_parent' | '_top' ) => void; }; img: { /** * Support for relative percent-widths. * * @defaultValue false */ enableExperimentalPercentWidth?: boolean; /** * Default width and height to display while image's dimensions are being retrieved. * * @remarks Changes to this prop will cause a react tree update. Always * memoize it. */ initialDimensions?: ImageDimensions; }; ol: ListElementConfig; ul: ListElementConfig; } /** * Props passed to internal and custom renderers. * * @public */ export interface RenderHTMLPassedProps { /** * Props to use in custom renderers with `useRendererProps`. * * @remarks * - When you use the hook, you'll get this object deep-merged with default renderers props. * - **Typescript users**: If you need to add fields to the {@link RenderersProps} interface, * you should use {@link https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation | module augmentation}: * * ```ts * declare module 'react-native-render-html' { * interface RenderersProps { * div?: { * customProp: boolean; * }; * } * } * ``` */ renderersProps?: Partial<RenderersProps>; } /** * A map which defines the type of parameters passed as third argument * of {@link EmbeddedHeadersProvider}. */ export interface EmbeddedWithHeadersParamsMap extends Record<EmbeddedWithHeadersTagName, Record<string, unknown>> { img: { /** * The print height of the image in DPI, if it can be determined beforehand * (for example, with a _height_ attribute set or an inline style). */ printHeight?: number; /** * The print width of the image in DPI, if it can be determined beforehand * (for example, with a _width_ attribute set or an inline style). */ printWidth?: number; }; } /** * Tag names eligible for headers provision. */ export type EmbeddedWithHeadersTagName = Exclude< EmbeddedTagNames, 'svg' | 'canvas' | 'math' >; /** * A function to provide headers to a peculiar embedded element. */ export type EmbeddedHeadersProvider = <T extends EmbeddedWithHeadersTagName>( uri: string, tagName: T, params: EmbeddedWithHeadersParamsMap[T] ) => Record<string, string> | null | void; /** * Props shared across renderers. * * @warning Shared props changes will cause all the React tree to invalidate. You should * always memoize these. * * @public */ export interface RenderHTMLSharedProps { /** * A component used to wrap pressable elements (e.g. when provided `onPress`). * Note that textual elements will not be wrapped; `TextProps.onPress` will * be used instead. * * @defaultValue A `TouchableNativeFeedback` based component on Android, `TouchableHighlight` based component on other platforms. */ GenericPressable?: ComponentType<GenericPressableProps>; /** * The WebView component used by plugins (iframe, table)... * See {@link https://github.com/native-html/plugins | @native-html/plugins}. * * @defaultValue `() => null` */ WebView?: ComponentType<any>; /** * When `true` (default), anonymous {@link TPhrasing} nodes parents of a * lonely {@link TText} node are not translated as React Native `Text` * elements. Instead, their child is directly rendered, e.g. with no `Text` * wrapper. * * @example **With `true`:** * * ```xml * <TPhrasing> * <TText>Hello</TText> * </TPhrasing> * ``` * * is translated to * * ```xml * <Text>Hello</Text> * ``` * * **With `false`:** * * ```xml * <TPhrasing> * <TText>Hello</TText> * </TPhrasing> * ``` * * is translated to * * ```xml * <Text><Text>Hello</Text></Text> * ``` * * @warning Unless strictly necessary, this should be left to `true` because * some styles don't apply to nested React Native `Text` elements * (`borderRadius`, `padding`...). * * @defaultValue true */ bypassAnonymousTPhrasingNodes?: boolean; /** * A function which takes contentWidth and tagName as arguments and returns a * new width. Can return Infinity to denote unconstrained widths. * * @param contentWidth - The available width in this {@link RenderHTML} component. * @param tagName - The tagName of this element to render, e.g. "img". * * @remarks * - Take advantage of {@link useComputeMaxWidthForTag} hook inside custom * renderers to get the maximum width for this tag. * - Changes to this prop will cause a react tree update. Always * memoize it. * * @defaultValue `(c) => c` */ computeEmbeddedMaxWidth?: (contentWidth: number, tagName: string) => number; /** * Provide support for list style types which are not supported by this * library. * * @remarks Check the numerous presets provided by * {@link https://github.com/jsamr/react-native-li/tree/master/packages/counter-style#readme | @jsamr/counter-style} * as they require zero-effort! * * @example * * ```js * import hebrew from '@jsamr/counter-style/presets/hebrew'; * * const customListStyleSpecs = { * hebrew: { * type: 'textual', * counterStyleRenderer: hebrew * } * }; * ``` */ customListStyleSpecs?: Record<string, ListStyleSpec>; /** * Log to the console a snapshot of the rendered {@link TDocument} after each * transient render tree invalidation. * * @defaultValue `false` */ debug?: boolean; /** * Default props for Text elements in the render tree. * * @remarks "style" will be merged into the tnode own styles. */ defaultTextProps?: TextProps; /** * Default props for View elements in the render tree. * * @remarks "style" will be merged into the tnode own styles. */ defaultViewProps?: ViewProps; /** * Default props for WebView elements in the render tree used by plugins. */ defaultWebViewProps?: any; /** * Follow closely the HTML standard and ignore `<br>` tags closing an * inline formatting context. * * @example * * ```html * <p> * Hello<br /> * </p> * ``` * * When this flag is set to `true`, one line is printed instead of two on * native platforms, which is the HTML-compliant behavior. * * @defaultValue false * * @remarks Recommended value is `true` on non-web platforms. Also note that * this is an experimental feature, thus subject to behavioral instability. */ enableExperimentalBRCollapsing?: boolean; /** * React Native doesn't handle lines like we would expect on a web browser. * For example: * ```jsx * <View> * <Text></Text> * </View> * ``` * will span 20 dpi in height. Setting this prop to `true` will make * the renderer take those React Native oddities into account. * See also this ticket: https://git.io/JErwX * * @remarks This is an experimental feature, thus subject to behavioral * instability. * * @defaultValue false */ enableExperimentalGhostLinesPrevention?: boolean; /** * Enable or disable margin collapsing CSS behavior (experimental!). * See {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing | MDN docs}. * * @remarks Limitations: * - Only adjacent siblings collapsing is implemented. * - If one of the margins height is in percent, no collapsing will occur. * - Will apply indiscriminately to all `display` properties (including * flex), which is not standard. * - Might not work well with {@link TPhrasing} nodes having only one child. * * This is an experimental feature, thus subject to behavioral instability. * * @defaultValue false */ enableExperimentalMarginCollapsing?: boolean; /** * Color used for pressable items, either for the ripple effect (Android), or * highlight (other platforms). * * @defaultValue rgba(38, 132, 240, 0.2) */ pressableHightlightColor?: string; /** * Provide headers for specific embedded elements, such as images, iframes... * * @example * * ```js * function provideEmbeddedHeaders(uri, tagName, params) { * if (tagName === "img" && * uri.startsWith("https://example.com")) { * return { * Authorization: "Bearer daem6QuaeloopheiD7Oh" * } * } * * // ... * * <RenderHTML provideEmbeddedHeaders={provideEmbeddedHeaders} /> * ``` */ provideEmbeddedHeaders?: EmbeddedHeadersProvider; } type SharedPropsWithoutFallback = Exclude< keyof RenderHTMLSharedProps, 'provideEmbeddedHeaders' | 'GenericPressable' | 'customListStyleSpecs' >; /** * Shared props available with {@link useSharedProps} hook or `sharedProp` * custom renderers prop. */ export type RenderHTMLAmbiantSharedProps = Required< Pick<RenderHTMLSharedProps, SharedPropsWithoutFallback> > & Omit<RenderHTMLSharedProps, SharedPropsWithoutFallback>; /** * Configuration for the {@link TRenderEngineProvider} component. * * @warning When one of these props changes, it will cause the * {@link TRenderEngine} to be rebuilt, and all transient trees to be * re-assembled. Beware! * * @public */ export interface TRenderEngineConfig { /** * Whitelist specific inline CSS style properties and ignore the others. * * @warning Property names must be camelCased: for example, `background-color` * should be written `backgroundColor`. */ allowedStyles?: CSSPropertyNameList; /** * The default style for the document (root). Inheritable styles will be * transferred to children. That works also for textual styles. * * @warning **Do NOT** use the `StyleSheet` API to create those styles. * * @remarks Any `fontFamily` used in those styles must be registered with * {@link TRenderEngineConfig.systemFonts} prop. */ baseStyle?: MixedStyleDeclaration; /** * Provide mixed styles to target elements selected by CSS classes. * * @warning **Do NOT** use the `StyleSheet` API to create those styles. * * @remarks Any `fontFamily` used in those styles must be registered with * {@link TRenderEngineConfig.systemFonts} prop. */ classesStyles?: MixedStyleRecord; /** * Customize element models for target tags. */ customHTMLElementModels?: HTMLElementModelRecord; /** * **Experimental** * * Disable hoisting. Especially useful for rendering with react-native-web. * Note that your layout might break in native! * * @defaultValue false */ dangerouslyDisableHoisting?: boolean; /** * **Experimental** * * Disable whitespace collapsing. Especially useful if your html is * being pre-processed server-side with a minifier. * * @defaultValue false */ dangerouslyDisableWhitespaceCollapsing?: boolean; /** * An object which callbacks will be invoked when a DOM element or text node * has been parsed and its children attached. This is great to tamper the dom, * remove children, insert nodes, change text nodes data... etc. * * @remark Each callback is applied during DOM parsing, thus with very little * overhead. However, it means that one node next siblings won't be available * since it has not yet been parsed. If you need some siblings logic, apply * this logic to the children of this node. */ domVisitors?: DomVisitorCallbacks; /** * The default value in pixels for 1em. */ emSize?: number; /** * Enable or disable inline CSS processing of inline styles. * * @remarks If you want to allow or disallow specific properties, use * `allowedStyles` or `ignoredStyles` props. * * @defaultValue true */ enableCSSInlineProcessing?: boolean; /** * Enable or disable fallback styles for each tag. For example, `pre` tags * will have `whiteSpace` set to 'pre' by default. * * @defaultValue true */ enableUserAgentStyles?: boolean; /** * A record for specific CSS fonts. * * @remarks Use `Plaform.select({ ios: ..., android: ..., default: ...})`. */ fallbackFonts?: FallbackFontsDefinitions; /** * ParserOptions for {@link https://github.com/fb55/htmlparser2/wiki/Parser-options | htmlparser2}. * * @defaultValue `{ decodeEntities: true }` */ htmlParserOptions?: HtmlParserOptions; /** * Provide mixed styles to target elements identified by the `id` attribute. * * @warning **Do NOT** use the `StyleSheet` API to create those styles. * * @remarks Any `fontFamily` used in those styles must be registered with * {@link TRenderEngineConfig.systemFonts} prop. */ idsStyles?: MixedStyleRecord; /** * Ignore specific DOM nodes. * * @warning When this function is invoked, the node has not yet been attached * to its parent or siblings. Use the second argument (`parent`) if you * need to perform logic based on parent. * * @remarks * - The function is applied during DOM parsing, thus with very little * overhead. However, it means that one node next siblings won't be * available since it has not yet been parsed. * - Use `ignoredDomTags` if you just need to target specific tag names. * * @returns `true` if this node should not be included in the DOM, anything * else otherwise. * * @param node - The node to check. Beware the parent node is not accessible. Use the second argument. * @param parent - The parent node. */ ignoreDomNode?: ( node: Node, parent: NodeWithChildren ) => boolean | void | unknown; /** * A list of **lowercase tags** which should not be included in the DOM. * * @remark The filtering is happening during parsing, thus with very little * overhead. */ ignoredDomTags?: string[]; /** * Blacklist specific inline CSS style properties and allow the others. * * @warning Property names must be camelCased: for example, `background-color` * should be written `backgroundColor`. * * @remarks Note that if you don't want inline style processing at all, you * should set `enableCSSInlineProcessing` prop to `false`. */ ignoredStyles?: CSSPropertyNameList; /** * Select the DOM root before TTree generation. For example, you could * iterate over children until you reach an article element and return this * element. * * @remarks Applied after DOM parsing, before normalization and TTree * construction. Before normalization implies that a body will be added in * the tree **after** selecting root. */ selectDomRoot?: TRenderEngineOptions['selectDomRoot']; /** * Set custom markers from a {@link TNode} and all its descendants. {@link Markers} will be * accessible in custom renderers via `tnode.markers` prop. * * @param targetMarkers - The markers to modify. * @param parentMarkers - {@link Markers} from the parent {@link TNode}. * @param tnode - The {@link TNode} to inspect. * * @defaultValue `() => null` */ setMarkersForTNode?: SetMarkersForTNode; /** * A list of fonts available in the current platform. These fonts will be used * to select the first match in CSS `fontFamily` property, which supports a * comma-separated list of fonts. By default, a handful of fonts are selected * per platform. * * @remarks * - You need to specify any font family you wish to use via `*styles` props * here, otherwise those styles will be ignored. * - If you are using expo, you should use or extend `Constants.systemFonts`. * * @example * ```tsx * import RenderHTML, {defaultSystemFonts} from 'react-native-render-html' * // Replace defaultSystemFonts with Constants.systemFonts if you're using expo * const systemFonts = [...defaultSystemFonts, 'Mysuperfont'] * // ... * <RenderHTML systemFonts={systemFonts} ... /> * ``` */ systemFonts?: string[]; /** * Provide mixed styles to target HTML tag names. * * @warning **Do NOT** use the `StyleSheet` API to create those styles. * * @remarks Any `fontFamily` used in those styles must be registered with * {@link TRenderEngineConfig.systemFonts} prop. */ tagsStyles?: MixedStyleRecord; } /** * A source represented by a URI. * * @public */ export interface HTMLSourceUri { /** * The HTTP body to send with the request. This must be a valid * UTF-8 string, and will be sent exactly as specified, with no * additional encoding (e.g. URL-escaping or base64) applied. */ body?: string; /** * Additional HTTP headers to send with the request. */ headers?: Record<string, string>; /** * The HTTP Method to use. Defaults to GET if not specified. */ method?: string; /** * The URI to load in the `HTML` component. Can be a local or remote file. */ uri: string; } /** * A source which content is provided in-place. * * @public */ export interface HTMLSourceInline { /** * The base URL to resolve relative URLs in the HTML code. * See {@link useNormalizedUrl}. */ baseUrl?: string; /** * A static HTML page to display in the HTML component. */ html: string; } /** * A source which content is a DOM tree created by the transient render * engine `parseDocument` method. * * See {@link useAmbientTRenderEngine}. * * @remarks When you use a DOM source, the `onHTMLLoaded` callback will never * be invoked for this source, since the source loader hasn't access to the * HTML source of the DOM. * * @public */ export interface HTMLSourceDom { /** * The base URL to resolve relative URLs in the HTML code. * See {@link useNormalizedUrl}. */ baseUrl?: string; /** * A DOM object. This object **must** have been created with * the transient render engine `parseDocument` method. */ dom: Element | Document; } /** * The source to render. * * @public */ export type HTMLSource = HTMLSourceInline | HTMLSourceDom | HTMLSourceUri; /** * * Props for the {@link RenderHTMLConfigProvider} component. * * @public */ export interface RenderHTMLConfig extends RenderHTMLSharedProps, RenderHTMLPassedProps { /** * Replace the default error if a remote website's content could not be fetched. */ remoteErrorView?: (source: HTMLSourceUri) => ReactElement; /** * Replace the default loader while fetching a remote website's content. */ remoteLoadingView?: (source: HTMLSourceUri) => ReactElement; /** * Your custom renderers. * * @remarks * * **TypeScript users**: To have intellisense for custom renderers, explicitly * set your custom renderer type to one of {@link CustomBlockRenderer}, * {@link CustomTextualRenderer} or {@link CustomMixedRenderer} depending * on the {@link HTMLContentModel} defined for this tag (see example below). * * @example * * A custom renderer for `<div>` tags which trigger an alert on press. * * ```tsx * import React from 'react'; * import RenderHTML, { CustomBlockRenderer } from 'react-native-render-html'; * import { Alert } from 'react-native'; * * const onPress = () => Alert.alert("I pressed a div!"); * * // (TypeScript) Notice the type for intellisense * const DivRenderer: CustomBlockRenderer = function DivRenderer({ TDefaultRenderer, ...props }) { * return <TDefaultRenderer {...props} onPress={onPress} />; * } * * const renderers = { div: DivRenderer } * * // * * return <RenderHTML renderers={renderers} /> * ``` */ renderers?: CustomTagRendererRecord; } /** * Props for the {@link RenderHTMLSource} component. * * @public */ export interface RenderHTMLSourceProps { /** * The width of the HTML content to display. The recommended practice is to pass * `useWindowDimensions().width` minus any padding or margins. * * @defaultValue `Dimensions.get('window').width` */ contentWidth?: number; /** * Handler invoked when the document metadata is available. It will * re-trigger on HTML content changes. */ onDocumentMetadataLoaded?: (documentMetadata: DocumentMetadata) => void; /** * Triggered when HTML is available to the RenderHTML component. */ onHTMLLoaded?: (html: string) => void; /** * Triggered when the transient render tree changes. Useful for debugging. */ onTTreeChange?: (ttree: TDocument) => void; /** * The object source to render (either `{ uri }`, `{ html }` or `{ dom }`). */ source: HTMLSource; } /** * Props for the {@link RenderHTML} component. * * @public */ export interface RenderHTMLProps extends RenderHTMLConfig, RenderHTMLSourceProps, TRenderEngineConfig {} /** * An object which keys are keyword font names, and values system fonts. * * @public */ export interface FallbackFontsDefinitions { monospace: string; 'sans-serif': string; serif: string; } /** * Props passed from parents to children. * * * @remarks Anonymous nodes will pass those props from their parents to * children. * */ export interface PropsFromParent extends Record<string, any> { collapsedMarginTop: number | null; } /** * Props to render a child. * * @public */ export interface TChildProps { /** * The child element. */ childElement: ReactElement; /** * The child associated {@link TNode}. */ childTnode: TNode; /** * The position relative to parent. */ index: number; /** * The React `key`. */ key: string | number; /** * Props that have been set via * {@link TChildrenRendererProps.propsForChildren}. */ propsFromParent: PropsFromParent; } /** * Common props for TChildren rendering logic. * * @public */ export interface TChildrenBaseProps { /** * When {@link RenderHTMLProps.enableExperimentalMarginCollapsing} is * enabled, this prop will be true by default. But you can opt-out when * rendering children. */ disableMarginCollapsing?: boolean; /** * Props that will be passed to children renderers via * {@link CustomRendererProps.propsFromParent}. */ propsForChildren?: Partial<PropsFromParent>; /** * A React render function to render and wrap individual children. */ renderChild?: (props: TChildProps) => ReactNode; } /** * Props for {@link TChildrenRenderer}. * * @public */ export interface TChildrenRendererProps extends TChildrenBaseProps { /** * An array of {@link TNode} to render. */ tchildren: ReadonlyArray<TNode>; } /** * Props for {@link TNodeChildrenRenderer}. * * @public */ export interface TNodeChildrenRendererProps extends TChildrenBaseProps { /** * The {@link TNode} from which children will be rendered. */ tnode: TNode; } /** * Props for {@link TNodeRenderer} component. * * @typeParam T - The concrete type of {@link TNode}. */ export interface TNodeRendererProps<T extends TNode> { /** * Props passed by direct parents. */ propsFromParent?: PropsFromParent; /** * The position of this React element relative to the parent React element, * starting at 0. * * @remarks Not to be confused with {@link TNodeShape.index}, which is * the position of the *TNode* before hoisting. The latter is much closer * to an intuitive understanding of the position of a DOM node in the DOM * tree. */ renderIndex: number; /** * The total number of elements children of this React element parent. */ renderLength: number; /** * The {@link TNode} to render. */ tnode: T; } /** * Abstract interface for renderers. * * @typeParam T - The concrete type of {@link TNode}. */ export interface RendererBaseProps<T extends TNode> extends TNodeRendererProps<T> { /** * Props passed to the underlying React Native element, either `Text` or * `View`. See also {@link RendererBaseProps.textProps} and * {@link RendererBaseProps.viewProps}. * * @remarks The `prop.style` property will have a greater specificity * than computed styles for this {@link TNode}. E.g. `style={[computedStyle, * nativeProps.style, viewProps.style]}`. * */ nativeProps?: StylessReactNativeProps & { style?: StyleProp<ViewStyle> }; /** * Any default renderer should be able to handle press. */ onPress?: (e: GestureResponderEvent) => void; /** * Props passed to the underlying `Text` element (`type` must be 'text'). See * also {@link RendererBaseProps.nativeProps} and * {@link RendererBaseProps.viewProps}. * * @remarks The `textProps.style` property will have a greater specificity than * computed styles for this {@link TNode}. E.g. `style={[computedStyle, * nativeProps.style, textProps.style]}`. */ textProps: TextProps; /** * Is the underlying component `Text` or `View`? */ type: 'text' | 'block'; /** * Props passed to the underlying `View` element (`type` must be 'view'). See * also {@link RendererBaseProps.nativeProps} and * {@link RendererBaseProps.textProps}. * * @remarks The `viewProps.style` property will have a greater specificity than * computed styles for this {@link TNode}. E.g. `style={[computedStyle, * nativeProps.style, viewProps.style]}`. */ viewProps: ViewProps; } /** * Props for {@link TDefaultRenderer}. * * @typeParam T - The concrete type of {@link TNode}. * @public */ export interface TDefaultRendererProps<T extends TNode> extends RendererBaseProps<T> { /** * When children is present, renderChildren will not be invoked. */ children?: ReactNode; /** * Props passed to children nodes. Those props are accessible from children * renderers as `propsFromParent` */ propsForChildren?: Partial<PropsFromParent>; /** * The style for this renderer will depend on the type of {@link TNode}. * You can check if a node is textual with `props.type === 'text'`. */ style: T extends TText | TPhrasing ? StyleProp<TextStyle> : StyleProp<ViewStyle>; } /** * Props for {@link InternalRenderer} components. * * @typeParam T - The concrete type of {@link TNode}. * @public */ export interface InternalRendererProps<T extends TNode> extends RendererBaseProps<T> { /** * Default renderer for this {@link TNode}. */ TDefaultRenderer: TDefaultRenderer<T>; /** * Props shared across the whole render tree. */ sharedProps: RenderHTMLAmbiantSharedProps; /** * Styles extracted with {@link TNode.getNativeStyles}. */ style: T extends TText | TPhrasing ? NativeTextStyles : NativeBlockStyles; } /** * Props for custom renderers, such as provided in the `renderers` prop. * * @typeParam T - The concrete type of {@link TNode}. * @public */ export interface CustomRendererProps<T extends TNode> extends InternalRendererProps<T> { /** * Internal renderer for this _tagName_, not to be confused with * {@link TDefaultRenderer}, which is the fallback renderer for any {@link TNode}. * * @remarks For example, when rendering `img` tags, `TDefaultRenderer` and * `InternalRenderer` won't be equal. * * When there is no internal renderer for this tag, this prop will fallback * to `TDefaultRenderer`. */ InternalRenderer: InternalRenderer<T>; } /** * Default renderer for any {@link TNode}. The renderer behavior will only * change given the {@link TNodeType | type} of the {@link TNode}. * * @typeParam T - The concrete type of {@link TNode}. * @public */ export type TDefaultRenderer<T extends TNode> = ComponentType< TDefaultRendererProps<T> >; /** * An "internal renderer" is an internal custom renderer, adding specific * features to the fallback `TDefaultRenderer`. For example, `<img/>` tags will * be rendered via an internal renderer, while `<div>` will fallback to a * {@link TDefaultRenderer}. * * @public * * @typeParam T - The concrete type of {@link TNode}. */ export type InternalRenderer<T extends TNode> = ComponentType< InternalRendererProps<T> >; /** * A custom renderer, such as provided in the {@link RenderHTMLProps.renderers} prop. * * @typeParam T - The concrete type of {@link TNode}. * @public */ export type CustomRenderer<T extends TNode> = ComponentType< CustomRendererProps<T> >; /** * An object containing meta-data extracted from resource URL and HTML * `<head>` element. * * @public */ export interface DocumentMetadata { /** * How anchors should be actioned on press? * * @remarks By default, `renderersProps.a.onPress` will always open the * system browser, equivalent to `_blank` target. However, you can customize * the behavior by providing your own implementation. */ baseTarget: TREDocumentContext['baseTarget']; /** * The base URL of this resource. It will influence how relative URLs are * resolved such as `href` and `src` element properties. By order of * precedence: * * 1. `baseUrl` from `<base/>` html element; * 2. `baseUrl` from `source.baseUrl` prop; * 3. `baseUrl` as origin of `source.uri` prop. */ baseUrl: string; /** * The writing direction of this document, extracted from the `dir` attribute * of `<html/>` element. */ dir: 'ltr' | 'rtl'; /** * The language of this document, extracted from the `lang` attribute of the * `<html/>` element; */ lang: string; /** * A data array comprised of attributes from &lt;link&gt; elements. */ links: TREDocumentContext['links']; /** * A data array comprised of attributes from &lt;meta&gt; elements. */ meta: TREDocumentContext['meta']; /** * The content of the &lt;title&gt; element. */ title: string; } /** * Props for unitary counter renderers. * * @public */ export type UnitaryCounterRendererProps = { color: string; fontSize: number; index: number; lineHeight: number; } & Pick< MixedStyleDeclaration, 'fontFamily' | 'fontStyle' | 'fontWeight' | 'fontVariant' >; /** * List style types supported internally. * * See {@link https://www.w3.org/TR/css-counter-styles-3 | CSS Counter Styles Level 3}. * * @public */ export type DefaultSupportedListStyleType = | 'none' | 'disc' | 'circle' | 'square' | 'decimal' | 'decimal-leading-zero' | 'lower-roman' | 'upper-roman' | 'lower-greek' | 'lower-alpha' | 'lower-latin' | 'upper-alpha' | 'upper-latin' | 'disclosure-open' | 'disclosure-closed'; /** * Specs for a list item marker renderer backed by a `CounterStyleRenderer` * from `@jsamr/counter-style`. * * @public */ export interface TextualListStyleSpec { counterStyleRenderer: CounterStyleRenderer; type: 'textual'; } /** * Specs for a list item marker renderer with only one representation. The * "Component" should render this representation, minus prefix and suffix. The * rendered component should have a maximum width of `0.6 * fontSize`, and a height of * `lineHeight`. * * @public */ export interface UnitaryListStyleSpec { Component: ComponentType<UnitaryCounterRendererProps>; counterStyleRenderer: CounterStyleRenderer; type: 'unitary'; } /** * An object to specify how to render list markers. * * @public */ export type ListStyleSpec = TextualListStyleSpec | UnitaryListStyleSpec;
the_stack
import { BlockAtom, getPx, INodeInfo, SylApi, SylController, SylPlugin } from '@syllepsis/adapter'; import { DOMOutputSpecArray, Node, Node as ProsemirrorNode } from 'prosemirror-model'; import { NodeSelection, TextSelection } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; import { addAttrsByConfig, createFileInput, getFixSize, getFromDOMByConfig, isMatchObject, isObjectURL, setDOMAttrByConfig, } from '../../utils'; import { ImageAttrs, ImageProps, IUpdateImageProps, TUploadDataType } from './types'; import { checkDomain, constructAttrs, correctSize, getImageFileList, getInputImageFiles, transformBlobFromObjectURL, } from './utils'; const PLUGIN_NAME = 'image'; let maxWidth = window.innerWidth - 40; const BASE_CONFIG: ImageProps = { uploader: () => Promise.resolve(''), uploadBeforeInsert: false, placeholder: '', uploadType: 'blob' as const, listenDrop: true, listenPaste: true, maxLength: 20, uploadMaxWidth: 375, }; // parse the DOM of image which generated by the the ImagePlugin const parseSylDOM = ( dom: HTMLElement, fixClass: string, captionClass: string, addAttributes?: ImageProps['addAttributes'], ) => { const image = (dom.querySelector('img') as HTMLImageElement) || null; const caption = dom.querySelector(captionClass) as HTMLInputElement | HTMLParagraphElement | null; const fixer = dom.querySelector(fixClass); const alt = (caption && (caption.innerText || (caption as HTMLInputElement).value)) || ''; const src = (image && image.src) || ''; const width = image.width; const height = image.height; const name = image.getAttribute('name') || ''; let align: ImageAttrs['align'] = dom.getAttribute('align') as ImageAttrs['align']; if (!align && fixer) { const className = fixer.className; if (className.includes('left')) align = 'left'; else if (className.includes('right')) align = 'right'; } const attrs: ImageAttrs = { src, alt, width, height, align, name }; addAttributes && getFromDOMByConfig(addAttributes, dom, attrs); return attrs; }; const uploadImg = async (editor: SylApi, src: string, fileName: string, config: ImageProps) => { let res: TUploadDataType = src; const { uploader, uploadType, onUploadError, deleteFailedUpload } = config; if (!uploader) throw new Error('Must provide uploader!'); if (isObjectURL(src)) res = await transformBlobFromObjectURL(src); if (typeof res !== 'string' && uploadType === 'file') { res = new File([res as Blob], fileName, { type: res?.type }); } try { const uploadRes = await uploader(res, { src, }); if (typeof uploadRes === 'string') return { src: uploadRes || src }; return { src, ...uploadRes }; } catch (err) { if (deleteFailedUpload) { const nodeInfos = editor.getExistNodes(PLUGIN_NAME); nodeInfos.some(({ node, pos }) => { if (node.attrs.src === src) { editor.deleteCard(pos); return true; } }); } if (onUploadError) onUploadError(res, err); else throw err; } }; const insertImageInEditor = ( editor: SylApi, dataInfos: { image?: HTMLImageElement; attrs?: { src: string; [key: string]: any } }[], config: Partial<ImageProps>, ) => { const pos = editor.view.state.selection.from; const $pos = editor.view.state.doc.resolve(pos); const images = [...dataInfos]; const insertNodes = { type: 'doc', content: [] as INodeInfo[] }; // when depth >= 2 and contained in table, inserting images will not update the selection,causes it to be inserted in reverse order const isInTable = $pos.node(1)?.type?.name === 'table' && $pos.depth >= 2; if(isInTable){ images.reverse(); } images.forEach(({ image, attrs }) => { if (!image || !attrs) return; const imageAttrs: Partial<ImageAttrs> = { width: config.uploadMaxWidth ? Math.min(image.naturalWidth, config.uploadMaxWidth) : image.naturalWidth, name: image.getAttribute('name') || '', alt: '', align: 'center', ...attrs, }; if(isInTable) { editor.insert({ type: PLUGIN_NAME, attrs: imageAttrs }); } else { insertNodes.content.push({ type: PLUGIN_NAME, attrs: imageAttrs }); } }); if (insertNodes.content.length && !isInTable) editor.insert(insertNodes, pos); }; // get the picture file and judge whether to upload it in advance const insertImageWithFiles = async (editor: SylApi, files: File[], config: Partial<ImageProps>) => { const results = await Promise.all( files.map( f => new Promise(resolve => { const url = window.URL.createObjectURL(f); let attrs: undefined | { src: string } = { src: url }; const image = document.createElement('img'); image.onload = async () => { if (config.uploadBeforeInsert) { const uploadRes = await uploadImg(editor, url, f.name, config); if (!uploadRes) resolve({}); else attrs = { ...attrs, ...uploadRes }; } resolve({ attrs, image }); }; image.onerror = async e => { const { onUploadError } = config; onUploadError && onUploadError(f, e as Event); resolve({}); }; image.src = attrs.src; image.setAttribute('name', f.name); }) as Promise<{ image?: HTMLImageElement; attrs?: { src: string } }>, ), ); insertImageInEditor(editor, results, config); }; const updateImageUrl = async (editor: SylApi, props: IUpdateImageProps, config: ImageProps) => { maxWidth = editor.view.dom.scrollWidth - 40; const { src, name } = props.attrs; if (props.state === undefined) props.state = {}; const state = props.state; let imageAttrs: Partial<ImageAttrs> = {}; try { // upload state, only single upload request is allowed in the same instance at the same time if (state.uploading || (!isObjectURL(src) && checkDomain(src, config))) { imageAttrs = await correctSize(props.attrs); } else { state.uploading = true; const attrs = await uploadImg(editor, src, name, config); state.uploading = false; if (!attrs) return; imageAttrs = await constructAttrs(props.attrs, attrs); } const $pos = editor.view.state.doc.resolve(props.getPos()); const curNode = $pos.nodeAfter; // confirm the image node exist if (!curNode || curNode.type.name !== PLUGIN_NAME || curNode.attrs.src !== src) return; if (!isMatchObject(imageAttrs, props.attrs)) editor.updateCardAttrs($pos.pos, imageAttrs); } finally { state.uploading = false; } }; const createImageFileInput = (editor: SylApi, config: ImageProps) => { const input = createFileInput({ multiple: true, accept: config.accept || 'image/*', onChange: (e: Event) => { const files = getInputImageFiles(e); insertImageWithFiles(editor, files, config); }, getContainer: () => editor.root, }); return input; }; class ImageController extends SylController<ImageProps> { public fileInput: HTMLInputElement; public toolbar = { className: 'image', tooltip: 'image', icon: '' as any, handler: () => this.fileInput.click(), }; constructor(editor: SylApi, props: ImageProps) { super(editor, props); if (Object.keys(props).length) this.props = { ...BASE_CONFIG, ...props }; this.fileInput = createImageFileInput(editor, this.props); editor.root.appendChild(this.fileInput); } public command = { insertImages: (editor: SylApi, files: File[]) => insertImageWithFiles(editor, files, this.props), updateImageUrl: (editor: SylApi, props: IUpdateImageProps) => updateImageUrl(editor, props, this.props), getConfiguration: () => this.props, }; public eventHandler = { handleClickOn( editor: SylApi, view: EditorView, pos: number, node: ProsemirrorNode, nodePos: number, event: MouseEvent, ) { if (node.type.name === PLUGIN_NAME) { const caption = (event.target as HTMLElement).closest('input'); if (caption) { if (caption) caption.focus(); const newTextSelection = TextSelection.create(view.state.doc, nodePos); view.dispatch(view.state.tr.setSelection(newTextSelection)); return true; } // when the currently selected image is a picture, but the system behaves as a cursor, correct the selection.(real is 'Range') const { state, dispatch } = view; const curSelection = window.getSelection(); if (curSelection && curSelection.type === 'Caret') { dispatch(state.tr.setSelection(NodeSelection.create(view.state.doc, nodePos))); return true; } return false; } return false; }, handlePaste: (editor: SylApi, view: EditorView, e: Event) => { const event = e as ClipboardEvent; if ((this.props && !this.props.listenPaste) || !event.clipboardData) { return false; } const files = getImageFileList(event.clipboardData.files); if (!files.length || event.clipboardData.getData('text/html')) { return false; } editor.command.image!.insertImages(files); return true; }, handleDOMEvents: { drop: (editor: SylApi, view: EditorView, e: Event) => { const event = e as DragEvent; if (view.dragging || (this.props && !this.props.listenDrop) || !event.dataTransfer) { return false; } const files: File[] = getImageFileList(event.dataTransfer.files); if (!files.length) return false; editor.command.image!.insertImages(files); e.preventDefault(); return true; }, }, }; public editorWillUnmount = () => { this.editor.root.removeChild(this.fileInput); }; } class Image extends BlockAtom<ImageAttrs> { public props: ImageProps; public name = PLUGIN_NAME; public traceSelection = false; constructor(editor: SylApi, props: ImageProps) { super(editor, props); addAttrsByConfig(props.addAttributes, this); this.props = props; const { align, alt, ...rest } = this.attrs; // @ts-ignore this.attrs = { ...rest }; if (!this.props.disableAlign) this.attrs.align = align; if (!this.props.disableCaption) this.attrs.alt = alt; } public parseDOM = [ { tag: 'div.syl-image-wrapper', getAttrs: (dom: HTMLElement) => parseSylDOM(dom, '.syl-image-fixer', '.syl-image-caption', this.props.addAttributes), }, { tag: 'img', getAttrs: (dom: HTMLImageElement) => { if (!dom.src) return false; const attrWidth = dom.getAttribute('width'); const attrHeight = dom.getAttribute('height'); let width = getPx(dom.style.width || (attrWidth && `${attrWidth}px`) || '', 16); let height = getPx(dom.style.height || (attrHeight && `${attrHeight}px`) || '', 16); if (!width || isNaN(width)) width = 0; if (!height || isNaN(height)) height = 0; if (width > maxWidth) { if (height) height = height / (width / maxWidth); width = maxWidth; } const formattedAttrs = { src: dom.getAttribute('src') || '', alt: dom.getAttribute('alt') || '', name: dom.getAttribute('name') || '', align: (dom.getAttribute('align') || 'center') as any, width, height, }; getFromDOMByConfig(this.props.addAttributes, dom, formattedAttrs); return formattedAttrs; }, }, ]; public toDOM = (node: Node) => { const { align, width, height, ...attrs } = node.attrs; setDOMAttrByConfig(this.props.addAttributes, node, attrs); if (width) attrs.width = getFixSize(width); if (height) attrs.height = getFixSize(height); const renderSpec = ['img', attrs] as DOMOutputSpecArray; if (this.inline) return renderSpec; const alignAttrs = this.props.disableAlign ? {} : { align: align || 'center' }; return [ 'div', { class: 'syl-image-wrapper', ...alignAttrs }, renderSpec, attrs.alt && ['p', { class: 'syl-image-caption' }, attrs.alt], ] as DOMOutputSpecArray; }; public attrs = { src: { default: '', }, alt: { default: '', }, name: { default: '', }, width: { default: 0, }, height: { default: 0, }, align: { default: 'center' as const, }, }; } class ImagePlugin extends SylPlugin<ImageProps> { public name = PLUGIN_NAME; public Controller = ImageController; public Schema = Image; } export { Image, ImageAttrs, ImageController, ImagePlugin, ImageProps };
the_stack
import { Id64String, Logger } from "@itwin/core-bentley"; import { AngleSweep, Arc3d, Point2d, Point3d, Transform, XAndY, XYAndZ } from "@itwin/core-geometry"; import { AxisAlignedBox3d, ColorByName, ColorDef, NpcCenter } from "@itwin/core-common"; import { BeButton, BeButtonEvent, Cluster, DecorateContext, Decorator, GraphicBranch, GraphicType, HitDetail, imageElementFromUrl, IModelApp, IModelConnection, Marker, MarkerImage, MarkerSet, MessageBoxIconType, MessageBoxType, readGltfGraphics, RenderGraphic, } from "@itwin/core-frontend"; // cSpell:ignore lerp export class ExampleGraphicDecoration { // __PUBLISH_EXTRACT_START__ View_Graphic_Decoration /** Add a world decoration to display 3d graphics showing the project extents interspersed with the scene graphics. */ public decorate(context: DecorateContext): void { // Check view type, project extents is only applicable to show in spatial views. const vp = context.viewport; if (!vp.view.isSpatialView()) return; const builder = context.createGraphicBuilder(GraphicType.WorldDecoration, undefined); // Set edge color to white or black depending on current view background color and set line weight to 2. builder.setSymbology(vp.getContrastToBackgroundColor(), ColorDef.black, 2); // Add range box edge geometry to builder. builder.addRangeBox(vp.iModel.projectExtents); context.addDecorationFromBuilder(builder); } // __PUBLISH_EXTRACT_END__ } export class ExamplePickableGraphicDecoration { // __PUBLISH_EXTRACT_START__ Pickable_View_Graphic_Decoration protected _decoId?: string; /** Add a pickable decoration that will display interspersed with the scene graphics. */ public decorate(context: DecorateContext): void { const vp = context.viewport; if (!vp.view.isSpatialView()) return; // Get next available Id to represent our decoration for it's life span. if (undefined === this._decoId) this._decoId = vp.iModel.transientIds.next; const builder = context.createGraphicBuilder(GraphicType.WorldDecoration, undefined, this._decoId); builder.setSymbology(vp.getContrastToBackgroundColor(), ColorDef.black, 2); builder.addRangeBox(vp.iModel.projectExtents); context.addDecorationFromBuilder(builder); } /** Return true if supplied Id represents a pickable decoration created by this decorator. */ public testDecorationHit(id: string): boolean { return id === this._decoId; } /** Return localized tooltip message for the decoration identified by HitDetail.sourceId. */ public async getDecorationToolTip(_hit: HitDetail): Promise<HTMLElement | string> { return "Project Extents"; } // __PUBLISH_EXTRACT_END__ } export class ExampleCanvasDecoration { // __PUBLISH_EXTRACT_START__ Canvas_Decoration /** Add a canvas decoration using CanvasRenderingContext2D to show a plus symbol. */ public decorate(context: DecorateContext): void { const vp = context.viewport; const size = Math.floor(vp.pixelsPerInch * 0.25) + 0.5; const sizeOutline = size + 1; const position = context.viewport.npcToView(NpcCenter); position.x = Math.floor(position.x) + 0.5; position.y = Math.floor(position.y) + 0.5; const drawDecoration = (ctx: CanvasRenderingContext2D) => { // Show black outline (with shadow) around white line for good visibility regardless of view background color. ctx.beginPath(); ctx.strokeStyle = "rgba(0,0,0,.5)"; ctx.lineWidth = 3; ctx.moveTo(-sizeOutline, 0); ctx.lineTo(sizeOutline, 0); ctx.moveTo(0, -sizeOutline); ctx.lineTo(0, sizeOutline); ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = "white"; ctx.lineWidth = 1; ctx.shadowColor = "black"; ctx.shadowBlur = 5; ctx.moveTo(-size, 0); ctx.lineTo(size, 0); ctx.moveTo(0, -size); ctx.lineTo(0, size); ctx.stroke(); }; context.addCanvasDecoration({ position, drawDecoration }); } // __PUBLISH_EXTRACT_END__ } // __PUBLISH_EXTRACT_START__ MarkerSet_Decoration /** Example Marker to show an *incident*. Each incident has an *id*, a *severity*, and an *icon*. */ class IncidentMarker extends Marker { private static _size = Point2d.create(30, 30); private static _imageSize = Point2d.create(40, 40); private static _imageOffset = Point2d.create(0, 30); private static _amber = ColorDef.create(ColorByName.amber); private static _sweep360 = AngleSweep.create360(); private _color: ColorDef; // uncomment the next line to make the icon only show when the cursor is over an incident marker. // public get wantImage() { return this._isHilited; } /** Get a color based on severity by interpolating Green(0) -> Amber(15) -> Red(30) */ public static makeColor(severity: number): ColorDef { return (severity <= 16 ? ColorDef.green.lerp(this._amber, (severity - 1) / 15.) : this._amber.lerp(ColorDef.red, (severity - 16) / 14.)); } public override onMouseButton(ev: BeButtonEvent): boolean { if (ev.button === BeButton.Data) { if (ev.isDown) { IModelApp.notifications.openMessageBox(MessageBoxType.LargeOk, `severity = ${this.severity}`, MessageBoxIconType.Information); // eslint-disable-line @typescript-eslint/no-floating-promises } } return true; } /** Create a new IncidentMarker */ constructor(location: XYAndZ, public severity: number, public id: number, icon: HTMLImageElement) { super(location, IncidentMarker._size); this._color = IncidentMarker.makeColor(severity); // color interpolated from severity this.setImage(icon); // save icon this.imageOffset = IncidentMarker._imageOffset; // move icon up by 30 pixels this.imageSize = IncidentMarker._imageSize; // 40x40 this.title = `Severity: ${severity}<br>Id: ${id}`; // tooltip this.setScaleFactor({ low: .2, high: 1.4 }); // make size 20% at back of frustum and 140% at front of frustum (if camera is on) // it would be better to use "this.label" here for a pure text string. We'll do it this way just to show that you can use HTML too this.htmlElement = document.createElement("div"); this.htmlElement.innerHTML = id.toString(); // just put the id of the incident as text } public override addMarker(context: DecorateContext) { super.addMarker(context); const builder = context.createGraphicBuilder(GraphicType.WorldDecoration); const ellipse = Arc3d.createScaledXYColumns(this.worldLocation, context.viewport.rotation.transpose(), .2, .2, IncidentMarker._sweep360); builder.setSymbology(ColorDef.white, this._color, 1); builder.addArc(ellipse, false, false); builder.setBlankingFill(this._color); builder.addArc(ellipse, true, true); context.addDecorationFromBuilder(builder); } } /** A Marker used to show a cluster of incidents */ class IncidentClusterMarker extends Marker { private _clusterColor: string; // public get wantImage() { return this._isHilited; } // draw the cluster as a white circle with an outline color based on what's in the cluster public override drawFunc(ctx: CanvasRenderingContext2D) { ctx.beginPath(); ctx.strokeStyle = this._clusterColor; ctx.fillStyle = "white"; ctx.lineWidth = 5; ctx.arc(0, 0, 13, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); } /** Create a new cluster marker with label and color based on the content of the cluster */ constructor(location: XYAndZ, size: XAndY, cluster: Cluster<IncidentMarker>, image: Promise<MarkerImage> | MarkerImage | undefined) { super(location, size); // get the top 10 incidents by severity const sorted: IncidentMarker[] = []; const maxLen = 10; cluster.markers.forEach((marker) => { if (maxLen > sorted.length || marker.severity > sorted[sorted.length - 1].severity) { const index = sorted.findIndex((val) => val.severity < marker.severity); if (index === -1) sorted.push(marker); else sorted.splice(index, 0, marker); if (sorted.length > maxLen) sorted.length = maxLen; } }); this.imageOffset = new Point3d(0, 28); this.imageSize = new Point2d(30, 30); this.label = cluster.markers.length.toLocaleString(); this.labelColor = "black"; this.labelFont = "bold 14px sans-serif"; let title = ""; sorted.forEach((marker) => { if (title !== "") title += "<br>"; title += `Severity: ${marker.severity} Id: ${marker.id}`; }); if (cluster.markers.length > maxLen) title += "<br>..."; this.title = title; this._clusterColor = IncidentMarker.makeColor(sorted[0].severity).toHexString(); if (image) this.setImage(image); } } /** A MarkerSet to hold incidents. This class supplies to `getClusterMarker` method to create IncidentClusterMarkers. */ class IncidentMarkerSet extends MarkerSet<IncidentMarker> { protected getClusterMarker(cluster: Cluster<IncidentMarker>): Marker { return new IncidentClusterMarker(cluster.getClusterLocation(), cluster.markers[0].size, cluster, IncidentMarkerDemo.decorator!.warningSign); } } /** This demo shows how to use MarkerSets to cluster markers that overlap on the screen. It creates a set of 500 * "incidents" at random locations within the ProjectExtents. For each incident, it creates an IncidentMarker with an Id and * with a random value between 1-30 for "severity", and one of 5 possible icons. */ export class IncidentMarkerDemo { private _awaiting = false; private _loading?: Promise<any>; private _images: Array<HTMLImageElement | undefined> = []; private _incidents = new IncidentMarkerSet(); private static _numMarkers = 500; public static decorator?: IncidentMarkerDemo; // static variable so we can tell if the demo is active. public get warningSign() { return this._images[0]; } // Load one image, logging if there was an error private async loadOne(src: string) { try { return await imageElementFromUrl(src); // note: "return await" is necessary inside try/catch } catch (err) { const msg = `Could not load image ${src}`; Logger.logError("IncidentDemo", msg); console.log(msg); // eslint-disable-line no-console } return undefined; } // load all images. After they're loaded, make the incident markers private async loadAll(extents: AxisAlignedBox3d) { const loads = [ this.loadOne("Warning_sign.svg"), // must be first, see "get warningSign()" above this.loadOne("Hazard_biological.svg"), this.loadOne("Hazard_electric.svg"), this.loadOne("Hazard_flammable.svg"), this.loadOne("Hazard_toxic.svg"), this.loadOne("Hazard_tripping.svg"), ]; await (this._loading = Promise.all(loads)); // this is a member so we can tell if we're still loading for (const img of loads) this._images.push(await img); const len = this._images.length; const pos = new Point3d(); for (let i = 0; i < IncidentMarkerDemo._numMarkers; ++i) { pos.x = extents.low.x + (Math.random() * extents.xLength()); pos.y = extents.low.y + (Math.random() * extents.yLength()); pos.z = extents.low.z + (Math.random() * extents.zLength()); const img = this._images[(i % len) + 1]; if (undefined !== img) this._incidents.markers.add(new IncidentMarker(pos, 1 + Math.round(Math.random() * 29), i, img)); } this._loading = undefined; } public constructor(extents: AxisAlignedBox3d) { this.loadAll(extents); // eslint-disable-line @typescript-eslint/no-floating-promises } /** We added this class as a ViewManager.decorator below. This method is called to ask for our decorations. We add the MarkerSet. */ public decorate(context: DecorateContext) { if (!context.viewport.view.isSpatialView()) return; if (undefined === this._loading) { this._incidents.addDecoration(context); return; } // if we're still loading, just mark this viewport as needing decorations when all loads are complete if (!this._awaiting) { this._awaiting = true; this._loading.then(() => { context.viewport.invalidateDecorations(); this._awaiting = false; }).catch(() => undefined); } } /** Turn the markers on and off. Each time it runs it creates a new random set of incidents. */ public static toggle(extents: AxisAlignedBox3d) { if (undefined === IncidentMarkerDemo.decorator) { // start the demo by creating the IncidentMarkerDemo object and adding it as a ViewManager decorator. IncidentMarkerDemo.decorator = new IncidentMarkerDemo(extents); IModelApp.viewManager.addDecorator(IncidentMarkerDemo.decorator); } else { // stop the demo IModelApp.viewManager.dropDecorator(IncidentMarkerDemo.decorator); IncidentMarkerDemo.decorator = undefined; } } } // __PUBLISH_EXTRACT_END__ // __PUBLISH_EXTRACT_START__ Application_LogoCard IModelApp.applicationLogoCard = () => { return IModelApp.makeLogoCard({ iconSrc: "MyApp.png", heading: "My Great Application", notice: "Example Application<br>Version 2.0" }); }; // __PUBLISH_EXTRACT_END__ // __PUBLISH_EXTRACT_START__ Gltf_Decoration /** A view decoration that draws a graphic created from a glTF asset. */ class GltfDecoration implements Decorator { /** A graphic created from a glTF asset. */ private readonly _graphic: RenderGraphic; /** The tooltip to be displayed when the graphic is moused-over. */ private readonly _tooltip: string; /** The Id of the graphic used for picking. */ private readonly _pickableId: Id64String; public constructor(graphic: RenderGraphic, tooltip: string, pickableId: Id64String) { this._graphic = graphic; this._tooltip = tooltip; this._pickableId = pickableId; } /** Tell the display system not to recreate our graphics every time the mouse cursor moves. */ public readonly useCachedDecorations = true; /** Draw our graphics into the viewport. */ public decorate(context: DecorateContext): void { // Our graphics are defined in spatial coordinates so should only be drawn in a spatial view if (context.viewport.view.isSpatialView()) { // Produce a "scene" graphic so that it will be affected by lighting and other aspects of the viewport's display style. context.addDecoration(GraphicType.Scene, this._graphic); } } /** Return true if the specified Id matches our graphic's pickable Id. */ public testDecorationHit(id: string): boolean { return id === this._pickableId; } /** Provide a tooltip when our graphic is moused-over. */ public async getDecorationToolTip(): Promise<string> { return this._tooltip; } } /** Open a file picker to allow the user to select a .gltf or .glb file describing a glTF asset, convert the asset into a RenderGraphic, * then install a Decorator to display the graphic in the center of the project extents. * @param iModel The iModel with which the graphic will be associated. Any viewports viewing a spatial view of this iModel will be decorated with the glTF asset. * @returns true if the graphic was successfully created. */ export async function displayGltfAsset(iModel: IModelConnection): Promise<boolean> { // Allow the user to select the glTF asset. try { // We need to cast `window` to `any` because the TypeScript type definition doesn't expose the `showOpenFilePicker` function. const [handle] = await (window as any).showOpenFilePicker({ types: [ { description: "glTF", accept: { "model/*": [".gltf", ".glb"] }, }, ], }); // Read the file's contents into memory. const file = await handle.getFile(); const buffer = await file.arrayBuffer(); // Allocate a new transient Id to identify the graphic so it can be picked. const id = iModel.transientIds.next; // Convert the glTF into a RenderGraphic. let graphic = await readGltfGraphics({ gltf: new Uint8Array(buffer), iModel, pickableOptions: { id }, }); if (!graphic) return false; // Transform the graphic to the center of the project extents. const transform = Transform.createTranslation(iModel.projectExtents.center); const branch = new GraphicBranch(); branch.add(graphic); graphic = IModelApp.renderSystem.createGraphicBranch(branch, transform); // Take ownership of the graphic so that it is not disposed of until we're finished with it. // By doing so we take responsibility for disposing of it ourselves. const owner = IModelApp.renderSystem.createGraphicOwner(graphic); // Install the decorator, using the file name as the tooltip. const decorator = new GltfDecoration(owner, file.name, id); IModelApp.viewManager.addDecorator(decorator); // When the iModel is closed, dispose of the graphic and uninstall the decorator. iModel.onClose.addOnce(() => { owner.disposeGraphic(); IModelApp.viewManager.dropDecorator(decorator); }); return true; } catch (_) { return false; } } // __PUBLISH_EXTRACT_END__
the_stack
import * as React from 'react'; import { Collapse, Form } from 'antd'; import { Symbolizer, FillSymbolizer, PointSymbolizer, GraphicType } from 'geostyler-style'; import ColorField from '../Field/ColorField/ColorField'; import OpacityField from '../Field/OpacityField/OpacityField'; import GraphicEditor from '../GraphicEditor/GraphicEditor'; import WidthField from '../Field/WidthField/WidthField'; import _cloneDeep from 'lodash/cloneDeep'; import _get from 'lodash/get'; import _isEqual from 'lodash/isEqual'; import { localize } from '../../LocaleWrapper/LocaleWrapper'; import en_US from '../../../locale/en_US'; import LineDashField from '../Field/LineDashField/LineDashField'; import { CompositionContext, Compositions } from '../../../context/CompositionContext/CompositionContext'; import CompositionUtil from '../../../Util/CompositionUtil'; import withDefaultsContext from '../../../hoc/withDefaultsContext'; import { DefaultValues } from '../../../context/DefaultValueContext/DefaultValueContext'; const Panel = Collapse.Panel; // i18n export interface FillEditorLocale { fillOpacityLabel?: string; fillColorLabel?: string; outlineColorLabel?: string; outlineWidthLabel?: string; graphicFillTypeLabel?: string; outlineDasharrayLabel?: string; opacityLabel?: string; outlineOpacityLabel?: string; } interface FillEditorDefaultProps { locale: FillEditorLocale; } // non default props export interface FillEditorProps extends Partial<FillEditorDefaultProps> { symbolizer: FillSymbolizer; onSymbolizerChange?: (changedSymb: Symbolizer) => void; defaultValues: DefaultValues; } export class FillEditor extends React.Component<FillEditorProps> { static componentName: string = 'FillEditor'; public static defaultProps: FillEditorDefaultProps = { locale: en_US.GsFillEditor }; public shouldComponentUpdate(nextProps: FillEditorProps): boolean { const diffProps = !_isEqual(this.props, nextProps); return diffProps; } onFillColorChange = (value: string) => { const { onSymbolizerChange } = this.props; const symbolizer: FillSymbolizer = _cloneDeep(this.props.symbolizer); symbolizer.color = value; if (onSymbolizerChange) { onSymbolizerChange(symbolizer); } }; onFillOpacityChange = (value: number) => { const { onSymbolizerChange } = this.props; const symbolizer: FillSymbolizer = _cloneDeep(this.props.symbolizer); symbolizer.fillOpacity = value; if (onSymbolizerChange) { onSymbolizerChange(symbolizer); } }; onOpacityChange = (value: number) => { const { onSymbolizerChange } = this.props; const symbolizer: FillSymbolizer = _cloneDeep(this.props.symbolizer); symbolizer.opacity = value; if (onSymbolizerChange) { onSymbolizerChange(symbolizer); } }; onOutlineOpacityChange = (value: number) => { const { onSymbolizerChange } = this.props; const symbolizer: FillSymbolizer = _cloneDeep(this.props.symbolizer); symbolizer.outlineOpacity = value; if (onSymbolizerChange) { onSymbolizerChange(symbolizer); } }; onOutlineColorChange = (value: string) => { const { onSymbolizerChange } = this.props; const symbolizer: FillSymbolizer = _cloneDeep(this.props.symbolizer); symbolizer.outlineColor = value; if (onSymbolizerChange) { onSymbolizerChange(symbolizer); } }; onOutlineWidthChange = (value: number) => { const { onSymbolizerChange } = this.props; const symbolizer: FillSymbolizer = _cloneDeep(this.props.symbolizer); symbolizer.outlineWidth = value; if (onSymbolizerChange) { onSymbolizerChange(symbolizer); } }; onOutlineDasharrayChange = (value: number[]) => { const { onSymbolizerChange } = this.props; const symbolizer: FillSymbolizer = _cloneDeep(this.props.symbolizer); symbolizer.outlineDasharray = value; if (onSymbolizerChange) { onSymbolizerChange(symbolizer); } }; onGraphicChange = (gFill: PointSymbolizer) => { const { onSymbolizerChange } = this.props; const symbolizer: FillSymbolizer = _cloneDeep(this.props.symbolizer); symbolizer.graphicFill = gFill; if (onSymbolizerChange) { onSymbolizerChange(symbolizer); } }; /** * Wraps a Form Item around a given element and adds its locale * to the From Item label. */ wrapFormItem = (locale: string, element: React.ReactElement): React.ReactElement => { const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } }; return element == null ? null : ( <Form.Item label={locale} {...formItemLayout} > {element} </Form.Item> ); }; render() { const { symbolizer, locale, defaultValues } = this.props; const { color, fillOpacity, outlineColor, graphicFill, outlineWidth, outlineDasharray, opacity, outlineOpacity } = symbolizer; return ( <CompositionContext.Consumer> {(composition: Compositions) => ( <div className="gs-fill-symbolizer-editor" > <Collapse bordered={false} defaultActiveKey={['1']}> <Panel header="General" key="1"> { this.wrapFormItem( locale.fillColorLabel, CompositionUtil.handleComposition({ composition, path: 'FillEditor.fillColorField', onChange: this.onFillColorChange, propName: 'color', propValue: color, defaultValue: defaultValues?.FillEditor?.defaultFillColor, defaultElement: <ColorField /> }) ) } { this.wrapFormItem( locale.fillOpacityLabel, CompositionUtil.handleComposition({ composition, path: 'FillEditor.fillOpacityField', onChange: this.onFillOpacityChange, propName: 'opacity', propValue: fillOpacity, defaultValue: defaultValues?.FillEditor?.defaultFillOpacity, defaultElement: <OpacityField /> }) ) } { this.wrapFormItem( locale.opacityLabel, CompositionUtil.handleComposition({ composition, path: 'FillEditor.opacityField', onChange: this.onOpacityChange, propName: 'opacity', propValue: opacity, defaultValue: defaultValues?.FillEditor?.defaultOpacity, defaultElement: <OpacityField /> }) ) } { this.wrapFormItem( locale.outlineOpacityLabel, CompositionUtil.handleComposition({ composition, path: 'FillEditor.outlineOpacityField', onChange: this.onOutlineOpacityChange, propName: 'opacity', propValue: outlineOpacity, defaultValue: defaultValues?.FillEditor?.defaultOutlineOpacity, defaultElement: <OpacityField /> }) ) } { this.wrapFormItem( locale.outlineColorLabel, CompositionUtil.handleComposition({ composition, path: 'FillEditor.outlineColorField', onChange: this.onOutlineColorChange, propName: 'color', propValue: outlineColor, defaultValue: defaultValues?.FillEditor?.defaultOutlineColor, defaultElement: <ColorField /> }) ) } { this.wrapFormItem( locale.outlineWidthLabel, CompositionUtil.handleComposition({ composition, path: 'FillEditor.outlineWidthField', onChange: this.onOutlineWidthChange, propName: 'width', propValue: outlineWidth, defaultValue: defaultValues?.FillEditor?.defaultOutlineWidth, defaultElement: <WidthField /> }) ) } { this.wrapFormItem( locale.outlineDasharrayLabel, CompositionUtil.handleComposition({ composition, path: 'FillEditor.outlineDasharrayField', onChange: this.onOutlineDasharrayChange, propName: 'dashArray', propValue: outlineDasharray, defaultElement: <LineDashField /> }) ) } </Panel> <Panel header="Graphic Fill" key="2"> { CompositionUtil.handleComposition({ composition, path: 'FillEditor.graphicEditorField', onChange: this.onGraphicChange, onChangeName: 'onGraphicChange', propName: 'graphic', propValue: graphicFill, defaultElement: ( <GraphicEditor graphicTypeFieldLabel={locale.graphicFillTypeLabel} graphic={graphicFill} graphicType={_get(graphicFill, 'kind') as GraphicType} /> ) }) } </Panel> </Collapse> </div> )} </CompositionContext.Consumer> ); } } export default withDefaultsContext(localize(FillEditor, FillEditor.componentName));
the_stack
import { err, ERROR } from "../errors"; import { ManagedCoreEvent, ManagedEvent, ManagedParentChangeEvent, ManagedChangeEvent, CHANGE, } from "./ManagedEvent"; import type { ManagedReference } from "./ManagedReference"; import { observe } from "./observe"; import * as util from "./util"; import { HIDDEN } from "./util"; /** Alias for Object.prototype.hasOwnProperty */ const _hOP = Object.prototype.hasOwnProperty; /** Enumeration of possible states for a managed object */ export enum ManagedState { /** State for a managed object that has been destroyed */ DESTROYED = 0, /** State for a managed object that has just been created */ CREATED, /** State for a managed object that is activating asynchronously */ ACTIVATING, /** State for a managed object that is currently active */ ACTIVE, /** State for a managed object that is deactivating asynchronously */ DEACTIVATING, /** State for a managed object that is currently inactive */ INACTIVE, /** State for a managed object that is being destroyed asynchronously */ DESTROYING, } /** Number of free RefLink instances to keep around */ const MAX_FREE_REFLINKS = 1000; /** Stack of currently unused managed references, ready for reuse */ let _freeRefLinks: util.RefLink[] = []; for (let i = 0; i < MAX_FREE_REFLINKS >> 2; i++) { _freeRefLinks[i] = { u: 0, a: undefined, b: undefined, p: "", j: undefined, k: undefined, f: undefined, g: undefined, }; } /** Next UID to be assigned to a new managed object */ let _nextUID = 16; /** Next UID to be assigned to a property or managed reference instance */ let _nextRefId = 16; /** Maximum number of recursive event emissions allowed _per object_ */ const RECURSE_EMIT_LIMIT = 4; /** Generic constructor type for ManagedObject classes */ export type ManagedObjectConstructor<TObject extends ManagedObject = ManagedObject> = new ( ...args: never[] ) => TObject; /** Base class for objects that have their own unique ID, life cycle including active/inactive and destroyed states, and managed references to other instances */ export class ManagedObject { /** * Add an observer to _all instances_ of this class and derived classes. The observer class is instantiated for each instance of this (observed) class, and its methods are automatically called when an event or property change occurs on the observed instance. * Methods of the observer class may be decorated using `@onPropertyChange` or `@onPropertyEvent`, or method names may be in the following format: * - `onExamplePropertyChange()` -- called when the value of `exampleProperty` changes, or if a Change event is emitted on a managed object referenced by this (managed) property * - `onExamplePropertyChangeAsync()` -- idem, but called asynchronously, and only once if multiple changes occurred before this method was called * - `onExampleEventName()` -- called when an event with name `ExampleEventName` is emitted on the object; as an exception, `onChange()` is called when _any_ event that derives from `MangedChangeEvent` is emitted * - `onExampleEventNameAsync()` -- idem, but called asynchronously * - `onEvent()` -- called when _any_ event is emitted on the object * - `onEventAsync()` -- idem, but called asynchronously * @note Observer classes may be nested inside of the observed class, which provides access to private and protected methods; see `@observe` */ static addObserver<T extends ManagedObject>( this: ManagedObjectConstructor<T>, Observer: { new (instance: T): any } ) { observe(this, () => Observer); return this; } /** Attach an event handler function, to be invoked for all events that are emitted _on all instances_ of this class _and_ derived classes. Given function is invoked in the context (`this` variable) of the emitting object, with the emitted event as a single parameter. */ static addEventHandler<T extends ManagedObject>( this: ManagedObjectConstructor<T>, handler: (this: T, e: ManagedEvent) => void ) { if ((this as any) === ManagedObject) { throw err(ERROR.Object_Base); } // get the previous prototype and handler on same prototype let prevProto: typeof this.prototype; let prevHandler: ((this: any, e: ManagedEvent) => void) | undefined; if (!_hOP.call(this.prototype, HIDDEN.EVENT_HANDLER)) { // add a handler to this prototype prevProto = Object.getPrototypeOf(this.prototype); Object.defineProperty(this.prototype, HIDDEN.EVENT_HANDLER, { enumerable: false, configurable: false, writable: true, }); } else { // chain with existing handler prevHandler = this.prototype[HIDDEN.EVENT_HANDLER]; } // add the event handler function this.prototype[HIDDEN.EVENT_HANDLER] = function (this: any, e: ManagedEvent) { prevProto && prevProto[HIDDEN.EVENT_HANDLER] ? prevProto[HIDDEN.EVENT_HANDLER]!.call(this, e) : prevHandler && prevHandler.call(this, e); try { handler.call(this, e); } catch (err) { util.exceptionHandler(err); } }; return this; } /** @internal Method that can be overridden on the class _prototype_ to be invoked for every new instance */ private [HIDDEN.PROTO_INSTANCE_INIT]() {} /** @internal Override the method that is run for every new instance, calling the previous method first, if any */ static _addInitializer(f: () => void) { let fp = _hOP.call(this.prototype, HIDDEN.PROTO_INSTANCE_INIT) && this.prototype[HIDDEN.PROTO_INSTANCE_INIT]; if (fp) { this.prototype[HIDDEN.PROTO_INSTANCE_INIT] = function () { (fp as Function).call(this); f.call(this); }; } else { let up = Object.getPrototypeOf(this.prototype); this.prototype[HIDDEN.PROTO_INSTANCE_INIT] = function () { let fpp = up[HIDDEN.PROTO_INSTANCE_INIT]; fpp && fpp.call(this); f.call(this); }; } } /** Create a new managed object instance */ constructor() { // override getter/setter properties to be non-enumerable this[HIDDEN.STATE_PROPERTY] = ManagedState.CREATED; Object.defineProperty(this, HIDDEN.STATE_PROPERTY, { ...Object.getOwnPropertyDescriptor(this, HIDDEN.STATE_PROPERTY), writable: true, enumerable: false, }); this[HIDDEN.REFCOUNT_PROPERTY] = 0; Object.defineProperty(this, HIDDEN.REFCOUNT_PROPERTY, { ...Object.getOwnPropertyDescriptor(this, HIDDEN.REFCOUNT_PROPERTY), enumerable: false, }); // intialize reflinks property to be non-enumerable as well Object.defineProperty(this, HIDDEN.REF_PROPERTY, { value: [], writable: false, configurable: false, enumerable: false, }); // run callbacks, if any this[HIDDEN.PROTO_INSTANCE_INIT](); } /** Unique ID of this managed object (read only) */ readonly managedId = _nextUID++; /** * The current lifecycle state of this managed object. * @note This property is read-only. To change the state of a managed object (i.e. to move its lifecycle between active/inactive and destroyed states), use the `activateManagedAsync`, `deactivateManagedAsync`, and `destroyManagedAsync` methods. If any additional logic is required when moving between states, override the `onManagedStateActivatingAsync`, `onManagedStateActiveAsync`, `onManagedStateDeactivatingAsync`, `onManagedStateInactiveAsync` and/or `onManagedStateDestroyingAsync` methods in any class that derives from `ManagedObject`. * @note This property _cannot_ be observed directly. Observer classes (see `addObserver`) should use methods such as `onActive` to observe lifecycle state. */ get managedState() { return this[HIDDEN.STATE_PROPERTY]; } /** * Returns the current number of managed references that point to this object * @note Observers (see `addObserver`) may use an `onReferenceCountChangeAsync` method to observe this value asynchronously. */ protected getReferenceCount() { return this[HIDDEN.REFCOUNT_PROPERTY]; } /** Returns an array of unique managed objects that contain managed references to this object (see `@managed`, `@managedChild`, and `@component` decorators) */ protected getManagedReferrers() { let seen: boolean[] = Object.create(null); let result: ManagedObject[] = []; this[HIDDEN.REF_PROPERTY].forEach(reflink => { let object: ManagedObject = reflink.a; if (object.managedState && !seen[object.managedId]) { result.push(object); } }); return result; } /** * Returns the managed object that contains a _managed child reference_ that points to this instance, if any (see `@managedChild` and `@component` decorators). * If a class argument is specified, parent references are recursed until a parent of given type is found. * The object itself is never returned, even if it contains a managed child reference that points to itself. * @note The reference to the managed parent (but not its events) can be observed (see `addObserver`) using an `onManagedParentChange` or `onManagedParentChangeAsync` method on the observer. */ protected getManagedParent<TParent extends ManagedObject = ManagedObject>( ParentClass?: ManagedObjectConstructor<TParent> ): TParent | undefined { let ref = this[HIDDEN.REF_PROPERTY].parent; let parent: ManagedObject | undefined = ref && ref.a; // if class reference given, check parents' references if (ParentClass && parent && !(parent instanceof <any>ParentClass)) { let parentRef = parent[HIDDEN.REF_PROPERTY].parent; parent = parentRef && parentRef.a; // check again (unrolled) if (parent && !(parent instanceof <any>ParentClass)) { parentRef = parent[HIDDEN.REF_PROPERTY].parent; parent = parentRef && parentRef.a; // continue in a loop, but keep track of objects already seen let seen: boolean[] | undefined; while (parent && !(parent instanceof <any>ParentClass)) { (seen || (seen = Object.create(null)))[parent.managedId] = true; parentRef = parent[HIDDEN.REF_PROPERTY].parent; parent = parentRef && parentRef.a; if (parent && seen![parent.managedId]) break; } } } return parent && parent !== this ? (parent as TParent) : undefined; } /** * Emit an event. If an event constructor is given, a new instance is created using given constructor arguments (rest parameters). If an event name (string) is given, a new plain event is created with given name. * For ways to handle events, see `@delegateEvents` (for events that are emitted by referenced objects) or `ManagedObject.addEventHandler` and `ManagedObject.addObserver` (static methods for class-based event handling). * @note There is a limit to the number of events that can be emitted recursively; avoid calling this method on the same object from _within_ a synchronous event handler. * @exception Throws an error if the current state is 'destroyed'. Managed objects in this state cannot emit events anymore. */ emit<TEvent extends ManagedEvent = ManagedEvent, TConstructorArgs extends any[] = any[]>( e: TEvent | (new (...args: TConstructorArgs) => TEvent) | string, ...constructorArgs: TConstructorArgs ) { if (!this[HIDDEN.STATE_PROPERTY] && e !== ManagedCoreEvent.DESTROYED) { throw err(ERROR.Object_Destroyed); } if (typeof e === "string") e = new ManagedEvent(e).freeze() as any; if (typeof e === "function") e = new e(...constructorArgs).freeze(); if (!(e instanceof ManagedEvent)) { throw err(ERROR.Object_NotEvent); } if (this._emitting === undefined) { Object.defineProperty(this, "_emitting", { enumerable: false, writable: true, value: 0, }); } else if (this._emitting! > RECURSE_EMIT_LIMIT) { throw err(ERROR.Object_Recursion, e.name); } let emitError: any; try { this._emitting = this._emitting! + 1; if (this[HIDDEN.EVENT_HANDLER]) { this[HIDDEN.EVENT_HANDLER]!(e); } this[HIDDEN.REF_PROPERTY].forEach(v => { if (v && v.a && v.f) v.f.call(undefined, e, v.a, this); }); } catch (err) { emitError = err; } this._emitting!--; if (emitError) util.exceptionHandler(emitError); return this; } /** Emit a change event (see `ManagedChangeEvent`), to signal that the internal state of the emitting object has changed. The `name` parameter is optional; if left out, the `CHANGE` event (instance) is emitted directly. */ emitChange(name?: string) { if (name === undefined) this.emit(CHANGE); else this.emit(ManagedChangeEvent, name); } /** * Propagate events from managed child objects that are _referenced_ as properties of this object (see `@managedChild` and `@component` decorators) by emitting the same events on this object itself. * @deprecated in favor of `@delegateEvents` since version 3.1 */ protected propagateChildEvents( ...types: ({ new (...args: any[]): ManagedEvent } | ((e: ManagedEvent) => any))[] ) { util.propagateEvents(this, true, ...types); return this; } /** Activate this object (i.e. change state to `ManagedState.ACTIVATING` and then to `ManagedState.ACTIVATED`); the `onManagedStateActivatingAsync` and `onManagedStateActiveAsync` methods are called in this process */ protected async activateManagedAsync() { return this._transitionManagedState( ManagedState.ACTIVE, async () => { this[HIDDEN.STATE_PROPERTY] = ManagedState.ACTIVATING; await this.onManagedStateActivatingAsync(); }, ManagedCoreEvent.ACTIVE, this.onManagedStateActiveAsync ); } /** Deactivate this object, if it is currently active (i.e. change state to `ManagedState.DEACTIVATING` and then to `ManagedState.DEACTIVATED`); the `onManagedStateDeactivatingAsync` and `onManagedStateInactiveAsync` methods are called in this process */ protected async deactivateManagedAsync() { await this._transitionManagedState( ManagedState.INACTIVE, async () => { this[HIDDEN.STATE_PROPERTY] = ManagedState.DEACTIVATING; await this.onManagedStateDeactivatingAsync(); }, ManagedCoreEvent.INACTIVE, this.onManagedStateInactiveAsync ); } /** * Destroy this managed object (i.e. change state to `ManagedState.DESTROYING` and then to `ManagedState.DESTROYED`, clear all managed references from and to this object, and destroy all managed children); the `onManagedStateDestroyingAsync` method is called in the process * @note Managed child objects are automatically destroyed when [1] their parent's reference (decorated with `@managedChild` or `@component`) is cleared or otherwise changed, or [2] the child object is removed from a managed list or map that is itself a managed child, or [3] when the parent object itself is destroyed. */ protected async destroyManagedAsync() { let n = 3; let state: ManagedState; while ( (state = this[HIDDEN.STATE_PROPERTY]) === ManagedState.ACTIVE || state === ManagedState.ACTIVATING || state === ManagedState.DEACTIVATING ) { if (n-- <= 0) throw err(ERROR.Object_CannotDeactivate); await this.deactivateManagedAsync(); } if (!state) return; await this._transitionManagedState( ManagedState.DESTROYED, async () => { this[HIDDEN.STATE_PROPERTY] = ManagedState.DESTROYING; await this.onManagedStateDestroyingAsync(); // remove all references, keep RefLink instances for reuse let refs = this[HIDDEN.REF_PROPERTY]; delete refs.parent; delete refs.head; delete refs.tail; let g: Array<(self: this) => void> = []; for (let p in refs) { if (refs[p]) { if (refs[p]!.g) g.push(refs[p]!.g!); ManagedObject._discardRefLink(refs[p]); } } // set status early and call destruction handlers this[HIDDEN.STATE_PROPERTY] = ManagedState.DESTROYED; g.forEach(fn => { try { fn(this); } catch {} }); }, ManagedCoreEvent.DESTROYED ); } /** Callback invoked when changing state to 'active', can be overridden to perform any actions before activating */ protected async onManagedStateActivatingAsync() {} /** Callback invoked immediately after state has changed to 'active' and before any other state transitions, can be overridden */ protected async onManagedStateActiveAsync() {} /** Callback invoked when changing state to 'inactive', can be overridden to perform any actions before deactivating */ protected async onManagedStateDeactivatingAsync() {} /** Callback invoked immediately after state has changed to 'inactive' and before any other state transitions, can be overridden */ protected async onManagedStateInactiveAsync() {} /** Callback invoked when changing state to 'destroyed', can be overridden to perform any actions first */ protected async onManagedStateDestroyingAsync() {} /** Implementation for all state transition methods: handle state transitions asynchronously with a way to chain next transitions */ private _transitionManagedState( newState: ManagedState, callback: () => undefined | Promise<any>, event: ManagedEvent, callbackAfter?: () => undefined | Promise<any> ) { if (!_hOP.call(this, "_transition")) { Object.defineProperty(this, "_transition", { configurable: false, writable: true, enumerable: false, }); } /** Helper function to go ahead with the actual transition */ let doTransitionAsync = async (t: ManagedStateTransition) => { let oldState = this[HIDDEN.STATE_PROPERTY]; if (newState === oldState) return; if (!oldState) throw err(ERROR.Object_Destroyed); let changedState: boolean | undefined; this._transition = t; try { await callback.call(this); this[HIDDEN.STATE_PROPERTY] = newState; changedState = true; this.emit(event); callbackAfter && callbackAfter.call(this); } finally { // change back to state from before calling callback if needed if (!changedState) this[HIDDEN.STATE_PROPERTY] = oldState; this._transition = t.pending || undefined; } }; /** Helper function to make a transition object, representing the transition and making it cancellable in case a new transition gets scheduled in place of this one */ let makeTransition = (prev: Promise<any>) => { let rejectResult: (err: any) => void; let rejected: boolean | undefined; // return an object that represents the transition which can be cancelled let result: ManagedStateTransition = { state: newState, p: new Promise((resolve, reject) => { // wait for previous promise, then make this current rejectResult = reject; let go = () => { if (rejected) return; resolve(doTransitionAsync(result)); }; prev.then(go, go); }), reject() { rejected = true; rejectResult(err(ERROR.Object_StateCancelled)); }, }; return result; }; // check if there is an ongoing transition already if (this._transition) { // check if there is already a next pending transition if (this._transition.pending) { // check if *same* transition is already pending if (this._transition.pending.state === newState) { return this._transition.pending.p; } // cancel existing pending transaction this._transition.pending.reject(); this._transition.pending = undefined; } // check if *same* transition is already ongoing if (this._transition.state === newState) { return this._transition.p; } // schedule transition after the ongoing one return (this._transition.pending = makeTransition(this._transition.p)).p; } else { // schedule transition right away (but still NOT sync!) return (this._transition = makeTransition(Promise.resolve())).p; } } /** @internal Create a new reference link object (or take one from the cache) and set given values, to indicate that the source object references given target */ protected static _createRefLink<T extends ManagedObject>( source: T, target: ManagedObject, propId: string, handleEvent?: (e: ManagedEvent, obj: T, ref: ManagedObject) => void, handleDestroy?: (obj: T) => void ) { let ref: util.RefLink; let targetRefs = target[HIDDEN.REF_PROPERTY]; if (_freeRefLinks.length) { // reuse existing instance ref = _freeRefLinks.pop()!; ref.a = source; ref.b = target; ref.p = propId; ref.f = handleEvent; ref.g = handleDestroy; ref.u = targetRefs.length; ref.j = ref.k = undefined; } else { // create new object ref = { u: targetRefs.length, a: source, b: target, p: propId, f: handleEvent, g: handleDestroy, j: undefined, k: undefined, }; } targetRefs.push(ref); target[HIDDEN.REFCOUNT_PROPERTY]++; source[HIDDEN.REF_PROPERTY][propId] = ref; return ref; } /** @internal Unlink given managed reference link object; returns true if unlinked, false if argument was not a RefLink instance */ protected static _discardRefLink(ref?: util.RefLink) { if (!ref || !(ref.u >= 0) || !ref.a || !ref.b) return false; let sourceRefs = ref.a && ref.a[HIDDEN.REF_PROPERTY]; if (sourceRefs && sourceRefs[ref.p] === ref) { if (ref.p[0] === HIDDEN.MANAGED_LIST_REF_PREFIX) { // fix prev/next and head/tail refs in ManagedList, if applicable if (sourceRefs.head === ref) sourceRefs.head = ref.k; if (sourceRefs.tail === ref) sourceRefs.tail = ref.j; if (ref.j && ref.j.k === ref) ref.j.k = ref.k; if (ref.k && ref.k.j === ref) ref.k.j = ref.j; delete sourceRefs[ref.p]; } else { // remove source property value sourceRefs[ref.p] = undefined; } } let targetRefs = ref.b && ref.b[HIDDEN.REF_PROPERTY]; if (targetRefs && targetRefs[ref.u] === ref) { // remove back reference and update reference count ref.b[HIDDEN.REFCOUNT_PROPERTY]--; if (ref.u >= 0 && ref.u === targetRefs.length - 1) { let i = targetRefs.length - 2; while (i >= 0 && targetRefs[i] === undefined) i--; targetRefs.length = i + 1; } else { delete targetRefs[ref.u]; } // if this was a parent-child link, destroy the child object if (targetRefs.parent === ref && ref.b !== ref.a) { targetRefs.parent = undefined; (ref.b as ManagedObject).destroyManagedAsync().catch(util.exceptionHandler); } } if (_freeRefLinks.length < MAX_FREE_REFLINKS) _freeRefLinks.push(ref); return true; } /** @internal Make given reference link object the (new) parent-child link for the referenced object */ protected static _makeManagedChildRefLink(ref: util.RefLink, propertyName?: string) { let target: ManagedObject = ref.b; let targetRefs = target[HIDDEN.REF_PROPERTY]; if (targetRefs[ref.u] === ref) { let oldParent = targetRefs.parent; if (!(oldParent && oldParent.a === ref.a)) { // set new parent reference targetRefs.parent = ref; if (!oldParent) { // make sure all contained objects are child objects // (for lists and maps) target[HIDDEN.MAKE_REF_MANAGED_PARENT_FN](); } else { // inform old parent that child has moved this._discardRefLink(oldParent); try { oldParent.g && oldParent.g(this); } catch {} } if (target[HIDDEN.STATE_PROPERTY]) { target.emit(ManagedParentChangeEvent, ref.a, propertyName); } } } } /** @internal Returns true if given managed reference object is a parent-child link */ protected static _isManagedChildRefLink(ref: util.RefLink) { let target: ManagedObject = ref.b; let targetRefs = target[HIDDEN.REF_PROPERTY]; return targetRefs.parent === ref; } /** @internal Validate in preparation for a reference assignment: source object should not be destroyed, and target reference should be either undefined or a managed object (optionally of given type) that is not destroyed, and possibly an instance of given class, if any */ protected static _validateReferenceAssignment( source: ManagedObject, target?: ManagedObject, ClassRestriction: ManagedObjectConstructor<any> = ManagedObject, name?: string ) { if (target !== undefined) { if (!source[HIDDEN.STATE_PROPERTY]) { throw err(ERROR.Object_RefDestroyed); } if (!(target instanceof ClassRestriction)) { throw err(ERROR.Object_InvalidRef, name); } if (!target[HIDDEN.STATE_PROPERTY]) { throw err(ERROR.Object_RefDestroyed); } } } /** * @internal Amend given property (on object or prototype) to turn it into a managed reference property. * @param object * the instance or prototype object in which to amend given property * @param propertyKey * the property to be amended * @param isChildReference * true if this reference should be a managed parent-child reference; automatically asserts a parent-child dependency between the referencing object and referenced object(s), recursively extending to objects in referenced managed lists, maps, and reference instances * @param readonlyRef * optionally, a read-only managed reference object; when provided, the property will not be writable, and reading it results in the _target_ of the reference object * @returns the newly applied property descriptor */ static createManagedReferenceProperty<T extends ManagedObject>( object: T, propertyKey: keyof T, isChildReference?: boolean, readonlyRef?: ManagedReference, ClassRestriction?: ManagedObjectConstructor<any> ) { if (!(object instanceof ManagedObject)) { throw err(ERROR.Object_PropNotManaged); } // check if descriptor already defined and cannot chain let chain = Object.getOwnPropertyDescriptor(object, propertyKey); if (chain && (!chain.set || !(chain.set as any)[HIDDEN.SETTER_CHAIN])) { throw err(ERROR.Object_PropGetSet); } // (re)define property on prototype let propId = HIDDEN.PROPERTY_ID_PREFIX + _nextRefId++; return util.defineChainableProperty( object, propertyKey, false, (obj, name, next) => { return (target: ManagedObject, event, topHandler) => { if (event) { if (readonlyRef) { // use reference target instead of reference itself if (target !== readonlyRef) return; target = readonlyRef.get()!; } next && next(target, event, topHandler); return; } if (readonlyRef && target !== readonlyRef) { // do not assign to read only reference (but used by getter initially) throw err(ERROR.Object_NotWritable); } ManagedObject._validateReferenceAssignment( obj, target, ClassRestriction, propertyKey as any ); let cur = obj[HIDDEN.REF_PROPERTY][propId]; if (cur && target && cur.b === target && !readonlyRef) return; // unlink existing reference, if any (also destroys child if needed) ManagedObject._discardRefLink(cur); // create new reference and update target count if (target) { let ref = ManagedObject._createRefLink( obj, target, propId, (e, obj, target) => { // propagate event to other handler(s) topHandler(target, e, topHandler); if (isChildReference && obj[HIDDEN.CHILD_EVENT_HANDLER]) { obj[HIDDEN.CHILD_EVENT_HANDLER]!(e, propertyKey as string); } }, () => { // handle target moved/destroyed: set to undefined (obj as any)[name] = undefined; } ); if (isChildReference) { // set (new) parent-child link on the target object ManagedObject._makeManagedChildRefLink(ref, propertyKey as string); } } if (readonlyRef) target = readonlyRef.get()!; next && next(target, event, topHandler); }; }, function (this: any) { let ref = this[HIDDEN.REF_PROPERTY][propId]; // dereference read-only reference, if any if (readonlyRef) { if (!ref) { // assign reference once ONLY // (set bogus link first to avoid recursion) ManagedObject._createRefLink(this, readonlyRef, propId); this[propertyKey] = readonlyRef; } return readonlyRef.get(); } // normal getter: return referenced object return ref && ref.b; } ); } /** @internal To be overridden, to turn existing references into child objects (i.e. for lists and maps) */ protected [HIDDEN.MAKE_REF_MANAGED_PARENT_FN]() {} /** @internal Reference link object map */ private readonly [HIDDEN.REF_PROPERTY]!: util.RefLinkMap; /** @internal Reference count */ private [HIDDEN.REFCOUNT_PROPERTY]!: number; /** @internal Current state value */ private [HIDDEN.STATE_PROPERTY]!: ManagedState; /** @internal Chained event handler(s) */ private [HIDDEN.EVENT_HANDLER]: (e: ManagedEvent) => void; /** @internal Child event handler (not chained) */ private [HIDDEN.CHILD_EVENT_HANDLER]: (e: ManagedEvent, name: string) => void; /** True if currently emitting an event */ private _emitting?: number; /** The current transition being handled, if any */ private _transition?: ManagedStateTransition; } /** Represents an ongoing state transition, and the next transition after it */ interface ManagedStateTransition { /** A promise for the transition */ p: Promise<any>; /** The intended state after this transition */ state: ManagedState; /** Function to reject this state if it has not yet been completed */ reject(): void; /** Next pending state transition (can be only one after the current transition); if this gets replaced, the `reject` function is called on the previous pending transition to cancel it */ pending?: ManagedStateTransition; }
the_stack
import * as zrUtil from 'zrender/src/core/util'; import * as graphic from '../../util/graphic'; import * as axisPointerModelHelper from './modelHelper'; import * as eventTool from 'zrender/src/core/event'; import * as throttleUtil from '../../util/throttle'; import {makeInner} from '../../util/model'; import { AxisPointer } from './AxisPointer'; import { AxisBaseModel } from '../../coord/AxisBaseModel'; import ExtensionAPI from '../../core/ExtensionAPI'; import Displayable, { DisplayableProps } from 'zrender/src/graphic/Displayable'; import Element from 'zrender/src/Element'; import { VerticalAlign, HorizontalAlign, CommonAxisPointerOption } from '../../util/types'; import { PathProps } from 'zrender/src/graphic/Path'; import Model from '../../model/Model'; import { TextProps } from 'zrender/src/graphic/Text'; const inner = makeInner<{ lastProp?: DisplayableProps labelEl?: graphic.Text pointerEl?: Displayable }, Element>(); const clone = zrUtil.clone; const bind = zrUtil.bind; type Icon = ReturnType<typeof graphic.createIcon>; interface Transform { x: number, y: number, rotation: number } type AxisValue = CommonAxisPointerOption['value']; // Not use top level axisPointer model type AxisPointerModel = Model<CommonAxisPointerOption>; interface BaseAxisPointer { /** * Should be implemenented by sub-class if support `handle`. */ getHandleTransform(value: AxisValue, axisModel: AxisBaseModel, axisPointerModel: AxisPointerModel): Transform /** * * Should be implemenented by sub-class if support `handle`. */ updateHandleTransform( transform: Transform, delta: number[], axisModel: AxisBaseModel, axisPointerModel: AxisPointerModel ): Transform & { cursorPoint: number[] tooltipOption?: { verticalAlign?: VerticalAlign align?: HorizontalAlign } } } export interface AxisPointerElementOptions { graphicKey: string pointer: PathProps & { type: 'Line' | 'Rect' | 'Circle' | 'Sector' } label: TextProps } /** * Base axis pointer class in 2D. */ class BaseAxisPointer implements AxisPointer { private _group: graphic.Group; private _lastGraphicKey: string; private _handle: Icon; private _dragging = false; private _lastValue: AxisValue; private _lastStatus: CommonAxisPointerOption['status']; private _payloadInfo: ReturnType<BaseAxisPointer['updateHandleTransform']>; /** * If have transition animation */ private _moveAnimation: boolean; private _axisModel: AxisBaseModel; private _axisPointerModel: AxisPointerModel; private _api: ExtensionAPI; /** * In px, arbitrary value. Do not set too small, * no animation is ok for most cases. */ protected animationThreshold = 15; /** * @implement */ render(axisModel: AxisBaseModel, axisPointerModel: AxisPointerModel, api: ExtensionAPI, forceRender?: boolean) { const value = axisPointerModel.get('value'); const status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not // be replaced when user calling setOption in not merge mode. this._axisModel = axisModel; this._axisPointerModel = axisPointerModel; this._api = api; // Optimize: `render` will be called repeatly during mouse move. // So it is power consuming if performing `render` each time, // especially on mobile device. if (!forceRender && this._lastValue === value && this._lastStatus === status ) { return; } this._lastValue = value; this._lastStatus = status; let group = this._group; const handle = this._handle; if (!status || status === 'hide') { // Do not clear here, for animation better. group && group.hide(); handle && handle.hide(); return; } group && group.show(); handle && handle.show(); // Otherwise status is 'show' const elOption = {} as AxisPointerElementOptions; this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type. const graphicKey = elOption.graphicKey; if (graphicKey !== this._lastGraphicKey) { this.clear(api); } this._lastGraphicKey = graphicKey; const moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel); if (!group) { group = this._group = new graphic.Group(); this.createPointerEl(group, elOption, axisModel, axisPointerModel); this.createLabelEl(group, elOption, axisModel, axisPointerModel); api.getZr().add(group); } else { const doUpdateProps = zrUtil.curry(updateProps, axisPointerModel, moveAnimation); this.updatePointerEl(group, elOption, doUpdateProps); this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel); } updateMandatoryProps(group, axisPointerModel, true); this._renderHandle(value); } /** * @implement */ remove(api: ExtensionAPI) { this.clear(api); } /** * @implement */ dispose(api: ExtensionAPI) { this.clear(api); } /** * @protected */ determineAnimation(axisModel: AxisBaseModel, axisPointerModel: AxisPointerModel): boolean { const animation = axisPointerModel.get('animation'); const axis = axisModel.axis; const isCategoryAxis = axis.type === 'category'; const useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap. if (!useSnap && !isCategoryAxis) { return false; } if (animation === 'auto' || animation == null) { const animationThreshold = this.animationThreshold; if (isCategoryAxis && axis.getBandWidth() > animationThreshold) { return true; } // It is important to auto animation when snap used. Consider if there is // a dataZoom, animation will be disabled when too many points exist, while // it will be enabled for better visual effect when little points exist. if (useSnap) { const seriesDataCount = axisPointerModelHelper.getAxisInfo(axisModel).seriesDataCount; const axisExtent = axis.getExtent(); // Approximate band width return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold; } return false; } return animation === true; } /** * add {pointer, label, graphicKey} to elOption * @protected */ makeElOption( elOption: AxisPointerElementOptions, value: AxisValue, axisModel: AxisBaseModel, axisPointerModel: AxisPointerModel, api: ExtensionAPI ) { // Shoule be implemenented by sub-class. } /** * @protected */ createPointerEl( group: graphic.Group, elOption: AxisPointerElementOptions, axisModel: AxisBaseModel, axisPointerModel: AxisPointerModel ) { const pointerOption = elOption.pointer; if (pointerOption) { const pointerEl = inner(group).pointerEl = new graphic[pointerOption.type]( clone(elOption.pointer) ); group.add(pointerEl); } } /** * @protected */ createLabelEl( group: graphic.Group, elOption: AxisPointerElementOptions, axisModel: AxisBaseModel, axisPointerModel: AxisPointerModel ) { if (elOption.label) { const labelEl = inner(group).labelEl = new graphic.Text( clone(elOption.label) ); group.add(labelEl); updateLabelShowHide(labelEl, axisPointerModel); } } /** * @protected */ updatePointerEl( group: graphic.Group, elOption: AxisPointerElementOptions, updateProps: (el: Element, props: PathProps) => void ) { const pointerEl = inner(group).pointerEl; if (pointerEl && elOption.pointer) { pointerEl.setStyle(elOption.pointer.style); updateProps(pointerEl, {shape: elOption.pointer.shape}); } } /** * @protected */ updateLabelEl( group: graphic.Group, elOption: AxisPointerElementOptions, updateProps: (el: Element, props: PathProps) => void, axisPointerModel: AxisPointerModel ) { const labelEl = inner(group).labelEl; if (labelEl) { labelEl.setStyle(elOption.label.style); updateProps(labelEl, { // Consider text length change in vertical axis, animation should // be used on shape, otherwise the effect will be weird. // TODOTODO // shape: elOption.label.shape, x: elOption.label.x, y: elOption.label.y }); updateLabelShowHide(labelEl, axisPointerModel); } } /** * @private */ _renderHandle(value: AxisValue) { if (this._dragging || !this.updateHandleTransform) { return; } const axisPointerModel = this._axisPointerModel; const zr = this._api.getZr(); let handle = this._handle; const handleModel = axisPointerModel.getModel('handle'); const status = axisPointerModel.get('status'); if (!handleModel.get('show') || !status || status === 'hide') { handle && zr.remove(handle); this._handle = null; return; } let isInit; if (!this._handle) { isInit = true; handle = this._handle = graphic.createIcon( handleModel.get('icon'), { cursor: 'move', draggable: true, onmousemove(e) { // Fot mobile devicem, prevent screen slider on the button. eventTool.stop(e.event); }, onmousedown: bind(this._onHandleDragMove, this, 0, 0), drift: bind(this._onHandleDragMove, this), ondragend: bind(this._onHandleDragEnd, this) } ); zr.add(handle); } updateMandatoryProps(handle, axisPointerModel, false); // update style (handle as graphic.Path).setStyle(handleModel.getItemStyle(null, [ 'color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY' ])); // update position let handleSize = handleModel.get('size'); if (!zrUtil.isArray(handleSize)) { handleSize = [handleSize, handleSize]; } handle.scaleX = handleSize[0] / 2; handle.scaleY = handleSize[1] / 2; throttleUtil.createOrUpdate( this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate' ); this._moveHandleToValue(value, isInit); } private _moveHandleToValue(value: AxisValue, isInit?: boolean) { updateProps( this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform( value, this._axisModel, this._axisPointerModel )) ); } private _onHandleDragMove(dx: number, dy: number) { const handle = this._handle; if (!handle) { return; } this._dragging = true; // Persistent for throttle. const trans = this.updateHandleTransform( getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel ); this._payloadInfo = trans; handle.stopAnimation(); (handle as graphic.Path).attr(getHandleTransProps(trans)); inner(handle).lastProp = null; this._doDispatchAxisPointer(); } /** * Throttled method. */ _doDispatchAxisPointer() { const handle = this._handle; if (!handle) { return; } const payloadInfo = this._payloadInfo; const axisModel = this._axisModel; this._api.dispatchAction({ type: 'updateAxisPointer', x: payloadInfo.cursorPoint[0], y: payloadInfo.cursorPoint[1], tooltipOption: payloadInfo.tooltipOption, axesInfo: [{ axisDim: axisModel.axis.dim, axisIndex: axisModel.componentIndex }] }); } private _onHandleDragEnd() { this._dragging = false; const handle = this._handle; if (!handle) { return; } const value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with // axisPointer. So move handle to align the exact value position when // drag ended. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle // button, and will be hidden after finger left handle button. this._api.dispatchAction({ type: 'hideTip' }); } /** * @private */ clear(api: ExtensionAPI) { this._lastValue = null; this._lastStatus = null; const zr = api.getZr(); const group = this._group; const handle = this._handle; if (zr && group) { this._lastGraphicKey = null; group && zr.remove(group); handle && zr.remove(handle); this._group = null; this._handle = null; this._payloadInfo = null; } throttleUtil.clear(this, '_doDispatchAxisPointer'); } /** * @protected */ doClear() { // Implemented by sub-class if necessary. } buildLabel(xy: number[], wh: number[], xDimIndex: 0 | 1) { xDimIndex = xDimIndex || 0; return { x: xy[xDimIndex], y: xy[1 - xDimIndex], width: wh[xDimIndex], height: wh[1 - xDimIndex] }; } } function updateProps( animationModel: AxisPointerModel, moveAnimation: boolean, el: Element, props: DisplayableProps ) { // Animation optimize. if (!propsEqual(inner(el).lastProp, props)) { inner(el).lastProp = props; moveAnimation ? graphic.updateProps(el, props, animationModel as Model< // Ignore animation property Pick<CommonAxisPointerOption, 'animationDurationUpdate' | 'animationEasingUpdate'> >) : (el.stopAnimation(), el.attr(props)); } } function propsEqual(lastProps: any, newProps: any) { if (zrUtil.isObject(lastProps) && zrUtil.isObject(newProps)) { let equals = true; zrUtil.each(newProps, function (item, key) { equals = equals && propsEqual(lastProps[key], item); }); return !!equals; } else { return lastProps === newProps; } } function updateLabelShowHide(labelEl: Element, axisPointerModel: AxisPointerModel) { labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide'](); } function getHandleTransProps(trans: Transform): Transform { return { x: trans.x || 0, y: trans.y || 0, rotation: trans.rotation || 0 }; } function updateMandatoryProps( group: Element, axisPointerModel: AxisPointerModel, silent?: boolean ) { const z = axisPointerModel.get('z'); const zlevel = axisPointerModel.get('zlevel'); group && group.traverse(function (el: Displayable) { if (el.type !== 'group') { z != null && (el.z = z); zlevel != null && (el.zlevel = zlevel); el.silent = silent; } }); } export default BaseAxisPointer;
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [geo](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonlocation.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Geo extends PolicyStatement { public servicePrefix = 'geo'; /** * Statement provider for service [geo](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonlocation.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 create an association between a geofence-collection and a tracker resource * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_AssociateTrackerConsumer.html */ public toAssociateTrackerConsumer() { return this.to('AssociateTrackerConsumer'); } /** * Grants permission to delete a batch of device position histories from a tracker resource * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_BatchDeleteDevicePositionHistory.html */ public toBatchDeleteDevicePositionHistory() { return this.to('BatchDeleteDevicePositionHistory'); } /** * Grants permission to delete a batch of geofences from a geofence collection * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_BatchDeleteGeofence.html */ public toBatchDeleteGeofence() { return this.to('BatchDeleteGeofence'); } /** * Grants permission to evaluate device positions against the position of geofences in a given geofence collection * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_BatchEvaluateGeofences.html */ public toBatchEvaluateGeofences() { return this.to('BatchEvaluateGeofences'); } /** * Grants permission to send a batch request to retrieve device positions * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_BatchGetDevicePosition.html */ public toBatchGetDevicePosition() { return this.to('BatchGetDevicePosition'); } /** * Grants permission to send a batch request for adding geofences into a given geofence collection * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_BatchPutGeofence.html */ public toBatchPutGeofence() { return this.to('BatchPutGeofence'); } /** * Grants permission to upload a position update for one or more devices to a tracker resource * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_BatchUpdateDevicePosition.html */ public toBatchUpdateDevicePosition() { return this.to('BatchUpdateDevicePosition'); } /** * Grants permission to calculate routes using a given route calculator resource * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_CalculateRoute.html */ public toCalculateRoute() { return this.to('CalculateRoute'); } /** * Grants permission to create a geofence-collection * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/location/latest/developerguide/API_CreateGeofenceCollection.html */ public toCreateGeofenceCollection() { return this.to('CreateGeofenceCollection'); } /** * Grants permission to create a map resource * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/location/latest/developerguide/API_CreateMap.html */ public toCreateMap() { return this.to('CreateMap'); } /** * Grants permission to create a place index resource * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/location/latest/developerguide/API_CreatePlaceIndex.html */ public toCreatePlaceIndex() { return this.to('CreatePlaceIndex'); } /** * Grants permission to create a route calculator resource * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/location/latest/developerguide/API_CreateRouteCalculator.html */ public toCreateRouteCalculator() { return this.to('CreateRouteCalculator'); } /** * Grants permission to create a tracker resource * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/location/latest/developerguide/API_CreateTracker.html */ public toCreateTracker() { return this.to('CreateTracker'); } /** * Grants permission to delete a geofence-collection * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_DeleteGeofenceCollection.html */ public toDeleteGeofenceCollection() { return this.to('DeleteGeofenceCollection'); } /** * Grants permission to delete a map resource * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_DeleteMap.html */ public toDeleteMap() { return this.to('DeleteMap'); } /** * Grants permission to delete a place index resource * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_DeletePlaceIndex.html */ public toDeletePlaceIndex() { return this.to('DeletePlaceIndex'); } /** * Grants permission to delete a route calculator resource * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_DeleteRouteCalculator.html */ public toDeleteRouteCalculator() { return this.to('DeleteRouteCalculator'); } /** * Grants permission to delete a tracker resource * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_DeleteTracker.html */ public toDeleteTracker() { return this.to('DeleteTracker'); } /** * Grants permission to retrieve geofence collection details * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_DescribeGeofenceCollection.html */ public toDescribeGeofenceCollection() { return this.to('DescribeGeofenceCollection'); } /** * Grants permission to retrieve map resource details * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_DescribeMap.html */ public toDescribeMap() { return this.to('DescribeMap'); } /** * Grants permission to retrieve place-index resource details * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_DescribePlaceIndex.html */ public toDescribePlaceIndex() { return this.to('DescribePlaceIndex'); } /** * Grants permission to retrieve route calculator resource details * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_DescribeRouteCalculator.html */ public toDescribeRouteCalculator() { return this.to('DescribeRouteCalculator'); } /** * Grants permission to retrieve a tracker resource details * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_DescribeTracker.html */ public toDescribeTracker() { return this.to('DescribeTracker'); } /** * Grants permission to remove the association between a tracker resource and a geofence-collection * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_DisassociateTrackerConsumer.html */ public toDisassociateTrackerConsumer() { return this.to('DisassociateTrackerConsumer'); } /** * Grants permission to retrieve the latest device position * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_GetDevicePosition.html */ public toGetDevicePosition() { return this.to('GetDevicePosition'); } /** * Grant permission to retrieve the device position history * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_GetDevicePositionHistory.html */ public toGetDevicePositionHistory() { return this.to('GetDevicePositionHistory'); } /** * Grants permission to retrieve the geofence details from a geofence-collection. * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_GetGeofence.html */ public toGetGeofence() { return this.to('GetGeofence'); } /** * Grants permission to retrieve the glyph file for a map resource * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_GetMapGlyphs.html */ public toGetMapGlyphs() { return this.to('GetMapGlyphs'); } /** * Grants permission to retrieve the sprite file for a map resource * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_GetMapSprites.html */ public toGetMapSprites() { return this.to('GetMapSprites'); } /** * Grants permission to retrieve the map style descriptor from a map resource * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_GetMapStyleDescriptor.html */ public toGetMapStyleDescriptor() { return this.to('GetMapStyleDescriptor'); } /** * Grants permission to retrieve the map tile from the map resource * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_GetMapTile.html */ public toGetMapTile() { return this.to('GetMapTile'); } /** * Grants permission to retrieve a list of devices and their latest positions from the given tracker resource * * Access Level: List * * https://docs.aws.amazon.com/location/latest/developerguide/API_ListDevicePositions.html */ public toListDevicePositions() { return this.to('ListDevicePositions'); } /** * Grants permission to lists geofence-collections * * Access Level: List * * https://docs.aws.amazon.com/location/latest/developerguide/API_ListGeofenceCollections.html */ public toListGeofenceCollections() { return this.to('ListGeofenceCollections'); } /** * Grants permission to list geofences stored in a given geofence collection * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_ListGeofences.html */ public toListGeofences() { return this.to('ListGeofences'); } /** * Grants permission to list map resources * * Access Level: List * * https://docs.aws.amazon.com/location/latest/developerguide/API_ListMaps.html */ public toListMaps() { return this.to('ListMaps'); } /** * Grants permission to return a list of place index resources * * Access Level: List * * https://docs.aws.amazon.com/location/latest/developerguide/API_ListPlaceIndexes.html */ public toListPlaceIndexes() { return this.to('ListPlaceIndexes'); } /** * Grants permission to return a list of route calculator resources * * Access Level: List * * https://docs.aws.amazon.com/location/latest/developerguide/API_ListRouteCalculators.html */ public toListRouteCalculators() { return this.to('ListRouteCalculators'); } /** * Grants permission to list the tags (metadata) which you have assigned to the resource * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to retrieve a list of geofence collections currently associated to the given tracker resource * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_ListTrackerConsumers.html */ public toListTrackerConsumers() { return this.to('ListTrackerConsumers'); } /** * Grants permission to return a list of tracker resources * * Access Level: List * * https://docs.aws.amazon.com/location/latest/developerguide/API_ListTrackers.html */ public toListTrackers() { return this.to('ListTrackers'); } /** * Grants permission to add a new geofence or update an existing geofence to a given geofence-collection * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_PutGeofence.html */ public toPutGeofence() { return this.to('PutGeofence'); } /** * Grants permission to reverse geocodes a given coordinate * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_SearchPlaceIndexForPosition.html */ public toSearchPlaceIndexForPosition() { return this.to('SearchPlaceIndexForPosition'); } /** * Grants permission to geocode free-form text, such as an address, name, city or region * * Access Level: Read * * https://docs.aws.amazon.com/location/latest/developerguide/API_SearchPlaceIndexForText.html */ public toSearchPlaceIndexForText() { return this.to('SearchPlaceIndexForText'); } /** * Grants permission to adds to or modifies the tags of the given resource. Tags are metadata which can be used to manage a resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/location/latest/developerguide/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove the given tags (metadata) from the resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/location/latest/developerguide/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update the description of a geofence collection * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_UpdateGeofenceCollection.html */ public toUpdateGeofenceCollection() { return this.to('UpdateGeofenceCollection'); } /** * Grants permission to update the description of a tracker resource * * Access Level: Write * * https://docs.aws.amazon.com/location/latest/developerguide/API_UpdateTracker.html */ public toUpdateTracker() { return this.to('UpdateTracker'); } protected accessLevelList: AccessLevelList = { "Write": [ "AssociateTrackerConsumer", "BatchDeleteDevicePositionHistory", "BatchDeleteGeofence", "BatchEvaluateGeofences", "BatchPutGeofence", "BatchUpdateDevicePosition", "CreateGeofenceCollection", "CreateMap", "CreatePlaceIndex", "CreateRouteCalculator", "CreateTracker", "DeleteGeofenceCollection", "DeleteMap", "DeletePlaceIndex", "DeleteRouteCalculator", "DeleteTracker", "DisassociateTrackerConsumer", "PutGeofence", "UpdateGeofenceCollection", "UpdateTracker" ], "Read": [ "BatchGetDevicePosition", "CalculateRoute", "DescribeGeofenceCollection", "DescribeMap", "DescribePlaceIndex", "DescribeRouteCalculator", "DescribeTracker", "GetDevicePosition", "GetDevicePositionHistory", "GetGeofence", "GetMapGlyphs", "GetMapSprites", "GetMapStyleDescriptor", "GetMapTile", "ListGeofences", "ListTagsForResource", "ListTrackerConsumers", "SearchPlaceIndexForPosition", "SearchPlaceIndexForText" ], "List": [ "ListDevicePositions", "ListGeofenceCollections", "ListMaps", "ListPlaceIndexes", "ListRouteCalculators", "ListTrackers" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type geofence-collection to the statement * * https://docs.aws.amazon.com/location/latest/developerguide/overview.html#geofence-overview * * @param geofenceCollectionName - Identifier for the geofenceCollectionName. * @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 onGeofenceCollection(geofenceCollectionName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:geo:${Region}:${Account}:geofence-collection/${GeofenceCollectionName}'; arn = arn.replace('${GeofenceCollectionName}', geofenceCollectionName); 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 map to the statement * * https://docs.aws.amazon.com/location/latest/developerguide/overview.html#map-overview * * @param mapName - Identifier for the mapName. * @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 onMap(mapName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:geo:${Region}:${Account}:map/${MapName}'; arn = arn.replace('${MapName}', mapName); 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 place-index to the statement * * https://docs.aws.amazon.com/location/latest/developerguide/overview.html#places-overview * * @param indexName - Identifier for the indexName. * @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 onPlaceIndex(indexName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:geo:${Region}:${Account}:place-index/${IndexName}'; arn = arn.replace('${IndexName}', indexName); 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 route-calculator to the statement * * https://docs.aws.amazon.com/location/latest/developerguide/overview.html#routes-overview * * @param calculatorName - Identifier for the calculatorName. * @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 onRouteCalculator(calculatorName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:geo:${Region}:${Account}:route-calculator/${CalculatorName}'; arn = arn.replace('${CalculatorName}', calculatorName); 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 tracker to the statement * * https://docs.aws.amazon.com/location/latest/developerguide/overview.html#tracking-overview * * @param trackerName - Identifier for the trackerName. * @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 onTracker(trackerName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:geo:${Region}:${Account}:tracker/${TrackerName}'; arn = arn.replace('${TrackerName}', trackerName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import ListCore from './model/core' import LifeCylcesCore, { ListLifeCycle } from './model/lifeCycles' import { IList, IListFunctionOptions, ModeType, IListQuery, IListProps, IListQueryData, IListResponse, ListLifeCycleTypes, IListFilterData, IListMultipleDataParams, IListMultiplePageSize, IListSelectionConfig, ExpandStatus, EmptyStatusType } from './types' export * from './types' import { isFn } from './util' import defaultQuery from './defaultQuery' function createList(props: IListProps = {}): IList { // 渲染相关的设置都在API层完成,core层只管数据,和操作数据的方法 const list = new ListCore(props) const lifeCycles = new LifeCylcesCore({ lifeCycles: props.lifeCycles }) const universalNotify = opts => { lifeCycles.notify(opts) const filterInstance = list.getFilterInstance() if (filterInstance) { filterInstance.notify( ListLifeCycleTypes.LIST_LIFECYCLES_FORM_GOD_MODE, opts ) } } const mode = list.getMode() // 通知UI重新渲染的方法 const refreshTable = (notifyId?: string[]) => lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_TABLE_REFRESH, payload: { notifyId } }) const refreshLoading = (notifyId?: string[]) => lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_LOADING_REFRESH, payload: { notifyId } }) const refreshPagination = (notifyId?: string[]) => lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_PAGINATION_REFRESH, payload: { notifyId } }) const refreshValidateConfig = (notifyId?: string[]) => lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_VALIDATE_CONFIG_REFRESH, payload: { notifyId } }) // const refreshConsumer = () => lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_CONSUMER_REFRESH }) // const refreshFilter = () => lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_FILTER_REFRESH }) const refreshSelection = (notifyId?: string[]) => lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_SELECTION_REFRESH, payload: { notifyId } }) // 请求相关 let columnsChange = false let url = props.url // 请求url let params = props.params || {} // url的param let paramsFields = props.paramsFields let method = props.method || 'GET' // GET | POST | ... let query = props.query || defaultQuery // 自定义请求方法,默认适用url模式 let autoLoad = props.autoLoad === undefined ? true : props.autoLoad let expandStatus: ExpandStatus = props.expandStatus === undefined ? 'collapse' : 'expand' // 展开或收起搜索条件 // 初始化搜索框的默认值, 用于重置 // 请求列表 const fetch = async (extraFilterData?: IListFilterData) => { if (mode === ModeType.DATASOURCE) { return } if (mode === ModeType.URL && !url) { return } // 请求时需要执行校验 const filterInstance = list.getFilterInstance() if (filterInstance) { if (Array.isArray(filterInstance.ignoreValidationKeys)) { const validatePath = filterInstance.ignoreValidationKeys.join(',') await filterInstance.validate(`*(!${validatePath})`) } else { await filterInstance.validate() } const { errors } = filterInstance.getFormState(state => { return { errors: state.errors } }) if (errors.length) { return } } const pageData = list.getPageData() // 分页数据 const filterData = list.getFilterData() // 搜索数据 const { sorter, sortLocal } = list.getSortConfig() // 排序数据 let sortData = {} if (!isFn(sortLocal)) { sortData = sorter } let queryFilterData = { ...filterData, ...(extraFilterData || {}) } // 自定义修改搜索框数据 if (isFn(props.formatFilter)) { queryFilterData = props.formatFilter(queryFilterData) } let queryData: IListQueryData = { filterData: queryFilterData, currentPage: pageData.currentPage, pageSize: pageData.pageSize, sort: sortData, _t: new Date().getTime() } // 自定义修改请求数据 if (isFn(props.formatBefore)) { queryData = props.formatBefore(queryData) } // 刷新table状态 listAPI.setLoading(true) // 请求前 universalNotify({ type: ListLifeCycleTypes.ON_LIST_BEFORE_QUERY, payload: { url, method, data: queryData }, ctx: listAPI }) // 请求开始 let result: IListResponse | void let reqErr = null let reqEmpty = false try { result = await query({ url, method, data: queryData }) } catch (e) { console.error(e && e.message ? e.message : e) if (e && e.message) { reqErr = e.message } else if (e) { reqErr = e } else { reqErr = 'unknow error' } // 异常流,触发生命周期 onError 钩子 universalNotify({ type: ListLifeCycleTypes.ON_LIST_ERROR, payload: reqErr, ctx: listAPI }) } // 自定义修改结果数据 if (isFn(props.formatAfter)) { result = props.formatAfter(result) } // 执行数据更新 const { dataList, total, pageSize, currentPage, multipleData, totalPages } = result || {} // 多实例模式 if (typeof multipleData === 'object') { // 生命周期:返回空数据 if ( !multipleData || Object.keys(multipleData).length === 0 || (Object.keys(multipleData) .map(k => { if (!multipleData[k]) return [] if (Array.isArray(multipleData[k] as any[])) return multipleData[k] if (Array.isArray((multipleData[k] as IListResponse).dataList)) return (multipleData[k] as IListResponse).dataList }) .reduce((buf: any[], cur: any[]) => [...buf, ...cur], []) as any[]) .length === 0 ) { reqEmpty = true } list.setMultipleData(multipleData) } else { // 生命周期:返回空数据 if (!dataList || (Array.isArray(dataList) && dataList.length === 0)) { reqEmpty = true } list.setPaginationDataSource(dataList) list.setDataSource(dataList) list.setPageData({ total, pageSize, currentPage, totalPages }) } list.setResponseData(result) // 生命周期:返回空数据 lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_EMPTY, ctx: listAPI }) // 生命周期:请求后 lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_AFTER_QUERY, payload: { result, empty: reqEmpty, hasError: reqErr !== null, error: reqErr }, ctx: listAPI }) list.setEmptyStatus( reqErr !== null ? EmptyStatusType.ERROR : reqEmpty ? EmptyStatusType.EMPTY : EmptyStatusType.VALID ) // 多实例模式 if (typeof multipleData === 'object') { lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_MULTIPLE_REFRESH, ctx: listAPI }) } // 生命周期:即将更新 lifeCycles.notify({ type: ListLifeCycleTypes.WILL_LIST_UPDATE, ctx: listAPI }) // 请求结束 listAPI.setLoading(false) refreshPagination() refreshTable() // 生命周期:已经触发更新 universalNotify({ type: ListLifeCycleTypes.DID_LIST_UPDATE, ctx: listAPI }) return result } // 清理查询条件 const clear = (fnOpts?: IListFunctionOptions) => { // 生命周期:清理查询条件 lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_CLEAR, ctx: listAPI }) if (!fnOpts || fnOpts.reset === true) { list.resetPage() } list.setSortConfig({ sorter: undefined }) list.clearFilterData() // 默认会执行请求 if (!fnOpts || fnOpts.withFetch === true) { fetch() } } // 重置,如果存在默认值,会恢复到默认值 const reset = (fnOpts?: IListFunctionOptions) => { // 生命周期:清理查询条件 lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_RESET, ctx: listAPI }) if (!fnOpts || fnOpts.reset === true) { list.resetPage() } list.setSortConfig({ sorter: undefined }) list.resetFilterData() // 默认会执行请求 if (!fnOpts || fnOpts.withFetch === true) { fetch() } } // 分页器跳转页面时使用 const setCurrentPage = (currentPage: number) => { list.setCurrentPage(Number(currentPage)) if (mode === ModeType.DATASOURCE) { // dataSource模式下,直接更新表格 refreshPagination() refreshTable() } else { fetch() // 直接请求数据 } } const setPageSize = (pageSize: number) => { list.setPageSize(Number(pageSize)) if (mode === ModeType.DATASOURCE) { // dataSource模式下,直接更新表格 refreshPagination() refreshTable() } else { fetch() // 直接请求数据 refreshPagination() } } // 刷新列表 const refresh = async (opts?: IListFunctionOptions) => { const refreshOpts = opts || { reset: true } // 默认刷新都是清空,支持reset设置为false if (refreshOpts.reset === true) { list.resetPage() } const result = await fetch(refreshOpts.filterData) return result } // 刷新table const setTableProps = async (tableProps, fnOpts?: IListFunctionOptions) => { list.setTableProps(tableProps) if (!fnOpts || fnOpts.withRender) { refreshTable() } } const hasSetColumns = () => columnsChange const setColumns = (cols: any[], opts) => { const { notifyId, init = false } = opts || {} if (!init) { columnsChange = true } list.setColumns(cols) refreshTable(notifyId) } // 设置dataSource const setDataSource = (dataSource, fnOpts?: IListFunctionOptions) => { list.setDataSource(dataSource) if (mode === ModeType.DATASOURCE) { list.setPageData({ total: list.getState('dataSource').length, currentPage: 1 }) if (!fnOpts || fnOpts.withRender) { refreshPagination() } } list.resetPage() if (!fnOpts || fnOpts.withRender) { refreshTable() } } // 设置多实例数据 const setMultipleData = ( multipleData: IListMultipleDataParams, fnOpts?: IListFunctionOptions ) => { const multipleKeys = Object.keys(multipleData) list.setMultipleData(multipleData) if (!fnOpts || fnOpts.withRender) { refreshTable(multipleKeys) refreshPagination(multipleKeys) } } // 设置多实例分页数据 const setMultiplePageSize = ( multiplePageSize: IListMultiplePageSize, fnOpts?: IListFunctionOptions ) => { const multipleKeys = Object.keys(multiplePageSize) list.setMultiplePageSize(multiplePageSize) if (!fnOpts || fnOpts.withRender) { refreshTable(multipleKeys) refreshPagination(multipleKeys) } } // 设置页面参数, 动态维护url参数 const setParams = (nextParams, fnOpts?: IListFunctionOptions) => { params = { ...params, ...nextParams } const { enableInvalid = false } = fnOpts || {} const searchParams = new URLSearchParams(location.search) Object.keys(nextParams).forEach(key => { let targetParams if (enableInvalid || [null, undefined].indexOf(nextParams[key]) === -1) { if (typeof nextParams[key] === 'object') { targetParams = JSON.stringify(nextParams[key]) } else { targetParams = nextParams[key] } searchParams.set(key, targetParams) } }) const search = searchParams.toString() const hashStr = (location.hash || '').split('?')[0] const newUrl = `${location.origin}${location.pathname}${hashStr}${ search ? '?' + search : '' }` window.history.replaceState(params, undefined, newUrl) } // 设置loading const setLoading = (loading: boolean, fnOpts?: IListFunctionOptions) => { list.setLoading(loading) if (!fnOpts || fnOpts.withRender) { refreshLoading() } } const setSelectionConfig = ( selectionConfig: IListSelectionConfig, fnOpts?: IListFunctionOptions ) => { list.setSelectionConfig(selectionConfig) if (!fnOpts || fnOpts.withRender) { refreshTable() refreshSelection() } } const disableSelectionConfig = () => { setSelectionConfig(null) } // 设置校验规则 const setValidateConfig = validateConfig => { list.setValidateConfig(validateConfig) refreshValidateConfig() } // 获取URL参数 const getParams = () => params // 设置url const setUrl = (nextUrl: string, fnOpts?: IListFunctionOptions) => { url = nextUrl if (!fnOpts || fnOpts.withFetch) { fetch() } } const getUrl = () => { return url } // 设置query const setQuery = (nextQuery: IListQuery, fnOpts?: IListFunctionOptions) => { query = nextQuery if (!fnOpts || fnOpts.withFetch) { fetch() } } // 适配搜索区域副作用 const getFilterEffects = props => { const noop = () => {} const { effects = noop } = props || {} return ($, actions) => { // 搜索区域初始化完成 $('onFormMount').subscribe(state => { lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_FILTER_MOUNT, ctx: listAPI, payload: state }) }) // 搜索区域values修改 $('onFormValuesChange').subscribe(state => { lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_FILTER_VALUES_CHANGE, ctx: listAPI, payload: state }) }) // 搜索区域字段修改 $('onFieldValueChange').subscribe(state => { lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_FILTER_ITEM_CHANGE, ctx: listAPI, payload: state }) }) // 搜索区域校验开始 $('onFormSubmitValidateStart').subscribe(() => { lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_VALIDATE_START, ctx: listAPI }) }) // 搜索区域校验失败 $('onFormSubmitValidateFailed').subscribe(state => { const { errors, warnings } = state lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_VALIDATE_END, ctx: listAPI, payload: { success: false, errors, warnings } }) }) // 搜索区域校验成功 $('onFormSubmitValidateSuccess').subscribe(state => { const { errors, warnings } = state lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_VALIDATE_END, ctx: listAPI, payload: { success: true, errors, warnings } }) }) effects($, actions) } } const toggleExpandStatus = () => { const filterInstance = list.getFilterInstance() if (expandStatus === 'expand') { expandStatus = 'collapse' filterInstance.notify(ListLifeCycleTypes.ON_LIST_FILTER_ITEM_COLLAPSE) lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_FILTER_ITEM_COLLAPSE, ctx: listAPI }) } else { expandStatus = 'expand' filterInstance.notify(ListLifeCycleTypes.ON_LIST_FILTER_ITEM_EXPAND) lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_FILTER_ITEM_EXPAND, ctx: listAPI }) } } const getExpandStatus = (): ExpandStatus => { return expandStatus } const initSyncFilterData = (executeNow = false) => { // 同步params到搜索区域上 const syncFilterData = {} Object.keys(params || {}).forEach(paramField => { if ( [].concat(paramsFields || []).some(f => f === '*' || f === paramField) ) { syncFilterData[paramField] = params[paramField] } }) // 静默设置到filter上,避免重复通知死循环 if (Object.keys(syncFilterData).length > 0) { lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_INIT_PARAMS_SET, ctx: listAPI, payload: syncFilterData }) listAPI.subscribe(ListLifeCycleTypes.ON_LIST_FILTER_MOUNT, () => { list.setFilterData(syncFilterData) }) if (executeNow) { list.setFilterData(syncFilterData) } } const filterInstance = list.getFilterInstance() if (filterInstance) { filterInstance.subscribe(({ type }) => { if (type === 'onFormSubmit') { listAPI.refresh() } else if (type === ListLifeCycleTypes.ON_FORM_LIST_RESET) { listAPI.reset() } else if (type === ListLifeCycleTypes.ON_FORM_LIST_CLEAR) { listAPI.clear() } }) } } const listAPI: IList = { // 监听相关 notify: (type: string | ListLifeCycleTypes, payload?: any) => { lifeCycles.notify({ type, payload, ctx: listAPI }) }, subscribe: lifeCycles.subscribe, unSubscribe: lifeCycles.unSubscribe, on: (type: string, cb?: any) => { list.on(type, cb) }, removeListener: (type: string, cb?: any) => { list.removeListener(type, cb) }, // emit: (type: string, payload?: any) => { // list.emit(type, payload) // }, refresh, // 更新API setLoading, // 动态刷新loading getLoading: list.getLoading, // 获取当前loading状态 setValidateConfig, getValidateConfig: list.getValidateConfig, setUrl, // 动态切换url getUrl, // 获取url setQuery, // 动态切换query getParams, // 获取url参数 setParams, // 动态设置url参数 // 搜索区域生命周期管理相关 getFilterEffects, // UI相关 search: refresh, // search 按钮 clear, // clear 按钮 reset, // reset 按钮 setCurrentPage, // 分页跳转 setPageSize, // 设置分页大小 // 筛选相关 getSelectionConfig: list.getSelectionConfig, setSelectionConfig, disableSelectionConfig, getSelections: list.getSelections, getEmptyStatus: list.getEmptyStatus, // 渲染取数相关 getTableProps: list.getTableProps, setTableProps, setPaginationDataSource: list.setPaginationDataSource, getPaginationDataSource: list.getPaginationDataSource, getSortConfig: list.getSortConfig, setSortConfig: list.setSortConfig, getMode: list.getMode, getPageData: list.getPageData, // 获取分页数据 setPageData: list.setPageData, // 设置分页数据 getFilterData: list.getFilterData, // 获取搜索框数据 setFilterData: list.setFilterData, // 设置搜索框数据 getFilterProps: list.getFilterProps, // 设置搜索框数据 getFilterInstance: list.getFilterInstance, setFilterInstance: list.setFilterInstance, setFormState: list.setFormState, getFormState: list.getFormState, setFieldState: list.setFieldState, getFieldState: list.getFieldState, getDataSource: list.getDataSource, // 获取页面数据 setDataSource, // 动态更新dataSource getMultipleData: list.getMultipleData, // 获取多实例数据 setMultipleData, // 设置多实例数据 setMultiplePageSize, // 设置多实例分页数据 getExpandStatus, toggleExpandStatus, appendMirrorFilterInstance: list.appendMirrorFilterInstance, getMirrorFilterInstanceList: list.getMirrorFilterInstanceList, initSyncFilterData, setResponseData: list.setResponseData, getResponseData: list.getResponseData, getAllColumns: list.getAllColumns, setAllColumns: list.setAllColumns, setColumns, getColumns: list.getColumns, setEmptyStatus: list.setEmptyStatus, hasSetColumns } initSyncFilterData() if (params && Object.keys(params).length) { setParams(params) } // 初始化即将完成 lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_WILL_INIT, ctx: listAPI }) // 挂载consumer相关渲染订阅事件 // 初始化完成 lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_INIT, ctx: listAPI }) // 挂载完成,执行请求 listAPI.subscribe(ListLifeCycleTypes.ON_LIST_MOUNTED, () => { if (autoLoad && ModeType.URL === mode) { fetch() } }) // 监听字段值改变, 如果命中paramsFields,就同步到url参数上 listAPI.subscribe( ListLifeCycleTypes.ON_LIST_FILTER_ITEM_CHANGE, fieldChangeData => { const { payload: fieldState } = fieldChangeData const { name, value } = fieldState if ([].concat(paramsFields || []).some(f => f === '*' || f === name)) { // 设置filter当前命中的字段值 const nextTargetParams = { [name]: value } lifeCycles.notify({ type: ListLifeCycleTypes.ON_LIST_PARAMS_CHANGE, ctx: listAPI, payload: nextTargetParams }) setParams(nextTargetParams) } } ) // 排序触发时,发起请求 listAPI.subscribe(ListLifeCycleTypes.ON_LIST_SORT, ({ payload }) => { const { sorter } = payload list.setSortConfig({ sorter }) const { sortLocal, ...othersSortConfig } = list.getSortConfig() if (!isFn(sortLocal)) { fetch() } else { const ds = list.getDataSource() const sortDs = sortLocal(ds, othersSortConfig) if (Array.isArray(sortDs)) { list.setPaginationDataSource(sortDs) refreshTable() } } }) return listAPI } export { createList as default, ListLifeCycle, ListLifeCycleTypes }
the_stack
import { expect } from 'chai'; import { Connection } from '@salesforce/core'; import * as path from 'path'; import * as fsExtra from 'fs-extra'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; import { CompletionItem, CompletionItemKind } from 'vscode'; import { extensions, Position, Uri, workspace, commands } from 'vscode'; import { stubMockConnection, spyChannelService, stubFailingMockConnection } from '../testUtilities'; let doc: vscode.TextDocument; let soqlFileUri: Uri; let workspacePath: string; let sandbox: sinon.SinonSandbox; let mockConnection: Connection; const aggregateFunctionItems = [ { label: 'AVG(...)', kind: CompletionItemKind.Function }, { label: 'MAX(...)', kind: CompletionItemKind.Function }, { label: 'MIN(...)', kind: CompletionItemKind.Function }, { label: 'SUM(...)', kind: CompletionItemKind.Function }, { label: 'COUNT(...)', kind: CompletionItemKind.Function }, { label: 'COUNT_DISTINCT(...)', kind: CompletionItemKind.Function } ]; const userFieldItems = [ { label: 'Id', kind: CompletionItemKind.Field, detail: 'id' }, { label: 'Name', kind: CompletionItemKind.Field, detail: 'string' }, { label: 'AccountId', kind: CompletionItemKind.Field, detail: 'reference' }, { label: 'Account', kind: CompletionItemKind.Class, insertText: 'Account.', detail: 'Ref. to Account' }, { label: 'IsDeleted', kind: 4, detail: 'boolean' } ]; // Register special provider to handle "embedded-soql" scheme. // This is the case when working on SOQL blocks inside Apex. In this situation, // SOQL LSP reads sobject metadata from the workspace's filesystem instead of // using jsforce lib (which invokes the remote SF remote API). workspace.registerTextDocumentContentProvider('embedded-soql', { provideTextDocumentContent: (uri: Uri) => { const originalUri = uri.path.replace(/^\//, '').replace(/.soql$/, ''); return workspace.fs .readFile(Uri.parse(originalUri)) .then(content => content.toLocaleString()); } }); describe('Should do completion', async () => { before(() => { // Populate filesystem with sobject's metadata. This is for the embedded-soql case const workspaceDir = path.normalize( __dirname + '/../../../../../system-tests/assets/sfdx-simple/.sfdx' ); const targetDir = path.join(workspaceDir, 'tools', 'soqlMetadata'); const soqlMetadataDir = path.normalize( __dirname + '/../../../../test/vscode-integration/soqlMetadata/' ); if (fsExtra.existsSync(targetDir)) { console.log('Removing existing ' + targetDir); fsExtra.removeSync(targetDir); } fsExtra.mkdirSync(targetDir, { recursive: true }); console.log('Copying ' + soqlMetadataDir + ' to ' + targetDir); fsExtra.copySync(soqlMetadataDir, targetDir, { recursive: true }); const files = fsExtra.readdirSync(targetDir); console.log('Copied ' + files.length + ' files'); }); beforeEach(async () => { workspacePath = workspace.workspaceFolders![0].uri.fsPath; soqlFileUri = Uri.file( path.join(workspacePath, `test_${generateRandomInt()}.soql`) ); sandbox = sinon.createSandbox(); mockConnection = stubMockConnection(sandbox); }); afterEach(async () => { sandbox.restore(); commands.executeCommand('workbench.action.closeActiveEditor'); await workspace.fs.delete(soqlFileUri); }); testCompletion('|', [ { label: 'SELECT', kind: CompletionItemKind.Keyword }, { label: 'SELECT ... FROM ...', kind: CompletionItemKind.Snippet, insertText: 'SELECT $2 FROM $1' } ]); testCompletion('SELECT id FROM |', [ { label: 'Account', kind: CompletionItemKind.Class }, { label: 'User', kind: CompletionItemKind.Class } ]); // Test the case of "embedded-soql" scheme: // SOQL LSP should read sobject metadata from the workspace's filesystem instead of // using jsforce lib (which invokes the remote SF remote API). // See test data at `packages/system-tests/assets/sfdx-simple/.sfdx/tools/soqlMetadata` testCompletion( 'SELECT id FROM |', [ { label: 'Account', kind: CompletionItemKind.Class }, { label: 'Attachment', kind: CompletionItemKind.Class }, { label: 'Case', kind: CompletionItemKind.Class }, { label: 'Contact', kind: CompletionItemKind.Class }, { label: 'Contract', kind: CompletionItemKind.Class }, { label: 'Lead', kind: CompletionItemKind.Class }, { label: 'Note', kind: CompletionItemKind.Class }, { label: 'Opportunity', kind: CompletionItemKind.Class }, { label: 'Order', kind: CompletionItemKind.Class }, { label: 'Pricebook2', kind: CompletionItemKind.Class }, { label: 'PricebookEntry', kind: CompletionItemKind.Class }, { label: 'Product2', kind: CompletionItemKind.Class }, { label: 'RecordType', kind: CompletionItemKind.Class }, { label: 'Report', kind: CompletionItemKind.Class }, { label: 'Task', kind: CompletionItemKind.Class }, { label: 'User', kind: CompletionItemKind.Class } ], { embeddedSoql: true } ); testCompletion('SELECT | FROM Account', [ { label: 'Id', kind: CompletionItemKind.Field, detail: 'id' }, { label: 'Name', kind: CompletionItemKind.Field, detail: 'string' }, { label: 'Description', kind: 4, detail: 'textarea' }, { label: 'CreatedDate', kind: 4, detail: 'datetime' }, { label: 'BillingCity', kind: 4, detail: 'string' }, { label: 'IsDeleted', kind: 4, detail: 'boolean' }, { label: 'LastActivityDate', kind: 4, detail: 'date' }, ...aggregateFunctionItems, { label: '(SELECT ... FROM ...)', kind: CompletionItemKind.Snippet, insertText: '(SELECT $2 FROM $1)' }, { label: 'COUNT()', kind: CompletionItemKind.Keyword }, { label: 'TYPEOF', kind: CompletionItemKind.Keyword } ]); // Test the case of "embedded-soql" scheme: // SOQL LSP should read sobject metadata from the workspace's filesystem instead of // using jsforce lib (which invokes the remote SF remote API). // See test data at `packages/system-tests/assets/sfdx-simple/.sfdx/tools/soqlMetadata` testCompletion( 'SELECT | FROM Account', [ { label: 'Id', kind: CompletionItemKind.Field, detail: 'id' }, { label: 'Name', kind: CompletionItemKind.Field, detail: 'string' }, { label: 'Description', kind: 4, detail: 'textarea' }, { label: 'CreatedDate', kind: 4, detail: 'datetime' }, { label: 'BillingCity', kind: 4, detail: 'string' }, { label: 'IsDeleted', kind: 4, detail: 'boolean' }, { label: 'LastActivityDate', kind: 4, detail: 'date' }, { label: 'Website', kind: 4, detail: 'url' }, { label: 'SystemModstamp', kind: 4, detail: 'datetime' }, { label: 'ShippingPostalCode', kind: 4, detail: 'string' }, ...aggregateFunctionItems, { label: '(SELECT ... FROM ...)', kind: CompletionItemKind.Snippet, insertText: '(SELECT $2 FROM $1)' }, { label: 'COUNT()', kind: CompletionItemKind.Keyword }, { label: 'TYPEOF', kind: CompletionItemKind.Keyword } ], { embeddedSoql: true, allowExtraCompletionItems: true } ); testCompletion('SELECT | FROM User', [ ...userFieldItems, ...aggregateFunctionItems, { label: '(SELECT ... FROM ...)', kind: CompletionItemKind.Snippet, insertText: '(SELECT $2 FROM $1)' }, { label: 'COUNT()', kind: CompletionItemKind.Keyword }, { label: 'TYPEOF', kind: CompletionItemKind.Keyword } ]); testCompletion('SELECT Id FROM Account WHERE |', [ { label: 'Id', kind: CompletionItemKind.Field, detail: 'id' }, { label: 'Name', kind: CompletionItemKind.Field, detail: 'string' }, { label: 'Description', kind: 4, detail: 'textarea' }, { label: 'CreatedDate', kind: 4, detail: 'datetime' }, { label: 'BillingCity', kind: 4, detail: 'string' }, { label: 'IsDeleted', kind: 4, detail: 'boolean' }, { label: 'LastActivityDate', kind: 4, detail: 'date' }, { label: 'NOT', kind: CompletionItemKind.Keyword } ]); const basicOperators = ['IN (', 'NOT IN (', '=', '!=', '<>']; const relativeOperators = ['<', '<=', '>', '>=']; const idOperators = basicOperators; const stringOperators = [...basicOperators, ...relativeOperators, 'LIKE']; testCompletion( 'SELECT Id FROM Account WHERE Id |', idOperators.map(operator => ({ label: operator, kind: CompletionItemKind.Keyword })) ); testCompletion( 'SELECT Id FROM Account WHERE Name |', stringOperators.map(operator => ({ label: operator, kind: CompletionItemKind.Keyword })) ); // Account.Name is not Nillable testCompletion('SELECT Id FROM Account WHERE Name = |', [ { label: 'abc123', kind: CompletionItemKind.Snippet } ]); // Account.BillingCity IS Nillable testCompletion('SELECT Id FROM Account WHERE BillingCity = |', [ { label: 'NULL', kind: CompletionItemKind.Keyword }, { label: 'abc123', kind: CompletionItemKind.Snippet } ]); // Account.BillingCity IS Nillable, however, some operators never accept NULL testCompletion('SELECT Id FROM Account WHERE BillingCity < |', [ { label: 'abc123', kind: CompletionItemKind.Snippet } ]); testCompletion('SELECT Id FROM Account WHERE BillingCity <= |', [ { label: 'abc123', kind: CompletionItemKind.Snippet } ]); testCompletion('SELECT Id FROM Account WHERE BillingCity > |', [ { label: 'abc123', kind: CompletionItemKind.Snippet } ]); testCompletion('SELECT Id FROM Account WHERE BillingCity >= |', [ { label: 'abc123', kind: CompletionItemKind.Snippet } ]); testCompletion('SELECT Id FROM Account WHERE BillingCity LIKE |', [ { label: 'abc123', kind: CompletionItemKind.Snippet } ]); testCompletion( 'SELECT Id FROM Account WHERE IsDeleted = |', ['TRUE', 'FALSE'].map(booleanValue => ({ label: booleanValue, kind: CompletionItemKind.Value })) ); testCompletion('SELECT Channel FROM QuickText WHERE Channel = |', [ { label: 'NULL', kind: CompletionItemKind.Keyword }, ...['Email', 'Portal', 'Phone'].map(booleanValue => ({ label: booleanValue, kind: CompletionItemKind.Value })) ]); // NOTE: NULL not supported in INCLUDES/EXCLUDES list testCompletion('SELECT Channel FROM QuickText WHERE Channel INCLUDES(|', [ ...['Email', 'Portal', 'Phone'].map(booleanValue => ({ label: booleanValue, kind: CompletionItemKind.Value })) ]); testCompletion( 'SELECT Id FROM Account WHERE CreatedDate < |', [ { label: 'YYYY-MM-DDThh:mm:ssZ', kind: CompletionItemKind.Snippet }, { label: 'YESTERDAY', kind: CompletionItemKind.Value }, { label: 'LAST_90_DAYS', kind: CompletionItemKind.Value }, { label: 'LAST_N_DAYS:n', kind: CompletionItemKind.Snippet } ], { allowExtraCompletionItems: true } ); testCompletion( 'SELECT Id FROM Account WHERE LastActivityDate < |', [ { label: 'YYYY-MM-DD', kind: CompletionItemKind.Snippet }, { label: 'YESTERDAY', kind: CompletionItemKind.Value }, { label: 'LAST_90_DAYS', kind: CompletionItemKind.Value }, { label: 'LAST_N_DAYS:n', kind: CompletionItemKind.Snippet } ], { allowExtraCompletionItems: true } ); testCompletion('SELECT Id, COUNT(Name) FROM Account GROUP BY |', [ // NOTE: CreatedDate and Description are NOT groupable, so we DON'T them: { label: '★ Id', kind: CompletionItemKind.Field, detail: 'id' }, { label: 'Name', kind: CompletionItemKind.Field, detail: 'string' }, { label: 'BillingCity', kind: CompletionItemKind.Field, detail: 'string' }, { label: 'IsDeleted', kind: CompletionItemKind.Field, detail: 'boolean' }, { label: 'LastActivityDate', kind: CompletionItemKind.Field, detail: 'date' }, { label: 'CUBE', kind: CompletionItemKind.Keyword }, { label: 'ROLLUP', kind: CompletionItemKind.Keyword } ]); testCompletion('SELECT Id FROM Account ORDER BY |', [ // NOTE: Description is NOT sorteable, so we DON'T expect it: { label: 'Id', kind: CompletionItemKind.Field, detail: 'id' }, { label: 'CreatedDate', kind: CompletionItemKind.Field, detail: 'datetime' }, { label: 'Name', kind: CompletionItemKind.Field, detail: 'string' }, { label: 'BillingCity', kind: CompletionItemKind.Field, detail: 'string' }, { label: 'IsDeleted', kind: CompletionItemKind.Field, detail: 'boolean' }, { label: 'LastActivityDate', kind: CompletionItemKind.Field, detail: 'date' } ]); testCompletion('SELECT Id, (SELECT FROM |) FROM Account', [ { label: 'Users', kind: CompletionItemKind.Class, detail: 'User' } ]); testCompletion('SELECT Id, (SELECT | FROM Users) FROM Account', [ ...userFieldItems, { label: 'TYPEOF', kind: CompletionItemKind.Keyword } ]); testCompletion( 'SELECT Id, (SELECT Name FROM Users ORDER BY |) FROM Account', [ // only sortable fields of User: { label: 'Id', kind: CompletionItemKind.Field, detail: 'id' }, { label: 'Name', kind: CompletionItemKind.Field, detail: 'string' }, { label: 'IsDeleted', kind: 4, detail: 'boolean' } ] ); // Semi-join testCompletion('SELECT Id FROM Account WHERE Id IN (SELECT | FROM User)', [ { label: 'Id', kind: CompletionItemKind.Field, detail: 'id' }, { label: 'AccountId', kind: CompletionItemKind.Field, detail: 'reference' } ]); }); describe('Should not do completion on metadata errors', async () => { const workspaceDir = path.normalize( __dirname + '/../../../../../system-tests/assets/sfdx-simple/.sfdx' ); const soqlMetadataDir = path.join(workspaceDir, 'tools', 'soqlMetadata'); before(() => { if (fsExtra.existsSync(soqlMetadataDir)) { console.log('Removing existing ' + soqlMetadataDir); fsExtra.removeSync(soqlMetadataDir); } }); beforeEach(async () => { workspacePath = workspace.workspaceFolders![0].uri.fsPath; soqlFileUri = Uri.file( path.join(workspacePath, `test_${generateRandomInt()}.soql`) ); sandbox = sinon.createSandbox(); mockConnection = stubFailingMockConnection(sandbox); }); afterEach(async () => { sandbox.restore(); commands.executeCommand('workbench.action.closeActiveEditor'); await workspace.fs.delete(soqlFileUri); }); testCompletion('SELECT Id FROM |', [], { expectChannelMsg: 'ERROR: We can’t retrieve ' + 'the objects in the org. Make sure that you’re connected to an authorized org ' + 'and have permissions to view the objects in the org.' }); testCompletion('SELECT Id FROM |', [], { embeddedSoql: true, expectChannelMsg: 'ERROR: We can’t retrieve list of objects. ' + 'Expected JSON files in directory: ' + soqlMetadataDir + '.' }); testCompletion( 'SELECT | FROM Account', [ ...aggregateFunctionItems, { label: '(SELECT ... FROM ...)', kind: CompletionItemKind.Snippet, insertText: '(SELECT $2 FROM $1)' }, { label: 'COUNT()', kind: CompletionItemKind.Keyword }, { label: 'TYPEOF', kind: CompletionItemKind.Keyword } ], { expectChannelMsg: 'ERROR: We can’t retrieve the fields for Account. Make sure that you’re connected ' + 'to an authorized org and have permissions to view the object and fields.' } ); testCompletion( 'SELECT | FROM Account', [ ...aggregateFunctionItems, { label: '(SELECT ... FROM ...)', kind: CompletionItemKind.Snippet, insertText: '(SELECT $2 FROM $1)' }, { label: 'COUNT()', kind: CompletionItemKind.Keyword }, { label: 'TYPEOF', kind: CompletionItemKind.Keyword } ], { embeddedSoql: true, expectChannelMsg: 'ERROR: We can’t retrieve the fields for Account. ' + 'Expected metadata file at: ' + path.join(soqlMetadataDir, '*', 'Account.json.') // [soqlMetadataDir, '*', 'Account.json.'].join(path.sep) } ); }); const shouldIgnoreCompletionItem = (i: CompletionItem) => i.kind !== CompletionItemKind.Text; function testCompletion( soqlTextWithCursorMarker: string, expectedCompletionItems: CompletionItem[], options: { cursorChar?: string; expectChannelMsg?: string; allowExtraCompletionItems?: boolean; embeddedSoql?: boolean; only?: boolean; skip?: boolean; } = {} ) { const { cursorChar = '|', expectChannelMsg } = options; const itFn = options.skip ? xit : options.only ? it.only : it; itFn(soqlTextWithCursorMarker, async () => { const position = await prepareSOQLFileAndGetCursorPosition( soqlTextWithCursorMarker, soqlFileUri, cursorChar ); const channelServiceSpy = spyChannelService(sandbox); const docUri = options.embeddedSoql ? Uri.parse( `embedded-soql://soql/${encodeURIComponent( soqlFileUri.toString() )}.soql` ) : soqlFileUri; let passed = false; for (let tries = 3; !passed && tries > 0; tries--) { try { const actualCompletionItems = ((await vscode.commands.executeCommand( 'vscode.executeCompletionItemProvider', docUri, position )) as vscode.CompletionList).items; const pickMainItemKeys = (item: CompletionItem) => ({ label: item.label, kind: item.kind, detail: item.detail }); const simplifiedActualCompletionItems = actualCompletionItems .filter(shouldIgnoreCompletionItem) .map(pickMainItemKeys); const simplifiedExpectedCompletionItems = expectedCompletionItems.map( pickMainItemKeys ); if (options.allowExtraCompletionItems) { expect(simplifiedActualCompletionItems).to.include.deep.members( simplifiedExpectedCompletionItems ); } else { expect(simplifiedActualCompletionItems).to.have.deep.members( simplifiedExpectedCompletionItems ); } if (expectChannelMsg) { expect(channelServiceSpy.called).to.be.true; console.log(channelServiceSpy.getCalls()); expect(channelServiceSpy.lastCall.args[0].toLowerCase()).to.equal( expectChannelMsg.toLowerCase() ); } passed = true; } catch (failure) { if (tries === 1) { console.log(failure); throw failure; } else { // give it a bit of time before trying again channelServiceSpy.resetHistory(); await sleep(100); } } } }); } async function sleep(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)); } export async function activate(docUri: vscode.Uri) { const ext = extensions.getExtension('salesforce.salesforcedx-vscode-soql')!; await ext.activate(); try { doc = await vscode.workspace.openTextDocument(docUri); await vscode.window.showTextDocument(doc); } catch (e) { console.error(e); } } async function prepareSOQLFileAndGetCursorPosition( soqlTextWithCursorMarker: string, fileUri: vscode.Uri, cursorChar: string = '|' ): Promise<vscode.Position> { const position = getCursorPosition(soqlTextWithCursorMarker, cursorChar); const soqlText = soqlTextWithCursorMarker.replace(cursorChar, ''); const encoder = new TextEncoder(); await workspace.fs.writeFile(fileUri, encoder.encode(soqlText)); await activate(fileUri); return position; } function getCursorPosition(text: string, cursorChar: string = '|'): Position { for (const [line, lineText] of text.split('\n').entries()) { const column = lineText.indexOf(cursorChar); if (column >= 0) return new Position(line, column); } throw new Error(`Cursor ${cursorChar} not found in ${text} !`); } function generateRandomInt() { return Math.floor(Math.random() * Math.floor(Number.MAX_SAFE_INTEGER)); }
the_stack
import { useState, useCallback } from 'react'; import { useFetchData, useFetchStatus, FetchStatus } from 'core/providers/base/hooks'; import { getAllMetricsGroupsById, getMetricsGroupsResumeById, getAllMetricsProviders, createMetric, updateMetric, getAllDataSourceMetrics as getAllDataSourceMetricsRequest, createMetricGroup, updateMetricGroup, deleteMetricGroup, deleteMetricByMetricId, deleteActionByActionId, getChartDataByQuery, getAllActionsTypes, createAction, updateAction, getGroupActionById } from 'core/providers/metricsGroups'; import { buildParams, URLParams } from 'core/utils/query'; import { useDispatch } from 'core/state/hooks'; import { toogleNotification } from 'core/components/Notification/state/actions'; import { MetricsGroup, MetricsGroupsResume, Metric, DataSource, ChartDataByQuery, ActionGroupPayload, ActionType, Action } from './types'; import { DetailedErrorResponse } from 'core/interfaces/ValidationError'; export const useMetricsGroupsResume = (): { getMetricsgroupsResume: Function; resume: MetricsGroupsResume[]; status: FetchStatus; } => { const getMetricsGroupsResumeData = useFetchData<MetricsGroupsResume[]>( getMetricsGroupsResumeById ); const status = useFetchStatus(); const [resume, setResume] = useState([]); const getMetricsgroupsResume = useCallback( async (payload: URLParams) => { try { status.pending(); const params = buildParams(payload); const resumeResponse = await getMetricsGroupsResumeData(params); setResume(resumeResponse); status.resolved(); return resumeResponse; } catch (e) { status.rejected(); } }, [getMetricsGroupsResumeData, status] ); return { getMetricsgroupsResume, resume, status }; }; export const useMetricsGroups = (): { getMetricsGroups: Function; metricsGroups: MetricsGroup[]; status: FetchStatus; } => { const getMetricsGroupData = useFetchData<MetricsGroup[]>( getAllMetricsGroupsById ); const status = useFetchStatus(); const [metricsGroups, setMetricsGroups] = useState<MetricsGroup[]>([]); const getMetricsGroups = useCallback( async (circleId: string) => { try { status.pending(); const metricsGroupsResponse = await getMetricsGroupData(circleId); setMetricsGroups(metricsGroupsResponse); status.resolved(); return metricsGroupsResponse; } catch (e) { status.rejected(); } }, [getMetricsGroupData, status] ); return { getMetricsGroups, metricsGroups, status }; }; export const useMetricProviders = () => { const getMetricProvidersData = useFetchData<DataSource[]>( getAllMetricsProviders ); const [providers, setProviders] = useState([]); const getMetricsProviders = useCallback(async () => { try { const providersResponse = await getMetricProvidersData(); setProviders(providersResponse); return providersResponse; } catch (e) { console.log(e); } }, [getMetricProvidersData]); return { getMetricsProviders, providers }; }; export const useSaveMetric = (metricId: string) => { const saveRequest = metricId ? updateMetric : createMetric; const saveMetricPayload = useFetchData<Metric>(saveRequest); const status = useFetchStatus(); const dispatch = useDispatch(); const saveMetric = useCallback( async (metricsGroupsId: string, metricPayload: Metric) => { try { status.pending(); const savedMetricResponse = await saveMetricPayload( metricsGroupsId, metricPayload ); status.resolved(); return savedMetricResponse; } catch (responseError) { status.rejected(); responseError.json().then((error: DetailedErrorResponse) => { const errorMessage = error?.errors?.[0]?.detail; dispatch( toogleNotification({ text: errorMessage ?? 'Error on save metric', status: 'error' }) ); }); } }, [saveMetricPayload, dispatch, status] ); return { saveMetric, status }; }; export const useProviderMetrics = () => { const getAllDataSourceMetricsData = useFetchData<string[]>( getAllDataSourceMetricsRequest ); const getAllDataSourceMetrics = useCallback( async (datasourceId: string) => { try { const response = await getAllDataSourceMetricsData(datasourceId); return response; } catch (e) { console.log(e); } }, [getAllDataSourceMetricsData] ); return { getAllDataSourceMetrics }; }; export const useCreateMetricsGroup = (metricGroupId: string) => { const saveMetricGroupRequest = metricGroupId ? updateMetricGroup : createMetricGroup; const createMetricsGroupPayload = useFetchData<MetricsGroup>( saveMetricGroupRequest ); const status = useFetchStatus(); const dispatch = useDispatch(); const createMetricsGroup = useCallback( async (name: string, circleId: string) => { try { status.pending(); const createdMetricsGroupResponse = await createMetricsGroupPayload( { name, circleId }, metricGroupId ); status.resolved(); return createdMetricsGroupResponse; } catch (responseError) { status.rejected(); responseError.json().then((error: DetailedErrorResponse) => { const errorMessage = error?.errors?.[0]?.detail; dispatch( toogleNotification({ text: errorMessage ?? 'Error on save metric group', status: 'error' }) ); }); } }, [createMetricsGroupPayload, status, dispatch, metricGroupId] ); return { createMetricsGroup, status }; }; export const useDeleteMetricsGroup = () => { const deleteMetricsGroupRequest = useFetchData<MetricsGroup>( deleteMetricGroup ); const dispatch = useDispatch(); const deleteMetricsGroup = useCallback( async (metricsGroupId: string) => { try { const deleteMetricsGroupResponse = await deleteMetricsGroupRequest( metricsGroupId ); dispatch( toogleNotification({ text: `Success deleting metrics group`, status: 'success' }) ); return deleteMetricsGroupResponse; } catch (e) { dispatch( toogleNotification({ text: `Error deleting metrics group`, status: 'error' }) ); } }, [deleteMetricsGroupRequest, dispatch] ); return { deleteMetricsGroup }; }; export const useDeleteMetric = () => { const deleteMetricRequest = useFetchData<MetricsGroup>( deleteMetricByMetricId ); const dispatch = useDispatch(); const deleteMetric = useCallback( async (metricsGroupId: string, metricId: string) => { try { const deleteMetricResponse = await deleteMetricRequest( metricsGroupId, metricId ); dispatch( toogleNotification({ text: `Success deleting metric`, status: 'success' }) ); return deleteMetricResponse; } catch (e) { dispatch( toogleNotification({ text: `Error metric delete`, status: 'error' }) ); } }, [deleteMetricRequest, dispatch] ); return { deleteMetric }; }; export const useMetricQuery = () => { const getMetricByQueryRequest = useFetchData<ChartDataByQuery>( getChartDataByQuery ); const dispatch = useDispatch(); const getMetricByQuery = useCallback( async (metricsGroupId: string, payload: URLParams) => { try { const params = buildParams(payload); const metricByQueryResponse = await getMetricByQueryRequest( metricsGroupId, params ); return metricByQueryResponse; } catch (responseError) { dispatch( toogleNotification({ text: 'Error on loading metric chart data', status: 'error' }) ); } }, [getMetricByQueryRequest, dispatch] ); return { getMetricByQuery }; }; export const useActionTypes = () => { const getAllActionsTypesRequest = useFetchData<ActionType[]>( getAllActionsTypes ); const getAllActionsTypesData = useCallback(async () => { try { const response = await getAllActionsTypesRequest(); return response; } catch (e) { console.log(e); } }, [getAllActionsTypesRequest]); return { getAllActionsTypesData }; }; export const useSaveAction = (actionId?: string) => { const saveRequest = actionId ? updateAction : createAction; const saveActionPayload = useFetchData<ActionGroupPayload>(saveRequest); const status = useFetchStatus(); const dispatch = useDispatch(); const saveAction = useCallback( async (actionGroupPayload: ActionGroupPayload) => { try { status.pending(); const savedActionResponse = await saveActionPayload( actionGroupPayload, actionId ); status.resolved(); dispatch( toogleNotification({ text: `The action ${actionGroupPayload.nickname} was successfully ${actionId ? `edit` : `added` }`, status: 'success' }) ); return savedActionResponse; } catch (error) { status.rejected(); dispatch( toogleNotification({ text: `An error occurred while trying to create the ${actionGroupPayload.nickname } ${actionId ? `edit` : `added`}`, status: 'error' }) ); } }, [saveActionPayload, status, dispatch, actionId] ); return { saveAction, status }; }; export const useDeleteAction = () => { const deleteActionRequest = useFetchData<MetricsGroup>( deleteActionByActionId ); const dispatch = useDispatch(); const deleteAction = useCallback( async (actionId: string, actionName: string) => { try { const deleteActionResponse = await deleteActionRequest(actionId); dispatch( toogleNotification({ text: `The action ${actionName} was successfully deleted.`, status: 'success' }) ); return deleteActionResponse; } catch (e) { dispatch( toogleNotification({ text: `Error deleting the action ${actionName}`, status: 'error' }) ); } }, [deleteActionRequest, dispatch] ); return { deleteAction }; }; export const useActionTypeById = () => { const getActionGroupById = useFetchData<Action>(getGroupActionById); const [isLoading, setIsLoading] = useState(false); const [actionData, setActionData] = useState<Action>(); const getActionGroup = useCallback( async (actionId: string) => { try { setIsLoading(true); const response = await getActionGroupById(actionId); setActionData(response); setIsLoading(false); return response; } catch (e) { console.log(e); } }, [getActionGroupById] ); return { getActionGroup, actionData, isLoading }; };
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a Synapse Linked Service. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleAccount = new azure.storage.Account("exampleAccount", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * accountKind: "BlobStorage", * accountTier: "Standard", * accountReplicationType: "LRS", * }); * const exampleDataLakeGen2Filesystem = new azure.storage.DataLakeGen2Filesystem("exampleDataLakeGen2Filesystem", {storageAccountId: exampleAccount.id}); * const exampleWorkspace = new azure.synapse.Workspace("exampleWorkspace", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * storageDataLakeGen2FilesystemId: exampleDataLakeGen2Filesystem.id, * sqlAdministratorLogin: "sqladminuser", * sqlAdministratorLoginPassword: "H@Sh1CoR3!", * managedVirtualNetworkEnabled: true, * }); * const exampleFirewallRule = new azure.synapse.FirewallRule("exampleFirewallRule", { * synapseWorkspaceId: exampleWorkspace.id, * startIpAddress: "0.0.0.0", * endIpAddress: "255.255.255.255", * }); * const exampleLinkedService = new azure.synapse.LinkedService("exampleLinkedService", { * synapseWorkspaceId: exampleWorkspace.id, * type: "AzureBlobStorage", * typePropertiesJson: `{ * "connectionString": "${azurerm_storage_account.test.primary_connection_string}" * } * `, * }, { * dependsOn: [exampleFirewallRule], * }); * ``` * * ## Import * * Synapse Linked Services can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:synapse/linkedService:LinkedService example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Synapse/workspaces/workspace1/linkedservices/linkedservice1 * ``` */ export class LinkedService extends pulumi.CustomResource { /** * Get an existing LinkedService resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: LinkedServiceState, opts?: pulumi.CustomResourceOptions): LinkedService { return new LinkedService(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:synapse/linkedService:LinkedService'; /** * Returns true if the given object is an instance of LinkedService. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is LinkedService { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === LinkedService.__pulumiType; } /** * A map of additional properties to associate with the Synapse Linked Service. */ public readonly additionalProperties!: pulumi.Output<{[key: string]: string} | undefined>; /** * List of tags that can be used for describing the Synapse Linked Service. */ public readonly annotations!: pulumi.Output<string[] | undefined>; /** * The description for the Synapse Linked Service. */ public readonly description!: pulumi.Output<string | undefined>; /** * A `integrationRuntime` block as defined below. */ public readonly integrationRuntime!: pulumi.Output<outputs.synapse.LinkedServiceIntegrationRuntime | undefined>; /** * The name which should be used for this Synapse Linked Service. Changing this forces a new Synapse Linked Service to be created. */ public readonly name!: pulumi.Output<string>; /** * A map of parameters to associate with the Synapse Linked Service. */ public readonly parameters!: pulumi.Output<{[key: string]: string} | undefined>; /** * The Synapse Workspace ID in which to associate the Linked Service with. Changing this forces a new Synapse Linked Service to be created. */ public readonly synapseWorkspaceId!: pulumi.Output<string>; /** * The type of data stores that will be connected to Synapse. For full list of supported data stores, please refer to [Azure Synapse connector](https://docs.microsoft.com/en-us/azure/data-factory/connector-overview). Changing this forces a new Synapse Linked Service to be created. */ public readonly type!: pulumi.Output<string>; /** * A JSON object that contains the properties of the Synapse Linked Service. */ public readonly typePropertiesJson!: pulumi.Output<string>; /** * Create a LinkedService resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: LinkedServiceArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: LinkedServiceArgs | LinkedServiceState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as LinkedServiceState | undefined; inputs["additionalProperties"] = state ? state.additionalProperties : undefined; inputs["annotations"] = state ? state.annotations : undefined; inputs["description"] = state ? state.description : undefined; inputs["integrationRuntime"] = state ? state.integrationRuntime : undefined; inputs["name"] = state ? state.name : undefined; inputs["parameters"] = state ? state.parameters : undefined; inputs["synapseWorkspaceId"] = state ? state.synapseWorkspaceId : undefined; inputs["type"] = state ? state.type : undefined; inputs["typePropertiesJson"] = state ? state.typePropertiesJson : undefined; } else { const args = argsOrState as LinkedServiceArgs | undefined; if ((!args || args.synapseWorkspaceId === undefined) && !opts.urn) { throw new Error("Missing required property 'synapseWorkspaceId'"); } if ((!args || args.type === undefined) && !opts.urn) { throw new Error("Missing required property 'type'"); } if ((!args || args.typePropertiesJson === undefined) && !opts.urn) { throw new Error("Missing required property 'typePropertiesJson'"); } inputs["additionalProperties"] = args ? args.additionalProperties : undefined; inputs["annotations"] = args ? args.annotations : undefined; inputs["description"] = args ? args.description : undefined; inputs["integrationRuntime"] = args ? args.integrationRuntime : undefined; inputs["name"] = args ? args.name : undefined; inputs["parameters"] = args ? args.parameters : undefined; inputs["synapseWorkspaceId"] = args ? args.synapseWorkspaceId : undefined; inputs["type"] = args ? args.type : undefined; inputs["typePropertiesJson"] = args ? args.typePropertiesJson : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(LinkedService.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering LinkedService resources. */ export interface LinkedServiceState { /** * A map of additional properties to associate with the Synapse Linked Service. */ additionalProperties?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * List of tags that can be used for describing the Synapse Linked Service. */ annotations?: pulumi.Input<pulumi.Input<string>[]>; /** * The description for the Synapse Linked Service. */ description?: pulumi.Input<string>; /** * A `integrationRuntime` block as defined below. */ integrationRuntime?: pulumi.Input<inputs.synapse.LinkedServiceIntegrationRuntime>; /** * The name which should be used for this Synapse Linked Service. Changing this forces a new Synapse Linked Service to be created. */ name?: pulumi.Input<string>; /** * A map of parameters to associate with the Synapse Linked Service. */ parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The Synapse Workspace ID in which to associate the Linked Service with. Changing this forces a new Synapse Linked Service to be created. */ synapseWorkspaceId?: pulumi.Input<string>; /** * The type of data stores that will be connected to Synapse. For full list of supported data stores, please refer to [Azure Synapse connector](https://docs.microsoft.com/en-us/azure/data-factory/connector-overview). Changing this forces a new Synapse Linked Service to be created. */ type?: pulumi.Input<string>; /** * A JSON object that contains the properties of the Synapse Linked Service. */ typePropertiesJson?: pulumi.Input<string>; } /** * The set of arguments for constructing a LinkedService resource. */ export interface LinkedServiceArgs { /** * A map of additional properties to associate with the Synapse Linked Service. */ additionalProperties?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * List of tags that can be used for describing the Synapse Linked Service. */ annotations?: pulumi.Input<pulumi.Input<string>[]>; /** * The description for the Synapse Linked Service. */ description?: pulumi.Input<string>; /** * A `integrationRuntime` block as defined below. */ integrationRuntime?: pulumi.Input<inputs.synapse.LinkedServiceIntegrationRuntime>; /** * The name which should be used for this Synapse Linked Service. Changing this forces a new Synapse Linked Service to be created. */ name?: pulumi.Input<string>; /** * A map of parameters to associate with the Synapse Linked Service. */ parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The Synapse Workspace ID in which to associate the Linked Service with. Changing this forces a new Synapse Linked Service to be created. */ synapseWorkspaceId: pulumi.Input<string>; /** * The type of data stores that will be connected to Synapse. For full list of supported data stores, please refer to [Azure Synapse connector](https://docs.microsoft.com/en-us/azure/data-factory/connector-overview). Changing this forces a new Synapse Linked Service to be created. */ type: pulumi.Input<string>; /** * A JSON object that contains the properties of the Synapse Linked Service. */ typePropertiesJson: pulumi.Input<string>; }
the_stack
import { expect } from "chai"; import React from "react"; import sinon from "sinon"; import { fireEvent, render } from "@testing-library/react"; import { TimeField, TimeSpec } from "../../components-react/datepicker/TimeField"; import TestUtils from "../TestUtils"; import { SpecialKey, TimeDisplay } from "@itwin/appui-abstract"; describe("<TimeField />", () => { let renderSpy: sinon.SinonSpy; const zeroTime: TimeSpec = { hours: 0, minutes: 15, seconds: 58, }; const amTime: TimeSpec = { hours: 9, minutes: 15, seconds: 58, }; const pmTime: TimeSpec = { hours: 15, minutes: 14, seconds: 13, }; before(async () => { await TestUtils.initializeUiComponents(); }); beforeEach(() => { sinon.restore(); renderSpy = sinon.spy(); }); after(() => { TestUtils.terminateUiComponents(); }); it("should render zeroTime", () => { const renderedComponent = render(<TimeField time={zeroTime} timeDisplay={TimeDisplay.H12MC} readOnly={true} />); const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(3); expect(inputs[0].value).to.eq("12"); expect(inputs[1].value).to.eq("15"); expect(inputs[2].value).to.eq("timepicker.day-period-am"); expect(inputs[0].disabled); expect(inputs[1].disabled); expect(inputs[2].disabled); }); it("should render read only inputs", () => { const renderedComponent = render(<TimeField time={amTime} timeDisplay={TimeDisplay.H12MC} readOnly={true} />); const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(3); expect(inputs[0].value).to.eq("09"); expect(inputs[1].value).to.eq("15"); expect(inputs[2].value).to.eq("timepicker.day-period-am"); expect(inputs[0].disabled); expect(inputs[1].disabled); expect(inputs[2].disabled); }); it("should render with day am period", () => { const renderedComponent = render(<TimeField time={amTime} timeDisplay={TimeDisplay.H12MC} readOnly={false} />); const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(3); expect(inputs[0].value).to.eq("09"); expect(inputs[1].value).to.eq("15"); expect(inputs[2].value).to.eq("timepicker.day-period-am"); }); it("should render with pm period", () => { const renderedComponent = render(<TimeField time={pmTime} timeDisplay={TimeDisplay.H12MSC} readOnly={false} />); const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(4); expect(inputs[0].value).to.eq("03"); expect(inputs[1].value).to.eq("14"); expect(inputs[2].value).to.eq("13"); expect(inputs[3].value).to.eq("timepicker.day-period-pm"); }); it("should render with 24 hour display (no seconds)", () => { const renderedComponent = render(<TimeField time={amTime} timeDisplay={TimeDisplay.H24M} readOnly={false} />); const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(2); expect(inputs[0].value).to.eq("09"); expect(inputs[1].value).to.eq("15"); }); it("should render with 24 hour display (w/seconds)", () => { const renderedComponent = render(<TimeField time={pmTime} timeDisplay={TimeDisplay.H24MS} readOnly={false} />); const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(3); expect(inputs[0].value).to.eq("15"); expect(inputs[1].value).to.eq("14"); expect(inputs[2].value).to.eq("13"); }); it("should trigger time hour change", () => { const renderedComponent = render(<TimeField time={amTime} timeDisplay={TimeDisplay.H12MC} onTimeChange={renderSpy} readOnly={false} />); // renderedComponent.debug(); expect(renderedComponent).not.to.be.undefined; const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(3); const hour = inputs[0]; const cycle = inputs[2]; expect(hour.value).to.eq("09"); fireEvent.keyDown(hour, { key: SpecialKey.ArrowUp }); expect(renderSpy).to.be.called; expect(hour.value).to.eq("10"); fireEvent.keyDown(hour, { key: SpecialKey.ArrowDown }); fireEvent.keyDown(hour, { key: SpecialKey.ArrowDown }); expect(hour.value).to.eq("08"); fireEvent.change(hour, { target: { value: "06" } }); fireEvent.keyDown(hour, { key: SpecialKey.Enter }); expect(hour.value).to.eq("06"); fireEvent.change(hour, { target: { value: "01" } }); fireEvent.keyDown(hour, { key: SpecialKey.Enter }); fireEvent.keyDown(hour, { key: SpecialKey.ArrowDown }); expect(hour.value).to.eq("12"); expect(cycle.value).to.eq("timepicker.day-period-am"); fireEvent.keyDown(hour, { key: SpecialKey.ArrowDown }); fireEvent.change(hour, { target: { value: "11" } }); fireEvent.keyDown(hour, { key: SpecialKey.Enter }); fireEvent.keyDown(hour, { key: SpecialKey.ArrowUp }); expect(hour.value).to.eq("12"); expect(cycle.value).to.eq("timepicker.day-period-pm"); // invalid time should cause input to revert to valid time hour.focus(); fireEvent.change(hour, { target: { value: "26" } }); // fireEvent.keyDown(hour, { key: SpecialKey.Enter }); hour.blur(); expect(hour.value).to.eq("12"); hour.focus(); fireEvent.change(hour, { target: { value: "08" } }); hour.blur(); expect(hour.value).to.eq("08"); expect(cycle.value).to.eq("timepicker.day-period-am"); }); it("should trigger time minute change", () => { const renderedComponent = render(<TimeField time={amTime} timeDisplay={TimeDisplay.H12MC} onTimeChange={renderSpy} readOnly={false} />); // renderedComponent.debug(); expect(renderedComponent).not.to.be.undefined; const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(3); const minute = inputs[1]; expect(minute.value).to.eq("15"); fireEvent.keyDown(minute, { key: SpecialKey.ArrowUp }); expect(renderSpy).to.be.called; expect(minute.value).to.eq("16"); fireEvent.keyDown(minute, { key: SpecialKey.ArrowDown }); fireEvent.keyDown(minute, { key: SpecialKey.ArrowDown }); expect(minute.value).to.eq("14"); fireEvent.change(minute, { target: { value: "30" } }); fireEvent.keyDown(minute, { key: SpecialKey.Enter }); expect(minute.value).to.eq("30"); // invalid time should cause input to revert to valid time minute.focus(); fireEvent.change(minute, { target: { value: "66" } }); minute.blur(); expect(minute.value).to.eq("30"); fireEvent.keyDown(minute, { key: SpecialKey.Home }); expect(minute.value).to.eq("00"); fireEvent.keyDown(minute, { key: SpecialKey.ArrowDown }); expect(minute.value).to.eq("59"); fireEvent.keyDown(minute, { key: SpecialKey.End }); expect(minute.value).to.eq("59"); fireEvent.keyDown(minute, { key: SpecialKey.ArrowUp }); expect(minute.value).to.eq("00"); }); it("should trigger time seconds change", () => { const renderedComponent = render(<TimeField time={amTime} timeDisplay={TimeDisplay.H12MSC} onTimeChange={renderSpy} readOnly={false} />); // renderedComponent.debug(); expect(renderedComponent).not.to.be.undefined; const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(4); const seconds = inputs[2]; expect(seconds.value).to.eq("58"); fireEvent.keyDown(seconds, { key: SpecialKey.ArrowUp }); expect(renderSpy).to.be.called; expect(seconds.value).to.eq("59"); fireEvent.keyDown(seconds, { key: SpecialKey.ArrowDown }); fireEvent.keyDown(seconds, { key: SpecialKey.ArrowDown }); expect(seconds.value).to.eq("57"); fireEvent.keyDown(seconds, { key: SpecialKey.ArrowUp }); fireEvent.keyDown(seconds, { key: SpecialKey.ArrowUp }); fireEvent.keyDown(seconds, { key: SpecialKey.ArrowUp }); expect(seconds.value).to.eq("00"); fireEvent.change(seconds, { target: { value: "30" } }); fireEvent.keyDown(seconds, { key: SpecialKey.Enter }); expect(seconds.value).to.eq("30"); // invalid time should cause input to revert to valid time seconds.focus(); fireEvent.change(seconds, { target: { value: "66" } }); seconds.blur(); expect(seconds.value).to.eq("30"); fireEvent.keyDown(seconds, { key: SpecialKey.Home }); expect(seconds.value).to.eq("00"); fireEvent.keyDown(seconds, { key: SpecialKey.ArrowDown }); expect(seconds.value).to.eq("59"); fireEvent.keyDown(seconds, { key: SpecialKey.End }); expect(seconds.value).to.eq("59"); }); it("should trigger time period change", () => { const renderedComponent = render(<TimeField time={amTime} timeDisplay={TimeDisplay.H12MSC} onTimeChange={renderSpy} readOnly={false} />); // renderedComponent.debug(); expect(renderedComponent).not.to.be.undefined; const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(4); const cycle = inputs[3]; const hour = inputs[0]; expect(cycle.value).to.eq("timepicker.day-period-am"); fireEvent.keyDown(cycle, { key: SpecialKey.ArrowUp }); expect(renderSpy).to.be.called; expect(cycle.value).to.eq("timepicker.day-period-pm"); fireEvent.keyDown(cycle, { key: SpecialKey.ArrowDown }); expect(cycle.value).to.eq("timepicker.day-period-am"); fireEvent.keyDown(cycle, { key: SpecialKey.End }); expect(cycle.value).to.eq("timepicker.day-period-pm"); fireEvent.keyDown(cycle, { key: "a" }); expect(cycle.value).to.eq("timepicker.day-period-am"); fireEvent.keyDown(cycle, { key: "p" }); expect(cycle.value).to.eq("timepicker.day-period-pm"); fireEvent.keyDown(cycle, { key: "A" }); expect(cycle.value).to.eq("timepicker.day-period-am"); fireEvent.keyDown(cycle, { key: "P" }); expect(cycle.value).to.eq("timepicker.day-period-pm"); fireEvent.keyDown(cycle, { key: SpecialKey.Home }); expect(cycle.value).to.eq("timepicker.day-period-am"); fireEvent.change(cycle, { target: { value: "pm" } }); fireEvent.keyDown(cycle, { key: SpecialKey.Enter }); expect(cycle.value).to.eq("timepicker.day-period-pm"); fireEvent.change(cycle, { target: { value: "am" } }); fireEvent.keyDown(cycle, { key: SpecialKey.Enter }); expect(cycle.value).to.eq("timepicker.day-period-am"); fireEvent.change(cycle, { target: { value: "PM" } }); fireEvent.keyDown(cycle, { key: SpecialKey.Enter }); expect(cycle.value).to.eq("timepicker.day-period-pm"); fireEvent.change(cycle, { target: { value: "AM" } }); fireEvent.keyDown(cycle, { key: SpecialKey.Enter }); expect(cycle.value).to.eq("timepicker.day-period-am"); cycle.focus(); fireEvent.change(cycle, { target: { value: "pm" } }); cycle.blur(); expect(cycle.value).to.eq("timepicker.day-period-pm"); cycle.focus(); fireEvent.change(hour, { target: { value: "22" } }); fireEvent.keyDown(hour, { key: SpecialKey.Enter }); fireEvent.change(cycle, { target: { value: "timepicker.day-period-am" } }); cycle.blur(); expect(cycle.value).to.eq("timepicker.day-period-am"); cycle.focus(); fireEvent.change(hour, { target: { value: "08" } }); fireEvent.keyDown(hour, { key: SpecialKey.Enter }); fireEvent.change(cycle, { target: { value: "PM" } }); cycle.blur(); expect(cycle.value).to.eq("timepicker.day-period-pm"); cycle.focus(); fireEvent.change(hour, { target: { value: "22" } }); fireEvent.keyDown(hour, { key: SpecialKey.Enter }); fireEvent.change(cycle, { target: { value: "am" } }); cycle.blur(); expect(cycle.value).to.eq("timepicker.day-period-am"); cycle.focus(); fireEvent.change(hour, { target: { value: "08" } }); fireEvent.keyDown(hour, { key: SpecialKey.Enter }); fireEvent.change(cycle, { target: { value: "timepicker.day-period-pm" } }); cycle.blur(); expect(cycle.value).to.eq("timepicker.day-period-pm"); cycle.focus(); fireEvent.change(cycle, { target: { value: "AM" } }); cycle.blur(); expect(cycle.value).to.eq("timepicker.day-period-am"); cycle.focus(); fireEvent.change(cycle, { target: { value: "AM" } }); cycle.blur(); expect(cycle.value).to.eq("timepicker.day-period-am"); renderedComponent.rerender(<TimeField time={pmTime} timeDisplay={TimeDisplay.H12MSC} onTimeChange={renderSpy} readOnly={false} />); }); it("should trigger AM time period change on blur", () => { const renderedComponent = render(<TimeField time={pmTime} timeDisplay={TimeDisplay.H12MSC} onTimeChange={renderSpy} readOnly={false} />); // renderedComponent.debug(); expect(renderedComponent).not.to.be.undefined; const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(4); const cycle = inputs[3]; cycle.focus(); fireEvent.change(cycle, { target: { value: "AM" } }); cycle.blur(); }); it("should trigger PM time period change on blur", () => { const renderedComponent = render(<TimeField time={amTime} timeDisplay={TimeDisplay.H12MSC} onTimeChange={renderSpy} readOnly={false} />); // renderedComponent.debug(); expect(renderedComponent).not.to.be.undefined; const inputs = renderedComponent.container.querySelectorAll("input"); expect(inputs.length).to.eq(4); const cycle = inputs[3]; cycle.focus(); fireEvent.change(cycle, { target: { value: "PM" } }); cycle.blur(); }); });
the_stack
export default function makeDashboard(integrationId: string) { return { annotations: { list: [ { builtIn: 1, datasource: "-- Grafana --", enable: true, hide: true, iconColor: "rgba(0, 211, 255, 1)", name: "Annotations & Alerts", type: "dashboard" } ] }, editable: true, gnetId: null, graphTooltip: 0, iteration: 1623952430144, links: [], panels: [ { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "A ten-second moving average of the # of SELECT, INSERT, UPDATE, and DELETE statements successfully executed per second across all nodes.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 0 }, hiddenSeries: false, id: 2, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(sql_select_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "Selects", refId: "A" }, { exemplar: true, expr: `sum(rate(sql_update_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "Updates", refId: "B" }, { exemplar: true, expr: `sum(rate(sql_insert_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "Inserts", refId: "C" }, { exemplar: true, expr: `sum(rate(sql_delete_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "Deletes", refId: "D" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "SQL Queries", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:77", format: "short", label: "queries", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:78", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Over the last minute, this node executed 99% of queries within this time. This time does not include network latency between the node and client.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 8 }, hiddenSeries: false, id: 4, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `histogram_quantile(0.99, rate(sql_service_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Service Latency: SQL, 99th Percentile", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:160", format: "ns", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:161", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of range replicas stored on this node. Ranges are subsets of your data, which are replicated to ensure survivability.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 16 }, hiddenSeries: false, id: 6, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `replicas{integration_id="${integrationId}",instance=~"$node"}`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Replicas per Node", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:216", format: "short", label: "replicas", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:217", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Usage of disk space\n\n**Capacity**: Maximum store size across all nodes. This value may be explicitly set per node using [--store](https://www.cockroachlabs.com/docs/v21.1/cockroach-start.html#store). If a store size has not been set, this metric displays the actual disk capacity.\n\n**Available**: Free disk space available to CockroachDB data across all nodes.\n\n**Used**: Disk space in use by CockroachDB data across all nodes. This excludes the Cockroach binary, operating system, and other system files.\n\n[How are these metrics calculated?](https://www.cockroachlabs.com/docs/v21.1/ui-storage-dashboard.html#capacity-metrics)", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 24 }, hiddenSeries: false, id: 8, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(sum(capacity{integration_id="${integrationId}",instance=~"$node"}) by (cluster))`, interval: "", intervalFactor: 2, legendFormat: "Max", refId: "B" }, { exemplar: true, expr: `sum(sum(capacity_available{integration_id="${integrationId}",instance=~"$node"}) by (cluster))`, interval: "", legendFormat: "Available", refId: "C" }, { exemplar: true, expr: `sum(sum(capacity_used{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Used", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Capacity", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:272", format: "bytes", label: "capacity", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:273", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } } ], refresh: false, schemaVersion: 27, style: "dark", tags: [], templating: { list: [ { allValue: "", current: { selected: false, text: "All", value: "$__all" }, datasource: "metrics", definition: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, description: null, error: null, hide: 0, includeAll: true, label: "Node", multi: false, name: "node", options: [], query: { query: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, refId: "Prometheus-node-Variable-Query" }, refresh: 1, regex: "", skipUrlSync: false, sort: 1, tagValuesQuery: "", tags: [], tagsQuery: "", type: "query", useTags: false } ] }, time: { from: "now-1h", to: "now" }, timepicker: {}, timezone: "", title: "CRDB Console: Overview", uid: `ove-${integrationId}`, version: 1 }; } export type Dashboard = ReturnType<typeof makeDashboard>;
the_stack
import { User, Request, Stacktrace, StackFrame, Extra, Extras, Primitive, } from '@sentry/types'; import { Options, Event, Breadcrumb, Level, RewriteFrames } from './types'; import { API } from '@sentry/core'; import { isError, isPlainObject, extractExceptionKeysForMessage, normalizeToSize, } from '@sentry/utils'; import { v4 as uuidv4 } from 'uuid'; import { parse } from 'cookie'; import { fromError } from 'stacktrace-js'; import { Scope } from './scope'; export default class Toucan { /** * Default maximum number of breadcrumbs added to an event. Can be overwritten * with {@link Options.maxBreadcrumbs}. */ private readonly DEFAULT_BREADCRUMBS = 100; /** * Absolute maximum number of breadcrumbs added to an event. The * `maxBreadcrumbs` option cannot be higher than this value. */ private readonly MAX_BREADCRUMBS = 100; /** * Is a {@link Scope}[] */ private scopes: Scope[]; /** * If an empty DSN is passed, we should treat it as valid option which signifies disabling the SDK. */ private disabled: boolean; /** * Options passed to constructor. See Options type. */ private options: Options; /** * Full store endpoint with auth search params. Parsed from options.dsn. */ private url: string; /** * Sentry request object transformed from incoming event.request. */ private request: Request | undefined; constructor(options: Options) { this.scopes = [new Scope()]; this.options = options; if (!options.dsn || options.dsn.length === 0) { // If an empty DSN is passed, we should treat it as valid option which signifies disabling the SDK. this.url = ''; this.disabled = true; this.debug(() => this.log('dsn missing, SDK is disabled')); } else { this.url = new API(options.dsn).getStoreEndpointWithUrlEncodedAuth(); this.disabled = false; this.debug(() => this.log(`dsn parsed, full store endpoint: ${this.url}`) ); } // This is to maintain backwards compatibility for 'event' option. When we remove it, all this complex logic can go away. if ('context' in options && options.context.request) { this.request = this.toSentryRequest(options.context.request); } else if ('request' in options && options.request) { this.request = this.toSentryRequest(options.request); } else if ('event' in options && 'request' in options.event) { this.request = this.toSentryRequest(options.event.request); } this.beforeSend = this.beforeSend.bind(this); /** * Wrap all class methods in a proxy that: * 1. Wraps all code in try/catch to handle internal erros gracefully. * 2. Prevents execution if disabled = true */ return new Proxy(this, { get: (target, key: string, receiver) => { return (...args: any) => { if (this.disabled) return; try { return Reflect.get(target, key, receiver).apply(target, args); } catch (err) { this.debug(() => this.error(err)); } }; }, }); } /** * Set key:value that will be sent as extra data with the event. * * @param key String key of extra * @param extra Extra value of extra */ setExtra(key: string, extra: Extra) { this.getScope().setExtra(key, extra); } /** * Set an object that will be merged sent as extra data with the event. * * @param extras Extras context object to merge into current context. */ setExtras(extras: Extras) { this.getScope().setExtras(extras); } /** * Set key:value that will be sent as tags data with the event. * * @param key String key of tag * @param value Primitive value of tag */ setTag(key: string, value: Primitive) { this.getScope().setTag(key, value); } /** * Set an object that will be merged sent as tags data with the event. * * @param tags Tags context object to merge into current context. */ setTags(tags: { [key: string]: Primitive }) { this.getScope().setTags(tags); } /** * Overrides the Sentry default grouping. See https://docs.sentry.io/data-management/event-grouping/sdk-fingerprinting/ * * @param fingerprint Array of strings used to override the Sentry default grouping. */ setFingerprint(fingerprint: string[]) { this.getScope().setFingerprint(fingerprint); } /** * Records a new breadcrumb which will be attached to future events. * * Breadcrumbs will be added to subsequent events to provide more context on user's actions prior to an error or crash. * @param breadcrumb The breadcrum to record. */ addBreadcrumb(breadcrumb: Breadcrumb) { const maxBreadcrumbs = this.options.maxBreadcrumbs ?? this.DEFAULT_BREADCRUMBS; const numberOfBreadcrumbs = Math.min(maxBreadcrumbs, this.MAX_BREADCRUMBS); if (numberOfBreadcrumbs <= 0) return; if (!breadcrumb.timestamp) { breadcrumb.timestamp = this.timestamp(); } this.getScope().addBreadcrumb(breadcrumb, numberOfBreadcrumbs); } /** * Captures an exception event and sends it to Sentry. * * @param exception An exception-like object. * @returns The generated eventId, or undefined if event wasn't scheduled. */ captureException(exception: unknown) { this.debug(() => this.log(`calling captureException`)); const event = this.buildEvent({}); if (!event) return; // This is to maintain backwards compatibility for 'event' option. When we remove it, all this complex logic can go away. if ('context' in this.options) { this.options.context.waitUntil(this.reportException(event, exception)); } else if ('event' in this.options) { this.options.event.waitUntil(this.reportException(event, exception)); } else { // 'waitUntil' not provided -- this is probably called from within a Durable Object this.reportException(event, exception); } return event.event_id; } /** * Captures a message event and sends it to Sentry. * * @param message The message to send to Sentry. * @param level Define the level of the message. * @returns The generated eventId, or undefined if event wasn't scheduled. */ captureMessage(message: string, level: Level = 'info') { this.debug(() => this.log(`calling captureMessage`)); const event = this.buildEvent({ level, message }); if (!event) return; if ('context' in this.options) { this.options.context.waitUntil(this.reportMessage(event)); } else if ('event' in this.options) { this.options.event.waitUntil(this.reportMessage(event)); } else { // 'waitUntil' not provided -- this is probably called from within a Durable Object this.reportMessage(event); } return event.event_id; } /** * Updates user context information for future events. * * @param user — User context object to be set in the current context. Pass null to unset the user. */ setUser(user: User | null) { this.getScope().setUser(user); } /** * In Cloudflare Workers it’s not possible to read event.request's body after having generated a response (if you attempt to, it throws an exception). * Chances are that if you are interested in reporting request body to Sentry, you have already read the data (via request.json()/request.text()). * Use this method to set it in Sentry context. * @param body */ setRequestBody(body: any) { if (this.request) { this.request.data = body; } else { this.request = { data: body }; } } /** * Creates a new scope with and executes the given operation within. The scope is automatically removed once the operation finishes or throws. * This is essentially a convenience function for: * * @example * pushScope(); * callback(); * popScope(); */ withScope(callback: (scope: Scope) => void): void { const scope = this.pushScope(); try { callback(scope); } finally { this.popScope(); } } /** * Send data to Sentry. * * @param data Event data */ private async postEvent(data: Event) { // We are sending User-Agent for backwards compatibility with older Sentry let headers: Record<string, string> = { 'Content-Type': 'application/json', 'User-Agent': '__name__/__version__', }; // Build headers if (this.options?.transportOptions?.headers) { headers = { ...headers, ...this.options.transportOptions.headers, }; } // Build body string const body = JSON.stringify(data); // Log the outgoing request this.debug(() => { this.log( `sending request to Sentry with headers: ${JSON.stringify( headers )} and body: ${body}` ); }); // Send to Sentry and wait for Response const response = await fetch(this.url, { method: 'POST', body, headers, }); // Log the response await this.debug(() => { return this.logResponse(response); }); // Resolve with response return response; } /** * Builds event payload. Applies beforeSend. * * @param additionalData Additional data added to defaults. * @returns Event */ private buildEvent(additionalData: Event): Event | undefined { const sampleRate = this.options.sampleRate; // 1.0 === 100% events are sent // 0.0 === 0% events are sent if (typeof sampleRate === 'number' && Math.random() > sampleRate) { this.debug(() => this.log(`skipping this event (sampleRate === ${sampleRate})`) ); return; } const pkg = this.options.pkg; // 'release' option takes precedence, if not present - try to derive from package.json const release = this.options.release ? this.options.release : pkg ? `${pkg.name}-${pkg.version}` : undefined; const scope = this.getScope(); // per https://docs.sentry.io/development/sdk-dev/event-payloads/#required-attributes const payload: Event = { event_id: uuidv4().replace(/-/g, ''), // dashes are not allowed logger: 'EdgeWorker', platform: 'node', release, environment: this.options.environment, timestamp: this.timestamp(), level: 'error', modules: pkg ? { ...pkg.dependencies, ...pkg.devDependencies, } : undefined, ...additionalData, request: this.request, sdk: { name: '__name__', version: '__version__', }, }; // Type-casting 'breadcrumb' to any because our level type is a union of literals, as opposed to Level enum. scope.applyToEvent(payload); const beforeSend = this.options.beforeSend ?? this.beforeSend; return beforeSend(payload); } /** * Converts data from fetch event's Request to Sentry Request used in Sentry Event * * @param request FetchEvent Request * @returns Sentry Request */ private toSentryRequest(request: FetchEvent['request']): Request { // Build cookies const cookieString = request.headers.get('cookie'); let cookies: Record<string, string> | undefined = undefined; if (cookieString) { try { cookies = parse(cookieString); } catch (e) {} } const headers: Record<string, string> = {}; // Build headers (omit cookie header, because we built in in the previous step) for (const [k, v] of (request.headers as any).entries()) { if (k !== 'cookie') { headers[k] = v; } } const rv: Request = { method: request.method, cookies, headers, }; try { const url = new URL(request.url); rv.url = `${url.protocol}//${url.hostname}${url.pathname}`; rv.query_string = url.search; } catch (e) { // `new URL` failed, let's try to split URL the primitive way const qi = request.url.indexOf('?'); if (qi < 0) { // no query string rv.url = request.url; } else { rv.url = request.url.substr(0, qi); rv.query_string = request.url.substr(qi + 1); } } return rv; } /** * This SDK's implementation of beforeSend. If 'beforeSend' is not provided in options, this implementation will be applied. * This function is applied to all events before sending to Sentry. * * By default it: * 1. Removes all request headers (unless opts.allowedHeaders is provided - in that case the allowlist is applied) * 2. Removes all request cookies (unless opts.allowedCookies is provided- in that case the allowlist is applied) * 3. Removes all search params (unless opts.allowedSearchParams is provided- in that case the allowlist is applied) * * @param event * @returns Event */ private beforeSend(event: Event) { const request = event.request; if (request) { // Let's try to remove sensitive data from incoming Request const allowedHeaders = this.options.allowedHeaders; const allowedCookies = this.options.allowedCookies; const allowedSearchParams = this.options.allowedSearchParams; if (allowedHeaders) { request.headers = this.applyAllowlist(request.headers, allowedHeaders); } else { delete request.headers; } if (allowedCookies) { request.cookies = this.applyAllowlist(request.cookies, allowedCookies); } else { delete request.cookies; } if (allowedSearchParams) { const params = Object.fromEntries( new URLSearchParams(request.query_string) as any ); const allowedParams = new URLSearchParams(); Object.keys(this.applyAllowlist(params, allowedSearchParams)).forEach( (allowedKey) => { allowedParams.set(allowedKey, params[allowedKey]); } ); request.query_string = allowedParams.toString(); } else { delete request.query_string; } } event.request = request; return event; } /** * Helper function that applies 'allowlist' on 'obj' keys. * * @param obj * @param allowlist * @returns New object with allowed keys. */ private applyAllowlist( obj: Record<string, any> = {}, allowlist: string[] | RegExp ) { let predicate: (item: string) => boolean = (item) => false; if (allowlist instanceof RegExp) { predicate = (item: string) => allowlist.test(item); } else if (Array.isArray(allowlist)) { const allowlistLowercased = allowlist.map((item) => item.toLowerCase()); predicate = (item: string) => allowlistLowercased.includes(item); } else { this.debug(() => this.warn( 'allowlist must be an array of strings, or a regular expression.' ) ); return {}; } return Object.keys(obj) .map((key) => key.toLowerCase()) .filter((key) => predicate(key)) .reduce<Record<string, string>>((allowed, key) => { allowed[key] = obj[key]; return allowed; }, {}); } /** * A number representing the seconds elapsed since the UNIX epoch. */ private timestamp() { return Date.now() / 1000; } /** * Builds Message as per https://develop.sentry.dev/sdk/event-payloads/message/, adds it to the event, * and sends it to Sentry. Inspired by https://github.com/getsentry/sentry-javascript/blob/master/packages/node/src/backend.ts. * * @param event */ private async reportMessage(event: Event) { return this.postEvent(event); } /** * Builds Exception as per https://docs.sentry.io/development/sdk-dev/event-payloads/exception/, adds it to the event, * and sends it to Sentry. Inspired by https://github.com/getsentry/sentry-javascript/blob/master/packages/node/src/backend.ts. * * @param event * @param error */ private async reportException(event: Event, maybeError: unknown) { let error: Error; if (isError(maybeError)) { error = maybeError as Error; } else if (isPlainObject(maybeError)) { // This will allow us to group events based on top-level keys // which is much better than creating new group when any key/value change const message = `Non-Error exception captured with keys: ${extractExceptionKeysForMessage( maybeError )}`; this.setExtra('__serialized__', normalizeToSize(maybeError as {})); error = new Error(message); } else { // This handles when someone does: `throw "something awesome";` // We use synthesized Error here so we can extract a (rough) stack trace. error = new Error(maybeError as string); } const stacktrace = await this.buildStackTrace(error); event.exception = { values: [{ type: error.name, value: error.message, stacktrace }], }; return this.postEvent(event); } /** * Builds Stacktrace as per https://docs.sentry.io/development/sdk-dev/event-payloads/stacktrace/ * * @param error Error object. * @returns Stacktrace */ private async buildStackTrace(error: Error): Promise<Stacktrace | undefined> { if (this.options.attachStacktrace === false) { return undefined; } try { const stack = await fromError(error); /** * sentry-cli and webpack-sentry-plugin upload the source-maps named by their path with a ~/ prefix. * Lets adhere to this behavior. */ const rewriteFrames: RewriteFrames = this.options.rewriteFrames ?? { root: '~/', iteratee: (frame) => frame, }; return { frames: stack .map<StackFrame>((frame) => { const filename = frame.fileName ?? ''; const stackFrame = { colno: frame.columnNumber, lineno: frame.lineNumber, filename, function: frame.functionName, }; if (!!rewriteFrames.root) { stackFrame.filename = `${rewriteFrames.root}${stackFrame.filename}`; } return !!rewriteFrames.iteratee ? rewriteFrames.iteratee(stackFrame) : stackFrame; }) .reverse(), }; } catch (e) { return undefined; } } /** * Runs a callback if debug === true. * Use this to delay execution of debug logic, to ensure toucan doesn't burn I/O in non-debug mode. * * @param callback */ private debug<ReturnType>(callback: () => ReturnType) { if (this.options.debug) { return callback(); } } private log(message: string) { console.log(`toucan-js: ${message}`); } private warn(message: string) { console.warn(`toucan-js: ${message}`); } private error(message: string) { console.error(`toucan-js: ${message}`); } /** * Reads and logs Response object from Sentry. Warning: Reads the Response stream (.text()). * Do not use without this.debug wrapper. * * @param response Response */ private async logResponse(response: Response) { let responseText = ''; // Read response body, set to empty if fails try { responseText = await response.text(); } catch (e) { responseText += ''; } // Parse origin from response.url, but at least give some string if parsing fails. let origin = 'Sentry'; try { const originUrl = new URL(response.url); origin = originUrl.origin; } catch (e) { origin = response.url ?? 'Sentry'; } const msg = `${origin} responded with [${response.status} ${response.statusText}]: ${responseText}`; if (response.ok) { this.log(msg); } else { this.error(msg); } } /** Returns the scope of the top stack. */ private getScope() { return this.scopes[this.scopes.length - 1]; } /** * Create a new scope to store context information. * The scope will be layered on top of the current one. It is isolated, i.e. all breadcrumbs and context information added to this scope will be removed once the scope ends. * Be sure to always remove this scope with {@link this.popScope} when the operation finishes or throws. */ private pushScope(): Scope { // We want to clone the content of prev scope const scope = Scope.clone(this.getScope()); this.scopes.push(scope); return scope; } /** * Removes a previously pushed scope from the stack. * This restores the state before the scope was pushed. All breadcrumbs and context information added since the last call to {@link this.pushScope} are discarded. */ private popScope(): boolean { if (this.scopes.length <= 1) return false; return !!this.scopes.pop(); } }
the_stack
import { isAssignableToSimpleTypeKind } from "ts-simple-type"; import * as tsModule from "typescript"; import { Declaration, Identifier, InterfaceDeclaration, Node, PropertyDeclaration, PropertySignature, SetAccessorDeclaration, Symbol, SyntaxKind, TypeChecker } from "typescript"; import { ModifierKind } from "../types/modifier-kind"; import { VisibilityKind } from "../types/visibility-kind"; import { resolveNodeValue } from "./resolve-node-value"; import { isNamePrivate } from "./text-util"; export interface AstContext { ts: typeof tsModule; checker: TypeChecker; } /** * Resolves all relevant declarations of a specific node. * @param node * @param context */ export function resolveDeclarations(node: Node, context: { checker: TypeChecker; ts: typeof tsModule }): Declaration[] { if (node == null) return []; const symbol = getSymbol(node, context); if (symbol == null) return []; return resolveSymbolDeclarations(symbol); } /** * Returns the symbol of a node. * This function follows aliased symbols. * @param node * @param context */ export function getSymbol(node: Node, context: { checker: TypeChecker; ts: typeof tsModule }): Symbol | undefined { if (node == null) return undefined; const { checker, ts } = context; // Get the symbol let symbol = checker.getSymbolAtLocation(node); if (symbol == null) { const identifier = getNodeIdentifier(node, context); symbol = identifier != null ? checker.getSymbolAtLocation(identifier) : undefined; } // Resolve aliased symbols if (symbol != null && isAliasSymbol(symbol, ts)) { symbol = checker.getAliasedSymbol(symbol); if (symbol == null) return undefined; } return symbol; } /** * Resolves the declarations of a symbol. A valueDeclaration is always the first entry in the array * @param symbol */ export function resolveSymbolDeclarations(symbol: Symbol): Declaration[] { // Filters all declarations const valueDeclaration = symbol.valueDeclaration; const declarations = symbol.getDeclarations() || []; if (valueDeclaration == null) { return declarations; } else { // Make sure that "valueDeclaration" is always the first entry return [valueDeclaration, ...declarations.filter(decl => decl !== valueDeclaration)]; } } /** * Resolve a declaration by trying to find the real value by following assignments. * @param node * @param context */ export function resolveDeclarationsDeep(node: Node, context: { checker: TypeChecker; ts: typeof tsModule }): Node[] { const declarations: Node[] = []; const allDeclarations = resolveDeclarations(node, context); for (const declaration of allDeclarations) { if (context.ts.isVariableDeclaration(declaration) && declaration.initializer != null && context.ts.isIdentifier(declaration.initializer)) { declarations.push(...resolveDeclarationsDeep(declaration.initializer, context)); } else if (context.ts.isTypeAliasDeclaration(declaration) && declaration.type != null && context.ts.isIdentifier(declaration.type)) { declarations.push(...resolveDeclarationsDeep(declaration.type, context)); } else { declarations.push(declaration); } } return declarations; } /** * Returns if the symbol has "alias" flag * @param symbol * @param ts */ export function isAliasSymbol(symbol: Symbol, ts: typeof tsModule): boolean { return hasFlag(symbol.flags, ts.SymbolFlags.Alias); } /** * Returns a set of modifiers on a node * @param node * @param ts */ export function getModifiersFromNode(node: Node, ts: typeof tsModule): Set<ModifierKind> | undefined { const modifiers: Set<ModifierKind> = new Set(); if (hasModifier(node, ts.SyntaxKind.ReadonlyKeyword)) { modifiers.add("readonly"); } if (hasModifier(node, ts.SyntaxKind.StaticKeyword)) { modifiers.add("static"); } if (ts.isGetAccessor(node)) { modifiers.add("readonly"); } return modifiers.size > 0 ? modifiers : undefined; } /** * Returns if a number has a flag * @param num * @param flag */ export function hasFlag(num: number, flag: number): boolean { return (num & flag) !== 0; } /** * Returns if a node has a specific modifier. * @param node * @param modifierKind */ export function hasModifier(node: Node, modifierKind: SyntaxKind): boolean { if (node.modifiers == null) return false; return (node.modifiers || []).find(modifier => modifier.kind === (modifierKind as unknown)) != null; } /** * Returns the visibility of a node */ export function getMemberVisibilityFromNode( node: PropertyDeclaration | PropertySignature | SetAccessorDeclaration | Node, ts: typeof tsModule ): VisibilityKind | undefined { if (hasModifier(node, ts.SyntaxKind.PrivateKeyword) || ("name" in node && ts.isIdentifier(node.name) && isNamePrivate(node.name.text))) { return "private"; } else if (hasModifier(node, ts.SyntaxKind.ProtectedKeyword)) { return "protected"; } else if (getNodeSourceFileLang(node) === "ts") { // Only return "public" in typescript land return "public"; } return undefined; } /** * Returns all keys and corresponding interface/class declarations for keys in an interface. * @param interfaceDeclaration * @param context */ export function getInterfaceKeys( interfaceDeclaration: InterfaceDeclaration, context: AstContext ): { key: string; keyNode: Node; identifier?: Node; declaration?: Node }[] { const extensions: { key: string; keyNode: Node; identifier?: Node; declaration?: Node }[] = []; const { ts } = context; for (const member of interfaceDeclaration.members) { // { "my-button": MyButton; } if (ts.isPropertySignature(member) && member.type != null) { const resolvedKey = resolveNodeValue(member.name, context); if (resolvedKey == null) { continue; } let identifier: Node | undefined; let declaration: Node | undefined; if (ts.isTypeReferenceNode(member.type)) { // { ____: MyButton; } or { ____: namespace.MyButton; } identifier = member.type.typeName; } else if (ts.isTypeLiteralNode(member.type)) { identifier = undefined; declaration = member.type; } else { continue; } if (declaration != null || identifier != null) { extensions.push({ key: String(resolvedKey.value), keyNode: resolvedKey.node, declaration, identifier }); } } } return extensions; } // noinspection JSUnusedGlobalSymbols export function isPropertyRequired(property: PropertySignature | PropertyDeclaration, checker: TypeChecker): boolean { const type = checker.getTypeAtLocation(property); // Properties in external modules don't have initializers, so we cannot infer if the property is required or not if (isNodeInDeclarationFile(property)) { return false; } // The property cannot be required if it has an initializer. if (property.initializer != null) { return false; } // Take "myProp?: string" into account if (property.questionToken != null) { return false; } // "any" or "unknown" should never be required if (isAssignableToSimpleTypeKind(type, ["ANY", "UNKNOWN"], checker)) { return false; } // Return "not required" if the property doesn't have an initializer and no type node. // In this case the type could be determined by the jsdoc @type tag but cannot be "null" union if "strictNullCheck" is false. if (property.type == null) { return false; } return !isAssignableToSimpleTypeKind(type, ["UNDEFINED", "NULL"], checker); } /** * Find a node recursively walking up the tree using parent nodes. * @param node * @param test */ export function findParent<T extends Node = Node>(node: Node | undefined, test: (node: Node) => node is T): T | undefined { if (node == null) return; return test(node) ? node : findParent(node.parent, test); } /** * Find a node recursively walking down the children of the tree. Depth first search. * @param node * @param test */ export function findChild<T extends Node = Node>(node: Node | undefined, test: (node: Node) => node is T): T | undefined { if (!node) return; if (test(node)) return node; return node.forEachChild(child => findChild(child, test)); } /** * Find multiple children by walking down the children of the tree. Depth first search. * @param node * @param test * @param emit */ export function findChildren<T extends Node = Node>(node: Node | undefined, test: (node: Node) => node is T, emit: (node: T) => void): void { if (!node) return; if (test(node)) { emit(node); } node.forEachChild(child => findChildren(child, test, emit)); } /** * Returns the language of the node's source file * @param node */ export function getNodeSourceFileLang(node: Node): "js" | "ts" { return node.getSourceFile().fileName.endsWith("ts") ? "ts" : "js"; } /** * Returns if a node is in a declaration file * @param node */ export function isNodeInDeclarationFile(node: Node): boolean { return node.getSourceFile().isDeclarationFile; } /** * Returns the leading comment for a given node * @param node * @param ts */ export function getLeadingCommentForNode(node: Node, ts: typeof tsModule): string | undefined { const sourceFileText = node.getSourceFile().text; const leadingComments = ts.getLeadingCommentRanges(sourceFileText, node.pos); if (leadingComments != null && leadingComments.length > 0) { return sourceFileText.substring(leadingComments[0].pos, leadingComments[0].end); } return undefined; } /** * Returns the declaration name of a given node if possible. * @param node * @param context */ export function getNodeName(node: Node, context: { ts: typeof tsModule }): string | undefined { return getNodeIdentifier(node, context)?.getText(); } /** * Returns the declaration name of a given node if possible. * @param node * @param context */ export function getNodeIdentifier(node: Node, context: { ts: typeof tsModule }): Identifier | undefined { if (context.ts.isIdentifier(node)) { return node; } else if ( (context.ts.isClassLike(node) || context.ts.isInterfaceDeclaration(node) || context.ts.isVariableDeclaration(node) || context.ts.isMethodDeclaration(node) || context.ts.isPropertyDeclaration(node) || context.ts.isFunctionDeclaration(node)) && node.name != null && context.ts.isIdentifier(node.name) ) { return node.name; } return undefined; }
the_stack
import { useCallback, useEffect, useRef, useState } from 'react' import { useDebounce, useKeyPressEvent, useWindowSize } from 'react-use' import { ReactZoomPanPinchRef, TransformComponent, TransformWrapper, } from 'react-zoom-pan-pinch' import { useFirebase } from './adapters/firebase' import CleanupTools from './components/CleanupTools' import ZoomTools from './components/ZoomTools' import { useEditor } from './context/EditorContext' import EditorToolSelector, { EditorTool } from './EditorToolSelector' const TOOLBAR_SIZE = 180 interface EditorUIProps { showOriginal: boolean showSeparator: boolean setShowOriginal: (showOriginal: boolean) => void setShowSeparator: (showSeparator: boolean) => void } export default function EditorUI({ showOriginal, showSeparator, setShowOriginal, setShowSeparator, }: EditorUIProps) { const [{ x, y }, setCoords] = useState({ x: -1, y: -1 }) const [showBrush, setShowBrush] = useState(false) const [isInpaintingLoading, setIsInpaintingLoading] = useState(false) const [tool, setTool] = useState<EditorTool>('clean') const firebase = useFirebase() const [minScale, setMinScale] = useState<number>() const windowSize = useWindowSize() const isSmallScreen = windowSize.width < 640 const viewportRef = useRef<ReactZoomPanPinchRef | undefined | null>() const [brushSize, setBrushSize] = useState(isSmallScreen ? 90 : 50) // Save the scale to a state to refresh when the user zooms in. const [currScale, setCurrScale] = useState<number>() const editor = useEditor() const { image, undo, file, edits, addLine, context, render, draw, setContext, maskCanvas, useHD, refiner, } = editor const currentEdit = edits[edits.length - 1] const scale = viewportRef.current?.state.scale || 1 // Zoom reset const resetZoom = useCallback( (duration = 200) => { if (!minScale || !image || !windowSize || !viewportRef.current) { return } const viewport = viewportRef.current const offsetX = (windowSize.width - image.width * minScale) / 2 const offsetY = (windowSize.height - image.height * minScale) / 2 viewport.setTransform(offsetX, offsetY, minScale, duration, 'easeOutQuad') setCurrScale(minScale) }, [minScale, image, windowSize] ) const setZoom = useCallback( (s: number) => { const viewport = viewportRef.current if (!viewport || !image) { return } // Get the percentage of the image currently on the center. const anchor = { x: (windowSize.width * 0.5 - viewport.state.positionX) / (image.width * viewport.state.scale), y: (windowSize.height * 0.5 - viewport.state.positionY) / (image.height * viewport.state.scale), } viewportRef.current?.setTransform( windowSize.width * 0.5 - image.width * s * anchor.x, windowSize.height * 0.5 - image.height * s * anchor.y, s, 200, 'easeOutQuad' ) setCurrScale(s) }, [windowSize.width, windowSize.height, image] ) // Toggle original useEffect(() => { if (showOriginal) { setShowSeparator(true) } else { setTimeout(() => setShowSeparator(false), 300) } }, [showOriginal, setShowSeparator]) // Toggle clean/zoom tool on spacebar. useKeyPressEvent( ' ', ev => { ev?.preventDefault() setShowBrush(false) setTool('zoom') }, ev => { ev?.preventDefault() setShowBrush(true) setTool('clean') } ) // Reset zoom on Escale useKeyPressEvent('Escape', resetZoom) // Reset zoom on HD change useEffect(() => resetZoom(0), [useHD, resetZoom]) // Reset zoom on window size change useDebounce(resetZoom, 75, [windowSize]) // Handle Tab useKeyPressEvent('Tab', undefined, ev => { ev?.preventDefault() ev?.stopPropagation() setShowOriginal(false) }) // Handle Cmd+Z useEffect(() => { const handler = (event: KeyboardEvent) => { // Switch to original tool when we press tab. We dupli if (event.key === 'Tab') { event.preventDefault() setShowOriginal(true) } // Handle Cmdt+Z if (edits.length < 2 && !currentEdit.lines.length) { return } const isCmdZ = (event.metaKey || event.ctrlKey) && event.key === 'z' if (isCmdZ) { event.preventDefault() undo() } } window.addEventListener('keydown', handler) return () => { window.removeEventListener('keydown', handler) } }, [edits, currentEdit, undo, setShowOriginal]) // Draw once the image image is loaded useEffect(() => { if (!image) { return } const rW = windowSize.width / image.naturalWidth const rH = (windowSize.height - TOOLBAR_SIZE) / image.naturalHeight if (rW < 1 || rH < 1) { const s = Math.min(rW, rH) setMinScale(s) // setCurrScale(s) } else { setMinScale(1) // setCurrScale(1) } if (context?.canvas) { context.canvas.width = image.naturalWidth context.canvas.height = image.naturalHeight } draw() }, [context?.canvas, draw, image, windowSize]) // Re-render when the refiner changes useEffect(() => { if (context) { setIsInpaintingLoading(true) render().finally(() => { setIsInpaintingLoading(false) }) } }, [refiner]) // eslint-disable-line react-hooks/exhaustive-deps // Handle mouse interactions useEffect(() => { if (!firebase || !image || !context || tool !== 'clean' || !scale) { return } const canvas = context?.canvas if (!canvas) { return } const onMouseDown = (ev: MouseEvent) => { if (!image.src || showOriginal) { return } const currLine = currentEdit.lines[currentEdit.lines.length - 1] currLine.size = brushSize / scale canvas.addEventListener('mousemove', onMouseDrag) canvas.addEventListener('mouseleave', onPointerUp) window.addEventListener('mouseup', onPointerUp) onPaint(ev.offsetX, ev.offsetY) } const onMouseMove = (ev: MouseEvent) => { setCoords({ x: ev.pageX, y: ev.pageY }) } const onPaint = (px: number, py: number) => { const currLine = currentEdit.lines[currentEdit.lines.length - 1] currLine.pts.push({ x: px, y: py }) draw() } const onMouseDrag = (ev: MouseEvent) => { const px = ev.offsetX const py = ev.offsetY onPaint(px, py) } const onPointerUp = async () => { if (!image?.src || !file) { return } canvas.removeEventListener('mousemove', onMouseDrag) canvas.removeEventListener('mouseleave', onPointerUp) window.removeEventListener('mouseup', onPointerUp) if (!useHD && !isSmallScreen) { setIsInpaintingLoading(true) await render() setIsInpaintingLoading(false) } else { addLine(true) } } window.addEventListener('mousemove', onMouseMove) const onTouchMove = (ev: TouchEvent) => { ev.preventDefault() ev.stopPropagation() const currLine = currentEdit.lines[currentEdit.lines.length - 1] const coords = canvas.getBoundingClientRect() currLine.pts.push({ x: (ev.touches[0].clientX - coords.x) / scale, y: (ev.touches[0].clientY - coords.y) / scale, }) draw() } const onTouchStart = (ev: TouchEvent) => { ev.preventDefault() ev.stopPropagation() if (!image.src || showOriginal) { return } const currLine = currentEdit.lines[currentEdit.lines.length - 1] currLine.size = brushSize / scale const coords = canvas.getBoundingClientRect() const px = (ev.touches[0].clientX - coords.x) / scale const py = (ev.touches[0].clientY - coords.y) / scale onPaint(px, py) } canvas.addEventListener('touchstart', onTouchStart) canvas.addEventListener('touchmove', onTouchMove) canvas.addEventListener('touchend', onPointerUp) canvas.onmouseenter = () => setShowBrush(true) canvas.onmouseleave = () => setShowBrush(false) canvas.onmousedown = onMouseDown canvas.focus() return () => { canvas.removeEventListener('mousemove', onMouseDrag) canvas.removeEventListener('mouseleave', onPointerUp) window.removeEventListener('mousemove', onMouseMove) window.removeEventListener('mouseup', onPointerUp) canvas.removeEventListener('touchstart', onTouchStart) canvas.removeEventListener('touchmove', onTouchMove) canvas.removeEventListener('touchend', onPointerUp) canvas.onmouseenter = null canvas.onmouseleave = null canvas.onmousedown = null } }, [ brushSize, context, file, draw, addLine, maskCanvas, image, currentEdit, firebase, scale, render, useHD, tool, // Add showBrush dependency to fix issue when moving the mouse while // pressing spacebar. showBrush, // Add dependency on minScale to fix offset issue with the first touch event // minScale, isSmallScreen, // Prevent drawing when showing the original image showOriginal, ]) // Current cursor const getCursor = useCallback(() => { if (showOriginal) { return 'default' } if (showBrush) { return 'none' } if (tool === 'zoom') { return 'grab' } return undefined }, [showBrush, tool, showOriginal]) if (!image || !scale || !minScale) { return <></> } return ( <> <TransformWrapper ref={r => { if (r) { viewportRef.current = r } }} panning={{ disabled: tool !== 'zoom', velocityDisabled: true }} wheel={{ step: 0.05 }} centerZoomedOut alignmentAnimation={{ disabled: true }} centerOnInit limitToBounds={false} initialScale={minScale} minScale={minScale} onZoom={ref => { setCurrScale(ref.state.scale) }} > <TransformComponent wrapperStyle={{ width: '100%', height: '100%' }} contentClass={ isInpaintingLoading ? 'animate-pulse-fast pointer-events-none transition-opacity' : '' } > <> <canvas className="rounded-sm" style={{ cursor: getCursor() }} ref={r => { if (r && !context) { const ctx = r.getContext('2d') if (ctx) { setContext(ctx) } } }} /> <div className={[ 'absolute top-0 right-0 pointer-events-none', 'overflow-hidden', 'border-primary', showSeparator ? 'border-l-4' : '', ].join(' ')} style={{ width: showOriginal ? `${Math.round(image.naturalWidth)}px` : '0px', height: image.naturalHeight, transitionProperty: 'width, height', transitionTimingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)', transitionDuration: '300ms', }} > <img className="absolute right-0" src={image.src} alt="original" width={`${image.naturalWidth}px`} height={`${image.naturalHeight}px`} style={{ width: `${image.naturalWidth}px`, height: `${image.naturalHeight}px`, maxWidth: 'none', }} /> </div> </> </TransformComponent> </TransformWrapper> {showBrush && tool === 'clean' && !showOriginal && ( <div className={[ 'hidden sm:block fixed z-50 rounded-full pointer-events-none', 'border border-primary bg-primary bg-opacity-80', ].join(' ')} style={{ width: `${brushSize}px`, height: `${brushSize}px`, left: `${x}px`, top: `${y}px`, transform: 'translate(-50%, -50%)', }} /> )} <div className={[ 'absolute w-full px-2 pb-2 sm:pb-0 flex', 'justify-center flex-col sm:flex-row space-y-2 sm:space-y-0', 'items-end sm:items-center bottom-0 pointer-events-none', ].join(' ')} style={{ // Center the action bar in the white area available. height: windowSize.width > 640 ? `${Math.max( TOOLBAR_SIZE / 2, (window.innerHeight - image.naturalHeight * scale) / 2 )}px` : undefined, }} > <EditorToolSelector tool={tool} onChange={setTool} /> <div className="flex w-full justify-center sm:justify-start sm:w-90 pointer-events-auto"> {tool === 'clean' && ( <CleanupTools editor={editor} brushSize={brushSize} setBrushSize={setBrushSize} isLoading={isInpaintingLoading} onCleanupClick={async () => { setIsInpaintingLoading(true) await render() setIsInpaintingLoading(false) }} /> )} {tool === 'zoom' && ( <ZoomTools zoom={currScale || minScale} minZoom={minScale} setZoom={setZoom} onResetClick={resetZoom} /> )} </div> </div> </> ) }
the_stack
function id(x) { return x[0]; } const isNumber = function (x) { return x.constructor === Number || (typeof x === "object" && x.type === "number"); }; const tok_id = { test: function (x) { return typeof x === "object" && x.type === "id"; } }; const entry_type_bib = { test: function (x) { return typeof x === "object" && x.type === "@bib"; } }; const entry_type_string = { test: function (x) { return typeof x === "object" && x.type === "@string"; } }; const entry_type_preamble = { test: function (x) { return typeof x === "object" && x.type === "@preamble"; } }; const entry_type_comment = { test: function (x) { return typeof x === "object" && x.type === "@comment"; } }; const ws: any = { test: function (x) { return typeof x === "object" && x.type === "ws"; } }; const num: any = {test: isNumber}; const pound: any = {literal: "#"}; const eq: any = {literal: "="}; const esc: any = {literal: "\\"}; const paren_l = {literal: "("}; const paren_r = {literal: ")"}; const brace_l = {literal: "{"}; const brace_r = {literal: "}"}; const quote_dbl = {literal: "\""}; const comma: any = {literal: ","}; function addToObj(obj, keyval) { if (keyval.type !== "keyval") throw new Error("Expected a keyval object"); const key = keyval.key.toLowerCase(); if (obj.fields[key]) { // TODO error? // console.log("WARNING: field '" + key + "' was already defined on " + obj["@type"] + " object with id '" + obj._id + "'. Ignoring this value."); return; } else { obj.fields[key] = keyval.value; return obj; } } function joinTokens(arr) { const strs: any = []; for (let i = 0; i < arr.length; i++) { if (typeof arr[i] === "object") { if (!arr[i].string) throw new Error("Expected token to have a string field called 'string' in object " + JSON.stringify(arr[i])); strs.push(arr[i].string); } else if (typeof arr[i] === "string" || typeof arr[i] === "number") { strs.push(arr[i]); } else throw new Error("Could not handle token " + JSON.stringify(arr[i]) + " in array " + JSON.stringify(arr)); } return strs.join(""); } export const grammar: any = { Lexer: undefined, ParserRules: [ {"name": "main$ebnf$1", "symbols": ["non_entry"], "postprocess": id}, { "name": "main$ebnf$1", "symbols": [], "postprocess": function () { return undefined; } }, {"name": "main$ebnf$2", "symbols": []}, {"name": "main$ebnf$2$subexpression$1$ebnf$1", "symbols": ["non_entry"], "postprocess": id}, { "name": "main$ebnf$2$subexpression$1$ebnf$1", "symbols": [], "postprocess": function () { return undefined; } }, {"name": "main$ebnf$2$subexpression$1", "symbols": ["entry", "main$ebnf$2$subexpression$1$ebnf$1"]}, { "name": "main$ebnf$2", "symbols": ["main$ebnf$2", "main$ebnf$2$subexpression$1"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "main", "symbols": ["main$ebnf$1", "main$ebnf$2"], "postprocess": function (data) { const topLevelObjects: any = []; // console.log(JSON.stringify(data)); if (data[0]) topLevelObjects.push({type: "NON_ENTRY", data: data[0]}); for (let i = 0; i < data[1].length; i++) { topLevelObjects.push({type: "ENTRY", data: data[1][i][0]}); if (data[1][i][1]) topLevelObjects.push({type: "NON_ENTRY", data: data[1][i][1]}); } return topLevelObjects; } }, {"name": "_$ebnf$1", "symbols": []}, { "name": "_$ebnf$1", "symbols": ["_$ebnf$1", ws], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, {"name": "_", "symbols": ["_$ebnf$1"]}, {"name": "entry_decl$subexpression$1", "symbols": [entry_type_bib]}, {"name": "entry_decl$subexpression$1", "symbols": [entry_type_string]}, {"name": "entry_decl$subexpression$1", "symbols": [entry_type_preamble]}, {"name": "entry_decl$subexpression$1", "symbols": [entry_type_comment]}, { "name": "entry_decl", "symbols": ["entry_decl$subexpression$1"], "postprocess": function (data) { return data[0][0]; } }, {"name": "entry$subexpression$1", "symbols": ["bib_entry"]}, {"name": "entry$subexpression$1", "symbols": ["string_entry"]}, {"name": "entry$subexpression$1", "symbols": ["preamble_entry"]}, {"name": "entry$subexpression$1", "symbols": ["comment_entry"]}, { "name": "entry", "symbols": ["entry$subexpression$1"], "postprocess": function (data) { return data[0][0]; } }, { "name": "comment", "symbols": ["main"], "postprocess": function (data) { return data[0]; } }, {"name": "comment_liberal$ebnf$1", "symbols": []}, {"name": "comment_liberal$ebnf$1$subexpression$1", "symbols": [/./]}, { "name": "comment_liberal$ebnf$1", "symbols": ["comment_liberal$ebnf$1", "comment_liberal$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "comment_liberal", "symbols": ["comment_liberal$ebnf$1"], "postprocess": function (data) { const toeknz: any = []; for (let tk = 0; tk < data[0].length; tk++) toeknz.push(data[0][tk][0]); return toeknz; } }, {"name": "entry_body_comment$subexpression$1$macrocall$2", "symbols": ["comment"]}, { "name": "entry_body_comment$subexpression$1$macrocall$1", "symbols": [paren_l, "entry_body_comment$subexpression$1$macrocall$2", paren_r], "postprocess": function (data) { return data[1]; } }, {"name": "entry_body_comment$subexpression$1", "symbols": ["entry_body_comment$subexpression$1$macrocall$1"]}, {"name": "entry_body_comment$subexpression$1$macrocall$4", "symbols": ["comment"]}, { "name": "entry_body_comment$subexpression$1$macrocall$3", "symbols": [brace_l, "entry_body_comment$subexpression$1$macrocall$4", brace_r], "postprocess": function (data) { return data[1]; } }, {"name": "entry_body_comment$subexpression$1", "symbols": ["entry_body_comment$subexpression$1$macrocall$3"]}, { "name": "entry_body_comment", "symbols": ["entry_body_comment$subexpression$1"], "postprocess": function (data) { return data[0][0][0]; } }, {"name": "entry_body_string$subexpression$1$macrocall$2", "symbols": ["keyval"]}, { "name": "entry_body_string$subexpression$1$macrocall$1", "symbols": [paren_l, "_", "entry_body_string$subexpression$1$macrocall$2", "_", paren_r], "postprocess": function (data) { return data[2]; } }, {"name": "entry_body_string$subexpression$1", "symbols": ["entry_body_string$subexpression$1$macrocall$1"]}, {"name": "entry_body_string$subexpression$1$macrocall$4", "symbols": ["keyval"]}, { "name": "entry_body_string$subexpression$1$macrocall$3", "symbols": [brace_l, "_", "entry_body_string$subexpression$1$macrocall$4", "_", brace_r], "postprocess": function (data) { return data[2]; } }, {"name": "entry_body_string$subexpression$1", "symbols": ["entry_body_string$subexpression$1$macrocall$3"]}, { "name": "entry_body_string", "symbols": ["entry_body_string$subexpression$1"], "postprocess": function (data) { return data[0][0][0]; } }, {"name": "entry_body_bib$subexpression$1$macrocall$2", "symbols": ["bib_content"]}, { "name": "entry_body_bib$subexpression$1$macrocall$1", "symbols": [paren_l, "_", "entry_body_bib$subexpression$1$macrocall$2", "_", paren_r], "postprocess": function (data) { return data[2]; } }, {"name": "entry_body_bib$subexpression$1", "symbols": ["entry_body_bib$subexpression$1$macrocall$1"]}, {"name": "entry_body_bib$subexpression$1$macrocall$4", "symbols": ["bib_content"]}, { "name": "entry_body_bib$subexpression$1$macrocall$3", "symbols": [brace_l, "_", "entry_body_bib$subexpression$1$macrocall$4", "_", brace_r], "postprocess": function (data) { return data[2]; } }, {"name": "entry_body_bib$subexpression$1", "symbols": ["entry_body_bib$subexpression$1$macrocall$3"]}, { "name": "entry_body_bib", "symbols": ["entry_body_bib$subexpression$1"], "postprocess": function (data) { return data[0][0][0]; } }, {"name": "bib_content$ebnf$1", "symbols": []}, {"name": "bib_content$ebnf$1$subexpression$1", "symbols": ["keyval", "_", comma, "_"]}, { "name": "bib_content$ebnf$1", "symbols": ["bib_content$ebnf$1", "bib_content$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, {"name": "bib_content$ebnf$2$subexpression$1", "symbols": ["_", comma]}, {"name": "bib_content$ebnf$2", "symbols": ["bib_content$ebnf$2$subexpression$1"], "postprocess": id}, { "name": "bib_content$ebnf$2", "symbols": [], "postprocess": function () { return undefined; } }, { "name": "bib_content", "symbols": ["key_string", "_", comma, "_", "bib_content$ebnf$1", "keyval", "bib_content$ebnf$2"], "postprocess": function (data) { const obj: any = { _id: data[0], fields: [] }; const keyvals = data[4]; for (let kv = 0; kv < keyvals.length; kv++) { obj.fields.push(keyvals[kv][0]); } obj.fields.push(data[5]); return obj; } }, { "name": "bib_entry", "symbols": [entry_type_bib, "_", "entry_body_bib"], "postprocess": function (data) { const obj: any = { _id: data[2]._id }; obj["@type"] = data[0].string; obj.fields = {}; const keyvals = data[2].fields; for (let kv = 0; kv < keyvals.length; kv++) { addToObj(obj, keyvals[kv]); } return obj; } }, { "name": "string_entry", "symbols": [entry_type_string, "_", "entry_body_string"], "postprocess": function (data) { return {type: "string", data: data[2]}; } }, { "name": "preamble_entry", "symbols": [entry_type_preamble, "_", "entry_body_comment"], "postprocess": function (data) { return {type: "preamble", data: data[2]}; } }, { "name": "comment_entry", "symbols": [entry_type_comment, "_", "entry_body_comment"], "postprocess": function (data) { return {type: "comment", data: data[2]}; } }, { "name": "keyval", "symbols": ["key_string", "_", eq, "_", "value_string"], "postprocess": function (data) { return {type: "keyval", key: data[0], value: data[4]}; } }, {"name": "braced_string$ebnf$1", "symbols": []}, {"name": "braced_string$ebnf$1$subexpression$1", "symbols": ["non_brace"]}, {"name": "braced_string$ebnf$1$subexpression$1", "symbols": ["braced_string"]}, { "name": "braced_string$ebnf$1", "symbols": ["braced_string$ebnf$1", "braced_string$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "braced_string", "symbols": [brace_l, "braced_string$ebnf$1", brace_r], "postprocess": function (data) { const tkz: any = []; for (const i in data[1]) tkz.push(data[1][i][0]); return {type: "braced", data: tkz}; } }, {"name": "quoted_string$ebnf$1", "symbols": []}, {"name": "quoted_string$ebnf$1$subexpression$1", "symbols": ["escaped_quote"]}, {"name": "quoted_string$ebnf$1$subexpression$1", "symbols": ["non_quote_non_brace"]}, {"name": "quoted_string$ebnf$1$subexpression$1", "symbols": ["braced_string"]}, { "name": "quoted_string$ebnf$1", "symbols": ["quoted_string$ebnf$1", "quoted_string$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "quoted_string", "symbols": [quote_dbl, "quoted_string$ebnf$1", quote_dbl], "postprocess": function (data) { const tks: any = []; for (const i in data[1]) tks.push(data[1][i][0]); return {type: "quotedstring", data: tks}; } }, {"name": "escaped_quote", "symbols": [esc, quote_dbl]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [tok_id]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [entry_type_bib]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [entry_type_string]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [entry_type_preamble]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [entry_type_comment]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [ws]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [num]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [pound]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [eq]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [esc]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [paren_l]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [paren_r]}, {"name": "non_quote_non_brace$subexpression$1", "symbols": [comma]}, {"name": "non_quote_non_brace", "symbols": ["non_quote_non_brace$subexpression$1"]}, {"name": "key_string$ebnf$1", "symbols": ["stringreftoken"]}, { "name": "key_string$ebnf$1", "symbols": ["key_string$ebnf$1", "stringreftoken"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "key_string", "symbols": ["key_string$ebnf$1"], "postprocess": function (data) { return joinTokens(data[0]).toLowerCase(); } }, {"name": "value_string$subexpression$1$ebnf$1", "symbols": []}, { "name": "value_string$subexpression$1$ebnf$1$subexpression$1", "symbols": ["_", pound, "_", "quoted_string_or_ref"] }, { "name": "value_string$subexpression$1$ebnf$1", "symbols": ["value_string$subexpression$1$ebnf$1", "value_string$subexpression$1$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "value_string$subexpression$1", "symbols": ["quoted_string_or_ref", "value_string$subexpression$1$ebnf$1"] }, {"name": "value_string$subexpression$1", "symbols": ["braced_string"]}, { "name": "value_string", "symbols": ["value_string$subexpression$1"], "postprocess": function (data) { // console.log("DATA",JSON.stringify(data)); const match = data[0]; if (match.length === 2) { // quoted string const tokenz: any = []; tokenz.push(match[0]); for (let i = 0; i < match[1].length; i++) tokenz.push(match[1][i][3]); return {type: "quotedstringwrapper", data: tokenz}; } else if (match[0].type === "braced") return {type: "bracedstringwrapper", data: match[0].data}; // else if(isNumber(match[0]) return [match[0]]; else throw new Error("Don't know how to handle value " + JSON.stringify(match[0])); } }, {"name": "quoted_string_or_ref$subexpression$1", "symbols": ["quoted_string"]}, {"name": "quoted_string_or_ref$subexpression$1", "symbols": ["string_ref"]}, {"name": "quoted_string_or_ref$subexpression$1", "symbols": [num]}, { "name": "quoted_string_or_ref", "symbols": ["quoted_string_or_ref$subexpression$1"], "postprocess": function (data) { // console.log(data); if (data[0][0].type === "quotedstring") return data[0][0]; else { return data[0][0]; } } }, {"name": "string_ref$subexpression$1$ebnf$1", "symbols": []}, { "name": "string_ref$subexpression$1$ebnf$1", "symbols": ["string_ref$subexpression$1$ebnf$1", "stringreftoken"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "string_ref$subexpression$1", "symbols": ["stringreftoken_n_num", "string_ref$subexpression$1$ebnf$1"] }, { "name": "string_ref", "symbols": ["string_ref$subexpression$1"], "postprocess": function (data) { const str = data[0][0] + joinTokens(data[0][1]); return {stringref: str}; } }, {"name": "stringreftoken$subexpression$1", "symbols": [esc]}, {"name": "stringreftoken$subexpression$1", "symbols": [paren_l]}, {"name": "stringreftoken$subexpression$1", "symbols": [paren_r]}, {"name": "stringreftoken$subexpression$1", "symbols": [tok_id]}, {"name": "stringreftoken$subexpression$1", "symbols": [num]}, {"name": "stringreftoken$subexpression$1", "symbols": [entry_type_bib]}, {"name": "stringreftoken$subexpression$1", "symbols": [entry_type_string]}, {"name": "stringreftoken$subexpression$1", "symbols": [entry_type_preamble]}, {"name": "stringreftoken$subexpression$1", "symbols": [entry_type_comment]}, { "name": "stringreftoken", "symbols": ["stringreftoken$subexpression$1"], "postprocess": function (data) { if (typeof data[0][0] === "object") { if (!data[0][0].string) throw new Error("Expected " + data[0] + "to have a 'string' field"); return data[0][0].string; } else { if ((!(typeof data[0][0] === "string" || typeof data[0][0] === "number"))) throw new Error("Expected " + data[0][0] + " to be a string"); return data[0][0]; } } }, {"name": "stringreftoken_n_num$subexpression$1", "symbols": [esc]}, {"name": "stringreftoken_n_num$subexpression$1", "symbols": [paren_l]}, {"name": "stringreftoken_n_num$subexpression$1", "symbols": [paren_r]}, {"name": "stringreftoken_n_num$subexpression$1", "symbols": [tok_id]}, {"name": "stringreftoken_n_num$subexpression$1", "symbols": [entry_type_bib]}, {"name": "stringreftoken_n_num$subexpression$1", "symbols": [entry_type_string]}, {"name": "stringreftoken_n_num$subexpression$1", "symbols": [entry_type_preamble]}, {"name": "stringreftoken_n_num$subexpression$1", "symbols": [entry_type_comment]}, { "name": "stringreftoken_n_num", "symbols": ["stringreftoken_n_num$subexpression$1"], "postprocess": function (data) { if (typeof data[0][0] === "object") { if (!data[0][0].string) throw new Error("Expected " + data[0] + "to have a 'string' field"); return data[0][0].string; } else { if ((!(typeof data[0][0] === "string" || typeof data[0][0] === "number"))) throw new Error("Expected " + data[0][0] + " to be a string"); return data[0][0]; } } }, {"name": "non_brace$subexpression$1", "symbols": [esc]}, {"name": "non_brace$subexpression$1", "symbols": [paren_l]}, {"name": "non_brace$subexpression$1", "symbols": [paren_r]}, {"name": "non_brace$subexpression$1", "symbols": [tok_id]}, {"name": "non_brace$subexpression$1", "symbols": [quote_dbl]}, {"name": "non_brace$subexpression$1", "symbols": [ws]}, {"name": "non_brace$subexpression$1", "symbols": [num]}, {"name": "non_brace$subexpression$1", "symbols": [comma]}, {"name": "non_brace$subexpression$1", "symbols": [entry_type_bib]}, {"name": "non_brace$subexpression$1", "symbols": [entry_type_string]}, {"name": "non_brace$subexpression$1", "symbols": [entry_type_preamble]}, {"name": "non_brace$subexpression$1", "symbols": [entry_type_comment]}, {"name": "non_brace$subexpression$1", "symbols": [pound]}, {"name": "non_brace$subexpression$1", "symbols": [eq]}, { "name": "non_brace", "symbols": ["non_brace$subexpression$1"], "postprocess": function (data) { return data[0][0]; } }, {"name": "non_bracket$subexpression$1", "symbols": [esc]}, {"name": "non_bracket$subexpression$1", "symbols": [tok_id]}, {"name": "non_bracket$subexpression$1", "symbols": [quote_dbl]}, {"name": "non_bracket$subexpression$1", "symbols": [ws]}, {"name": "non_bracket$subexpression$1", "symbols": [num]}, {"name": "non_bracket$subexpression$1", "symbols": [comma]}, {"name": "non_bracket$subexpression$1", "symbols": [entry_type_bib]}, {"name": "non_bracket$subexpression$1", "symbols": [entry_type_string]}, {"name": "non_bracket$subexpression$1", "symbols": [entry_type_preamble]}, {"name": "non_bracket$subexpression$1", "symbols": [entry_type_comment]}, {"name": "non_bracket$subexpression$1", "symbols": [pound]}, {"name": "non_bracket$subexpression$1", "symbols": [eq]}, { "name": "non_bracket", "symbols": ["non_bracket$subexpression$1"], "postprocess": function (data) { return data[0][0]; } }, {"name": "non_entry$ebnf$1$subexpression$1", "symbols": ["escaped_entry"]}, {"name": "non_entry$ebnf$1$subexpression$1", "symbols": ["escaped_escape"]}, {"name": "non_entry$ebnf$1$subexpression$1", "symbols": ["escaped_non_esc_outside_entry"]}, {"name": "non_entry$ebnf$1$subexpression$1", "symbols": ["non_esc_outside_entry"]}, {"name": "non_entry$ebnf$1", "symbols": ["non_entry$ebnf$1$subexpression$1"]}, {"name": "non_entry$ebnf$1$subexpression$2", "symbols": ["escaped_entry"]}, {"name": "non_entry$ebnf$1$subexpression$2", "symbols": ["escaped_escape"]}, {"name": "non_entry$ebnf$1$subexpression$2", "symbols": ["escaped_non_esc_outside_entry"]}, {"name": "non_entry$ebnf$1$subexpression$2", "symbols": ["non_esc_outside_entry"]}, { "name": "non_entry$ebnf$1", "symbols": ["non_entry$ebnf$1", "non_entry$ebnf$1$subexpression$2"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "non_entry", "symbols": ["non_entry$ebnf$1"], "postprocess": function (data) { // console.log("non_entry",data); const tokens: any = []; for (let Ti = 0; Ti < data[0].length; Ti++) tokens.push(data[0][Ti][0]); return tokens; } }, { "name": "escaped_escape", "symbols": [esc, esc], "postprocess": function () { return "\\"; } }, { "name": "escaped_entry", "symbols": [esc, "entry_decl"], "postprocess": function (data) { return {type: "escapedEntry", data: data[1]}; } }, { "name": "escaped_non_esc_outside_entry", "symbols": [esc, "non_esc_outside_entry"], "postprocess": function (data) { return data; // ["\\", data[1]]; } }, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [tok_id]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [ws]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [num]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [pound]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [eq]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [paren_l]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [paren_r]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [brace_l]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [brace_r]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [quote_dbl]}, {"name": "non_esc_outside_entry$subexpression$1", "symbols": [comma]}, { "name": "non_esc_outside_entry", "symbols": ["non_esc_outside_entry$subexpression$1"], "postprocess": function (data) { // console.log("ooutside_entry",data[0][0]); return data[0][0]; } } ] , ParserStart: "main" };
the_stack
"use strict"; // import knockout from 'terriajs-cesium/Source/ThirdParty/knockout'; import React from "react"; import { findAll, findAllWithType, findAllWithClass, findWithRef } from "react-shallow-testutils"; import { getShallowRenderedOutput, findAllEqualTo, findAllWithPropsChildEqualTo } from "./MoreShallowTools"; import Cartographic from "terriajs-cesium/Source/Core/Cartographic"; import Ellipsoid from "terriajs-cesium/Source/Core/Ellipsoid"; import Entity from "terriajs-cesium/Source/DataSources/Entity"; import JulianDate from "terriajs-cesium/Source/Core/JulianDate"; import loadJson from "../../lib/Core/loadJson"; import TimeInterval from "terriajs-cesium/Source/Core/TimeInterval"; import TimeIntervalCollectionProperty from "terriajs-cesium/Source/DataSources/TimeIntervalCollectionProperty"; import CreateModel from "../../lib/Models/Definition/CreateModel"; import CzmlCatalogItem from "../../lib/Models/Catalog/CatalogItems/CzmlCatalogItem"; import { FeatureInfoSection } from "../../lib/ReactViews/FeatureInfo/FeatureInfoSection"; import Terria from "../../lib/Models/Terria"; import Styles from "../../lib/ReactViews/FeatureInfo/feature-info-section.scss"; import upsertModelFromJson from "../../lib/Models/Definition/upsertModelFromJson"; import CommonStrata from "../../lib/Models/Definition/CommonStrata"; import MappableTraits from "../../lib/Traits/TraitsClasses/MappableTraits"; import mixTraits from "../../lib/Traits/mixTraits"; import FeatureInfoTraits from "../../lib/Traits/TraitsClasses/FeatureInfoTraits"; import DiscretelyTimeVaryingTraits from "../../lib/Traits/TraitsClasses/DiscretelyTimeVaryingTraits"; import DiscretelyTimeVaryingMixin from "../../lib/ModelMixins/DiscretelyTimeVaryingMixin"; import MappableMixin, { MapItem } from "../../lib/ModelMixins/MappableMixin"; import CatalogMemberMixin from "../../lib/ModelMixins/CatalogMemberMixin"; import { observable } from "mobx"; import i18next from "i18next"; import CatalogMemberFactory from "../../lib/Models/Catalog/CatalogMemberFactory"; let separator = ","; if (typeof Intl === "object" && typeof Intl.NumberFormat === "function") { const thousand = Intl.NumberFormat().format(1000); if (thousand.length === 5) { separator = thousand[1]; } } const contentClass = Styles.content; function findAllWithHref(reactElement: any, text: any) { return findAll( reactElement, (element: any) => element && element.props && element.props.href === text ); } // Takes the absolute value of the value and pads it to 2 digits i.e. 7->07, 17->17, -3->3, -13->13. It is expected that value is an integer is in the range [0, 99]. function absPad2(value: number) { return (Math.abs(value) < 10 ? "0" : "") + Math.abs(value); } describe("FeatureInfoSection", function() { let terria: Terria; let feature: any; let viewState: any; let catalogItem: TestModel; beforeEach(function() { terria = new Terria({ baseUrl: "./" }); catalogItem = new TestModel("test", terria); viewState = {}; // Not important for tests, but is a required prop. const properties = { name: "Kay", foo: "bar", material: "steel", "material.process.#1": "smelted", size: "12345678.9012", efficiency: "0.2345678", date: "2017-11-23T08:47:53Z", owner_html: "Jay<br>Smith", ampersand: "A & B", lessThan: "A < B", unsafe: 'ok!<script>alert("gotcha")</script>' }; feature = new Entity({ name: "Bar", properties: properties }); }); it("renders a static description", function() { feature.description = { getValue: function() { return "<p>hi!</p>"; }, isConstant: true }; const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllWithType(result, "p").length).toEqual(1); expect(findAllEqualTo(result, "hi!").length).toEqual(1); }); it("does not render unsafe html", function() { feature.description = { getValue: function() { return '<script>alert("gotcha")</script><p>hi!</p>'; }, isConstant: true }; const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllWithType(result, "script").length).toEqual(0); expect(findAllEqualTo(result, 'alert("gotcha")').length).toEqual(0); expect(findAllWithType(result, "p").length).toEqual(1); expect(findAllEqualTo(result, "hi!").length).toEqual(1); }); function timeVaryingDescription() { const desc = new TimeIntervalCollectionProperty(); desc.intervals.addInterval( new TimeInterval({ start: JulianDate.fromDate(new Date("2010-01-01")), stop: JulianDate.fromDate(new Date("2011-01-01")), data: "<p>hi</p>" }) ); desc.intervals.addInterval( new TimeInterval({ start: JulianDate.fromDate(new Date("2011-01-01")), stop: JulianDate.fromDate(new Date("2012-01-01")), data: "<p>bye</p>" }) ); return desc; } it("renders a time-varying description", function() { feature.description = timeVaryingDescription(); catalogItem.setTrait(CommonStrata.user, "currentTime", "2011-06-30"); const section = ( <FeatureInfoSection feature={feature} isOpen={true} catalogItem={catalogItem} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "hi").length).toEqual(0); expect(findAllEqualTo(result, "bye").length).toEqual(1); catalogItem.setTrait(CommonStrata.user, "currentTime", "2010-06-30"); const section2 = ( <FeatureInfoSection feature={feature} isOpen={true} catalogItem={catalogItem} viewState={viewState} t={() => {}} /> ); const result2 = getShallowRenderedOutput(section2); expect(findAllEqualTo(result2, "hi").length).toEqual(1); expect(findAllEqualTo(result2, "bye").length).toEqual(0); }); it("handles features with no properties", function() { feature = new Entity({ name: "Foot", description: "bart" }); const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Foot").length).toEqual(1); expect(findAllEqualTo(result, "bart").length).toEqual(1); }); it("handles html format feature info", function() { feature = new Entity({ name: "Foo", description: "<html><head><title>GetFeatureInfo</title></head><body><table><tr><th>thing</th></tr><tr><td>BAR</td></tr></table><br/></body></html>" }); const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Foo").length).toEqual(1); expect(findAllEqualTo(result, "BAR").length).toEqual(1); }); it("handles html format feature info where markdown would break the html", function() { feature = new Entity({ name: "Foo", description: "<html><head><title>GetFeatureInfo</title></head><body><table>\n\n <tr>\n\n<th>thing</th></tr><tr><td>BAR</td></tr></table><br/></body></html>" }); // Markdown applied to this description would pull out the lonely <tr> and make it <pre><code><tr>\n</code></pre> , so check this doesn't happen. const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "<tr>\n").length).toEqual(0); expect(findAllEqualTo(result, "&lt;\n").length).toEqual(0); // Also cover the possibility that it might be encoded. }); it("maintains and applies inline style attributes", function() { feature = new Entity({ name: "Foo", description: '<div style="background:rgb(170, 187, 204)">countdown</div>' }); const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); const divs = findAllWithPropsChildEqualTo(result, "countdown"); expect(divs.length).toEqual(1); // Note #ABC is converted by IE11 to rgb(170, 187, 204), so just test that directly. Also IE11 adds space to the front, so strip all spaces out. expect(divs[0].props.style.background.replace(/ /g, "")).toEqual( "rgb(170,187,204)" ); }); it("does not break when html format feature info has style tag", function() { // Note this does not test that it actually uses the style tag for styling. feature = new Entity({ name: "Foo", description: '<html><head><title>GetFeatureInfo</title></head><style>table.info tr {background:#fff;}</style><body><table class="info"><tr><th>thing</th></tr><tr><td>BAR</td></tr></table><br/></body></html>' }); const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Foo").length).toEqual(1); expect(findAllEqualTo(result, "BAR").length).toEqual(1); }); it("does not break when there are neither properties nor description", function() { feature = new Entity({ name: "Vapid" }); const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Vapid").length).toEqual(1); expect(findWithRef(result, "no-info")).toBeDefined(); }); it("shows properties if no description", function() { // Tests both static and potentially time-varying properties. feature = new Entity({ name: "Meals", properties: { lunch: "eggs", dinner: { getValue: function() { return "ham"; } } } }); const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Meals").length).toEqual(1); expect(findAllEqualTo(result, "lunch").length).toEqual(1); expect(findAllEqualTo(result, "eggs").length).toEqual(1); expect(findAllEqualTo(result, "dinner").length).toEqual(1); expect(findAllEqualTo(result, "ham").length).toEqual(1); }); describe("templating", function() { it("uses and completes a string-form featureInfoTemplate if present", function() { const template = "This is a {{material}} {{foo}}."; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "This is a steel bar.").length).toEqual(1); }); it("can use _ to refer to . and # in property keys in the featureInfoTemplate", function() { const template = "Made from {{material_process__1}} {{material}}."; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Made from smelted steel.").length).toEqual( 1 ); }); it("formats large numbers without commas", function() { const template = "Size: {{size}}"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Size: 12345678.9012").length).toEqual(1); }); it("can format numbers with commas", function() { const template = { template: "Size: {{size}}", formats: { size: { type: "number", useGrouping: true } } }; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect( findAllEqualTo( result, "Size: 12" + separator + "345" + separator + "678.9012" ).length ).toEqual(1); }); it("formats numbers in the formats section with no type as if type were number", function() { const template = { template: "Size: {{size}}", formats: { size: { useGrouping: true } } }; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect( findAllEqualTo( result, "Size: 12" + separator + "345" + separator + "678.9012" ).length ).toEqual(1); }); it("can format numbers using terria.formatNumber", function() { let template = "Base: {{#terria.formatNumber}}{{size}}{{/terria.formatNumber}}"; template += ' Sep: {{#terria.formatNumber}}{"useGrouping":true, "maximumFractionDigits":3}{{size}}{{/terria.formatNumber}}'; template += ' DP: {{#terria.formatNumber}}{"maximumFractionDigits":3}{{efficiency}}{{/terria.formatNumber}}'; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect( findAllEqualTo( result, "Base: 12345678.9012 Sep: 12" + separator + "345" + separator + "678.901 DP: 0.235" ).length ).toEqual(1); }); it("can format numbers using terria.formatNumber without quotes", function() { let template = "Sep: {{#terria.formatNumber}}{useGrouping:true, maximumFractionDigits:3}{{size}}{{/terria.formatNumber}}"; template += " DP: {{#terria.formatNumber}}{maximumFractionDigits:3}{{efficiency}}{{/terria.formatNumber}}"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect( findAllEqualTo( result, "Sep: 12" + separator + "345" + separator + "678.901 DP: 0.235" ).length ).toEqual(1); }); it("can handle white text in terria.formatNumber", function() { const template = 'Sep: {{#terria.formatNumber}}{"useGrouping":true, "maximumFractionDigits":3} \n {{size}}{{/terria.formatNumber}}'; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect( findAllEqualTo( result, "Sep: 12" + separator + "345" + separator + "678.901" ).length ).toEqual(1); }); it("handles non-numbers terria.formatNumber", function() { const template = "Test: {{#terria.formatNumber}}text{{/terria.formatNumber}}"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Test: text").length).toEqual(1); }); it("can use a dateFormatString when it is specified in terria.formatDateTime", function() { const template = 'Test: {{#terria.formatDateTime}}{"format": "dd-mm-yyyy HH:MM:ss"}2017-11-23T08:47:53Z{{/terria.formatDateTime}}'; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); const date = new Date(Date.UTC(2017, 11, 23, 8, 47, 53)); const formattedDate = absPad2(date.getDate()) + "-" + absPad2(date.getMonth()) + "-" + date.getFullYear() + " " + absPad2(date.getHours()) + ":" + absPad2(date.getMinutes()) + ":" + absPad2(date.getSeconds()); // E.g. "23-11-2017 19:47:53" expect(findAllEqualTo(result, "Test: " + formattedDate).length).toEqual( 1 ); }); it("defaults dateFormatString to isoDateTime when it is not specified in terria.formatDateTime", function() { const template = "Test: {{#terria.formatDateTime}}2017-11-23T08:47:53Z{{/terria.formatDateTime}}"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); const date = new Date(Date.UTC(2017, 11, 23, 8, 47, 53)); const offset = -date.getTimezoneOffset(); const offsetMinute = offset % 60; const offsetHour = (offset - offsetMinute) / 60; const timeZone = (offset >= 0 ? "+" : "-") + absPad2(offsetHour) + "" + absPad2(offsetMinute); const formattedDate = date.getFullYear() + "-" + absPad2(date.getMonth()) + "-" + absPad2(date.getDate()) + "T" + absPad2(date.getHours()) + ":" + absPad2(date.getMinutes()) + ":" + absPad2(date.getSeconds()) + timeZone; // E.g. "2017-11-23T19:47:53+1100" expect(findAllEqualTo(result, "Test: " + formattedDate).length).toEqual( 1 ); }); it("can format dates using the dateTime as the type within the formats section", function() { const template = { template: "Date: {{date}}", formats: { date: { type: "dateTime", format: "dd-mm-yyyy HH:MM:ss" } } }; const section = ( <FeatureInfoSection feature={feature} isOpen={true} catalogItem={catalogItem} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); const date = new Date(Date.UTC(2017, 11, 23, 8, 47, 53)); const formattedDate = absPad2(date.getDate()) + "-" + absPad2(date.getMonth()) + "-" + date.getFullYear() + " " + absPad2(date.getHours()) + ":" + absPad2(date.getMinutes()) + ":" + absPad2(date.getSeconds()); // E.g. "23-11-2017 19:47:53" expect(findAllEqualTo(result, "Date: " + formattedDate).length).toEqual( 1 ); }); it("handles non-numbers in terria.formatDateTime", function() { const template = "Test: {{#terria.formatDateTime}}text{{/terria.formatDateTime}}"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Test: text").length).toEqual(1); }); it("url encodes text components", function() { const template = "Test: {{#terria.urlEncodeComponent}}W/HO:E#1{{/terria.urlEncodeComponent}}"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Test: W%2FHO%3AE%231").length).toEqual(1); }); it("url encodes sections of text", function() { const template = "Test: {{#terria.urlEncode}}http://example.com/a b{{/terria.urlEncode}}"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect( findAllWithHref(result, "http://example.com/a%20b").length ).toEqual(1); }); it("does not escape ampersand as &amp;", function() { const template = { template: "Ampersand: {{ampersand}}" }; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Ampersand: A & B").length).toEqual(1); expect(findAllEqualTo(result, "&amp;").length).toEqual(0); }); it("does not escape < as &lt;", function() { const template = { template: "Less than: {{lessThan}}" }; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Less than: A < B").length).toEqual(1); expect(findAllEqualTo(result, "&lt;").length).toEqual(0); }); it("can embed safe html in template", function() { const template = "<div>Hello {{owner_html}}.</div>"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Hello Jay").length).toEqual(1); expect(findAllWithType(result, "br").length).toEqual(1); expect(findAllEqualTo(result, "Smith.").length).toEqual(1); }); it("cannot embed unsafe html in template", function() { const template = "<div>Hello {{unsafe}}</div>"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Hello ok!").length).toEqual(1); expect(findAllWithType(result, "script").length).toEqual(0); expect(findAllEqualTo(result, 'alert("gotcha")').length).toEqual(0); }); it("can use a json featureInfoTemplate with partials", function() { const template = { template: '<div class="jj">test {{>boldfoo}}</div>', partials: { boldfoo: "<b>{{foo}}</b>" } }; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllWithClass(result, "jk").length).toEqual(0); // just to be sure the null case gives 0. expect(findAllWithClass(result, "jj").length).toEqual(1); expect(findAllWithType(result, "b").length).toEqual(1); expect(findAllEqualTo(result, "test ").length).toEqual(1); expect(findAllEqualTo(result, "bar").length).toEqual(1); }); it("sets the name from featureInfoTemplate", function() { const template = { name: "{{name}} {{foo}}" }; const section = ( <FeatureInfoSection feature={feature} isOpen={false} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); const nameElement = findAllWithClass(result, Styles.title)[0]; const nameSpan = nameElement.props.children[0]; const name = nameSpan.props.children; expect(name).toContain("Kay bar"); }); it("can access clicked lat and long", function() { const template = "<div>Clicked {{#terria.formatNumber}}{maximumFractionDigits:0}{{terria.coords.latitude}}{{/terria.formatNumber}}, {{#terria.formatNumber}}{maximumFractionDigits:0}{{terria.coords.longitude}}{{/terria.formatNumber}}</div>"; const position = Ellipsoid.WGS84.cartographicToCartesian( Cartographic.fromDegrees(77, 44, 6) ); const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} position={position} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Clicked 44, 77").length).toEqual(1); }); it("can replace text, using terria.partialByName", function() { // Replace "Kay" of feature.properties.name with "Yak", or "This name" with "That name". const template = { template: "{{#terria.partialByName}}{{name}}{{/terria.partialByName}}", partials: { Bar: "Rab", Kay: "Yak", "This name": "That name" } }; let section = ( <FeatureInfoSection feature={feature} // feature.properties.name === "Kay"; isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); let result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Yak").length).toEqual(1); expect(findAllEqualTo(result, "Kay").length).toEqual(0); feature.properties.name = "This name"; section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "That name").length).toEqual(1); expect(findAllEqualTo(result, "Yak").length).toEqual(0); }); it("does not replace text if no matching, using terria.partialByName", function() { const template = { template: "{{#terria.partialByName}}{{name}}{{/terria.partialByName}}", partials: { Bar: "Rab", NotKay: "Yak", "This name": "That name" } }; const section = ( <FeatureInfoSection feature={feature} // feature.properties.name === "Kay"; isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Yak").length).toEqual(0); expect(findAllEqualTo(result, "Kay").length).toEqual(1); }); it("can replace text and filter out unsafe replacement, using terria.partialByName", function() { const template = { template: "{{#terria.partialByName}}{{name}}{{/terria.partialByName}}", partials: { Bar: "Rab", Kay: "Yak!<script>alert('gotcha')</script>", This: "That" } }; const section = ( <FeatureInfoSection feature={feature} // feature.properties.name === "Kay"; isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "Yak!").length).toEqual(1); expect(findAllEqualTo(result, "Yak!alert('gotcha')").length).toEqual(0); expect(findAllEqualTo(result, "alert('gotcha')").length).toEqual(0); expect( findAllEqualTo(result, "Yak!<script>alert('gotcha')</script>").length ).toEqual(0); expect(findAllEqualTo(result, "Kay").length).toEqual(0); }); /* // v8 version does not support this feature at the moment. See https://github.com/TerriaJS/terriajs/issues/5685 it("can access the current time", function() { const template = "<div class='rrrr'>Time: {{terria.currentTime}}</div>"; catalogItem._discreteTimes = ["2017-11-23", "2018-01-03"]; // const timeInterval = new TimeInterval({ // start: JulianDate.fromIso8601("2017-11-23T19:47:53+11:00"), // stop: JulianDate.fromIso8601("2018-01-03T07:05:00Z"), // isStartIncluded: true, // isStopIncluded: false // }); // const intervals = new TimeIntervalCollection([timeInterval]); // const availableDate = JulianDate.toDate(timeInterval.start); // catalogItem.intervals = intervals; // catalogItem.availableDates = [availableDate]; // catalogItem.canUseOwnClock = true; // catalogItem.useOwnClock = true; // catalogItem.clock.currentTime = JulianDate.fromIso8601( // "2017-12-19T17:13:11+07:00" // ); catalogItem.setTrait(CommonStrata.user, "currentTime", "2017-12-01"); terria.timelineClock.currentTime = JulianDate.fromIso8601( "2001-01-01T01:01:01+01:00" ); // An decoy date to make sure that we are indeed using the catalog items clock and not terria.clock. const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} catalogItem={catalogItem} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, catalogItem._discreteTimes[0]).length).toEqual( 1 ); }); */ it("can render a recursive featureInfoTemplate", function() { const template = { template: "<ul>{{>show_children}}</ul>", partials: { show_children: "{{#children}}<li>{{name}}<ul>{{>show_children}}</ul></li>{{/children}}" } }; feature.properties.merge({ children: [ { name: "Alice", children: [ { name: "Bailey", children: null }, { name: "Beatrix", children: null } ] }, { name: "Xavier", children: [ { name: "Yann", children: null }, { name: "Yvette", children: null } ] } ] }); // const recursedHtml = '' // + '<ul>' // + '<li>Alice' // + '<ul>' // + '<li>' + 'Bailey' + '<ul></ul>' + '</li>' // + '<li>' + 'Beatrix' + '<ul></ul>' + '</li>' // + '</ul>' // + '</li>' // + '<li>Xavier' // + '<ul>' // + '<li>' + 'Yann' + '<ul></ul>' + '</li>' // + '<li>' + 'Yvette' + '<ul></ul>' + '</li>' // + '</ul>' // + '</li>' // + '</ul>'; const section = ( <FeatureInfoSection feature={feature} isOpen={true} template={template} viewState={viewState} t={() => {}} /> ); const result = getShallowRenderedOutput(section); const content = findAllWithClass(result, contentClass)[0]; expect(findAllWithType(content, "ul").length).toEqual(7); expect(findAllWithType(content, "li").length).toEqual(6); }); }); describe("raw data", function() { beforeEach(function() { feature.description = { getValue: function() { return "<p>hi!</p>"; }, isConstant: true }; }); it("does not appear if no template", function() { const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} t={i18next.t} /> ); const result = getShallowRenderedOutput(section); expect( findAllEqualTo(result, "featureInfo.showCuratedData").length ).toEqual(0); expect(findAllEqualTo(result, "featureInfo.showRawData").length).toEqual( 0 ); }); it('shows "Show Raw Data" if template', function() { const template = "Test"; const section = ( <FeatureInfoSection feature={feature} isOpen={true} viewState={viewState} template={template} t={i18next.getFixedT("cimode")} /> ); const result = getShallowRenderedOutput(section); expect( findAllEqualTo(result, "featureInfo.showCuratedData").length ).toEqual(0); expect(findAllEqualTo(result, "featureInfo.showRawData").length).toEqual( 1 ); }); }); describe("CZML templating", function() { beforeEach(function() {}); it("uses and completes a string-form featureInfoTemplate", async function() { // target = '<table><tbody><tr><td>Name:</td><td>Test</td></tr><tr><td>Type:</td><td>ABC</td></tr></tbody></table><br /> // <table><tbody><tr><td>Year</td><td>Capacity</td></tr><tr><td>2010</td><td>14.4</td></tr><tr><td>2011</td><td>22.8</td></tr><tr><td>2012</td><td>10.7</td></tr></tbody></table>'; const json = await loadJson("test/init/czml-with-template-0.json"); const czmlItem = upsertModelFromJson( CatalogMemberFactory, terria, "", "definition", json, {} ).throwIfUndefined() as CzmlCatalogItem; await czmlItem.loadMapItems(); const czmlData = czmlItem.mapItems; expect(czmlData.length).toBeGreaterThan(0); const czmlFeature = czmlData[0].entities.values[0]; const section = ( <FeatureInfoSection feature={czmlFeature} isOpen={true} viewState={viewState} template={czmlItem.featureInfoTemplate} t={() => {}} /> ); const result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "ABC").length).toEqual(1); expect(findAllEqualTo(result, "2010").length).toEqual(1); expect(findAllEqualTo(result, "14.4").length).toEqual(1); expect(findAllEqualTo(result, "2012").length).toEqual(1); expect(findAllEqualTo(result, "10.7").length).toEqual(1); }); it("uses and completes a time-varying, string-form featureInfoTemplate", async function() { // targetBlank = '<table><tbody><tr><td>Name:</td><td>Test</td></tr><tr><td>Type:</td><td></td></tr></tbody></table><br /> // <table><tbody><tr><td>Year</td><td>Capacity</td></tr><tr><td>2010</td><td>14.4</td></tr><tr><td>2011</td><td>22.8</td></tr><tr><td>2012</td><td>10.7</td></tr></tbody></table>'; // targetABC = '<table><tbody><tr><td>Name:</td><td>Test</td></tr><tr><td>Type:</td><td>ABC</td></tr></tbody></table><br /> // <table><tbody><tr><td>Year</td><td>Capacity</td></tr><tr><td>2010</td><td>14.4</td></tr><tr><td>2011</td><td>22.8</td></tr><tr><td>2012</td><td>10.7</td></tr></tbody></table>'; // targetDEF = '<table><tbody><tr><td>Name:</td><td>Test</td></tr><tr><td>Type:</td><td>DEF</td></tr></tbody></table><br /> // <table><tbody><tr><td>Year</td><td>Capacity</td></tr><tr><td>2010</td><td>14.4</td></tr><tr><td>2011</td><td>22.8</td></tr><tr><td>2012</td><td>10.7</td></tr></tbody></table>'; const json = await loadJson("test/init/czml-with-template-1.json"); const czmlItem = upsertModelFromJson( CatalogMemberFactory, terria, "", "definition", json, {} ).throwIfUndefined() as CzmlCatalogItem; await czmlItem.loadMapItems(); const czmlData = czmlItem.mapItems; expect(czmlData.length).toBeGreaterThan(0); const czmlFeature = czmlData[0].entities.values[0]; czmlItem.setTrait(CommonStrata.user, "currentTime", "2010-02-02"); let section = ( <FeatureInfoSection feature={czmlFeature} isOpen={true} catalogItem={czmlItem} viewState={viewState} template={czmlItem.featureInfoTemplate} t={() => {}} /> ); let result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "ABC").length).toEqual(0); expect(findAllEqualTo(result, "DEF").length).toEqual(0); czmlItem.setTrait(CommonStrata.user, "currentTime", "2012-02-02"); section = ( <FeatureInfoSection feature={czmlFeature} isOpen={true} catalogItem={czmlItem} viewState={viewState} template={czmlItem.featureInfoTemplate} t={() => {}} /> ); result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "ABC").length).toEqual(1); expect(findAllEqualTo(result, "DEF").length).toEqual(0); czmlItem.setTrait(CommonStrata.user, "currentTime", "2014-02-02"); section = ( <FeatureInfoSection feature={czmlFeature} isOpen={true} catalogItem={czmlItem} viewState={viewState} template={czmlItem.featureInfoTemplate} t={() => {}} /> ); result = getShallowRenderedOutput(section); expect(findAllEqualTo(result, "ABC").length).toEqual(0); expect(findAllEqualTo(result, "DEF").length).toEqual(1); }); }); }); // Test time varying item // Mixins: discretely time varying & Mappable mixins // Traits: traits for the above class TestModelTraits extends mixTraits( FeatureInfoTraits, MappableTraits, DiscretelyTimeVaryingTraits ) {} class TestModel extends MappableMixin( DiscretelyTimeVaryingMixin(CatalogMemberMixin(CreateModel(TestModelTraits))) ) { get mapItems(): MapItem[] { throw new Error("Method not implemented."); } protected forceLoadMapItems(): Promise<void> { throw new Error("Method not implemented."); } @observable _discreteTimes: string[] = []; get discreteTimes() { return this._discreteTimes.map(t => ({ time: t, tag: undefined })); } }
the_stack
import { createReducerFromMap, SUCCESS, FAIL, Action, createActionCreator, actionStatus, } from './helpers'; import { SET_IS_SMALL_SCREEN, SET_SEARCH_FIELDS, RESET_SEARCH, TOGGLE_SEARCH_DETAILS, TOGGLE_MENU, REQUEST_USER_ACTION, IMPORT_INSTANCE, CREATE_ACCESS, RUN_ACCOUNTS_SYNC, RUN_BALANCE_RESYNC, RUN_OPERATIONS_SYNC, RUN_APPLY_BULKEDIT, UPDATE_ACCESS_AND_FETCH, ENABLE_DEMO_MODE, SET_SETTING, } from './actions'; import { assertDefined, computeIsSmallScreen } from '../helpers'; import { DARK_MODE, FLUID_LAYOUT } from '../../shared/settings'; import { produce } from 'immer'; import { AnyAction } from 'redux'; import { FinishUserAction } from './banks'; import { UserActionField } from '../../shared/types'; import { KeyValue } from './settings'; import { EnableDemoParams } from '.'; // All the possible search fields. // Note: update `reduceSetSearchField` if you add a field here. export type SearchFields = { keywords: string[]; categoryIds: number[]; type: string; amountLow: number | null; amountHigh: number | null; dateLow: Date | null; dateHigh: Date | null; }; export type UserActionRequested = { message: string | null; fields: UserActionField[] | null; finish: FinishUserAction; }; export type UiState = { search: SearchFields; displaySearchDetails: boolean; isSmallScreen: boolean; isMenuHidden: boolean; isDemoMode: boolean; processingReason: string | null; userActionRequested: UserActionRequested | null; }; // Sets a group of search fields. export function setSearchFields(map: Partial<SearchFields>) { return setSearchFieldsAction({ map }); } type SetSearchFieldsParams = { map: Partial<SearchFields> }; const setSearchFieldsAction = createActionCreator<SetSearchFieldsParams>(SET_SEARCH_FIELDS); function reduceSetSearchFields(state: UiState, action: Action<SetSearchFieldsParams>) { const { map } = action; return produce(state, draft => { draft.search = { ...draft.search, ...map }; return draft; }); } // Clears all the search fields export function resetSearch() { return resetSearchAction(); } const resetSearchAction = createActionCreator<void>(RESET_SEARCH); // eslint-disable-next-line @typescript-eslint/no-unused-vars function reduceResetSearch(state: UiState, _action: Action<void>) { return produce(state, draft => { draft.search = initialSearch(); return draft; }); } // Opens or closes the search details window. export function toggleSearchDetails(show: boolean | undefined) { return toggleSearchDetailsAction({ show }); } type ToggleSearchDetailsParams = { show?: boolean }; const toggleSearchDetailsAction = createActionCreator<ToggleSearchDetailsParams>(TOGGLE_SEARCH_DETAILS); function reduceToggleSearchDetails(state: UiState, action: Action<ToggleSearchDetailsParams>) { const { show: showOrUndefined } = action; const show = typeof showOrUndefined === 'undefined' ? !getDisplaySearchDetails(state) : showOrUndefined; return produce(state, draft => { draft.displaySearchDetails = show; return draft; }); } // Defines that the app is now running in small screen mode. export function setIsSmallScreen(isSmall: boolean) { return setIsSmallScreenAction({ isSmall }); } type SetIsSmallScreenParams = { isSmall: boolean }; const setIsSmallScreenAction = createActionCreator<SetIsSmallScreenParams>(SET_IS_SMALL_SCREEN); function reduceSetIsSmallScreen(state: UiState, action: Action<SetIsSmallScreenParams>) { const { isSmall } = action; return produce(state, draft => { draft.isSmallScreen = isSmall; return draft; }); } // Opens or closes the (left) menu. export function toggleMenu(hide: boolean | undefined) { return toggleMenuAction({ hide }); } type ToggleMenuParams = { hide?: boolean }; const toggleMenuAction = createActionCreator<ToggleMenuParams>(TOGGLE_MENU); function reduceToggleMenu(state: UiState, action: Action<ToggleMenuParams>) { const { hide: hideOrUndefined } = action; const hide = typeof hideOrUndefined === 'undefined' ? !isMenuHidden(state) : hideOrUndefined; return produce(state, draft => { draft.isMenuHidden = hide; return draft; }); } // Requests the accomplishment of a user action to the user. export function requestUserAction( finish: FinishUserAction, message: string | null, fields: UserActionField[] | null ) { return requestUserActionAction({ finish, message, fields }); } export function finishUserAction() { return actionStatus.ok(requestUserActionAction({})); } type RequestUserActionParams = { finish?: FinishUserAction; message?: string | null; fields?: UserActionField[] | null; }; const requestUserActionAction = createActionCreator<RequestUserActionParams>(REQUEST_USER_ACTION); function reduceUserAction(state: UiState, action: Action<RequestUserActionParams>) { return produce(state, draft => { if (action.status === SUCCESS) { draft.userActionRequested = null; return draft; } assertDefined(action.message); assertDefined(action.fields); assertDefined(action.finish); // Clear the processing reason, in case there was one. The finish() // action should reset it. draft.processingReason = null; draft.userActionRequested = { message: action.message, fields: action.fields, finish: action.finish, }; return draft; }); } // Generates the reducer to display or not the spinner. function showSpinnerWithReason(processingReason: string) { return (state: UiState, action: AnyAction) => { const { status } = action; return produce(state, draft => { draft.processingReason = status === FAIL || status === SUCCESS ? null : processingReason; return draft; }); }; } function setDarkMode(enabled: boolean) { document.body.classList.toggle('dark', enabled); } function setFluidLayout(enabled: boolean) { document.body.classList.toggle('fluid', enabled); } // External reducers. function reduceSetSetting(state: UiState, action: Action<KeyValue>) { switch (action.key) { case DARK_MODE: { const enabled = typeof action.value === 'boolean' ? action.value : action.value === 'true'; setDarkMode(enabled); break; } case FLUID_LAYOUT: { const enabled = typeof action.value === 'boolean' ? action.value : action.value === 'true'; setFluidLayout(enabled); break; } default: break; } return state; } function reduceEnableDemo(state: UiState, action: Action<EnableDemoParams>): UiState { const msg = action.enabled ? 'client.demo.enabling' : 'client.demo.disabling'; return showSpinnerWithReason(msg)(state, action); } const reducers = { // Own reducers. [REQUEST_USER_ACTION]: reduceUserAction, [RESET_SEARCH]: reduceResetSearch, [SET_IS_SMALL_SCREEN]: reduceSetIsSmallScreen, [SET_SEARCH_FIELDS]: reduceSetSearchFields, [TOGGLE_MENU]: reduceToggleMenu, [TOGGLE_SEARCH_DETAILS]: reduceToggleSearchDetails, // External actions. [SET_SETTING]: reduceSetSetting, [ENABLE_DEMO_MODE]: reduceEnableDemo, // Processing reasons reducers. [CREATE_ACCESS]: showSpinnerWithReason('client.spinner.fetch_account'), [IMPORT_INSTANCE]: showSpinnerWithReason('client.spinner.import'), [RUN_ACCOUNTS_SYNC]: showSpinnerWithReason('client.spinner.sync'), [RUN_APPLY_BULKEDIT]: showSpinnerWithReason('client.spinner.apply'), [RUN_BALANCE_RESYNC]: showSpinnerWithReason('client.spinner.balance_resync'), [RUN_OPERATIONS_SYNC]: showSpinnerWithReason('client.spinner.sync'), [UPDATE_ACCESS_AND_FETCH]: showSpinnerWithReason('client.spinner.fetch_account'), }; export const reducer = createReducerFromMap(reducers); // Initial state. function initialSearch(): SearchFields { // Keep in sync with hasSearchFields. return { keywords: [], categoryIds: [], type: '', amountLow: null, amountHigh: null, dateLow: null, dateHigh: null, }; } export function initialState( isDemoEnabled: boolean, enabledDarkMode: boolean, enabledFluidLayout: boolean ): UiState { const search = initialSearch(); setDarkMode(enabledDarkMode); setFluidLayout(enabledFluidLayout); return { search, displaySearchDetails: false, processingReason: null, userActionRequested: null, isDemoMode: isDemoEnabled, isSmallScreen: computeIsSmallScreen(), isMenuHidden: computeIsSmallScreen(), }; } // Getters. export function getSearchFields(state: UiState): SearchFields { return state.search; } export function hasSearchFields(state: UiState): boolean { // Keep in sync with initialSearch(); const { search } = state; return ( search.keywords.length > 0 || search.categoryIds.length > 0 || search.type !== '' || search.amountLow !== null || search.amountHigh !== null || search.dateLow !== null || search.dateHigh !== null ); } export function getDisplaySearchDetails(state: UiState): boolean { return state.displaySearchDetails; } export function getProcessingReason(state: UiState): string | null { return state.processingReason; } export function isSmallScreen(state: UiState): boolean { return state.isSmallScreen; } export function isMenuHidden(state: UiState): boolean { return state.isMenuHidden; } export function isDemoMode(state: UiState): boolean { return state.isDemoMode; } export function userActionRequested(state: UiState): UserActionRequested | null { return state.userActionRequested; }
the_stack
class PlotBasics { private plotTitleSpan: HTMLSpanElement; private range_x: jquery.flot.range; private range_y: jquery.flot.range; private reset_range: boolean; private options: jquery.flot.plotOptions; private plot: jquery.flot.plot; private plot_data: Array<Array<number>>; private isPeakDetection: boolean = true; private peakDatapointSpan: HTMLSpanElement; private peakDatapoint: number[]; private hoverDatapointSpan: HTMLSpanElement; private hoverDatapoint: number[]; private clickDatapointSpan: HTMLSpanElement; private clickDatapoint: number[]; constructor(document: Document, private plot_placeholder: JQuery, private plotDriver: Plot, private n_pts: number, public x_min, public x_max, public y_min, public y_max, private driver, private rangeFunction, private plotTitle: string) { this.plotTitleSpan = <HTMLSpanElement>document.getElementById("plot-title"); this.plotTitleSpan.textContent = this.plotTitle; this.range_x = <jquery.flot.range>{}; this.range_x.from = this.x_min; this.range_x.to = this.x_max; this.range_y = <jquery.flot.range>{}; this.range_y.from = this.y_min; this.range_y.to = this.y_max; this.setPlot(this.range_x.from, this.range_x.to, this.range_y.from, this.range_y.to); this.rangeSelect(this.rangeFunction); this.dblClick(this.rangeFunction); this.onWheel(this.rangeFunction); this.showHoverPoint(); this.showClickPoint(); this.plotLeave(); this.reset_range = true; this.hoverDatapointSpan = <HTMLSpanElement>document.getElementById("hover-datapoint"); this.hoverDatapoint = []; this.clickDatapointSpan = <HTMLSpanElement>document.getElementById("click-datapoint"); this.clickDatapoint = []; this.peakDatapointSpan = <HTMLSpanElement>document.getElementById("peak-datapoint"); this.plot_data = []; this.initUnitInputs(); this.initPeakDetection(); } setPlot(x_min: number, x_max: number, y_min: number, y_max: number) { this.reset_range = false; this.options = { canvas: true, series: { shadowSize: 0 // Drawing is faster without shadows }, yaxis: { min: y_min, max: y_max }, xaxis: { min: x_min, max: x_max, show: true }, grid: { margin: { top: 0, left: 0, }, borderColor: "#d5d5d5", borderWidth: 1, clickable: true, hoverable: true, autoHighlight: true }, selection: { mode: "xy" }, colors: ["#019cd5", "#006400"], legend: { show: true, noColumns: 0, labelFormatter: (label: string, series: any): string => { return "<b style='font-size: 16px; color: #333'>" + label + "\t</b>" }, margin: 0, position: "ne", } } } rangeSelect(rangeFunction: string) { this.plot_placeholder.bind("plotselected", (event: JQueryEventObject, ranges: jquery.flot.ranges) => { // Clamp the zooming to prevent external zoom if (ranges.xaxis.to - ranges.xaxis.from < 0.00001) { ranges.xaxis.to = ranges.xaxis.from + 0.00001; } if (ranges.yaxis.to - ranges.yaxis.from < 0.00001) { ranges.yaxis.to = ranges.yaxis.from + 0.00001; } this.range_x.from = ranges.xaxis.from; this.range_x.to = ranges.xaxis.to; this.range_y.from = ranges.yaxis.from; this.range_y.to = ranges.yaxis.to; if (rangeFunction.length > 0) { this.driver[rangeFunction](ranges.xaxis); } this.reset_range = true; }); } // A double click on the plot resets to full span dblClick(rangeFunction: string) { this.plot_placeholder.bind("dblclick", (evt: JQueryEventObject) => { this.range_x.from = 0; this.range_x.to = this.x_max; this.range_y = <jquery.flot.range>{}; if (rangeFunction.length > 0) { this.driver[rangeFunction](this.range_x); } this.reset_range = true; }); } setRangeX(from: number, to: number) { this.range_x.from = from; this.range_x.to = to; this.reset_range = true; } updateDatapointSpan(datapoint: number[], datapointSpan: HTMLSpanElement): void { let positionX: number = (this.plot.pointOffset({x: datapoint[0], y: datapoint[1] })).left; let positionY: number = (this.plot.pointOffset({x: datapoint[0], y: datapoint[1] })).top; datapointSpan.innerHTML = "(" + (datapoint[0].toFixed(2)).toString() + "," + datapoint[1].toFixed(2).toString() + ")"; if (datapoint[0] < (this.range_x.from + this.range_x.to) / 2) { datapointSpan.style.left = (positionX + 5).toString() + "px"; } else { datapointSpan.style.left = (positionX - 140).toString() + "px"; } if (datapoint[1] < ( (this.range_y.from + this.range_y.to) / 2 ) ) { datapointSpan.style.top = (positionY - 50).toString() + "px"; } else { datapointSpan.style.top = (positionY + 5).toString() + "px"; } } redraw(plot_data: number[][], n_pts: number, peakDatapoint: number[], ylabel: string, callback: () => void) { const plt_data: jquery.flot.dataSeries[] = [{label: ylabel, data: plot_data}]; if (this.reset_range) { this.options.xaxis.min = this.range_x.from; this.options.xaxis.max = this.range_x.to; this.options.yaxis.min = this.range_y.from; this.options.yaxis.max = this.range_y.to; this.plot = $.plot(this.plot_placeholder, plt_data, this.options); this.plot.setupGrid(); this.range_y.from = this.plot.getAxes().yaxis.min; this.range_y.to = this.plot.getAxes().yaxis.max; this.reset_range = false; } else { this.plot.setData(plt_data); this.plot.draw(); } let localData: jquery.flot.dataSeries[] = this.plot.getData(); setTimeout(() => {this.plot.unhighlight()}, 100); if (this.clickDatapoint.length > 0) { let i: number; for (i = 0; i < n_pts; i++) { if (localData[0]['data'][i][0] > this.clickDatapoint[0]) { break; } } let p1 = localData[0]['data'][i-1]; let p2 = localData[0]['data'][i]; if (p1 === null) { this.clickDatapoint[1] = p2[1]; } else if (p2 === null) { this.clickDatapoint[1] = p1[1]; } else { this.clickDatapoint[1] = p1[1] + (p2[1] - p1[1]) * (this.clickDatapoint[0] - p1[0]) / (p2[0] - p1[0]); } if (this.range_x.from < this.clickDatapoint[0] && this.clickDatapoint[0] < this.range_x.to && this.range_y.from < this.clickDatapoint[1] && this.clickDatapoint[1] < this.range_y.to) { this.updateDatapointSpan(this.clickDatapoint, this.clickDatapointSpan); this.clickDatapointSpan.style.display = "inline-block"; this.plot.highlight(localData[0], this.clickDatapoint); } else { this.clickDatapointSpan.style.display = "none"; } } if (this.isPeakDetection && peakDatapoint.length > 0) { for (let i: number = 0; i <= n_pts; i++) { if (peakDatapoint[1] < plot_data[i][1]) { peakDatapoint[0] = plot_data[i][0]; peakDatapoint[1] = plot_data[i][1]; } } this.plot.unhighlight(localData[0], peakDatapoint); if (this.range_x.from < peakDatapoint[0] && peakDatapoint[0] < this.range_x.to && this.range_y.from < peakDatapoint[1] && peakDatapoint[1] < this.range_y.to) { this.updateDatapointSpan(peakDatapoint, this.peakDatapointSpan); this.plot.highlight(localData[0], peakDatapoint); this.peakDatapointSpan.style.display = "inline-block"; } else { this.plot.unhighlight(localData[0], peakDatapoint); this.peakDatapointSpan.style.display = "none"; } } else { this.plot.unhighlight(localData[0], peakDatapoint); this.peakDatapointSpan.style.display = "none"; } callback(); } redrawRange(data: number[][], range_x: jquery.flot.range, ylabel: string, callback: () => void): void { const plt_data: jquery.flot.dataSeries[] = [{label: ylabel, data: data}]; if (data.length == 0) { callback(); return; } if (this.reset_range) { this.options.xaxis.min = range_x.from; this.options.xaxis.max = range_x.to; this.options.yaxis.min = this.range_y.from; this.options.yaxis.max = this.range_y.to; this.plot = $.plot(this.plot_placeholder, plt_data, this.options); this.plot.setupGrid(); this.reset_range = false; } else { this.plot.setData(plt_data); this.plot.draw(); } callback(); } redrawTwoChannels(ch0: number[][], ch1: number[][], range_x: jquery.flot.range, label1: string, label2: string, is_channel_1: boolean, is_channel_2: boolean, callback: () => void): void { if (ch0.length === 0 || ch1.length === 0) { callback(); return; } let plotCh0: number[][] = []; let plotCh1: number[][] = []; if (is_channel_1 && is_channel_2) { plotCh0 = ch0; plotCh1 = ch1; // plotData = [ch0, ch1]; } else if (is_channel_1 && !is_channel_2) { plotCh0 = ch0; plotCh1 = []; } else if (!is_channel_1 && is_channel_2) { plotCh0 = []; plotCh1 = ch1; } else { plotCh0 = []; plotCh1 = []; } const plt_data: jquery.flot.dataSeries[] = [{label: label1, data: plotCh0}, {label: label2, data: plotCh1}]; if (this.reset_range) { this.options.xaxis.min = range_x.from; this.options.xaxis.max = range_x.to; this.options.yaxis.min = this.range_y.from; this.options.yaxis.max = this.range_y.to; this.plot = $.plot(this.plot_placeholder, plt_data, this.options); this.plot.setupGrid(); this.reset_range = false; } else { this.plot.setData(plt_data); this.plot.draw(); } callback(); } onWheel(rangeFunction: string): void { this.plot_placeholder.bind("wheel", (evt: JQueryEventObject) => { let delta: number = (<JQueryMousewheel.JQueryMousewheelEventObject>evt.originalEvent).deltaX + (<JQueryMousewheel.JQueryMousewheelEventObject>evt.originalEvent).deltaY; delta /= Math.abs(delta); const zoomRatio: number = 0.2; if ((<JQueryInputEventObject>evt.originalEvent).shiftKey) { // Zoom Y const positionY: number = (<JQueryMouseEventObject>evt.originalEvent).pageY - this.plot.offset().top; const y0: any = this.plot.getAxes().yaxis.c2p(<any>positionY); this.range_y = { from: y0 - (1 + zoomRatio * delta) * (y0 - this.plot.getAxes().yaxis.min), to: y0 - (1 + zoomRatio * delta) * (y0 - this.plot.getAxes().yaxis.max) }; this.reset_range = true; return false; } else if ((<JQueryInputEventObject>evt.originalEvent).altKey) { // Zoom X const positionX: number = (<JQueryMouseEventObject>evt.originalEvent).pageX - this.plot.offset().left; const x0: any = this.plot.getAxes().xaxis.c2p(<any>positionX); if (x0 < 0 || x0 > this.x_max) { return; } this.range_x = { from: Math.max(x0 - (1 + zoomRatio * delta) * (x0 - this.plot.getAxes().xaxis.min), 0), to: Math.min(x0 - (1 + zoomRatio * delta) * (x0 - this.plot.getAxes().xaxis.max), this.x_max) }; if (rangeFunction.length > 0) { this.driver[rangeFunction](this.range_x); } this.reset_range = true; return false; } return true; }); } initUnitInputs(): void { let unitInputs: HTMLInputElement[] = <HTMLInputElement[]><any>document.getElementsByClassName("unit-input"); for (let i = 0; i < unitInputs.length; i ++) { unitInputs[i].addEventListener( 'change', (event) => { this.reset_range = true; }) } } initPeakDetection(): void { let peakInputs: HTMLInputElement[] = <HTMLInputElement[]><any>document.getElementsByClassName("peak-input"); for (let i = 0; i < peakInputs.length; i ++) { peakInputs[i].addEventListener( 'change', (event) => { if (this.isPeakDetection) { this.isPeakDetection = false; } else { this.isPeakDetection = true; } }) } } showHoverPoint(): void { this.plot_placeholder.bind("plothover", (event: JQueryEventObject, pos, item) => { if (item) { this.hoverDatapoint[0] = item.datapoint[0]; this.hoverDatapoint[1] = item.datapoint[1]; this.hoverDatapointSpan.style.display = "inline-block"; this.updateDatapointSpan(this.hoverDatapoint, this.hoverDatapointSpan); } else { this.hoverDatapointSpan.style.display = "none"; } }); } showClickPoint(): void { this.plot_placeholder.bind("plotclick", (event: JQueryEventObject, pos, item) => { if (item) { this.clickDatapoint[0] = item.datapoint[0]; this.clickDatapoint[1] = item.datapoint[1]; this.clickDatapointSpan.style.display = "inline-block"; this.updateDatapointSpan(this.clickDatapoint, this.clickDatapointSpan); this.plot.unhighlight(); this.plot.highlight(item.series, this.clickDatapoint); } }); } plotLeave(): void { this.plot_placeholder.bind("mouseleave", (event: JQueryEventObject, pos, item) => { this.hoverDatapointSpan.style.display = "none"; }); } }
the_stack
import React, { useEffect, useRef, useState, SetStateAction, useCallback, useMemo, Dispatch, } from 'react'; import isEqual from 'react-fast-compare'; import {useSelector as useReduxSelector} from 'react-redux'; import NetInfo, {NetInfoState} from '@react-native-community/netinfo'; import {useTheme} from '@react-navigation/native'; import {AppTheme} from '@config/type'; import {RootState} from '@store/allReducers'; import {LayoutAnimation, BackHandler, Keyboard, Platform} from 'react-native'; import {onCheckType} from '@common'; type UseStateFull<T = any> = { value: T; setValue: React.Dispatch<SetStateAction<T>>; }; function useSelector<T>( selector: (state: RootState) => T, equalityFn = isEqual, ): T { return useReduxSelector<RootState, T>(selector, equalityFn); } type ConfigAnimated = { duration: number; type: keyof typeof LayoutAnimation.Types; creationProp: keyof typeof LayoutAnimation.Properties; }; function useAnimatedState<T>( initialValue: T, config: ConfigAnimated = { duration: 500, creationProp: 'opacity', type: 'easeInEaseOut', }, ): [T, Dispatch<SetStateAction<T>>] { const [value, setValue] = useState<T>(initialValue); const onSetState = useCallback( (newValue: T | ((prevState: T) => T)) => { LayoutAnimation.configureNext( LayoutAnimation.create( config.duration, LayoutAnimation.Types[config.type], LayoutAnimation.Properties[config.creationProp], ), ); setValue(newValue); }, [config], ); return [value, onSetState]; } function useInterval(callback: Function, delay: number) { const savedCallback = useRef<Function>(); useEffect(() => { savedCallback.current = callback; }, [callback]); useEffect(() => { function tick() { savedCallback.current && savedCallback.current(); } if (delay !== null) { const id = setInterval(tick, delay); return () => clearInterval(id); } }, [delay]); } type NetInfoTuple = [boolean, boolean]; function useNetWorkStatus(): NetInfoTuple { const [status, setStatus] = useState<boolean>(false); const [canAccess, setCanAccess] = useState<boolean>(false); useEffect(() => { const unsubscribe = NetInfo.addEventListener((state: NetInfoState) => { setStatus(state.isConnected ?? false); setCanAccess(state.isInternetReachable ?? false); }); return () => { unsubscribe(); }; }, []); return [status, canAccess]; } type UseArrayActions<T> = { setValue: UseStateFull<T[]>['setValue']; add: (value: T | T[]) => void; push: (value: T | T[]) => void; pop: () => void; shift: () => void; unshift: (value: T | T[]) => void; clear: () => void; move: (from: number, to: number) => void; removeById: ( id: T extends {id: string} ? string : T extends {id: number} ? number : unknown, ) => void; modifyById: ( id: T extends {id: string} ? string : T extends {id: number} ? number : unknown, newValue: Partial<T>, ) => void; removeIndex: (index: number) => void; }; type UseArray<T = any> = [T[], UseArrayActions<T>]; function useArray<T = any>(initial: T[]): UseArray<T> { const [value, setValue] = useState(initial); const push = useCallback(a => { setValue(v => [...v, ...(Array.isArray(a) ? a : [a])]); }, []); const unshift = useCallback( a => setValue(v => [...(Array.isArray(a) ? a : [a]), ...v]), [], ); const pop = useCallback(() => setValue(v => v.slice(0, -1)), []); const shift = useCallback(() => setValue(v => v.slice(1)), []); const move = useCallback( (from: number, to: number) => setValue(it => { const copy = it.slice(); copy.splice(to < 0 ? copy.length + to : to, 0, copy.splice(from, 1)[0]); return copy; }), [], ); const clear = useCallback(() => setValue(() => []), []); const removeById = useCallback( id => setValue(arr => arr.filter((v: any) => v && v.id !== id)), [], ); const removeIndex = useCallback( index => setValue(v => { const copy = v.slice(); copy.splice(index, 1); return copy; }), [], ); const modifyById = useCallback( (id, newValue) => setValue(arr => arr.map((v: any) => (v.id === id ? {...v, ...newValue} : v)), ), [], ); const actions = useMemo( () => ({ setValue, add: push, unshift, push, move, clear, removeById, removeIndex, pop, shift, modifyById, }), [ modifyById, push, unshift, move, clear, removeById, removeIndex, pop, shift, ], ); return [value, actions]; } type UseBooleanActions = { setValue: React.Dispatch<SetStateAction<boolean>>; toggle: () => void; setTrue: () => void; setFalse: () => void; }; type UseBoolean = [boolean, UseBooleanActions]; function useBoolean(initial: boolean): UseBoolean { const [value, setValue] = useState<boolean>(initial); const toggle = useCallback(() => setValue(v => !v), []); const setTrue = useCallback(() => setValue(true), []); const setFalse = useCallback(() => setValue(false), []); const actions = useMemo( () => ({setValue, toggle, setTrue, setFalse}), [setFalse, setTrue, toggle], ); return useMemo(() => [value, actions], [actions, value]); } type UseNumberActions = { setValue: React.Dispatch<SetStateAction<number>>; increase: (value?: number) => void; decrease: (value?: number) => void; }; type UseNumber = [number, UseNumberActions]; function useNumber( initial: number, { upperLimit, lowerLimit, loop, step = 1, }: { upperLimit?: number; lowerLimit?: number; loop?: boolean; step?: number; } = {}, ): UseNumber { const [value, setValue] = useState<number>(initial); const decrease = useCallback( (d?: number) => { setValue(aValue => { const decreaseBy = d !== undefined ? d : step; const nextValue = aValue - decreaseBy; if (lowerLimit !== undefined) { if (nextValue < lowerLimit) { if (loop && upperLimit) { return upperLimit; } return lowerLimit; } } return nextValue; }); }, [loop, lowerLimit, step, upperLimit], ); const increase = useCallback( (i?: number) => { setValue(aValue => { const increaseBy = i !== undefined ? i : step; const nextValue = aValue + increaseBy; if (upperLimit !== undefined) { if (nextValue > upperLimit) { if (loop) { return initial; } return upperLimit; } } return nextValue; }); }, [initial, loop, step, upperLimit], ); const actions = useMemo( () => ({ setValue, increase, decrease, }), [decrease, increase], ); return [value, actions]; } function useStateFull<T = any>(initial: T): UseStateFull<T> { const [value, setValue] = useState(initial); return useMemo( () => ({ value, setValue, }), [value], ); } function usePrevious<T = any>(value: T): T | undefined { const ref = useRef<T>(); useEffect(() => { ref.current = value; }, [value]); return ref.current; } type UseSetArrayStateAction<T extends object> = React.Dispatch< SetStateAction<Partial<T>> >; type UseSetStateArray<T extends object> = [ T, UseSetArrayStateAction<T>, () => void, ]; function useSetStateArray<T extends object>( initialValue: T, ): UseSetStateArray<T> { const [value, setValue] = useState<T>(initialValue); const setState = useCallback( (v: SetStateAction<Partial<T>>) => { return setValue(oldValue => ({ ...oldValue, ...(typeof v === 'function' ? v(oldValue) : v), })); }, [setValue], ); const resetState = useCallback(() => setValue(initialValue), [initialValue]); return [value, setState, resetState]; } type UseSetStateAction<T extends object> = React.Dispatch< SetStateAction<Partial<T>> >; type UseSetState<T extends object> = { setState: UseSetStateAction<T>; state: T; resetState: () => void; }; function useSetState<T extends object>(initialValue: T): UseSetState<T> { const [state, setState, resetState] = useSetStateArray(initialValue); return useMemo( () => ({ setState, resetState, state, }), [setState, resetState, state], ); } function useStyle<T>(style: (theme: AppTheme) => T): T { const theme: AppTheme = useTheme(); return style(theme); } function useAsyncState<T>( initialValue: T, ): [ T, (newValue: SetStateAction<T>, callback?: (newState: T) => void) => void, ] { const [state, setState] = useState(initialValue); const _callback = useRef<(newState: T) => void>(); const _setState = ( newValue: SetStateAction<T>, callback?: (newState: T) => void, ) => { if (callback) { _callback.current = callback; } setState(newValue); }; useEffect(() => { if (typeof _callback.current === 'function') { _callback.current(state); _callback.current = undefined; } }, [state]); return [state, _setState]; } type Init<T> = () => T; function useConst<T>(init: Init<T>) { const ref = useRef<T | null>(null); if (ref.current === null) { ref.current = init(); } return ref.current; } function useUnMount(callback: () => void) { // eslint-disable-next-line react-hooks/exhaustive-deps return useEffect(() => () => callback(), []); } function useForceUpdate() { const unloadingRef = useRef(false); const [forcedRenderCount, setForcedRenderCount] = useState(0); useUnMount(() => (unloadingRef.current = true)); return useCallback(() => { !unloadingRef.current && setForcedRenderCount(forcedRenderCount + 1); }, [forcedRenderCount]); } function useIsKeyboardShown() { const [isKeyboardShown, setIsKeyboardShown] = React.useState(false); React.useEffect(() => { const handleKeyboardShow = () => setIsKeyboardShown(true); const handleKeyboardHide = () => setIsKeyboardShown(false); if (Platform.OS === 'ios') { Keyboard.addListener('keyboardWillShow', handleKeyboardShow); Keyboard.addListener('keyboardWillHide', handleKeyboardHide); } else { Keyboard.addListener('keyboardDidShow', handleKeyboardShow); Keyboard.addListener('keyboardDidHide', handleKeyboardHide); } return () => { if (Platform.OS === 'ios') { Keyboard.removeListener('keyboardWillShow', handleKeyboardShow); Keyboard.removeListener('keyboardWillHide', handleKeyboardHide); } else { Keyboard.removeListener('keyboardDidShow', handleKeyboardShow); Keyboard.removeListener('keyboardDidHide', handleKeyboardHide); } }; }, []); return isKeyboardShown; } function useDisableBackHandler(disabled: boolean, callback?: () => void) { // function const onBackPress = useCallback(() => { if (onCheckType(callback, 'function')) { callback(); } return true; }, [callback]); useEffect(() => { if (disabled) { BackHandler.addEventListener('hardwareBackPress', onBackPress); } else { BackHandler.removeEventListener('hardwareBackPress', onBackPress); } }, [disabled, onBackPress]); } function useDismissKeyboard(isHide: boolean) { useEffect(() => { if (isHide) { Keyboard.dismiss(); } }, [isHide]); } function useMounted(callback: () => void, deps: any[] = []) { const [mounted, setMounted] = useState<boolean>(false); useEffect(() => { setMounted(true); }, []); useEffect(() => { if (mounted) { callback(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [...deps]); } function useIsMounted() { const isMountedRef = useRef<boolean | null>(null); useEffect(() => { isMountedRef.current = true; return () => { isMountedRef.current = false; }; }, []); return isMountedRef; } export { useIsMounted, useDisableBackHandler, useDismissKeyboard, useInterval, useSelector, useNetWorkStatus, useArray, useBoolean, useNumber, useStateFull, usePrevious, useSetState, useStyle, useAsyncState, useConst, useUnMount, useForceUpdate, useAnimatedState, useMounted, useIsKeyboardShown, };
the_stack
module android.widget { import ArrayMap = android.util.ArrayMap; import ArrayDeque = java.util.ArrayDeque; import ArrayList = java.util.ArrayList; import Rect = android.graphics.Rect; import SynchronizedPool = android.util.Pools.SynchronizedPool; import SparseArray = android.util.SparseArray; import SparseMap = android.util.SparseMap; import Gravity = android.view.Gravity; import View = android.view.View; import ViewGroup = android.view.ViewGroup; import Integer = java.lang.Integer; import System = java.lang.System; import HorizontalScrollView = android.widget.HorizontalScrollView; import ScrollView = android.widget.ScrollView; import AttrBinder = androidui.attr.AttrBinder; import Context = android.content.Context; /** * A Layout where the positions of the children can be described in relation to each other or to the * parent. * * <p> * Note that you cannot have a circular dependency between the size of the RelativeLayout and the * position of its children. For example, you cannot have a RelativeLayout whose height is set to * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT WRAP_CONTENT} and a child set to * {@link #ALIGN_PARENT_BOTTOM}. * </p> * * <p><strong>Note:</strong> In platform version 17 and lower, RelativeLayout was affected by * a measurement bug that could cause child views to be measured with incorrect * {@link android.view.View.MeasureSpec MeasureSpec} values. (See * {@link android.view.View.MeasureSpec#makeMeasureSpec(int, int) MeasureSpec.makeMeasureSpec} * for more details.) This was triggered when a RelativeLayout container was placed in * a scrolling container, such as a ScrollView or HorizontalScrollView. If a custom view * not equipped to properly measure with the MeasureSpec mode * {@link android.view.View.MeasureSpec#UNSPECIFIED UNSPECIFIED} was placed in a RelativeLayout, * this would silently work anyway as RelativeLayout would pass a very large * {@link android.view.View.MeasureSpec#AT_MOST AT_MOST} MeasureSpec instead.</p> * * <p>This behavior has been preserved for apps that set <code>android:targetSdkVersion="17"</code> * or older in their manifest's <code>uses-sdk</code> tag for compatibility. Apps targeting SDK * version 18 or newer will receive the correct behavior</p> * * <p>See the <a href="{@docRoot}guide/topics/ui/layout/relative.html">Relative * Layout</a> guide.</p> * * <p> * Also see {@link android.widget.RelativeLayout.LayoutParams RelativeLayout.LayoutParams} for * layout attributes * </p> * * @attr ref android.R.styleable#RelativeLayout_gravity * @attr ref android.R.styleable#RelativeLayout_ignoreGravity */ export class RelativeLayout extends ViewGroup { static TRUE:string = ""; /** * Rule that aligns a child's right edge with another child's left edge. */ static LEFT_OF:number = 0; /** * Rule that aligns a child's left edge with another child's right edge. */ static RIGHT_OF:number = 1; /** * Rule that aligns a child's bottom edge with another child's top edge. */ static ABOVE:number = 2; /** * Rule that aligns a child's top edge with another child's bottom edge. */ static BELOW:number = 3; /** * Rule that aligns a child's baseline with another child's baseline. */ static ALIGN_BASELINE:number = 4; /** * Rule that aligns a child's left edge with another child's left edge. */ static ALIGN_LEFT:number = 5; /** * Rule that aligns a child's top edge with another child's top edge. */ static ALIGN_TOP:number = 6; /** * Rule that aligns a child's right edge with another child's right edge. */ static ALIGN_RIGHT:number = 7; /** * Rule that aligns a child's bottom edge with another child's bottom edge. */ static ALIGN_BOTTOM:number = 8; /** * Rule that aligns the child's left edge with its RelativeLayout * parent's left edge. */ static ALIGN_PARENT_LEFT:number = 9; /** * Rule that aligns the child's top edge with its RelativeLayout * parent's top edge. */ static ALIGN_PARENT_TOP:number = 10; /** * Rule that aligns the child's right edge with its RelativeLayout * parent's right edge. */ static ALIGN_PARENT_RIGHT:number = 11; /** * Rule that aligns the child's bottom edge with its RelativeLayout * parent's bottom edge. */ static ALIGN_PARENT_BOTTOM:number = 12; /** * Rule that centers the child with respect to the bounds of its * RelativeLayout parent. */ static CENTER_IN_PARENT:number = 13; /** * Rule that centers the child horizontally with respect to the * bounds of its RelativeLayout parent. */ static CENTER_HORIZONTAL:number = 14; /** * Rule that centers the child vertically with respect to the * bounds of its RelativeLayout parent. */ static CENTER_VERTICAL:number = 15; /** * Rule that aligns a child's end edge with another child's start edge. */ static START_OF:number = 16; /** * Rule that aligns a child's start edge with another child's end edge. */ static END_OF:number = 17; /** * Rule that aligns a child's start edge with another child's start edge. */ static ALIGN_START:number = 18; /** * Rule that aligns a child's end edge with another child's end edge. */ static ALIGN_END:number = 19; /** * Rule that aligns the child's start edge with its RelativeLayout * parent's start edge. */ static ALIGN_PARENT_START:number = 20; /** * Rule that aligns the child's end edge with its RelativeLayout * parent's end edge. */ static ALIGN_PARENT_END:number = 21; static VERB_COUNT:number = 22; private static RULES_VERTICAL:number[] = [ RelativeLayout.ABOVE, RelativeLayout.BELOW, RelativeLayout.ALIGN_BASELINE, RelativeLayout.ALIGN_TOP, RelativeLayout.ALIGN_BOTTOM ]; private static RULES_HORIZONTAL:number[] = [ RelativeLayout.LEFT_OF, RelativeLayout.RIGHT_OF, RelativeLayout.ALIGN_LEFT, RelativeLayout.ALIGN_RIGHT, RelativeLayout.START_OF, RelativeLayout.END_OF, RelativeLayout.ALIGN_START, RelativeLayout.ALIGN_END ]; private mBaselineView:View = null; private mHasBaselineAlignedChild:boolean; private mGravity:number = Gravity.START | Gravity.TOP; private mContentBounds:Rect = new Rect(); private mSelfBounds:Rect = new Rect(); private mIgnoreGravity:string = View.NO_ID; //private mTopToBottomLeftToRightSet:SortedSet<View> = null; private mDirtyHierarchy:boolean; private mSortedHorizontalChildren:View[]; private mSortedVerticalChildren:View[]; private mGraph:RelativeLayout.DependencyGraph = new RelativeLayout.DependencyGraph(); // Compatibility hack. Old versions of the platform had problems // with MeasureSpec value overflow and RelativeLayout was one source of them. // Some apps came to rely on them. :( private mAllowBrokenMeasureSpecs:boolean = false; // Compatibility hack. Old versions of the platform would not take // margins and padding into account when generating the height measure spec // for children during the horizontal measure pass. private mMeasureVerticalWithPaddingMargin:boolean = false; // A default width used for RTL measure pass /** * Value reduced so as not to interfere with View's measurement spec. flags. See: * {@link View#MEASURED_SIZE_MASK}. * {@link View#MEASURED_STATE_TOO_SMALL}. **/ private static DEFAULT_WIDTH:number = 0x00010000; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) { super(context, bindElement, defStyle); if (bindElement || defStyle) { const a = context.obtainStyledAttributes(bindElement, defStyle); this.mIgnoreGravity = a.getResourceId('ignoreGravity', View.NO_ID); this.mGravity = Gravity.parseGravity(a.getAttrValue('gravity'), this.mGravity); a.recycle(); } this.queryCompatibilityModes(); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('ignoreGravity', { setter(v:RelativeLayout, value:any, a:AttrBinder) { v.setIgnoreGravity(value+''); }, getter(v:RelativeLayout) { return v.mIgnoreGravity; } }).set('gravity', { setter(v:RelativeLayout, value:any, a:AttrBinder) { v.setGravity(a.parseGravity(value, v.mGravity)); }, getter(v:RelativeLayout) { return v.mGravity; } }); } private queryCompatibilityModes():void { this.mAllowBrokenMeasureSpecs = false; //version <= Build.VERSION_CODES.JELLY_BEAN_MR1; this.mMeasureVerticalWithPaddingMargin = true; //version >= Build.VERSION_CODES.JELLY_BEAN_MR2; } shouldDelayChildPressedState():boolean { return false; } /** * Defines which View is ignored when the gravity is applied. This setting has no * effect if the gravity is <code>Gravity.START | Gravity.TOP</code>. * * @param viewId The id of the View to be ignored by gravity, or 0 if no View * should be ignored. * * @see #setGravity(int) * * @attr ref android.R.styleable#RelativeLayout_ignoreGravity */ setIgnoreGravity(viewId:string):void { this.mIgnoreGravity = viewId; } /** * Describes how the child views are positioned. * * @return the gravity. * * @see #setGravity(int) * @see android.view.Gravity * * @attr ref android.R.styleable#RelativeLayout_gravity */ getGravity():number { return this.mGravity; } /** * Describes how the child views are positioned. Defaults to * <code>Gravity.START | Gravity.TOP</code>. * * <p>Note that since RelativeLayout considers the positioning of each child * relative to one another to be significant, setting gravity will affect * the positioning of all children as a single unit within the parent. * This happens after children have been relatively positioned.</p> * * @param gravity See {@link android.view.Gravity} * * @see #setHorizontalGravity(int) * @see #setVerticalGravity(int) * * @attr ref android.R.styleable#RelativeLayout_gravity */ setGravity(gravity:number):void { if (this.mGravity != gravity) { if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { gravity |= Gravity.START; } if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { gravity |= Gravity.TOP; } this.mGravity = gravity; this.requestLayout(); } } setHorizontalGravity(horizontalGravity:number):void { const gravity:number = horizontalGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK; if ((this.mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) != gravity) { this.mGravity = (this.mGravity & ~Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) | gravity; this.requestLayout(); } } setVerticalGravity(verticalGravity:number):void { const gravity:number = verticalGravity & Gravity.VERTICAL_GRAVITY_MASK; if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) != gravity) { this.mGravity = (this.mGravity & ~Gravity.VERTICAL_GRAVITY_MASK) | gravity; this.requestLayout(); } } getBaseline():number { return this.mBaselineView != null ? this.mBaselineView.getBaseline() : super.getBaseline(); } requestLayout():void { super.requestLayout(); this.mDirtyHierarchy = true; } private sortChildren():void { const count:number = this.getChildCount(); if (this.mSortedVerticalChildren == null || this.mSortedVerticalChildren.length != count) { this.mSortedVerticalChildren = new Array<View>(count); } if (this.mSortedHorizontalChildren == null || this.mSortedHorizontalChildren.length != count) { this.mSortedHorizontalChildren = new Array<View>(count); } const graph:RelativeLayout.DependencyGraph = this.mGraph; graph.clear(); for (let i:number = 0; i < count; i++) { graph.add(this.getChildAt(i)); } graph.getSortedViews(this.mSortedVerticalChildren, RelativeLayout.RULES_VERTICAL); graph.getSortedViews(this.mSortedHorizontalChildren, RelativeLayout.RULES_HORIZONTAL); } protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { if (this.mDirtyHierarchy) { this.mDirtyHierarchy = false; this.sortChildren(); } let myWidth:number = -1; let myHeight:number = -1; let width:number = 0; let height:number = 0; const widthMode:number = View.MeasureSpec.getMode(widthMeasureSpec); const heightMode:number = View.MeasureSpec.getMode(heightMeasureSpec); const widthSize:number = View.MeasureSpec.getSize(widthMeasureSpec); const heightSize:number = View.MeasureSpec.getSize(heightMeasureSpec); // Record our dimensions if they are known; if (widthMode != View.MeasureSpec.UNSPECIFIED) { myWidth = widthSize; } if (heightMode != View.MeasureSpec.UNSPECIFIED) { myHeight = heightSize; } if (widthMode == View.MeasureSpec.EXACTLY) { width = myWidth; } if (heightMode == View.MeasureSpec.EXACTLY) { height = myHeight; } this.mHasBaselineAlignedChild = false; let ignore:View = null; let gravity:number = this.mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK; const horizontalGravity:boolean = gravity != Gravity.START && gravity != 0; gravity = this.mGravity & Gravity.VERTICAL_GRAVITY_MASK; const verticalGravity:boolean = gravity != Gravity.TOP && gravity != 0; let left:number = Integer.MAX_VALUE; let top:number = Integer.MAX_VALUE; let right:number = Integer.MIN_VALUE; let bottom:number = Integer.MIN_VALUE; let offsetHorizontalAxis:boolean = false; let offsetVerticalAxis:boolean = false; if ((horizontalGravity || verticalGravity) && this.mIgnoreGravity != View.NO_ID) { ignore = this.findViewById(this.mIgnoreGravity); } const isWrapContentWidth:boolean = widthMode != View.MeasureSpec.EXACTLY; const isWrapContentHeight:boolean = heightMode != View.MeasureSpec.EXACTLY; // We need to know our size for doing the correct computation of children positioning in RTL // mode but there is no practical way to get it instead of running the code below. // So, instead of running the code twice, we just set the width to a "default display width" // before the computation and then, as a last pass, we will update their real position with // an offset equals to "DEFAULT_WIDTH - width". const layoutDirection:number = this.getLayoutDirection(); if (this.isLayoutRtl() && myWidth == -1) { myWidth = RelativeLayout.DEFAULT_WIDTH; } let views:View[] = this.mSortedHorizontalChildren; let count:number = views.length; for (let i:number = 0; i < count; i++) { let child:View = views[i]; if (child.getVisibility() != RelativeLayout.GONE) { let params:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> child.getLayoutParams(); let rules:string[] = params.getRules(layoutDirection); this.applyHorizontalSizeRules(params, myWidth, rules); this.measureChildHorizontal(child, params, myWidth, myHeight); if (this.positionChildHorizontal(child, params, myWidth, isWrapContentWidth)) { offsetHorizontalAxis = true; } } } views = this.mSortedVerticalChildren; count = views.length; //const targetSdkVersion:number = this.getContext().getApplicationInfo().targetSdkVersion; for (let i:number = 0; i < count; i++) { let child:View = views[i]; if (child.getVisibility() != RelativeLayout.GONE) { let params:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> child.getLayoutParams(); this.applyVerticalSizeRules(params, myHeight); this._measureChild(child, params, myWidth, myHeight); if (this.positionChildVertical(child, params, myHeight, isWrapContentHeight)) { offsetVerticalAxis = true; } if (isWrapContentWidth) { if (this.isLayoutRtl()) { //if (targetSdkVersion < Build.VERSION_CODES.KITKAT) { // width = Math.max(width, myWidth - params.mLeft); //} else { width = Math.max(width, myWidth - params.mLeft - params.leftMargin); //} } else { //if (targetSdkVersion < Build.VERSION_CODES.KITKAT) { // width = Math.max(width, params.mRight); //} else { width = Math.max(width, params.mRight + params.rightMargin); //} } } if (isWrapContentHeight) { //if (targetSdkVersion < Build.VERSION_CODES.KITKAT) { // height = Math.max(height, params.mBottom); //} else { height = Math.max(height, params.mBottom + params.bottomMargin); //} } if (child != ignore || verticalGravity) { left = Math.min(left, params.mLeft - params.leftMargin); top = Math.min(top, params.mTop - params.topMargin); } if (child != ignore || horizontalGravity) { right = Math.max(right, params.mRight + params.rightMargin); bottom = Math.max(bottom, params.mBottom + params.bottomMargin); } } } if (this.mHasBaselineAlignedChild) { for (let i:number = 0; i < count; i++) { let child:View = this.getChildAt(i); if (child.getVisibility() != RelativeLayout.GONE) { let params:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> child.getLayoutParams(); this.alignBaseline(child, params); if (child != ignore || verticalGravity) { left = Math.min(left, params.mLeft - params.leftMargin); top = Math.min(top, params.mTop - params.topMargin); } if (child != ignore || horizontalGravity) { right = Math.max(right, params.mRight + params.rightMargin); bottom = Math.max(bottom, params.mBottom + params.bottomMargin); } } } } if (isWrapContentWidth) { // Width already has left padding in it since it was calculated by looking at // the right of each child view width += this.mPaddingRight; if (this.mLayoutParams != null && this.mLayoutParams.width >= 0) { width = Math.max(width, this.mLayoutParams.width); } width = Math.max(width, this.getSuggestedMinimumWidth()); width = RelativeLayout.resolveSize(width, widthMeasureSpec); if (offsetHorizontalAxis) { for (let i:number = 0; i < count; i++) { let child:View = this.getChildAt(i); if (child.getVisibility() != RelativeLayout.GONE) { let params:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> child.getLayoutParams(); const rules:string[] = params.getRules(layoutDirection); if (rules[RelativeLayout.CENTER_IN_PARENT] != null || rules[RelativeLayout.CENTER_HORIZONTAL] != null) { RelativeLayout.centerHorizontal(child, params, width); } else if (rules[RelativeLayout.ALIGN_PARENT_RIGHT] != null) { const childWidth:number = child.getMeasuredWidth(); params.mLeft = width - this.mPaddingRight - childWidth; params.mRight = params.mLeft + childWidth; } } } } } if (isWrapContentHeight) { // Height already has top padding in it since it was calculated by looking at // the bottom of each child view height += this.mPaddingBottom; if (this.mLayoutParams != null && this.mLayoutParams.height >= 0) { height = Math.max(height, this.mLayoutParams.height); } height = Math.max(height, this.getSuggestedMinimumHeight()); height = RelativeLayout.resolveSize(height, heightMeasureSpec); if (offsetVerticalAxis) { for (let i:number = 0; i < count; i++) { let child:View = this.getChildAt(i); if (child.getVisibility() != RelativeLayout.GONE) { let params:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> child.getLayoutParams(); const rules:string[] = params.getRules(layoutDirection); if (rules[RelativeLayout.CENTER_IN_PARENT] != null || rules[RelativeLayout.CENTER_VERTICAL] != null) { RelativeLayout.centerVertical(child, params, height); } else if (rules[RelativeLayout.ALIGN_PARENT_BOTTOM] != null) { const childHeight:number = child.getMeasuredHeight(); params.mTop = height - this.mPaddingBottom - childHeight; params.mBottom = params.mTop + childHeight; } } } } } if (horizontalGravity || verticalGravity) { const selfBounds:Rect = this.mSelfBounds; selfBounds.set(this.mPaddingLeft, this.mPaddingTop, width - this.mPaddingRight, height - this.mPaddingBottom); const contentBounds:Rect = this.mContentBounds; Gravity.apply(this.mGravity, right - left, bottom - top, selfBounds, contentBounds, layoutDirection); const horizontalOffset:number = contentBounds.left - left; const verticalOffset:number = contentBounds.top - top; if (horizontalOffset != 0 || verticalOffset != 0) { for (let i:number = 0; i < count; i++) { let child:View = this.getChildAt(i); if (child.getVisibility() != RelativeLayout.GONE && child != ignore) { let params:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> child.getLayoutParams(); if (horizontalGravity) { params.mLeft += horizontalOffset; params.mRight += horizontalOffset; } if (verticalGravity) { params.mTop += verticalOffset; params.mBottom += verticalOffset; } } } } } if (this.isLayoutRtl()) { const offsetWidth:number = myWidth - width; for (let i:number = 0; i < count; i++) { let child:View = this.getChildAt(i); if (child.getVisibility() != RelativeLayout.GONE) { let params:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> child.getLayoutParams(); params.mLeft -= offsetWidth; params.mRight -= offsetWidth; } } } this.setMeasuredDimension(width, height); } private alignBaseline(child:View, params:RelativeLayout.LayoutParams):void { const layoutDirection:number = this.getLayoutDirection(); let rules:string[] = params.getRules(layoutDirection); let anchorBaseline:number = this.getRelatedViewBaseline(rules, RelativeLayout.ALIGN_BASELINE); if (anchorBaseline != -1) { let anchorParams:RelativeLayout.LayoutParams = this.getRelatedViewParams(rules, RelativeLayout.ALIGN_BASELINE); if (anchorParams != null) { let offset:number = anchorParams.mTop + anchorBaseline; let baseline:number = child.getBaseline(); if (baseline != -1) { offset -= baseline; } let height:number = params.mBottom - params.mTop; params.mTop = offset; params.mBottom = params.mTop + height; } } if (this.mBaselineView == null) { this.mBaselineView = child; } else { let lp:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> this.mBaselineView.getLayoutParams(); if (params.mTop < lp.mTop || (params.mTop == lp.mTop && params.mLeft < lp.mLeft)) { this.mBaselineView = child; } } } /** * Measure a child. The child should have left, top, right and bottom information * stored in its LayoutParams. If any of these values is -1 it means that the view * can extend up to the corresponding edge. * * @param child Child to measure * @param params LayoutParams associated with child * @param myWidth Width of the the RelativeLayout * @param myHeight Height of the RelativeLayout */ private _measureChild(child:View, params:RelativeLayout.LayoutParams, myWidth:number, myHeight:number):void { let childWidthMeasureSpec:number = this.getChildMeasureSpec(params.mLeft, params.mRight, params.width, params.leftMargin, params.rightMargin, this.mPaddingLeft, this.mPaddingRight, myWidth); let childHeightMeasureSpec:number = this.getChildMeasureSpec(params.mTop, params.mBottom, params.height, params.topMargin, params.bottomMargin, this.mPaddingTop, this.mPaddingBottom, myHeight); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } private measureChildHorizontal(child:View, params:RelativeLayout.LayoutParams, myWidth:number, myHeight:number):void { let childWidthMeasureSpec:number = this.getChildMeasureSpec(params.mLeft, params.mRight, params.width, params.leftMargin, params.rightMargin, this.mPaddingLeft, this.mPaddingRight, myWidth); let maxHeight:number = myHeight; if (this.mMeasureVerticalWithPaddingMargin) { maxHeight = Math.max(0, myHeight - this.mPaddingTop - this.mPaddingBottom - params.topMargin - params.bottomMargin); } let childHeightMeasureSpec:number; if (myHeight < 0 && !this.mAllowBrokenMeasureSpecs) { if (params.height >= 0) { childHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(params.height, View.MeasureSpec.EXACTLY); } else { // Negative values in a mySize/myWidth/myWidth value in RelativeLayout measurement // is code for, "we got an unspecified mode in the RelativeLayout's measurespec." // Carry it forward. childHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); } } else if (params.width == RelativeLayout.LayoutParams.MATCH_PARENT) { childHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxHeight, View.MeasureSpec.EXACTLY); } else { childHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxHeight, View.MeasureSpec.AT_MOST); } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } /** * Get a measure spec that accounts for all of the constraints on this view. * This includes size constraints imposed by the RelativeLayout as well as * the View's desired dimension. * * @param childStart The left or top field of the child's layout params * @param childEnd The right or bottom field of the child's layout params * @param childSize The child's desired size (the width or height field of * the child's layout params) * @param startMargin The left or top margin * @param endMargin The right or bottom margin * @param startPadding mPaddingLeft or mPaddingTop * @param endPadding mPaddingRight or mPaddingBottom * @param mySize The width or height of this view (the RelativeLayout) * @return MeasureSpec for the child */ private getChildMeasureSpec(childStart:number, childEnd:number, childSize:number, startMargin:number, endMargin:number, startPadding:number, endPadding:number, mySize:number):number { if (mySize < 0 && !this.mAllowBrokenMeasureSpecs) { if (childSize >= 0) { return View.MeasureSpec.makeMeasureSpec(childSize, View.MeasureSpec.EXACTLY); } // Carry it forward. return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); } let childSpecMode:number = 0; let childSpecSize:number = 0; // Figure out start and end bounds. let tempStart:number = childStart; let tempEnd:number = childEnd; // view's margins and our padding if (tempStart < 0) { tempStart = startPadding + startMargin; } if (tempEnd < 0) { tempEnd = mySize - endPadding - endMargin; } // Figure out maximum size available to this view let maxAvailable:number = tempEnd - tempStart; if (childStart >= 0 && childEnd >= 0) { // Constraints fixed both edges, so child must be an exact size childSpecMode = View.MeasureSpec.EXACTLY; childSpecSize = maxAvailable; } else { if (childSize >= 0) { // Child wanted an exact size. Give as much as possible childSpecMode = View.MeasureSpec.EXACTLY; if (maxAvailable >= 0) { // We have a maxmum size in this dimension. childSpecSize = Math.min(maxAvailable, childSize); } else { // We can grow in this dimension. childSpecSize = childSize; } } else if (childSize == RelativeLayout.LayoutParams.MATCH_PARENT) { // Child wanted to be as big as possible. Give all available // space childSpecMode = View.MeasureSpec.EXACTLY; childSpecSize = maxAvailable; } else if (childSize == RelativeLayout.LayoutParams.WRAP_CONTENT) { // our max size if (maxAvailable >= 0) { // We have a maximum size in this dimension. childSpecMode = View.MeasureSpec.AT_MOST; childSpecSize = maxAvailable; } else { // We can grow in this dimension. Child can be as big as it // wants childSpecMode = View.MeasureSpec.UNSPECIFIED; childSpecSize = 0; } } } return View.MeasureSpec.makeMeasureSpec(childSpecSize, childSpecMode); } private positionChildHorizontal(child:View, params:RelativeLayout.LayoutParams, myWidth:number, wrapContent:boolean):boolean { const layoutDirection:number = this.getLayoutDirection(); let rules:string[] = params.getRules(layoutDirection); if (params.mLeft < 0 && params.mRight >= 0) { // Right is fixed, but left varies params.mLeft = params.mRight - child.getMeasuredWidth(); } else if (params.mLeft >= 0 && params.mRight < 0) { // Left is fixed, but right varies params.mRight = params.mLeft + child.getMeasuredWidth(); } else if (params.mLeft < 0 && params.mRight < 0) { // Both left and right vary if (rules[RelativeLayout.CENTER_IN_PARENT] != null || rules[RelativeLayout.CENTER_HORIZONTAL] != null) { if (!wrapContent) { RelativeLayout.centerHorizontal(child, params, myWidth); } else { params.mLeft = this.mPaddingLeft + params.leftMargin; params.mRight = params.mLeft + child.getMeasuredWidth(); } return true; } else { // from the left. This will give LEFT/TOP for LTR and RIGHT/TOP for RTL. if (this.isLayoutRtl()) { params.mRight = myWidth - this.mPaddingRight - params.rightMargin; params.mLeft = params.mRight - child.getMeasuredWidth(); } else { params.mLeft = this.mPaddingLeft + params.leftMargin; params.mRight = params.mLeft + child.getMeasuredWidth(); } } } return rules[RelativeLayout.ALIGN_PARENT_END] != null; } private positionChildVertical(child:View, params:RelativeLayout.LayoutParams, myHeight:number, wrapContent:boolean):boolean { let rules:string[] = params.getRules(); if (params.mTop < 0 && params.mBottom >= 0) { // Bottom is fixed, but top varies params.mTop = params.mBottom - child.getMeasuredHeight(); } else if (params.mTop >= 0 && params.mBottom < 0) { // Top is fixed, but bottom varies params.mBottom = params.mTop + child.getMeasuredHeight(); } else if (params.mTop < 0 && params.mBottom < 0) { // Both top and bottom vary if (rules[RelativeLayout.CENTER_IN_PARENT] != null || rules[RelativeLayout.CENTER_VERTICAL] != null) { if (!wrapContent) { RelativeLayout.centerVertical(child, params, myHeight); } else { params.mTop = this.mPaddingTop + params.topMargin; params.mBottom = params.mTop + child.getMeasuredHeight(); } return true; } else { params.mTop = this.mPaddingTop + params.topMargin; params.mBottom = params.mTop + child.getMeasuredHeight(); } } return rules[RelativeLayout.ALIGN_PARENT_BOTTOM] != null; } private applyHorizontalSizeRules(childParams:RelativeLayout.LayoutParams, myWidth:number, rules:string[]):void { let anchorParams:RelativeLayout.LayoutParams; // -1 indicated a "soft requirement" in that direction. For example: // left=10, right=-1 means the view must start at 10, but can go as far as it wants to the right // left =-1, right=10 means the view must end at 10, but can go as far as it wants to the left // left=10, right=20 means the left and right ends are both fixed childParams.mLeft = -1; childParams.mRight = -1; anchorParams = this.getRelatedViewParams(rules, RelativeLayout.LEFT_OF); if (anchorParams != null) { childParams.mRight = anchorParams.mLeft - (anchorParams.leftMargin + childParams.rightMargin); } else if (childParams.alignWithParent && rules[RelativeLayout.LEFT_OF] != null) { if (myWidth >= 0) { childParams.mRight = myWidth - this.mPaddingRight - childParams.rightMargin; } } anchorParams = this.getRelatedViewParams(rules, RelativeLayout.RIGHT_OF); if (anchorParams != null) { childParams.mLeft = anchorParams.mRight + (anchorParams.rightMargin + childParams.leftMargin); } else if (childParams.alignWithParent && rules[RelativeLayout.RIGHT_OF] != null) { childParams.mLeft = this.mPaddingLeft + childParams.leftMargin; } anchorParams = this.getRelatedViewParams(rules, RelativeLayout.ALIGN_LEFT); if (anchorParams != null) { childParams.mLeft = anchorParams.mLeft + childParams.leftMargin; } else if (childParams.alignWithParent && rules[RelativeLayout.ALIGN_LEFT] != null) { childParams.mLeft = this.mPaddingLeft + childParams.leftMargin; } anchorParams = this.getRelatedViewParams(rules, RelativeLayout.ALIGN_RIGHT); if (anchorParams != null) { childParams.mRight = anchorParams.mRight - childParams.rightMargin; } else if (childParams.alignWithParent && rules[RelativeLayout.ALIGN_RIGHT] != null) { if (myWidth >= 0) { childParams.mRight = myWidth - this.mPaddingRight - childParams.rightMargin; } } if (null != rules[RelativeLayout.ALIGN_PARENT_LEFT]) { childParams.mLeft = this.mPaddingLeft + childParams.leftMargin; } if (null != rules[RelativeLayout.ALIGN_PARENT_RIGHT]) { if (myWidth >= 0) { childParams.mRight = myWidth - this.mPaddingRight - childParams.rightMargin; } } } private applyVerticalSizeRules(childParams:RelativeLayout.LayoutParams, myHeight:number):void { let rules:string[] = childParams.getRules(); let anchorParams:RelativeLayout.LayoutParams; childParams.mTop = -1; childParams.mBottom = -1; anchorParams = this.getRelatedViewParams(rules, RelativeLayout.ABOVE); if (anchorParams != null) { childParams.mBottom = anchorParams.mTop - (anchorParams.topMargin + childParams.bottomMargin); } else if (childParams.alignWithParent && rules[RelativeLayout.ABOVE] != null) { if (myHeight >= 0) { childParams.mBottom = myHeight - this.mPaddingBottom - childParams.bottomMargin; } } anchorParams = this.getRelatedViewParams(rules, RelativeLayout.BELOW); if (anchorParams != null) { childParams.mTop = anchorParams.mBottom + (anchorParams.bottomMargin + childParams.topMargin); } else if (childParams.alignWithParent && rules[RelativeLayout.BELOW] != null) { childParams.mTop = this.mPaddingTop + childParams.topMargin; } anchorParams = this.getRelatedViewParams(rules, RelativeLayout.ALIGN_TOP); if (anchorParams != null) { childParams.mTop = anchorParams.mTop + childParams.topMargin; } else if (childParams.alignWithParent && rules[RelativeLayout.ALIGN_TOP] != null) { childParams.mTop = this.mPaddingTop + childParams.topMargin; } anchorParams = this.getRelatedViewParams(rules, RelativeLayout.ALIGN_BOTTOM); if (anchorParams != null) { childParams.mBottom = anchorParams.mBottom - childParams.bottomMargin; } else if (childParams.alignWithParent && rules[RelativeLayout.ALIGN_BOTTOM] != null) { if (myHeight >= 0) { childParams.mBottom = myHeight - this.mPaddingBottom - childParams.bottomMargin; } } if (null != rules[RelativeLayout.ALIGN_PARENT_TOP]) { childParams.mTop = this.mPaddingTop + childParams.topMargin; } if (null != rules[RelativeLayout.ALIGN_PARENT_BOTTOM]) { if (myHeight >= 0) { childParams.mBottom = myHeight - this.mPaddingBottom - childParams.bottomMargin; } } if (rules[RelativeLayout.ALIGN_BASELINE] != null) { this.mHasBaselineAlignedChild = true; } } private getRelatedView(rules:string[], relation:number):View { let id:string = rules[relation]; if (id != null) { let node:RelativeLayout.DependencyGraph.Node = this.mGraph.mKeyNodes.get(id); if (node == null) return null; let v:View = node.view; // Find the first non-GONE view up the chain while (v.getVisibility() == View.GONE) { rules = (<RelativeLayout.LayoutParams> v.getLayoutParams()).getRules(v.getLayoutDirection()); node = this.mGraph.mKeyNodes.get((rules[relation])); if (node == null) return null; v = node.view; } return v; } return null; } private getRelatedViewParams(rules:string[], relation:number):RelativeLayout.LayoutParams { let v:View = this.getRelatedView(rules, relation); if (v != null) { let params:ViewGroup.LayoutParams = v.getLayoutParams(); if (params instanceof RelativeLayout.LayoutParams) { return <RelativeLayout.LayoutParams> v.getLayoutParams(); } } return null; } private getRelatedViewBaseline(rules:string[], relation:number):number { let v:View = this.getRelatedView(rules, relation); if (v != null) { return v.getBaseline(); } return -1; } private static centerHorizontal(child:View, params:RelativeLayout.LayoutParams, myWidth:number):void { let childWidth:number = child.getMeasuredWidth(); let left:number = (myWidth - childWidth) / 2; params.mLeft = left; params.mRight = left + childWidth; } private static centerVertical(child:View, params:RelativeLayout.LayoutParams, myHeight:number):void { let childHeight:number = child.getMeasuredHeight(); let top:number = (myHeight - childHeight) / 2; params.mTop = top; params.mBottom = top + childHeight; } protected onLayout(changed:boolean, l:number, t:number, r:number, b:number):void { // The layout has actually already been performed and the positions // cached. Apply the cached values to the children. const count:number = this.getChildCount(); for (let i:number = 0; i < count; i++) { let child:View = this.getChildAt(i); if (child.getVisibility() != RelativeLayout.GONE) { let st:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> child.getLayoutParams(); child.layout(st.mLeft, st.mTop, st.mRight, st.mBottom); } } } public generateLayoutParamsFromAttr(attrs: HTMLElement): android.view.ViewGroup.LayoutParams { return new RelativeLayout.LayoutParams(this.getContext(), attrs); } /** * Returns a set of layout parameters with a width of * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, * a height of {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} and no spanning. */ protected generateDefaultLayoutParams():ViewGroup.LayoutParams { return new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); } // Override to allow type-checking of LayoutParams. protected checkLayoutParams(p:ViewGroup.LayoutParams):boolean { return p instanceof RelativeLayout.LayoutParams; } protected generateLayoutParams(p:ViewGroup.LayoutParams):ViewGroup.LayoutParams { return new RelativeLayout.LayoutParams(p); } // //dispatchPopulateAccessibilityEvent(event:AccessibilityEvent):boolean { // if (this.mTopToBottomLeftToRightSet == null) { // this.mTopToBottomLeftToRightSet = new TreeSet<View>(new RelativeLayout.TopToBottomLeftToRightComparator(this)); // } // // sort children top-to-bottom and left-to-right // for (let i:number = 0, count:number = this.getChildCount(); i < count; i++) { // this.mTopToBottomLeftToRightSet.add(this.getChildAt(i)); // } // for (let view:View of this.mTopToBottomLeftToRightSet) { // if (view.getVisibility() == View.VISIBLE && view.dispatchPopulateAccessibilityEvent(event)) { // this.mTopToBottomLeftToRightSet.clear(); // return true; // } // } // this.mTopToBottomLeftToRightSet.clear(); // return false; //} // //onInitializeAccessibilityEvent(event:AccessibilityEvent):void { // super.onInitializeAccessibilityEvent(event); // event.setClassName(RelativeLayout.class.getName()); //} // //onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void { // super.onInitializeAccessibilityNodeInfo(info); // info.setClassName(RelativeLayout.class.getName()); //} } export module RelativeLayout{ ///** // * Compares two views in left-to-right and top-to-bottom fashion. // */ //export class TopToBottomLeftToRightComparator implements Comparator<View> { // _RelativeLayout_this:RelativeLayout; // constructor(arg:RelativeLayout){ // this._RelativeLayout_this = arg; // } // // compare(first:View, second:View):number { // // top - bottom // let topDifference:number = first.getTop() - second.getTop(); // if (topDifference != 0) { // return topDifference; // } // // left - right // let leftDifference:number = first.getLeft() - second.getLeft(); // if (leftDifference != 0) { // return leftDifference; // } // // break tie by height // let heightDiference:number = first.getHeight() - second.getHeight(); // if (heightDiference != 0) { // return heightDiference; // } // // break tie by width // let widthDiference:number = first.getWidth() - second.getWidth(); // if (widthDiference != 0) { // return widthDiference; // } // return 0; // } //} /** * Per-child layout information associated with RelativeLayout. * * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignWithParentIfMissing * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toLeftOf * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toRightOf * @attr ref android.R.styleable#RelativeLayout_Layout_layout_above * @attr ref android.R.styleable#RelativeLayout_Layout_layout_below * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignBaseline * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignLeft * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignTop * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignRight * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignBottom * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentLeft * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentTop * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentRight * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentBottom * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerInParent * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerHorizontal * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerVertical * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toStartOf * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toEndOf * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignStart * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignEnd * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentStart * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentEnd */ export class LayoutParams extends ViewGroup.MarginLayoutParams { private mRules:string[] = new Array<string>(RelativeLayout.VERB_COUNT); private mInitialRules:string[] = new Array<string>(RelativeLayout.VERB_COUNT); mLeft:number = 0; mTop:number = 0; mRight:number = 0; mBottom:number = 0; private mStart:number = LayoutParams.DEFAULT_MARGIN_RELATIVE; private mEnd:number = LayoutParams.DEFAULT_MARGIN_RELATIVE; private mRulesChanged:boolean = false; private mIsRtlCompatibilityMode:boolean = false; /** * When true, uses the parent as the anchor if the anchor doesn't exist or if * the anchor's visibility is GONE. */ alignWithParent:boolean; //constructor( c:Context, attrs:AttributeSet) { // super(c, attrs); // let a:TypedArray = c.obtainStyledAttributes(attrs, com.android.internal.R.styleable.RelativeLayout_Layout); // const targetSdkVersion:number = c.getApplicationInfo().targetSdkVersion; // this.mIsRtlCompatibilityMode = (targetSdkVersion < JELLY_BEAN_MR1 || !c.getApplicationInfo().hasRtlSupport()); // const rules:number[] = this.mRules; // //noinspection MismatchedReadAndWriteOfArray // const initialRules:number[] = this.mInitialRules; // const N:number = a.getIndexCount(); // for (let i:number = 0; i < N; i++) { // let attr:number = a.getIndex(i); // switch(attr) { // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignWithParentIfMissing: // this.alignWithParent = a.getBoolean(attr, false); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toLeftOf: // rules[RelativeLayout.LEFT_OF] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toRightOf: // rules[RelativeLayout.RIGHT_OF] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_above: // rules[RelativeLayout.ABOVE] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_below: // rules[RelativeLayout.BELOW] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignBaseline: // rules[RelativeLayout.ALIGN_BASELINE] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignLeft: // rules[RelativeLayout.ALIGN_LEFT] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignTop: // rules[RelativeLayout.ALIGN_TOP] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignRight: // rules[RelativeLayout.ALIGN_RIGHT] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignBottom: // rules[RelativeLayout.ALIGN_BOTTOM] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentLeft: // rules[RelativeLayout.ALIGN_PARENT_LEFT] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : 0; // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentTop: // rules[RelativeLayout.ALIGN_PARENT_TOP] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : 0; // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentRight: // rules[RelativeLayout.ALIGN_PARENT_RIGHT] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : 0; // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentBottom: // rules[RelativeLayout.ALIGN_PARENT_BOTTOM] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : 0; // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerInParent: // rules[RelativeLayout.CENTER_IN_PARENT] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : 0; // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerHorizontal: // rules[RelativeLayout.CENTER_HORIZONTAL] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : 0; // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerVertical: // rules[RelativeLayout.CENTER_VERTICAL] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : 0; // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toStartOf: // rules[RelativeLayout.START_OF] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toEndOf: // rules[RelativeLayout.END_OF] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignStart: // rules[RelativeLayout.ALIGN_START] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignEnd: // rules[RelativeLayout.ALIGN_END] = a.getResourceId(attr, 0); // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentStart: // rules[RelativeLayout.ALIGN_PARENT_START] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : 0; // break; // case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentEnd: // rules[RelativeLayout.ALIGN_PARENT_END] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : 0; // break; // } // } // this.mRulesChanged = true; // System.arraycopy(rules, RelativeLayout.LEFT_OF, initialRules, RelativeLayout.LEFT_OF, RelativeLayout.VERB_COUNT); // a.recycle(); //} constructor(context:Context, attrs:HTMLElement); constructor(w:number, h:number); constructor(source:RelativeLayout.LayoutParams); constructor(source:ViewGroup.LayoutParams); constructor(source:ViewGroup.MarginLayoutParams); constructor(...args){ super(...(() => { if (args[0] instanceof android.content.Context && args[1] instanceof HTMLElement) return [args[0], args[1]]; else if (typeof args[0] === 'number' && typeof args[1] === 'number') return [args[0], args[1]]; else if (args[0] instanceof RelativeLayout.LayoutParams) return [args[0]]; else if (args[0] instanceof ViewGroup.MarginLayoutParams) return [args[0]]; else if (args[0] instanceof ViewGroup.LayoutParams) return [args[0]]; })()); if (args[0] instanceof Context && args[1] instanceof HTMLElement) { const c = <Context>args[0]; const attrs = <HTMLElement>args[1]; let a = c.obtainStyledAttributes(attrs); // const targetSdkVersion:number = c.getApplicationInfo().targetSdkVersion; this.mIsRtlCompatibilityMode = false;//(targetSdkVersion < JELLY_BEAN_MR1 || !c.getApplicationInfo().hasRtlSupport()); const rules:string[] = this.mRules; //noinspection MismatchedReadAndWriteOfArray const initialRules:string[] = this.mInitialRules; for (let attr of a.getLowerCaseNoNamespaceAttrNames()) { switch(attr) { case 'layout_alignwithparentifmissing': this.alignWithParent = a.getBoolean(attr, false); break; case 'layout_toleftof': rules[RelativeLayout.LEFT_OF] = a.getResourceId(attr, null); break; case 'layout_torightof': rules[RelativeLayout.RIGHT_OF] = a.getResourceId(attr, null); break; case 'layout_above': rules[RelativeLayout.ABOVE] = a.getResourceId(attr, null); break; case 'layout_below': rules[RelativeLayout.BELOW] = a.getResourceId(attr, null); break; case 'layout_alignbaseline': rules[RelativeLayout.ALIGN_BASELINE] = a.getResourceId(attr, null); break; case 'layout_alignleft': rules[RelativeLayout.ALIGN_LEFT] = a.getResourceId(attr, null); break; case 'layout_aligntop': rules[RelativeLayout.ALIGN_TOP] = a.getResourceId(attr, null); break; case 'layout_alignright': rules[RelativeLayout.ALIGN_RIGHT] = a.getResourceId(attr, null); break; case 'layout_alignbottom': rules[RelativeLayout.ALIGN_BOTTOM] = a.getResourceId(attr, null); break; case 'layout_alignparentleft': rules[RelativeLayout.ALIGN_PARENT_LEFT] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : null; break; case 'layout_alignparenttop': rules[RelativeLayout.ALIGN_PARENT_TOP] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : null; break; case 'layout_alignparentright': rules[RelativeLayout.ALIGN_PARENT_RIGHT] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : null; break; case 'layout_alignparentbottom': rules[RelativeLayout.ALIGN_PARENT_BOTTOM] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : null; break; case 'layout_centerinparent': rules[RelativeLayout.CENTER_IN_PARENT] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : null; break; case 'layout_centerhorizontal': rules[RelativeLayout.CENTER_HORIZONTAL] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : null; break; case 'layout_centervertical': rules[RelativeLayout.CENTER_VERTICAL] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : null; break; case 'layout_tostartof': rules[RelativeLayout.START_OF] = a.getResourceId(attr, null); break; case 'layout_toendof': rules[RelativeLayout.END_OF] = a.getResourceId(attr, null); break; case 'layout_alignstart': rules[RelativeLayout.ALIGN_START] = a.getResourceId(attr, null); break; case 'layout_alignend': rules[RelativeLayout.ALIGN_END] = a.getResourceId(attr, null); break; case 'layout_alignparentstart': rules[RelativeLayout.ALIGN_PARENT_START] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : null; break; case 'layout_alignparentend': rules[RelativeLayout.ALIGN_PARENT_END] = a.getBoolean(attr, false) ? RelativeLayout.TRUE : null; break; } } this.mRulesChanged = true; System.arraycopy(rules, RelativeLayout.LEFT_OF, initialRules, RelativeLayout.LEFT_OF, RelativeLayout.VERB_COUNT); a.recycle(); } else if (typeof args[0] === 'number' && typeof args[1] === 'number') { super(args[0], args[1]); } else if (args[0] instanceof RelativeLayout.LayoutParams) { const source = <RelativeLayout.LayoutParams>args[0]; this.mIsRtlCompatibilityMode = source.mIsRtlCompatibilityMode; this.mRulesChanged = source.mRulesChanged; this.alignWithParent = source.alignWithParent; System.arraycopy(source.mRules, RelativeLayout.LEFT_OF, this.mRules, RelativeLayout.LEFT_OF, RelativeLayout.VERB_COUNT); System.arraycopy(source.mInitialRules, RelativeLayout.LEFT_OF, this.mInitialRules, RelativeLayout.LEFT_OF, RelativeLayout.VERB_COUNT); } else if (args[0] instanceof ViewGroup.MarginLayoutParams) { } else if (args[0] instanceof ViewGroup.LayoutParams) { } } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('layout_alignWithParentIfMissing', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { param.alignWithParent = attrBinder.parseBoolean(value, false); }, getter(param:LayoutParams) { return param.alignWithParent; } }).set('layout_toLeftOf', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.LEFT_OF, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.LEFT_OF]; } }).set('layout_toRightOf', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.RIGHT_OF, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.RIGHT_OF]; } }).set('layout_above', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.ABOVE, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ABOVE]; } }).set('layout_below', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.BELOW, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.BELOW]; } }).set('layout_alignBaseline', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.ALIGN_BASELINE, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_BASELINE]; } }).set('layout_alignLeft', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.ALIGN_LEFT, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_LEFT]; } }).set('layout_alignTop', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.ALIGN_TOP, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_TOP]; } }).set('layout_alignRight', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.ALIGN_RIGHT, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_RIGHT]; } }).set('layout_alignBottom', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.ALIGN_BOTTOM, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_BOTTOM]; } }).set('layout_alignParentLeft', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { const anchor = attrBinder.parseBoolean(value, false) ? RelativeLayout.TRUE : null; this.addRule(RelativeLayout.ALIGN_PARENT_LEFT, anchor); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_PARENT_LEFT]; } }).set('layout_alignParentTop', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { const anchor = attrBinder.parseBoolean(value, false) ? RelativeLayout.TRUE : null; this.addRule(RelativeLayout.ALIGN_PARENT_TOP, anchor); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_PARENT_TOP]; } }).set('layout_alignParentRight', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { const anchor = attrBinder.parseBoolean(value, false) ? RelativeLayout.TRUE : null; this.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, anchor); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_PARENT_RIGHT]; } }).set('layout_alignParentBottom', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { const anchor = attrBinder.parseBoolean(value, false) ? RelativeLayout.TRUE : null; this.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, anchor); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_PARENT_BOTTOM]; } }).set('layout_centerInParent', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { const anchor = attrBinder.parseBoolean(value, false) ? RelativeLayout.TRUE : null; this.addRule(RelativeLayout.CENTER_IN_PARENT, anchor); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.CENTER_IN_PARENT]; } }).set('layout_centerHorizontal', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { const anchor = attrBinder.parseBoolean(value, false) ? RelativeLayout.TRUE : null; this.addRule(RelativeLayout.CENTER_HORIZONTAL, anchor); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.CENTER_HORIZONTAL]; } }).set('layout_centerVertical', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { const anchor = attrBinder.parseBoolean(value, false) ? RelativeLayout.TRUE : null; this.addRule(RelativeLayout.CENTER_VERTICAL, anchor); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.CENTER_VERTICAL]; } }).set('layout_toStartOf', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.LEFT_OF, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.LEFT_OF]; } }).set('layout_toEndOf', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.RIGHT_OF, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.RIGHT_OF]; } }).set('layout_alignStart', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.ALIGN_LEFT, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_LEFT]; } }).set('layout_alignEnd', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { this.addRule(RelativeLayout.ALIGN_RIGHT, value+''); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_RIGHT]; } }).set('layout_alignParentStart', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { const anchor = attrBinder.parseBoolean(value, false) ? RelativeLayout.TRUE : null; this.addRule(RelativeLayout.ALIGN_PARENT_LEFT, anchor); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_PARENT_LEFT]; } }).set('layout_alignParentEnd', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { const anchor = attrBinder.parseBoolean(value, false) ? RelativeLayout.TRUE : null; this.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, anchor); }, getter(param:LayoutParams) { return param.mRules[RelativeLayout.ALIGN_PARENT_RIGHT]; } }); } /** * Adds a layout rule to be interpreted by the RelativeLayout. Use this for * verbs that take a target, such as a sibling (ALIGN_RIGHT) or a boolean * value (VISIBLE). * * @param verb One of the verbs defined by * {@link android.widget.RelativeLayout RelativeLayout}, such as * ALIGN_WITH_PARENT_LEFT. * @param anchor The id of another view to use as an anchor, * or a boolean value(represented as {@link RelativeLayout#TRUE}) * for true or 0 for false). For verbs that don't refer to another sibling * (for example, ALIGN_WITH_PARENT_BOTTOM) just use -1. * @see #addRule(int) */ addRule(verb:number, anchor:string=RelativeLayout.TRUE):void { this.mRules[verb] = anchor; this.mInitialRules[verb] = anchor; this.mRulesChanged = true; } /** * Removes a layout rule to be interpreted by the RelativeLayout. * * @param verb One of the verbs defined by * {@link android.widget.RelativeLayout RelativeLayout}, such as * ALIGN_WITH_PARENT_LEFT. * @see #addRule(int) * @see #addRule(int, int) */ removeRule(verb:number):void { this.mRules[verb] = null; this.mInitialRules[verb] = null; this.mRulesChanged = true; } private hasRelativeRules():boolean { return (this.mInitialRules[RelativeLayout.START_OF] != null || this.mInitialRules[RelativeLayout.END_OF] != null || this.mInitialRules[RelativeLayout.ALIGN_START] != null || this.mInitialRules[RelativeLayout.ALIGN_END] != null || this.mInitialRules[RelativeLayout.ALIGN_PARENT_START] != null || this.mInitialRules[RelativeLayout.ALIGN_PARENT_END] != null); } // The way we are resolving rules depends on the layout direction and if we are pre JB MR1 // or not. // // If we are pre JB MR1 (said as "RTL compatibility mode"), "left"/"right" rules are having // predominance over any "start/end" rules that could have been defined. A special case: // if no "left"/"right" rule has been defined and "start"/"end" rules are defined then we // resolve those "start"/"end" rules to "left"/"right" respectively. // // If we are JB MR1+, then "start"/"end" rules are having predominance over "left"/"right" // rules. If no "start"/"end" rule is defined then we use "left"/"right" rules. // // In all cases, the result of the resolution should clear the "start"/"end" rules to leave // only the "left"/"right" rules at the end. private resolveRules(layoutDirection:number):void { const isLayoutRtl:boolean = (layoutDirection == View.LAYOUT_DIRECTION_RTL); // Reset to initial state System.arraycopy(this.mInitialRules, RelativeLayout.LEFT_OF, this.mRules, RelativeLayout.LEFT_OF, RelativeLayout.VERB_COUNT); // Apply rules depending on direction and if we are in RTL compatibility mode if (this.mIsRtlCompatibilityMode) { if (this.mRules[RelativeLayout.ALIGN_START] != null) { if (this.mRules[RelativeLayout.ALIGN_LEFT] == null) { // "left" rule is not defined but "start" rule is: use the "start" rule as // the "left" rule this.mRules[RelativeLayout.ALIGN_LEFT] = this.mRules[RelativeLayout.ALIGN_START]; } this.mRules[RelativeLayout.ALIGN_START] = null; } if (this.mRules[RelativeLayout.ALIGN_END] != null) { if (this.mRules[RelativeLayout.ALIGN_RIGHT] == null) { // "right" rule is not defined but "end" rule is: use the "end" rule as the // "right" rule this.mRules[RelativeLayout.ALIGN_RIGHT] = this.mRules[RelativeLayout.ALIGN_END]; } this.mRules[RelativeLayout.ALIGN_END] = null; } if (this.mRules[RelativeLayout.START_OF] != null) { if (this.mRules[RelativeLayout.LEFT_OF] == null) { // "left" rule is not defined but "start" rule is: use the "start" rule as // the "left" rule this.mRules[RelativeLayout.LEFT_OF] = this.mRules[RelativeLayout.START_OF]; } this.mRules[RelativeLayout.START_OF] = null; } if (this.mRules[RelativeLayout.END_OF] != null) { if (this.mRules[RelativeLayout.RIGHT_OF] == null) { // "right" rule is not defined but "end" rule is: use the "end" rule as the // "right" rule this.mRules[RelativeLayout.RIGHT_OF] = this.mRules[RelativeLayout.END_OF]; } this.mRules[RelativeLayout.END_OF] = null; } if (this.mRules[RelativeLayout.ALIGN_PARENT_START] != null) { if (this.mRules[RelativeLayout.ALIGN_PARENT_LEFT] == null) { // "left" rule is not defined but "start" rule is: use the "start" rule as // the "left" rule this.mRules[RelativeLayout.ALIGN_PARENT_LEFT] = this.mRules[RelativeLayout.ALIGN_PARENT_START]; } this.mRules[RelativeLayout.ALIGN_PARENT_START] = null; } if (this.mRules[RelativeLayout.ALIGN_PARENT_RIGHT] == null) { if (this.mRules[RelativeLayout.ALIGN_PARENT_RIGHT] == null) { // "right" rule is not defined but "end" rule is: use the "end" rule as the // "right" rule this.mRules[RelativeLayout.ALIGN_PARENT_RIGHT] = this.mRules[RelativeLayout.ALIGN_PARENT_END]; } this.mRules[RelativeLayout.ALIGN_PARENT_END] = null; } } else { // JB MR1+ case if ((this.mRules[RelativeLayout.ALIGN_START] != null || this.mRules[RelativeLayout.ALIGN_END] != null) && (this.mRules[RelativeLayout.ALIGN_LEFT] != null || this.mRules[RelativeLayout.ALIGN_RIGHT] != null)) { // "start"/"end" rules take precedence over "left"/"right" rules this.mRules[RelativeLayout.ALIGN_LEFT] = null; this.mRules[RelativeLayout.ALIGN_RIGHT] = null; } if (this.mRules[RelativeLayout.ALIGN_START] != null) { // "start" rule resolved to "left" or "right" depending on the direction this.mRules[isLayoutRtl ? RelativeLayout.ALIGN_RIGHT : RelativeLayout.ALIGN_LEFT] = this.mRules[RelativeLayout.ALIGN_START]; this.mRules[RelativeLayout.ALIGN_START] = null; } if (this.mRules[RelativeLayout.ALIGN_END] != null) { // "end" rule resolved to "left" or "right" depending on the direction this.mRules[isLayoutRtl ? RelativeLayout.ALIGN_LEFT : RelativeLayout.ALIGN_RIGHT] = this.mRules[RelativeLayout.ALIGN_END]; this.mRules[RelativeLayout.ALIGN_END] = null; } if ((this.mRules[RelativeLayout.START_OF] != null || this.mRules[RelativeLayout.END_OF] != null) && (this.mRules[RelativeLayout.LEFT_OF] != null || this.mRules[RelativeLayout.RIGHT_OF] != null)) { // "start"/"end" rules take precedence over "left"/"right" rules this.mRules[RelativeLayout.LEFT_OF] = null; this.mRules[RelativeLayout.RIGHT_OF] = null; } if (this.mRules[RelativeLayout.START_OF] != null) { // "start" rule resolved to "left" or "right" depending on the direction this.mRules[isLayoutRtl ? RelativeLayout.RIGHT_OF : RelativeLayout.LEFT_OF] = this.mRules[RelativeLayout.START_OF]; this.mRules[RelativeLayout.START_OF] = null; } if (this.mRules[RelativeLayout.END_OF] != null) { // "end" rule resolved to "left" or "right" depending on the direction this.mRules[isLayoutRtl ? RelativeLayout.LEFT_OF : RelativeLayout.RIGHT_OF] = this.mRules[RelativeLayout.END_OF]; this.mRules[RelativeLayout.END_OF] = null; } if ((this.mRules[RelativeLayout.ALIGN_PARENT_START] != null || this.mRules[RelativeLayout.ALIGN_PARENT_END] != null) && (this.mRules[RelativeLayout.ALIGN_PARENT_LEFT] != null || this.mRules[RelativeLayout.ALIGN_PARENT_RIGHT] != null)) { // "start"/"end" rules take precedence over "left"/"right" rules this.mRules[RelativeLayout.ALIGN_PARENT_LEFT] = null; this.mRules[RelativeLayout.ALIGN_PARENT_RIGHT] = null; } if (this.mRules[RelativeLayout.ALIGN_PARENT_START] != null) { // "start" rule resolved to "left" or "right" depending on the direction this.mRules[isLayoutRtl ? RelativeLayout.ALIGN_PARENT_RIGHT : RelativeLayout.ALIGN_PARENT_LEFT] = this.mRules[RelativeLayout.ALIGN_PARENT_START]; this.mRules[RelativeLayout.ALIGN_PARENT_START] = null; } if (this.mRules[RelativeLayout.ALIGN_PARENT_END] != null) { // "end" rule resolved to "left" or "right" depending on the direction this.mRules[isLayoutRtl ? RelativeLayout.ALIGN_PARENT_LEFT : RelativeLayout.ALIGN_PARENT_RIGHT] = this.mRules[RelativeLayout.ALIGN_PARENT_END]; this.mRules[RelativeLayout.ALIGN_PARENT_END] = null; } } this.mRulesChanged = false; } /** * Retrieves a complete list of all supported rules, where the index is the rule * verb, and the element value is the value specified, or "false" if it was never * set. If there are relative rules defined (*_START / *_END), they will be resolved * depending on the layout direction. * * @param layoutDirection the direction of the layout. * Should be either {@link View#LAYOUT_DIRECTION_LTR} * or {@link View#LAYOUT_DIRECTION_RTL} * @return the supported rules * @see #addRule(int, int) * * @hide */ getRules(layoutDirection?:number):string[] { if(layoutDirection!=null) { if (this.hasRelativeRules() && (this.mRulesChanged || layoutDirection != this.getLayoutDirection())) { this.resolveRules(layoutDirection); if (layoutDirection != this.getLayoutDirection()) { this.setLayoutDirection(layoutDirection); } } } return this.mRules; } resolveLayoutDirection(layoutDirection:number):void { const isLayoutRtl:boolean = this.isLayoutRtl(); if (isLayoutRtl) { if (this.mStart != LayoutParams.DEFAULT_MARGIN_RELATIVE) this.mRight = this.mStart; if (this.mEnd != LayoutParams.DEFAULT_MARGIN_RELATIVE) this.mLeft = this.mEnd; } else { if (this.mStart != LayoutParams.DEFAULT_MARGIN_RELATIVE) this.mLeft = this.mStart; if (this.mEnd != LayoutParams.DEFAULT_MARGIN_RELATIVE) this.mRight = this.mEnd; } if (this.hasRelativeRules() && layoutDirection != this.getLayoutDirection()) { this.resolveRules(layoutDirection); } // This will set the layout direction super.resolveLayoutDirection(layoutDirection); } } export class DependencyGraph { /** * List of all views in the graph. */ private mNodes:ArrayList<DependencyGraph.Node> = new ArrayList<DependencyGraph.Node>(); /** * List of nodes in the graph. Each node is identified by its * view id (see View#getId()). */ mKeyNodes:SparseMap<string, DependencyGraph.Node> = new SparseMap<string, DependencyGraph.Node>(); /** * Temporary data structure used to build the list of roots * for this graph. */ private mRoots:ArrayDeque<DependencyGraph.Node> = new ArrayDeque<DependencyGraph.Node>(); /** * Clears the graph. */ clear():void { const nodes:ArrayList<DependencyGraph.Node> = this.mNodes; const count:number = nodes.size(); for (let i:number = 0; i < count; i++) { nodes.get(i).release(); } nodes.clear(); this.mKeyNodes.clear(); this.mRoots.clear(); } /** * Adds a view to the graph. * * @param view The view to be added as a node to the graph. */ add(view:View):void { const id:string = view.getId(); const node:DependencyGraph.Node = DependencyGraph.Node.acquire(view); if (id != View.NO_ID) { this.mKeyNodes.put(id, node); } this.mNodes.add(node); } /** * Builds a sorted list of views. The sorting order depends on the dependencies * between the view. For instance, if view C needs view A to be processed first * and view A needs view B to be processed first, the dependency graph * is: B -> A -> C. The sorted array will contain views B, A and C in this order. * * @param sorted The sorted list of views. The length of this array must * be equal to getChildCount(). * @param rules The list of rules to take into account. */ getSortedViews(sorted:View[], rules:number[]):void { const roots:ArrayDeque<DependencyGraph.Node> = this.findRoots(rules); let index:number = 0; let node:DependencyGraph.Node; while ((node = roots.pollLast()) != null) { const view:View = node.view; const key:string = view.getId(); sorted[index++] = view; const dependents:ArrayMap<DependencyGraph.Node, DependencyGraph> = node.dependents; const count:number = dependents.size(); for (let i:number = 0; i < count; i++) { const dependent:DependencyGraph.Node = dependents.keyAt(i); const dependencies = dependent.dependencies; dependencies.remove(key); if (dependencies.size() == 0) { roots.add(dependent); } } } if (index < sorted.length) { throw Error(`new IllegalStateException("Circular dependencies cannot exist" + " in RelativeLayout")`); } } /** * Finds the roots of the graph. A root is a node with no dependency and * with [0..n] dependents. * * @param rulesFilter The list of rules to consider when building the * dependencies * * @return A list of node, each being a root of the graph */ private findRoots(rulesFilter:number[]):ArrayDeque<DependencyGraph.Node> { const keyNodes:SparseMap<string, DependencyGraph.Node> = this.mKeyNodes; const nodes:ArrayList<DependencyGraph.Node> = this.mNodes; const count:number = nodes.size(); // all dependents and dependencies before running the algorithm for (let i:number = 0; i < count; i++) { const node:DependencyGraph.Node = nodes.get(i); node.dependents.clear(); node.dependencies.clear(); } // Builds up the dependents and dependencies for each node of the graph for (let i:number = 0; i < count; i++) { const node:DependencyGraph.Node = nodes.get(i); const layoutParams:RelativeLayout.LayoutParams = <RelativeLayout.LayoutParams> node.view.getLayoutParams(); const rules:string[] = layoutParams.mRules; const rulesCount:number = rulesFilter.length; // dependencies for a specific set of rules for (let j:number = 0; j < rulesCount; j++) { const rule:string = rules[rulesFilter[j]]; if (rule != null) { // The node this node depends on const dependency:DependencyGraph.Node = keyNodes.get(rule); // Skip unknowns and self dependencies if (dependency == null || dependency == node) { continue; } // Add the current node as a dependent dependency.dependents.put(node, this); // Add a dependency to the current node node.dependencies.put(rule, dependency); } } } const roots:ArrayDeque<DependencyGraph.Node> = this.mRoots; roots.clear(); // Finds all the roots in the graph: all nodes with no dependencies for (let i:number = 0; i < count; i++) { const node:DependencyGraph.Node = nodes.get(i); if (node.dependencies.size() == 0) roots.addLast(node); } return roots; } } export module DependencyGraph{ /** * A node in the dependency graph. A node is a view, its list of dependencies * and its list of dependents. * * A node with no dependent is considered a root of the graph. */ export class Node { /** * The view representing this node in the layout. */ view:View; /** * The list of dependents for this node; a dependent is a node * that needs this node to be processed first. */ dependents:ArrayMap<Node, RelativeLayout.DependencyGraph> = new ArrayMap<Node, RelativeLayout.DependencyGraph>(); /** * The list of dependencies for this node. */ dependencies:SparseMap<string, Node> = new SparseMap<string, Node>(); /* * START POOL IMPLEMENTATION */ // The pool is static, so all nodes instances are shared across // activities, that's why we give it a rather high limit private static POOL_LIMIT:number = 100; private static sPool:SynchronizedPool<Node> = new SynchronizedPool<Node>(Node.POOL_LIMIT); static acquire(view:View):Node { let node:Node = Node.sPool.acquire(); if (node == null) { node = new Node(); } node.view = view; return node; } release():void { this.view = null; this.dependents.clear(); this.dependencies.clear(); Node.sPool.release(this); } /* * END POOL IMPLEMENTATION */ } } } }
the_stack
import { PivotFieldList } from '../../src/pivotfieldlist/base/field-list'; import { createElement, remove, isNullOrUndefined, EmitType, closest, getInstance } from '@syncfusion/ej2-base'; import { pivot_dataset } from '../base/datasource.spec'; import { IDataSet } from '../../src/base/engine'; import { MenuEventArgs } from '@syncfusion/ej2-navigations'; import { PivotCommon } from '../../src/common/base/pivot-common'; import { CalculatedField } from '../../src/common/calculatedfield/calculated-field'; import { PivotView } from '../../src/pivotview/base/pivotview'; import { GroupingBar } from '../../src/common/grouping-bar/grouping-bar'; import { FieldList } from '../../src/common/actions/field-list'; import { addClass, removeClass } from '@syncfusion/ej2-base'; import { DropDownList } from '@syncfusion/ej2-dropdowns'; import * as util from '../utils.spec'; import { profile, inMB, getMemoryProfile } from '../common.spec'; /** * Pivot keyboard interaction spec */ describe('Pivot Rendering', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('Testing on keyboard interaction with Field List', () => { let fieldListObj: PivotFieldList; let pivotCommon: PivotCommon; let keyModule: any; let cField: any; interface CommonArgs { preventDefault(): void; } let elem: HTMLElement = createElement('div', { id: 'PivotFieldList', styles: 'height:400px;width:60%' }); afterAll(() => { if (fieldListObj) { fieldListObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); let dataBound: EmitType<Object> = () => { done(); }; PivotFieldList.Inject(CalculatedField); fieldListObj = new PivotFieldList( { dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, enableSorting: true, sortSettings: [{ name: 'company', order: 'Descending' }], filterSettings: [{ name: 'name', type: 'Include', items: ['Knight Wooten'] }, { name: 'company', type: 'Exclude', items: ['NIPAZ'] }, { name: 'gender', type: 'Include', items: ['male'] }], rows: [{ name: 'company' }, { name: 'state' }], columns: [{ name: 'name' }], values: [{ name: 'balance' }, { name: 'quantity' }], filters: [{ name: 'gender' }] }, allowCalculatedField: true, renderMode: 'Fixed', dataBound: dataBound }); fieldListObj.appendTo('#PivotFieldList'); keyModule = fieldListObj.pivotCommon.keyboardModule; pivotCommon = fieldListObj.pivotCommon; cField = fieldListObj.calculatedFieldModule; }); it('Check shiftS key for sort action', () => { let pivotButtons: HTMLElement[] = [].slice.call(fieldListObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); keyModule.keyActionHandler({ action: 'shiftS', target: pivotButtons[2], preventDefault: (): void => { /** Null */ } }); expect((pivotButtons[2]).querySelector('.e-descend')).toBeTruthy; }); it('Check shiftF key for filter action', (done: Function) => { let pivotButtons: HTMLElement[] = [].slice.call(fieldListObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); keyModule.keyActionHandler({ action: 'shiftF', target: pivotButtons[0], preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotCommon.filterDialog.dialogPopUp.element.classList.contains('e-popup-open')).toBe(true); done(); }, 1000); }); it('Check shiftF key for filter update action', (done: Function) => { let filterDialog: HTMLElement = pivotCommon.filterDialog.dialogPopUp.element; (filterDialog.querySelector('.e-ok-btn') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotCommon.filterDialog.dialogPopUp).toBeUndefined; done(); }, 1000); }); it('Check remove action', () => { let pivotButtons: HTMLElement[] = [].slice.call(fieldListObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); keyModule.keyActionHandler({ action: 'delete', target: pivotButtons[0], preventDefault: (): void => { /** Null */ } }); let pivotButtonUpdate: HTMLElement[] = [].slice.call(fieldListObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtonUpdate.length).toEqual(pivotButtons.length - 1); }); it('Check enter formula action', (done: Function) => { (document.querySelector('.e-calculated-field') as HTMLElement).click(); addClass([(document.querySelectorAll('.e-pivot-calc-dialog-div .e-list-item')[0] as HTMLElement)], ['e-hover', 'e-node-focus']); cField.keyActionHandler({ action: 'enter', currentTarget: cField.dialog.element, preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { // expect(true).toBeTruthy(); expect((document.querySelector('#' + cField.parentID + 'droppable') as HTMLTextAreaElement).value === '"Count(_id)"').toBeTruthy(); (document.querySelector('#' + cField.parentID + 'droppable') as HTMLTextAreaElement).value = ''; done(); }, 1000); }); it('Check enter formula action', (done: Function) => { removeClass([(document.querySelectorAll('.e-pivot-calc-dialog-div .e-list-item')[0] as HTMLElement)], ['e-hover', 'e-node-focus']); addClass([(document.querySelectorAll('.e-pivot-calc-dialog-div .e-list-item')[15] as HTMLElement)], ['e-hover', 'e-node-focus']); cField.keyActionHandler({ action: 'enter', currentTarget: cField.dialog.element, preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { // expect(true).toBeTruthy(); expect((document.querySelector('#' + cField.parentID + 'droppable') as HTMLTextAreaElement).value === '"Count(product)"').toBeTruthy(); done(); }, 1000); }); it('Check enter formula action', (done: Function) => { (document.querySelector('#' + cField.parentID + 'droppable') as HTMLTextAreaElement).value = '10'; removeClass([(document.querySelectorAll('.e-pivot-calc-dialog-div .e-list-item')[15] as HTMLElement)], ['e-hover', 'e-node-focus']); addClass([(document.querySelectorAll('.e-pivot-calc-dialog-div .e-list-item')[1] as HTMLElement)], ['e-hover', 'e-node-focus']); cField.keyActionHandler({ action: 'enter', currentTarget: cField.dialog.element, preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { // expect(true).toBeTruthy(); expect((document.querySelector('#' + cField.parentID + 'droppable') as HTMLTextAreaElement).value === '10"Sum(advance)"').toBeTruthy(); done(); }, 1000); }); it('Check enter formula action', (done: Function) => { (document.querySelector('#' + cField.parentID + 'droppable') as HTMLTextAreaElement).value = '10'; removeClass([(document.querySelectorAll('.e-pivot-calc-dialog-div .e-list-item')[1] as HTMLElement)], ['e-hover', 'e-node-focus']); addClass([(document.querySelectorAll('.e-pivot-calc-dialog-div .e-list-item')[15] as HTMLElement)], ['e-hover', 'e-node-focus']); cField.keyActionHandler({ action: 'enter', currentTarget: cField.dialog.element, preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { // expect(true).toBeTruthy(); expect((document.querySelector('#' + cField.parentID + 'droppable') as HTMLTextAreaElement).value === '10"Count(product)"').toBeTruthy(); (document.querySelector('#' + cField.parentID + 'droppable') as HTMLTextAreaElement).value = ''; done(); }, 1000); }); it('Check menu action', () => { removeClass([(document.querySelectorAll('.e-pivot-calc-dialog-div .e-list-item')[15] as HTMLElement)], ['e-hover', 'e-node-focus']); addClass([(document.querySelectorAll('.e-pivot-calc-dialog-div .e-list-item')[1] as HTMLElement)], ['e-hover', 'e-node-focus']); cField.keyActionHandler({ action: 'moveRight', currentTarget: cField.dialog.element, preventDefault: (): void => { /** Null */ } }); expect(true).toBeTruthy(); cField.closeDialog(); }); }); describe('Testing on keyboard interaction with Field List-Popup mode', () => { let fieldListObj: PivotFieldList; let pivotCommon: PivotCommon; let eventArgs: any; let elem: HTMLElement = createElement('div', { id: 'PivotFieldList', styles: 'height:400px;width:60%' }); afterAll(() => { if (fieldListObj) { fieldListObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); let dataBound: EmitType<Object> = () => { done(); }; PivotFieldList.Inject(CalculatedField); fieldListObj = new PivotFieldList( { dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, enableSorting: true, sortSettings: [{ name: 'company', order: 'Descending' }], calculatedFieldSettings: [{ name: 'price', formula: '5+10' }], filterSettings: [{ name: 'name', type: 'Include', items: ['Knight Wooten'] }, { name: 'company', type: 'Exclude', items: ['NIPAZ'] }, { name: 'gender', type: 'Include', items: ['male'] }], rows: [{ name: 'company' }, { name: 'state' }], columns: [{ name: 'name' }], values: [{ name: 'balance' }, { name: 'quantity' }], filters: [{ name: 'gender' }, { name: 'price', type: 'CalculatedField' }] }, allowCalculatedField: true, target: elem, dataBound: dataBound }); fieldListObj.appendTo('#PivotFieldList'); util.disableDialogAnimation(fieldListObj.dialogRenderer.fieldListDialog); pivotCommon = fieldListObj.pivotCommon; }); it('control class testing', () => { expect(fieldListObj.element.classList.contains('e-pivotfieldlist')).toEqual(true); }); it('Check enter key for filter action', () => { let fieldListIcon: HTMLElement = (fieldListObj.element.querySelector('.e-toggle-field-list') as HTMLElement); expect(fieldListIcon.classList.contains('e-hide')).not.toBeTruthy(); eventArgs = { keyCode: 13, altKey: false, ctrlKey: false, shiftKey: false, target: fieldListIcon, preventDefault: (): void => { /** Null */ } }; (fieldListObj.dialogRenderer as any).keyPress(eventArgs); expect(fieldListIcon.classList.contains('e-hide')).toBeTruthy(); }); it('check field list icon', () => { (fieldListObj.element.querySelector('.e-toggle-field-list') as HTMLElement).click(); expect(true).toBe(true); }); it('check field list dialog with targetID', () => { expect(!isNullOrUndefined(elem.querySelector('.e-pivotfieldlist-container'))); }); }); describe('Testing on keyboard interaction with PivotGrid with GroupingBar', () => { let pivotGridObj: PivotView; let pivotCommon: PivotCommon; let keyModule: any; let pivotViewKeyModule: any; let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:200px; width:500px' }); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); let dataBound: EmitType<Object> = () => { done(); }; PivotView.Inject(GroupingBar); pivotGridObj = new PivotView( { dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, enableSorting: true, sortSettings: [{ name: 'company', order: 'Descending' }], filterSettings: [{ name: 'name', type: 'Include', items: ['Knight Wooten'] }, { name: 'company', type: 'Exclude', items: ['NIPAZ'] }, { name: 'gender', type: 'Include', items: ['male'] }], rows: [{ name: 'company' }, { name: 'state' }], columns: [{ name: 'name' }], values: [{ name: 'balance' }, { name: 'quantity' }], filters: [{ name: 'gender' }] }, showGroupingBar: true, dataBound: dataBound }); pivotGridObj.appendTo('#PivotGrid'); }); beforeEach(() => { keyModule = pivotGridObj.pivotCommon.keyboardModule; pivotViewKeyModule = pivotGridObj.keyboardModule; pivotCommon = pivotGridObj.pivotCommon; }); it('Check sort action', () => { let pivotButtons: HTMLElement[] = [].slice.call(pivotGridObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); keyModule.keyActionHandler({ action: 'shiftS', target: pivotButtons[pivotButtons.length - 1], preventDefault: (): void => { /** Null */ } }); expect((pivotButtons[pivotButtons.length - 1]).querySelector('.e-descend')).toBeTruthy; }); it('Check filter action', (done: Function) => { let pivotButtons: HTMLElement[] = [].slice.call(pivotGridObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); keyModule.keyActionHandler({ action: 'shiftF', target: pivotButtons[pivotButtons.length - 1], preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotCommon.filterDialog.dialogPopUp.element.classList.contains('e-popup-open')).toBe(true); done(); }, 1000); }); it('Close filter dialog', (done: Function) => { let filterDialog: HTMLElement = pivotCommon.filterDialog.dialogPopUp.element; (filterDialog.querySelector('.e-ok-btn') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotCommon.filterDialog.dialogPopUp).toBeUndefined; done(); }, 1000); }); it('Check remove action', (done: Function) => { let pivotButtons: HTMLElement[] = [].slice.call(pivotGridObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); keyModule.keyActionHandler({ action: 'delete', target: pivotButtons[0], preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let pivotButtonUpdate: HTMLElement[] = [].slice.call(pivotGridObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtonUpdate.length).toEqual(pivotButtons.length - 1); done(); }, 1000); }); it('Check tab action', (done: Function) => { let pivotButtons: HTMLElement[] = [].slice.call(pivotGridObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); pivotViewKeyModule.keyActionHandler({ action: 'tab', target: pivotButtons[0], preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let focuesdEle: HTMLElement = document.activeElement as HTMLElement; expect(focuesdEle.id === pivotButtons[0].id).toBeTruthy; done(); }, 1000); }); it('Check tab action to grid cell focus', (done: Function) => { let pivotButtons: HTMLElement[] = [].slice.call(pivotGridObj.element.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); pivotViewKeyModule.keyActionHandler({ action: 'tab', target: pivotButtons[pivotButtons.length - 1], preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotGridObj.grid.element.querySelector('.e-focused')).toBeTruthy; done(); }, 1000); }); }); describe('Testing on keyboard interaction with PivotGrid with FieldList', () => { let pivotGridObj: PivotView; let pivotCommon: PivotCommon; let pivotViewKeyModule: any; let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:200px; width:500px' }); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); let dataBound: EmitType<Object> = () => { done(); }; PivotView.Inject(FieldList); pivotGridObj = new PivotView( { dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, enableSorting: true, sortSettings: [{ name: 'company', order: 'Descending' }], filterSettings: [{ name: 'name', type: 'Include', items: ['Knight Wooten'] }, { name: 'company', type: 'Include', items: ['NIPAZ'] }, { name: 'gender', type: 'Include', items: ['male'] }], rows: [{ name: 'company' }, { name: 'state' }], columns: [{ name: 'name' }], values: [{ name: 'balance' }, { name: 'quantity' }], filters: [{ name: 'gender' }] }, showFieldList: true, dataBound: dataBound }); pivotGridObj.appendTo('#PivotGrid'); }); beforeEach((done: Function) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { pivotViewKeyModule = pivotGridObj.keyboardModule; done(); }, 1000); }); it('Check tab action', (done: Function) => { pivotViewKeyModule.keyActionHandler({ action: 'tab', target: pivotGridObj.element.querySelector('.e-toggle-field-list'), preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotGridObj.grid.element.querySelector('.e-focused')).toBeTruthy; done(); }, 1000); }); it('Check enter action to grid cell', (done: Function) => { expect(pivotGridObj.grid.element.querySelector('.e-expand')).toBeTruthy; let gridcell: Element = closest(pivotGridObj.grid.element.querySelector('.e-expand'), '.e-rowcell'); expect(gridcell).toBeTruthy; pivotViewKeyModule.keyActionHandler({ action: 'enter', target: gridcell, preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotGridObj.grid.element.querySelector('.e-collapse')).toBeTruthy; done(); }, 1000); }); it('set rtl property', (done: Function) => { pivotGridObj.enableRtl = true; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotGridObj.element.classList.contains('e-rtl')).toBeTruthy; done(); }, 1000); }); it('remove rtl property', (done: Function) => { pivotGridObj.enableRtl = false; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotGridObj.element.classList.contains('e-rtl')).not.toBeTruthy; done(); }, 1000); }); }); describe('Testing on keyboard interaction with PivotGrid with GroupingBar and FieldList', () => { let pivotGridObj: PivotView; let pivotCommon: PivotCommon; let keyModule: any; let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:200px; width:500px' }); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); let dataBound: EmitType<Object> = () => { done(); }; PivotView.Inject(GroupingBar, FieldList); pivotGridObj = new PivotView( { dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, enableSorting: true, sortSettings: [{ name: 'company', order: 'Descending' }], filterSettings: [{ name: 'name', type: 'Include', items: ['Knight Wooten'] }, { name: 'company', type: 'Include', items: ['NIPAZ'] }, { name: 'gender', type: 'Include', items: ['male'] }], rows: [{ name: 'company' }, { name: 'state' }], columns: [{ name: 'name' }], values: [{ name: 'balance' }, { name: 'quantity' }], filters: [{ name: 'gender' }] }, showFieldList: true, showGroupingBar: true, dataBound: dataBound }); pivotGridObj.appendTo('#PivotGrid'); }); beforeEach((done: Function) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { keyModule = pivotGridObj.pivotCommon.keyboardModule; pivotCommon = pivotGridObj.pivotCommon; done(); }, 1000); }); it('Check enter action to grid cell', (done: Function) => { expect(pivotGridObj.grid.element.querySelector('.e-expand')).toBeTruthy; let gridcell: Element = closest(pivotGridObj.grid.element.querySelector('.e-expand'), '.e-rowcell'); expect(gridcell).toBeTruthy; keyModule.keyActionHandler({ action: 'enter', target: gridcell, preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotGridObj.grid.element.querySelector('.e-collapse')).toBeTruthy; done(); }, 1000); }); }); describe('Testing on keyboard interaction with PivotGrid only', () => { let pivotGridObj: PivotView; let pivotViewKeyModule: any; let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:200px; width:500px' }); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); let dataBound: EmitType<Object> = () => { done(); }; pivotGridObj = new PivotView( { dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, enableSorting: true, sortSettings: [{ name: 'company', order: 'Descending' }], filterSettings: [{ name: 'name', type: 'Include', items: ['Knight Wooten'] }, { name: 'company', type: 'Include', items: ['NIPAZ'] }, { name: 'gender', type: 'Include', items: ['male'] }], rows: [{ name: 'company' }, { name: 'state' }], columns: [{ name: 'name' }], values: [{ name: 'balance' }, { name: 'quantity' }], filters: [{ name: 'gender' }] }, dataBound: dataBound }); pivotGridObj.appendTo('#PivotGrid'); }); beforeEach((done: Function) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { pivotViewKeyModule = pivotGridObj.keyboardModule; done(); }, 1000); }); it('Check tab action', (done: Function) => { pivotViewKeyModule.keyActionHandler({ action: 'tab', target: pivotGridObj.element, preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotGridObj.grid.element.querySelector('.e-focused')).toBeTruthy; done(); }, 1000); }); it('Check tab action for last cell', (done: Function) => { let gridcell: Element = [].slice.call(pivotGridObj.grid.element.querySelectorAll('td'))[pivotGridObj.grid.element.querySelectorAll('td').length - 1]; pivotViewKeyModule.keyActionHandler({ action: 'tab', target: gridcell, preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotGridObj.grid.element.querySelector('.e-focused')).not.toBeTruthy; done(); }, 1000); }); it('Check enter action to grid cell', (done: Function) => { expect(pivotGridObj.grid.element.querySelector('.e-expand')).toBeTruthy; let gridcell: Element = closest(pivotGridObj.grid.element.querySelector('.e-expand'), '.e-rowcell'); expect(gridcell).toBeTruthy; pivotViewKeyModule.keyActionHandler({ action: 'enter', target: gridcell, preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(pivotGridObj.grid.element.querySelector('.e-collapse')).toBeTruthy; done(); }, 1000); }); }); describe('Testing Pivot Grid aggregation module on keyboard interaction in grouping bar with fieldlist', () => { let pivotGridObj: any; let keyModule: any; let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:200px; width:500px' }); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll(() => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); PivotView.Inject(GroupingBar, FieldList, CalculatedField); pivotGridObj = new PivotView({ dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, formatSettings: [{ name: 'balance', format: 'C' }], sortSettings: [{ name: 'eyeColor', order: 'Descending' }], rows: [{ name: 'eyeColor' }], columns: [{ name: 'isActive' }], values: [{ name: 'balance' }] }, showFieldList: true, allowCalculatedField: true, showGroupingBar: true, width: 1000, height: 500 }); pivotGridObj.appendTo('#PivotGrid'); }); it('set keymodule', (done: Function) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { keyModule = pivotGridObj.pivotCommon.keyboardModule done(); }, 1000); }); it('check dropdown icon', () => { var valueField: HTMLElement = pivotGridObj.element.querySelector('.e-group-values'); var pivotButtons: HTMLElement[] = [].slice.call(valueField.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); keyModule.keyActionHandler({ action: 'enter', target: pivotButtons[0], preventDefault: (): void => { /** Null */ } }); expect(document.getElementById("FieldListcontextmenu")).toBeTruthy; }); it('select context Menu', (done: Function) => { let menuObj: any = (pivotGridObj.pivotButtonModule.menuOption as any).menuInfo[0]; let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>menuObj.element.querySelectorAll('li'); let menu: any = { element: li[1], item: menuObj.items[1] }; menuObj.select(menu as MenuEventArgs); var valueField: HTMLElement = pivotGridObj.element.querySelector('.e-group-values'); var pivotButtons: HTMLElement[] = [].slice.call(valueField.querySelectorAll('.e-pivot-button')); //expect(pivotButtons.length).toBeGreaterThan(0); let buttonText: HTMLElement = ((pivotButtons[0]).querySelector('.e-content') as HTMLElement); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { menuObj.close(); expect(buttonText.innerHTML).toEqual('Count of balance'); done(); }, 1000); }); it('check pivot grid aggregation', () => { expect(pivotGridObj.pivotValues[1][1].formattedText).toEqual('69'); }); it('check dropdown icon for more option', () => { var valueField: HTMLElement = pivotGridObj.element.querySelector('.e-group-values'); var pivotButtons: HTMLElement[] = [].slice.call(valueField.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); keyModule.keyActionHandler({ action: 'enter', target: pivotButtons[0], preventDefault: (): void => { /** Null */ } }); expect(document.getElementById("FieldListcontextmenu")).toBeTruthy; }); it('check more option dialog', (done: Function) => { let menuObj: any = (pivotGridObj.pivotButtonModule.menuOption as any).menuInfo[0]; let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>menuObj.element.querySelectorAll('li'); let menu: any = { element: li[li.length - 1], item: menuObj.items[li.length - 1] }; menuObj.select(menu as MenuEventArgs); var valueField: HTMLElement = pivotGridObj.element.querySelector('.e-group-values'); var pivotButtons: HTMLElement[] = [].slice.call(valueField.querySelectorAll('.e-pivot-button')); //expect(pivotButtons.length).toBeGreaterThan(0); let buttonText: HTMLElement = ((pivotButtons[0]).querySelector('.e-content') as HTMLElement); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { menuObj.close(); expect(buttonText.innerHTML).toEqual('Count of balance'); done(); }, 1000); }); it('agrregation options check', (done: Function) => { let dialogElement: HTMLElement = (pivotGridObj.pivotButtonModule.menuOption as any).valueDialog.element; let dropdownlist: any = getInstance(dialogElement.querySelector('#' + 'PivotGrid_type_option') as HTMLElement, DropDownList); let fieldsddl: any = getInstance(dialogElement.querySelector('#' + 'PivotGrid_base_field_option') as HTMLElement, DropDownList); expect(fieldsddl).toBeTruthy; expect(dropdownlist).toBeTruthy; dropdownlist.value = "DifferenceFrom"; fieldsddl.value = "isActive"; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (dialogElement.querySelector('.e-ok-btn') as HTMLElement).click(); done(); }, 1000); }); it('check pivot grid aggregation', () => { expect(pivotGridObj.pivotValues[1][2].formattedText).toEqual('$29,322.76'); }); it('Check aggregation in fieldlist', (done: Function) => { //pivotGridObj.refresh(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((pivotGridObj.element.querySelector('.e-toggle-field-list') as HTMLElement).click()).toBeTruthy; done(); }, 1000); }); it('check dropdown icon', () => { //var valueField: HTMLElement = pivotGridObj.element.querySelector('.e-group-values'); var valueField: HTMLElement = pivotGridObj.pivotFieldListModule.axisTableModule.axisTable.querySelector('.e-field-list-values'); var pivotButtons: HTMLElement[] = [].slice.call(valueField.querySelectorAll('.e-pivot-button')); //expect(pivotButtons.length).toBeGreaterThan(0); keyModule.keyActionHandler({ action: 'enter', target: pivotButtons[0], preventDefault: (): void => { /** Null */ } }); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; expect(document.getElementById("FieldListcontextmenu")).toBeTruthy; }); it('select context Menu', (done: Function) => { let menuObj: any = (pivotGridObj.pivotFieldListModule.pivotButtonModule.menuOption as any).menuInfo[0]; let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>menuObj.element.querySelectorAll('li'); let menu: any = { element: li[6], item: menuObj.items[6] }; menuObj.select(menu as MenuEventArgs); var valueField: HTMLElement = pivotGridObj.pivotFieldListModule.axisTableModule.axisTable.querySelector('.e-field-list-values'); var pivotButtons: HTMLElement[] = [].slice.call(valueField.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); let buttonText: HTMLElement = ((pivotButtons[0]).querySelector('.e-content') as HTMLElement); expect(buttonText.innerHTML === 'Avg of balance').toBeTruthy(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { done(); }, 1000); }); it('close the fieldlist dialog', (done: Function) => { let fieldListWrapper = document.getElementById('PivotGrid_PivotFieldList_Container'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((fieldListWrapper.querySelector('.e-cancel-btn') as HTMLElement).click()).toBeTruthy; done(); }, 1000); }); it('check pivot grid aggregation', (done: Function) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = pivotGridObj.element.querySelector('td[aria-colindex="1"]'); expect(target.querySelector(".e-cellvalue").innerHTML).toEqual('$2,424.22'); done(); }, 1000); }); it('destroy aggregate menu', () => { let menuOption: any = pivotGridObj.pivotButtonModule.menuOption; menuOption.destroy(); expect((pivotGridObj.pivotButtonModule.menuOption as any).menuInfo[0]).toBeUndefined; expect((pivotGridObj.pivotButtonModule.menuOption as any).valueDialog).toBeUndefined; }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange); //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()); //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
namespace annie { /** * 矢量对象 * @class annie.Shape * @extends annie.Bitmap * @since 1.0.0 * @public */ export class Shape extends DisplayObject { public constructor() { super(); let s=this; s._instanceType = "annie.Shape"; } //一个数组,每个元素也是一个数组[类型 0是属性,1是方法,名字 执行的属性或方法名,参数] private _command: any = []; /** * 通过一系统参数获取生成颜色或渐变所需要的对象 * 一般给用户使用较少,Annie2x工具自动使用 * @method getGradientColor * @static * @param points * @param colors * @return {any} * @since 1.0.0 * @public */ public static getGradientColor(points: any, colors: any): any { let colorObj: any; let ctx = CanvasRender._ctx; if (points.length == 4) { colorObj = ctx.createLinearGradient(points[0], points[1], points[2], points[3]); } else { colorObj = ctx.createRadialGradient(points[0], points[1], 0, points[2], points[3], points[4]); } for (let i = 0, l = colors.length; i < l; i++) { colorObj.addColorStop(colors[i][0], Shape.getRGBA(colors[i][1], colors[i][2])); } return colorObj; } /** * 设置位图填充时需要使用的方法,一般给用户使用较少,Annie2x工具自动使用 * @method getBitmapStyle * @static * @param {Image} image HTML Image元素 * @return {CanvasPattern} * @public * @since 1.0.0 */ public static getBitmapStyle(image: any): any { let ctx = CanvasRender._ctx; return ctx.createPattern(image, "repeat"); } /** * 通过24位颜色值和一个透明度值生成RGBA值 * @method getRGBA * @static * @public * @since 1.0.0 * @param {string} color 字符串的颜色值,如:#33ffee * @param {number} alpha 0-1区间的一个数据 0完全透明 1完全不透明 * @return {string} */ public static getRGBA(color: string, alpha: number): string { if (color.indexOf("0x") == 0) { color = color.replace("0x", "#"); } if (color.length < 7) { color = "#000000"; } if (alpha != 1) { let r = parseInt("0x" + color.substr(1, 2)); let g = parseInt("0x" + color.substr(3, 2)); let b = parseInt("0x" + color.substr(5, 2)); color = "rgba(" + r + "," + g + "," + b + "," + alpha + ")"; } return color; } private _isBitmapStroke: Array<number>; private _isBitmapFill: Array<number>; /** * 添加一条绘画指令,具体可以查阅Html Canvas画图方法 * @method addDraw * @param {string} commandName ctx指令的方法名 如moveTo lineTo arcTo等 * @param {Array} params * @public * @since 1.0.0 * @return {void} */ public addDraw(commandName: string, params: Array<any>): void { let s = this; s._command[s._command.length] = [1, commandName, params]; } /** * 画一个带圆角的矩形 * @method drawRoundRect * @param {number} x 点x值 * @param {number} y 点y值 * @param {number} w 宽 * @param {number} h 高 * @param {number} rTL 左上圆角半径 * @param {number} rTR 右上圆角半径 * @param {number} rBL 左下圆角半径 * @param {number} rBR 右上圆角半径 * @public * @since 1.0.0 * @return {void} */ public drawRoundRect(x: number, y: number, w: number, h: number, rTL: number = 0, rTR: number = 0, rBL: number = 0, rBR: number = 0): void { let max = (w < h ? w : h) / 2; let mTL = 0, mTR = 0, mBR = 0, mBL = 0; if (rTL < 0) { rTL *= (mTL = -1); } if (rTL > max) { rTL = max; } if (rTR < 0) { rTR *= (mTR = -1); } if (rTR > max) { rTR = max; } if (rBR < 0) { rBR *= (mBR = -1); } if (rBR > max) { rBR = max; } if (rBL < 0) { rBL *= (mBL = -1); } if (rBL > max) { rBL = max; } let c = this._command; c[c.length] = [1, "moveTo", [x + w - rTR, y]]; c[c.length] = [1, "arcTo", [x + w + rTR * mTR, y - rTR * mTR, x + w, y + rTR, rTR]]; c[c.length] = [1, "lineTo", [x + w, y + h - rBR]]; c[c.length] = [1, "arcTo", [x + w + rBR * mBR, y + h + rBR * mBR, x + w - rBR, y + h, rBR]]; c[c.length] = [1, "lineTo", [x + rBL, y + h]]; c[c.length] = [1, "arcTo", [x - rBL * mBL, y + h + rBL * mBL, x, y + h - rBL, rBL]]; c[c.length] = [1, "lineTo", [x, y + rTL]]; c[c.length] = [1, "arcTo", [x - rTL * mTL, y - rTL * mTL, x + rTL, y, rTL]]; c[c.length] = [1, "closePath", []]; } /** * 绘画时移动到某一点 * @method moveTo * @param {number} x * @param {number} y * @public * @since 1.0.0 * @return {void} */ public moveTo(x: number, y: number): void { this._command[this._command.length] = [1, "moveTo", [x, y]]; } /** * 从上一点画到某一点,如果没有设置上一点,则上一点默认为(0,0) * @method lineTo * @param {number} x * @param {number} y * @public * @since 1.0.0 * @return {void} */ public lineTo(x: number, y: number): void { this._command[this._command.length] = [1, "lineTo", [x, y]]; } /** * 从上一点画弧到某一点,如果没有设置上一点,则上一点默认为(0,0) * @method arcTo * @param {number} x * @param {number} y * @public * @since 1.0.0 * @return {void} */ public arcTo(x: number, y: number): void { this._command[this._command.length] = [1, "arcTo", [x, y]]; } /** * 二次贝赛尔曲线 * 从上一点画二次贝赛尔曲线到某一点,如果没有设置上一点,则上一占默认为(0,0) * @method quadraticCurveTo * @param {number} cpX 控制点X * @param {number} cpX 控制点Y * @param {number} x 终点X * @param {number} y 终点Y * @public * @since 1.0.0 * @return {void} */ public quadraticCurveTo(cpX: number, cpY: number, x: number, y: number): void { this._command[this._command.length] = [1, "quadraticCurveTo", [cpX, cpY, x, y]]; } /** * 三次贝赛尔曲线 * 从上一点画二次贝赛尔曲线到某一点,如果没有设置上一点,则上一占默认为(0,0) * @method bezierCurveTo * @param {number} cp1X 1控制点X * @param {number} cp1Y 1控制点Y * @param {number} cp2X 2控制点X * @param {number} cp2Y 2控制点Y * @param {number} x 终点X * @param {number} y 终点Y * @public * @since 1.0.0 * @return {void} */ public bezierCurveTo(cp1X: number, cp1Y: number, cp2X: number, cp2Y: number, x: number, y: number): void { this._command[this._command.length] = [1, "bezierCurveTo", [cp1X, cp1Y, cp2X, cp2Y, x, y]]; } /** * 闭合一个绘画路径 * @method closePath * @public * @since 1.0.0 * @return {void} */ public closePath(): void { this._command[this._command.length] = [1, "closePath", []]; } /** * 画一个矩形 * @method drawRect * @param {number} x * @param {number} y * @param {number} w * @param {number} h * @public * @since 1.0.0 * @return {void} */ public drawRect(x: number, y: number, w: number, h: number): void { let c = this._command; c[c.length] = [1, "moveTo", [x, y]]; c[c.length] = [1, "lineTo", [x + w, y]]; c[c.length] = [1, "lineTo", [x + w, y + h]]; c[c.length] = [1, "lineTo", [x, y + h]]; c[c.length] = [1, "closePath", []]; } /** * 画一个弧形 * @method drawArc * @param {number} x 起始点x * @param {number} y 起始点y * @param {number} radius 半径 * @param {number} start 开始角度 * @param {number} end 结束角度 * @public * @since 1.0.0 * @return {void} */ public drawArc(x: number, y: number, radius: number, start: number, end: number): void { this._command[this._command.length] = [1, "arc", [x, y, radius, start / 180 * Math.PI, end / 180 * Math.PI]]; } /** * 画一个圆 * @method drawCircle * @param {number} x 圆心x * @param {number} y 圆心y * @param {number} radius 半径 * @public * @since 1.0.0 * @return {void} */ public drawCircle(x: number, y: number, radius: number): void { this._command[this._command.length] = [1, "arc", [x, y, radius, 0, 2 * Math.PI]]; } /** * 画一个椭圆 * @method drawEllipse * @param {number} x * @param {number} y * @param {number} w * @param {number} h * @public * @since 1.0.0 * @return {void} */ public drawEllipse(x: number, y: number, w: number, h: number): void { let k = 0.5522848; let ox = (w / 2) * k; let oy = (h / 2) * k; let xe = x + w; let ye = y + h; let xm = x + w / 2; let ym = y + h / 2; let c = this._command; c[c.length] = [1, "moveTo", [x, ym]]; c[c.length] = [1, "bezierCurveTo", [x, ym - oy, xm - ox, y, xm, y]]; c[c.length] = [1, "bezierCurveTo", [xm + ox, y, xe, ym - oy, xe, ym]]; c[c.length] = [1, "bezierCurveTo", [xe, ym + oy, xm + ox, ye, xm, ye]]; c[c.length] = [1, "bezierCurveTo", [xm - ox, ye, x, ym + oy, x, ym]]; } /** * 清除掉之前所有绘画的东西 * @method clear * @public * @since 1.0.0 * @return {void} */ public clear(): void { let s = this; s._command = []; s.a2x_ut = false; s.clearBounds(); } /** * 开始绘画填充,如果想画的东西有颜色填充,一定要从此方法开始 * @method beginFill * @param {string} color 颜色值 单色和RGBA格式 * @public * @since 1.0.0 * @return {void} */ public beginFill(color: string): void { this._fill(color); } /** * 线性渐变填充 一般给Annie2x用 * @method beginLinearGradientFill * @param {Array} points 一组点 * @param {Array} colors 一组颜色值 * @public * @since 1.0.0 * @return {void} * @example * var shape=new annie.Shape(); * shape.beginLinearGradientFill([0,0,200,0],[[0,"#ff0000",1],[0.164706,"#ffff00",1],[0.364706,"#00ff00",1],[0.498039,"#00ffff",1],[0.666667,"#0000ff",1],[0.831373,"#ff00ff",1],[1,"#ff0000",1]]); * shape.drawRect(0,0,200,200); * shape.endFill(); * s.addChild(shape); */ public beginLinearGradientFill(points: any, colors: any): void { this._fill(Shape.getGradientColor(points, colors)); } /** * 径向渐变填充 一般给Annie2x用 * @method beginRadialGradientFill * @param {Array} points 一组点 * @param {Array} colors 一组颜色值 * @param {Object} matrixDate 如果渐变填充有矩阵变形信息 * @public * @since 1.0.0 * @return {void} * @example * var shape=new annie.Shape(); * shape.beginRadialGradientFill([100,100,100,100,100],[[0,"#00ff00",1],[1,"#000000",1]]); * shape.drawRect(0,0,200,200); * shape.endFill(); * s.addChild(shape); */ public beginRadialGradientFill = function (points: any, colors: any): void { this._fill(Shape.getGradientColor(points, colors)); }; /** * 位图填充 一般给Annie2x用 * @method beginBitmapFill * @param {Image} image * @param { Array} matrix * @public * @since 1.0.0 * @return {void} */ public beginBitmapFill(image: any, matrix: Array<number>): void { let s = this; if (matrix) { s._isBitmapFill = matrix; } s._fill(Shape.getBitmapStyle(image)); } private _fill(fillStyle: any): void { let s = this; let c = s._command; c[c.length] = [0, "fillStyle", fillStyle]; c[c.length] = [1, "beginPath", []]; } /** * 给线条着色 * @method beginStroke * @param {string} color 颜色值 * @param {number} lineWidth 宽度 * @param {number} cap 线头的形状 0 butt 1 round 2 square 默认 butt * @param {number} join 线与线之间的交接处形状 0 miter 1 bevel 2 round 默认miter * @param {number} miter 正数,规定最大斜接长度,如果斜接长度超过 miterLimit 的值,边角会以 lineJoin 的 "bevel" 类型来显示 默认10 * @public * @since 1.0.0 * @return {void} */ public beginStroke(color: string, lineWidth: number = 1, cap: number = 0, join: number = 0, miter: number = 0): void { this._stroke(color, lineWidth, cap, join, miter); } private static _caps: Array<string> = ["butt", "round", "square"]; private static _joins: Array<string> = ["miter", "round", "bevel"]; /** * 画线性渐变的线条 一般给Annie2x用 * @method beginLinearGradientStroke * @param {Array} points 一组点 * @param {Array} colors 一组颜色值 * @param {number} lineWidth * @param {number} cap 线头的形状 0 butt 1 round 2 square 默认 butt * @param {number} join 线与线之间的交接处形状 0 miter 1 bevel 2 round 默认miter * @param {number} miter 正数,规定最大斜接长度,如果斜接长度超过 miterLimit 的值,边角会以 lineJoin 的 "bevel" 类型来显示 默认10 * @public * @since 1.0.0 * @return {void} */ public beginLinearGradientStroke(points: Array<number>, colors: any, lineWidth: number = 1, cap: number = 0, join: number = 0, miter: number = 10): void { this._stroke(Shape.getGradientColor(points, colors), lineWidth, cap, join, miter); } /** * 画径向渐变的线条 一般给Annie2x用 * @method beginRadialGradientStroke * @param {Array} points 一组点 * @param {Array} colors 一组颜色值 * @param {number} lineWidth * @param {string} cap 线头的形状 butt round square 默认 butt * @param {string} join 线与线之间的交接处形状 bevel round miter 默认miter * @param {number} miter 正数,规定最大斜接长度,如果斜接长度超过 miterLimit 的值,边角会以 lineJoin 的 "bevel" 类型来显示 默认10 * @public * @since 1.0.0 * @return {void} */ public beginRadialGradientStroke = function (points: Array<number>, colors: any, lineWidth: number = 1, cap: number = 0, join: number = 0, miter: number = 10) { this._stroke(Shape.getGradientColor(points, colors), lineWidth, cap, join, miter); }; /** * 线条位图填充 一般给Annie2x用 * @method beginBitmapStroke * @param {Image} image * @param {Array} matrix * @param {number} lineWidth * @param {string} cap 线头的形状 butt round square 默认 butt * @param {string} join 线与线之间的交接处形状 bevel round miter 默认miter * @param {number} miter 正数,规定最大斜接长度,如果斜接长度超过 miterLimit 的值,边角会以 lineJoin 的 "bevel" 类型来显示 默认10 * @public * @since 1.0.0 * @return {void} */ public beginBitmapStroke(image: any, matrix: Array<number>, lineWidth: number = 1, cap: number = 0, join: number = 0, miter: number = 10): void { let s = this; if (matrix) { s._isBitmapStroke = matrix; } s._stroke(Shape.getBitmapStyle(image), lineWidth, cap, join, miter); } private _stroke(strokeStyle: any, width: number, cap: number, join: number, miter: number): void { let c = this._command; c[c.length] = [0, "lineWidth", width]; c[c.length] = [0, "lineCap", Shape._caps[cap]]; c[c.length] = [0, "lineJoin", Shape._joins[join]]; c[c.length] = [0, "miterLimit", miter]; c[c.length] = [0, "strokeStyle", strokeStyle]; c[c.length] = [1, "beginPath", []]; } /** * 结束填充 * @method endFill * @public * @since 1.0.0 * @return {void} */ public endFill(): void { let s = this; let c = s._command; let m = s._isBitmapFill; if (m) { c[c.length] = [2, "setTransform", m]; } c[c.length] = ([1, "fill", []]); if (m) { s._isBitmapFill = null; } s.a2x_ut = true; } /** * 设置虚线参数 * @method setLineDash * @param {Array} data 一个长度为2的数组,第1个是虚线长度,第2个是虚线间隔,如果此参数为[]的空数组,则是清除虚线。 * 如[5,20]是画虚线,[]则是请除虚线,变为实线 * @since 2.0.2 * @return {void} */ public setLineDash(data: Array<number> = []): void { let c = this._command; c[c.length] = [1, "setLineDash", [data, 0]]; } /** * 结束画线 * @method endStroke * @public * @since 1.0.0 * @return {void} */ public endStroke(): void { let s = this; let c = s._command; let m = s._isBitmapStroke; if (m) { //如果为2则还需要特别处理 c[c.length] = [2, "setTransform", m]; } c[c.length] = ([1, "stroke", []]); if (m) { s._isBitmapStroke = null; } s.a2x_ut = true; } /** * 解析一段路径 一般给Annie2x用 * @method decodePath * @param {Array} data * @public * @since 1.0.0 * @return {void} */ public decodePath(data: Array<number>): void { let s = this; let instructions = ["moveTo", "lineTo", "quadraticCurveTo", "bezierCurveTo", "closePath"]; let count = data.length; for (let i = 0; i < count; i++) { if (data[i] == 0 || data[i] == 1) { s.addDraw(instructions[data[i]], [data[i + 1], data[i + 2]]); i += 2; } else { s.addDraw(instructions[data[i]], [data[i + 1], data[i + 2], data[i + 3], data[i + 4]]); i += 4; } } s.a2x_ut = true; }; //是否矢量元素有更新 private a2x_ut: boolean = true; protected _updateMatrix(): void { super._updateMatrix(); let s: any = this; if (s.a2x_ut){ s.a2x_ut = false; //更新矢量 let cLen: number = s._command.length; let leftX: number; let leftY: number; let buttonRightX: number; let buttonRightY: number; let i: number; if (cLen > 0) { //确定是否有数据,如果有数据的话就计算出缓存图的宽和高 let data: any; let lastX = 0; let lastY = 0; let lineWidth = 0; for (i = 0; i < cLen; i++) { data = s._command[i]; if (data[0] == 1) { if (data[1] == "moveTo" || data[1] == "lineTo" || data[1] == "arcTo" || data[1] == "bezierCurveTo") { if (leftX == undefined) { leftX = data[2][0]; } if (leftY == undefined) { leftY = data[2][1]; } if (buttonRightX == undefined) { buttonRightX = data[2][0]; } if (buttonRightY == undefined) { buttonRightY = data[2][1]; } if (data[1] == "bezierCurveTo") { leftX = Math.min(leftX, data[2][0], data[2][2], data[2][4]); leftY = Math.min(leftY, data[2][1], data[2][3], data[2][5]); buttonRightX = Math.max(buttonRightX, data[2][0], data[2][2], data[2][4]); buttonRightY = Math.max(buttonRightY, data[2][1], data[2][3], data[2][5]); lastX = data[2][4]; lastY = data[2][5]; } else { leftX = Math.min(leftX, data[2][0]); leftY = Math.min(leftY, data[2][1]); buttonRightX = Math.max(buttonRightX, data[2][0]); buttonRightY = Math.max(buttonRightY, data[2][1]); lastX = data[2][0]; lastY = data[2][1]; } } else if (data[1] == "quadraticCurveTo") { //求中点 let mid1X = (lastX + data[2][0]) * 0.5; let mid1Y = (lastY + data[2][1]) * 0.5; let mid2X = (data[2][0] + data[2][2]) * 0.5; let mid2Y = (data[2][1] + data[2][3]) * 0.5; if (leftX == undefined) { leftX = mid1X; } if (leftY == undefined) { leftY = mid1Y; } if (buttonRightX == undefined) { buttonRightX = mid1X; } if (buttonRightY == undefined) { buttonRightY = mid1Y; } leftX = Math.min(leftX, mid1X, mid2X, data[2][2]); leftY = Math.min(leftY, mid1Y, mid2Y, data[2][3]); buttonRightX = Math.max(buttonRightX, mid1X, mid2X, data[2][2]); buttonRightY = Math.max(buttonRightY, mid1Y, mid2Y, data[2][3]); lastX = data[2][2]; lastY = data[2][3]; } else if (data[1] == "arc") { let yuanPointX = data[2][0]; let yuanPointY = data[2][1]; let radio = data[2][2]; let yuanLeftX = yuanPointX - radio; let yuanLeftY = yuanPointY - radio; let yuanBRX = yuanPointX + radio; let yuanBRY = yuanPointY + radio; if (leftX == undefined) { leftX = yuanLeftX; } if (leftY == undefined) { leftY = yuanLeftY; } if (buttonRightX == undefined) { buttonRightX = yuanBRX; } if (buttonRightY == undefined) { buttonRightY = yuanBRY; } leftX = Math.min(leftX, yuanLeftX); leftY = Math.min(leftY, yuanLeftY); buttonRightX = Math.max(buttonRightX, yuanBRX); buttonRightY = Math.max(buttonRightY, yuanBRY); } } else { if (data[1] == "lineWidth") { if (lineWidth < data[2]) { lineWidth = data[2]; } } } } if (leftX != undefined || lineWidth > 0) { if (leftX == undefined) { leftX = 0; leftY = 0; } leftX -=lineWidth; leftY -=lineWidth; buttonRightX += lineWidth; buttonRightY += lineWidth; let width = buttonRightX - leftX; let height = buttonRightY - leftY; // s._offsetX = leftX; // s._offsetY = leftY; s._bounds.x = leftX; s._bounds.y = leftY; s._bounds.width = width; s._bounds.height = height; s.a2x_um=true; } } } if(s.a2x_um){ s._checkDrawBounds(); } s.a2x_um = false; s.a2x_ua = false; } public _draw(ctx: any, isMask: boolean = false): void { let s = this; let com = s._command; let cLen = com.length; let data: any; ctx.translate(s._offsetX, s._offsetY); let isStroke = false; for (let i = 0; i < cLen; i++) { data = com[i]; if (data[0] > 0) { let paramsLen = data[2].length; if (isMask && (isStroke || data[1] == "beginPath" || data[1] == "closePath" || paramsLen == 0)) continue; if (paramsLen == 0) { ctx[data[1]](); } else if (paramsLen == 2) { ctx[data[1]](data[2][0], data[2][1]); } else if (paramsLen == 4) { ctx[data[1]](data[2][0], data[2][1], data[2][2], data[2][3]); } else if (paramsLen == 5) { ctx[data[1]](data[2][0], data[2][1], data[2][2], data[2][3], data[2][4]); } else if (paramsLen == 6) { let lx = data[2][4]; let ly = data[2][5]; /* if (data[0] == 2) { //位图填充 lx -= leftX; ly -= leftY; }*/ ctx[data[1]](data[2][0], data[2][1], data[2][2], data[2][3], lx, ly); } } else { if (isMask) { if (data[1] == "strokeStyle") { isStroke = true; } else if (data[1] == "fillStyle") { isStroke = false; } } else { ctx[data[1]] = data[2]; } } } } /** * 如果有的话,改变矢量对象的边框或者填充的颜色. * @method changeColor * @param {Object} infoObj * @param {string|any} infoObj.fillColor 填充颜色值,如"#fff" 或者 "rgba(255,255,255,1)"或者是annie.Shape.getGradientColor()方法返回的渐变对象; * @param {string} infoObj.strokeColor 线条颜色值,如"#fff" 或者 "rgba(255,255,255,1)"; * @param {number} infoObj.lineWidth 线条的粗细,如"1,2,3..."; * @public * @since 1.0.2 * @return {void} */ public changeColor(infoObj: any): void { let s = this; let cLen: number = s._command.length; let c = s._command; for (let i = 0; i < cLen; i++) { if (c[i][0] == 0) { if (c[i][1] == "fillStyle" && infoObj.fillColor && c[i][2] != infoObj.fillColor) { c[i][2] = infoObj.fillColor; s.a2x_ut = true; } if (c[i][1] == "strokeStyle" && infoObj.strokeColor && c[i][2] != infoObj.strokeColor) { c[i][2] = infoObj.strokeColor; s.a2x_ut = true; } if (c[i][1] == "lineWidth" && infoObj.lineWidth && c[i][2] != infoObj.lineWidth) { c[i][2] = infoObj.lineWidth; s.a2x_ut = true; } } } } public destroy(): void { //清除相应的数据引用 let s = this; s._command = null; s._isBitmapStroke = null; s._isBitmapFill = null; super.destroy(); } } }
the_stack
import { expect } from "chai"; import { concat, EMPTY, Observable, of, SchedulerLike, Subject, timer, } from "rxjs"; import { marbles } from "rxjs-marbles"; import { delay, ignoreElements, map } from "rxjs/operators"; import { traverse } from "./traverse"; // prettier-ignore describe("traverse", () => { describe("lists", () => { const createFactory = ( max: number = Infinity, count?: number, time?: number, scheduler?: SchedulerLike ) => ( marker: number | undefined ): Observable<{ markers: number[]; values: string[] }> => { const at = marker === undefined ? 0 : marker + 1; const markers = [at]; const values: string[] = []; for (let c = 0; c < (count || 1); ++c) { values.push((at + c).toString()); } const source = at <= max ? of({ markers, values }) : EMPTY; return time !== undefined && scheduler !== undefined ? source.pipe(delay(time, scheduler)) : source; }; it( "should complete if there is no data", marbles(m => { const notifier = m.hot(" --n----|"); const notifierSubs = " ^-! "; const expected = m.cold(" --| "); const factory = createFactory(-1, 1, m.time("--|"), m.scheduler); const traversed = traverse({ factory, notifier }); m.expect(traversed).toBeObservable(expected); m.expect(notifier).toHaveSubscriptions(notifierSubs); }) ); it( "should traverse the first chunk of data", marbles(m => { const notifier = m.hot(" n-"); const expected = m.cold(" 0-"); const factory = createFactory(); const traversed = traverse({ factory, notifier }); m.expect(traversed).toBeObservable(expected); }) ); it( "should traverse further chunks in response to the notifier", marbles(m => { const notifier = m.hot(" n-n----n--n--"); const expected = m.cold(" 0-1----2--3--"); const factory = createFactory(); const traversed = traverse({ factory, notifier }); m.expect(traversed).toBeObservable(expected); }) ); it( "should flatten values within chunks", marbles(m => { const notifier = m.hot(" n----n-------n-----n-----"); const expected = m.cold(" (01)-(12)----(23)--(34)--"); const factory = createFactory(Infinity, 2); const traversed = traverse({ factory, notifier }); m.expect(traversed).toBeObservable(expected); }) ); it( "should queue notifications", marbles(m => { const notifier = m.hot(" nnn------------"); const expected = m.cold(" ----0---1---2--"); const factory = createFactory( Infinity, 1, m.time("----|"), m.scheduler ); const traversed = traverse({ factory, notifier }); m.expect(traversed).toBeObservable(expected); }) ); it( "should traverse without a notifier", marbles(m => { const expected = m.cold("----0---1---(2|)"); const factory = createFactory(2, 1, m.time("----|"), m.scheduler); const traversed = traverse({ factory }); m.expect(traversed).toBeObservable(expected); }) ); it( "should traverse with an operator", marbles(m => { const other = m.cold(" |"); const subs = [ " ----(^!)---------", " --------(^!)-----", " ------------(^!)-" ]; const expected = m.cold(" ----0---1---(2|) "); const factory = createFactory(2, 1, m.time("----|"), m.scheduler); const traversed = traverse({ factory, operator: source => concat(source, other) }); m.expect(traversed).toBeObservable(expected); m.expect(other).toHaveSubscriptions(subs); }) ); it( "should traverse with an asynchonous operator", marbles(m => { const other = m.cold(" ----|"); const subs = [ " ^---!-------", " ----^---!---", " --------^---!" ]; const expected = m.cold(" 0---1---2---|"); const factory = createFactory(2); const traversed = traverse({ factory, operator: source => concat(source, other) }); m.expect(traversed).toBeObservable(expected); m.expect(other).toHaveSubscriptions(subs); }) ); it( "should serialize production", marbles(m => { const values = { w: { markers: ["x", "y", "z"], values: [] }, x: { markers: [], values: ["a", "b"] }, y: { markers: [], values: ["c", "d"] }, z: { markers: [], values: ["e", "f"] } }; const w = m.cold(" -----(w|)", values); const x = m.cold(" -----(x|)", values); const y = m.cold(" -----(y|)", values); const z = m.cold(" -----(z|)", values); const expected = m.cold(" ----------(ab)-(cd)-(ef|)"); const wSubs = " ^----!-------------------"; const xSubs = " -----^----!--------------"; const ySubs = " ----------^----!---------"; const zSubs = " ---------------^----!----"; const factory = (marker: string | undefined, index: number) => { switch (marker) { case undefined: return w; case "x": return x; case "y": return y; case "z": return z; default: return EMPTY; } }; const traversed = traverse({ factory }); m.expect(traversed).toBeObservable(expected); m.expect(w).toHaveSubscriptions(wSubs); m.expect(x).toHaveSubscriptions(xSubs); m.expect(y).toHaveSubscriptions(ySubs); m.expect(z).toHaveSubscriptions(zSubs); }) ); }); describe("graphs", () => { const createFactory = (time?: number, scheduler?: SchedulerLike) => ( marker: any ): Observable<{ markers: any[]; values: string[] }> => { const data = { a: { d: {}, e: {} }, b: { f: {} }, c: {} }; const node = marker ? marker : data; const element: any = { markers: [], values: [] }; Object.keys(node).forEach(key => { if (Object.keys(node[key]).length) { element.markers.push(node[key]); } element.values.push(key); }); return time && scheduler ? concat( timer(time, scheduler).pipe(ignoreElements()) as Observable<never>, of(element) ) : of(element); }; it( "should traverse graphs with a notifier", marbles(m => { const notifier = m.hot(" n-----n-----n---"); const expected = m.cold(" (abc)-(de)--(f|)"); const factory = createFactory(); const traversed = traverse({ factory, notifier }); m.expect(traversed).toBeObservable(expected); }) ); it( "should queue notifications for graphs", marbles(m => { const notifier = m.hot(" nnn-------------------"); const expected = m.cold(" ------(abc)-(de)--(f|)"); const factory = createFactory(m.time("------|"), m.scheduler); const traversed = traverse({ factory, notifier }); m.expect(traversed).toBeObservable(expected); }) ); it( "should traverse graphs without a notifier", marbles(m => { const expected = m.cold("------(abc)-(de)--(f|)"); const factory = createFactory(m.time("------|"), m.scheduler); const traversed = traverse({ factory }); m.expect(traversed).toBeObservable(expected); }) ); it( "should support concurrency", marbles(m => { const expected = m.cold("------(abc)-(def|)"); const factory = createFactory(m.time("------|"), m.scheduler); const traversed = traverse({ factory, concurrency: Infinity }); m.expect(traversed).toBeObservable(expected); }) ); }); describe("GitHub usage example", () => { function get( url: string ): Observable<{ content: { html_url: string }[]; next: string | null; }> { // The next URL would be obtained from the Link header. // https://blog.angularindepth.com/rxjs-understanding-expand-a5f8b41a3602 switch (url) { case "https://api.github.com/users/cartant/repos": return of({ content: [ { html_url: "https://github.com/cartant/rxjs-etc" }, { html_url: "https://github.com/cartant/rxjs-marbles" } ], next: "https://api.github.com/users/cartant/repos?page=2" }); case "https://api.github.com/users/cartant/repos?page=2": return of({ content: [ { html_url: "https://github.com/cartant/rxjs-spy" }, { html_url: "https://github.com/cartant/rxjs-tslint-rules" } ], next: null }); default: throw new Error("Unexpected URL."); } } describe("with notifier", () => { it("should traverse the pages", (callback: any) => { const notifier = new Subject<void>(); const urls = traverse({ factory: (marker?: string) => get(marker || "https://api.github.com/users/cartant/repos").pipe( map(response => ({ markers: response.next ? [response.next] : [], values: response.content })) ), notifier }).pipe(map(repo => repo.html_url)); const received: string[] = []; urls.subscribe(url => received.push(url), callback, () => { expect(received).to.deep.equal([ "https://github.com/cartant/rxjs-etc", "https://github.com/cartant/rxjs-marbles", "https://github.com/cartant/rxjs-spy", "https://github.com/cartant/rxjs-tslint-rules" ]); callback(); }); notifier.next(); notifier.next(); }); }); describe("with an operator", () => { it("should traverse the pages", (callback: any) => { const urls = traverse({ factory: (marker?: string) => get(marker || "https://api.github.com/users/cartant/repos").pipe( map(response => ({ markers: response.next ? [response.next] : [], values: response.content })) ), operator: repos => repos.pipe(map(repo => repo.html_url)) }); const received: string[] = []; urls.subscribe(url => received.push(url), callback, () => { expect(received).to.deep.equal([ "https://github.com/cartant/rxjs-etc", "https://github.com/cartant/rxjs-marbles", "https://github.com/cartant/rxjs-spy", "https://github.com/cartant/rxjs-tslint-rules" ]); callback(); }); }); }); }); });
the_stack
module CorsicaTests { "use strict"; export class BaseEvents { testEventsMixin() { var TC = WinJS.Class.define(); WinJS.Class.mix(TC, WinJS.Utilities.eventMixin); var hitCount = 0; var tc = new TC(); var f = function (e) { hitCount++; LiveUnit.Assert.areEqual(tc, e.target); LiveUnit.Assert.areEqual("my detail", e.detail); }; tc.addEventListener("myevent", f); var f2 = function (e) { hitCount++; LiveUnit.Assert.areEqual(tc, e.target); LiveUnit.Assert.areEqual("my detail", e.detail); }; tc.addEventListener("myevent", f2); LiveUnit.Assert.areEqual(0, hitCount); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(2, hitCount); } testEventsMixinRemoveWithMultipleEvents() { var TC = WinJS.Class.define(); WinJS.Class.mix(TC, WinJS.Utilities.eventMixin); var tc = new TC(); var handler = function handler() { tc.removeEventListener("myevent", handler, false); }; tc.addEventListener("myevent", handler, false); tc.addEventListener("myevent", handler, false); tc.dispatchEvent("myevent"); } testEventsMixin_removeEvent() { var TC = WinJS.Class.define(); WinJS.Class.mix(TC, WinJS.Utilities.eventMixin); var hitCount = 0; var tc = new TC(); var f = function (e) { hitCount++; LiveUnit.Assert.areEqual(tc, e.target); LiveUnit.Assert.areEqual("my detail", e.detail); }; tc.addEventListener("myevent", f); var f2 = function (e) { hitCount++; LiveUnit.Assert.areEqual(tc, e.target); LiveUnit.Assert.areEqual("my detail", e.detail); }; tc.addEventListener("myevent", f2); LiveUnit.Assert.areEqual(0, hitCount); var result = tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(false, result); LiveUnit.Assert.areEqual(2, hitCount); tc.removeEventListener("myevent", f2); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(3, hitCount); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(4, hitCount); tc.removeEventListener("myevent", f); LiveUnit.Assert.areEqual(4, hitCount); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(4, hitCount); // Remove the event one extra time, should not fail. tc.removeEventListener("myevent", f); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(4, hitCount); // Add twice should only result in one registration tc.addEventListener("myevent", f); tc.addEventListener("myevent", f); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(5, hitCount); // Remove should remove the handler even though it was registered twice. tc.removeEventListener("myevent", f); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(5, hitCount); } testEventsMixin_cancelEvent() { var TC = WinJS.Class.define(); WinJS.Class.mix(TC, WinJS.Utilities.eventMixin); var hitCount = 0; var tc = new TC(); var f = function (e) { hitCount++; LiveUnit.Assert.areEqual(tc, e.target); LiveUnit.Assert.areEqual("my detail", e.detail); e.preventDefault(); }; tc.addEventListener("myevent", f); var f2 = function (e) { hitCount++; LiveUnit.Assert.areEqual(tc, e.target); LiveUnit.Assert.areEqual("my detail", e.detail); }; tc.addEventListener("myevent", f2); LiveUnit.Assert.areEqual(0, hitCount); var result = tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(true, result); LiveUnit.Assert.areEqual(2, hitCount); } testEventsMixin_stopPropagation() { var TC = WinJS.Class.define(); WinJS.Class.mix(TC, WinJS.Utilities.eventMixin); var hitCount = 0; var tc = new TC(); var f = function (e) { hitCount++; LiveUnit.Assert.areEqual(tc, e.target); LiveUnit.Assert.areEqual("my detail", e.detail); e.stopImmediatePropagation(); }; tc.addEventListener("myevent", f); var f2 = function (e) { hitCount++; LiveUnit.Assert.areEqual(tc, e.target); LiveUnit.Assert.areEqual("my detail", e.detail); }; tc.addEventListener("myevent", f2); LiveUnit.Assert.areEqual(0, hitCount); var result = tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(false, result); LiveUnit.Assert.areEqual(1, hitCount); } testCreatingEventPropertiesWithEventMixins() { var testRunCount = 0; var test = function (tc, expectedEventTarget) { var hitCount = 0; var onmyeventHandler1 = function (e) { hitCount++; LiveUnit.Assert.areEqual(expectedEventTarget, e.target); LiveUnit.Assert.areEqual("my detail", e.detail); }; tc.onmyevent = onmyeventHandler1; tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(1, hitCount); LiveUnit.Assert.isTrue(onmyeventHandler1 === tc.onmyevent); // Attempt to explicitly remove this event listener, this should fail. tc.removeEventListener("myevent", onmyeventHandler1, false); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(2, hitCount); // Add the same listener again imperatively tc.addEventListener("myevent", onmyeventHandler1, false); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(4, hitCount); // Attempt to explicitly remove this event listener, this should only remove one. tc.removeEventListener("myevent", onmyeventHandler1, false); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(5, hitCount); testRunCount++; }; (function () { var TestClassWithEventMixin = WinJS.Class.define(); WinJS.Class.mix(TestClassWithEventMixin, WinJS.Utilities.eventMixin, WinJS.Utilities.createEventProperties("myevent", "myotherevent") ); var tcwem = new TestClassWithEventMixin(); test(tcwem, tcwem); })(); LiveUnit.Assert.areEqual(1, testRunCount); } testCreatingEventPropertiesPreserveDOMOrdering() { function sequenceEquals(l, r) { if (l.length === r.length) { for (var i = 0, len = l.length; i < len; i++) { if (l[i] !== r[i]) { return false; } } return true; } else { return false; } } var testRunCount = 0; var test = function (tc, tc2) { var hitCount = 0; var results = []; var results2 = []; tc.onmyevent = function () { results.push("one"); }; tc2.onmyevent = function () { results2.push("one"); }; tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(1, results.length); LiveUnit.Assert.isTrue(sequenceEquals(["one"], results)); LiveUnit.Assert.areEqual(0, results2.length); tc2.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(1, results.length); LiveUnit.Assert.isTrue(sequenceEquals(["one"], results)); LiveUnit.Assert.areEqual(1, results2.length); LiveUnit.Assert.isTrue(sequenceEquals(["one"], results2)); // After adding another event listener "one" should still be dispatched first results = []; tc.addEventListener("myevent", function () { results.push("two"); }); tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(2, results.length); LiveUnit.Assert.isTrue(sequenceEquals(["one", "two"], results)); // After replacing the event listener property value the new property value // should be dispatched first. results = []; tc.onmyevent = function () { results.push("three"); }; tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(2, results.length); LiveUnit.Assert.isTrue(sequenceEquals(["three", "two"], results)); // After setting the event listener property value to null we should // only see the explicitly registered listener getting called. results = []; tc.onmyevent = null; tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(1, results.length); LiveUnit.Assert.isTrue(sequenceEquals(["two"], results)); // After adding a new event listener property value we see that it is // dispatched at the end because the nulling out of the property removed // the slot reservation. results = []; tc.onmyevent = function () { results.push("four"); }; tc.dispatchEvent("myevent", "my detail"); LiveUnit.Assert.areEqual(2, results.length); LiveUnit.Assert.isTrue(sequenceEquals(["two", "four"], results)); testRunCount++; }; // Put this in its own function to ensure we don't accidentially capture above. // (function () { var TestClassWithEventMixin = WinJS.Class.define(); WinJS.Class.mix(TestClassWithEventMixin, WinJS.Utilities.eventMixin, WinJS.Utilities.createEventProperties("myevent", "myotherevent") ); test(new TestClassWithEventMixin(), new TestClassWithEventMixin()); })(); LiveUnit.Assert.areEqual(1, testRunCount); } } } LiveUnit.registerTestClass("CorsicaTests.BaseEvents");
the_stack
import { toQueryString } from "../../utils"; import { SdkClient } from "../common/sdk-client"; import { TrendPredictionModels } from "./trend-prediction-models"; /** * Predicts future values for time series using linear and nonlinear regression models. * Models can be of univariable input, e.g. f(x) or f(t), or of multivariable input, * e.g. f(t, x1, x2, …). * * @export * @class TrendPredictionClient * @extends {SdkClient} */ export class TrendPredictionClient extends SdkClient { private _baseUrl = "/api/trendprediction/v3"; /** * Fits a regression model on the training dataset, storing the trained regression model in a database. * * @param {TrendPredictionModels.TrainBody} modelData * * Data structure with three parts - modelConfiguration, metadataConfiguration, and trainingData. * * * modelConfiguration * contains the information necessary for configuring the regression model to be trained (e.g., the degree of a polynomial in case of polynomial regression). * * * metadataConfiguration * specifies which variables are the input variables (regressors), and which one is the output variable (regressand) of the regression model. * In order to specify time as one of the input variables, set propertyName equal to timestamp * * * trainingData * contains the time series data that will be used for model training the regression model. * It should contain the values for all variables specified under metadataConfiguration. * * * @returns {Promise<TrendPredictionModels.ModelDto>} * * @memberOf TrendPredictionClient */ public async Train(modelData: TrendPredictionModels.TrainBody): Promise<TrendPredictionModels.ModelDto> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/train`, body: modelData, }); return result as TrendPredictionModels.ModelDto; } /** * Fits a regression model on the training dataset, storing the trained regression model in a database. * * @param {TrendPredictionModels.TrainBodyDirect} modelData * @param {{ * from: Date; * to: Date; * }} params * @param params.from Beginning of the time range to be retrieved (exclusive) * @param params.to End of the time range to be retrieved (exclusive) * * * Data structure with two parts - modelConfiguration, metadataConfiguration. * * * modelConfiguration * contains the information necessary for configuring the regression model to * be trained (e.g., the degree of a polynomial in case of polynomial regression). * * * metadataConfiguration * specifies which variables are the input variables (regressors), and which one is the output variable * (regressand) of the regression model. In order to specify time as one of the input variables, * set propertyName equal to timestamp. * * @returns {Promise<TrendPredictionModels.ModelDtoDirect>} * * @memberOf TrendPredictionClient */ public async TrainDirect( modelData: TrendPredictionModels.TrainBodyDirect, params: { from: Date; to: Date; } ): Promise<TrendPredictionModels.ModelDtoDirect> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/trainDirect?${toQueryString(params)}`, body: modelData, }); return result as TrendPredictionModels.ModelDtoDirect; } /** * Predicts future values of a given output variable using a pre-trained regression model. * * @param {TrendPredictionModels.PredictBody} modelData * * * Data structure with two parts - modelConfiguration and predictionData. * * * modelConfiguration * contains the information necessary to identify the pre-trained regression model (i.e., modelId). * * predictionData * contains the values of the input variables used by the pre-trained regression model. Note that it is necessary to include the values * for all of the input variables specified under metadataConfiguration at the training step. * The example below assumes the two input variables that were used to train the regression model are * * @example * [entityId: turbine1, propertySet: combustionSubpart1, property: pressure], * [entityId: turbine1, propertySet: combustionSubpart1, property: temperature]. * @returns {Promise<TrendPredictionModels.PredictionDataArray>} * * @memberOf TrendPredictionClient */ public async Predict( modelData: TrendPredictionModels.PredictBody ): Promise<TrendPredictionModels.PredictionDataArray> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/predict`, body: modelData, }); return result as TrendPredictionModels.PredictionDataArray; } /** * Predicts future values of a given output variable using a pre-trained regression model. * * @param {TrendPredictionModels.PredictBodyDirect} modelData * @param {{ * from: Date; * to: Date; * }} params * @param params.from Beginning of the time range to be retrieved (exclusive) * @param params.to End of the time range to be retrieved (exclusive) * * * Data structure with two parts - modelConfiguration and predictionData. * * * modelConfiguration * contains the information necessary to identify the pre-trained regression model (i.e., modelId). * * * predictionData * contains the values of the input variables used by the pre-trained regression model. * Note that it is necessary to include the values for all of the input variables specified under * metadataConfiguration at the training step. * * @example below assumes the two input variables that were used to train the regression model are * [assetId: turbine1, aspectName: combustionSubpart1, variableName: pressure], * [assetId: turbine1, aspectName: combustionSubpart1, variableName: temperature]. * * @returns {Promise<TrendPredictionModels.PredictionDataArrayDirect>} * * @memberOf TrendPredictionClient */ public async PredictDirect( modelData: TrendPredictionModels.PredictBodyDirect, params: { from: Date; to: Date; } ): Promise<TrendPredictionModels.PredictionDataArrayDirect> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/predictDirect?${toQueryString(params)}`, body: modelData, }); return result as TrendPredictionModels.PredictionDataArrayDirect; } /** * Fits a regression model on the training dataset and predicts future values of a given output variable using the trained regression model * * @param {TrendPredictionModels.TrainPredictBody} modelData * * * Data structure with four parts - modelConfiguration, metadataConfiguration, trainingData, and predictionData. * * * modelConfiguration * contains the information necessary for configuring the regression model to be trained (e.g., the degree of a polynomial in case of polynomial regression) * *metadataConfiguration * specifies which variables are the input variables (regressors), and which one is the output variable (regressand) of the regression model. * In order to specify time as one of the input variables, set propertyName equal to timestamp. * * trainingData * contains the time series data that will be used for model training the regression model. * It should contain the values for all variables specified under metadataConfiguration. * *predictionData * contains the values of the input variables used by the pre-trained regression model. * Note that it is necessary to include the values for all of the input variables specified under metadataConfiguration at the training step. * * @returns {Promise<TrendPredictionModels.PredictionDataArray>} * * @memberOf TrendPredictionClient */ public async TrainAndPredict( modelData: TrendPredictionModels.TrainPredictBody ): Promise<TrendPredictionModels.PredictionDataArray> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/trainAndPredict`, body: modelData, }); return result as TrendPredictionModels.PredictionDataArray; } /** * Fits a regression model on the training dataset and predicts future values of a * given output variable using the trained regression model. * * @param {TrendPredictionModels.TrainPredictBodyDirect} modelData * @param {{ * trainFrom: Date; * trainTo: Date; * predictFrom: Date; * predictTo: Date; * }} params * @param params.trainFrom Beginning of the time range to be retrieved (exclusive) * @param params.trainTo End of the time range to be retrieved (exclusive) * @param params.predictFrom Beginning of the time range to be retrieved (exclusive) * @param params.predictTo End of the time range to be retrieved (exclusive) * * * Data structure with two parts - modelConfiguration and metadataConfiguration. * * * modelConfiguration * contains the information necessary for configuring the regression model to be trained * (e.g., the degree of a polynomial in case of polynomial regression). * * * metadataConfiguration * specifies which variables are the input variables (regressors), and which one is the output variable * (regressand) of the regression model. In order to specify time as one of the input variables, * set propertyName equal to timestamp. * * @returns {Promise<TrendPredictionModels.PredictionDataArrayDirect>} * * @memberOf TrendPredictionClient */ public async TrainAndPredictDirect( modelData: TrendPredictionModels.TrainPredictBodyDirect, params: { trainFrom: Date; trainTo: Date; predictFrom: Date; predictTo: Date; } ): Promise<TrendPredictionModels.PredictionDataArrayDirect> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/trainAndPredictDirect?${toQueryString(params)}`, body: modelData, }); return result as TrendPredictionModels.PredictionDataArrayDirect; } /** * Retrieves all trained regression models for a given entity. * * @param {({ * entityId: string; * sort?: "asc" | "desc"; * })} [optional={ entityId: "*", sort: "asc" }] * @returns {Promise<TrendPredictionModels.ModelDto[]>} * * * entityid * Entity to get the regression models for. * * sort * Sorts the regression models by creation timestamp (ascending/descending). * Available values : asc, desc * * @memberOf TrendPredictionClient */ public async GetModels( optional: { entityId: string; sort?: "asc" | "desc"; size?: number; } = { entityId: "*", sort: "asc", size: 100 } // ! fixed on the client for the february version of the api ): Promise<TrendPredictionModels.ModelDto[]> { const qs = toQueryString(optional); return (await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/models?${qs}`, message: "GetModels", })) as TrendPredictionModels.ModelDto[]; } /** * Retrieves a regression model using the corresponding ID. * * @param {string} id * * Id of the regression model. * @returns {Promise<TrendPredictionModels.ModelDto>} * * @memberOf TrendPredictionClient */ public async GetModel(id: string): Promise<TrendPredictionModels.ModelDto> { return (await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/models/${id}`, message: "GetModel", })) as TrendPredictionModels.ModelDto; } /** * Deletes a regression model using the corresponding ID. * * @param {string} id * * Id of the regression model. * * @returns * * @memberOf TrendPredictionClient */ public async DeleteModel(id: string) { return await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/models/${id}`, message: "DeleteModel", noResponse: true, }); } }
the_stack
import { WatchQueryFetchPolicy, ApolloError, useQuery, NetworkStatus, gql } from '@apollo/client'; import { graphql } from '@apollo/client/react/hoc'; import qs from 'qs'; import { useState } from 'react'; import compose from 'recompose/compose'; import withState from 'recompose/withState'; import * as _ from 'underscore'; import { extractCollectionInfo, extractFragmentInfo, getFragment, getCollection, pluralize, camelCaseify } from '../vulcan-lib'; import { useLocation, useNavigation } from '../routeUtil'; // Multi query used on the client // // mutation multiMovieQuery($input: MultiMovieInput) { // movies(input: $input) { // results { // _id // name // __typename // } // totalCount // __typename // } // } const multiClientTemplate = ({ typeName, fragmentName, extraQueries, extraVariablesString }) => `query multi${typeName}Query($input: Multi${typeName}Input, ${extraVariablesString || ''}) { ${camelCaseify(pluralize(typeName))}(input: $input) { results { ...${fragmentName} } totalCount __typename } ${extraQueries ? extraQueries : ''} }`; function getGraphQLQueryFromOptions({ collectionName, collection, fragmentName, fragment, extraQueries, extraVariables, }) { const typeName = collection.options.typeName; ({ fragmentName, fragment } = extractFragmentInfo({ fragmentName, fragment }, collectionName)); let extraVariablesString = '' if (extraVariables) { extraVariablesString = Object.keys(extraVariables).map(k => `$${k}: ${extraVariables[k]}`).join(', ') } // build graphql query from options return gql` ${multiClientTemplate({ typeName, fragmentName, extraQueries, extraVariablesString })} ${fragment} `; } // Paginated items container // // Options: // // - collection: the collection to fetch the documents from // - fragment: the fragment that defines which properties to fetch // - fragmentName: the name of the fragment, passed to getFragment // - limit: the number of documents to show initially // - pollInterval: how often the data should be updated, in ms (set to 0 to disable polling) // - terms: an object that defines which documents to fetch // // Props Received: // - terms: an object that defines which documents to fetch // // Terms object can have the following properties: // - view: String // - userId: String // - cat: String // - date: String // - after: String // - before: String // - enableTotal: Boolean // - enableCache: Boolean // - listId: String // - query: String # search query // - postId: String // - limit: String export function withMulti({ limit = 10, // Only used as a fallback if terms.limit is not specified pollInterval = 0, //LESSWRONG: Polling is disabled, and by now it would probably horribly break if turned on enableTotal = false, //LESSWRONG: enableTotal defaults false enableCache = false, extraQueries, extraVariables, fetchPolicy, notifyOnNetworkStatusChange, propertyName = "results", collectionName, collection, fragmentName, fragment, terms: queryTerms, }: { limit?: number, pollInterval?: number, enableTotal?: boolean, enableCache?: boolean, extraQueries?: any, extraVariables?: any, fetchPolicy?: WatchQueryFetchPolicy, notifyOnNetworkStatusChange?: boolean, propertyName?: string, collectionName?: CollectionNameString, collection?: CollectionBase<any>, fragmentName?: FragmentName, fragment?: any, terms?: any, }) { // if this is the SSR process, set pollInterval to null // see https://github.com/apollographql/apollo-client/issues/1704#issuecomment-322995855 //pollInterval = typeof window === 'undefined' ? null : pollInterval; ({ collectionName, collection } = extractCollectionInfo({ collectionName, collection })); ({ fragmentName, fragment } = extractFragmentInfo({ fragmentName, fragment }, collectionName)); const typeName = collection!.options.typeName; const resolverName = collection!.options.multiResolverName; const query = getGraphQLQueryFromOptions({ collectionName, collection, fragmentName, fragment, extraQueries, extraVariables }); return compose( // wrap component with HoC that manages the terms object via its state withState('paginationTerms', 'setPaginationTerms', (props: any) => { // get initial limit from props, or else options const paginationLimit = (props.terms && props.terms.limit) || limit; const paginationTerms = { limit: paginationLimit, itemsPerPage: paginationLimit, }; return paginationTerms; }), // wrap component with graphql HoC graphql( query, { alias: `with${pluralize(typeName)}`, // graphql query options options(props: any) { const { terms, paginationTerms, ...rest } = props; // get terms from options, then props, then pagination const mergedTerms = { ...queryTerms, ...terms, ...paginationTerms }; const graphQLOptions: any = { variables: { input: { terms: mergedTerms, enableCache, enableTotal, }, ...(_.pick(rest, Object.keys(extraVariables || {}))) }, // note: pollInterval can be set to 0 to disable polling (20s by default) pollInterval, ssr: true, }; if (fetchPolicy) { graphQLOptions.fetchPolicy = fetchPolicy; } // set to true if running into https://github.com/apollographql/apollo-client/issues/1186 if (notifyOnNetworkStatusChange) { graphQLOptions.notifyOnNetworkStatusChange = notifyOnNetworkStatusChange; } return graphQLOptions; }, // define props returned by graphql HoC props(props: any) { // see https://github.com/apollographql/apollo-client/blob/master/packages/apollo-client/src/core/networkStatus.ts if (!(props?.data)) throw new Error("Missing props.data"); const refetch = props.data.refetch, // results = Utils.convertDates(collection, props.data[listResolverName]), results = props.data[resolverName] && props.data[resolverName].results, totalCount = props.data[resolverName] && props.data[resolverName].totalCount, networkStatus = props.data.networkStatus, loadingInitial = props.data.networkStatus === 1, loading = props.data.networkStatus === 1, loadingMore = props.data.networkStatus === 2, error = props.data.error; if (error) { // This error was already caught by the apollo middleware, but the // middleware had no idea who made the query. To aid in debugging, log a // stack trace here. // eslint-disable-next-line no-console console.error(error.message) } return { // see https://github.com/apollostack/apollo-client/blob/master/src/queries/store.ts#L28-L36 // note: loading will propably change soon https://github.com/apollostack/apollo-client/issues/831 loading, loadingInitial, loadingMore, [propertyName]: results, totalCount, refetch, networkStatus, error, count: results && results.length, // regular load more (reload everything) loadMore(providedTerms) { // if new terms are provided by presentational component use them, else default to incrementing current limit once const newTerms = typeof providedTerms === 'undefined' ? { /*...props.ownProps.terms,*/ ...props.ownProps.paginationTerms, limit: results.length + props.ownProps.paginationTerms.itemsPerPage, } : providedTerms; props.ownProps.setPaginationTerms(newTerms); }, fragmentName, fragment, ...props.ownProps, // pass on the props down to the wrapped component data: props.data, }; }, } ) ); } export interface UseMultiOptions< FragmentTypeName extends keyof FragmentTypes, CollectionName extends CollectionNameString > { terms: ViewTermsByCollectionName[CollectionName], extraVariablesValues?: any, pollInterval?: number, enableTotal?: boolean, enableCache?: boolean, extraQueries?: any, extraVariables?: any, fetchPolicy?: WatchQueryFetchPolicy, nextFetchPolicy?: WatchQueryFetchPolicy, collectionName: CollectionNameString, fragmentName: FragmentTypeName, limit?: number, itemsPerPage?: number, skip?: boolean, queryLimitName?: string, alwaysShowLoadMore?: boolean, } export type LoadMoreCallback = (limitOverride?: number) => void export type LoadMoreProps = { loadMore: LoadMoreCallback count: number, totalCount: number, loading: boolean, hidden: boolean, } export function useMulti< FragmentTypeName extends keyof FragmentTypes, CollectionName extends CollectionNameString = CollectionNamesByFragmentName[FragmentTypeName] >({ terms, extraVariablesValues, pollInterval = 0, //LESSWRONG: Polling defaults disabled enableTotal = false, //LESSWRONG: enableTotal defaults false enableCache = false, extraQueries, extraVariables, fetchPolicy, nextFetchPolicy, collectionName, fragmentName, //fragment, limit:initialLimit = 10, // Only used as a fallback if terms.limit is not specified itemsPerPage = 10, skip = false, queryLimitName, alwaysShowLoadMore = false, }: UseMultiOptions<FragmentTypeName,CollectionName>): { loading: boolean, loadingInitial: boolean, loadingMore: boolean, results?: Array<FragmentTypes[FragmentTypeName]>, totalCount?: number, refetch: any, error: ApolloError|undefined, count?: number, showLoadMore: boolean, loadMoreProps: LoadMoreProps, loadMore: any, limit: number, } { const { query: locationQuery, location } = useLocation(); const { history } = useNavigation(); const defaultLimit = ((locationQuery && queryLimitName && parseInt(locationQuery[queryLimitName])) || (terms && terms.limit) || initialLimit) const [ limit, setLimit ] = useState(defaultLimit); const [ lastTerms, setLastTerms ] = useState(_.clone(terms)); const collection = getCollection(collectionName); const fragment = getFragment(fragmentName); const query = getGraphQLQueryFromOptions({ collectionName, collection, fragmentName, fragment, extraQueries, extraVariables }); const resolverName = collection.options.multiResolverName; const graphQLVariables = { input: { terms: { ...terms, limit: defaultLimit }, enableCache, enableTotal, }, ...(_.pick(extraVariablesValues, Object.keys(extraVariables || {}))) } let effectiveLimit = limit; if (!_.isEqual(terms, lastTerms)) { setLastTerms(terms); setLimit(defaultLimit); effectiveLimit = defaultLimit; } // Due to https://github.com/apollographql/apollo-client/issues/6760 this is necessary to restore the Apollo 2.0 behavior for cache-and-network policies const newNextFetchPolicy = nextFetchPolicy || (fetchPolicy === "cache-and-network" || fetchPolicy === "network-only") ? "cache-only" : undefined const useQueryArgument = { variables: graphQLVariables, pollInterval, fetchPolicy, nextFetchPolicy: newNextFetchPolicy as WatchQueryFetchPolicy, ssr: true, skip, notifyOnNetworkStatusChange: true } const {data, error, loading, refetch, fetchMore, networkStatus} = useQuery(query, useQueryArgument); if (error) { // This error was already caught by the apollo middleware, but the // middleware had no idea who made the query. To aid in debugging, log a // stack trace here. // eslint-disable-next-line no-console console.error(error.message) } const count = (data && data[resolverName] && data[resolverName].results && data[resolverName].results.length) || 0; const totalCount = data && data[resolverName] && data[resolverName].totalCount; // If we did a query to count the total number of results (enableTotal), // show a Load More if we have fewer than that many results. If we didn't do // that, show a Load More if we got at least as many results as requested. // This means that if the total number of results exactly matches the limit, // the last click of Load More won't get any more documents. // // The caller of this function is responsible for showing a Load More button // if showLoadMore returned true. const showLoadMore = alwaysShowLoadMore || (enableTotal ? (count < totalCount) : (count >= effectiveLimit)); const loadMore: LoadMoreCallback = async (limitOverride?: number) => { const newLimit = limitOverride || (effectiveLimit+itemsPerPage) if (queryLimitName) { const newQuery = {...locationQuery, [queryLimitName]: newLimit} history.push({...location, search: `?${qs.stringify(newQuery)}`}) } void fetchMore({ variables: { ...graphQLVariables, input: { ...graphQLVariables.input, terms: {...graphQLVariables.input.terms, limit: newLimit} } }, updateQuery: (prev, { fetchMoreResult }) => { if (!fetchMoreResult) return prev; return fetchMoreResult } }) setLimit(newLimit) }; // A bundle of props that you can pass to Components.LoadMore, to make // everything just work. const loadMoreProps = { loadMore, count, totalCount, loading, hidden: !showLoadMore, }; let results = data?.[resolverName]?.results; if (results && results.length > limit) { results = _.take(results, limit); } return { loading: loading || networkStatus === NetworkStatus.fetchMore, loadingInitial: networkStatus === NetworkStatus.loading, loadingMore: networkStatus === NetworkStatus.fetchMore, results, totalCount: totalCount, refetch, error, count, showLoadMore, loadMoreProps, loadMore, limit: effectiveLimit, }; } export default withMulti;
the_stack
import MessageRouter from "../../../../../main/js/joynr/messaging/routing/MessageRouter"; import BrowserAddress from "../../../../../main/js/generated/joynr/system/RoutingTypes/BrowserAddress"; import ChannelAddress from "../../../../../main/js/generated/joynr/system/RoutingTypes/ChannelAddress"; import InProcessAddress from "../../../../../main/js/joynr/messaging/inprocess/InProcessAddress"; import JoynrMessage from "../../../../../main/js/joynr/messaging/JoynrMessage"; import TypeRegistry from "../../../../../main/js/joynr/start/TypeRegistry"; import * as UtilInternal from "../../../../../main/js/joynr/util/UtilInternal"; import nanoid from "nanoid"; import testUtil = require("../../../testUtil"); import UdsAddress from "../../../../../main/js/generated/joynr/system/RoutingTypes/UdsAddress"; import UdsClientAddress from "../../../../../main/js/generated/joynr/system/RoutingTypes/UdsClientAddress"; const typeRegistry = require("../../../../../main/js/joynr/types/TypeRegistrySingleton").getInstance(); typeRegistry.addType(BrowserAddress).addType(ChannelAddress); let fakeTime: number; async function increaseFakeTime(timeMs: number) { fakeTime = fakeTime + timeMs; jest.advanceTimersByTime(timeMs); await testUtil.multipleSetImmediate(); } describe("libjoynr-js.joynr.messaging.routing.MessageRouter", () => { let typeRegistry: any; let senderParticipantId: any, receiverParticipantId: any, receiverParticipantId2: any; let joynrMessage: any, joynrMessage2: any; let address: any; let messagingStubSpy: any, messagingSkeletonSpy: any, messagingStubFactorySpy: any; let messageQueueSpy: any, messageRouter: any, messageRouterWithUdsAddress: any, routingProxySpy: any, parentMessageRouterAddress: any, incomingAddress: any; let multicastAddressCalculatorSpy: any; let serializedTestGlobalClusterControllerAddress: any; let multicastAddress: any; const routingTable: any = {}; const multicastSkeletons: any = {}; const createMessageRouter = function( messageQueue: any, incomingAddress?: any, parentMessageRouterAddress?: any ): MessageRouter { return new MessageRouter({ initialRoutingTable: routingTable, messagingStubFactory: messagingStubFactorySpy, multicastSkeletons, multicastAddressCalculator: multicastAddressCalculatorSpy, messageQueue, incomingAddress, parentMessageRouterAddress }); }; const createRootMessageRouter = function(messageQueue: any) { return createMessageRouter(messageQueue); }; beforeEach(done => { incomingAddress = new BrowserAddress({ windowId: "incomingAddress" }); parentMessageRouterAddress = new BrowserAddress({ windowId: "parentMessageRouterAddress" }); senderParticipantId = `testSenderParticipantId_${Date.now()}`; receiverParticipantId = `TestMessageRouter_participantId_${Date.now()}`; receiverParticipantId2 = `TestMessageRouter_delayedParticipantId_${Date.now()}`; joynrMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST, payload: "hello" }); joynrMessage.expiryDate = 9360686108031; joynrMessage.to = receiverParticipantId; joynrMessage.from = senderParticipantId; joynrMessage2 = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST, payload: "hello2" }); joynrMessage2.to = receiverParticipantId2; joynrMessage2.from = "senderParticipantId"; address = { addressInformation: "some info" }; multicastAddressCalculatorSpy = { calculate: jest.fn() }; multicastAddress = new BrowserAddress({ windowId: "incomingAddress" }); multicastAddressCalculatorSpy.calculate.mockReturnValue(multicastAddress); messagingStubSpy = { transmit: jest.fn() }; messagingSkeletonSpy = { registerMulticastSubscription: jest.fn(), unregisterMulticastSubscription: jest.fn() }; messagingStubSpy.transmit.mockReturnValue( Promise.resolve({ myKey: "myValue" }) ); messagingStubFactorySpy = { createMessagingStub: jest.fn() }; messagingStubFactorySpy.createMessagingStub.mockReturnValue(messagingStubSpy); messageQueueSpy = { putMessage: jest.fn(), getAndRemoveMessages: jest.fn(), shutdown: jest.fn() }; fakeTime = Date.now(); jest.useFakeTimers(); jest.spyOn(Date, "now").mockImplementation(() => { return fakeTime; }); typeRegistry = new TypeRegistry(); typeRegistry.addType(ChannelAddress); typeRegistry.addType(BrowserAddress); serializedTestGlobalClusterControllerAddress = "testGlobalAddress"; routingProxySpy = { addNextHop: jest.fn().mockResolvedValue(undefined), removeNextHop: jest.fn(), resolveNextHop: jest.fn(), addMulticastReceiver: jest.fn(), removeMulticastReceiver: jest.fn(), globalAddress: { get: jest.fn().mockResolvedValue(serializedTestGlobalClusterControllerAddress) }, replyToAddress: { get: jest.fn().mockResolvedValue(serializedTestGlobalClusterControllerAddress) }, proxyParticipantId: "proxyParticipantId" }; messageRouter = createRootMessageRouter(messageQueueSpy); messageRouter.setReplyToAddress(serializedTestGlobalClusterControllerAddress); done(); }); afterEach(done => { jest.useRealTimers(); done(); }); it("does not queue Reply and Publication Messages with unknown destinationParticipant", async () => { const msgTypes = [ JoynrMessage.JOYNRMESSAGE_TYPE_REPLY, JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REPLY, JoynrMessage.JOYNRMESSAGE_TYPE_PUBLICATION ]; for (let i = 0; i < msgTypes.length; i++) { joynrMessage2 = new JoynrMessage({ type: msgTypes[i], payload: "hello2" }); joynrMessage2.expiryDate = Date.now() + 2000; joynrMessage2.to = receiverParticipantId2; joynrMessage2.from = "senderParticipantId"; await messageRouter.route(joynrMessage2); expect(messageQueueSpy.putMessage).not.toHaveBeenCalledWith(joynrMessage2); expect(messageQueueSpy.getAndRemoveMessages).not.toHaveBeenCalled(); expect(messagingStubFactorySpy.createMessagingStub).not.toHaveBeenCalled(); expect(messagingStubSpy.transmit).not.toHaveBeenCalled(); } }); it("queues Messages with unknown destinationParticipant which are not of type Reply or Publication", async () => { const msgTypes = [ JoynrMessage.JOYNRMESSAGE_TYPE_ONE_WAY, JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST, JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST, JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST, JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST, JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_STOP ]; for (let i = 0; i < msgTypes.length; i++) { joynrMessage2 = new JoynrMessage({ type: msgTypes[i], payload: "hello2" }); joynrMessage2.expiryDate = Date.now() + 2000; joynrMessage2.to = receiverParticipantId2; joynrMessage2.from = "senderParticipantId"; await messageRouter.route(joynrMessage2); expect(messageQueueSpy.putMessage).toHaveBeenCalledWith(joynrMessage2); expect(messageQueueSpy.getAndRemoveMessages).not.toHaveBeenCalled(); expect(messagingStubFactorySpy.createMessagingStub).not.toHaveBeenCalled(); expect(messagingStubSpy.transmit).not.toHaveBeenCalled(); messageQueueSpy.putMessage.mockClear(); } }); it("routes previously queued message once respective participant gets registered", async () => { const messageQueue = [joynrMessage2]; joynrMessage2.expiryDate = Date.now() + 2000; const onFulfilledSpy = jest.fn(); messageRouter .route(joynrMessage2) .then(onFulfilledSpy) .catch(() => {}); await increaseFakeTime(1); expect(messageQueueSpy.putMessage).toHaveBeenCalledWith(joynrMessage2); expect(messagingStubFactorySpy.createMessagingStub).not.toHaveBeenCalled(); expect(messagingStubSpy.transmit).not.toHaveBeenCalled(); const isGloballyVisible = true; messageRouter.addNextHop(joynrMessage2.to, address, isGloballyVisible).catch(() => {}); messageQueueSpy.getAndRemoveMessages.mockReturnValue(messageQueue); messageRouter.participantRegistered(joynrMessage2.to); await increaseFakeTime(1); expect(messageQueueSpy.getAndRemoveMessages).toHaveBeenCalledWith(joynrMessage2.to); expect(messagingStubFactorySpy.createMessagingStub).toHaveBeenCalledWith(address); expect(messagingStubSpy.transmit).toHaveBeenCalledWith(joynrMessage2); await messageRouter.removeNextHop(joynrMessage2.to); await increaseFakeTime(1); }); it("drop previously queued message if respective participant gets registered after expiry date", async () => { joynrMessage2.expiryDate = Date.now() + 2000; const messageQueue = []; messageQueue[0] = joynrMessage2; await messageRouter.route(joynrMessage2); await increaseFakeTime(1); expect(messageQueueSpy.putMessage).toHaveBeenCalledTimes(1); expect(messageQueueSpy.putMessage).toHaveBeenCalledWith(joynrMessage2); expect(messageQueueSpy.getAndRemoveMessages).not.toHaveBeenCalled(); messageQueueSpy.getAndRemoveMessages.mockReturnValue(messageQueue); await increaseFakeTime(2000 + 1); const isGloballyVisible = true; await messageRouter.addNextHop(joynrMessage2.to, address, isGloballyVisible); await increaseFakeTime(1); expect(messageQueueSpy.putMessage).toHaveBeenCalledTimes(1); expect(messageQueueSpy.getAndRemoveMessages).toHaveBeenCalledTimes(1); expect(messageQueueSpy.getAndRemoveMessages).toHaveBeenCalledWith(joynrMessage2.to); expect(messagingStubFactorySpy.createMessagingStub).not.toHaveBeenCalled(); expect(messagingStubSpy.transmit).not.toHaveBeenCalled(); await messageRouter.removeNextHop(joynrMessage2.to); await increaseFakeTime(1); }); it("route drops expired messages, but will resolve the Promise", async () => { const isGloballyVisible = true; await messageRouter.addNextHop(joynrMessage.to, address, isGloballyVisible); joynrMessage.expiryDate = Date.now() - 1; joynrMessage.isLocalMessage = true; await messageRouter.route(joynrMessage); expect(messagingStubSpy.transmit).not.toHaveBeenCalled(); }); it("sets replyTo address for non local messages", () => { const isGloballyVisible = true; messageRouter.addNextHop(joynrMessage.to, address, isGloballyVisible); joynrMessage.isLocalMessage = false; expect(joynrMessage.replyChannelId).toEqual(undefined); messageRouter.route(joynrMessage); expect(messagingStubSpy.transmit).toHaveBeenCalled(); const transmittedJoynrMessage = messagingStubSpy.transmit.mock.calls[0][0]; expect(transmittedJoynrMessage.replyChannelId).toEqual(serializedTestGlobalClusterControllerAddress); }); it("does not set replyTo address for local messages", () => { const isGloballyVisible = false; messageRouter.addNextHop(joynrMessage.to, address, isGloballyVisible); joynrMessage.isLocalMessage = true; expect(joynrMessage.replyChannelId).toEqual(undefined); messageRouter.route(joynrMessage); expect(messagingStubSpy.transmit).toHaveBeenCalled(); const transmittedJoynrMessage = messagingStubSpy.transmit.mock.calls[0][0]; expect(transmittedJoynrMessage.replyChannelId).toEqual(undefined); }); function routeMessageWithValidReplyToAddressCallsAddNextHop() { messageRouter.addNextHop.mockClear(); expect(messageRouter.addNextHop).not.toHaveBeenCalled(); const channelId = `testChannelId_${Date.now()}`; const channelAddress = new ChannelAddress({ messagingEndpointUrl: "http://testurl.com", channelId }); joynrMessage.replyChannelId = JSON.stringify(channelAddress); messageRouter.route(joynrMessage); expect(messageRouter.addNextHop).toHaveBeenCalledTimes(1); expect(messageRouter.addNextHop.mock.calls[0][0]).toBe(senderParticipantId); expect(messageRouter.addNextHop.mock.calls[0][1].channelId).toBe(channelId); expect(messageRouter.addNextHop.mock.calls[0][2]).toBe(true); } it("route calls addNextHop for request messages received from global", () => { jest.spyOn(messageRouter, "addNextHop"); joynrMessage.isReceivedFromGlobal = true; joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST; routeMessageWithValidReplyToAddressCallsAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST; routeMessageWithValidReplyToAddressCallsAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST; routeMessageWithValidReplyToAddressCallsAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST; routeMessageWithValidReplyToAddressCallsAddNextHop(); }); function routeMessageWithValidReplyToAddressDoesNotCallAddNextHop() { messageRouter.addNextHop.mockClear(); const channelId = `testChannelId_${Date.now()}`; const channelAddress = new ChannelAddress({ messagingEndpointUrl: "http://testurl.com", channelId }); joynrMessage.replyChannelId = JSON.stringify(channelAddress); messageRouter.route(joynrMessage); expect(messageRouter.addNextHop).not.toHaveBeenCalled(); } it("route does NOT call addNextHop for request messages NOT received from global", () => { jest.spyOn(messageRouter, "addNextHop"); joynrMessage.isReceivedFromGlobal = false; joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); }); it("route does NOT call addNextHop for non request messages received from global", () => { jest.spyOn(messageRouter, "addNextHop"); joynrMessage.isReceivedFromGlobal = true; joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_ONE_WAY; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_REPLY; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REPLY; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_PUBLICATION; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_STOP; routeMessageWithValidReplyToAddressDoesNotCallAddNextHop(); }); it("route does NOT call addNextHop for request messages received from global without replyTo address", () => { jest.spyOn(messageRouter, "addNextHop"); joynrMessage.isReceivedFromGlobal = true; joynrMessage.type = JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST; messageRouter.route(joynrMessage); expect(messageRouter.addNextHop).not.toHaveBeenCalled(); }); it("addNextHop will work", async () => { messageRouter = createMessageRouter(messageQueueSpy); messageRouter.setReplyToAddress(serializedTestGlobalClusterControllerAddress); messageRouter.addNextHop(joynrMessage.to, address); await messageRouter.route(joynrMessage); expect(messagingStubSpy.transmit).toHaveBeenCalled(); }); describe("route multicast messages", () => { let parameters: any; let multicastMessage: any; let addressOfSubscriberParticipant: any; let isGloballyVisible: any; beforeEach(() => { parameters = { multicastId: `multicastId- ${nanoid()}`, subscriberParticipantId: "subscriberParticipantId", providerParticipantId: "providerParticipantId" }; routingTable["providerParticipantId"] = { _typeName: "typeName" }; multicastSkeletons["typeName"] = messagingSkeletonSpy; multicastMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST, payload: "hello" }); multicastMessage.expiryDate = 9360686108031; multicastMessage.to = parameters.multicastId; multicastMessage.from = "senderParticipantId"; /* add routing table entry for parameters.subscriberParticipantId, * otherwise messaging stub call can be executed by the message router */ addressOfSubscriberParticipant = new BrowserAddress({ windowId: "windowIdOfSubscriberParticipant" }); isGloballyVisible = true; messageRouter.addNextHop( parameters.subscriberParticipantId, addressOfSubscriberParticipant, isGloballyVisible ); }); it("never, if message is received from global and NO local receiver", () => { multicastMessage.isReceivedFromGlobal = true; messageRouter.route(multicastMessage); expect(messagingStubSpy.transmit).not.toHaveBeenCalled(); }); it("once, if message is received from global and has local receiver", () => { messageRouter.addMulticastReceiver(parameters); multicastMessage.isReceivedFromGlobal = true; messageRouter.route(multicastMessage); expect(messagingStubSpy.transmit).toHaveBeenCalled(); expect(messagingStubSpy.transmit.mock.calls.length).toBe(1); }); it("once, if message is NOT received from global and NO local receiver", () => { messageRouter.route(multicastMessage); expect(messagingStubFactorySpy.createMessagingStub).toHaveBeenCalled(); expect(messagingStubFactorySpy.createMessagingStub.mock.calls.length).toEqual(1); const address = messagingStubFactorySpy.createMessagingStub.mock.calls[0][0]; expect(address).toEqual(multicastAddress); expect(messagingStubSpy.transmit).toHaveBeenCalled(); expect(messagingStubSpy.transmit.mock.calls.length).toBe(1); }); it("twice, if message is NOT received from global and local receiver available", () => { messageRouter.addMulticastReceiver(parameters); messageRouter.route(multicastMessage); expect(messagingStubSpy.transmit).toHaveBeenCalled(); expect(messagingStubSpy.transmit.mock.calls.length).toBe(2); }); it("twice, if message is NOT received from global and two local receivers available with same receiver address", () => { messageRouter.addMulticastReceiver(parameters); const parametersForSndReceiver = { multicastId: parameters.multicastId, subscriberParticipantId: "subscriberParticipantId2", providerParticipantId: "providerParticipantId" }; messageRouter.addMulticastReceiver(parametersForSndReceiver); messageRouter.addNextHop( parametersForSndReceiver.subscriberParticipantId, addressOfSubscriberParticipant, isGloballyVisible ); messageRouter.route(multicastMessage); expect(messagingStubSpy.transmit).toHaveBeenCalled(); expect(messagingStubSpy.transmit.mock.calls.length).toBe(2); }); it("three times, if message is NOT received from global and two local receivers available with different receiver address", () => { messageRouter.addMulticastReceiver(parameters); const parametersForSndReceiver = { multicastId: parameters.multicastId, subscriberParticipantId: "subscriberParticipantId2", providerParticipantId: "providerParticipantId" }; messageRouter.addMulticastReceiver(parametersForSndReceiver); messageRouter.addNextHop( parametersForSndReceiver.subscriberParticipantId, new BrowserAddress({ windowId: "windowIdOfNewSubscribeParticipant" }), isGloballyVisible ); messageRouter.route(multicastMessage); expect(messagingStubSpy.transmit).toHaveBeenCalled(); expect(messagingStubSpy.transmit.mock.calls.length).toBe(3); }); }); // describe route multicast messages it("routes messages using the messagingStubFactory and messageStub", async () => { const isGloballyVisible = true; await messageRouter.addNextHop(joynrMessage.to, address, isGloballyVisible); await messageRouter.route(joynrMessage); await increaseFakeTime(1); expect(messagingStubFactorySpy.createMessagingStub).toHaveBeenCalledWith(address); expect(messagingStubSpy.transmit).toHaveBeenCalledWith(joynrMessage); messageRouter.removeNextHop(joynrMessage.to); await increaseFakeTime(1); }); it("discards messages without resolvable address", async () => { await messageRouter.route(joynrMessage); await increaseFakeTime(1); expect(messagingStubFactorySpy.createMessagingStub).not.toHaveBeenCalled(); expect(messagingStubSpy.transmit).not.toHaveBeenCalled(); }); describe("ChildMessageRouterWithUdsAddress", () => { beforeEach(done => { incomingAddress = new UdsClientAddress({ id: "udsId" }); parentMessageRouterAddress = new UdsAddress({ path: "path" }); messageRouterWithUdsAddress = createMessageRouter( messageQueueSpy, incomingAddress, parentMessageRouterAddress ); messageRouterWithUdsAddress.setReplyToAddress(serializedTestGlobalClusterControllerAddress); done(); }); it("addNextHop adds UdsClientAddress to local and parent routing table", async () => { const expectedParameters = { participantId: joynrMessage.to, udsClientAddress: incomingAddress, isGloballyVisible: false }; await messageRouterWithUdsAddress.setRoutingProxy(routingProxySpy); expect(routingTable[joynrMessage.to]).toBeUndefined(); address = new UdsClientAddress({ id: "udsId" }); await messageRouterWithUdsAddress.addNextHop(joynrMessage.to, address, false); expect(routingTable[joynrMessage.to].id).toEqual("udsId"); expect(routingTable[joynrMessage.to]._typeName).toEqual(address._typeName); expect(() => messageRouterWithUdsAddress.removeNextHop(joynrMessage.to)).not.toThrow(); expect(routingProxySpy.addNextHop).toHaveBeenCalledWith(expectedParameters); }); }); // describe ChildMessageRouterWithUdsAddress describe("ChildMessageRouter", () => { beforeEach(() => { messageRouter = createMessageRouter(messageQueueSpy, incomingAddress, parentMessageRouterAddress); messageRouter.setReplyToAddress(serializedTestGlobalClusterControllerAddress); }); it("queries global address from routing provider", () => { messageRouter = createMessageRouter(messageQueueSpy, incomingAddress, parentMessageRouterAddress); routingProxySpy.addNextHop.mockReturnValue(Promise.resolve()); }); it("sets replyTo address for non local messages", () => { const isGloballyVisible = true; messageRouter.addNextHop(joynrMessage.to, address, isGloballyVisible); joynrMessage.isLocalMessage = false; expect(joynrMessage.replyChannelId).toEqual(undefined); messageRouter.route(joynrMessage); expect(messagingStubSpy.transmit).toHaveBeenCalled(); const transmittedJoynrMessage = messagingStubSpy.transmit.mock.calls[0][0]; expect(transmittedJoynrMessage.replyChannelId).toEqual(serializedTestGlobalClusterControllerAddress); }); it("does not set replyTo address for local messages", () => { const isGloballyVisible = true; messageRouter.addNextHop(joynrMessage.to, address, isGloballyVisible); joynrMessage.isLocalMessage = true; expect(joynrMessage.replyChannelId).toEqual(undefined); messageRouter.route(joynrMessage); expect(messagingStubSpy.transmit).toHaveBeenCalled(); const transmittedJoynrMessage = messagingStubSpy.transmit.mock.calls[0][0]; expect(transmittedJoynrMessage.replyChannelId).toEqual(undefined); }); it("queues non local messages until global address is available", async () => { const isGloballyVisible = true; messageRouter = createMessageRouter(messageQueueSpy, incomingAddress, parentMessageRouterAddress); routingProxySpy.addNextHop.mockReturnValue(Promise.resolve()); await messageRouter.addNextHop(joynrMessage.to, address, isGloballyVisible); joynrMessage.isLocalMessage = false; const expectedJoynrMessage = JoynrMessage.parseMessage(UtilInternal.extendDeep({}, joynrMessage)); expectedJoynrMessage.replyChannelId = serializedTestGlobalClusterControllerAddress; await messageRouter.route(joynrMessage); expect(messagingStubSpy.transmit).not.toHaveBeenCalled(); await messageRouter.setRoutingProxy(routingProxySpy); await messageRouter.configureReplyToAddressFromRoutingProxy(); await testUtil.multipleSetImmediate(); expect(messagingStubSpy.transmit).toHaveBeenCalledWith(expectedJoynrMessage); }); it("address can be resolved once known to message router", async () => { const participantId = "participantId-setToKnown"; const address = await messageRouter.resolveNextHop(participantId); expect(address).toBe(undefined); // it is expected that the given participantId cannot be resolved messageRouter.setToKnown(participantId); const address2 = await messageRouter.resolveNextHop(participantId); expect(address2).toBe(parentMessageRouterAddress); }); describe("addMulticastReceiver", () => { let parameters: any; beforeEach(() => { parameters = { multicastId: `multicastId- ${nanoid()}`, subscriberParticipantId: "subscriberParticipantId", providerParticipantId: "providerParticipantId" }; routingTable["providerParticipantId"] = { _typeName: "typeName" }; multicastSkeletons["typeName"] = messagingSkeletonSpy; messageRouter.setToKnown(parameters.providerParticipantId); routingProxySpy.addMulticastReceiver.mockReturnValue(Promise.resolve()); expect(messageRouter.hasMulticastReceivers()).toBe(false); }); it("calls matching skeleton", () => { messageRouter.addMulticastReceiver(parameters); expect(messagingSkeletonSpy.registerMulticastSubscription).toHaveBeenCalled(); expect(messagingSkeletonSpy.registerMulticastSubscription).toHaveBeenCalledWith(parameters.multicastId); expect(messageRouter.hasMulticastReceivers()).toBe(true); }); it("calls routing proxy if available", () => { messageRouter.setRoutingProxy(routingProxySpy); messageRouter.addMulticastReceiver(parameters); expect(routingProxySpy.addMulticastReceiver).toHaveBeenCalled(); expect(routingProxySpy.addMulticastReceiver).toHaveBeenCalledWith(parameters); expect(messageRouter.hasMulticastReceivers()).toBe(true); }); it("does not call routing proxy for in process provider", () => { const isGloballyVisible = true; messageRouter.setRoutingProxy(routingProxySpy); parameters.providerParticipantId = "inProcessParticipant"; messageRouter.addNextHop( parameters.providerParticipantId, new InProcessAddress(undefined as any), isGloballyVisible ); messageRouter.addMulticastReceiver(parameters); expect(routingProxySpy.addMulticastReceiver).not.toHaveBeenCalled(); expect(messageRouter.hasMulticastReceivers()).toBe(true); }); it("queues calls and forwards them once proxy is available", () => { messageRouter.addMulticastReceiver(parameters); expect(routingProxySpy.addMulticastReceiver).not.toHaveBeenCalled(); }); }); // describe addMulticastReceiver describe("removeMulticastReceiver", () => { let parameters: any; beforeEach(() => { parameters = { multicastId: `multicastId- ${nanoid()}`, subscriberParticipantId: "subscriberParticipantId", providerParticipantId: "providerParticipantId" }; routingTable["providerParticipantId"] = { _typeName: "typeName" }; multicastSkeletons["typeName"] = messagingSkeletonSpy; messageRouter.setToKnown(parameters.providerParticipantId); routingProxySpy.addMulticastReceiver.mockReturnValue(Promise.resolve()); routingProxySpy.removeMulticastReceiver.mockReturnValue(Promise.resolve()); expect(messageRouter.hasMulticastReceivers()).toBe(false); /* addMulticastReceiver is already tested, but added here for * checking proper removeMulticastReceiver functionality */ messageRouter.addMulticastReceiver(parameters); expect(messageRouter.hasMulticastReceivers()).toBe(true); }); it("calls matching skeleton registration and unregistration", () => { messageRouter.removeMulticastReceiver(parameters); expect(messagingSkeletonSpy.unregisterMulticastSubscription).toHaveBeenCalled(); expect(messagingSkeletonSpy.unregisterMulticastSubscription).toHaveBeenCalledWith( parameters.multicastId ); expect(messageRouter.hasMulticastReceivers()).toBe(false); }); it("calls routing proxy if available", () => { messageRouter.setRoutingProxy(routingProxySpy); messageRouter.removeMulticastReceiver(parameters); expect(routingProxySpy.removeMulticastReceiver).toHaveBeenCalled(); expect(routingProxySpy.removeMulticastReceiver).toHaveBeenCalledWith(parameters); expect(messageRouter.hasMulticastReceivers()).toBe(false); }); it("queues calls and forwards them once proxy is available", () => { messageRouter.removeMulticastReceiver(parameters); expect(routingProxySpy.removeMulticastReceiver).not.toHaveBeenCalled(); }); }); // describe removeMulticastReceiver async function checkRoutingProxyAddNextHop( participantId: any, address: any, isGloballyVisible: any ): Promise<void> { routingProxySpy.addNextHop.mockClear(); const expectedParticipantId = participantId; const expectedAddress = incomingAddress; const expectedIsGloballyVisible = isGloballyVisible; await messageRouter.addNextHop(participantId, address, isGloballyVisible); expect(routingProxySpy.addNextHop).toHaveBeenCalledTimes(1); expect(routingProxySpy.addNextHop.mock.calls[0][0].participantId).toEqual(expectedParticipantId); expect(routingProxySpy.addNextHop.mock.calls[0][0].browserAddress).toEqual(expectedAddress); expect(routingProxySpy.addNextHop.mock.calls[0][0].isGloballyVisible).toEqual(expectedIsGloballyVisible); } it("check if routing proxy is called correctly for hop additions", async () => { routingProxySpy.addNextHop.mockReturnValue(Promise.resolve()); await messageRouter.setRoutingProxy(routingProxySpy); let isGloballyVisible = true; await checkRoutingProxyAddNextHop(joynrMessage.to, address, isGloballyVisible); isGloballyVisible = false; await checkRoutingProxyAddNextHop(joynrMessage.to, address, isGloballyVisible); }); it("check if setRoutingProxy calls addNextHop", () => { routingProxySpy.addNextHop.mockReturnValue(Promise.resolve()); expect(routingProxySpy.addNextHop).not.toHaveBeenCalled(); }); it("check if resolved hop from routing proxy is cached", () => { routingProxySpy.resolveNextHop.mockReturnValue(Promise.resolve({ resolved: true })); messageRouter.setRoutingProxy(routingProxySpy); }); it("check if routing proxy is called with queued hop removals", async () => { const onFulfilledSpy = jest.fn(); routingProxySpy.removeNextHop.mockReturnValue(Promise.resolve()); messageRouter.removeNextHop(joynrMessage.to).then(onFulfilledSpy); expect(onFulfilledSpy).not.toHaveBeenCalled(); onFulfilledSpy.mockClear(); expect(routingProxySpy.removeNextHop).not.toHaveBeenCalled(); messageRouter.setRoutingProxy(routingProxySpy); await increaseFakeTime(1); expect(routingProxySpy.removeNextHop).toHaveBeenCalled(); expect(routingProxySpy.removeNextHop.mock.calls[0][0].participantId).toEqual(joynrMessage.to); }); it("check if routing proxy is called with multiple queued hop removals", async () => { const onFulfilledSpy = jest.fn(); routingProxySpy.removeNextHop.mockReturnValue(Promise.resolve()); messageRouter.removeNextHop(joynrMessage.to).then(onFulfilledSpy); messageRouter.removeNextHop(joynrMessage2.to).then(onFulfilledSpy); await testUtil.multipleSetImmediate(); expect(onFulfilledSpy).not.toHaveBeenCalled(); expect(routingProxySpy.removeNextHop).not.toHaveBeenCalled(); await messageRouter.setRoutingProxy(routingProxySpy); await increaseFakeTime(1); expect(routingProxySpy.removeNextHop).toHaveBeenCalled(); expect(routingProxySpy.removeNextHop.mock.calls[0][0].participantId).toEqual(joynrMessage.to); expect(routingProxySpy.removeNextHop.mock.calls[1][0].participantId).toEqual(joynrMessage2.to); }); it("check if routing proxy is called with queued hop removals 2", async () => { routingProxySpy.resolveNextHop.mockResolvedValue({ resolved: true }); await messageRouter.resolveNextHop(joynrMessage.to); await messageRouter.setRoutingProxy(routingProxySpy); expect(routingProxySpy.resolveNextHop).not.toHaveBeenCalled(); const resolvedNextHop = await messageRouter.resolveNextHop(joynrMessage.to); expect(routingProxySpy.resolveNextHop).toHaveBeenCalled(); expect(routingProxySpy.resolveNextHop.mock.calls[0][0].participantId).toEqual(joynrMessage.to); expect(resolvedNextHop).toEqual(parentMessageRouterAddress); }); it(" throws exception when called while shut down", done => { messageRouter.shutdown(); expect(messageQueueSpy.shutdown).toHaveBeenCalled(); messageRouter .removeNextHop("hopId") .then(done.fail) .catch(() => { return messageRouter.resolveNextHop("hopId").then(done.fail); }) .catch(() => { return messageRouter.addNextHop("hopId", {}).then(done.fail); }) .catch(() => done()); }); }); // describe ChildMessageRouter }); // describe MessageRouter
the_stack
import { InputTextField } from "../core/text/InputTextField"; import { TextField } from "../core/text/TextField"; import { TextFormat } from "../core/text/TextFormat"; import { AlignType, AutoSizeType, ObjectPropID, VertAlignType } from "./FieldTypes"; import { GObject } from "./GObject"; import { UIConfig } from "./UIConfig"; import { ByteBuffer } from "../utils/ByteBuffer"; import { UBBParser, defaultParser } from "../utils/UBBParser"; import { XMLUtils } from "../utils/xml/XMLUtils"; import { RichTextField } from "../core/text/RichTextField"; export type TextTemplate = { [index: string]: string }; export class GTextField extends GObject { protected _textField: TextField | RichTextField | InputTextField; protected _text: string; protected _ubbEnabled: boolean; protected _updatingSize: boolean; protected _template: TextTemplate; constructor() { super(); let tf = this._textField.textFormat; tf.font = UIConfig.defaultFont; tf.size = 12; tf.lineSpacing = 3; this._textField.applyFormat(); this._text = ""; this._textField.autoSize = AutoSizeType.Both; this._textField.wordWrap = false; } protected createDisplayObject(): void { this._displayObject = this._textField = new TextField(); } public get text(): string { if (this._displayObject instanceof InputTextField) this._text = this._textField.text; return this._text; } public set text(value: string) { if (value == null) value = ""; this._text = value; this.setText(); this.updateSize(); this.updateGear(6); } protected setText() { let str = this._text; if (this._template) str = this.parseTemplate(str); this._textField.maxWidth = this.maxWidth; if (this._ubbEnabled) this._textField.htmlText = defaultParser.parse(XMLUtils.encodeString(str)); else this._textField.text = str; } public get textTemplate(): TextTemplate { return this._template; } public set textTemplate(value: TextTemplate) { if (!this._template && !value) return; this._template = value; this.flushVars(); } public setVar(name: string, value: string): GTextField { if (!this._template) this._template = {}; this._template[name] = value; return this; } public flushVars(): void { this.setText(); this.updateSize(); } public get textFormat(): TextFormat { return this._textField.textFormat; } public applyFormat(): void { this._textField.applyFormat(); if (!this._underConstruct) this.updateSize(); } public get align(): AlignType { return this._textField.align; } public set align(value: AlignType) { this._textField.align = value; } public get verticalAlign(): VertAlignType { return this._textField.verticalAlign; } public set verticalAlign(value: VertAlignType) { this._textField.verticalAlign = value; } public get singleLine(): boolean { return this._textField.singleLine; } public set singleLine(value: boolean) { this._textField.singleLine = value; } public set ubbEnabled(value: boolean) { this._ubbEnabled = value; } public get ubbEnabled(): boolean { return this._ubbEnabled; } public get autoSize(): number { return this._textField.autoSize; } public set autoSize(value: number) { this._textField.autoSize = value; if (value == AutoSizeType.Both) { this._textField.wordWrap = false; if (!this._underConstruct) this.setSize(this._textField.textWidth, this._textField.textHeight); } else { this._textField.wordWrap = true; if (value == AutoSizeType.Height) { if (!this._underConstruct) { this._textField.width = this.width; this.height = this._textField.textHeight; } } else this._textField.setSize(this.width, this.height); } } public get textWidth(): number { return this._textField.textWidth; } public get textHeight(): number { return this._textField.textHeight; } public get color(): number { return this._textField.textFormat.color; } public set color(value: number) { if (this._textField.textFormat.color != value) { // if (this.grayed) // this._textField.color = "#AAAAAA"; // else // this._textField.color = this._color; this._textField.textFormat.color = value; this._textField.applyFormat(); this.updateGear(4); } } public getProp(index: number): any { switch (index) { case ObjectPropID.Color: return this.color; case ObjectPropID.OutlineColor: return this._textField.textFormat.outlineColor; case ObjectPropID.FontSize: return this._textField.textFormat.size; default: return super.getProp(index); } } public setProp(index: number, value: any): void { switch (index) { case ObjectPropID.Color: this.color = value; break; case ObjectPropID.OutlineColor: this._textField.textFormat.outlineColor = value; this._textField.applyFormat(); break; case ObjectPropID.FontSize: this._textField.textFormat.size = value; this._textField.applyFormat(); break; default: super.setProp(index, value); break; } } private updateSize(): void { if (this._updatingSize) return; this._updatingSize = true; if (this._textField.autoSize == AutoSizeType.Both) { this.setSize(this._textField.width, this._textField.height); } else if (this._textField.autoSize == AutoSizeType.Height) { this.height = this._textField.height; } this._updatingSize = false; } protected handleSizeChanged(): void { if (this._updatingSize) return; if (this._underConstruct) this._textField.setSize(this.width, this.height); else if (this._textField.autoSize != AutoSizeType.Both) { if (this._textField.autoSize == AutoSizeType.Height) { this._textField.width = this.width;//先调整宽度,让文本重排 if (this._text != "") //文本为空时,1是本来就不需要调整, 2是为了防止改掉文本为空时的默认高度,造成关联错误 this.setSizeDirectly(this.width, this._textField.height); } else this._textField.setSize(this.width, this.height); } } // protected handleGrayedChanged(): void { // super.handleGrayedChanged(); // if (this.grayed) // this._textField.color = "#AAAAAA"; // else // this._textField.color = this._color; // } public setup_beforeAdd(buffer: ByteBuffer, beginPos: number): void { super.setup_beforeAdd(buffer, beginPos); buffer.seek(beginPos, 5); let tf = this._textField.textFormat; tf.font = buffer.readS(); tf.size = buffer.readShort(); tf.color = buffer.readColor(); let c = buffer.readByte(); this.align = c == 0 ? "left" : (c == 1 ? "center" : "right"); c = buffer.readByte(); this.verticalAlign = c == 0 ? "top" : (c == 1 ? "middle" : "bottom"); tf.lineSpacing = buffer.readShort(); tf.letterSpacing = buffer.readShort(); this.ubbEnabled = buffer.readBool(); this.autoSize = buffer.readByte(); tf.underline = buffer.readBool(); tf.italic = buffer.readBool(); tf.bold = buffer.readBool(); this.singleLine = buffer.readBool(); if (buffer.readBool()) { tf.outlineColor = buffer.readColor(); tf.outline = buffer.readFloat() + 1; } if (buffer.readBool()) //shadow { tf.shadowColor = buffer.readColor(); let f1 = buffer.readFloat(); let f2 = buffer.readFloat(); tf.shadowOffset.set(f1, f2); } if (buffer.readBool()) this._template = {}; if (buffer.version >= 3) tf.strikethrough = buffer.readBool(); this._textField.applyFormat(); } public setup_afterAdd(buffer: ByteBuffer, beginPos: number): void { super.setup_afterAdd(buffer, beginPos); buffer.seek(beginPos, 6); var str: string = buffer.readS(); if (str != null) this.text = str; } protected parseTemplate(template: string): string { var pos1: number = 0, pos2: number, pos3: number; var tag: string; var value: string; var result: string = ""; while ((pos2 = template.indexOf("{", pos1)) != -1) { if (pos2 > 0 && template.charCodeAt(pos2 - 1) == 92)//\ { result += template.substring(pos1, pos2 - 1); result += "{"; pos1 = pos2 + 1; continue; } result += template.substring(pos1, pos2); pos1 = pos2; pos2 = template.indexOf("}", pos1); if (pos2 == -1) break; if (pos2 == pos1 + 1) { result += template.substr(pos1, 2); pos1 = pos2 + 1; continue; } tag = template.substring(pos1 + 1, pos2); pos3 = tag.indexOf("="); if (pos3 != -1) { value = this._template[tag.substring(0, pos3)]; if (value == null) result += tag.substring(pos3 + 1); else result += value; } else { value = this._template[tag]; if (value != null) result += value; } pos1 = pos2 + 1; } if (pos1 < template.length) result += template.substr(pos1); return result; } }
the_stack
import { jsx } from '@emotion/react' import React from 'react' import { components, FormatOptionLabelMeta, InputProps, OptionsType, ValueType } from 'react-select' import CreatableSelect from 'react-select/creatable' import { IndicatorContainerProps } from 'react-select/src/components/containers' import { MultiValueRemoveProps } from 'react-select/src/components/MultiValue' import { styleFn } from 'react-select/src/styles' import { last } from '../../../../../core/shared/array-utils' import { atomWithPubSub, usePubSubAtomReadOnly, usePubSubAtomWriteOnly, } from '../../../../../core/shared/atom-with-pub-sub' import { emptyComments, jsxAttributeValue } from '../../../../../core/shared/element-template' import * as PP from '../../../../../core/shared/property-path' import { getTailwindOptionForClassName, LabelWithStripes, MatchHighlighter, TailWindOption, useFilteredOptions, useGetSelectedClasses, } from '../../../../../core/tailwind/tailwind-options' import { when } from '../../../../../utils/react-conditionals' import { FlexColumn, FlexRow, InspectorSubsectionHeader, SquareButton, UNSAFE_getIconURL, useColorTheme, UtopiaTheme, } from '../../../../../uuiui' import * as EditorActions from '../../../../editor/actions/action-creators' import { useInputFocusOnCountIncrease } from '../../../../editor/hook-utils' import { applyShortcutConfigurationToDefaults, handleShortcuts, REDO_CHANGES_SHORTCUT, UNDO_CHANGES_SHORTCUT, } from '../../../../editor/shortcut-definitions' import { useEditorState, useRefEditorState } from '../../../../editor/store/store-hook' import { ExpandableIndicator } from '../../../../navigator/navigator-item/expandable-indicator' import { UIGridRow } from '../../../widgets/ui-grid-row' const IndicatorsContainer: React.FunctionComponent<IndicatorContainerProps<TailWindOption>> = () => null const MultiValueRemove: React.FunctionComponent<MultiValueRemoveProps<TailWindOption>> = ( props, ) => <div {...props.innerProps} /> const valueContainer: styleFn = (base) => ({ ...base, padding: '2px 4px', height: '100%', width: '100%', }) const container: styleFn = (base) => ({ ...base, minHeight: UtopiaTheme.layout.inputHeight.default, paddingTop: 2, paddingBottom: 2, }) const control: styleFn = () => ({ label: 'control', alignItems: 'center', backgroundColor: 'rgb(245, 245, 245)', boxSizing: 'border-box', cursor: 'default', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', position: 'relative', transition: 'all 100ms', minHeight: UtopiaTheme.layout.inputHeight.default, }) const placeholder: styleFn = (base) => ({ ...base, paddingTop: 2, paddingBottom: 2, paddingLeft: 6, paddingRight: 6, }) const menu: styleFn = (base) => ({ ...base, position: 'relative', boxShadow: 'none', borderRadius: 0, background: 'transparent', }) const AlwaysTrue = () => true let queuedDispatchTimeout: number | undefined = undefined let queuedFocusTimeout: number | undefined = undefined const focusedOptionAtom = atomWithPubSub<string | null>({ key: 'classNameSubsectionFocusedOption', defaultValue: null, }) function formatOptionLabel( { label, categories }: TailWindOption, { context, inputValue }: FormatOptionLabelMeta<TailWindOption>, ) { return context === 'menu' ? ( <MatchHighlighter text={label} searchString={inputValue} /> ) : ( <LabelWithStripes label={label} categories={categories ?? []} /> ) } function isOptionsType<T>(valueType: T | OptionsType<T>): valueType is OptionsType<T> { return Array.isArray(valueType) } function valueTypeAsArray<T>(valueType: ValueType<T>): ReadonlyArray<T> { if (valueType == null) { return [] } else if (isOptionsType(valueType)) { return valueType } else { return [valueType] } } const FooterSection = React.memo((props: { filter: string; options: Array<TailWindOption> }) => { const theme = useColorTheme() const focusedOptionValue = usePubSubAtomReadOnly(focusedOptionAtom) const focusedOption = focusedOptionValue == null ? null : props.options.find((o) => o.value === focusedOptionValue) const joinedAttributes = focusedOption?.attributes?.join(', ') const attributesText = joinedAttributes == null || joinedAttributes === '' ? '\u00a0' : `Sets: ${joinedAttributes}` return ( <div css={{ label: 'focusedElementMetadata', overflow: 'hidden', boxShadow: `inset 0px 1px 1px 0px ${theme.neutralInvertedBackground.o(10).value}`, padding: '8px 8px', fontSize: '10px', pointerEvents: 'none', color: theme.textColor.value, }} > <FlexColumn> <FlexRow> <span> <MatchHighlighter text={attributesText} searchString={props.filter} /> </span> </FlexRow> </FlexColumn> </div> ) }) const Input = (props: InputProps) => { const value = (props as any).value const isHidden = value.length !== 0 ? false : props.isHidden return <components.Input {...props} isHidden={isHidden} /> } const ClassNameControl = React.memo(() => { const editorStoreRef = useRefEditorState((store) => store) const theme = useColorTheme() const targets = useEditorState( (store) => store.editor.selectedViews, 'ClassNameSubsection targets', ) const dispatch = useEditorState((store) => store.dispatch, 'ClassNameSubsection dispatch') const [filter, setFilter] = React.useState('') const isFocusedRef = React.useRef(false) const shouldPreviewOnFocusRef = React.useRef(false) const updateFocusedOption = usePubSubAtomWriteOnly(focusedOptionAtom) const focusedValueRef = React.useRef<string | null>(null) const focusTriggerCount = useEditorState( (store) => store.editor.inspector.classnameFocusCounter, 'ClassNameSubsection classnameFocusCounter', ) const inputRef = useInputFocusOnCountIncrease<CreatableSelect<TailWindOption>>(focusTriggerCount) const clearFocusedOption = React.useCallback(() => { shouldPreviewOnFocusRef.current = false updateFocusedOption(null) dispatch([EditorActions.clearTransientProps()], 'canvas') }, [updateFocusedOption, dispatch]) const onBlur = React.useCallback(() => { isFocusedRef.current = false shouldPreviewOnFocusRef.current = false clearFocusedOption() }, [clearFocusedOption]) const onFocus = React.useCallback(() => { isFocusedRef.current = true }, []) const options = useFilteredOptions(filter, 100) React.useEffect(() => { return function cleanup() { dispatch([EditorActions.clearTransientProps()], 'canvas') } /** deps is explicitly empty */ // eslint-disable-next-line react-hooks/exhaustive-deps }, []) const { selectedClasses, elementPaths, isSettable } = useGetSelectedClasses() const selectedOptions = selectedClasses.map(getTailwindOptionForClassName) const elementPath = elementPaths[0] const isMenuEnabled = isSettable && elementPaths.length === 1 const selectedOptionsLength = selectedOptions?.length ?? 0 const [isExpanded, setIsExpanded] = React.useState(selectedOptionsLength > 0) const expandSection = React.useCallback(() => { setIsExpanded(true) queuedFocusTimeout = window.setTimeout(() => inputRef.current?.focus(), 0) }, [inputRef]) const contractSection = React.useCallback(() => { setIsExpanded(false) if (queuedFocusTimeout != null) { window.clearTimeout(queuedFocusTimeout) } }, []) const toggleIsExpanded = React.useCallback(() => { if (isExpanded) { contractSection() } else { expandSection() } }, [isExpanded, expandSection, contractSection]) const triggerCountRef = React.useRef(focusTriggerCount) React.useEffect(() => { if (!isExpanded && focusTriggerCount > triggerCountRef.current) { triggerCountRef.current = focusTriggerCount expandSection() } }, [focusTriggerCount, isExpanded, expandSection]) const onChange = React.useCallback( (newValueType: ValueType<TailWindOption>) => { // As the value of the dropdown is changing, hide the selection // controls so they can see the results of what they're doing. EditorActions.hideAndShowSelectionControls(dispatch) const newValue = valueTypeAsArray(newValueType) if (elementPath != null) { if (queuedDispatchTimeout != null) { window.clearTimeout(queuedDispatchTimeout) queuedDispatchTimeout = undefined } dispatch( [ EditorActions.setProp_UNSAFE( elementPath, PP.create(['className']), jsxAttributeValue(newValue.map((value) => value.value).join(' '), emptyComments), ), EditorActions.clearTransientProps(), ], 'everyone', ) } }, [dispatch, elementPath], ) const onInputChange = React.useCallback( (newInput) => { if (newInput === '') { clearFocusedOption() } focusedValueRef.current = null setFilter(newInput) }, [clearFocusedOption, setFilter], ) const handleKeyDown = React.useCallback( (event: React.KeyboardEvent<HTMLElement>) => { // As someone is typing, hide the selection // controls so they can see the results of what they're doing. EditorActions.hideAndShowSelectionControls(dispatch) const shouldStopPreviewing = filter === '' && (event.key === 'ArrowLeft' || event.key === 'ArrowRight') if (shouldStopPreviewing) { clearFocusedOption() } else { shouldPreviewOnFocusRef.current = true } if ( event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.key === 'PageUp' || event.key === 'PageDown' || event.key === 'Home' || event.key === 'End' ) { // Any of these keys will jump the focus to the menu focusedValueRef.current = null } if ( filter === '' && selectedOptions != null && (event.key === 'Backspace' || event.key === 'Delete') ) { if (event.key === 'Delete' && focusedValueRef.current == null) { // prevent the default react-select behaviour here, as it will delete the last value // if nothing is focused, which feels wrong event.preventDefault() } else { const updatedFilterText = focusedValueRef.current ?? last(selectedOptions)?.label if (updatedFilterText != null) { setFilter(updatedFilterText) } } } if (event.key === 'Escape') { inputRef.current?.blur() } const namesByKey = applyShortcutConfigurationToDefaults( editorStoreRef.current.userState.shortcutConfig, ) handleShortcuts(namesByKey, event.nativeEvent, null, { [UNDO_CHANGES_SHORTCUT]: () => { return dispatch([EditorActions.undo()]) }, [REDO_CHANGES_SHORTCUT]: () => { return dispatch([EditorActions.redo()]) }, }) }, [clearFocusedOption, dispatch, editorStoreRef, filter, inputRef, selectedOptions], ) const multiValueLabel: styleFn = React.useCallback( (base, { isFocused }) => { const enabledColor = isFocused ? theme.inverted.textColor.value : theme.inverted.primary.value const color = isMenuEnabled ? enabledColor : theme.fg8.value const backgroundColor = isFocused ? theme.inverted.primary.value : theme.bg1.value return { ...base, label: 'multiValueLabel', display: 'flex', alignItems: 'center', paddingTop: 2, paddingBottom: 2, paddingLeft: 6, paddingRight: 0, fontSize: 9, borderRadius: 3, color: color, backgroundColor: backgroundColor, } }, [isMenuEnabled, theme], ) const multiValueRemove: styleFn = React.useCallback( (base, state) => ({ label: 'multiValueRemove', width: isMenuEnabled ? 16 : 0, height: UtopiaTheme.layout.inputHeight.small, display: 'flex', alignItems: 'center', padding: 0, overflow: 'hidden', marginRight: 2, backgroundImage: `url(${ (state.isFocused as boolean) ? UNSAFE_getIconURL('cross-in-translucent-circle', 'blue') : UNSAFE_getIconURL('cross-small') })`, backgroundSize: 16, backgroundPosition: 'center center', ':hover': { backgroundImage: `url(${UNSAFE_getIconURL('cross-in-translucent-circle', 'blue')})`, }, }), [isMenuEnabled], ) const multiValue: styleFn = React.useCallback( (base, { isFocused, data }) => { const backgroundColor = isFocused ? theme.inverted.primary.value : theme.bg1.value if (isFocused) { focusedValueRef.current = data.label } return { label: 'multiValue', fontWeight: 600, color: theme.emphasizedForeground.value, borderRadius: UtopiaTheme.inputBorderRadius, display: 'flex', marginRight: 4, marginTop: 2, marginBottom: 2, minWidth: 0, height: UtopiaTheme.layout.inputHeight.small, boxShadow: `inset 0 0 0 1px ${ isFocused ? theme.inspectorFocusedColor.value : 'transparent' }`, overflow: 'hidden', backgroundColor: backgroundColor, } }, [theme], ) const option: styleFn = React.useCallback( (base, { isFocused, isDisabled, value }) => { if ( isFocusedRef.current && shouldPreviewOnFocusRef.current && isFocused && targets.length === 1 ) { const oldClassNameString = selectedOptions == null ? '' : selectedOptions.map((v) => v.value).join(' ') + ' ' const newClassNameString = oldClassNameString + value if (queuedDispatchTimeout != null) { window.clearTimeout(queuedDispatchTimeout) } queuedDispatchTimeout = window.setTimeout(() => { dispatch( [ EditorActions.setPropTransient( targets[0], PP.create(['className']), jsxAttributeValue(newClassNameString, emptyComments), ), ], 'canvas', ) }, 10) updateFocusedOption(value) } const color = isFocused ? theme.inverted.textColor.value : theme.textColor.value const backgroundColor = isFocused ? theme.inverted.primary.value : theme.bg1.value const borderRadius = isFocused ? 3 : 0 return { minHeight: 27, display: 'flex', alignItems: 'center', paddingLeft: 8, paddingRight: 8, backgroundColor: backgroundColor, color: color, cursor: isDisabled ? 'not-allowed' : 'default', borderRadius: borderRadius, } // return base }, [dispatch, targets, selectedOptions, updateFocusedOption, theme], ) return ( <div style={{ backgroundColor: theme.emphasizedBackground.value, boxShadow: `0px 0px 1px 0px ${theme.neutralInvertedBackground.o(30).value}`, margin: 4, }} > <InspectorSubsectionHeader style={{ color: theme.primary.value }}> <span style={{ flexGrow: 1, cursor: 'pointer' }} onClick={toggleIsExpanded}> Class Names </span> <SquareButton highlight onClick={toggleIsExpanded}> <ExpandableIndicator visible collapsed={!isExpanded} selected={false} /> </SquareButton> </InspectorSubsectionHeader> {when( isExpanded, <React.Fragment> <UIGridRow padded variant='<-------------1fr------------->'> <CreatableSelect ref={inputRef} autoFocus={false} placeholder={isMenuEnabled ? 'Add class…' : ''} isMulti value={selectedOptions} isDisabled={!isMenuEnabled} onChange={onChange} onInputChange={onInputChange} components={{ IndicatorsContainer, Input, MultiValueRemove, }} className='className-inspector-control' styles={{ container, control, valueContainer, multiValue, multiValueLabel, multiValueRemove, placeholder, menu, option, }} filterOption={AlwaysTrue} options={options} menuIsOpen={isMenuEnabled} onBlur={onBlur} onFocus={onFocus} escapeClearsValue={true} formatOptionLabel={formatOptionLabel} onKeyDown={handleKeyDown} maxMenuHeight={199} inputValue={filter} /> </UIGridRow> {when(isMenuEnabled, <FooterSection options={options} filter={filter} />)} </React.Fragment>, )} </div> ) }) export const ClassNameSubsection = React.memo(() => { return <ClassNameControl /> })
the_stack
import * as React from 'react'; import { View, Text, ScrollView as NativeScrollView, FlatList as NativeFlatList, FlatListProps, findNodeHandle, Pressable, } from 'react-native'; import type { ComponentProps, MutableRefObject, LegacyRef, ReactNode, RefObject, RefCallback, } from 'react'; const { createContext, forwardRef, useContext, useMemo, useRef, useImperativeHandle, } = React; // from react-merge-refs (avoid dependency) function mergeRefs<T = any>( refs: Array<MutableRefObject<T> | LegacyRef<T>> ): RefCallback<T> { return (value) => { refs.forEach((ref) => { if (typeof ref === 'function') { ref(value); } else if (ref != null) { (ref as MutableRefObject<T | null>).current = value; } }); }; } // type Props<Anchors extends readonly string[]> = { // anchors: Anchors; // }; type Unpromisify<T> = T extends Promise<infer R> ? R : T; /** * The following is taken/edited from `useScrollToTop` from `@react-navigation/native` */ type ScrollOptions = { y?: number; animated?: boolean }; type ScrollableView = | { scrollToTop(): void } | { scrollTo(options: ScrollOptions): void } | { scrollToOffset(options: { offset?: number; animated?: boolean }): void } | { scrollResponderScrollTo(options: ScrollOptions): void }; type ScrollableWrapper = | { getScrollResponder(): ReactNode } | { getNode(): ScrollableView } | ScrollableView; function getScrollableNode(ref: RefObject<ScrollableWrapper>) { if (ref.current == null) { return null; } if ( 'scrollTo' in ref.current || 'scrollToOffset' in ref.current || 'scrollResponderScrollTo' in ref.current ) { // This is already a scrollable node. return ref.current; } else if ('getScrollResponder' in ref.current) { // If the view is a wrapper like FlatList, SectionList etc. // We need to use `getScrollResponder` to get access to the scroll responder return ref.current.getScrollResponder(); } else if ('getNode' in ref.current) { // When a `ScrollView` is wraped in `Animated.createAnimatedComponent` // we need to use `getNode` to get the ref to the actual scrollview. // Note that `getNode` is deprecated in newer versions of react-native // this is why we check if we already have a scrollable node above. return ref.current.getNode(); } else { return ref.current; } } /** * End of react-navigation code. */ type ScrollToOptions = { animated?: boolean; /** * A number that determines how far from the content you want to scroll. * * Default: `-10`, which means it scrolls to 10 pixels before the content. */ offset?: number; /** * If you're using a `ScrollView` or `FlatList` imported from this library, you can ignore this field. */ // horizontal?: boolean; }; export interface Anchors {} export type AnchorsRef = { scrollTo: ( name: Anchor, options?: ScrollToOptions ) => Promise<{ success: true } | { success: false; message: string }>; }; /** * If you need to control a `ScrollView` or `FlatList` from outside of their scope: * * ```jsx * import React from 'react' * import { useAnchors, ScrollView } from '@nandorojo/anchor' * * export default function App() { * const anchors = useAnchors() * * const onPress = () => { * anchors.current?.scrollTo('list') * } * * return ( * <ScrollView anchors={anchors}> * <Target name="list" /> * </ScrollView> * ) * } * ``` */ const useAnchors = () => { const ref = useRef<AnchorsRef>(null); return ref; }; // @ts-expect-error type Anchor = Anchors['anchor'] extends string ? Anchors['anchor'] : string; // export default function createAnchors() { type AnchorsContext = { targetRefs: RefObject<Record<Anchor, View | Text>>; scrollRef: RefObject<ScrollableWrapper>; registerTargetRef: (name: Anchor, ref: View | Text) => void; registerScrollRef: (ref: ScrollableWrapper | null) => void; horizontal: ComponentProps<typeof NativeScrollView>['horizontal']; scrollTo: AnchorsRef['scrollTo']; }; const AnchorsContext = createContext<AnchorsContext>({ targetRefs: { current: {} as any, }, scrollRef: { current: null as any, }, registerTargetRef: () => { // no-op }, registerScrollRef: () => { // no-op }, horizontal: false, scrollTo: () => { return new Promise((resolve) => resolve({ success: false, message: 'Missing @nandorojo/anchor provider.', }) ); }, }); const useAnchorsContext = () => useContext(AnchorsContext); const useCreateAnchorsContext = ({ horizontal, }: Pick<AnchorsContext, 'horizontal'>): AnchorsContext => { const targetRefs = useRef<Record<string, View>>({}); const scrollRef = useRef<ScrollableWrapper>(); return useMemo(() => { return { targetRefs, scrollRef: scrollRef as RefObject<ScrollableWrapper>, registerTargetRef: (target, ref) => { targetRefs.current = { ...targetRefs.current, [target]: ref, }; }, registerScrollRef: (ref) => { if (ref) { scrollRef.current = ref; } }, horizontal, scrollTo: ( name: Anchor, { animated = true, offset = -10 }: ScrollToOptions = {} ) => { return new Promise< { success: true } | { success: false; message: string } >((resolve) => { const node = scrollRef.current && findNodeHandle(scrollRef.current as any); if (!node) { return resolve({ success: false, message: 'Scroll ref does not exist. Will not scroll to view.', }); } if (!targetRefs.current?.[name]) { resolve({ success: false, message: 'Anchor ref ' + name + ' does not exist. It will not scroll. Please make sure to use the ScrollView provided by @nandorojo/anchors, or use the registerScrollRef function for your own ScrollView.', }); } targetRefs.current?.[name].measureLayout( node, (left, top) => { requestAnimationFrame(() => { const scrollY = top; const scrollX = left; const scrollable = getScrollableNode( scrollRef as RefObject<ScrollableWrapper> ) as ScrollableWrapper; let scrollTo = horizontal ? scrollX : scrollY; scrollTo += offset; scrollTo = Math.max(scrollTo, 0); const key = horizontal ? 'x' : 'y'; if ('scrollTo' in scrollable) { scrollable.scrollTo({ [key]: scrollTo, animated, }); } else if ('scrollToOffset' in scrollable) { scrollable.scrollToOffset({ offset: scrollTo, animated, }); } else if ('scrollResponderScrollTo' in scrollable) { scrollable.scrollResponderScrollTo({ [key]: scrollTo, animated, }); } resolve({ success: true }); }); }, () => { resolve({ success: false, message: 'Failed to measure target node.', }); } ); }); }, }; }, [horizontal]); }; function useRegisterTarget() { const { registerTargetRef } = useAnchorsContext(); return useMemo( () => ({ register: (name: Anchor) => { return (ref: View) => registerTargetRef(name, ref); }, }), [registerTargetRef] ); } function useScrollTo() { const { scrollTo } = useAnchorsContext(); return useMemo( () => ({ scrollTo, // scrollTo: ( // name: Anchor, // { animated = true, offset = -10 }: ScrollToOptions = {} // ) => { // return new Promise< // { success: true } | { success: false; message: string } // >((resolve) => { // const node = // scrollRef.current && findNodeHandle(scrollRef.current as any); // if (!node) { // return resolve({ // success: false, // message: 'Scroll ref does not exist. Will not scroll to view.', // }); // } // if (!targetRefs.current?.[name]) { // resolve({ // success: false, // message: // 'Anchor ref ' + // name + // ' does not exist. It will not scroll. Please make sure to use the ScrollView provided by @nandorojo/anchors, or use the registerScrollRef function for your own ScrollView.', // }); // } // targetRefs.current?.[name].measureLayout( // node, // (left, top) => { // requestAnimationFrame(() => { // const scrollY = top; // const scrollX = left; // const scrollable = getScrollableNode( // scrollRef // ) as ScrollableWrapper; // let scrollTo = horizontal ? scrollX : scrollY; // scrollTo += offset; // scrollTo = Math.max(scrollTo, 0); // const key = horizontal ? 'x' : 'y'; // if ('scrollTo' in scrollable) { // scrollable.scrollTo({ // [key]: scrollTo, // animated, // }); // } else if ('scrollToOffset' in scrollable) { // scrollable.scrollToOffset({ // offset: scrollTo, // animated, // }); // } else if ('scrollResponderScrollTo' in scrollable) { // scrollable.scrollResponderScrollTo({ // [key]: scrollTo, // animated, // }); // } // resolve({ success: true }); // }); // }, // () => { // resolve({ // success: false, // message: 'Failed to measure target node.', // }); // } // ); // }); // }, }), [scrollTo] ); } function useRegisterScroller() { const { registerScrollRef } = useAnchorsContext(); return { registerScrollRef }; } function AnchorProvider({ children, horizontal, anchors, }: { children: ReactNode; anchors?: RefObject<AnchorsRef> } & Pick< AnchorsContext, 'horizontal' >) { const value = useCreateAnchorsContext({ horizontal }); useImperativeHandle(anchors, () => ({ scrollTo: (...props) => { return value.scrollTo(...props); }, })); return ( <AnchorsContext.Provider value={value}>{children}</AnchorsContext.Provider> ); } /** * Identical to the normal React Native `ScrollView`, except that it allows scrolling to anchor links. * * If you use this component, you don't need to use the `AnchorProvider`. It implements it for you. */ const ScrollView = forwardRef< NativeScrollView, ComponentProps<typeof NativeScrollView> & { children?: ReactNode; } & Pick<ComponentProps<typeof AnchorProvider>, 'anchors'> >(function ScrollView({ horizontal = false, anchors, ...props }, ref) { return ( <AnchorProvider anchors={anchors} horizontal={horizontal}> <AnchorsContext.Consumer> {({ registerScrollRef }) => ( <NativeScrollView horizontal={horizontal} {...props} ref={mergeRefs([registerScrollRef, ref])} /> )} </AnchorsContext.Consumer> </AnchorProvider> ); }); /** * Identical to the normal React Native flatlist, except that it allows scrolling to anchor links. * * If you use this component, you don't need to use the `AnchorProvider`. * * One important difference: if you want to use the `ref`, pass it to `flatListRef` instead of `ref`. */ function FlatList<T = any>({ flatListRef, horizontal = false, anchors, ...props }: FlatListProps<T> & { flatListRef?: RefObject<NativeFlatList> } & Pick< ComponentProps<typeof AnchorProvider>, 'anchors' >) { return ( <AnchorProvider anchors={anchors} horizontal={horizontal}> <AnchorsContext.Consumer> {({ registerScrollRef }) => ( <NativeFlatList {...props} horizontal={horizontal} ref={mergeRefs([registerScrollRef, flatListRef || null])} /> )} </AnchorsContext.Consumer> </AnchorProvider> ); } function ScrollTo({ target, onPress, options, onRequestScrollTo, ...props }: { children?: ReactNode; target: Anchor; options?: ScrollToOptions; onRequestScrollTo?: ( props: Unpromisify<ReturnType<ReturnType<typeof useScrollTo>['scrollTo']>> ) => void; } & ComponentProps<typeof Pressable>) { const { scrollTo } = useScrollTo(); return ( <Pressable {...props} onPress={async (e) => { onPress?.(e); const result = await scrollTo(target, options); onRequestScrollTo?.(result); }} /> ); } const Target = forwardRef< View, { name: Anchor; children?: ReactNode } & ComponentProps<typeof View> >(function Target({ name, ...props }, ref) { const { register } = useRegisterTarget(); return <View {...props} ref={mergeRefs([register(name), ref])} />; }); export { AnchorProvider, ScrollView, FlatList, useRegisterTarget, useScrollTo, ScrollTo, Target, ScrollTo as Anchor, useRegisterScroller, useAnchors, }; // }
the_stack
import * as Net from 'net'; import * as IPCPluginMessages from '../../../../common/ipc/plugins.ipc.messages/index'; import * as Tools from '../../tools/index'; import { ChildProcess, fork } from 'child_process'; import { Emitter, Subscription } from '../../tools/index'; import { CStdoutSocketAliases } from '../../consts/controller.plugin.process'; import Logger from '../../tools/env.logger'; import ControllerIPCPlugin from './plugin.process.ipc'; import ServiceProduction from '../../services/service.production'; import ServicePaths from '../../services/service.paths'; export const CFirstDebugPort = 9240; export const CDebugPortSeqName = 'plugin_debug_ports'; const CSettings = { resolverTimeout: 3000, }; interface IConnection { socket: Net.Socket; file: string; } interface IOpt { id: number; name: string; entrypoint: string; token: string; } const CPluginStartTimeout = 10000; /** * @class ControllerPluginProcessSingle * @description Execute plugin node process and provide access to it */ export default class ControllerPluginProcessSingle extends Emitter { public static Events = { close: Symbol(), disconnect: Symbol(), error: Symbol(), output: Symbol(), }; private _logger: Logger; private _opt: IOpt; private _process: ChildProcess | undefined; private _ipc: ControllerIPCPlugin | undefined; private _connections: Map<string, IConnection> = new Map(); private _subscriptions: { [key: string]: Subscription } = {}; private _resolvers: { bind: Map<string, () => void>, unbind: Map<string, () => void>, } = { bind: new Map(), unbind: new Map(), }; private _stderr: string = ''; private _rejector?: (error: Error) => void; private _resolver?: () => void; constructor(opt: IOpt) { super(); this._opt = opt; this._logger = new Logger(`Plugin: ${this._opt.name}`); this._onSTDErr = this._onSTDErr.bind(this); this._onSTDOut = this._onSTDOut.bind(this); this._onClose = this._onClose.bind(this); this._onError = this._onError.bind(this); this._onDisconnect = this._onDisconnect.bind(this); } /** * Attempt to fork plugin process * @returns { Promise<void> } */ public attach(): Promise<void> { return new Promise((resolve, reject) => { // Store rejector this._rejector = reject; this._resolver = resolve; // Prepare arguments const args: string[] = [ `--chipmunk-settingspath=${ServicePaths.getPluginsCfgFolder()}`, `--chipmunk-plugin-alias=${this._opt.name.replace(/[^\d\w-_]/gi, '_')}`, ]; if (!ServiceProduction.isProduction()) { args.push(`--inspect=127.0.0.1:${Tools.getSequence(CDebugPortSeqName, CFirstDebugPort)}`); } this._process = fork( this._opt.entrypoint, args, { stdio: [ 'pipe', // stdin - doesn't used by parent process 'pipe', // stdout - listened by parent process. Whole output from it goes to logs of parent process 'pipe', // stderr - listened by parent process. Whole output from it goes to logs of parent process 'ipc', // ipc - used by parent process as command sender / reciever ]}); // Getting data events this._process.stderr?.on('data', this._onSTDErr); this._process.stdout?.on('data', this._onSTDOut); // State process events this._process.on('exit', this._onClose); this._process.on('close', this._onClose); this._process.on('error', this._onError); this._process.on('disconnect', this._onDisconnect); // Create IPC controller const ipc = new ControllerIPCPlugin(this._opt.name, this._process, this._opt.token); // Subscribe to state event let subscription: Subscription | undefined; ipc.subscribe(IPCPluginMessages.PluginState, (state: IPCPluginMessages.PluginState) => { if (subscription !== undefined) { subscription.destroy(); } if (state.state !== IPCPluginMessages.EPluginState.ready) { return this._reject(new Error(this._logger.error(`Fail to attach plugin, because plugin state is: ${state.state}`))); } // Send token ipc.send(new IPCPluginMessages.PluginToken({ token: this._opt.token, id: this._opt.id, })).then(() => { Promise.all([ ipc.subscribe(IPCPluginMessages.SessionStreamBound, this._onSessionStreamBound.bind(this)).then((_subscription: Subscription) => { this._subscriptions.SessionStreamBound = _subscription; }), ipc.subscribe(IPCPluginMessages.SessionStreamUnbound, this._onSessionStreamUnbound.bind(this)).then((_subscription: Subscription) => { this._subscriptions.SessionStreamUnbound = _subscription; }), ]).then(() => { this._ipc = ipc; this._resolve(); }).catch((error: Error) => { this._reject(new Error(this._logger.warn(`Fail to subscribe to plugin's IPC events due error: ${error.message}`))); }); }).catch((sendingError: Error) => { this._reject(new Error(this._logger.error(`Fail delivery plugin token due error: ${sendingError.message}`))); }); }).then((_subscription: Subscription) => { subscription = _subscription; setTimeout(() => { if (this._rejector !== undefined) { this._reject(new Error(this._logger.error(`Fail to start plugin because timeout.`))); } }, CPluginStartTimeout); }).catch((error: Error) => { this._reject(new Error(this._logger.warn(`Fail to subscribe to plugin's state event due error: ${error.message}`))); }); }); } /** * Returns IPC controller of plugin * @returns { Promise<void> } */ public getIPC(): ControllerIPCPlugin | Error { if (this._ipc === undefined) { return new Error(`IPC controller isn't initialized.`); } return this._ipc; } /** * Attempt to kill plugin process * @returns void */ public kill(signal: NodeJS.Signals = 'SIGTERM'): boolean { Object.keys(this._subscriptions).forEach((key: string) => { this._subscriptions[key].destroy(); }); if (this._ipc !== undefined) { this._ipc.destroy(); } if (this._process !== undefined) { if (!this._process.killed) { this._process.kill(signal); } this._process = undefined; this._connections.clear(); } return true; } public bindStream(guid: string, connection: IConnection): Promise<void> { return new Promise((resolve, reject) => { if (this._process === undefined) { return reject(new Error(this._logger.warn(`Attempt to bind stream to plugin, which doesn't attached. Stream GUID: ${guid}.`))); } if (this._connections.has(guid)) { return reject(new Error(this._logger.warn(`Plugin process is already bound with stream "${guid}"`))); } this._logger.debug(`Sent information about stream GUID: ${guid}.`); // Bind socket this._bindRefWithId(connection.socket).then(() => { if (this._process === undefined) { return reject(new Error(this._logger.warn(`Fail to bind stream to plugin, which doesn't attached. Stream GUID: ${guid}.`))); } this._connections.set(guid, connection); // Send socket to plugin process if (process.platform === 'win32') { // Passing sockets is not supported on Windows. this._process.send(`${CStdoutSocketAliases.bind}${guid};${connection.file}`); } else { // On all other platforms we can pass socket this._process.send(`${CStdoutSocketAliases.bind}${guid};${connection.file}`, connection.socket); } this._setBindResolver(guid, resolve); }).catch(reject); }); } public unbindStream(guid: string): Promise<void> { return new Promise((resolve) => { if (this._process === undefined) { this._logger.warn(`Attempt to unbind stream to plugin, which doesn't attached. Stream GUID: ${guid}.`); return resolve(); } if (!this._connections.has(guid)) { this._logger.warn(`Plugin process is already unbound from stream "${guid}" or it wasn't bound at all, because plugin doesn't listen "openStream" event`); return resolve(); } this._connections.delete(guid); // Passing sockets is not supported on Windows. this._process.send(`${CStdoutSocketAliases.unbind}${guid}`); this._setUnbindResolver(guid, resolve); }); } public isAttached(): boolean { return this._process !== undefined; } private _reject(error: Error) { if (this._rejector === undefined || this._resolver === undefined) { return; } this.kill(); this._rejector(error); this._rejector = undefined; this._resolver = undefined; } private _resolve() { if (this._rejector === undefined || this._resolver === undefined) { return; } this._resolver(); this._rejector = undefined; this._resolver = undefined; } private _bindRefWithId(socket: Net.Socket): Promise<void> { return new Promise((resolve, reject) => { socket.write(`[plugin:${this._opt.id}]`, (error: Error | undefined) => { if (error) { return reject(new Error(this._logger.error(`Cannot send binding message into socket due error: ${error.message}`))); } resolve(); }); }); } private _setBindResolver(guid: string, resolver: () => void) { this._resolvers.bind.set(guid, resolver); setTimeout(this._applyBindResolver.bind(this, guid), CSettings.resolverTimeout); } private _setUnbindResolver(guid: string, resolver: () => void) { this._resolvers.unbind.set(guid, resolver); setTimeout(this._applyUnbindResolver.bind(this, guid), CSettings.resolverTimeout); } private _applyBindResolver(guid: string) { const resolver = this._resolvers.bind.get(guid); if (resolver === undefined) { return; } resolver(); this._resolvers.bind.delete(guid); } private _applyUnbindResolver(guid: string) { const resolver = this._resolvers.unbind.get(guid); if (resolver === undefined) { return; } resolver(); this._resolvers.bind.delete(guid); } /** * Handler to listen stdout and stderr of plugin process * @returns void */ private _onSTDOut(chunk: Buffer): void { const str: string = chunk.toString(); this._logger.save(this._opt.token, str); this.emit(ControllerPluginProcessSingle.Events.output); } /** * Handler to listen stdout and stderr of plugin process * @returns void */ private _onSTDErr(chunk: Buffer): void { const str: string = chunk.toString(); this._logger.save(this._opt.token, str); this._stderr += str; } /** * Handler to listen close event of process * @returns void */ private _onClose(...args: any[]): void { this.kill(); this.emit(ControllerPluginProcessSingle.Events.close, ...args); } /** * Handler to listen error event of process * @returns void */ private _onError(...args: any[]): void { this.kill(); this.emit(ControllerPluginProcessSingle.Events.error, ...args); } /** * Handler to listen disconnect event of process * @returns void */ private _onDisconnect(...args: any[]): void { this.kill(); this.emit(ControllerPluginProcessSingle.Events.disconnect, ...args); this._reject(new Error(this._stderr)); } private _onSessionStreamBound(message: IPCPluginMessages.SessionStreamBound) { if (message.error) { this._logger.warn(`Fail to bind stream due error: ${message.error}`); } this._applyBindResolver(message.streamId); } private _onSessionStreamUnbound(message: IPCPluginMessages.SessionStreamUnbound) { if (message.error) { this._logger.warn(`Fail to unbind stream due error: ${message.error}`); } this._applyUnbindResolver(message.streamId); } }
the_stack
import { ReportOptions, ConstraintKey, Constraint } from "./types"; import { normaliseQuery } from "./utils"; import { enums } from "./protos"; import { QueryError, buildSelectClause, buildFromClause, validateConstraintKeyAndValue, convertNumericEnumToString, extractConstraintConditions, extractDateConstantConditions, extractDateConditions, buildWhereClause, buildLimitClause, completeOrderly, buildOrderClauseOld, buildOrderClauseNew, buildRequestOptions, buildQuery, } from "./query"; const options: ReportOptions = { entity: "ad_group", attributes: ["ad_group.name", "ad_group.id"], metrics: ["metrics.impressions", "metrics.cost_micros"], segments: ["segments.date"], constraints: [ { key: "ad_group.status", op: "=", val: enums.AdGroupStatus.PAUSED, }, { "campaign.advertising_channel_type": enums.AdvertisingChannelType.SEARCH, }, { key: "metrics.clicks", op: ">", val: 10 }, ], date_constant: "LAST_BUSINESS_WEEK", from_date: "2020-01-01", to_date: "2020-03-01", order_by: "metrics.impressions", sort_order: "ASC", limit: 10, page_size: 5, page_token: "A1B2C3D4", validate_only: false, summary_row_setting: "NO_SUMMARY_ROW", }; describe("buildSelectClause", () => { it("throws if attributes, metrics and segments are undefined", () => { expect(() => buildSelectClause(undefined, undefined, undefined) ).toThrowError(QueryError.MISSING_FIELDS); }); it("throws if attributes, metrics and segments are empty", () => { expect(() => buildSelectClause([], [], [])).toThrowError( QueryError.MISSING_FIELDS ); }); it("correctly parses attributes, metrics and segments", () => { const selectClause = buildSelectClause( options.attributes, options.metrics, options.segments ); expect(selectClause).toEqual( `SELECT ad_group.name, ad_group.id, metrics.impressions, metrics.cost_micros, segments.date` ); }); it("parses any combination of attributes, metrics and segments", () => { expect(() => { buildSelectClause(options.attributes, undefined, undefined); buildSelectClause(undefined, options.metrics, undefined); buildSelectClause(undefined, undefined, options.segments); buildSelectClause(options.attributes, options.metrics, undefined); buildSelectClause(options.attributes, undefined, options.segments); buildSelectClause(undefined, options.metrics, options.segments); }).not.toThrowError(); }); }); describe("buildFromClause", () => { it("throws if the entity undefined", () => { // @ts-ignore expect(() => buildFromClause(undefined)).toThrowError( QueryError.UNDEFINED_ENTITY ); }); it("correctly parses entity", () => { const fromClause = buildFromClause(options.entity); expect(fromClause).toEqual(` FROM ad_group`); }); }); describe("validateConstraintKeyAndValue", () => { const key = "test_key" as ConstraintKey; it("throws for bad constraint value types", () => { const constraintValues = [ {}, undefined, null, () => { return; }, ]; constraintValues.forEach((val) => { // @ts-ignore expect(() => validateConstraintKeyAndValue(key, "=", val)).toThrowError( // @ts-ignore QueryError.INVALID_CONSTRAINT_VALUE(key, val) ); }); }); it("does not throw for an empty string val", () => { expect(() => validateConstraintKeyAndValue(key, "!=", "") ).not.toThrowError(); const validatedValue = validateConstraintKeyAndValue(key, "!=", ""); expect(validatedValue.op).toEqual("="); expect(validatedValue.val).toEqual('""'); }); it("returns numbers and booleans as original", () => { const constraintValues = [15, true, -20, false]; constraintValues.forEach((val) => { const validatedValue = validateConstraintKeyAndValue(key, "!=", val); expect(validatedValue.op).toEqual("="); expect(validatedValue.val).toEqual(val); }); }); it("returns arrays as strings", () => { const val1 = [1, 2, 3, 4]; const validatedValue1 = validateConstraintKeyAndValue(key, "!=", val1); expect(validatedValue1.op).toEqual("IN"); expect(validatedValue1.val).toEqual(`(1, 2, 3, 4)`); const val2 = ["a", "b", "c", "d"]; const validatedValue2 = validateConstraintKeyAndValue(key, "!=", val2); expect(validatedValue2.op).toEqual("IN"); expect(validatedValue2.val).toEqual(`("a", "b", "c", "d")`); }); it("adds quotation marks to string constraints that do not already have them", () => { const val = enums.AdvertisingChannelType.SEARCH; const validatedValue = validateConstraintKeyAndValue(key, "!=", val); expect(validatedValue.op).toEqual("="); expect(validatedValue.val).toEqual(enums.AdvertisingChannelType.SEARCH); }); it("returns string constraints that already have quotation marks", () => { const val1 = `'SEARCH'`; const validatedValue1 = validateConstraintKeyAndValue(key, "!=", val1); expect(validatedValue1.op).toEqual("="); expect(validatedValue1.val).toEqual(val1); const val2 = `"SEARCH"`; const validatedValue2 = validateConstraintKeyAndValue(key, "!=", val2); expect(validatedValue2.op).toEqual("="); expect(validatedValue2.val).toEqual(val2); }); it("returns date constants without quotation marks", () => { const val1 = `LAST_30_DAYS`; const validatedValue1 = validateConstraintKeyAndValue(key, "DURING", val1); expect(validatedValue1.op).toEqual("DURING"); expect(validatedValue1.val).toEqual(val1); const val2 = `YESTERDAY`; const validatedValue2 = validateConstraintKeyAndValue(key, "DURING", val2); expect(validatedValue2.op).toEqual("DURING"); expect(validatedValue2.val).toEqual(val2); }); }); describe("convertNumericEnumToString", () => { it("returns strings and booleans as they are", () => { const fieldValues = ["string value", true, false]; fieldValues.forEach((val) => { expect(convertNumericEnumToString("campaign.status", val)).toEqual(val); }); }); it("returns numeric enums as their string counterparts", () => { const val = convertNumericEnumToString( "campaign.status", enums.CampaignStatus.ENABLED ); // 2 expect(val).toEqual(`"ENABLED"`); }); it("returns invalid enums as they are", () => { const val = convertNumericEnumToString("campaign.status", 20); expect(val).toEqual(20); }); it("returns numberic values for non enum fields as they are", () => { const val = convertNumericEnumToString("campaign.id", 2); expect(val).toEqual(2); }); }); describe("extractConstraintConditions", () => { it("returns an empty array if no constraints are provided", () => { const constraintConditions = extractConstraintConditions(undefined); expect(constraintConditions).toEqual([]); }); it("throws if constraints are not an array or an object", () => { const constraints = [ "constraint", 2, null, () => { return; }, ]; constraints.forEach((constraint) => { // @ts-ignore expect(() => extractConstraintConditions(constraint)).toThrowError( QueryError.INVALID_CONSTRAINTS_FORMAT ); }); }); it("throws if a constraint array item is not an object or string", () => { const constraints = [ 2, [], null, () => { return; }, ]; constraints.forEach((constraint) => { expect(() => // @ts-ignore extractConstraintConditions([constraint]) ).toThrowError(QueryError.INVALID_CONSTRAINT_OBJECT_FORMAT); }); }); it("throws if a constraint array item is an object with an invalid format", () => { const constraints = [ { a: "a", b: "b" }, // too many keys {}, // to few keys { key_: "a", oper: "b", value: "c" }, // wrong { key, op val } syntax ]; constraints.forEach((constraint) => { expect(() => extractConstraintConditions([constraint as Constraint]) ).toThrowError(QueryError.INVALID_CONSTRAINT_OBJECT_FORMAT); }); }); it('throws if the "key" in the { key, op val } constraint syntax is not a string', () => { const keyValues = [ 2, [], () => { return; }, ]; keyValues.forEach((value) => { const constraints = [{ key: value, op: ">", val: 10 }]; // @ts-ignore expect(() => extractConstraintConditions(constraints)).toThrowError( QueryError.INVALID_CONSTRAINT_KEY ); }); }); it("parses constraints with a { key, op val } syntax", () => { const constraintConditions = extractConstraintConditions([ { key: "campaign.id", op: ">", val: 10 }, ]); expect(constraintConditions).toEqual(["campaign.id > 10"]); }); it("parses constraints with an object syntax", () => { const constraintConditions = extractConstraintConditions({ "campaign.id": 10, "campaign.advertising_channel_type": enums.AdvertisingChannelType.SEARCH, }); expect(constraintConditions).toEqual([ "campaign.id = 10", 'campaign.advertising_channel_type = "SEARCH"', ]); }); it("parses constraints that are strings", () => { const constraintConditions = extractConstraintConditions([ "metrics.historical_quality_score IS NOT NULL", ]); expect(constraintConditions).toEqual([ "metrics.historical_quality_score IS NOT NULL", ]); }); }); describe("extractDateConstantConditions", () => { it("returns an empty array if no constraints are provided", () => { const dateConstantConditions = extractDateConstantConditions(undefined); expect(dateConstantConditions).toEqual([]); }); it("throws if dateConstant is not a string", () => { const dateConstants = [ 2, [], {}, () => { return; }, null, ]; dateConstants.forEach((dateConstant) => { // @ts-ignore expect(() => extractDateConstantConditions(dateConstant)).toThrowError( // @ts-ignore QueryError.INVALID_DATE_CONSTANT_TYPE(dateConstant) ); }); }); it("parses date constant correctly", () => { const dateConstantConditions = extractDateConstantConditions( options.date_constant ); expect(dateConstantConditions[0]).toEqual( "segments.date DURING LAST_BUSINESS_WEEK" ); }); }); describe("extractDateConditions", () => { it("returns an empty array when no dates are provided", () => { const dateConditions = extractDateConditions(undefined, undefined); expect(dateConditions).toEqual([]); }); it("throws if fromDate is not provided", () => { expect(() => extractDateConditions(undefined, options.to_date) ).toThrowError(QueryError.MISSING_FROM_DATE); }); it("uses the current data if toDate is not provided", () => { const dateConditions = extractDateConditions(options.from_date, undefined); const todayDate = new Date(); const conditionDate = new Date(dateConditions[1].split(`"`)[1]); expect(todayDate.getDate()).toEqual(conditionDate.getDate()); expect(todayDate.getMonth()).toEqual(conditionDate.getMonth()); expect(todayDate.getFullYear()).toEqual(conditionDate.getFullYear()); }); it("throws if fromDate is not a string", () => { const fromDates = [ 2, [], {}, () => { return; }, null, ]; fromDates.forEach((fromDate) => { // @ts-ignore expect(() => extractDateConditions(fromDate, "2020-12-25")).toThrowError( // @ts-ignore QueryError.INVALID_FROM_DATE_TYPE(fromDate) ); }); }); it("throws if toDate is not a string", () => { const toDates = [ 2, [], {}, () => { return; }, null, ]; toDates.forEach((toDate) => { // @ts-ignore expect(() => extractDateConditions("2020-12-25", toDate)).toThrowError( // @ts-ignore QueryError.INVALID_TO_DATE_TYPE(toDate) ); }); }); it("parses dates correctly", () => { const dateConditions = extractDateConditions( options.from_date, options.to_date ); expect(dateConditions[0]).toEqual('segments.date >= "2020-01-01"'); expect(dateConditions[1]).toEqual('segments.date <= "2020-03-01"'); }); }); describe("buildWhereClause", () => { it("returns an empty string when no constraints or dates are provided", () => { const whereClause = buildWhereClause( undefined, undefined, undefined, undefined ); expect(whereClause).toEqual(""); }); }); describe("buildLimitClause", () => { it("throws if the limit is not a number", () => { const limits = [ "a", {}, [], null, () => { return; }, ]; limits.forEach((limit) => { // @ts-ignore expect(() => buildLimitClause(limit)).toThrowError( QueryError.INVALID_LIMIT ); }); }); it("correctly parses limit", () => { const limitClause = buildLimitClause(10); expect(limitClause).toEqual(` LIMIT 10`); }); it("returns an empty string if no limit is provided", () => { const limitClause = buildLimitClause(undefined); expect(limitClause).toEqual(``); }); }); describe("completeOrderly", () => { it("throws if an orderly is an empty string", () => { expect(() => completeOrderly("", options.entity)).toThrowError( QueryError.INVALID_ORDERLY ); }); it("completes orderlies without entities", () => { const orderly = completeOrderly("resource_name", options.entity); expect(orderly).toEqual("ad_group.resource_name"); }); it("returns orderlies that already have their entity", () => { const orderly1 = completeOrderly("campaign.resource_name", options.entity); const orderly2 = completeOrderly( "ad_group_criterion.keyword.match_type", options.entity ); const orderly3 = completeOrderly( "ad_group_ad.ad.gmail_ad.teaser.logo_image", options.entity ); expect(orderly1).toEqual("campaign.resource_name"); expect(orderly2).toEqual("ad_group_criterion.keyword.match_type"); expect(orderly3).toEqual("ad_group_ad.ad.gmail_ad.teaser.logo_image"); }); }); describe("buildOrderClauseOld", () => { it("throws if the sortOrder is invalid", () => { const sortOrders = [ "asc", "desc", "ascending", "descending", 2, {}, [], null, () => { return; }, ]; sortOrders.forEach((sortOrder) => { expect(() => // @ts-ignore buildOrderClauseOld(options.order_by, sortOrder, options.entity) ).toThrowError(QueryError.INVALID_SORT_ORDER); }); }); it("sets the sortOrder to descending if none is provided", () => { const orderClause = buildOrderClauseOld( options.order_by, undefined, options.entity ); expect(orderClause.endsWith("DESC")).toBeTruthy(); }); it("returns an empty string if no orderBy is provided", () => { const orderClause = buildOrderClauseOld( undefined, options.sort_order, options.entity ); expect(orderClause).toEqual(""); }); it("correctly parses orderBy from a string", () => { const orderClause = buildOrderClauseOld( options.order_by, options.sort_order, options.entity ); expect(orderClause).toEqual(` ORDER BY metrics.impressions ASC`); }); it("correctly parses orderBy from an array", () => { const orderClause = buildOrderClauseOld( ["metrics.impressions", "campaign.id"], options.sort_order, options.entity ); expect(orderClause).toEqual( ` ORDER BY metrics.impressions, campaign.id ASC` ); }); it("throws if an element in an orderBy array is not a string", () => { const orders = [ 2, {}, [], null, () => { return; }, ]; orders.forEach((order) => { expect(() => // @ts-ignore buildOrderClauseOld([order], options.sort_order, options.entity) ).toThrowError(QueryError.INVALID_ORDERLY); }); }); it("throws if orderBy is not an array or a string", () => { const orderBys = [ 2, {}, null, () => { return; }, ]; orderBys.forEach((orderBy) => { expect(() => // @ts-ignore buildOrderClauseOld(orderBy, options.sort_order, options.entity) ).toThrowError(QueryError.INVALID_ORDERBY); }); }); }); describe("buildOrderClauseNew", () => { it("throws if order is not an array", () => { const orders = [ 2, "string", {}, null, () => { return; }, ]; orders.forEach((order) => { expect(() => // @ts-ignore buildOrderClauseNew(order, options.entity) ).toThrowError(QueryError.INVALID_ORDER); }); }); it("sets the sortOrder to descending if none is provided", () => { const orderClause = buildOrderClauseNew( [{ field: "metrics.clicks" }], options.entity ); expect(orderClause.endsWith("DESC")).toBeTruthy(); }); it("returns an empty string if an empty array is provided", () => { const orderClause = buildOrderClauseNew([], options.entity); expect(orderClause).toEqual(""); }); it("correctly parses a single order", () => { const orderClause = buildOrderClauseNew( [{ field: "metrics.clicks", sort_order: "ASC" }], options.entity ); expect(orderClause).toEqual(` ORDER BY metrics.clicks ASC`); }); it("correctly parses multiple orders", () => { const orderClause = buildOrderClauseNew( [ { field: "metrics.clicks", sort_order: "ASC" }, { field: "campaign.id", sort_order: "DESC" }, { field: "segments.date", sort_order: "ASC" }, ], options.entity ); expect(orderClause).toEqual( ` ORDER BY metrics.clicks ASC, campaign.id DESC, segments.date ASC` ); }); }); const expectedRequestOptions = { page_size: 5, page_token: "A1B2C3D4", validate_only: false, summary_row_setting: "NO_SUMMARY_ROW", }; describe("buildRequestOptions", () => { it("takes the correct fields from the report options", () => { const requestOptions = buildRequestOptions(options); expect(requestOptions).toEqual(expectedRequestOptions); }); }); describe("buildQuery", () => { it("correctly builds test report options [!IMPORTANT!]", () => { const builtQuery = buildQuery(options); const expectedQuery = normaliseQuery( `SELECT ad_group.name, ad_group.id, metrics.impressions, metrics.cost_micros, segments.date FROM ad_group WHERE ad_group.status = "PAUSED" AND campaign.advertising_channel_type = "SEARCH" AND metrics.clicks > 10 AND segments.date DURING LAST_BUSINESS_WEEK AND segments.date >= "2020-01-01" AND segments.date <= "2020-03-01" ORDER BY metrics.impressions ASC LIMIT 10` ); expect(builtQuery).toEqual({ gaqlQuery: expectedQuery, requestOptions: expectedRequestOptions, }); }); const sampleQueries: { options: ReportOptions; expected: string }[] = [ { options: { entity: "campaign", attributes: ["campaign.id"], constraints: [ { key: "campaign.id", op: "IN", val: [1, 2, 3], }, ], }, expected: normaliseQuery( `SELECT campaign.id FROM campaign WHERE campaign.id IN (1, 2, 3)` ), }, { options: { entity: "campaign_criterion", attributes: [ "campaign.id", "campaign_criterion.location.geo_target_constant", "campaign_criterion.location_group", "campaign_criterion.proximity.radius", ], constraints: { "campaign.id": [11, 15, 21, 4], "campaign_criterion.type": [ enums.CriterionType.LOCATION, enums.CriterionType.LOCATION_GROUP, enums.CriterionType.PROXIMITY, ], }, }, expected: normaliseQuery( `SELECT campaign.id, campaign_criterion.location.geo_target_constant, campaign_criterion.location_group, campaign_criterion.proximity.radius FROM campaign_criterion WHERE campaign.id IN (11, 15, 21, 4) AND campaign_criterion.type IN ("LOCATION", "LOCATION_GROUP", "PROXIMITY")` ), }, { options: { entity: "campaign", attributes: [ "campaign.id", "campaign.name", "campaign_budget.id", "campaign_budget.amount_micros", "campaign_budget.explicitly_shared", ], metrics: ["metrics.cost_micros"], constraints: [{ "campaign.id": [11, 15, 21, 4] }], segments: ["segments.date"], }, expected: normaliseQuery( `SELECT campaign.id, campaign.name, campaign_budget.id, campaign_budget.amount_micros, campaign_budget.explicitly_shared, metrics.cost_micros, segments.date FROM campaign WHERE campaign.id IN (11, 15, 21, 4)` ), }, { options: { entity: "keyword_view", attributes: ["ad_group_criterion.criterion_id", "campaign.id"], segments: ["segments.date"], metrics: [ "metrics.historical_quality_score", "metrics.historical_creative_quality_score", "metrics.historical_landing_page_quality_score", "metrics.historical_search_predicted_ctr", "metrics.impressions", ], constraints: [ { "campaign.status": enums.CampaignStatus.ENABLED, }, { key: "metrics.impressions", op: ">", val: 0, }, "metrics.historical_quality_score IS NOT NULL", ], date_constant: "LAST_30_DAYS", order_by: "segments.date", sort_order: "DESC", limit: 50000, }, expected: normaliseQuery( `SELECT ad_group_criterion.criterion_id, campaign.id, metrics.historical_quality_score, metrics.historical_creative_quality_score, metrics.historical_landing_page_quality_score, metrics.historical_search_predicted_ctr, metrics.impressions, segments.date FROM keyword_view WHERE campaign.status = "ENABLED" AND metrics.impressions > 0 AND metrics.historical_quality_score IS NOT NULL AND segments.date DURING LAST_30_DAYS ORDER BY segments.date DESC LIMIT 50000` ), }, { options: { entity: "ad_group", attributes: [ "ad_group.id", "campaign.advertising_channel_sub_type", "campaign.id", ], metrics: ["metrics.cost_micros"], constraints: [ { key: "metrics.cost_micros", op: ">", val: 0, }, { key: "metrics.clicks", op: ">", val: 10, }, { "campaign.status": enums.CampaignStatus.ENABLED }, { "campaign.serving_status": enums.CampaignServingStatus.SERVING }, { "ad_group.status": enums.AdGroupStatus.ENABLED }, ], order: [ { field: "metrics.cost_micros", sort_order: "DESC" }, { field: "metrics.clicks", sort_order: "ASC" }, { field: "ad_group.id" }, ], }, expected: normaliseQuery( `SELECT ad_group.id, campaign.advertising_channel_sub_type, campaign.id, metrics.cost_micros FROM ad_group WHERE metrics.cost_micros > 0 AND metrics.clicks > 10 AND campaign.status = "ENABLED" AND campaign.serving_status = "SERVING" AND ad_group.status = "ENABLED" ORDER BY metrics.cost_micros DESC, metrics.clicks ASC, ad_group.id DESC` ), }, ]; it("buildQuery", () => { sampleQueries.forEach((sample) => { const builtQuery = buildQuery(sample.options); expect(builtQuery.gaqlQuery).toEqual(sample.expected); }); }); });
the_stack
import uniq from "lodash/uniq"; import compact from "lodash/compact"; import { BigNumber } from "bignumber.js"; import { getEnv } from "../../../env"; //@ts-expect-error import { WsProvider, ApiPromise } from "@polkadot/api"; import { u8aToString } from "@polkadot/util"; import { AccountId, Registration } from "@polkadot/types/interfaces"; import { Data, Option } from "@polkadot/types"; import type { ITuple } from "@polkadot/types/types"; import type { PolkadotValidator, PolkadotStakingProgress } from "../types"; type AsyncApiFunction = (api: typeof ApiPromise) => Promise<any>; const VALIDATOR_COMISSION_RATIO = 1000000000; // @ts-expect-error Generics doesn't work for dynamically added env const getWsUrl = () => getEnv("API_POLKADOT_NODE"); const WEBSOCKET_DEBOUNCE_DELAY = 30000; let api; let pendingQueries: Array<Promise<any>> = []; let apiDisconnectTimeout; /** * Connects to Substrate Node, executes calls then disconnects * * @param {*} execute - the calls to execute on api */ async function withApi(execute: AsyncApiFunction): Promise<any> { // If client is instanciated already, ensure it is connected & ready if (api) { try { await api.isReadyOrError; } catch (err) { // definitely not connected... api = null; pendingQueries = []; } } if (!api) { const wsProvider = new WsProvider( getWsUrl(), /* autoConnectMs = */ false ); wsProvider.connect(); api = await new ApiPromise({ provider: wsProvider, }).isReadyOrError; } cancelDebouncedDisconnect(); try { const query = execute(api); pendingQueries.push(query.catch((err) => err)); const res = await query; return res; } finally { debouncedDisconnect(); } } /** * Disconnects Websocket API client after all pending queries are flushed. */ export const disconnect = async () => { cancelDebouncedDisconnect(); if (api) { const disconnecting = api; const pending = pendingQueries; api = undefined; pendingQueries = []; await Promise.all(pending); await disconnecting.disconnect(); } }; const cancelDebouncedDisconnect = () => { if (apiDisconnectTimeout) { clearTimeout(apiDisconnectTimeout); apiDisconnectTimeout = null; } }; /** * Disconnects Websocket client after a delay. */ const debouncedDisconnect = () => { cancelDebouncedDisconnect(); apiDisconnectTimeout = setTimeout(disconnect, WEBSOCKET_DEBOUNCE_DELAY); }; /** * Returns true if ElectionStatus is Close. If ElectionStatus is Open, some features must be disabled. */ export const isElectionClosed = async (): Promise<Boolean> => withApi(async (api: typeof ApiPromise) => { const status = await api.query.staking.eraElectionStatus(); const res = status.isClose; return !!res; }); /** * Returns true if the address is a new account with no balance * * @param {*} addr */ export const isNewAccount = async (address: string): Promise<Boolean> => withApi(async (api: typeof ApiPromise) => { const { nonce, data: { free }, } = await api.query.system.account(address); return ( new BigNumber(0).isEqualTo(nonce) && new BigNumber(0).isEqualTo(free) ); }); /** * Returns true if the address is a new account with no balance * * @param {*} addr */ export const isControllerAddress = async (address: string): Promise<Boolean> => withApi(async (api: typeof ApiPromise) => { const ledgetOpt = await api.query.staking.ledger(address); return ledgetOpt.isSome; }); /** * Get all validators addresses to check for validity. */ const getValidatorsStashesAddresses = async (): Promise<string[]> => withApi(async (api: typeof ApiPromise) => { const list = await api.derive.staking.stashes(); return list.map((v) => v.toString()); }); /** * Returns all addresses that are not validators */ export const verifyValidatorAddresses = async ( validators: string[] ): Promise<string[]> => { const allValidators = await getValidatorsStashesAddresses(); return validators.filter((v) => !allValidators.includes(v)); }; /** * Get all account-related data * * @param {*} addr */ export const getAccount = async (addr: string) => withApi(async () => { const balances = await getBalances(addr); const stakingInfo = await getStakingInfo(addr); const nominations = await getNominations(addr); return { ...balances, ...stakingInfo, nominations }; }); /** * Returns all the balances for an account * * @param {*} addr - the account address */ export const getBalances = async (addr: string) => withApi(async (api: typeof ApiPromise) => { const [finalizedHash, balances] = await Promise.all([ api.rpc.chain.getFinalizedHead(), api.derive.balances.all(addr), ]); const { number } = await api.rpc.chain.getHeader(finalizedHash); return { blockHeight: number.toNumber(), balance: new BigNumber(balances.freeBalance), spendableBalance: new BigNumber(balances.availableBalance), nonce: balances.accountNonce.toNumber(), lockedBalance: new BigNumber(balances.lockedBalance), }; }); /** * Returns all staking-related data for an account * * @param {*} addr */ export const getStakingInfo = async (addr: string) => withApi(async (api: typeof ApiPromise) => { const [controlledLedgerOpt, bonded] = await Promise.all([ api.query.staking.ledger(addr), api.query.staking.bonded(addr), ]); // NOTE: controlledLedgerOpt is not the current stash ledger... const stash = controlledLedgerOpt.isSome ? controlledLedgerOpt.unwrap().stash.toString() : null; const controller = bonded.isSome ? bonded.unwrap().toString() : null; // If account is not a stash, no need to fetch corresponding ledger if (!controller) { return { controller: null, stash: stash || null, unlockedBalance: new BigNumber(0), unlockingBalance: new BigNumber(0), unlockings: [], }; } const [activeOpt, ledgerOpt] = await Promise.all([ api.query.staking.activeEra(), api.query.staking.ledger(controller), ]); const now = new Date(); const { index, start } = activeOpt.unwrapOrDefault(); const activeEraIndex = index.toNumber(); const activeEraStart = start.unwrap().toNumber(); const blockTime = api.consts.babe.expectedBlockTime; // 6000 ms const epochDuration = api.consts.babe.epochDuration; // 2400 blocks const eraLength = api.consts.staking.sessionsPerEra // 6 sessions .mul(epochDuration) .mul(blockTime) .toNumber(); const ledger = ledgerOpt.isSome ? ledgerOpt.unwrap() : null; const unlockings = ledger ? ledger.unlocking.map((lock) => ({ amount: new BigNumber(lock.value), completionDate: new Date( activeEraStart + (lock.era - activeEraIndex) * eraLength ), // This is an estimation of the date of completion, since it depends on block validation speed })) : []; const unlocked = unlockings.filter((lock) => lock.completionDate <= now); const unlockingBalance = unlockings.reduce( (sum, lock) => sum.plus(lock.amount), new BigNumber(0) ); const unlockedBalance = unlocked.reduce( (sum, lock) => sum.plus(lock.amount), new BigNumber(0) ); return { controller, stash, unlockedBalance, unlockingBalance, unlockings, }; }); /** * Returns nominations for an account including validator address, status and associated stake. * * @param {*} addr */ export const getNominations = async (addr: string) => withApi(async (api: typeof ApiPromise) => { const [{ activeEra }, nominationsOpt] = await Promise.all([ api.derive.session.indexes(), api.query.staking.nominators(addr), ]); if (nominationsOpt.isNone) return []; const targets = nominationsOpt.unwrap().targets; const [exposures, stashes] = await Promise.all([ api.query.staking.erasStakers.multi( targets.map((target) => [activeEra, target]) ), api.derive.staking.stashes(), ]); const allStashes = stashes.map((stash) => stash.toString()); return targets.map((target, index) => { const exposure = exposures[index]; const individualExposure = exposure.others.find( (o) => o.who.toString() === addr ); const value = individualExposure ? new BigNumber(individualExposure.value) : new BigNumber(0); const status = exposure.others.length ? individualExposure ? "active" : "inactive" : allStashes.includes(target.toString()) ? "waiting" : null; return { address: target.toString(), value, status, }; }); }); /** * Returns all the params from the chain to build an extrinsic (a transaction on Substrate) */ export const getTransactionParams = async () => withApi(async (api: typeof ApiPromise) => { const chainName = await api.rpc.system.chain(); const blockHash = await api.rpc.chain.getFinalizedHead(); const genesisHash = await api.rpc.chain.getBlockHash(0); const { number } = await api.rpc.chain.getHeader(blockHash); const { specName, specVersion, transactionVersion } = await api.rpc.state.getRuntimeVersion(blockHash); return { blockHash, blockNumber: number, genesisHash, chainName: chainName.toString(), specName: specName.toString(), specVersion, transactionVersion, }; }); /** * Broadcast the transaction to the substrate node * * @param {string} extrinsic - the encoded extrinsic to send */ export const submitExtrinsic = async (extrinsic: string) => withApi(async (api: typeof ApiPromise) => { const tx = api.tx(extrinsic); const hash = await api.rpc.author.submitExtrinsic(tx); return hash; }); /** * Retrieve the transaction fees and weights * Note: fees on Substrate are not set by the signer, but directly by the blockchain runtime. * * @param {string} extrinsic - the encoded extrinsic to send with a fake signing */ export const paymentInfo = async (extrinsic: string) => withApi(async (api: typeof ApiPromise) => { const info = await api.rpc.payment.queryInfo(extrinsic); return info; }); /** * Fetch all reward points for validators for current era * * @returns Map<String, BigNumber> */ export const fetchRewardPoints = async () => withApi(async (api: typeof ApiPromise) => { const activeOpt = await api.query.staking.activeEra(); const { index: activeEra } = activeOpt.unwrapOrDefault(); const { individual } = await api.query.staking.erasRewardPoints(activeEra); // recast BTreeMap<AccountId,RewardPoint> to Map<String, RewardPoint> because strict equality does not work const rewards = new Map<String, BigNumber>( [...individual.entries()].map(([k, v]) => [ k.toString(), new BigNumber(v.toString()), ]) ); return rewards; }); /** * @source https://github.com/polkadot-js/api/blob/master/packages/api-derive/src/accounts/info.ts */ function dataAsString(data: Data): string { return data.isRaw ? u8aToString(data.asRaw.toU8a(true)).trim() : data.isNone ? "" : data.toHex(); } /** * Fetch identity name of multiple addresses. * Get parent identity if any, and concatenate parent name with child name. * * @param {string[]} addresses */ export const fetchIdentities = async (addresses: string[]) => withApi(async (api: typeof ApiPromise) => { const superOfOpts = await api.query.identity.superOf.multi< Option<ITuple<[AccountId, Data]>> >(addresses); const withParent = superOfOpts.map((superOfOpt) => superOfOpt?.isSome ? superOfOpt?.unwrap() : undefined ); const parentAddresses = uniq( compact(withParent.map((superOf) => superOf && superOf[0].toString())) ); const [identities, parentIdentities] = await Promise.all([ api.query.identity.identityOf.multi<Option<Registration>>(addresses), api.query.identity.identityOf.multi<Option<Registration>>( parentAddresses ), ]); const map = new Map<string, string>( addresses.map((addr, index) => { const indexOfParent = withParent[index] ? parentAddresses.indexOf(withParent[index][0].toString()) : -1; const identityOpt = indexOfParent > -1 ? parentIdentities[indexOfParent] : identities[index]; if (identityOpt.isNone) { return [addr, ""]; } const { info: { display }, } = identityOpt.unwrap(); const name = withParent[index] ? `${dataAsString(display)} / ${dataAsString(withParent[index][1])}` : dataAsString(display); return [addr, name]; }) ); return map; }); /** * Transforms each validator into an internal Validator type. * @param {*} rewards - map of addres sand corresponding reward * @param {*} identities - map of address and corresponding identity * @param {*} elected - list of elected validator addresses * @param {*} maxNominators - constant for oversubscribed validators * @param {*} validator - the validator details to transform. */ const mapValidator = ( rewards, identities, elected, maxNominators, validator ): PolkadotValidator => { const address = validator.accountId.toString(); return { address: address, identity: identities.get(address) || "", nominatorsCount: validator.exposure.others.length, rewardPoints: rewards.get(address) || null, commission: new BigNumber(validator.validatorPrefs.commission).dividedBy( VALIDATOR_COMISSION_RATIO ), totalBonded: new BigNumber(validator.exposure.total), selfBonded: new BigNumber(validator.exposure.own), isElected: elected.includes(address), isOversubscribed: validator.exposure.others.length >= maxNominators, }; }; /** * List all validators for the current era, and their exposure, and identity. */ export const getValidators = async ( stashes: string | string[] = "elected" ): Promise<PolkadotValidator> => withApi(async (api: typeof ApiPromise) => { const [allStashes, elected] = await Promise.all([ api.derive.staking.stashes(), api.query.session.validators(), ]); let stashIds; const allIds = allStashes.map((s) => s.toString()); const electedIds = elected.map((s) => s.toString()); if (Array.isArray(stashes)) { stashIds = allIds.filter((s) => stashes.includes(s)); } else if (stashes === "elected") { stashIds = electedIds; } else { const waitingIds = allIds.filter((v) => !electedIds.includes(v)); if (stashes === "waiting") { stashIds = waitingIds; } else { // Keep elected in first positions stashIds = [...electedIds, ...waitingIds]; } } const [validators, rewards, identities] = await Promise.all([ api.derive.staking.accounts(stashIds), fetchRewardPoints(), fetchIdentities(stashIds), ]); return validators.map( mapValidator.bind( null, rewards, identities, electedIds, api.consts.staking.maxNominatorRewardedPerValidator ) ); }); /** * Get Active Era progress */ export const getStakingProgress = async (): Promise<PolkadotStakingProgress> => withApi(async (api: typeof ApiPromise) => { const [activeEraOpt, status] = await Promise.all([ api.query.staking.activeEra(), api.query.staking.eraElectionStatus(), ]); const { index: activeEra } = activeEraOpt.unwrapOrDefault(); return { activeEra: activeEra.toNumber(), electionClosed: !!status.isClose, }; }); /** * Return TypeRegistry and decorated extrinsics from client */ export const getRegistry = async () => withApi(async (api: typeof ApiPromise) => { return { registry: api.registry, extrinsics: api.tx, }; });
the_stack
import * as k8s from "@kubernetes/client-node"; import * as assert from "power-assert"; import { KubernetesDelete } from "../../../../lib/pack/k8s/kubernetes/request"; import { appObject, k8sObject, logObject } from "../../../../lib/pack/k8s/kubernetes/resource"; describe("pack/k8s/kubernetes/resource", () => { describe("appObject", () => { it("should throw an exception if kind invalid", () => { [undefined, "", "Nothing"].forEach(k => { const a: KubernetesDelete = { name: "good-girl-gone-bad", ns: "rihanna", workspaceId: "AR14NN4", }; assert.throws(() => appObject(a, k), /Unsupported kind of Kubernetes resource object:/); }); }); it("should return a namespace object", () => { const a: KubernetesDelete = { name: "good-girl-gone-bad", ns: "rihanna", workspaceId: "AR14NN4", }; const o = appObject(a, "Namespace"); const e = { apiVersion: "v1", kind: "Namespace", metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "rihanna", }, }; assert.deepStrictEqual(o, e); }); it("should return a v1 namespaced object", () => { ["Secret", "Service", "ServiceAccount"].forEach(k => { const a: KubernetesDelete = { name: "good-girl-gone-bad", ns: "rihanna", workspaceId: "AR14NN4", }; const o = appObject(a, k); const e = { apiVersion: "v1", kind: k, metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", namespace: "rihanna", }, }; assert.deepStrictEqual(o, e); }); }); it("should return a networking.k8s.io/v1beta1 namespaced object", () => { const a: KubernetesDelete = { name: "good-girl-gone-bad", ns: "rihanna", workspaceId: "AR14NN4", }; const o = appObject(a, "Ingress"); const e = { apiVersion: "networking.k8s.io/v1beta1", kind: "Ingress", metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", namespace: "rihanna", }, }; assert.deepStrictEqual(o, e); }); it("should return a namespaced apps object", () => { const a: KubernetesDelete = { name: "good-girl-gone-bad", ns: "rihanna", workspaceId: "AR14NN4", }; const o = appObject(a, "Deployment"); const e = { apiVersion: "apps/v1", kind: "Deployment", metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", namespace: "rihanna", }, }; assert.deepStrictEqual(o, e); }); it("should return a namespaced RBAC object", () => { ["Role", "RoleBinding"].forEach(k => { const a: KubernetesDelete = { name: "good-girl-gone-bad", ns: "rihanna", workspaceId: "AR14NN4", }; const o = appObject(a, k); const e = { apiVersion: "rbac.authorization.k8s.io/v1", kind: k, metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", namespace: "rihanna", }, }; assert.deepStrictEqual(o, e); }); }); it("should return a cluster RBAC object", () => { ["ClusterRole", "ClusterRoleBinding"].forEach(k => { const a: KubernetesDelete = { name: "good-girl-gone-bad", ns: "rihanna", workspaceId: "AR14NN4", }; const o = appObject(a, k); const e = { apiVersion: "rbac.authorization.k8s.io/v1", kind: k, metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", }, }; assert.deepStrictEqual(o, e); }); }); }); describe("k8sObject", () => { it("should return a minimal object from a service account", () => { const d: k8s.V1ServiceAccount = { apiVersion: "v1", kind: "ServiceAccount", metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", namespace: "rihanna", }, }; const o = k8sObject(d); assert.deepStrictEqual(o, d); }); it("should return a minimal object from a deployment", () => { const d: k8s.V1Deployment = { apiVersion: "apps/v1", kind: "Deployment", metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", namespace: "rihanna", }, spec: { selector: {}, template: { spec: { containers: [ { image: "umbrella:4.36", name: "umbrella", }, ], }, }, }, }; const o = k8sObject(d); const e = { apiVersion: "apps/v1", kind: "Deployment", metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", namespace: "rihanna", }, }; assert.deepStrictEqual(o, e); }); }); describe("stringifyObject", () => { it("should stringify a service", () => { const d: k8s.V1Service = { apiVersion: "v1", kind: "Service", metadata: { name: "good-girl-gone-bad", namespace: "rihanna", }, spec: { ports: [{ port: 8080 }], }, }; const s = logObject(d); // tslint:disable-next-line:max-line-length const e = `{"apiVersion":"v1","kind":"Service","metadata":{"name":"good-girl-gone-bad","namespace":"rihanna"},"spec":{"ports":[{"port":8080}]}}`; assert(s === e); }); it("should stringify and truncate a deployment", () => { const d: k8s.V1Deployment = { apiVersion: "apps/v1", kind: "Deployment", metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", namespace: "rihanna", }, spec: { selector: {}, template: { spec: { containers: [ { image: "umbrella:4.36", name: "umbrella", }, ], }, }, }, }; const s = logObject(d); // tslint:disable-next-line:max-line-length const e = `{"apiVersion":"apps/v1","kind":"Deployment","metadata":{"labels":{"app.kubernetes.io/name":"good-girl-gone-bad","atomist.com/workspaceId":"AR14NN4"},"name":"good-girl-gone-bad","namespace":"rihann...}`; assert(s === e); }); it("should remove data values from a secret", () => { const d: k8s.V1Secret = { apiVersion: "v1", data: { One: "VW1icmVsbGEgKGZlYXQuIEpheS1aKQ==", Two: "UHVzaCBVcCBvbiBNZQ==", Seven: "U2F5IEl0", }, kind: "Secret", metadata: { labels: { "app.kubernetes.io/name": "good-girl-gone-bad", "atomist.com/workspaceId": "AR14NN4", }, name: "good-girl-gone-bad", namespace: "rihanna", }, }; const s = logObject(d); // tslint:disable-next-line:max-line-length const e = `{"apiVersion":"v1","data":{"One":"V******************************=","Two":"U******************=","Seven":"********"},"kind":"Secret","metadata":{"labels":{"app.kubernetes.io/name":"good-girl-gone-...}`; assert(s === e); }); }); });
the_stack
import React, {useEffect, useRef, useState} from 'react'; import {useDebounce} from 'react-use'; import {Button, Checkbox, Input, InputNumber, Select, Tooltip} from 'antd'; import {WarningOutlined} from '@ant-design/icons'; import _ from 'lodash'; import styled from 'styled-components'; import {DEFAULT_EDITOR_DEBOUNCE, DEFAULT_KUBECONFIG_DEBOUNCE, TOOLTIP_DELAY} from '@constants/constants'; import { AddExclusionPatternTooltip, AddInclusionPatternTooltip, AutoLoadLastProjectTooltip, BrowseKubeconfigTooltip, EnableHelmWithKustomizeTooltip, HelmPreviewModeTooltip, KubeconfigPathTooltip, KustomizeCommandTooltip, } from '@constants/tooltips'; import {ProjectConfig} from '@models/appconfig'; import {useAppDispatch, useAppSelector} from '@redux/hooks'; import {updateShouldOptionalIgnoreUnsatisfiedRefs} from '@redux/reducers/main'; import {isInClusterModeSelector} from '@redux/selectors'; import FilePatternList from '@molecules/FilePatternList'; import {useFocus} from '@utils/hooks'; import Colors from '@styles/Colors'; const StyledDiv = styled.div` margin-bottom: 20px; `; const StyledSpan = styled.span` font-weight: 500; font-size: 20px; display: block; margin-bottom: 6px; `; const StyledButton = styled(Button)` margin-top: 10px; `; const HiddenInput = styled.input` display: none; `; const StyledSelect = styled(Select)` width: 100%; `; const StyledWarningOutlined = styled( (props: {isKubeconfigPathValid: boolean; highlighted?: boolean; className: string}) => ( <WarningOutlined className={props.className} /> ) )` ${props => `color: ${ props.highlighted ? Colors.whitePure : !props.isKubeconfigPathValid ? Colors.redError : Colors.yellowWarning }; margin-left: ${props.highlighted ? '10px' : '5px'}; padding-top: ${props.highlighted ? '5px' : '0px'}; `}; `; const StyledHeading = styled.h2` font-size: 16px; margin-bottom: 7px; `; type SettingsProps = { config?: ProjectConfig | null; onConfigChange?: Function; isClusterPaneIconHighlighted?: boolean | null; showLoadLastProjectOnStartup?: boolean | null; showEnableHelmWithKustomize?: boolean | null; }; export const Settings = ({ config, onConfigChange, isClusterPaneIconHighlighted, showLoadLastProjectOnStartup, showEnableHelmWithKustomize, }: SettingsProps) => { const dispatch = useAppDispatch(); const isSettingsOpened = Boolean(useAppSelector(state => state.ui.isSettingsOpen)); const resourceRefsProcessingOptions = useAppSelector(state => state.main.resourceRefsProcessingOptions); const uiState = useAppSelector(state => state.ui); const isInClusterMode = useAppSelector(isInClusterModeSelector); const fileInput = useRef<HTMLInputElement>(null); const [inputRef, focusInput] = useFocus<Input>(); const hasUserPerformedClickOnClusterIcon = useAppSelector(state => state.uiCoach.hasUserPerformedClickOnClusterIcon); const wasRehydrated = useAppSelector(state => state.main.wasRehydrated); const [isClusterActionDisabled, setIsClusterActionDisabled] = useState( Boolean(!config?.kubeConfig?.path) || Boolean(!config?.kubeConfig?.isPathValid) ); const [currentKubeConfig, setCurrentKubeConfig] = useState(config?.kubeConfig?.path); const isEditingDisabled = uiState.isClusterDiffVisible || isInClusterMode; const [localConfig, setLocalConfig] = useState<ProjectConfig | null | undefined>(config); const handleConfigChange = () => { if (onConfigChange && !_.isEqual(localConfig, config)) { onConfigChange(localConfig); } }; useEffect(() => { setIsClusterActionDisabled(Boolean(!config?.kubeConfig?.path) || Boolean(!config?.kubeConfig?.isPathValid)); setCurrentKubeConfig(config?.kubeConfig?.path); }, [config?.kubeConfig]); useEffect(() => { // If config prop is changed externally, This code will make localConfig even with config prop setLocalConfig(config); }, [config]); useEffect(() => { handleConfigChange(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [localConfig]); useDebounce( () => { handleConfigChange(); }, DEFAULT_EDITOR_DEBOUNCE, [localConfig?.folderReadsMaxDepth] ); const onChangeFileIncludes = (patterns: string[]) => { setLocalConfig({...localConfig, fileIncludes: patterns}); }; const onChangeScanExcludes = (patterns: string[]) => { setLocalConfig({...localConfig, scanExcludes: patterns}); }; const onChangeHelmPreviewMode = (selectedHelmPreviewMode: any) => { if (selectedHelmPreviewMode === 'template' || selectedHelmPreviewMode === 'install') { setLocalConfig({...localConfig, settings: {...localConfig?.settings, helmPreviewMode: selectedHelmPreviewMode}}); } }; const onChangeHideExcludedFilesInFileExplorer = (e: any) => { setLocalConfig({ ...localConfig, settings: {...localConfig?.settings, hideExcludedFilesInFileExplorer: e.target.checked}, }); }; const onChangeKustomizeCommand = (selectedKustomizeCommand: any) => { if (selectedKustomizeCommand === 'kubectl' || selectedKustomizeCommand === 'kustomize') { setLocalConfig({ ...localConfig, settings: {...localConfig?.settings, kustomizeCommand: selectedKustomizeCommand}, }); } }; const onChangeLoadLastFolderOnStartup = (e: any) => { setLocalConfig({ ...localConfig, settings: {...localConfig?.settings, loadLastProjectOnStartup: e.target.checked}, }); }; const setShouldIgnoreOptionalUnsatisfiedRefs = (e: any) => { dispatch(updateShouldOptionalIgnoreUnsatisfiedRefs(e.target.checked)); }; const onChangeEnableHelmWithKustomize = (e: any) => { setLocalConfig({ ...localConfig, settings: {...localConfig?.settings, enableHelmWithKustomize: e.target.checked}, }); }; const openFileSelect = () => { if (isEditingDisabled) { return; } fileInput && fileInput.current?.click(); }; useDebounce( () => { if (currentKubeConfig !== localConfig?.kubeConfig?.path) { setLocalConfig({...localConfig, kubeConfig: {path: currentKubeConfig}}); } }, DEFAULT_KUBECONFIG_DEBOUNCE, [currentKubeConfig] ); const onUpdateKubeconfig = (e: any) => { if (isEditingDisabled) { return; } setCurrentKubeConfig(e.target.value); }; const onSelectFile = (e: React.SyntheticEvent) => { e.preventDefault(); if (fileInput.current?.files && fileInput.current.files.length > 0) { const file: any = fileInput.current.files[0]; if (file.path) { const path = file.path; setCurrentKubeConfig(path); } } }; const toggleClusterSelector = () => { setLocalConfig({ ...localConfig, settings: { ...localConfig?.settings, isClusterSelectorVisible: Boolean(!localConfig?.settings?.isClusterSelectorVisible), }, }); }; return ( <> <StyledDiv> <StyledHeading> KUBECONFIG {isClusterActionDisabled && hasUserPerformedClickOnClusterIcon && wasRehydrated && ( <StyledWarningOutlined className={isClusterPaneIconHighlighted ? 'animated-highlight' : ''} isKubeconfigPathValid={Boolean(config?.kubeConfig?.isPathValid)} highlighted={Boolean(isClusterPaneIconHighlighted)} /> )} </StyledHeading> <Tooltip title={KubeconfigPathTooltip}> <Input ref={inputRef} value={currentKubeConfig} onChange={onUpdateKubeconfig} disabled={isEditingDisabled} onClick={() => focusInput()} /> </Tooltip> <Tooltip mouseEnterDelay={TOOLTIP_DELAY} title={BrowseKubeconfigTooltip} placement="right"> <StyledButton onClick={openFileSelect} disabled={isEditingDisabled}> Browse </StyledButton> </Tooltip> <StyledDiv style={{marginTop: 16}}> <Checkbox checked={Boolean(localConfig?.settings?.isClusterSelectorVisible)} onChange={toggleClusterSelector}> Show Cluster Selector </Checkbox> </StyledDiv> <HiddenInput type="file" onChange={onSelectFile} ref={fileInput} /> </StyledDiv> <StyledDiv> <StyledSpan>Files: Include</StyledSpan> <FilePatternList value={localConfig?.fileIncludes || []} onChange={onChangeFileIncludes} tooltip={AddInclusionPatternTooltip} isSettingsOpened={isSettingsOpened} /> </StyledDiv> <StyledDiv> <StyledSpan>Files: Exclude</StyledSpan> <FilePatternList value={localConfig?.scanExcludes || []} onChange={onChangeScanExcludes} tooltip={AddExclusionPatternTooltip} isSettingsOpened={isSettingsOpened} type="excludes" /> </StyledDiv> <StyledDiv> <Checkbox checked={Boolean(localConfig?.settings?.hideExcludedFilesInFileExplorer)} onChange={onChangeHideExcludedFilesInFileExplorer} > Hide excluded files </Checkbox> </StyledDiv> <StyledDiv> <StyledSpan>Helm Preview Mode</StyledSpan> <Tooltip title={HelmPreviewModeTooltip}> <StyledSelect value={localConfig?.settings?.helmPreviewMode} onChange={onChangeHelmPreviewMode}> <Select.Option value="template">Template</Select.Option> <Select.Option value="install">Install</Select.Option> </StyledSelect> </Tooltip> </StyledDiv> <StyledDiv> <StyledSpan>Kustomize Command</StyledSpan> <Tooltip title={KustomizeCommandTooltip}> <StyledSelect value={localConfig?.settings?.kustomizeCommand} onChange={onChangeKustomizeCommand}> <Select.Option value="kubectl">Use kubectl</Select.Option> <Select.Option value="kustomize">Use kustomize</Select.Option> </StyledSelect> </Tooltip> </StyledDiv> {showEnableHelmWithKustomize && ( <StyledDiv> <Tooltip title={EnableHelmWithKustomizeTooltip}> <Checkbox checked={localConfig?.settings?.enableHelmWithKustomize} onChange={onChangeEnableHelmWithKustomize} > Enable Helm-related features when invoking Kustomize </Checkbox> </Tooltip> </StyledDiv> )} {showLoadLastProjectOnStartup && ( <StyledDiv> <StyledSpan>On Startup</StyledSpan> <Tooltip title={AutoLoadLastProjectTooltip}> <Checkbox checked={Boolean(localConfig?.settings?.loadLastProjectOnStartup)} onChange={onChangeLoadLastFolderOnStartup} > Automatically load last project </Checkbox> </Tooltip> </StyledDiv> )} <StyledDiv> <StyledSpan>Maximum folder read recursion depth</StyledSpan> <InputNumber min={1} value={localConfig?.folderReadsMaxDepth} onChange={(value: number) => setLocalConfig({...localConfig, folderReadsMaxDepth: value})} /> </StyledDiv> <StyledDiv> <StyledSpan>Resource links processing</StyledSpan> <Checkbox checked={resourceRefsProcessingOptions.shouldIgnoreOptionalUnsatisfiedRefs} onChange={setShouldIgnoreOptionalUnsatisfiedRefs} > Ignore optional unsatisfied links </Checkbox> </StyledDiv> {/* <StyledDiv> <StyledSpan>Theme</StyledSpan> <Radio.Group size="large" value={appConfig.settings.theme} onChange={onChangeTheme}> <Radio.Button value={Themes.Dark}>Dark</Radio.Button> <Radio.Button value={Themes.Light}>Light</Radio.Button> </Radio.Group> </StyledDiv> <StyledDiv> <StyledSpan>Text Size</StyledSpan> <Radio.Group size="large" value={appConfig.settings.textSize}> <Radio.Button value={TextSizes.Large}>Large</Radio.Button> <Radio.Button value={TextSizes.Medium}>Medium</Radio.Button> <Radio.Button value={TextSizes.Small}>Small</Radio.Button> </Radio.Group> </StyledDiv> <StyledDiv> <StyledSpan>Language</StyledSpan> <Radio.Group size="large" value={appConfig.settings.language}> <Space direction="vertical"> <Radio value={Languages.English}>English</Radio> </Space> </Radio.Group> </StyledDiv> */} </> ); };
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [comprehend](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncomprehend.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Comprehend extends PolicyStatement { public servicePrefix = 'comprehend'; /** * Statement provider for service [comprehend](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncomprehend.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 detect the language or languages present in the list of text documents * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_BatchDetectDominantLanguage.html */ public toBatchDetectDominantLanguage() { return this.to('BatchDetectDominantLanguage'); } /** * Grants permission to detect the named entities ("People", "Places", "Locations", etc) within the given list of text documents * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_BatchDetectEntities.html */ public toBatchDetectEntities() { return this.to('BatchDetectEntities'); } /** * Grants permission to detect the phrases in the list of text documents that are most indicative of the content * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_BatchDetectKeyPhrases.html */ public toBatchDetectKeyPhrases() { return this.to('BatchDetectKeyPhrases'); } /** * Grants permission to detect the sentiment of a text in the list of documents (Positive, Negative, Neutral, or Mixed) * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_BatchDetectSentiment.html */ public toBatchDetectSentiment() { return this.to('BatchDetectSentiment'); } /** * Grants permission to detect syntactic information (like Part of Speech, Tokens) in a list of text documents * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_BatchDetectSyntax.html */ public toBatchDetectSyntax() { return this.to('BatchDetectSyntax'); } /** * Grants permission to create a new document classification request to analyze a single document in real-time, using a previously created and trained custom model and an endpoint * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ClassifyDocument.html */ public toClassifyDocument() { return this.to('ClassifyDocument'); } /** * Grants permission to classify the personally identifiable information within given documents at realtime * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ContainsPiiEntities.html */ public toContainsPiiEntities() { return this.to('ContainsPiiEntities'); } /** * Grants permission to create a new document classifier that you can use to categorize documents * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifVolumeKmsKey() * - .ifModelKmsKey() * - .ifOutputKmsKey() * - .ifVpcSecurityGroupIds() * - .ifVpcSubnets() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_CreateDocumentClassifier.html */ public toCreateDocumentClassifier() { return this.to('CreateDocumentClassifier'); } /** * Grants permission to create a model-specific endpoint for synchronous inference for a previously trained custom model * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_CreateEndpoint.html */ public toCreateEndpoint() { return this.to('CreateEndpoint'); } /** * Grants permission to create an entity recognizer using submitted files * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifVolumeKmsKey() * - .ifModelKmsKey() * - .ifVpcSecurityGroupIds() * - .ifVpcSubnets() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_CreateEntityRecognizer.html */ public toCreateEntityRecognizer() { return this.to('CreateEntityRecognizer'); } /** * Grants permission to delete a previously created document classifier * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DeleteDocumentClassifier.html */ public toDeleteDocumentClassifier() { return this.to('DeleteDocumentClassifier'); } /** * Grants permission to delete a model-specific endpoint for a previously-trained custom model. All endpoints must be deleted in order for the model to be deleted * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DeleteEndpoint.html */ public toDeleteEndpoint() { return this.to('DeleteEndpoint'); } /** * Grants permission to delete a submitted entity recognizer * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DeleteEntityRecognizer.html */ public toDeleteEntityRecognizer() { return this.to('DeleteEntityRecognizer'); } /** * Grants permission to get the properties associated with a document classification job * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeDocumentClassificationJob.html */ public toDescribeDocumentClassificationJob() { return this.to('DescribeDocumentClassificationJob'); } /** * Grants permission to get the properties associated with a document classifier * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeDocumentClassifier.html */ public toDescribeDocumentClassifier() { return this.to('DescribeDocumentClassifier'); } /** * Grants permission to get the properties associated with a dominant language detection job * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeDominantLanguageDetectionJob.html */ public toDescribeDominantLanguageDetectionJob() { return this.to('DescribeDominantLanguageDetectionJob'); } /** * Grants permission to get the properties associated with a specific endpoint. Use this operation to get the status of an endpoint * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeEndpoint.html */ public toDescribeEndpoint() { return this.to('DescribeEndpoint'); } /** * Grants permission to get the properties associated with an entities detection job * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeEntitiesDetectionJob.html */ public toDescribeEntitiesDetectionJob() { return this.to('DescribeEntitiesDetectionJob'); } /** * Grants permission to provide details about an entity recognizer including status, S3 buckets containing training data, recognizer metadata, metrics, and so on * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeEntityRecognizer.html */ public toDescribeEntityRecognizer() { return this.to('DescribeEntityRecognizer'); } /** * Grants permission to get the properties associated with an Events detection job * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeEventsDetectionJob.html */ public toDescribeEventsDetectionJob() { return this.to('DescribeEventsDetectionJob'); } /** * Grants permission to get the properties associated with a key phrases detection job * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeKeyPhrasesDetectionJob.html */ public toDescribeKeyPhrasesDetectionJob() { return this.to('DescribeKeyPhrasesDetectionJob'); } /** * Grants permission to get the properties associated with a PII entities detection job * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribePiiEntitiesDetectionJob.html */ public toDescribePiiEntitiesDetectionJob() { return this.to('DescribePiiEntitiesDetectionJob'); } /** * Grants permission to get the properties associated with a sentiment detection job * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeSentimentDetectionJob.html */ public toDescribeSentimentDetectionJob() { return this.to('DescribeSentimentDetectionJob'); } /** * Grants permission to get the properties associated with a topic detection job * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DescribeTopicsDetectionJob.html */ public toDescribeTopicsDetectionJob() { return this.to('DescribeTopicsDetectionJob'); } /** * Grants permission to detect the language or languages present in the text * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DetectDominantLanguage.html */ public toDetectDominantLanguage() { return this.to('DetectDominantLanguage'); } /** * Grants permission to detect the named entities ("People", "Places", "Locations", etc) within the given text document * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DetectEntities.html */ public toDetectEntities() { return this.to('DetectEntities'); } /** * Grants permission to detect the phrases in the text that are most indicative of the content * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DetectKeyPhrases.html */ public toDetectKeyPhrases() { return this.to('DetectKeyPhrases'); } /** * Grants permission to detect the personally identifiable information entities ("Name", "SSN", "PIN", etc) within the given text document * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DetectPiiEntities.html */ public toDetectPiiEntities() { return this.to('DetectPiiEntities'); } /** * Grants permission to detect the sentiment of a text in a document (Positive, Negative, Neutral, or Mixed) * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DetectSentiment.html */ public toDetectSentiment() { return this.to('DetectSentiment'); } /** * Grants permission to detect syntactic information (like Part of Speech, Tokens) in a text document * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_DetectSyntax.html */ public toDetectSyntax() { return this.to('DetectSyntax'); } /** * Grants permission to get a list of the document classification jobs that you have submitted * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListDocumentClassificationJobs.html */ public toListDocumentClassificationJobs() { return this.to('ListDocumentClassificationJobs'); } /** * Grants permission to get a list of summaries of the document classifiers that you have created * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListDocumentClassifierSummaries.html */ public toListDocumentClassifierSummaries() { return this.to('ListDocumentClassifierSummaries'); } /** * Grants permission to get a list of the document classifiers that you have created * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListDocumentClassifiers.html */ public toListDocumentClassifiers() { return this.to('ListDocumentClassifiers'); } /** * Grants permission to get a list of the dominant language detection jobs that you have submitted * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListDominantLanguageDetectionJobs.html */ public toListDominantLanguageDetectionJobs() { return this.to('ListDominantLanguageDetectionJobs'); } /** * Grants permission to get a list of all existing endpoints that you've created * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListEndpoints.html */ public toListEndpoints() { return this.to('ListEndpoints'); } /** * Grants permission to get a list of the entity detection jobs that you have submitted * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListEntitiesDetectionJobs.html */ public toListEntitiesDetectionJobs() { return this.to('ListEntitiesDetectionJobs'); } /** * Grants permission to get a list of summaries for the entity recognizers that you have created * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListEntityRecognizerSummaries.html */ public toListEntityRecognizerSummaries() { return this.to('ListEntityRecognizerSummaries'); } /** * Grants permission to get a list of the properties of all entity recognizers that you created, including recognizers currently in training * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListEntityRecognizers.html */ public toListEntityRecognizers() { return this.to('ListEntityRecognizers'); } /** * Grants permission to get a list of Events detection jobs that you have submitted * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListEventsDetectionJobs.html */ public toListEventsDetectionJobs() { return this.to('ListEventsDetectionJobs'); } /** * Grants permission to get a list of key phrase detection jobs that you have submitted * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListKeyPhrasesDetectionJobs.html */ public toListKeyPhrasesDetectionJobs() { return this.to('ListKeyPhrasesDetectionJobs'); } /** * Grants permission to get a list of PII entities detection jobs that you have submitted * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListPiiEntitiesDetectionJobs.html */ public toListPiiEntitiesDetectionJobs() { return this.to('ListPiiEntitiesDetectionJobs'); } /** * Grants permission to get a list of sentiment detection jobs that you have submitted * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListSentimentDetectionJobs.html */ public toListSentimentDetectionJobs() { return this.to('ListSentimentDetectionJobs'); } /** * Grants permission to list tags for a resource * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to get a list of the topic detection jobs that you have submitted * * Access Level: Read * * https://docs.aws.amazon.com/comprehend/latest/dg/API_ListTopicsDetectionJobs.html */ public toListTopicsDetectionJobs() { return this.to('ListTopicsDetectionJobs'); } /** * Grants permission to start an asynchronous document classification job * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifVolumeKmsKey() * - .ifOutputKmsKey() * - .ifVpcSecurityGroupIds() * - .ifVpcSubnets() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StartDocumentClassificationJob.html */ public toStartDocumentClassificationJob() { return this.to('StartDocumentClassificationJob'); } /** * Grants permission to start an asynchronous dominant language detection job for a collection of documents * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifVolumeKmsKey() * - .ifOutputKmsKey() * - .ifVpcSecurityGroupIds() * - .ifVpcSubnets() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StartDominantLanguageDetectionJob.html */ public toStartDominantLanguageDetectionJob() { return this.to('StartDominantLanguageDetectionJob'); } /** * Grants permission to start an asynchronous entity detection job for a collection of documents * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifVolumeKmsKey() * - .ifOutputKmsKey() * - .ifVpcSecurityGroupIds() * - .ifVpcSubnets() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StartEntitiesDetectionJob.html */ public toStartEntitiesDetectionJob() { return this.to('StartEntitiesDetectionJob'); } /** * Grants permission to start an asynchronous Events detection job for a collection of documents * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifOutputKmsKey() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StartEventsDetectionJob.html */ public toStartEventsDetectionJob() { return this.to('StartEventsDetectionJob'); } /** * Grants permission to start an asynchronous key phrase detection job for a collection of documents * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifVolumeKmsKey() * - .ifOutputKmsKey() * - .ifVpcSecurityGroupIds() * - .ifVpcSubnets() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StartKeyPhrasesDetectionJob.html */ public toStartKeyPhrasesDetectionJob() { return this.to('StartKeyPhrasesDetectionJob'); } /** * Grants permission to start an asynchronous PII entities detection job for a collection of documents * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifOutputKmsKey() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StartPiiEntitiesDetectionJob.html */ public toStartPiiEntitiesDetectionJob() { return this.to('StartPiiEntitiesDetectionJob'); } /** * Grants permission to start an asynchronous sentiment detection job for a collection of documents * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifVolumeKmsKey() * - .ifOutputKmsKey() * - .ifVpcSecurityGroupIds() * - .ifVpcSubnets() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StartSentimentDetectionJob.html */ public toStartSentimentDetectionJob() { return this.to('StartSentimentDetectionJob'); } /** * Grants permission to start an asynchronous job to detect the most common topics in the collection of documents and the phrases associated with each topic * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifVolumeKmsKey() * - .ifOutputKmsKey() * - .ifVpcSecurityGroupIds() * - .ifVpcSubnets() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StartTopicsDetectionJob.html */ public toStartTopicsDetectionJob() { return this.to('StartTopicsDetectionJob'); } /** * Grants permission to stop a dominant language detection job * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StopDominantLanguageDetectionJob.html */ public toStopDominantLanguageDetectionJob() { return this.to('StopDominantLanguageDetectionJob'); } /** * Grants permission to stop an entity detection job * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StopEntitiesDetectionJob.html */ public toStopEntitiesDetectionJob() { return this.to('StopEntitiesDetectionJob'); } /** * Grants permission to stop an Events detection job * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StopEventsDetectionJob.html */ public toStopEventsDetectionJob() { return this.to('StopEventsDetectionJob'); } /** * Grants permission to stop a key phrase detection job * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StopKeyPhrasesDetectionJob.html */ public toStopKeyPhrasesDetectionJob() { return this.to('StopKeyPhrasesDetectionJob'); } /** * Grants permission to stop a PII entities detection job * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StopPiiEntitiesDetectionJob.html */ public toStopPiiEntitiesDetectionJob() { return this.to('StopPiiEntitiesDetectionJob'); } /** * Grants permission to stop a sentiment detection job * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StopSentimentDetectionJob.html */ public toStopSentimentDetectionJob() { return this.to('StopSentimentDetectionJob'); } /** * Grants permission to stop a previously created document classifier training job * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StopTrainingDocumentClassifier.html */ public toStopTrainingDocumentClassifier() { return this.to('StopTrainingDocumentClassifier'); } /** * Grants permission to stop a previously created entity recognizer training job * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_StopTrainingEntityRecognizer.html */ public toStopTrainingEntityRecognizer() { return this.to('StopTrainingEntityRecognizer'); } /** * Grants permission to tag a resource with given key value pairs * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to untag a resource with given key * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/comprehend/latest/dg/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update information about the specified endpoint * * Access Level: Write * * https://docs.aws.amazon.com/comprehend/latest/dg/API_UpdateEndpoint.html */ public toUpdateEndpoint() { return this.to('UpdateEndpoint'); } protected accessLevelList: AccessLevelList = { "Read": [ "BatchDetectDominantLanguage", "BatchDetectEntities", "BatchDetectKeyPhrases", "BatchDetectSentiment", "BatchDetectSyntax", "ClassifyDocument", "ContainsPiiEntities", "DescribeDocumentClassificationJob", "DescribeDocumentClassifier", "DescribeDominantLanguageDetectionJob", "DescribeEndpoint", "DescribeEntitiesDetectionJob", "DescribeEntityRecognizer", "DescribeEventsDetectionJob", "DescribeKeyPhrasesDetectionJob", "DescribePiiEntitiesDetectionJob", "DescribeSentimentDetectionJob", "DescribeTopicsDetectionJob", "DetectDominantLanguage", "DetectEntities", "DetectKeyPhrases", "DetectPiiEntities", "DetectSentiment", "DetectSyntax", "ListDocumentClassificationJobs", "ListDocumentClassifierSummaries", "ListDocumentClassifiers", "ListDominantLanguageDetectionJobs", "ListEndpoints", "ListEntitiesDetectionJobs", "ListEntityRecognizerSummaries", "ListEntityRecognizers", "ListEventsDetectionJobs", "ListKeyPhrasesDetectionJobs", "ListPiiEntitiesDetectionJobs", "ListSentimentDetectionJobs", "ListTagsForResource", "ListTopicsDetectionJobs" ], "Write": [ "CreateDocumentClassifier", "CreateEndpoint", "CreateEntityRecognizer", "DeleteDocumentClassifier", "DeleteEndpoint", "DeleteEntityRecognizer", "StartDocumentClassificationJob", "StartDominantLanguageDetectionJob", "StartEntitiesDetectionJob", "StartEventsDetectionJob", "StartKeyPhrasesDetectionJob", "StartPiiEntitiesDetectionJob", "StartSentimentDetectionJob", "StartTopicsDetectionJob", "StopDominantLanguageDetectionJob", "StopEntitiesDetectionJob", "StopEventsDetectionJob", "StopKeyPhrasesDetectionJob", "StopPiiEntitiesDetectionJob", "StopSentimentDetectionJob", "StopTrainingDocumentClassifier", "StopTrainingEntityRecognizer", "UpdateEndpoint" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type document-classifier to the statement * * @param documentClassifierName - Identifier for the documentClassifierName. * @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 onDocumentClassifier(documentClassifierName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:document-classifier/${DocumentClassifierName}'; arn = arn.replace('${DocumentClassifierName}', documentClassifierName); 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 document-classifier-endpoint to the statement * * @param documentClassifierEndpointName - Identifier for the documentClassifierEndpointName. * @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 onDocumentClassifierEndpoint(documentClassifierEndpointName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:document-classifier-endpoint/${DocumentClassifierEndpointName}'; arn = arn.replace('${DocumentClassifierEndpointName}', documentClassifierEndpointName); 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 entity-recognizer to the statement * * @param entityRecognizerName - Identifier for the entityRecognizerName. * @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 onEntityRecognizer(entityRecognizerName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:entity-recognizer/${EntityRecognizerName}'; arn = arn.replace('${EntityRecognizerName}', entityRecognizerName); 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 entity-recognizer-endpoint to the statement * * @param entityRecognizerEndpointName - Identifier for the entityRecognizerEndpointName. * @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 onEntityRecognizerEndpoint(entityRecognizerEndpointName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:entity-recognizer-endpoint/${EntityRecognizerEndpointName}'; arn = arn.replace('${EntityRecognizerEndpointName}', entityRecognizerEndpointName); 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 dominant-language-detection-job to the statement * * @param jobId - Identifier for the jobId. * @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 onDominantLanguageDetectionJob(jobId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:dominant-language-detection-job/${JobId}'; arn = arn.replace('${JobId}', jobId); 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 entities-detection-job to the statement * * @param jobId - Identifier for the jobId. * @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 onEntitiesDetectionJob(jobId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:entities-detection-job/${JobId}'; arn = arn.replace('${JobId}', jobId); 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 pii-entities-detection-job to the statement * * @param jobId - Identifier for the jobId. * @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 onPiiEntitiesDetectionJob(jobId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:pii-entities-detection-job/${JobId}'; arn = arn.replace('${JobId}', jobId); 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 events-detection-job to the statement * * @param jobId - Identifier for the jobId. * @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 onEventsDetectionJob(jobId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:events-detection-job/${JobId}'; arn = arn.replace('${JobId}', jobId); 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 key-phrases-detection-job to the statement * * @param jobId - Identifier for the jobId. * @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 onKeyPhrasesDetectionJob(jobId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:key-phrases-detection-job/${JobId}'; arn = arn.replace('${JobId}', jobId); 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 sentiment-detection-job to the statement * * @param jobId - Identifier for the jobId. * @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 onSentimentDetectionJob(jobId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:sentiment-detection-job/${JobId}'; arn = arn.replace('${JobId}', jobId); 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 topics-detection-job to the statement * * @param jobId - Identifier for the jobId. * @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 onTopicsDetectionJob(jobId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:topics-detection-job/${JobId}'; arn = arn.replace('${JobId}', jobId); 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 document-classification-job to the statement * * @param jobId - Identifier for the jobId. * @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 onDocumentClassificationJob(jobId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:comprehend:${Region}:${Account}:document-classification-job/${JobId}'; arn = arn.replace('${JobId}', jobId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access by the model KMS key associated with the resource in the request * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncomprehend.html#amazoncomprehend-policy-keys * * Applies to actions: * - .toCreateDocumentClassifier() * - .toCreateEntityRecognizer() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifModelKmsKey(value: string | string[], operator?: Operator | string) { return this.if(`ModelKmsKey`, value, operator || 'ArnLike'); } /** * Filters access by the output KMS key associated with the resource in the request * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncomprehend.html#amazoncomprehend-policy-keys * * Applies to actions: * - .toCreateDocumentClassifier() * - .toStartDocumentClassificationJob() * - .toStartDominantLanguageDetectionJob() * - .toStartEntitiesDetectionJob() * - .toStartEventsDetectionJob() * - .toStartKeyPhrasesDetectionJob() * - .toStartPiiEntitiesDetectionJob() * - .toStartSentimentDetectionJob() * - .toStartTopicsDetectionJob() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifOutputKmsKey(value: string | string[], operator?: Operator | string) { return this.if(`OutputKmsKey`, value, operator || 'ArnLike'); } /** * Filters access by the volume KMS key associated with the resource in the request * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncomprehend.html#amazoncomprehend-policy-keys * * Applies to actions: * - .toCreateDocumentClassifier() * - .toCreateEntityRecognizer() * - .toStartDocumentClassificationJob() * - .toStartDominantLanguageDetectionJob() * - .toStartEntitiesDetectionJob() * - .toStartKeyPhrasesDetectionJob() * - .toStartSentimentDetectionJob() * - .toStartTopicsDetectionJob() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifVolumeKmsKey(value: string | string[], operator?: Operator | string) { return this.if(`VolumeKmsKey`, value, operator || 'ArnLike'); } /** * Filters access by the list of all VPC security group ids associated with the resource in the request * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncomprehend.html#amazoncomprehend-policy-keys * * Applies to actions: * - .toCreateDocumentClassifier() * - .toCreateEntityRecognizer() * - .toStartDocumentClassificationJob() * - .toStartDominantLanguageDetectionJob() * - .toStartEntitiesDetectionJob() * - .toStartKeyPhrasesDetectionJob() * - .toStartSentimentDetectionJob() * - .toStartTopicsDetectionJob() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifVpcSecurityGroupIds(value: string | string[], operator?: Operator | string) { return this.if(`VpcSecurityGroupIds`, value, operator || 'StringLike'); } /** * Filters access by the list of all VPC subnets associated with the resource in the request * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncomprehend.html#amazoncomprehend-policy-keys * * Applies to actions: * - .toCreateDocumentClassifier() * - .toCreateEntityRecognizer() * - .toStartDocumentClassificationJob() * - .toStartDominantLanguageDetectionJob() * - .toStartEntitiesDetectionJob() * - .toStartKeyPhrasesDetectionJob() * - .toStartSentimentDetectionJob() * - .toStartTopicsDetectionJob() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifVpcSubnets(value: string | string[], operator?: Operator | string) { return this.if(`VpcSubnets`, value, operator || 'StringLike'); } }
the_stack
import * as _ from 'lodash' import * as PpUtils from './pputils' import * as Option from '../clib/option' import * as PpExtend from '../interp/ppextend' import * as ConstrExpr from '../intf/constr-expr' import * as MiscTypes from '../intf/misctypes' import * as Names from '../kernel/names' import { cAST } from '../lib/c-ast' import * as Loc from '../lib/loc' import * as Pp from '../lib/pp' import * as StrToken from '../str-token' import { PpCmdGlue } from '../lib/pp'; import { CLocalDef, LocalBinderExpr } from '../intf/constr-expr'; export type PrecAssoc = [number, ParenRelation] const lAtom = 0 const lProd = 200 const lLambda = 200 const lIf = 200 const lLetIn = 200 const lLetPattern = 200 const lFix = 200 const lCast = 100 const lArg = 9 const lApp = 10 const lPosInt = 0 const lNegInt = 35 const lTop : PrecAssoc = [200, new E()] const lProj = 1 const lDelim = 1 const lSimpleConstr : PrecAssoc = [8, new E()] const lSimplePatt : PrecAssoc = [1, new E()] export function precLess(child : number, parent : PrecAssoc) { const [parentPrec, parentAssoc] = parent if (parentPrec < 0 && child === lProd) { return true } const absParentPrec = Math.abs(parentPrec) if (parentAssoc instanceof E) { return child <= absParentPrec } if (parentAssoc instanceof L) { return child < absParentPrec } if (parentAssoc instanceof Prec) { return child <= parentAssoc.precedence } if (parentAssoc instanceof Any) { return true } } /* peaCoqBox should not disrupt the pretty-printing flow, but add a <span> so that sub-expression highlighting is more accurate */ function peaCoqBox(l : Pp.t) : Pp.t { return [new Pp.PpCmdBox(new Pp.PpHoVBox(0), [l])] } function prComAt(n : number) : Pp.t { return Pp.mt() } function prId(id : string) : Pp.t { return Names.Id.print(id) } function prLIdent(i : cAST<string>) : Pp.t { const id = i.v return i.loc.caseOf({ nothing : () => prId(id), just : (loc : Loc.t) => { const [b, ] = Loc.unLoc(loc) return PpUtils.prLocated(prId, [just(Loc.makeLoc(b, b + Names.Id.toString(id).length)), id]) }, }) } function prName(n : Names.Name.t) : Pp.t { return Names.Name.print(n) } function prLName(ln : MiscTypes.lname) : Pp.t { const v = ln.v if (v instanceof Name) { return peaCoqBox(prLIdent(new cAST(v.id, ln.loc))) } else { return peaCoqBox(PpUtils.prAST(Names.Name.print, ln)) } } function surroundImpl(k : BindingKind, p : Pp.t) : Pp.t { if (k instanceof Explicit) { return ([] as Pp.t[]).concat(Pp.str('('), p, Pp.str(')')) } if (k instanceof Implicit) { return ([] as Pp.t[]).concat(Pp.str('{'), p, Pp.str('}')) } throw MatchFailure('surroundImpl', k) } function surroundImplicit(k : BindingKind, p : Pp.t) : Pp.t { if (k instanceof Explicit) { return p } if (k instanceof Implicit) { return ([] as Pp.t[]).concat(Pp.str('{'), p, Pp.str('}')) } throw MatchFailure('surroundImplicit', k) } function prBinder( many : boolean, pr : (c : ConstrExpr) => Pp.t, [nal, k, t] : [cAST<Name>[], BinderKind, ConstrExpr] ) : Pp.t { if (k instanceof Generalized) { const [b, bp, tp] = [k.kind1, k.kind2, k.b] throw 'TODO : prBinder Generalized' } if (k instanceof Default) { const b = k.kind if (t instanceof ConstrExpr.CHole && t.introPatternNamingExpr instanceof MiscTypes.IntroAnonymous) { throw 'TODO : prBinder CHole' } else { const s = ([] as Pp.t[]).concat( Pp.prListWithSep(Pp.spc, prLName, nal), Pp.str(' : '), pr(t) ) return peaCoqBox(many ? surroundImpl(b, s) : surroundImplicit(b, s)) } } throw MatchFailure('prBinder', k) } function prDelimitedBinders( kw : (n : number) => Pp.t, sep : () => Pp.t, prC : (t : ConstrExpr) => Pp.t, bl : ConstrExpr.LocalBinderExpr[] ) : Pp.t { const n = beginOfBinders(bl) if (bl.length === 0) { throw 'prDelimitedBinders : bl should not be empty' } const bl0 = bl[0] if (bl0 instanceof ConstrExpr.CLocalAssum && bl.length === 1) { const [nal, k, t] = [bl0.names, bl0.binderKind, bl0.type] return (([] as Pp.t[]).concat(kw(n), prBinder(false, prC, [nal, k, t]))) } else { return (([] as Pp.t[]).concat(kw(n), prUndelimitedBinders(sep, prC, bl))) } } function tagEvar(p : Pp.t) : Pp.t { return Pp.tag('evar', p) } function tagKeyword(p : Pp.t) : Pp.t { return Pp.tag('keyword', p) } function tagNotation(r : Pp.t) : Pp.t { return Pp.tag('notation', r) } function tagPath(p : Pp.t) : Pp.t { return Pp.tag('path', p) } function tagRef(r : Pp.t) : Pp.t { return Pp.tag('reference', r) } function tagType(r : Pp.t) : Pp.t { return Pp.tag('univ', r) } function tagVariable(p : Pp.t) : Pp.t { return Pp.tag('variable', p) } function keyword(s : string) : Pp.t { return tagKeyword(Pp.str(s)) } function prForall() : Pp.t { return ([] as Pp.t[]).concat(keyword('forall'), Pp.spc()) } function prFun() : Pp.t { return ([] as Pp.t[]).concat(keyword('fun'), Pp.spc()) } const maxInt = 9007199254740991 function prBinderAmongMany( prC : (t : ConstrExpr) => Pp.t, b : ConstrExpr.LocalBinderExpr ) : Pp.t { if (b instanceof ConstrExpr.CLocalAssum) { const [nal, k, t] = [b.names, b.binderKind, b.type] return prBinder(true, prC, [nal, k, t]) } if (b instanceof ConstrExpr.CLocalDef) { const [na, c, topt] = [b.name, b.value, b.optionalType] // const cp, topt /* TODO : if (c instanceof CCast) { throw 'TODO : prBinderAmongMany then' } else { throw 'TODO : prBinderAmongMany else' } */ debugger throw b } debugger throw b } function prUndelimitedBinders( sep : () => Pp.t, prC : (t : ConstrExpr) => Pp.t, l : ConstrExpr.LocalBinderExpr[] ) { return Pp.prListWithSep(sep, (b) => prBinderAmongMany(prC, b), l) } function prBindersGen( prC : (t : ConstrExpr) => Pp.t, sep : () => Pp.t, isOpen : boolean, ul : ConstrExpr.LocalBinderExpr[] ) { if (isOpen) { return prDelimitedBinders(Pp.mt, sep, prC, ul) } else { return prUndelimitedBinders(sep, prC, ul) } } function tagUnparsing(unp : PpExtend.Unparsing, pp1 : Pp.t) : Pp.t { if (unp instanceof PpExtend.UnpTerminal) { return tagNotation(pp1) } return pp1 } function printHunks( n : number, pr : (_1 : [number, ParenRelation], _2 : ConstrExpr) => Pp.t, prPatt : (_1 : [number, ParenRelation], _2 : CasesPatternExpr) => Pp.t, prBinders : (_1 : () => Pp.t, _2 : boolean, _3 : ConstrExpr.ConstrExprR) => Pp.t, [terms, termlists, binders, binderlists] : ConstrExpr.ConstrNotationSubstitution, unps : PpExtend.Unparsing[] ) : Pp.t { const env = terms.slice(0) const envlist = termlists.slice(0) const bl = binders.slice(0) const bll = binderlists.slice(0) function pop<T>(a : T[]) : T { const res = a.shift() if (res === undefined) { debugger throw a } return res } function ret(unp : PpExtend.Unparsing, pp1 : Pp.t, pp2 : Pp.t) : Pp.t { return ([] as Pp.t[]).concat(tagUnparsing(unp, pp1), pp2) } function aux(ul : PpExtend.Unparsing[]) : Pp.t { if (ul.length === 0) { return Pp.mt() } const unp = ul[0] const l = _.tail(ul) if (unp instanceof PpExtend.UnpMetaVar) { const prec = unp.parenRelation const c = pop(env) const pp2 = aux(l) const pp1 = pr([n, prec], c) return ret(unp, pp1, pp2) } if (unp instanceof PpExtend.UnpBinderMetaVar) { const [prec] = [unp.parenRelation] const c = pop(bl) const pp2 = aux(l) const pp1 = prPatt([n, prec], c) return ret(unp, pp1, pp2) } if (unp instanceof PpExtend.UnpListMetaVar) { const [prec, sl] = [unp.parenRelation, unp.unparsing] const cl = pop(envlist) const pp1 = Pp.prListWithSep( () => aux(sl), x => pr([n, prec], x), cl ) const pp2 = aux(l) return ret(unp, pp1, pp2) } if (unp instanceof PpExtend.UnpBinderListMetaVar) { const [isOpen, sl] = [unp.isOpen, unp.unparsing] const cl = pop(bll) const pp2 = aux(l) const pp1 = prBinders(() => aux(sl), isOpen, cl) return ret(unp, pp1, pp2) } if (unp instanceof PpExtend.UnpTerminal) { const s = unp.terminal const pp2 = aux(l) const pp1 = Pp.str(s) return ret(unp, pp1, pp2) } if (unp instanceof PpExtend.UnpBox) { const [b, sub] = [unp.box, unp.unparsing] const pp1 = PpExtend.PpCmdOfBox(b, aux(sub)) const pp2 = aux(l) return ret(unp, pp1, pp2) } if (unp instanceof PpExtend.UnpCut) { const pp2 = aux(l) const pp1 = PpExtend.PpCmdOfCut(unp.cut) return ret(unp, pp1, pp2) } throw MatchFailure('printHunks', unp) } return aux(unps) } type PpResult = [Pp.t, number] // Here Coq would consult the notation table to figure [unpl] and [level] from // [s], but we have it already figured out. function prNotation( pr : (_1 : [number, ParenRelation], _2 : ConstrExpr.ConstrExprR) => Pp.t, prPatt : (_1 : [number, ParenRelation], _2 : CasesPatternExpr) => Pp.t, prBinders : (_1 : () => Pp.t, _2 : boolean, _3 : ConstrExpr.LocalBinderExpr[]) => Pp.t, s : ConstrExpr.Notation, env : ConstrExpr.ConstrNotationSubstitution, // these extra arguments are PeaCoq-specific unpl : PpExtend.Unparsing[], level : number ) : PpResult { return [ printHunks(level, pr, prPatt, prBinders, env, unpl), level ] } function reprQualid(sp : QualId) : QualId { return sp } function prList<T>(pr : (t : T) => Pp.t, l : T[]) : Pp.t { return new Pp.PpCmdGlue(l.map(pr)) } function prQualid(sp : QualId) : Pp.t { const [sl0, id0] = reprQualid(sp) const id = tagRef(Names.Id.print(id0)) const rev = Names.DirPath.repr(sl0).slice(0).reverse() const sl = ( (rev.length === 0) ? Pp.mt() : prList( (dir : string) => ([] as Pp.t[]).concat(tagPath(Names.Id.print(dir)), Pp.str('.')), sl0 ) ) return ([] as Pp.t[]).concat(sl, id) } function prReference(r : Reference) : Pp.t { if (r instanceof Qualid) { return peaCoqBox(prQualid(r.lQualid[1])) } if (r instanceof Ident) { return peaCoqBox(tagVariable(Pp.str(r.id[1]))) } throw MatchFailure('prReference', r) } function prGlobSortInstance<T>(i : IGlobSortGen<T>) : Pp.t { if (i instanceof GProp) { return tagType(Pp.str('Prop')) } if (i instanceof GSet) { return tagType(Pp.str('Set')) } if (i instanceof GType) { // TODO : this is weird, it's not a Maybe, probably a bug here return i.type.caseOf({ nothing : () => tagType(Pp.str('Type')), just : (t : string) => Pp.str(t), }) } throw MatchFailure('prGlobSortInstance', i) } function prOptNoSpc<T>(pr : (t : T) => Pp.t, mx : Maybe<T>) : Pp.t { return mx.caseOf({ nothing : () => Pp.mt(), just : x => pr(x), }) } function prUnivAnnot<T>(pr : (t : T) => Pp.t, x : T) : Pp.t { return ([] as Pp.t[]).concat(Pp.str('@{'), pr(x), Pp.str('}')) } function prUniverseInstance(us : Maybe<InstanceExpr>) : Pp.t { return prOptNoSpc( x => { return prUnivAnnot( y => Pp.prListWithSep(Pp.spc, prGlobSortInstance, y), x ) }, us ) } function prCRef(r : Reference, us : Maybe<InstanceExpr>) : Pp.t { return ([] as Pp.t[]).concat(prReference(r), prUniverseInstance(us)) } function chop<T>(i : number, l : T[]) : [T[], T[]] { return [l.slice(0, i), l.slice(i)] } function sepLast<T>(l : T[]) : [T, T[]] { const len = l.length return [l[len - 1], l.slice(0, len - 1)] } function prProj( pr : (_1 : ConstrExpr.ConstrExprR, _2 : ConstrExpr) => Pp.t, prApp : ( pr : (_1 : PrecAssoc, _2 : ConstrExpr) => Pp.t, a : ConstrExpr, l : ConstrExpr.AppArgs ) => Pp.t, a : ConstrExpr, f : ConstrExpr, l : ConstrExpr.AppArgs ) : Pp.t { return ([] as Pp.t[]).concat( pr([lProj, new E()], a), Pp.cut(), Pp.str('.('), prApp(pr, f, l), Pp.str(')') ) } function prExplArgs( pr : (pa : PrecAssoc, ce : ConstrExpr) => Pp.t, [a, mexpl] : ConstrExpr.AppArg ) : Pp.t { return mexpl.caseOf({ nothing : () => pr([lApp, new L()], a), just : expl => { const e = expl.some[1] if (e instanceof ExplByPos) { throw 'Anomaly : Explicitation by position not implemented' } if (e instanceof ExplByName) { return ([] as Pp.t[]).concat(Pp.str('('), prId(e.name), Pp.str(' :='), pr(lTop, a), Pp.str(')')) } throw MatchFailure('prExplArgs', e) }, }) } function prApp( pr : (_1 : PrecAssoc, _2 : ConstrExpr) => Pp.t, a : ConstrExpr, l : ConstrExpr.AppArgs ) { return Pp.hov( 2, ([] as Pp.t[]).concat( pr([lApp, new L()], a), prList(a => ([] as Pp.t[]).concat(Pp.spc(), prExplArgs(pr, a)), l) ) ) } function precOfPrimToken(t : PrimToken) : number { if (t instanceof Numeral) { return t.sign ? lPosInt : lNegInt } if (t instanceof PrimTokenString) { return lAtom } throw MatchFailure('precOfPrimToken', t) } function qs(s : string) : Pp.t { return Pp.str('\'' + s + '\'') } function prPrimToken(t : PrimToken) : Pp.t { if (t instanceof Numeral) { return Pp.str(t.sign ? t.raw : `-${t.raw}`) } if (t instanceof PrimTokenString) { return qs(t.str) } throw MatchFailure('prPrimToken', t) } function prUniv(l : string[]) { if (l.length === 1) { return Pp.str(l[0]) } else { return ([] as Pp.t[]).concat( Pp.str('max('), Pp.prListWithSep(() => Pp.str(','), Pp.str, l), Pp.str(')') ) } } function prGlobSort(s : GlobSort) : Pp.t { if (s instanceof GProp) { return tagType(Pp.str('Prop')) } if (s instanceof GSet) { return tagType(Pp.str('Set')) } if (s instanceof GType) { if (s.type.length === 0) { return tagType(Pp.str('Type')) } else { return Pp.hov( 0, ([] as Pp.t[]).concat(tagType(Pp.str('Type')), prUnivAnnot(prUniv, s.type)) ) } } throw MatchFailure('prGlobSort', s) } function prDelimiters(key : string, strm : Pp.t) : Pp.t { return peaCoqBox(([] as Pp.t[]).concat(strm, Pp.str('%' + key))) } function tagConstrExpr(ce : ConstrExpr, cmds : Pp.t) { return peaCoqBox(cmds) } function prDanglingWithFor( sep : () => Pp.t, pr : (_1 : () => Pp.t, _2 : PrecAssoc, _3 : ConstrExpr.ConstrExprR) => Pp.t, inherited : PrecAssoc, a : ConstrExpr ) : Pp.t { if (a.v instanceof ConstrExpr.CFix || a.v instanceof ConstrExpr.CCoFix) { throw 'TODO: CFix or CCoFix' } return pr(sep, inherited, a) } function prWithComments( loc : Maybe<Loc.t>, pp : Pp.t ) : Pp.t { return PpUtils.prLocated(x => x, [loc, pp]) } function prPatt( sep : () => Pp.t, inh : PrecAssoc, p : ConstrExpr.ConstrExpr ) : Pp.t { function match(pp : ConstrExpr.ConstrExprR) : [Pp.t, number] { // TODO CPatRecord // TODO CPatAlias if (pp instanceof CPatCstr) { return pp.cases1.caseOf<[Pp.t, number]>({ nothing : () => { if (pp.cases2.length === 0) { return [prReference(pp.reference), lAtom] } else { return [ ([] as Pp.t[]).concat( prReference(pp.reference), prList( x => prPatt(Pp.spc, [lApp, new L()], x), pp.cases2 ) ), lApp ] } }, just : cases1 => { if (pp.cases2.length === 0) { return [ ([] as Pp.t[]).concat( Pp.str('@'), prReference(pp.reference), prList( x => prPatt(Pp.spc, [lApp, new L()], x), cases1 ) ), lApp ] } return [ ([] as Pp.t[]).concat( Pp.surround(([] as Pp.t[]).concat( Pp.str('@'), prReference(pp.reference), prList( x => prPatt(Pp.spc, [lApp, new L()], x), cases1 ) )), prList( x => prPatt(Pp.spc, [lApp, new L()], x), pp.cases2 ) ), lApp ] }, }) } else if (pp instanceof CPatAtom) { const r = pp.reference return r.caseOf<PpResult>({ nothing : () => [Pp.str('_'), lAtom], just : r => [prReference(r), lAtom], }) // } else if (p instanceof CPatOr) { // TODO } else if (pp instanceof CPatNotation) { if ( pp.notation === '( _ )' && pp.substitution[0].length === 1 && pp.substitution[1].length === 0 && pp.patterns.length === 0 ) { const p = pp.substitution[0][0] return [ ([] as Pp.t[]).concat( prPatt(() => Pp.str('('), [Number.MAX_VALUE, new E()], p), Pp.str(')') ) , lAtom ] } else { const s = pp.notation const [l, ll] = pp.substitution const args = pp.patterns const [strmNot, lNot] = prNotation( (x, y : CasesPatternExpr) => prPatt(Pp.mt, x, y), (x : any, y : any) => Pp.mt(), (x : any, y : any, z : any) => Pp.mt(), s, [l, ll, [], []], pp.unparsing, pp.precedence ) const prefix = (args.length === 0 || precLess(lNot, [lApp, new L()])) ? strmNot : Pp.surround(strmNot) return [ ([] as Pp.t[]).concat(prefix, prList(x => prPatt(Pp.spc, [lApp, new L()], x), args)), args.length === 0 ? lNot : lApp ] } } else if (pp instanceof CPatPrim) { return [prPrimToken(pp.token), lAtom] } else if (pp instanceof CPatDelimiters) { return [ prDelimiters(pp.str, prPatt(Pp.mt, lSimplePatt, pp.cases)), 1 ] } else { throw MatchFailure('prPatt > match', pp) } } const [strm, prec] = match(p.v) const loc = p.loc return prWithComments(loc, ([] as Pp.t[]).concat( sep(), precLess(prec, inh) ? strm : Pp.surround(strm) )) } function prAsin( pr : (_1 : PrecAssoc, _2 : ConstrExpr) => Pp.t, mna : Maybe<MiscTypes.lname>, indnalopt : Maybe<ConstrExpr> ) : Pp.t { return ([] as Pp.t[]).concat( mna.caseOf({ nothing : () => Pp.mt(), just : na => ([] as Pp.t[]).concat( Pp.spc(), keyword('as'), Pp.spc(), prLName(na) ), }), indnalopt.caseOf({ nothing : () => Pp.mt(), just : i => ([] as Pp.t[]).concat( Pp.spc(), keyword('in'), Pp.spc(), prPatt(Pp.mt, lSimplePatt, i) ), }) ) } function prCaseItem( pr : (_1 : PrecAssoc, _2 : ConstrExpr) => Pp.t, [tm, asClause, inClause] : [ConstrExpr, Maybe<cAST<Name>>, Maybe<ConstrExpr>] ) : Pp.t { return Pp.hov(0, ([] as Pp.t[]).concat( pr([lCast, new E()], tm), prAsin(pr, asClause, inClause) )) } function sepV() : Pp.t { return ([] as Pp.t[]).concat(Pp.str(','), Pp.spc()) } function constrLoc(c : ConstrExpr) : Maybe<Loc.t> { return c.loc } function prSepCom( sep : () => Pp.t, f : (c : ConstrExpr) => Pp.t, c : ConstrExpr ) : Pp.t { return prWithComments(constrLoc(c), ([] as Pp.t[]).concat(sep(), f(c))) } function prCaseType( pr : (_1 : PrecAssoc, _2 : ConstrExpr) => Pp.t, mpo : Maybe<ConstrExpr> ) : Pp.t { // TODO : po instanceof CHole with IntroAnonymous return mpo.caseOf({ nothing : () => Pp.mt(), just : po => ([] as Pp.t[]).concat( Pp.spc(), Pp.hov(2, ([] as Pp.t[]).concat( keyword('return'), prSepCom(Pp.spc, x => pr(lSimpleConstr, x), po) )) ), }) } function prEqn( pr : (_1 : PrecAssoc, _2 : ConstrExpr) => Pp.t, { loc, v } : ConstrExpr.BranchExpr ) : Pp.t { const [pl, rhs] = v // const pl1 = _(pl0).map((located : Located<Array<CasesPatternExpr>>) => located[1]).value() return ([] as Pp.t[]).concat( Pp.spc(), Pp.hov(4, prWithComments( loc, ([] as Pp.t[]).concat( Pp.str('| '), Pp.hov(0, ([] as Pp.t[]).concat( Pp.prListWithSep( Pp.prSpaceBar, (x : ConstrExpr.ConstrExpr[]) => Pp.prListWithSep(sepV, (y : ConstrExpr.ConstrExpr) => prPatt(Pp.mt, lTop, y), x), pl ), Pp.str(' =>') )), prSepCom(Pp.spc, x => pr(lTop, x), rhs) ) ) ) ) } function prSimpleReturnType( pr : (_1 : PrecAssoc, _2 : ConstrExpr) => Pp.t, na : Maybe<MiscTypes.lname>, po : Maybe<ConstrExpr> ) : Pp.t { return ( ([] as Pp.t[]).concat( na.caseOf({ nothing : () => Pp.mt(), just : x => x.v instanceof Name ? ([] as Pp.t[]).concat(Pp.spc(), keyword('as'), prId(x.v.id)) : Pp.mt() }) ) ) } const prFunSep : Pp.t = ([] as Pp.t[]).concat(Pp.spc(), Pp.str('=>')) function prGen( pr : (_1 : () => Pp.t, _2 : PrecAssoc, _3 : ConstrExpr) => Pp.t ) : (_1 : () => Pp.t, _2 : PrecAssoc, _3 : ConstrExpr) => Pp.t { return ( sep : () => Pp.t, inherited : PrecAssoc, a : ConstrExpr ) => { function ret(cmds : Pp.t, prec : number) : PpResult { return [tagConstrExpr(a, cmds), prec] } const prmt = (x : [number, ParenRelation], y : ConstrExpr) => pr(Pp.mt, x, y) function match(aa : ConstrExpr.ConstrExprR) : PpResult { if (aa instanceof ConstrExpr.CApp) { // TODO : ldots_var const pf = aa.funct[0] const f = aa.funct[1] return pf.caseOf<PpResult>({ nothing : () => { const b = <ConstrExpr.CApp>aa // TS bug const [f, l] = [b.funct[1], b.args] return ret(prApp(prmt, f, l), lApp) }, just : pf => { const b = <ConstrExpr.CApp>aa // TS bug const [i, f, l] = [pf, b.funct[1], b.args] const [l1, l2] = chop(i, l) const [c, rest] = sepLast(l1) // TODO : assert c[1] is empty option? const p = prProj(prmt, prApp, c[0], f, rest) // TODO : it might be nice if we could highlight the structure // nested applications, rather than having a flat n-ary one if (l2.length > 0) { return ret( ([] as Pp.t[]).concat( p, prList( aaa => { return ([] as Pp.t[]).concat(Pp.spc(), prExplArgs(prmt, aaa)) }, l2 ) ), lApp ) } else { return [p, lProj] } }, }) } if (aa instanceof ConstrExpr.CCases) { if (aa.caseStyle instanceof LetPatternStyle) { throw 'TODO : LetPatternStyle' } const [rtnTypOpt, c, eqns] = [aa.returnType, aa.cases, aa.branches] const prDangling = (pa : [number, ParenRelation], c : ConstrExpr) => prDanglingWithFor(Pp.mt, pr, pa, c) return ret( Pp.v(0, Pp.hv(0, ([] as Pp.t[]).concat( keyword('match'), Pp.brk(1, 2), Pp.hov(0, Pp.prListWithSep( sepV, x => prCaseItem(prDangling, x), aa.cases ) ), prCaseType(prDangling, aa.returnType), Pp.spc(), keyword('with'), prList( (e : ConstrExpr.BranchExpr) => prEqn((x, y) => pr(Pp.mt, x, y), e), aa.branches ), Pp.spc(), keyword('end') ))), lAtom ) } if (aa instanceof ConstrExpr.CDelimiters) { const [sc, e] = [aa.str, aa.expr] return ret( prDelimiters(sc, pr(Pp.mt, [lDelim, new E()], e)), lDelim ) } if (aa instanceof ConstrExpr.CLambdaN) { const [bl, a1] = ConstrExpr.extractLamBinders(aa) return ret( Pp.hov(0, ([] as Pp.t[]).concat( Pp.hov(2, prDelimitedBinders(prFun, Pp.spc, x => pr(Pp.spc, lTop, x), bl)), prFunSep, pr(Pp.spc, lTop, a1) )), lLambda ) } if (aa instanceof ConstrExpr.CLetIn) { const [x, a, t, b] = [aa.name, aa.bound, aa.type, aa.body] if (a instanceof ConstrExpr.CFix || a instanceof ConstrExpr.CCoFix) { throw ('TODO : pr CLetIn with CFix/CcoFix') } return ret( Pp.hv(0, ([] as Pp.t[]).concat( Pp.hov(2, ([] as Pp.t[]).concat( keyword('let'), Pp.spc(), prLName(x), prOptNoSpc(t => ([] as Pp.t[]).concat(Pp.str(' :'), Pp.ws(1), pr(Pp.mt, lTop, t)), t), Pp.str(' :='), pr(Pp.spc, lTop, a), Pp.spc(), keyword('in') )), pr(Pp.spc, lTop, aa.body) )), lLetIn ) } if (aa instanceof ConstrExpr.CLetTuple) { const [nal, [na, po], c, b] = [aa.names, aa.returnType, aa.bound, aa.body] return ret( Pp.hv(0, Pp.hov(2, ([] as Pp.t[]).concat( keyword('let'), Pp.spc(), Pp.hov(1, ([] as Pp.t[]).concat( Pp.str('('), Pp.prListWithSep(sepV, prLName, nal), Pp.str(')'), prSimpleReturnType(prmt, na, po), Pp.str(' :='), pr(Pp.spc, lTop, aa.bound), Pp.spc(), keyword('in') )), pr(Pp.spc, lTop, aa.body) ) ) ), lLetIn ) } if (aa instanceof ConstrExpr.CNotation) { if (aa.notation === '(\u00A0_\u00A0)') { const [[t], [], []] = aa.substitution return ret( ([] as Pp.t[]).concat( pr( () => { return Pp.str('(') }, [maxInt, new L()], t ), Pp.str(')') ), lAtom ) } else { const [s, env] = [aa.notation, aa.substitution] return prNotation( (x : [number, ParenRelation], y : {}) => pr(Pp.mt, x, y), (x, y) => prPatt(Pp.mt, x, y), (x : () => Pp.t, y : boolean, z : LocalBinderExpr[]) => prBindersGen(w => pr(Pp.mt, lTop, w), x, y, z), s, env, aa.unparsing, aa.precedence ) } } if (aa instanceof ConstrExpr.CPrim) { return ret( prPrimToken(aa.token), precOfPrimToken(aa.token) ) } if (aa instanceof ConstrExpr.CProdN) { const [bl, aRest] = ConstrExpr.extractProdBinders(aa) return ret( ([] as Pp.t[]).concat( prDelimitedBinders( prForall, Pp.spc, x => pr(Pp.mt, lTop, x), bl), Pp.str(','), pr(Pp.spc, lTop, aRest) ), lProd ) } if (aa instanceof ConstrExpr.CRef) { const [r, us] = [aa.reference, aa.universeInstance] return ret( prCRef(r, us), lAtom ) } if (aa instanceof ConstrExpr.CSort) { return ret(prGlobSort(aa.globSort), lAtom) } throw MatchFailure('pr > match', aa) } const [strm, prec] = match(a) return ( ([] as Pp.t[]).concat( sep(), precLess(prec, inherited) ? strm : Pp.surround(strm) ) ) } } export function prConstrExpr(a : ConstrExpr) : Pp.t { return fix(prGen)(Pp.mt, lTop, a) } function prHTMLGen( pr : (_1 : () => Pp.t, _2 : PrecAssoc, _3 : ConstrExpr) => Pp.t ) : (_1 : () => Pp.t, _2 : PrecAssoc, _3 : ConstrExpr) => Pp.t { const recur = prGen(pr) return (sep : () => Pp.t, pa : PrecAssoc, e : ConstrExpr) => { return ([] as Pp.t[]).concat( Pp.str(`<span class='ace_editor syntax'>`), recur(sep, pa, e), Pp.str('</span>') ) } } function prHTML(a : ConstrExpr) : Pp.t { return fix(prHTMLGen)(Pp.mt, lTop, a) } function dumbPrintPpCmd(p : Pp.t) : string { if (p instanceof Pp.PpCmdBox) { // FIXME : use blockType return dumbPrintPpCmds(p.contents) } if (p instanceof Pp.PpCmdPrintBreak) { return ' '.repeat(p.nspaces) } if (p instanceof Pp.PpCmdForceNewline) { return 'TODO : PpExtend.PpCmdForceNewline' } if (p instanceof Pp.PpCmdComment) { return 'TODO : PpExtend.PpCmdComment' } throw MatchFailure('dumbPrintPpCmd', p) } function dumbPrintStrToken(t : StrToken.StrToken) : string { if (t instanceof StrToken.StrDef) { return t.str } if (t instanceof StrToken.StrLen) { return t.str } throw MatchFailure('dumbPrintStrToken', t) } function dumbPrintPpCmds(l : Pp.t) : string { return _.reduce( l, (acc, p) => { return acc + dumbPrintPpCmd(p) }, '' ) } // function ppCmdSameShape(p : PpExtend.PpCmd, old : PpExtend.PpCmd) : boolean { // return (p.constructor === old.constructor) // } // export function ppCmdsSameShape(l : Pp.t, old : Pp.t) : boolean { // if (l.length === 0 && old.length === 0) { return true } // if (l.length > 0 && old.length > 0) { // return ( // ppCmdSameShape(l[0], old[0]) // && ppCmdsSameShape(l.slice(1), old.slice(1)) // ) // } // return false // } function beginOfBinder(lBi : ConstrExpr.LocalBinderExpr) : number { const bLoc = (l : Maybe<Loc.t>) => (Option.cata(Loc.unLoc, [0, 0], l))[0] if (lBi instanceof ConstrExpr.CLocalDef) { return bLoc(lBi.name.loc) } if (lBi instanceof ConstrExpr.CLocalAssum) { return bLoc(lBi.names[0].loc) } if (lBi instanceof ConstrExpr.CLocalPattern) { return bLoc(lBi.pattern.loc) } throw MatchFailure('beginOfBinder', lBi) } function beginOfBinders(bl : ConstrExpr.LocalBinderExpr[]) { if (bl.length === 0) { return 0 } else { return beginOfBinder(bl[0]) } }
the_stack
import { _, CodeInspection, CommandManager, Commands, Dialogs, DocumentManager, EditorManager, FileViewController, KeyBindingManager, FileSystem, Menus, Mustache, FindInFiles, WorkspaceManager, ProjectManager, StringUtils } from "./brackets-modules"; import * as moment from "moment"; import * as Promise from "bluebird"; import * as Git from "./git/GitCli"; import * as Git2 from "./git/Git"; import * as Events from "./Events"; import EventEmitter from "./EventEmitter"; import * as Preferences from "./Preferences"; import * as ErrorHandler from "./ErrorHandler"; import ExpectedError from "./ExpectedError"; import * as Main from "./Main"; import * as GutterManager from "./GutterManager"; import * as Strings from "strings"; import * as Utils from "./Utils"; import * as SettingsDialog from "./SettingsDialog"; import * as ProgressDialog from "./dialogs/Progress"; const PANEL_COMMAND_ID = "brackets-git.panel"; const gitPanelTemplate = require("text!templates/git-panel.html"); const gitPanelResultsTemplate = require("text!templates/git-panel-results.html"); const gitAuthorsDialogTemplate = require("text!templates/authors-dialog.html"); const gitCommitDialogTemplate = require("text!templates/git-commit-dialog.html"); const gitTagDialogTemplate = require("text!templates/git-tag-dialog.html"); const gitDiffDialogTemplate = require("text!templates/git-diff-dialog.html"); const questionDialogTemplate = require("text!templates/git-question-dialog.html"); const showFileWhiteList = /^\.gitignore$/; const COMMIT_MODE = { CURRENT: "CURRENT", ALL: "ALL", DEFAULT: "DEFAULT" }; let gitPanel = null; let $gitPanel = $(null); let gitPanelDisabled = null; let gitPanelMode = null; let showingUntracked = true; let $tableContainer = $(null); let lastCommitMessage = null; function lintFile(filename) { const fullPath = Preferences.get("currentGitRoot") + filename; let codeInspectionPromise; try { codeInspectionPromise = CodeInspection.inspectFile(FileSystem.getFileForPath(fullPath)); } catch (e) { ErrorHandler.logError("CodeInspection.inspectFile failed to execute for file " + fullPath); ErrorHandler.logError(e); codeInspectionPromise = Promise.reject(e); } return Promise.cast(codeInspectionPromise); } function _makeDialogBig($dialog) { const $wrapper = $dialog.parents(".modal-wrapper").first(); if ($wrapper.length === 0) { return null; } // We need bigger commit dialog const minWidth = 500; const minHeight = 300; const maxWidth = $wrapper.width(); const maxHeight = $wrapper.height(); let desiredWidth = maxWidth / 1.5; let desiredHeight = maxHeight / 2; if (desiredWidth < minWidth) { desiredWidth = minWidth; } if (desiredHeight < minHeight) { desiredHeight = minHeight; } $dialog .width(desiredWidth) .children(".modal-body") .css("max-height", desiredHeight) .end(); return { width: desiredWidth, height: desiredHeight }; } function _showCommitDialog(stagedDiff, _lintResults, prefilledMessage, commitMode, files) { let lintResults = _lintResults || []; // Flatten the error structure from various providers lintResults.forEach((lintResult) => { lintResult.errors = []; if (Array.isArray(lintResult.result)) { lintResult.result.forEach((resultSet) => { if (!resultSet.result || !resultSet.result.errors) { return; } const providerName = resultSet.provider.name; resultSet.result.errors.forEach((e) => { lintResult.errors.push((e.pos.line + 1) + ": " + e.message + " (" + providerName + ")"); }); }); } else { ErrorHandler.logError( "[brackets-git] lintResults contain object in unexpected format: " + JSON.stringify(lintResult) ); } lintResult.hasErrors = lintResult.errors.length > 0; }); // Filter out only results with errors to show lintResults = _.filter(lintResults, (lintResult) => lintResult.hasErrors); // Open the dialog const compiledTemplate = Mustache.render(gitCommitDialogTemplate, { Strings, hasLintProblems: lintResults.length > 0, lintResults }); const dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate); const $dialog = dialog.getElement(); // We need bigger commit dialog _makeDialogBig($dialog); // Show nicely colored commit diff $dialog.find(".commit-diff").append(Utils.formatDiff(stagedDiff)); // Enable / Disable amend checkbox function toggleAmendCheckbox(bool) { $dialog.find(".amend-commit") .prop("disabled", !bool) .parent() .attr("title", !bool ? Strings.AMEND_COMMIT_FORBIDDEN : null); } toggleAmendCheckbox(false); Git.getCommitCounts() .then((commits) => { const hasRemote = $gitPanel.find(".git-selected-remote").data("remote") != null; const hasCommitsAhead = commits.ahead > 0; toggleAmendCheckbox(!hasRemote || hasRemote && hasCommitsAhead); }) .catch((err) => ErrorHandler.logError(err)); function getCommitMessageElement() { let r = $dialog.find("[name='commit-message']:visible"); if (r.length !== 1) { r = $dialog.find("[name='commit-message']").toArray(); for (const ri of r) { const $ri = $(ri); if ($ri.css("display") !== "none") { return $ri; } } } return r; } const $commitMessageCount = $dialog.find("input[name='commit-message-count']"); // Add event to count characters in commit message function recalculateMessageLength() { const val = getCommitMessageElement().val().trim(); let length = val.length; if (val.indexOf("\n")) { // longest line const lengths = val.split("\n").map((l) => l.length); length = Math.max(...lengths); } $commitMessageCount .val(length) .toggleClass("over50", length > 50 && length <= 100) .toggleClass("over100", length > 100); } let usingTextArea = false; // commit message handling function switchCommitMessageElement() { usingTextArea = !usingTextArea; const findStr = "[name='commit-message']"; const currentValue = $dialog.find(findStr + ":visible").val(); $dialog.find(findStr).toggle(); $dialog.find(findStr + ":visible") .val(currentValue) .focus(); recalculateMessageLength(); } $dialog.find("button.primary").on("click", (e) => { const $commitMessage = getCommitMessageElement(); if ($commitMessage.val().trim().length === 0) { e.stopPropagation(); $commitMessage.addClass("invalid"); } else { $commitMessage.removeClass("invalid"); } }); $dialog.find("button.extendedCommit").on("click", () => { switchCommitMessageElement(); // this value will be set only when manually triggered Preferences.set("useTextAreaForCommitByDefault", usingTextArea); }); function prefillMessage(msg) { if (msg.indexOf("\n") !== -1 && !usingTextArea) { switchCommitMessageElement(); } $dialog.find("[name='commit-message']:visible").val(msg); recalculateMessageLength(); } // Assign action to amend checkbox $dialog.find(".amend-commit").on("click", function () { if ($(this).prop("checked") === false) { prefillMessage(""); } else { Git.getLastCommitMessage().then((msg) => prefillMessage(msg)); } }); if (Preferences.get("useTextAreaForCommitByDefault")) { switchCommitMessageElement(); } if (prefilledMessage) { prefillMessage(prefilledMessage.trim()); } // Add focus to commit message input getCommitMessageElement().focus(); $dialog.find("[name='commit-message']") .on("keyup", recalculateMessageLength) .on("change", recalculateMessageLength); recalculateMessageLength(); dialog.done((buttonId) => { if (buttonId === "ok") { if (commitMode === COMMIT_MODE.ALL || commitMode === COMMIT_MODE.CURRENT) { const filePaths = _.map(files, (next) => next.file); Git.stage(filePaths) .then(() => _getStagedDiff()) .then((diff) => _doGitCommit($dialog, getCommitMessageElement, diff)) .catch((err) => ErrorHandler.showError(err, "Cant get diff for staged files")); } else { _doGitCommit($dialog, getCommitMessageElement, stagedDiff); } } else { Git.status(); } }); } function _doGitCommit($dialog, getCommitMessageElement, stagedDiff) { // this event won't launch when commit-message is empty so its safe to assume that it is not let commitMessage = getCommitMessageElement().val(); const amendCommit = $dialog.find(".amend-commit").prop("checked"); // if commit message is extended and has a newline, put an empty line after first line to separate subject and body const s = commitMessage.split("\n"); if (s.length > 1 && s[1].trim() !== "") { s.splice(1, 0, ""); } commitMessage = s.join("\n"); // save lastCommitMessage in case the commit will fail lastCommitMessage = commitMessage; // now we are going to be paranoid and we will check if some mofo didn't change our diff _getStagedDiff().then((diff) => { if (diff === stagedDiff) { return Git.commit(commitMessage, amendCommit).then(() => { // clear lastCommitMessage because the commit was successful lastCommitMessage = null; }); } throw new ExpectedError( "The files you were going to commit were modified while commit dialog was displayed. " + "Aborting the commit as the result would be different then what was shown in the dialog." ); }).catch((err) => { if (ErrorHandler.contains(err, "Please tell me who you are")) { const defer = Promise.defer(); EventEmitter.emit(Events.GIT_CHANGE_USERNAME, null, () => { EventEmitter.emit(Events.GIT_CHANGE_EMAIL, null, () => { defer.resolve(); }); }); return defer.promise; } return ErrorHandler.showError(err, "Git Commit failed"); }).finally(() => { EventEmitter.emit(Events.GIT_COMMITED); refresh(); }); } function _showAuthors(file, blame, fromLine?, toLine?) { const linesTotal = blame.length; let blameStats = blame.reduce((stats, lineInfo) => { const name = lineInfo.author + " " + lineInfo["author-mail"]; if (stats[name]) { stats[name] += 1; } else { stats[name] = 1; } return stats; }, {}); blameStats = _.reduce(blameStats, (arr, val, key) => { arr.push({ authorName: key, lines: val, percentage: Math.round(val / (linesTotal / 100)) }); return arr; }, []); blameStats = _.sortBy(blameStats, "lines").reverse(); if (fromLine || toLine) { file += " (" + Strings.LINES + " " + fromLine + "-" + toLine + ")"; } const compiledTemplate = Mustache.render(gitAuthorsDialogTemplate, { file, blameStats, Strings }); Dialogs.showModalDialogUsingTemplate(compiledTemplate); } function _getCurrentFilePath(editor?) { const gitRoot = Preferences.get("currentGitRoot"); const document = editor ? editor.document : DocumentManager.getCurrentDocument(); let filePath = document.file.fullPath; if (filePath.indexOf(gitRoot) === 0) { filePath = filePath.substring(gitRoot.length); } return filePath; } function handleAuthorsSelection() { const editor = EditorManager.getActiveEditor(); const filePath = _getCurrentFilePath(editor); const currentSelection = editor.getSelection(); const fromLine = currentSelection.start.line + 1; let toLine = currentSelection.end.line + 1; // fix when nothing is selected on that line if (currentSelection.end.ch === 0) { toLine -= 1; } const isSomethingSelected = currentSelection.start.line !== currentSelection.end.line || currentSelection.start.ch !== currentSelection.end.ch; if (!isSomethingSelected) { ErrorHandler.showError(new ExpectedError(Strings.ERROR_NOTHING_SELECTED)); return; } if (editor.document.isDirty) { ErrorHandler.showError(new ExpectedError(Strings.ERROR_SAVE_FIRST)); return; } Git.getBlame(filePath, fromLine, toLine).then((blame) => { return _showAuthors(filePath, blame, fromLine, toLine); }).catch((err) => { ErrorHandler.showError(err, "Git Blame failed"); }); } function handleAuthorsFile() { const filePath = _getCurrentFilePath(); Git.getBlame(filePath).then((blame) => { return _showAuthors(filePath, blame); }).catch((err) => { ErrorHandler.showError(err, "Git Blame failed"); }); } function handleGitDiff(file) { if (Preferences.get("useDifftool")) { Git.difftool(file); } else { Git.diffFileNice(file).then((diff) => { // show the dialog with the diff const compiledTemplate = Mustache.render(gitDiffDialogTemplate, { file, Strings }); const dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate); const $dialog = dialog.getElement(); _makeDialogBig($dialog); $dialog.find(".commit-diff").append(Utils.formatDiff(diff)); }).catch((err) => { ErrorHandler.showError(err, "Git Diff failed"); }); } } function handleGitTag(file) { // Open the Tag Dialog const compiledTemplate = Mustache.render(gitTagDialogTemplate, { file, Strings }); const dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate); const $dialog = dialog.getElement(); _makeDialogBig($dialog); $dialog.find("button.primary").on("click", () => { const tagname = $dialog.find("input.commit-message").val(); Git.setTagName(tagname).then(() => { refresh(); EventEmitter.emit(Events.HISTORY_SHOW, "GLOBAL"); }).catch((err) => { ErrorHandler.showError(err, "Create tag failed"); }); }); } function handleGitUndo(file) { const compiledTemplate = Mustache.render(questionDialogTemplate, { title: Strings.UNDO_CHANGES, question: StringUtils.format(Strings.Q_UNDO_CHANGES, _.escape(file)), Strings }); Dialogs.showModalDialogUsingTemplate(compiledTemplate).done((buttonId) => { if (buttonId === "ok") { Git2.discardFileChanges(file).then(() => { const gitRoot = Preferences.get("currentGitRoot"); DocumentManager.getAllOpenDocuments().forEach((doc) => { if (doc.file.fullPath === gitRoot + file) { Utils.reloadDoc(doc); } }); refresh(); }).catch((err) => { ErrorHandler.showError(err, "Discard changes to a file failed"); }); } }); } function handleGitDelete(file) { const compiledTemplate = Mustache.render(questionDialogTemplate, { title: Strings.DELETE_FILE, question: StringUtils.format(Strings.Q_DELETE_FILE, _.escape(file)), Strings }); Dialogs.showModalDialogUsingTemplate(compiledTemplate).done((buttonId) => { if (buttonId === "ok") { FileSystem.resolve(Preferences.get("currentGitRoot") + file, (err, fileEntry) => { if (err) { ErrorHandler.showError(err, "Could not resolve file"); return; } Promise.cast(ProjectManager.deleteItem(fileEntry)) .then(() => { refresh(); }) .catch((err2) => { ErrorHandler.showError(err2, "File deletion failed"); }); }); } }); } function _getStagedDiff(commitMode?, files?) { return ProgressDialog.show(_getStagedDiffForCommitMode(commitMode, files), Strings.GETTING_STAGED_DIFF_PROGRESS, { preDelay: 3, postDelay: 1 }) .catch((err) => { if (ErrorHandler.contains(err, "cleanup")) { return false; // will display list of staged files instead } throw err; }) .then((diff) => { if (!diff) { return Git.getListOfStagedFiles().then((filesList) => { return Strings.DIFF_FAILED_SEE_FILES + "\n\n" + filesList; }); } return diff; }); } function _getStagedDiffForCommitMode(commitMode, files) { if (commitMode === COMMIT_MODE.ALL) { return _getStaggedDiffForAllFiles(); } if (commitMode === COMMIT_MODE.CURRENT && _.isArray(files)) { if (files.length > 1) { return Promise.reject("_getStagedDiffForCommitMode() got files.length > 1"); } const isUntracked = files[0].status.indexOf(Git.FILE_STATUS.UNTRACKED) !== -1; return isUntracked ? _getDiffForUntrackedFiles(files[0].file) : Git.getDiffOfAllIndexFiles(files[0].file); } return Git.getDiffOfStagedFiles(); } function _getStaggedDiffForAllFiles() { return Git.status().then((statusFiles) => { const untrackedFiles = []; const fileArray = []; statusFiles.forEach((fileObject) => { const isUntracked = fileObject.status.indexOf(Git.FILE_STATUS.UNTRACKED) !== -1; if (isUntracked) { untrackedFiles.push(fileObject.file); } else { fileArray.push(fileObject.file); } }); return untrackedFiles.length > 0 ? _getDiffForUntrackedFiles(fileArray.concat(untrackedFiles)) : Git.getDiffOfAllIndexFiles(fileArray); }); } function _getDiffForUntrackedFiles(files) { let diff; return Git.stage(files, false) .then(() => Git.getDiffOfStagedFiles()) .then((_diff) => { diff = _diff; return Git2.resetIndex(); }) .then(() => diff); } // whatToDo gets values "continue" "skip" "abort" function handleRebase(whatToDo) { Git.rebase(whatToDo).then(() => { EventEmitter.emit(Events.REFRESH_ALL); }).catch((err) => { ErrorHandler.showError(err, "Rebase " + whatToDo + " failed"); }); } function abortMerge() { Git2.discardAllChanges().then(() => { EventEmitter.emit(Events.REFRESH_ALL); }).catch((err) => { ErrorHandler.showError(err, "Merge abort failed"); }); } function findConflicts() { FindInFiles.doSearch(/^<<<<<<<\s|^=======\s|^>>>>>>>\s/gm); } function commitMerge() { Utils.loadPathContent(Preferences.get("currentGitRoot") + "/.git/MERGE_MSG").then((msg) => { handleGitCommit(msg, true, COMMIT_MODE.DEFAULT); EventEmitter.once(Events.GIT_COMMITED, () => { EventEmitter.emit(Events.REFRESH_ALL); }); }).catch((err) => { ErrorHandler.showError(err, "Merge commit failed"); }); } function inspectFiles(gitStatusResults) { const lintResults = []; const codeInspectionPromises = gitStatusResults.map((fileObj) => { const isDeleted = fileObj.status.indexOf(Git.FILE_STATUS.DELETED) !== -1; // do a code inspection for the file, if it was not deleted if (!isDeleted) { return lintFile(fileObj.file) .catch(() => { return [ { provider: { name: "See console [F12] for details" }, result: { errors: [ { pos: { line: 0, ch: 0 }, message: "CodeInspection failed to execute for this file." } ] } } ]; }) .then((result) => { if (result) { lintResults.push({ filename: fileObj.file, result }); } }); } return null; }); return Promise.all(_.compact(codeInspectionPromises)).then(() => { return lintResults; }); } function handleGitCommit(prefilledMessage, isMerge, commitMode) { const stripWhitespace = Preferences.get("stripWhitespaceFromCommits"); const codeInspectionEnabled = Preferences.get("useCodeInspection"); // Disable button (it will be enabled when selecting files after reset) Utils.setLoading($gitPanel.find(".git-commit")); let p; // First reset staged files, then add selected files to the index. if (commitMode === COMMIT_MODE.DEFAULT) { p = Git.status().then((files) => { files = _.filter(files, (file) => { return file.status.indexOf(Git.FILE_STATUS.STAGED) !== -1; }); if (files.length === 0 && !isMerge) { return ErrorHandler.showError( new Error("Commit button should have been disabled"), "Nothing staged to commit" ); } return handleGitCommitInternal(stripWhitespace, files, codeInspectionEnabled, commitMode, prefilledMessage); }); } else if (commitMode === COMMIT_MODE.ALL) { p = Git.status().then((files) => { return handleGitCommitInternal(stripWhitespace, files, codeInspectionEnabled, commitMode, prefilledMessage); }); } else if (commitMode === COMMIT_MODE.CURRENT) { p = Git.status().then((files) => { const gitRoot = Preferences.get("currentGitRoot"); const currentDoc = DocumentManager.getCurrentDocument(); if (currentDoc) { const relativePath = currentDoc.file.fullPath.substring(gitRoot.length); const currentFile = _.filter(files, (next) => { return relativePath === next.file; }); return handleGitCommitInternal( stripWhitespace, currentFile, codeInspectionEnabled, commitMode, prefilledMessage ); } return null; }); } p.catch((err) => { ErrorHandler.showError(err, "Preparing commit dialog failed"); }).finally(() => { Utils.unsetLoading($gitPanel.find(".git-commit")); }); } function handleGitCommitInternal(stripWhitespace, files, codeInspectionEnabled, commitMode, prefilledMessage) { let queue: Promise<any> = Promise.resolve(); let lintResults; if (stripWhitespace) { queue = queue.then(() => { return ProgressDialog.show(Utils.stripWhitespaceFromFiles(files, commitMode === COMMIT_MODE.DEFAULT), Strings.CLEANING_WHITESPACE_PROGRESS, { preDelay: 3, postDelay: 1 }); }); } if (codeInspectionEnabled) { queue = queue.then(() => { return inspectFiles(files).then((_lintResults) => { lintResults = _lintResults; }); }); } return queue.then(() => { // All files are in the index now, get the diff and show dialog. return _getStagedDiff(commitMode, files).then((diff) => { return _showCommitDialog(diff, lintResults, prefilledMessage, commitMode, files); }); }); } function refreshCurrentFile() { const gitRoot = Preferences.get("currentGitRoot"); const currentDoc = DocumentManager.getCurrentDocument(); if (currentDoc) { $gitPanel.find("tr").each(function () { const currentFullPath = currentDoc.file.fullPath; const thisFile = $(this).attr("x-file"); $(this).toggleClass("selected", gitRoot + thisFile === currentFullPath); }); } else { $gitPanel.find("tr").removeClass("selected"); } } function shouldShow(fileObj) { if (showFileWhiteList.test(fileObj.name)) { return true; } return ProjectManager.shouldShow(fileObj); } function _refreshTableContainer(files) { if (!gitPanel.isVisible()) { return; } // remove files that we should not show files = _.filter(files, (file) => { return shouldShow(file); }); const allStaged = files.length > 0 && _.all(files, (file) => { return file.status.indexOf(Git.FILE_STATUS.STAGED) !== -1; }); $gitPanel.find(".check-all").prop("checked", allStaged).prop("disabled", files.length === 0); const $editedList = $tableContainer.find(".git-edited-list"); const visibleBefore = $editedList.length ? $editedList.is(":visible") : true; $editedList.remove(); if (files.length === 0) { $tableContainer.append($("<p class='git-edited-list nothing-to-commit' />").text(Strings.NOTHING_TO_COMMIT)); } else { // if desired, remove untracked files from the results if (showingUntracked === false) { files = _.filter(files, (file) => { return file.status.indexOf(Git.FILE_STATUS.UNTRACKED) === -1; }); } // - files.forEach((file) => { file.staged = file.status.indexOf(Git.FILE_STATUS.STAGED) !== -1; file.statusText = file.status.map((status) => { return Strings["FILE_" + status]; }).join(", "); file.allowDiff = file.status.indexOf(Git.FILE_STATUS.UNTRACKED) === -1 && file.status.indexOf(Git.FILE_STATUS.RENAMED) === -1 && file.status.indexOf(Git.FILE_STATUS.DELETED) === -1; file.allowDelete = file.status.indexOf(Git.FILE_STATUS.UNTRACKED) !== -1 || file.status.indexOf(Git.FILE_STATUS.STAGED) !== -1 && file.status.indexOf(Git.FILE_STATUS.ADDED) !== -1; file.allowUndo = !file.allowDelete; }); $tableContainer.append(Mustache.render(gitPanelResultsTemplate, { files, Strings })); refreshCurrentFile(); } $tableContainer.find(".git-edited-list").toggle(visibleBefore); } function refreshCommitCounts() { // Find Push and Pull buttons const $pullBtn = $gitPanel.find(".git-pull"); const $pushBtn = $gitPanel.find(".git-push"); const clearCounts = function () { $pullBtn.children("span").remove(); $pushBtn.children("span").remove(); }; // Check if there's a remote, resolve if there's not const remotes = Preferences.get("defaultRemotes") || {}; const defaultRemote = remotes[Preferences.get("currentGitRoot")]; if (!defaultRemote) { clearCounts(); return Promise.resolve(); } // Get the commit counts and append them to the buttons return Git.getCommitCounts().then((commits) => { clearCounts(); if (commits.behind > 0) { $pullBtn.append($("<span/>").text(" (" + commits.behind + ")")); } if (commits.ahead > 0) { $pushBtn.append($("<span/>").text(" (" + commits.ahead + ")")); } }).catch((err) => { clearCounts(); ErrorHandler.logError(err); }); } export function refresh() { // set the history panel to false and remove the class that show the button history active when refresh $gitPanel.find(".git-history-toggle").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_HISTORY); $gitPanel.find(".git-file-history").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_FILE_HISTORY); if (gitPanelMode === "not-repo") { $tableContainer.empty(); return Promise.resolve(); } $tableContainer.find("#git-history-list").remove(); $tableContainer.find(".git-edited-list").show(); const p1 = Git.status().catch((err) => { // this is an expected "error" if (ErrorHandler.contains(err, "Not a git repository")) { return; } throw err; }); const p2 = refreshCommitCounts(); // Clone button $gitPanel.find(".git-clone").prop("disabled", false); // FUTURE: who listens for this? return Promise.all([p1, p2]); } export function toggle(bool) { if (gitPanelDisabled === true) { return; } if (typeof bool !== "boolean") { bool = !gitPanel.isVisible(); } Preferences.persist("panelEnabled", bool); Main.$icon.toggleClass("on", bool); gitPanel.setVisible(bool); // Mark menu item as enabled/disabled. CommandManager.get(PANEL_COMMAND_ID).setChecked(bool); if (bool) { refresh(); } } function handleToggleUntracked() { showingUntracked = !showingUntracked; $gitPanel .find(".git-toggle-untracked") .text(showingUntracked ? Strings.HIDE_UNTRACKED : Strings.SHOW_UNTRACKED); refresh(); } function commitCurrentFile() { // do not return anything here, core expects jquery promise Promise.cast(CommandManager.execute("file.save")) .then(() => { return Git2.resetIndex(); }) .then(() => { return handleGitCommit(lastCommitMessage, false, COMMIT_MODE.CURRENT); }); } function commitAllFiles() { // do not return anything here, core expects jquery promise Promise.cast(CommandManager.execute("file.saveAll")) .then(() => { return Git2.resetIndex(); }) .then(() => { return handleGitCommit(lastCommitMessage, false, COMMIT_MODE.ALL); }); } // Disable "commit" button if there aren't staged files to commit function _toggleCommitButton(files) { const anyStaged = _.any(files, (file) => file.status.indexOf(Git.FILE_STATUS.STAGED) !== -1); $gitPanel.find(".git-commit").prop("disabled", !anyStaged); } EventEmitter.on(Events.GIT_STATUS_RESULTS, (results) => { _refreshTableContainer(results); _toggleCommitButton(results); }); function undoLastLocalCommit() { Git2.undoLastLocalCommit() .catch((err) => { ErrorHandler.showError(err, "Impossible to undo last commit"); }) .finally(() => { refresh(); }); } let lastCheckOneClicked = null; function attachDefaultTableHandlers() { $tableContainer = $gitPanel.find(".table-container") .off() .on("click", ".check-one", function (e) { e.stopPropagation(); const $tr = $(this).closest("tr"); const file = $tr.attr("x-file"); const status = $tr.attr("x-status"); const isChecked = $(this).is(":checked"); if (e.shiftKey) { // stage/unstage all file between const lc = lastCheckOneClicked.localeCompare(file); const lcClickedSelector = "[x-file='" + lastCheckOneClicked + "']"; let sequence; if (lc < 0) { sequence = $tr.prevUntil(lcClickedSelector).andSelf(); } else if (lc > 0) { sequence = $tr.nextUntil(lcClickedSelector).andSelf(); } if (sequence) { sequence = sequence.add($tr.parent().children(lcClickedSelector)); const promises = sequence.map(function () { const $this = $(this); return isChecked ? Git.stage($this.attr("x-file"), $this.attr("x-status") === Git.FILE_STATUS.DELETED) : Git.unstage($this.attr("x-file")); }).toArray(); return Promise.all(promises).then(() => { return Git.status(); }).catch((err) => { ErrorHandler.showError(err, "Modifying file status failed"); }); } } lastCheckOneClicked = file; if (isChecked) { return Git.stage(file, status === Git.FILE_STATUS.DELETED).then(() => { Git.status(); }); } return Git.unstage(file).then(() => { Git.status(); }); }) .on("dblclick", ".check-one", (e) => { e.stopPropagation(); }) .on("click", ".btn-git-diff", (e) => { e.stopPropagation(); handleGitDiff($(e.target).closest("tr").attr("x-file")); }) .on("click", ".btn-git-undo", (e) => { e.stopPropagation(); handleGitUndo($(e.target).closest("tr").attr("x-file")); }) .on("click", ".btn-git-delete", (e) => { e.stopPropagation(); handleGitDelete($(e.target).closest("tr").attr("x-file")); }) .on("click", ".modified-file", (e) => { const $this = $(e.currentTarget); if ($this.attr("x-status") === Git.FILE_STATUS.DELETED) { return; } CommandManager.execute(Commands.FILE_OPEN, { fullPath: Preferences.get("currentGitRoot") + $this.attr("x-file") }); }) .on("dblclick", ".modified-file", (e) => { const $this = $(e.currentTarget); if ($this.attr("x-status") === Git.FILE_STATUS.DELETED) { return; } FileViewController.addToWorkingSetAndSelect(Preferences.get("currentGitRoot") + $this.attr("x-file")); }); } EventEmitter.on(Events.GIT_CHANGE_USERNAME, (event, callback) => { return Git.getConfig("user.name").then((currentUserName) => { return Utils.askQuestion( Strings.CHANGE_USER_NAME, Strings.ENTER_NEW_USER_NAME, { defaultValue: currentUserName } ) .then((userName: string) => { if (!userName.length) { userName = currentUserName; } return Git.setConfig("user.name", userName, true).catch((err) => { ErrorHandler.showError(err, "Impossible to change username"); }).then(() => { EventEmitter.emit(Events.GIT_USERNAME_CHANGED, userName); }).finally(() => { if (callback) { return callback(userName); } }); }); }); }); EventEmitter.on(Events.GIT_CHANGE_EMAIL, (event, callback) => { return Git.getConfig("user.email").then((currentUserEmail) => { return Utils.askQuestion( Strings.CHANGE_USER_EMAIL, Strings.ENTER_NEW_USER_EMAIL, { defaultValue: currentUserEmail } ) .then((userEmail: string) => { if (!userEmail.length) { userEmail = currentUserEmail; } return Git.setConfig("user.email", userEmail, true).catch((err) => { ErrorHandler.showError(err, "Impossible to change user email"); }).then(() => { EventEmitter.emit(Events.GIT_EMAIL_CHANGED, userEmail); }).finally(() => { if (callback) { return callback(userEmail); } }); }); }); }); EventEmitter.on(Events.GERRIT_TOGGLE_PUSH_REF, (event, callback) => { // update preference and emit so the menu item updates return Git.getConfig("gerrit.pushref").then((strEnabled) => { const toggledValue = strEnabled !== "true"; // Set the global preference // Saving a preference to tell the GitCli.push() method to check for gerrit push ref enablement // so we don't slow down people who aren't using gerrit. Preferences.persist("gerritPushref", toggledValue); return Git.setConfig("gerrit.pushref", toggledValue, true) .then(() => { EventEmitter.emit(Events.GERRIT_PUSH_REF_TOGGLED, toggledValue); }) .finally(() => { if (callback) { return callback(toggledValue); } }); }).catch((err) => { ErrorHandler.showError(err, "Impossible to toggle gerrit push ref"); }); }); EventEmitter.on(Events.GERRIT_PUSH_REF_TOGGLED, (enabled) => { setGerritCheckState(enabled); }); function setGerritCheckState(enabled) { $gitPanel .find(".toggle-gerrit-push-ref") .toggleClass("checkmark", enabled); } function discardAllChanges() { return Utils.askQuestion(Strings.RESET_LOCAL_REPO, Strings.RESET_LOCAL_REPO_CONFIRM, { booleanResponse: true }) .then((response) => { if (response) { return Git2.discardAllChanges().catch((err) => { ErrorHandler.showError(err, "Reset of local repository failed"); }).then(() => { refresh(); }); } return null; }); } export function init() { // Add panel const panelHtml = Mustache.render(gitPanelTemplate, { enableAdvancedFeatures: Preferences.get("enableAdvancedFeatures"), showBashButton: Preferences.get("showBashButton"), S: Strings }); const $panelHtml = $(panelHtml); $panelHtml.find(".git-available, .git-not-available").hide(); gitPanel = WorkspaceManager.createBottomPanel("brackets-git.panel", $panelHtml, 100); $gitPanel = gitPanel.$panel; $gitPanel .on("click", ".close", toggle) .on("click", ".check-all", function () { return $(this).is(":checked") ? Git.stageAll().then(() => { Git.status(); }) : Git2.resetIndex().then(() => { Git.status(); }); }) .on("click", ".git-refresh", EventEmitter.emitFactory(Events.REFRESH_ALL)) .on("click", ".git-commit", EventEmitter.emitFactory(Events.HANDLE_GIT_COMMIT)) .on("click", ".git-rebase-continue", (e) => { handleRebase("continue"); }) .on("click", ".git-rebase-skip", (e) => { handleRebase("skip"); }) .on("click", ".git-rebase-abort", (e) => { handleRebase("abort"); }) .on("click", ".git-commit-merge", commitMerge) .on("click", ".git-merge-abort", abortMerge) .on("click", ".git-find-conflicts", findConflicts) .on("click", ".git-prev-gutter", GutterManager.goToPrev) .on("click", ".git-next-gutter", GutterManager.goToNext) .on("click", ".git-toggle-untracked", handleToggleUntracked) .on("click", ".authors-selection", handleAuthorsSelection) .on("click", ".authors-file", handleAuthorsFile) .on("click", ".git-file-history", EventEmitter.emitFactory(Events.HISTORY_SHOW, "FILE")) .on("click", ".git-history-toggle", EventEmitter.emitFactory(Events.HISTORY_SHOW, "GLOBAL")) .on("click", ".git-fetch", EventEmitter.emitFactory(Events.HANDLE_FETCH)) .on("click", ".git-push", function () { const typeOfRemote = $(this).attr("x-selected-remote-type"); if (typeOfRemote === "git") { EventEmitter.emit(Events.HANDLE_PUSH); } }) .on("click", ".git-pull", EventEmitter.emitFactory(Events.HANDLE_PULL)) .on("click", ".git-bug", ErrorHandler.reportBug) .on("click", ".git-init", EventEmitter.emitFactory(Events.HANDLE_GIT_INIT)) .on("click", ".git-clone", EventEmitter.emitFactory(Events.HANDLE_GIT_CLONE)) .on("click", ".change-remote", EventEmitter.emitFactory(Events.HANDLE_REMOTE_PICK)) .on("click", ".remove-remote", EventEmitter.emitFactory(Events.HANDLE_REMOTE_DELETE)) .on("click", ".git-remote-new", EventEmitter.emitFactory(Events.HANDLE_REMOTE_CREATE)) .on("click", ".git-settings", SettingsDialog.show) .on("contextmenu", "tr", function (e) { const $this = $(this); if ($this.hasClass("history-commit")) { return; } $this.click(); setTimeout(() => { Menus.getContextMenu("git-panel-context-menu").open(e); }, 1); }) .on("click", ".change-user-name", EventEmitter.emitFactory(Events.GIT_CHANGE_USERNAME)) .on("click", ".change-user-email", EventEmitter.emitFactory(Events.GIT_CHANGE_EMAIL)) .on("click", ".toggle-gerrit-push-ref", EventEmitter.emitFactory(Events.GERRIT_TOGGLE_PUSH_REF)) .on("click", ".undo-last-commit", undoLastLocalCommit) .on("click", ".git-bash", EventEmitter.emitFactory(Events.TERMINAL_OPEN)) .on("click", ".tags", (e) => { e.stopPropagation(); handleGitTag($(e.target).closest("tr").attr("x-file")); }) .on("click", ".reset-all", discardAllChanges); /* Put here event handlers for advanced actions if (Preferences.get("enableAdvancedFeatures")) { $gitPanel .on("click", target, function); } */ // Attaching table handlers attachDefaultTableHandlers(); // Commit current and all shortcuts const COMMIT_CURRENT_CMD = "brackets-git.commitCurrent"; const COMMIT_ALL_CMD = "brackets-git.commitAll"; const BASH_CMD = "brackets-git.launchBash"; const PUSH_CMD = "brackets-git.push"; const PULL_CMD = "brackets-git.pull"; const GOTO_PREV_CHANGE = "brackets-git.gotoPrevChange"; const GOTO_NEXT_CHANGE = "brackets-git.gotoNextChange"; const REFRESH_GIT = "brackets-git.refreshAll"; // Add command to menu. // Register command for opening bottom panel. CommandManager.register(Strings.PANEL_COMMAND, PANEL_COMMAND_ID, toggle); KeyBindingManager.addBinding(PANEL_COMMAND_ID, Preferences.get("panelShortcut"), brackets.platform); CommandManager.register(Strings.COMMIT_CURRENT_SHORTCUT, COMMIT_CURRENT_CMD, commitCurrentFile); KeyBindingManager.addBinding(COMMIT_CURRENT_CMD, Preferences.get("commitCurrentShortcut"), brackets.platform); CommandManager.register(Strings.COMMIT_ALL_SHORTCUT, COMMIT_ALL_CMD, commitAllFiles); KeyBindingManager.addBinding(COMMIT_ALL_CMD, Preferences.get("commitAllShortcut"), brackets.platform); CommandManager.register(Strings.LAUNCH_BASH_SHORTCUT, BASH_CMD, EventEmitter.emitFactory(Events.TERMINAL_OPEN)); KeyBindingManager.addBinding(BASH_CMD, Preferences.get("bashShortcut"), brackets.platform); CommandManager.register(Strings.PUSH_SHORTCUT, PUSH_CMD, EventEmitter.emitFactory(Events.HANDLE_PUSH)); KeyBindingManager.addBinding(PUSH_CMD, Preferences.get("pushShortcut"), brackets.platform); CommandManager.register(Strings.PULL_SHORTCUT, PULL_CMD, EventEmitter.emitFactory(Events.HANDLE_PULL)); KeyBindingManager.addBinding(PULL_CMD, Preferences.get("pullShortcut"), brackets.platform); CommandManager.register(Strings.GOTO_PREVIOUS_GIT_CHANGE, GOTO_PREV_CHANGE, GutterManager.goToPrev); KeyBindingManager.addBinding(GOTO_PREV_CHANGE, Preferences.get("gotoPrevChangeShortcut"), brackets.platform); CommandManager.register(Strings.GOTO_NEXT_GIT_CHANGE, GOTO_NEXT_CHANGE, GutterManager.goToNext); KeyBindingManager.addBinding(GOTO_NEXT_CHANGE, Preferences.get("gotoNextChangeShortcut"), brackets.platform); CommandManager.register(Strings.REFRESH_GIT, REFRESH_GIT, EventEmitter.emitFactory(Events.REFRESH_ALL)); KeyBindingManager.addBinding(REFRESH_GIT, Preferences.get("refreshShortcut"), brackets.platform); // Init moment - use the correct language moment.lang(brackets.getLocale()); // Show gitPanel when appropriate if (Preferences.get("panelEnabled")) { toggle(true); } } // function init() { export function enable() { EventEmitter.emit(Events.GIT_ENABLED); // this function is called after every Branch.refresh gitPanelMode = null; // $gitPanel.find(".git-available").show(); $gitPanel.find(".git-not-available").hide(); // Main.$icon.removeClass("warning").removeAttr("title"); gitPanelDisabled = false; // after all is enabled refresh(); } export function disable(cause) { EventEmitter.emit(Events.GIT_DISABLED, cause); gitPanelMode = cause; // causes: not-repo if (gitPanelMode === "not-repo") { $gitPanel.find(".git-available").hide(); $gitPanel.find(".git-not-available").show(); } else { Main.$icon.addClass("warning").attr("title", cause); toggle(false); gitPanelDisabled = true; } refresh(); } // Event listeners EventEmitter.on(Events.GIT_USERNAME_CHANGED, (userName) => { $gitPanel.find(".git-user-name").text(userName); }); EventEmitter.on(Events.GIT_EMAIL_CHANGED, (email) => { $gitPanel.find(".git-user-email").text(email); }); EventEmitter.on(Events.GIT_REMOTE_AVAILABLE, () => { $gitPanel.find(".git-pull, .git-push, .git-fetch").prop("disabled", false); }); EventEmitter.on(Events.GIT_REMOTE_NOT_AVAILABLE, () => { $gitPanel.find(".git-pull, .git-push, .git-fetch").prop("disabled", true); }); EventEmitter.on(Events.GIT_ENABLED, () => { // Add info from Git to panel Git.getConfig("user.name").then((currentUserName) => { EventEmitter.emit(Events.GIT_USERNAME_CHANGED, currentUserName); }); Git.getConfig("user.email").then((currentEmail) => { EventEmitter.emit(Events.GIT_EMAIL_CHANGED, currentEmail); }); Git.getConfig("gerrit.pushref").then((strEnabled) => { const enabled = strEnabled === "true"; // Handle the case where we switched to a repo that is using gerrit if (enabled && !Preferences.get("gerritPushref")) { Preferences.persist("gerritPushref", true); } EventEmitter.emit(Events.GERRIT_PUSH_REF_TOGGLED, enabled); }); }); EventEmitter.on(Events.BRACKETS_CURRENT_DOCUMENT_CHANGE, () => { if (!gitPanel) { return; } refreshCurrentFile(); }); EventEmitter.on(Events.BRACKETS_DOCUMENT_SAVED, () => { if (!gitPanel) { return; } refresh(); }); EventEmitter.on(Events.BRACKETS_FILE_CHANGED, (event, fileSystemEntry) => { // files are added or deleted from the directory if (fileSystemEntry.isDirectory) { refresh(); } }); EventEmitter.on(Events.REBASE_MERGE_MODE, (rebaseEnabled, mergeEnabled) => { $gitPanel.find(".git-rebase").toggle(rebaseEnabled); $gitPanel.find(".git-merge").toggle(mergeEnabled); $gitPanel.find("button.git-commit").toggle(!rebaseEnabled && !mergeEnabled); }); EventEmitter.on(Events.FETCH_STARTED, () => { $gitPanel.find(".git-fetch") .addClass("btn-loading") .prop("disabled", true); }); EventEmitter.on(Events.FETCH_COMPLETE, () => { $gitPanel.find(".git-fetch") .removeClass("btn-loading") .prop("disabled", false); refreshCommitCounts(); }); EventEmitter.on(Events.REFRESH_COUNTERS, () => { refreshCommitCounts(); }); EventEmitter.on(Events.HANDLE_GIT_COMMIT, () => { handleGitCommit(lastCommitMessage, false, COMMIT_MODE.DEFAULT); }); EventEmitter.on(Events.TERMINAL_DISABLE, () => { $gitPanel.find(".git-bash").prop("disabled", true).attr("title", Strings.TERMINAL_DISABLED); }); export function getPanel() { return $gitPanel; }
the_stack
// Path Markup Syntax: http://msdn.microsoft.com/en-us/library/cc189041(v=vs.95).aspx //FigureDescription Syntax // MoveCommand DrawCommands [CloseCommand] //Double Syntax // digits // digits.digits // 'Infinity' // '-Infinity' // 'NaN' //Point Syntax // x,y // x y //Loop until exhausted // Parse FigureDescription // Find "M" or "m"? - Parse MoveCommand (start point) // <point> // // Find "L" or "l"? - Parse LineCommand (end point) // <point> // Find "H" or "h"? - Parse HorizontalLineCommand (x) // <double> // Find "V" or "v"? - Parse VerticalLineCommand (y) // <double> // Find "C" or "c"? - Parse CubicBezierCurveCommand (control point 1, control point 2, end point) // <point> <point> <point> // Find "Q" or "q"? - Parse QuadraticBezierCurveCommand (control point, end point) // <point> <point> // Find "S" or "s"? - Parse SmoothCubicBezierCurveCommand (control point 2, end point) // <point> <point> // Find "T" or "t"? - Parse SmoothQuadraticBezierCurveCommand (control point, end point) // <point> <point> // Find "A" or "a"? - Parse EllipticalArcCommand (size, rotationAngle, isLargeArcFlag, sweepDirectionFlag, endPoint) // <point> <double> <1,0> <1,0> <point> // // Find "Z" or "z"? - CloseCommand module Fayde.Media { export function ParseGeometry (val: string): Geometry { return (new MediaParser(val)).ParseGeometryImpl(); } export function ParseShapePoints (val: string): Point[] { return (new MediaParser(val)).ParseShapePoints(); } class MediaParser { private str: string; private len: number; private index: number = 0; constructor (str: string) { this.str = str; this.len = str.length; } ParseGeometryImpl (): Geometry { var cp = new Point(); var cp1: Point, cp2: Point, cp3: Point; var start = new Point(); var fillRule = Shapes.FillRule.EvenOdd; var cbz = false; // last figure is a cubic bezier curve var qbz = false; // last figure is a quadratic bezier curve var cbzp = new Point(); // points needed to create "smooth" beziers var qbzp = new Point(); // points needed to create "smooth" beziers var path = new minerva.path.Path(); while (this.index < this.len) { var c; while (this.index < this.len && (c = this.str.charAt(this.index)) === ' ') { this.index++; } this.index++; var relative = false; switch (c) { case 'f': case 'F': c = this.str.charAt(this.index); if (c === '0') fillRule = Shapes.FillRule.EvenOdd; else if (c === '1') fillRule = Shapes.FillRule.NonZero; else return null; this.index++; c = this.str.charAt(this.index); break; case 'm': relative = true; case 'M': cp1 = this.ParsePoint(); if (cp1 == null) break; if (relative) { cp1.x += cp.x; cp1.y += cp.y; } path.move(cp1.x, cp1.y); start.x = cp.x = cp1.x; start.y = cp.y = cp1.y; this.Advance(); while (this.MorePointsAvailable()) { if ((cp1 = this.ParsePoint()) == null) break; if (relative) { cp1.x += cp.x; cp1.y += cp.y; } path.line(cp1.x, cp1.y); } cp.x = cp1.x; cp.y = cp1.y; cbz = qbz = false; break; case 'l': relative = true; case 'L': while (this.MorePointsAvailable()) { if ((cp1 = this.ParsePoint()) == null) break; if (relative) { cp1.x += cp.x; cp1.y += cp.y; } path.line(cp1.x, cp1.y); cp.x = cp1.x; cp.y = cp1.y; this.Advance(); } cbz = qbz = false; break; case 'h': relative = true; case 'H': var x = this.ParseDouble(); if (x == null) break; if (relative) x += cp.x; cp = new Point(x, cp.y); path.line(cp.x, cp.y); cbz = qbz = false; break; case 'v': relative = true; case 'V': var y = this.ParseDouble(); if (y == null) break; if (relative) y += cp.y; cp = new Point(cp.x, y); path.line(cp.x, cp.y); cbz = qbz = false; break; case 'c': relative = true; case 'C': while (this.MorePointsAvailable()) { if ((cp1 = this.ParsePoint()) == null) break; if (relative) { cp1.x += cp.x; cp1.y += cp.y; } this.Advance(); if ((cp2 = this.ParsePoint()) == null) break; if (relative) { cp2.x += cp.x; cp2.y += cp.y; } this.Advance(); if ((cp3 = this.ParsePoint()) == null) break; if (relative) { cp3.x += cp.x; cp3.y += cp.y; } this.Advance(); path.cubicBezier(cp1.x, cp1.y, cp2.x, cp2.y, cp3.x, cp3.y); cp1.x = cp3.x; cp1.y = cp3.y; } cp.x = cp3.x; cp.y = cp3.y; cbz = true; cbzp.x = cp2.x; cbzp.y = cp2.y; qbz = false; break; case 's': relative = true; case 'S': while (this.MorePointsAvailable()) { if ((cp2 = this.ParsePoint()) == null) break; if (relative) { cp2.x += cp.x; cp2.y += cp.y; } this.Advance(); if ((cp3 = this.ParsePoint()) == null) break; if (relative) { cp3.x += cp.x; cp3.y += cp.y; } if (cbz) { cp1.x = 2 * cp.x - cbzp.x; cp1.y = 2 * cp.y - cbzp.y; } else cp1 = cp; path.cubicBezier(cp1.x, cp1.y, cp2.x, cp2.y, cp3.x, cp3.y); cbz = true; cbzp.x = cp2.x; cbzp.y = cp2.y; cp.x = cp3.x; cp.y = cp3.y; this.Advance(); } qbz = false; break; case 'q': relative = true; case 'Q': while (this.MorePointsAvailable()) { if ((cp1 = this.ParsePoint()) == null) break; if (relative) { cp1.x += cp.x; cp1.y += cp.y; } this.Advance(); if ((cp2 = this.ParsePoint()) == null) break; if (relative) { cp2.x += cp.x; cp2.y += cp.y; } this.Advance(); path.quadraticBezier(cp1.x, cp1.y, cp2.x, cp2.y); cp.x = cp2.x; cp.y = cp2.y; } qbz = true; qbzp.x = cp1.x; qbzp.y = cp1.y; cbz = false; break; case 't': relative = true; case 'T': while (this.MorePointsAvailable()) { if ((cp2 = this.ParsePoint()) == null) break; if (relative) { cp2.x += cp.x; cp2.y += cp.y; } if (qbz) { cp1.x = 2 * cp.x - qbzp.x; cp1.y = 2 * cp.y - qbzp.y; } else cp1 = cp; path.quadraticBezier(cp1.x, cp1.y, cp2.x, cp2.y); qbz = true; qbzp.x = cp1.x; qbzp.y = cp1.y; cp.x = cp2.x; cp.y = cp2.y; this.Advance(); } cbz = false; break; case 'a': relative = true; case 'A': while (this.MorePointsAvailable()) { if ((cp1 = this.ParsePoint()) == null) break; var angle = this.ParseDouble(); var is_large = this.ParseDouble() !== 0; var sweep = minerva.SweepDirection.Counterclockwise; if (this.ParseDouble() !== 0) sweep = minerva.SweepDirection.Clockwise; if ((cp2 = this.ParsePoint()) == null) break; if (relative) { cp2.x += cp.x; cp2.y += cp.y; } path.ellipticalArc(cp1.x, cp1.y, angle, is_large, sweep, cp2.x, cp2.y); cp.x = cp2.x; cp.y = cp2.y; this.Advance(); } cbz = qbz = false; break; case 'z': case 'Z': //path.Line(start.x, start.y); path.close(); //path.Move(start.x, start.y); cp.x = start.x; cp.y = start.y; cbz = qbz = false; break; default: break; } } var pg = new PathGeometry(); pg.OverridePath(path); pg.FillRule = <Shapes.FillRule>fillRule; return pg; } ParseShapePoints (): Point[] { var points: Point[] = []; var p: Point; while (this.MorePointsAvailable() && (p = this.ParsePoint()) != null) { points.push(p); } return points; } private ParsePoint (): Point { var x = this.ParseDouble(); if (x == null) return null; var c; while (this.index < this.len && ((c = this.str.charAt(this.index)) === ' ' || c === ',')) { this.index++; } if (this.index >= this.len) return null; var y = this.ParseDouble(); if (y == null) return null; return new Point(x, y); } private ParseDouble (): number { this.Advance(); var isNegative = false; if (this.Match('-')) { isNegative = true; this.index++; } else if (this.Match('+')) { this.index++; } if (this.Match('Infinity')) { this.index += 8; return isNegative ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY; } if (this.Match('NaN')) return NaN; var temp = ''; while (this.index < this.len) { var code = this.str.charCodeAt(this.index); var c = this.str[this.index]; //0-9, ., E, e, E-, e- if (code >= 48 && code <= 57) temp += c; else if (code === 46) temp += c; else if (c === 'E' || c === 'e') { temp += c; if (this.str[this.index + 1] === '-') { temp += '-'; this.index++; } } else break; this.index++; } if (temp.length === 0) return null; var f = parseFloat(temp); return isNegative ? -f : f; } private Match (matchStr: string): boolean { var c1: string; var c2: string; for (var i = 0; i < matchStr.length && (this.index + i) < this.len; i++) { c1 = matchStr.charAt(i); c2 = this.str.charAt(this.index + i); if (c1 !== c2) return false; } return true; } private Advance () { var code: number; var c: string; while (this.index < this.len) { code = this.str.charCodeAt(this.index); //alphanum if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57)) break; c = String.fromCharCode(code); if (c === '.') break; if (c === '-') break; if (c === '+') break; this.index++; } } private MorePointsAvailable (): boolean { var c; while (this.index < this.len && ((c = this.str.charAt(this.index)) === ',' || c === ' ')) { this.index++; } if (this.index >= this.len) return false; if (c === '.' || c === '-' || c === '+') return true; var code = this.str.charCodeAt(this.index); return code >= 48 && code <= 57; } } nullstone.registerTypeConverter(Geometry, (val: any): any => { if (val instanceof Geometry) return val; if (typeof val === "string") return ParseGeometry(val); return val; }); }
the_stack
import { html, render as litRender } from 'lit-html'; import { createObjectStore } from 'reduxular'; import { gql, sudograph } from 'sudograph'; import { FileMeta, ChunkInfo, UploadState, DownloadState } from '../types/index.d'; import { GRAPHQL_CANISTER_ID } from '../utilities/environment'; import { AuthClient } from '@dfinity/auth-client'; import { Identity } from '@dfinity/agent'; type State = Readonly<{ identity: Identity | undefined; fileMetas: ReadonlyArray<FileMeta>; creatingFileMeta: boolean; uploadStates: { [fileId: string]: UploadState; }; downloadStates: { [fileId: string]: DownloadState; }; sudograph: any; // TODO get type for this, prepare for set and unset }>; const InitialState: State = { identity: undefined, fileMetas: [], creatingFileMeta: false, uploadStates: {}, downloadStates: {}, sudograph: null }; class FilesApp extends HTMLElement { shadow = this.attachShadow({ mode: 'closed' }); store = createObjectStore(InitialState, (state: State) => litRender(this.render(state), this.shadow), this); async connectedCallback() { const authClient = await AuthClient.create(); if (await authClient.isAuthenticated()) { this.store.identity = authClient.getIdentity(); } this.createAndSetSudographClient(); await this.fetchAndSetFileMetas(); } createAndSetSudographClient() { const sudographObject = sudograph({ canisterId: GRAPHQL_CANISTER_ID, identity: this.store.identity, mutationFunctionName: 'graphql_mutation_custom' }); this.store.sudograph = sudographObject; } async fetchAndSetFileMetas() { this.store.fileMetas = await fetchFileMetas(this.store.sudograph); this.store.fileMetas.forEach((fileMeta) => { this.store.uploadStates = { ...this.store.uploadStates, [fileMeta.id]: { uploading: false, percentage: 0, totalChunks: 0, totalChunksUploaded: 0 } }; }); this.store.fileMetas.forEach((fileMeta) => { this.store.downloadStates = { ...this.store.downloadStates, [fileMeta.id]: { downloading: false, percentage: 0, totalChunks: 0, totalChunksDownloaded: 0 } }; }); } async uploadFileHandler(e: InputEvent) { const files = (e.target as HTMLInputElement).files; const file = files?.[0]; if (file === undefined) { return; } this.store.creatingFileMeta = true; const { fileId, bytes, chunkInfos } = await createFileMeta( this.store.sudograph, file ); this.store.creatingFileMeta = false; await this.fetchAndSetFileMetas(); this.store.uploadStates = { ...this.store.uploadStates, [fileId]: { ...this.store.uploadStates[fileId], uploading: true, totalChunks: chunkInfos.length } }; await uploadFile( this.store.sudograph, fileId, bytes, chunkInfos, this.uploadFileNotifier.bind(this) ); this.store.uploadStates = { ...this.store.uploadStates, [fileId]: { ...this.store.uploadStates[fileId], uploading: false } }; } uploadFileNotifier(fileId: string) { const uploadState = this.store.uploadStates[fileId]; const percentage = uploadState.totalChunks === 0 ? 0 : Math.floor((uploadState.totalChunksUploaded / uploadState.totalChunks) * 100); this.store.uploadStates = { ...this.store.uploadStates, [fileId]: { ...uploadState, percentage, totalChunksUploaded: uploadState.totalChunksUploaded + 1 } }; } async downloadFileHandler(fileMeta: FileMeta) { this.store.downloadStates = { ...this.store.downloadStates, [fileMeta.id]: { downloading: true, percentage: 0, totalChunks: fileMeta.numChunks, totalChunksDownloaded: 0 } }; const allFileBytesArray = await fetchAllFileBytes( this.store.sudograph, fileMeta, this.downloadFileNotifier.bind(this) ); const allFileBytesUint8Array = Uint8Array.from(allFileBytesArray); const fileBlob = new Blob([allFileBytesUint8Array]); const fileBlobUrl = window.URL.createObjectURL(fileBlob); const a = document.createElement('a'); a.href = fileBlobUrl; a.download = fileMeta.name; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(fileBlobUrl); document.body.removeChild(a); this.store.downloadStates = { ...this.store.downloadStates, [fileMeta.id]: { ...this.store.downloadStates[fileMeta.id], downloading: false } }; } downloadFileNotifier(fileId: string) { const downloadState = this.store.downloadStates[fileId]; const percentage = downloadState.totalChunks === 0 ? 0 : Math.floor((downloadState.totalChunksDownloaded / downloadState.totalChunks) * 100); this.store.downloadStates = { ...this.store.downloadStates, [fileId]: { ...downloadState, percentage, totalChunksDownloaded: downloadState.totalChunksDownloaded + 1 } }; } async login() { const authClient = await AuthClient.create(); await authClient.login({ onSuccess: () => { this.store.identity = authClient.getIdentity(); this.createAndSetSudographClient(); } }); } render(state: State) { return html` <style> .file-info-container { padding-bottom: 1rem; } .file-info { padding: .5rem; } </style> <h1>Files</h1> <br> <div ?hidden=${state.identity !== undefined}> <button @click=${() => this.login()} > Login </button> <div>* this is a demo and only lastmjs can upload files</div> </div> <div ?hidden=${state.identity === undefined}> <input type="file" @change=${(e: InputEvent) => this.uploadFileHandler(e)} .disabled=${state.creatingFileMeta === true} > <span ?hidden=${state.creatingFileMeta === false}>Saving...</span> </div> <br> <div> ${state.fileMetas.map((fileMeta) => { const uploadState = state.uploadStates[fileMeta.id]; const downloadState = state.downloadStates[fileMeta.id]; if ( uploadState === undefined || downloadState === undefined ) { return html``; } return html` <div class="file-info-container"> <div class="file-info"> ${fileMeta.name} <button ?hidden=${uploadState.uploading === true || downloadState.downloading === true} @click=${() => this.downloadFileHandler(fileMeta)} > Download </button> <div ?hidden=${uploadState.uploading === false} > Uploading: ${uploadState.percentage}% </div> <div ?hidden=${downloadState.downloading === false} > Downloading: ${downloadState.percentage}% </div> </div> </div> `; })} </div> `; } } window.customElements.define('files-app', FilesApp); // TODO add type for query async function fetchFileMetas(sudograph: any): Promise<ReadonlyArray<FileMeta>> { const result = await sudograph.query(gql` query { readFile { id name numChunks } } `); const fileMetas: ReadonlyArray<FileMeta> = result.data.readFile; return fileMetas; } async function fetchAllFileBytes( sudograph: any, fileMeta: FileMeta, notifier: (fileId: string) => void, limit: number = 1 ): Promise<ReadonlyArray<number>> { const promises = new Array(fileMeta.numChunks).fill(0).map(async (_, index) => { const result = await sudograph.query(gql` query ( $fileId: ID! $offset: Int! $limit: Int! ) { readFileChunk(search: { file: { id: { eq: $fileId } } }, limit: $limit, offset: $offset, order: { startByte: ASC }) { id bytes startByte endByte } } `, { fileId: fileMeta.id, offset: index, limit }); console.log('fetchAllFileBytes result', result); notifier(fileMeta.id); // TODO add error handling const bytes: ReadonlyArray<number> = result.data.readFileChunk[0].bytes; return bytes; }); const byteArrays = await Promise.all(promises); return byteArrays.flat(); } async function createFileMeta( sudograph: any, file: File, limit: number = 250000 // TODO make a global setting for this that the user can configure ): Promise<{ fileId: string; bytes: Uint8Array, chunkInfos: ReadonlyArray<ChunkInfo> }> { const bytes = new Uint8Array(await file.arrayBuffer()); const chunkInfos = getChunkInfos( 0, limit, bytes.length ); const fileId = await createFile( sudograph, new Date(), file.name, chunkInfos.length ); return { fileId, bytes, chunkInfos }; } function getChunkInfos( offset: number, limit: number, totalBytes: number, chunkInfos: ReadonlyArray<ChunkInfo> = [] ): ReadonlyArray<ChunkInfo> { if (limit + offset >= totalBytes) { return [ ...chunkInfos, { startByte: offset, endByte: totalBytes - 1 } ]; } return getChunkInfos( offset + limit, limit, totalBytes, [ ...chunkInfos, { startByte: offset, endByte: offset + limit - 1 } ] ); } async function createFile( sudograph: any, createdAt: Date, name: string, numChunks: number ): Promise<string> { const createFileResult = await sudograph.mutation(gql` mutation ( $createdAt: Date! $name: String! $numChunks: Int! ) { createFile(input: { createdAt: $createdAt name: $name numChunks: $numChunks }) { id } } `, { createdAt, name, numChunks }); console.log('createFileResult', createFileResult); // TODO add error handling const fileId: string = createFileResult.data.createFile[0].id; return fileId; } async function uploadFile( sudograph: any, fileId: string, bytes: Uint8Array, chunkInfos: ReadonlyArray<ChunkInfo>, notifier: (fileId: string) => void ): Promise<void> { const promises = chunkInfos.map(async (chunkInfo) => { const slice = Array.from(bytes.slice(chunkInfo.startByte, chunkInfo.endByte + 1)); await createFileChunk( sudograph, slice, chunkInfo.endByte, fileId, chunkInfo.startByte ); notifier(fileId); }); await Promise.all(promises); } async function createFileChunk( sudograph: any, bytes: ReadonlyArray<number>, endByte: number, fileId: string, startByte: number ): Promise<void> { const createFileChunkResult = await sudograph.mutation(gql` mutation ( $bytes: Blob! $endByte: Int! $fileId: ID! $startByte: Int! ) { createFileChunk(input: { bytes: $bytes endByte: $endByte file: { connect: $fileId } startByte: $startByte }) { id } } `, { bytes, endByte, fileId, startByte }); console.log('createFileChunkResult', createFileChunkResult); }
the_stack
import * as _ from 'lodash'; import { expect } from 'chai'; import * as parallel from 'mocha.parallel'; import type * as BalenaSdk from '../../..'; const getAllByResourcePropNameProvider = (resourceName: string) => `getAllBy${_.upperFirst(_.camelCase(resourceName))}`; const getAllByResourceFactory = function <T extends BalenaSdk.ResourceTagBase>( model: TagModelBase<T>, resourceName: string, ) { const propName = getAllByResourcePropNameProvider(resourceName); return function ( idOrUniqueParam: number | string, cb?: (err: Error | null, result?: any) => void, ) { return (model as any)[propName](idOrUniqueParam, cb) as Promise< BalenaSdk.ResourceTagBase[] >; }; }; export interface TagModelBase<T extends BalenaSdk.ResourceTagBase> { getAll( options?: BalenaSdk.PineOptions<BalenaSdk.ResourceTagBase>, ): Promise<T[]>; set(uuidOrId: string | number, tagKey: string, value: string): Promise<void>; remove(uuidOrId: string | number, tagKey: string): Promise<void>; } export interface Options<T extends BalenaSdk.ResourceTagBase> { model: TagModelBase<T>; modelNamespace: string; resourceName: string; uniquePropertyNames: string[]; resourceProvider?: () => { id: number }; setTagResourceProvider?: () => { id: number }; } export const itShouldGetAllTagsByResource = function < T extends BalenaSdk.ResourceTagBase, >(opts: Options<T>) { const { model, resourceName, uniquePropertyNames } = opts; const getAllByResource = getAllByResourceFactory(model, resourceName); let ctx: Mocha.Context; before(function () { if (!opts.resourceProvider) { throw new Error('A resourceProvider was not provided!'); } this.resource = opts.resourceProvider(); // used for tag creation in beforeEach this.setTagResource = ( opts.setTagResourceProvider || opts.resourceProvider )(); ctx = this; }); parallel('', function () { it('should become an empty array by default [Promise]', function () { const promise = getAllByResource(ctx.resource.id); return expect(promise).to.become([]); }); it('should become an empty array by default [callback]', function (done) { getAllByResource(ctx.resource.id, function (err, tags) { try { expect(err).to.be.null; expect(tags).to.deep.equal([]); done(); } catch (err) { done(err); } }); }); it(`should be rejected if the ${resourceName} id does not exist`, function () { const promise = getAllByResource(999999); return expect(promise).to.be.rejectedWith( `${_.startCase(resourceName)} not found: 999999`, ); }); uniquePropertyNames.forEach((uniquePropertyName) => { it(`should be rejected if the ${resourceName} ${uniquePropertyName} does not exist`, function () { const promise = getAllByResource( uniquePropertyName === 'id' ? 123456789 : '123456789', ); return expect(promise).to.be.rejectedWith( `${_.startCase(resourceName)} not found: 123456789`, ); }); }); }); describe('given a tag', function () { before(function () { ctx = this; // we use the tag associated resource id here // for cases like device.tags.getAllByApplication() // where @setTagResource will be a device and // @resource will be an application return model.set(this.setTagResource.id, 'EDITOR', 'vim'); }); after(function () { return model.remove(this.setTagResource.id, 'EDITOR'); }); parallel('', function () { uniquePropertyNames.forEach((uniquePropertyName) => { it(`should retrieve the tag by ${resourceName} ${uniquePropertyName}`, async function () { const tags = await getAllByResource(ctx.resource[uniquePropertyName]); expect(tags).to.have.length(1); expect(tags[0].tag_key).to.equal('EDITOR'); expect(tags[0].value).to.equal('vim'); }); }); it(`should retrieve the tag by ${resourceName} id [callback]`, function (done) { getAllByResource(ctx.resource.id, function (err, tags) { try { expect(err).to.be.null; expect(tags).to.have.length(1); expect(tags[0].tag_key).to.equal('EDITOR'); expect(tags[0].value).to.equal('vim'); done(); } catch (err) { done(err); } }); }); }); }); }; export const itShouldSetGetAndRemoveTags = function < T extends BalenaSdk.ResourceTagBase, >(opts: Options<T>) { const { model, resourceName, uniquePropertyNames, modelNamespace } = opts; const getAllByResource = getAllByResourceFactory(model, resourceName); before(function () { if (!opts.resourceProvider) { throw new Error('A resourceProvider was not provided!'); } this.resource = opts.resourceProvider(); }); uniquePropertyNames.forEach((param) => describe(`given a ${resourceName} ${param}`, function () { const $it = param ? it : it.skip; $it( `should be rejected if the ${resourceName} id does not exist`, function () { const resourceUniqueKey = param === 'id' ? 999999 : '123456789'; const promise = model.set(resourceUniqueKey, 'EDITOR', 'vim'); return expect(promise).to.be.rejectedWith( `${_.startCase(resourceName)} not found: ${resourceUniqueKey}`, ); }, ); $it('should initially have no tags', async function () { const tags = await getAllByResource(this.resource[param]); return expect(tags).to.have.length(0); }); $it('...should be able to create a tag', function () { const promise = model.set( this.resource[param], `EDITOR_BY_${resourceName}_${param}`, 'vim', ); return expect(promise).to.not.be.rejected; }); $it( '...should be able to retrieve all tags, including the one created', async function () { const tags = await getAllByResource(this.resource[param]); expect(tags).to.have.length(1); const tag = tags[0]; expect(tag).to.be.an('object'); expect(tag.tag_key).to.equal(`EDITOR_BY_${resourceName}_${param}`); expect(tag.value).to.equal('vim'); }, ); $it('...should be able to update a tag', async function () { await model.set( this.resource[param], `EDITOR_BY_${resourceName}_${param}`, 'nano', ); const tags = await getAllByResource(this.resource[param]); expect(tags).to.have.length(1); const tag = tags[0]; expect(tag).to.be.an('object'); expect(tag.tag_key).to.equal(`EDITOR_BY_${resourceName}_${param}`); expect(tag.value).to.equal('nano'); }); $it('...should be able to remove a tag', async function () { await model.remove( this.resource[param], `EDITOR_BY_${resourceName}_${param}`, ); const tags = await getAllByResource(this.resource.id); return expect(tags).to.have.length(0); }); }), ); describe(`${modelNamespace}.set()`, function () { it('should not allow creating a resin tag', function () { const promise = model.set(this.resource.id, 'io.resin.test', 'secret'); return expect(promise).to.be.rejectedWith( 'Tag keys beginning with io.resin. are reserved.', ); }); it('should not allow creating a balena tag', function () { const promise = model.set(this.resource.id, 'io.balena.test', 'secret'); return expect(promise).to.be.rejectedWith( 'Tag keys beginning with io.balena. are reserved.', ); }); it('should not allow creating a tag with a name containing a whitespace', function () { const promise = model.set(this.resource.id, 'EDITOR 1', 'vim'); return expect(promise).to.be.rejectedWith( /Request error: Tag keys cannot contain whitespace./, ); }); it('should be rejected if the tag_key is undefined', function () { const promise = model.set(this.resource.id, undefined as any, 'vim'); return expect(promise).to.be.rejected; }); it('should be rejected if the tag_key is null', function () { const promise = model.set(this.resource.id, null as any, 'vim'); return expect(promise).to.be.rejected; }); it('should be able to create a numeric tag', async function () { await model.set(this.resource.id, 'EDITOR_NUMERIC', 1 as any); const tags = await getAllByResource(this.resource.id); expect(tags).to.have.length(1); expect(tags[0].tag_key).to.equal('EDITOR_NUMERIC'); expect(tags[0].value).to.equal('1'); return model.remove(this.resource.id, 'EDITOR_NUMERIC'); }); }); describe('given two existing tags', function () { let ctx: Mocha.Context; before(function () { ctx = this; return Promise.all([ model.set(this.resource.id, 'EDITOR', 'vim'), model.set(this.resource.id, 'LANGUAGE', 'js'), ]); }); after(function () { return Promise.all([ model.remove(this.resource.id, 'EDITOR'), model.remove(this.resource.id, 'LANGUAGE'), ]); }); parallel(`${modelNamespace}.getAll()`, function () { it('should retrieve all the tags', async function () { let tags = await model.getAll(); tags = _.sortBy(tags, 'tag_key'); expect(tags.length).to.be.gte(2); // exclude tags that the user can access b/c of public apps const tagsOfUsersResource = tags.filter( (t) => t[resourceName].__id === ctx.resource.id, ); expect(tagsOfUsersResource[0].tag_key).to.equal('EDITOR'); expect(tagsOfUsersResource[0].value).to.equal('vim'); expect(tagsOfUsersResource[1].tag_key).to.equal('LANGUAGE'); expect(tagsOfUsersResource[1].value).to.equal('js'); }); it('should retrieve the filtered tag', async function () { const tags = await model.getAll({ $filter: { tag_key: 'EDITOR' } }); expect(tags.length).to.be.gte(1); // exclude tags that the user can access b/c of public apps const tagsOfUsersResource = tags.filter( (t) => t[resourceName].__id === ctx.resource.id, ); expect(tagsOfUsersResource[0].tag_key).to.equal('EDITOR'); expect(tagsOfUsersResource[0].value).to.equal('vim'); }); }); describe(`${modelNamespace}.set()`, () => it('should be able to update a tag without affecting the rest', async function () { await model.set(ctx.resource.id, 'EDITOR', 'emacs'); let tags = await getAllByResource(ctx.resource.id); tags = _.sortBy(tags, 'tag_key'); expect(tags).to.have.length(2); expect(tags[0].tag_key).to.equal('EDITOR'); expect(tags[0].value).to.equal('emacs'); expect(tags[1].tag_key).to.equal('LANGUAGE'); expect(tags[1].value).to.equal('js'); })); }); };
the_stack
import { Injectable } from '@angular/core'; import { CoreFileUploaderStoreFilesResult } from '@features/fileuploader/services/fileuploader'; import { CoreFile } from '@services/file'; import { CoreSites } from '@services/sites'; import { CoreTextUtils } from '@services/utils/text'; import { CoreTimeUtils } from '@services/utils/time'; import { makeSingleton } from '@singletons'; import { CoreFormFields } from '@singletons/form'; import { CoreText } from '@singletons/text'; import { AddonModWorkshopAssessmentDBRecord, AddonModWorkshopEvaluateAssessmentDBRecord, AddonModWorkshopEvaluateSubmissionDBRecord, AddonModWorkshopSubmissionDBRecord, ASSESSMENTS_TABLE, EVALUATE_ASSESSMENTS_TABLE, EVALUATE_SUBMISSIONS_TABLE, SUBMISSIONS_TABLE, } from './database/workshop'; import { AddonModWorkshopAction } from './workshop'; /** * Service to handle offline workshop. */ @Injectable({ providedIn: 'root' }) export class AddonModWorkshopOfflineProvider { /** * Get all the workshops ids that have something to be synced. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with workshops id that have something to be synced. */ async getAllWorkshops(siteId?: string): Promise<number[]> { const promiseResults = await Promise.all([ this.getAllSubmissions(siteId), this.getAllAssessments(siteId), this.getAllEvaluateSubmissions(siteId), this.getAllEvaluateAssessments(siteId), ]); const workshopIds: Record<number, number> = {}; // Get workshops from any offline object all should have workshopid. promiseResults.forEach((offlineObjects) => { offlineObjects.forEach((offlineObject: AddonModWorkshopOfflineSubmission | AddonModWorkshopOfflineAssessment | AddonModWorkshopOfflineEvaluateSubmission | AddonModWorkshopOfflineEvaluateAssessment) => { workshopIds[offlineObject.workshopid] = offlineObject.workshopid; }); }); return Object.values(workshopIds); } /** * Check if there is an offline data to be synced. * * @param workshopId Workshop ID to remove. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: true if has offline data, false otherwise. */ async hasWorkshopOfflineData(workshopId: number, siteId?: string): Promise<boolean> { try { const results = await Promise.all([ this.getSubmissions(workshopId, siteId), this.getAssessments(workshopId, siteId), this.getEvaluateSubmissions(workshopId, siteId), this.getEvaluateAssessments(workshopId, siteId), ]); return results.some((result) => result && result.length); } catch { // No offline data found. return false; } } /** * Delete workshop submission action. * * @param workshopId Workshop ID. * @param submissionId Submission ID. * @param action Action to be done. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if stored, rejected if failure. */ async deleteSubmissionAction( workshopId: number, action: AddonModWorkshopAction, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopSubmissionDBRecord> = { workshopid: workshopId, action: action, }; await site.getDb().deleteRecords(SUBMISSIONS_TABLE, conditions); } /** * Delete all workshop submission actions. * * @param workshopId Workshop ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if stored, rejected if failure. */ async deleteAllSubmissionActions(workshopId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopSubmissionDBRecord> = { workshopid: workshopId, }; await site.getDb().deleteRecords(SUBMISSIONS_TABLE, conditions); } /** * Get the all the submissions to be synced. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the objects to be synced. */ async getAllSubmissions(siteId?: string): Promise<AddonModWorkshopOfflineSubmission[]> { const site = await CoreSites.getSite(siteId); const records = await site.getDb().getRecords<AddonModWorkshopSubmissionDBRecord>(SUBMISSIONS_TABLE); return records.map(this.parseSubmissionRecord.bind(this)); } /** * Get the submissions of a workshop to be synced. * * @param workshopId ID of the workshop. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the object to be synced. */ async getSubmissions(workshopId: number, siteId?: string): Promise<AddonModWorkshopOfflineSubmission[]> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopSubmissionDBRecord> = { workshopid: workshopId, }; const records = await site.getDb().getRecords<AddonModWorkshopSubmissionDBRecord>(SUBMISSIONS_TABLE, conditions); return records.map(this.parseSubmissionRecord.bind(this)); } /** * Get an specific action of a submission of a workshop to be synced. * * @param workshopId ID of the workshop. * @param action Action to be done. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the object to be synced. */ async getSubmissionAction( workshopId: number, action: AddonModWorkshopAction, siteId?: string, ): Promise<AddonModWorkshopOfflineSubmission> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopSubmissionDBRecord> = { workshopid: workshopId, action: action, }; const record = await site.getDb().getRecord<AddonModWorkshopSubmissionDBRecord>(SUBMISSIONS_TABLE, conditions); return this.parseSubmissionRecord(record); } /** * Offline version for adding a submission action to a workshop. * * @param workshopId Workshop ID. * @param courseId Course ID the workshop belongs to. * @param title The submission title. * @param content The submission text content. * @param attachmentsId Stored attachments. * @param submissionId Submission Id, if action is add, the time the submission was created. * If set to 0, current time is used. * @param action Action to be done. ['add', 'update', 'delete'] * @param siteId Site ID. If not defined, current site. * @return Promise resolved when submission action is successfully saved. */ async saveSubmission( workshopId: number, courseId: number, title: string, content: string, attachmentsId: CoreFileUploaderStoreFilesResult | undefined, submissionId = 0, action: AddonModWorkshopAction, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const timemodified = CoreTimeUtils.timestamp(); const submission: AddonModWorkshopSubmissionDBRecord = { workshopid: workshopId, courseid: courseId, title: title, content: content, attachmentsid: JSON.stringify(attachmentsId), action: action, submissionid: submissionId, timemodified: timemodified, }; await site.getDb().insertRecord(SUBMISSIONS_TABLE, submission); } /** * Parse "attachments" column of a submission record. * * @param record Submission record, modified in place. */ protected parseSubmissionRecord(record: AddonModWorkshopSubmissionDBRecord): AddonModWorkshopOfflineSubmission { return { ...record, attachmentsid: CoreTextUtils.parseJSON(record.attachmentsid), }; } /** * Delete workshop assessment. * * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if stored, rejected if failure. */ async deleteAssessment(workshopId: number, assessmentId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopAssessmentDBRecord> = { workshopid: workshopId, assessmentid: assessmentId, }; await site.getDb().deleteRecords(ASSESSMENTS_TABLE, conditions); } /** * Get the all the assessments to be synced. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the objects to be synced. */ async getAllAssessments(siteId?: string): Promise<AddonModWorkshopOfflineAssessment[]> { const site = await CoreSites.getSite(siteId); const records = await site.getDb().getRecords<AddonModWorkshopAssessmentDBRecord>(ASSESSMENTS_TABLE); return records.map(this.parseAssessmentRecord.bind(this)); } /** * Get the assessments of a workshop to be synced. * * @param workshopId ID of the workshop. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the object to be synced. */ async getAssessments(workshopId: number, siteId?: string): Promise<AddonModWorkshopOfflineAssessment[]> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopAssessmentDBRecord> = { workshopid: workshopId, }; const records = await site.getDb().getRecords<AddonModWorkshopAssessmentDBRecord>(ASSESSMENTS_TABLE, conditions); return records.map(this.parseAssessmentRecord.bind(this)); } /** * Get an specific assessment of a workshop to be synced. * * @param workshopId ID of the workshop. * @param assessmentId Assessment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the object to be synced. */ async getAssessment(workshopId: number, assessmentId: number, siteId?: string): Promise<AddonModWorkshopOfflineAssessment> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopAssessmentDBRecord> = { workshopid: workshopId, assessmentid: assessmentId, }; const record = await site.getDb().getRecord<AddonModWorkshopAssessmentDBRecord>(ASSESSMENTS_TABLE, conditions); return this.parseAssessmentRecord(record); } /** * Offline version for adding an assessment to a workshop. * * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param courseId Course ID the workshop belongs to. * @param inputData Assessment data. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when assessment is successfully saved. */ async saveAssessment( workshopId: number, assessmentId: number, courseId: number, inputData: CoreFormFields, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const assessment: AddonModWorkshopAssessmentDBRecord = { workshopid: workshopId, courseid: courseId, inputdata: JSON.stringify(inputData), assessmentid: assessmentId, timemodified: CoreTimeUtils.timestamp(), }; await site.getDb().insertRecord(ASSESSMENTS_TABLE, assessment); } /** * Parse "inpudata" column of an assessment record. * * @param record Assessnent record, modified in place. */ protected parseAssessmentRecord(record: AddonModWorkshopAssessmentDBRecord): AddonModWorkshopOfflineAssessment { return { ...record, inputdata: CoreTextUtils.parseJSON(record.inputdata), }; } /** * Delete workshop evaluate submission. * * @param workshopId Workshop ID. * @param submissionId Submission ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if stored, rejected if failure. */ async deleteEvaluateSubmission(workshopId: number, submissionId: number, siteId?: string): Promise<void> { const conditions: Partial<AddonModWorkshopEvaluateSubmissionDBRecord> = { workshopid: workshopId, submissionid: submissionId, }; const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(EVALUATE_SUBMISSIONS_TABLE, conditions); } /** * Get the all the evaluate submissions to be synced. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the objects to be synced. */ async getAllEvaluateSubmissions(siteId?: string): Promise<AddonModWorkshopOfflineEvaluateSubmission[]> { const site = await CoreSites.getSite(siteId); const records = await site.getDb().getRecords<AddonModWorkshopEvaluateSubmissionDBRecord>(EVALUATE_SUBMISSIONS_TABLE); return records.map(this.parseEvaluateSubmissionRecord.bind(this)); } /** * Get the evaluate submissions of a workshop to be synced. * * @param workshopId ID of the workshop. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the object to be synced. */ async getEvaluateSubmissions(workshopId: number, siteId?: string): Promise<AddonModWorkshopOfflineEvaluateSubmission[]> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopEvaluateSubmissionDBRecord> = { workshopid: workshopId, }; const records = await site.getDb().getRecords<AddonModWorkshopEvaluateSubmissionDBRecord>(EVALUATE_SUBMISSIONS_TABLE, conditions); return records.map(this.parseEvaluateSubmissionRecord.bind(this)); } /** * Get an specific evaluate submission of a workshop to be synced. * * @param workshopId ID of the workshop. * @param submissionId Submission ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the object to be synced. */ async getEvaluateSubmission( workshopId: number, submissionId: number, siteId?: string, ): Promise<AddonModWorkshopOfflineEvaluateSubmission> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopEvaluateSubmissionDBRecord> = { workshopid: workshopId, submissionid: submissionId, }; const record = await site.getDb().getRecord<AddonModWorkshopEvaluateSubmissionDBRecord>(EVALUATE_SUBMISSIONS_TABLE, conditions); return this.parseEvaluateSubmissionRecord(record); } /** * Offline version for evaluation a submission to a workshop. * * @param workshopId Workshop ID. * @param submissionId Submission ID. * @param courseId Course ID the workshop belongs to. * @param feedbackText The feedback for the author. * @param published Whether to publish the submission for other users. * @param gradeOver The new submission grade (empty for no overriding the grade). * @param siteId Site ID. If not defined, current site. * @return Promise resolved when submission evaluation is successfully saved. */ async saveEvaluateSubmission( workshopId: number, submissionId: number, courseId: number, feedbackText = '', published?: boolean, gradeOver?: string, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const submission: AddonModWorkshopEvaluateSubmissionDBRecord = { workshopid: workshopId, courseid: courseId, submissionid: submissionId, timemodified: CoreTimeUtils.timestamp(), feedbacktext: feedbackText, published: Number(published), gradeover: JSON.stringify(gradeOver), }; await site.getDb().insertRecord(EVALUATE_SUBMISSIONS_TABLE, submission); } /** * Parse "published" and "gradeover" columns of an evaluate submission record. * * @param record Evaluate submission record, modified in place. */ protected parseEvaluateSubmissionRecord( record: AddonModWorkshopEvaluateSubmissionDBRecord, ): AddonModWorkshopOfflineEvaluateSubmission { return { ...record, published: Boolean(record.published), gradeover: CoreTextUtils.parseJSON(record.gradeover), }; } /** * Delete workshop evaluate assessment. * * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if stored, rejected if failure. */ async deleteEvaluateAssessment(workshopId: number, assessmentId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopEvaluateAssessmentDBRecord> = { workshopid: workshopId, assessmentid: assessmentId, }; await site.getDb().deleteRecords(EVALUATE_ASSESSMENTS_TABLE, conditions); } /** * Get the all the evaluate assessments to be synced. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the objects to be synced. */ async getAllEvaluateAssessments(siteId?: string): Promise<AddonModWorkshopOfflineEvaluateAssessment[]> { const site = await CoreSites.getSite(siteId); const records = await site.getDb().getRecords<AddonModWorkshopEvaluateAssessmentDBRecord>(EVALUATE_ASSESSMENTS_TABLE); return records.map(this.parseEvaluateAssessmentRecord.bind(this)); } /** * Get the evaluate assessments of a workshop to be synced. * * @param workshopId ID of the workshop. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the object to be synced. */ async getEvaluateAssessments(workshopId: number, siteId?: string): Promise<AddonModWorkshopOfflineEvaluateAssessment[]> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopEvaluateAssessmentDBRecord> = { workshopid: workshopId, }; const records = await site.getDb().getRecords<AddonModWorkshopEvaluateAssessmentDBRecord>(EVALUATE_ASSESSMENTS_TABLE, conditions); return records.map(this.parseEvaluateAssessmentRecord.bind(this)); } /** * Get an specific evaluate assessment of a workshop to be synced. * * @param workshopId ID of the workshop. * @param assessmentId Assessment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the object to be synced. */ async getEvaluateAssessment( workshopId: number, assessmentId: number, siteId?: string, ): Promise<AddonModWorkshopOfflineEvaluateAssessment> { const site = await CoreSites.getSite(siteId); const conditions: Partial<AddonModWorkshopEvaluateAssessmentDBRecord> = { workshopid: workshopId, assessmentid: assessmentId, }; const record = await site.getDb().getRecord<AddonModWorkshopEvaluateAssessmentDBRecord>(EVALUATE_ASSESSMENTS_TABLE, conditions); return this.parseEvaluateAssessmentRecord(record); } /** * Offline version for evaluating an assessment to a workshop. * * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param courseId Course ID the workshop belongs to. * @param feedbackText The feedback for the reviewer. * @param weight The new weight for the assessment. * @param gradingGradeOver The new grading grade (empty for no overriding the grade). * @param siteId Site ID. If not defined, current site. * @return Promise resolved when assessment evaluation is successfully saved. */ async saveEvaluateAssessment( workshopId: number, assessmentId: number, courseId: number, feedbackText?: string, weight = 0, gradingGradeOver?: string, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const assessment: AddonModWorkshopEvaluateAssessmentDBRecord = { workshopid: workshopId, courseid: courseId, assessmentid: assessmentId, timemodified: CoreTimeUtils.timestamp(), feedbacktext: feedbackText || '', weight: weight, gradinggradeover: JSON.stringify(gradingGradeOver), }; await site.getDb().insertRecord(EVALUATE_ASSESSMENTS_TABLE, assessment); } /** * Parse "gradinggradeover" column of an evaluate assessment record. * * @param record Evaluate assessment record, modified in place. */ protected parseEvaluateAssessmentRecord( record: AddonModWorkshopEvaluateAssessmentDBRecord, ): AddonModWorkshopOfflineEvaluateAssessment { return { ...record, gradinggradeover: CoreTextUtils.parseJSON(record.gradinggradeover), }; } /** * Get the path to the folder where to store files for offline attachments in a workshop. * * @param workshopId Workshop ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the path. */ async getWorkshopFolder(workshopId: number, siteId?: string): Promise<string> { const site = await CoreSites.getSite(siteId); const siteFolderPath = CoreFile.getSiteFolder(site.getId()); const workshopFolderPath = 'offlineworkshop/' + workshopId + '/'; return CoreText.concatenatePaths(siteFolderPath, workshopFolderPath); } /** * Get the path to the folder where to store files for offline submissions. * * @param workshopId Workshop ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the path. */ async getSubmissionFolder(workshopId: number, siteId?: string): Promise<string> { const folderPath = await this.getWorkshopFolder(workshopId, siteId); return CoreText.concatenatePaths(folderPath, 'submission'); } /** * Get the path to the folder where to store files for offline assessment. * * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the path. */ async getAssessmentFolder(workshopId: number, assessmentId: number, siteId?: string): Promise<string> { let folderPath = await this.getWorkshopFolder(workshopId, siteId); folderPath += 'assessment/'; return CoreText.concatenatePaths(folderPath, String(assessmentId)); } } export const AddonModWorkshopOffline = makeSingleton(AddonModWorkshopOfflineProvider); export type AddonModWorkshopOfflineSubmission = Omit<AddonModWorkshopSubmissionDBRecord, 'attachmentsid'> & { attachmentsid?: CoreFileUploaderStoreFilesResult; }; export type AddonModWorkshopOfflineAssessment = Omit<AddonModWorkshopAssessmentDBRecord, 'inputdata'> & { inputdata: CoreFormFields; }; export type AddonModWorkshopOfflineEvaluateSubmission = Omit<AddonModWorkshopEvaluateSubmissionDBRecord, 'published' | 'gradeover'> & { published: boolean; gradeover: string; }; export type AddonModWorkshopOfflineEvaluateAssessment = Omit<AddonModWorkshopEvaluateAssessmentDBRecord, 'gradinggradeover'> & { gradinggradeover: string; };
the_stack
// Copyright (c) 2019 Erin Catto // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import * as b2 from "@box2d"; import * as testbed from "@testbed"; // This test demonstrates how to use the world ray-cast feature. // NOTE: we are intentionally filtering one of the polygons, therefore // the ray will always miss one type of polygon. // This callback finds the closest hit. Polygon 0 is filtered. class RayCastClosestCallback extends b2.RayCastCallback { public m_hit: boolean = false; public readonly m_point: b2.Vec2 = new b2.Vec2(); public readonly m_normal: b2.Vec2 = new b2.Vec2(); constructor() { super(); } public ReportFixture(fixture: b2.Fixture, point: b2.Vec2, normal: b2.Vec2, fraction: number): number { const body: b2.Body = fixture.GetBody(); const userData: any = body.GetUserData(); if (userData) { const index: number = userData.index; if (index === 0) { // By returning -1, we instruct the calling code to ignore this fixture // and continue the ray-cast to the next fixture. return -1; } } this.m_hit = true; this.m_point.Copy(point); this.m_normal.Copy(normal); // By returning the current fraction, we instruct the calling code to clip the ray and // continue the ray-cast to the next fixture. WARNING: do not assume that fixtures // are reported in order. However, by clipping, we can always get the closest fixture. return fraction; } } // This callback finds any hit. Polygon 0 is filtered. For this type of query we are usually // just checking for obstruction, so the actual fixture and hit point are irrelevant. class RayCastAnyCallback extends b2.RayCastCallback { public m_hit: boolean = false; public readonly m_point: b2.Vec2 = new b2.Vec2(); public readonly m_normal: b2.Vec2 = new b2.Vec2(); constructor() { super(); } public ReportFixture(fixture: b2.Fixture, point: b2.Vec2, normal: b2.Vec2, fraction: number): number { const body: b2.Body = fixture.GetBody(); const userData: any = body.GetUserData(); if (userData) { const index: number = userData.index; if (index === 0) { // By returning -1, we instruct the calling code to ignore this fixture // and continue the ray-cast to the next fixture. return -1; } } this.m_hit = true; this.m_point.Copy(point); this.m_normal.Copy(normal); // At this point we have a hit, so we know the ray is obstructed. // By returning 0, we instruct the calling code to terminate the ray-cast. return 0; } } // This ray cast collects multiple hits along the ray. Polygon 0 is filtered. // The fixtures are not necessary reported in order, so we might not capture // the closest fixture. class RayCastMultipleCallback extends b2.RayCastCallback { private static e_maxCount: number = 3; public m_points: b2.Vec2[] = b2.Vec2.MakeArray(RayCastMultipleCallback.e_maxCount); public m_normals: b2.Vec2[] = b2.Vec2.MakeArray(RayCastMultipleCallback.e_maxCount); public m_count: number = 0; constructor() { super(); } public ReportFixture(fixture: b2.Fixture, point: b2.Vec2, normal: b2.Vec2, fraction: number): number { const body: b2.Body = fixture.GetBody(); const userData: any = body.GetUserData(); if (userData) { const index: number = userData.index; if (index === 0) { // By returning -1, we instruct the calling code to ignore this fixture // and continue the ray-cast to the next fixture. return -1; } } // DEBUG: b2.Assert(this.m_count < RayCastMultipleCallback.e_maxCount); this.m_points[this.m_count].Copy(point); this.m_normals[this.m_count].Copy(normal); ++this.m_count; if (this.m_count === RayCastMultipleCallback.e_maxCount) { // At this point the buffer is full. // By returning 0, we instruct the calling code to terminate the ray-cast. return 0; } // By returning 1, we instruct the caller to continue without clipping the ray. return 1; } } enum RayCastMode { e_closest, e_any, e_multiple, } export class RayCast extends testbed.Test { private static e_maxBodies: number = 256; private m_bodyIndex: number = 0; private m_bodies: Array<b2.Body | null> = []; private m_polygons: b2.PolygonShape[] = []; private m_circle: b2.CircleShape = new b2.CircleShape(); private m_edge: b2.EdgeShape = new b2.EdgeShape(); private m_angle: number = 0; private m_mode: RayCastMode = RayCastMode.e_closest; constructor() { super(); for (let i = 0; i < 4; ++i) { this.m_polygons[i] = new b2.PolygonShape(); } // Ground body { const bd = new b2.BodyDef(); const ground = this.m_world.CreateBody(bd); const shape = new b2.EdgeShape(); shape.SetTwoSided(new b2.Vec2(-40.0, 0.0), new b2.Vec2(40.0, 0.0)); ground.CreateFixture(shape, 0.0); } { const vertices: b2.Vec2[] = [/*3*/]; vertices[0] = new b2.Vec2(-0.5, 0.0); vertices[1] = new b2.Vec2(0.5, 0.0); vertices[2] = new b2.Vec2(0.0, 1.5); this.m_polygons[0].Set(vertices, 3); } { const vertices: b2.Vec2[] = [/*3*/]; vertices[0] = new b2.Vec2(-0.1, 0.0); vertices[1] = new b2.Vec2(0.1, 0.0); vertices[2] = new b2.Vec2(0.0, 1.5); this.m_polygons[1].Set(vertices, 3); } { const w = 1.0; const b = w / (2.0 + b2.Sqrt(2.0)); const s = b2.Sqrt(2.0) * b; const vertices: b2.Vec2[] = [/*8*/]; vertices[0] = new b2.Vec2(0.5 * s, 0.0); vertices[1] = new b2.Vec2(0.5 * w, b); vertices[2] = new b2.Vec2(0.5 * w, b + s); vertices[3] = new b2.Vec2(0.5 * s, w); vertices[4] = new b2.Vec2(-0.5 * s, w); vertices[5] = new b2.Vec2(-0.5 * w, b + s); vertices[6] = new b2.Vec2(-0.5 * w, b); vertices[7] = new b2.Vec2(-0.5 * s, 0.0); this.m_polygons[2].Set(vertices, 8); } { this.m_polygons[3].SetAsBox(0.5, 0.5); } { this.m_circle.m_radius = 0.5; } { this.m_edge.SetTwoSided(new b2.Vec2(-1, 0), new b2.Vec2(1, 0)); } this.m_bodyIndex = 0; for (let i = 0; i < RayCast.e_maxBodies; ++i) { this.m_bodies[i] = null; } this.m_angle = 0; this.m_mode = RayCastMode.e_closest; } public CreateBody(index: number): void { const old_body = this.m_bodies[this.m_bodyIndex]; if (old_body !== null) { this.m_world.DestroyBody(old_body); this.m_bodies[this.m_bodyIndex] = null; } const bd: b2.BodyDef = new b2.BodyDef(); const x: number = b2.RandomRange(-10.0, 10.0); const y: number = b2.RandomRange(0.0, 20.0); bd.position.Set(x, y); bd.angle = b2.RandomRange(-b2.pi, b2.pi); bd.userData = {}; bd.userData.index = index; if (index === 4) { bd.angularDamping = 0.02; } const new_body = this.m_bodies[this.m_bodyIndex] = this.m_world.CreateBody(bd); if (index < 4) { const fd: b2.FixtureDef = new b2.FixtureDef(); fd.shape = this.m_polygons[index]; fd.friction = 0.3; new_body.CreateFixture(fd); } else if (index < 5) { const fd: b2.FixtureDef = new b2.FixtureDef(); fd.shape = this.m_circle; fd.friction = 0.3; new_body.CreateFixture(fd); } else { const fd: b2.FixtureDef = new b2.FixtureDef(); fd.shape = this.m_edge; fd.friction = 0.3; new_body.CreateFixture(fd); } this.m_bodyIndex = (this.m_bodyIndex + 1) % RayCast.e_maxBodies; } public DestroyBody(): void { for (let i = 0; i < RayCast.e_maxBodies; ++i) { const body = this.m_bodies[i]; if (body !== null) { this.m_world.DestroyBody(body); this.m_bodies[i] = null; return; } } } public Keyboard(key: string): void { switch (key) { case "1": case "2": case "3": case "4": case "5": case "6": this.CreateBody(parseInt(key, 10) - 1); break; case "d": this.DestroyBody(); break; case "m": if (this.m_mode === RayCastMode.e_closest) { this.m_mode = RayCastMode.e_any; } else if (this.m_mode === RayCastMode.e_any) { this.m_mode = RayCastMode.e_multiple; } else if (this.m_mode === RayCastMode.e_multiple) { this.m_mode = RayCastMode.e_closest; } } } public Step(settings: testbed.Settings): void { const advanceRay: boolean = !settings.m_pause || settings.m_singleStep; super.Step(settings); testbed.g_debugDraw.DrawString(5, this.m_textLine, "Press 1-6 to drop stuff, m to change the mode"); this.m_textLine += testbed.DRAW_STRING_NEW_LINE; switch (this.m_mode) { case RayCastMode.e_closest: testbed.g_debugDraw.DrawString(5, this.m_textLine, "Ray-cast mode: closest - find closest fixture along the ray"); break; case RayCastMode.e_any: testbed.g_debugDraw.DrawString(5, this.m_textLine, "Ray-cast mode: any - check for obstruction"); break; case RayCastMode.e_multiple: testbed.g_debugDraw.DrawString(5, this.m_textLine, "Ray-cast mode: multiple - gather multiple fixtures"); break; } this.m_textLine += testbed.DRAW_STRING_NEW_LINE; const L = 11.0; const point1 = new b2.Vec2(0.0, 10.0); const d = new b2.Vec2(L * b2.Cos(this.m_angle), L * b2.Sin(this.m_angle)); const point2 = b2.Vec2.AddVV(point1, d, new b2.Vec2()); if (this.m_mode === RayCastMode.e_closest) { const callback = new RayCastClosestCallback(); this.m_world.RayCast(callback, point1, point2); if (callback.m_hit) { testbed.g_debugDraw.DrawPoint(callback.m_point, 5.0, new b2.Color(0.4, 0.9, 0.4)); testbed.g_debugDraw.DrawSegment(point1, callback.m_point, new b2.Color(0.8, 0.8, 0.8)); const head = b2.Vec2.AddVV(callback.m_point, b2.Vec2.MulSV(0.5, callback.m_normal, b2.Vec2.s_t0), new b2.Vec2()); testbed.g_debugDraw.DrawSegment(callback.m_point, head, new b2.Color(0.9, 0.9, 0.4)); } else { testbed.g_debugDraw.DrawSegment(point1, point2, new b2.Color(0.8, 0.8, 0.8)); } } else if (this.m_mode === RayCastMode.e_any) { const callback = new RayCastAnyCallback(); this.m_world.RayCast(callback, point1, point2); if (callback.m_hit) { testbed.g_debugDraw.DrawPoint(callback.m_point, 5.0, new b2.Color(0.4, 0.9, 0.4)); testbed.g_debugDraw.DrawSegment(point1, callback.m_point, new b2.Color(0.8, 0.8, 0.8)); const head = b2.Vec2.AddVV(callback.m_point, b2.Vec2.MulSV(0.5, callback.m_normal, b2.Vec2.s_t0), new b2.Vec2()); testbed.g_debugDraw.DrawSegment(callback.m_point, head, new b2.Color(0.9, 0.9, 0.4)); } else { testbed.g_debugDraw.DrawSegment(point1, point2, new b2.Color(0.8, 0.8, 0.8)); } } else if (this.m_mode === RayCastMode.e_multiple) { const callback = new RayCastMultipleCallback(); this.m_world.RayCast(callback, point1, point2); testbed.g_debugDraw.DrawSegment(point1, point2, new b2.Color(0.8, 0.8, 0.8)); for (let i = 0; i < callback.m_count; ++i) { const p = callback.m_points[i]; const n = callback.m_normals[i]; testbed.g_debugDraw.DrawPoint(p, 5.0, new b2.Color(0.4, 0.9, 0.4)); testbed.g_debugDraw.DrawSegment(point1, p, new b2.Color(0.8, 0.8, 0.8)); const head = b2.Vec2.AddVV(p, b2.Vec2.MulSV(0.5, n, b2.Vec2.s_t0), new b2.Vec2()); testbed.g_debugDraw.DrawSegment(p, head, new b2.Color(0.9, 0.9, 0.4)); } } if (advanceRay) { this.m_angle += 0.25 * b2.pi / 180.0; } /* #if 0 // This case was failing. { b2Vec2 vertices[4]; //vertices[0].Set(-22.875f, -3.0f); //vertices[1].Set(22.875f, -3.0f); //vertices[2].Set(22.875f, 3.0f); //vertices[3].Set(-22.875f, 3.0f); b2PolygonShape shape; //shape.Set(vertices, 4); shape.SetAsBox(22.875f, 3.0f); b2RayCastInput input; input.p1.Set(10.2725f,1.71372f); input.p2.Set(10.2353f,2.21807f); //input.maxFraction = 0.567623f; input.maxFraction = 0.56762173f; b2Transform xf; xf.SetIdentity(); xf.p.Set(23.0f, 5.0f); b2RayCastOutput output; bool hit; hit = shape.RayCast(&output, input, xf); hit = false; b2Color color(1.0f, 1.0f, 1.0f); b2Vec2 vs[4]; for (int32 i = 0; i < 4; ++i) { vs[i] = b2Mul(xf, shape.m_vertices[i]); } g_debugDraw.DrawPolygon(vs, 4, color); g_debugDraw.DrawSegment(input.p1, input.p2, color); } #endif */ } public static Create(): testbed.Test { return new RayCast(); } } export const testIndex: number = testbed.RegisterTest("Collision", "Ray Cast", RayCast.Create);
the_stack
import { DMMF } from '@prisma/client/runtime' import Chance from 'chance' import _, { Dictionary } from 'lodash' import mls from 'multilines' import { Scalar } from './scalars' import { SeedKit, SeedModels, SeedOptions, SeedModelFieldDefinition, SeedModelFieldRelationConstraint, SeedFunction, PrismaClientType, SeedModelScalarListDefinition, } from './types' import { withDefault, not, filterKeys, mapEntries } from './utils' /** * Creates a function which can be used to seed mock data to database. * * @param dmmf */ export function getSeed< GeneratedPrismaClientType extends PrismaClientType, GeneratedSeedModels extends SeedModels >( dmmf: DMMF.Document, ): SeedFunction<GeneratedPrismaClientType, GeneratedSeedModels> { return async ( options: SeedOptions<GeneratedPrismaClientType, GeneratedSeedModels>, ) => { /** * The wrapped function which handles the execution of * the seeding algorithm. */ const opts = { seed: 42, ...options, } const faker = new Chance(opts.seed) const kit: SeedKit = { faker, } const models: SeedModels = options.models ? options.models(kit) : { '*': { amount: 5, }, } /* Fixture calculations */ const orders: Order[] = getOrdersFromDMMF(dmmf, models) const steps: Step[] = getStepsFromOrders(orders) const tasks: Task[] = getTasksFromSteps(steps) /* Creates mock data and pushes it to Prisma */ const fixtures: Fixture[] = await seedTasks( options.client, faker, models, orders, tasks, ) return groupFixtures(fixtures) } /** * The Core logic * 1. Create orders from models. Orders tell how many instances of a model * should exist in the end. * 2. Create steps from orders. Steps cronologically order the creation of the actual * instances to enable relations. * 3. Create Tasks from Steps. Tasks represent single unordered unit derived from Step. * 4. Convert tasks to virual data instances, apply mock generation functions to obtain actual data, relations are represented as lists * of strings. */ /** * Prisma Faker uses intermediate step between model-faker definition * and database seeding. Fixture is a virtual data unit used to describe * future data and calculate relations. */ type Order = { model: DMMF.Model mapping: DMMF.Mapping amount: number relations: Dictionary<Relation> enums: Dictionary<DMMF.Enum> } type RelationType = '1-to-1' | '1-to-many' | 'many-to-1' | 'many-to-many' type RelationDirection = { optional: boolean; from: string } type Relation = { type: RelationType direction: RelationDirection field: DMMF.Field backRelationField: DMMF.Field // signifies the back relation min: number max: number } /** * Note the `relationTo` field; it defines the direction of a relation. * This helps with the execution process calculation. If the relation is * pointing towards the model, we shouldn't create it since the cyclic complement * will implement it. */ type Step = { order: number // the creation order of a step, starts with 0 amount: number // number of instances created in this step model: DMMF.Model mapping: DMMF.Mapping relations: Dictionary<Relation> enums: Dictionary<DMMF.Enum> } type Task = { order: number // the creation order of a step, starts with 0 model: DMMF.Model mapping: DMMF.Mapping relations: Dictionary<Relation> enums: Dictionary<DMMF.Enum> } /** * ID field packs the id itself and the id field name. * Examples: * - { id: 1 } * - { ArtistId: "uniqueid" } */ type ID = Dictionary<string | number> type Scalar = string | number | boolean | Date type FixtureData = Dictionary< | Scalar | { set: Scalar[] } | { connect: ID } | { connect: ID[] } | { create: FixtureData } > /** * Represents the virtual unit. */ type Fixture = { model: DMMF.Model seed: any relations: Dictionary<Relation> } /* Helper functions */ /** * Converts dmmf to orders. Orders represent the summary of a mock requirements * for particular model. During generation the function detects relation types, * and validates the bulk of the request. * * @param dmmf */ function getOrdersFromDMMF( dmmf: DMMF.Document, seedModels: SeedModels, ): Order[] { type FixtureDefinition = { amount: number factory?: Dictionary< SeedModelFieldDefinition | (() => SeedModelFieldDefinition) > } return dmmf.datamodel.models.map(model => { /* User defined settings */ const fakerModel = getSeedModel(seedModels, model.name) /* Find Photon mappings for seeding step */ const mapping = dmmf.mappings.find(m => m.model === model.name)! /* Generate relations based on provided restrictions. */ const relations: Order['relations'] = model.fields .filter(f => f.kind === 'object') .reduce<Order['relations']>((acc, field) => { const seedModelField: SeedModelFieldRelationConstraint = _.get( fakerModel, ['factory', field.name], {}, ) as object switch (typeof seedModelField) { case 'object': { /* Calculate the relation properties */ return { ...acc, [field.name]: getRelationType( dmmf.datamodel.models, seedModels, field, model, seedModelField, ), } } /* istanbul ignore next */ default: { throw new Error( `Expected a relation constraint got ${typeof seedModelField}`, ) } } }, {}) const enums: Order['enums'] = model.fields .filter(field => field.kind === 'enum') .reduce((acc, field) => { const enume = dmmf.datamodel.enums.find( enume => enume.name === field.type, ) if (enume === undefined) { throw new Error( `Couldn't find enumerator declaration for ${field.type}`, ) } return { ...acc, [field.name]: enume, } }, {}) return { model: model, mapping: mapping, amount: fakerModel.amount, relations: relations, enums: enums, } }) /** * Finds a model definition in seed models or returns the required * fallback seed model definition. */ function getSeedModel( seedModels: SeedModels, model: string, ): FixtureDefinition { const fallback = seedModels['*'] const definitionConstructor = _.get(seedModels, model) return withDefault(fallback, { amount: seedModels['*'].amount, ...definitionConstructor, }) } /** * Finds the prescribed model from the DMMF models. */ function getDMMFModel(models: DMMF.Model[], model: string): DMMF.Model { return models.find(m => m.name === model)! } /** * Derives the relation type, relation direction, and constraints from the field * and definition. * * We have four different relation types: * 1. 1-to-1 * ~ There can be at most one connection or none if optional. * ~ We'll connect the nodes from this model (a child model). * 2. 1-to-many * ~ The node can have 0 to infinite connections (we'll use min/max spec). * ~ We'll connect the nodes from this model (a child model). * 3. many-to-1 * ~ A particular instance can either connect or not connect if optional. * ~ We'll fill the pool with ids of this model (a parent model) or create nodes * if the relation is required in both directions. * 4. many-to-many * ~ A particular instance can have 0 to infinite connections (we'll use min/max spec). * ~ We'll use `relationTo` to determine whether this is a parent or child model and * create nodes accordingly. * * We presume that the field is a relation. */ function getRelationType( dmmfModels: DMMF.Model[], seedModels: SeedModels, field: DMMF.Field, fieldModel: DMMF.Model, definition: SeedModelFieldRelationConstraint, ): Relation { /** * model A { * field: Relation * } */ /* Field definitions */ const fieldSeedModel = getSeedModel(seedModels, fieldModel.name) /** * Relation definitions * * NOTE: relaitonField is a back reference to the examined model. */ const relationModel = getDMMFModel(dmmfModels, field.type) const backRelationField = relationModel.fields.find( f => f.relationName === field.relationName, )! const relationSeedModel = getSeedModel(seedModels, field.type) /* Relation type definitions */ if (field.isList && backRelationField.isList) { /** * many-to-many (A) * * model A { * bs: B[] * } * model B { * as: A[] * } */ const min = withDefault(0, definition.min) const max = withDefault(min, definition.max) /* Validation */ if (min > max) { /* istanbul ignore next */ /* Inconsistent mock definition. */ throw new Error( /* prettier-ignore */ mls` | ${fieldModel.name}.${field.name}: number of minimum instances is higher than maximum. `, ) } else if (max > relationSeedModel.amount) { /* istanbul ignore next */ /* Missing relation instances */ const missingInstances = max - relationSeedModel.amount throw new Error( /* prettier-ignore */ mls` | ${fieldModel.name}.${field.name} requests more(${max}) instances of | ${relationModel.name}(${relationSeedModel.amount}) than available. | Please add more(${missingInstances}) ${relationModel.name} instances. `, ) } else { /* Valid declaration */ return { type: 'many-to-many', min: min, max: max, direction: getRelationDirection(field, backRelationField), field, backRelationField: backRelationField, } } } else if (!field.isList && backRelationField.isList) { /** * many-to-1 (A) * * model A { * b: B * } * model B { * as: [A] * } */ if ( field.isRequired && relationSeedModel.amount < fieldSeedModel.amount ) { const missingInstances = fieldSeedModel.amount - relationSeedModel.amount throw new Error( /* prettier-ignore */ mls` | ${fieldModel.name}.${field.name} requests more (${fieldSeedModel.amount}) instances of ${relationModel.name}(${relationSeedModel.amount}) than available. | Please add ${missingInstances} more ${relationModel.name} instances. `, ) } const min = field.isRequired ? 1 : withDefault(0, definition.min) return { type: 'many-to-1', min: min, max: 1, direction: getRelationDirection(field, backRelationField), field, backRelationField: backRelationField, } } else if (field.isList && !backRelationField.isList) { /** * 1-to-many (A) * * model A { * bs: b[] * } * * model B { * a: A * } */ /** * TODO: This is not completely accurate, because there * could be more of this type than of backRelation, and this * setup doesn't allow for that. * * TODO: Intellisense: if back relation field required min should be at least 1. */ // const min = backRelationField.isRequired // ? 1 // : withDefault(0, definition.min) const min = withDefault(0, definition.min) const max = withDefault(fieldSeedModel.amount, definition.max) /* Validation */ if (min > max) { /* istanbul ignore next */ /* Inconsistent mock definition. */ throw new Error( /* prettier-ignore */ mls` | ${fieldModel.name}.${field.name}: number of minimum instances is higher than maximum. `, ) } // else if (max > relationSeedModel.amount) { // /* istanbul ignore next */ /* Missing relation instances */ // const missingInstances = max - relationSeedModel.amount // throw new Error( // /* prettier-ignore */ // mls` // | ${fieldModel.name}.${field.name} requests more (${max}) instances of ${relationModel.name}(${relationSeedModel.amount}) than available. // | Please add more (${missingInstances}) ${relationModel.name} instances. // `, // ) // } if (min * fieldSeedModel.amount > relationSeedModel.amount) { const missingInstances = min * fieldSeedModel.amount - relationSeedModel.amount throw new Error( /* prettier-ignore */ mls` | ${fieldModel.name}.${field.name} requests more (${min * fieldSeedModel.amount}) instances of ${relationModel.name}(${relationSeedModel.amount}) than available. | Please add ${missingInstances} more ${relationModel.name} instances. `, ) } /* Valid declaration */ return { type: '1-to-many', min: min, max: max, direction: getRelationDirection(field, backRelationField), field, backRelationField: backRelationField, } } else { /** * 1-to-1 (A) * * model A { * b: B * } * model B { * a: A * } */ /* Validation */ if ( field.isRequired && backRelationField.isRequired && fieldSeedModel.amount !== relationSeedModel.amount ) { /* Required 1-to-1 relation unit amount mismatch. */ throw new Error( /* prettier-ignore */ mls` | A 1-to-1 required relation ${fieldModel.name}.${field.name}-${relationModel.name} has different number of units assigned. | Please make sure that number of ${fieldModel.name} and ${relationModel.name} match. `, ) } else if ( !field.isRequired && backRelationField.isRequired && fieldSeedModel.amount < relationSeedModel.amount ) { /* An optional 1-to-1 relation inadequate unit amount. */ throw new Error( /* prettier-ignore */ mls` | A 1-to-1 relation ${relationModel.name} needs at least ${relationSeedModel.amount} ${fieldModel.name} units, but only ${fieldSeedModel.amount} were provided. | Please make sure there's an adequate amount of resources available. `, ) } else { /* Sufficient amounts. */ return { type: '1-to-1', min: field.isRequired ? 1 : withDefault(0, definition.min), max: 1, direction: getRelationDirection(field, backRelationField), field, backRelationField: backRelationField, } } } } /** * Determines relation direction based on the type of fields * connecting the two types together. * * `relation direction` tells which of the two models should be created first. */ function getRelationDirection( field: DMMF.Field, backRelationField: DMMF.Field, ): RelationDirection { /* Model of the observed type. */ const fieldModel = backRelationField.type const relationModel = field.type if (field.isRequired && backRelationField.isRequired) { /** * model A { * b: B * } * model B { * a: A * } * * -> Create B while creating A, the order doesn't matter. */ return { optional: true, from: _.head([fieldModel, relationModel].sort())!, } } else if (field.isRequired && !backRelationField.isRequired) { /** * model A { * b: B * } * model B { * a: A? * } * * We should create B first. */ return { optional: false, from: relationModel, } } else if (field.isRequired && backRelationField.isList) { /** * model A { * b: B * } * model B { * a: A[] * } * * -> We should create B and connect As to it. */ return { optional: false, from: relationModel, } } else if (field.isList && backRelationField.isRequired) { /** * model A { * b: B[] * } * model B { * a: A * } * * -> We should create A and connect Bs to it later. */ return { optional: false, from: fieldModel, } } else if (field.isList && !backRelationField.isRequired) { /** * model A { * b: B[] * } * model B { * a: A? * } * * -> We should create B first. */ return { optional: true, from: _.head([fieldModel, relationModel].sort())!, } } else if (field.isList && backRelationField.isList) { /** * model A { * b: B[] * } * model B { * a: A[] * } * * -> The order doesn't matter, just be consistent. */ return { optional: true, from: _.head([fieldModel, relationModel].sort())!, } } else if (!field.isRequired && backRelationField.isRequired) { /** * model A { * b: B? * } * model B { * a: A * } * * We should create A first, and connect B with A once we create B. */ return { optional: false, from: fieldModel, } } else if (!field.isRequired && !backRelationField.isRequired) { /** * model A { * b: B? * } * model B { * a: A? * } * * -> The order doesn't matter just be consistent. */ return { optional: true, from: _.head([fieldModel, relationModel].sort())!, } } else if (!field.isRequired && backRelationField.isList) { /** * model A { * b: B? * } * model B { * a: A[] * } * * -> We should create A(s) first and then connect B with them. */ return { optional: true, from: _.head([fieldModel, relationModel].sort())!, } } else { throw new Error(`Uncovered relation type.`) } } } /** * Coverts orders to steps. Steps represent an ordered entity that specifies the creation * of a virtual data. * * Creates a pool of available instances and validates relation constraints. Using * `isOrderWellDefined` and `getStepsFromOrder` functions, you should be able to implement * the topological sort algorithm. * * This function assumes that the graph is acylic. * * @param orders */ function getStepsFromOrders(orders: Order[]): Step[] { type Pool = Dictionary<DMMF.Model> let graph: Order[] = orders.filter(not(isLeafOrder)) let pool: Pool = {} // edges let sortedSteps: Step[] = [] // L let leafs: Order[] = orders.filter(isLeafOrder) // S while (leafs.length !== 0) { const leaf = leafs.shift()! // n const { pool: poolWithLeaf, step: leafStep } = insertOrderIntoPool( sortedSteps.length, pool, leaf, ) pool = poolWithLeaf sortedSteps.push(leafStep) for (const order of graph) { if (isOrderWellDefinedInPool(pool, order)) { /* Remove the edge from the graph. */ graph = graph.filter(({ model }) => model.name !== order.model.name) /* Update the leafs list. */ leafs.push(order) } } } if (graph.length !== 0) { throw new Error(`${graph.map(o => o.model.name).join(', ')} have cycles!`) } return sortedSteps /* Helper functions */ /** * Determines whether we can already process the order based on the pool * capacity. * * This function in combination with `getStepsFromOrder` should give you * all you need to implement meaningful topological sort on steps. */ function isOrderWellDefinedInPool(pool: Pool, order: Order): boolean { return Object.values(order.relations).every( relation => pool.hasOwnProperty(relation.field.type) || relation.direction.from === order.model.name || relation.direction.optional, ) } /** * Tells whether the order has outgoing relations. * * @param order */ function isLeafOrder(order: Order): boolean { return Object.values(order.relations).every( relation => relation.direction.from === order.model.name || relation.direction.optional, ) } /** * Converts a well defined order to a step and adds it to the pool. * * This function in combination with `isOrderWellDefinedInPool` should give * you everything you need to implement meaningful topological sort on steps. */ function insertOrderIntoPool( ordinal: number, pool: Pool, order: Order, ): { step: Step pool: Pool } { /** * Fix optional relations' direction. */ const fixedRelations = mapEntries(order.relations, relation => { if (!relation.direction.optional) return relation return { ...relation, direction: { optional: false, /** * If pool already includes the model of the relation, * make the foreign relation first and create this model * afterwards. */ from: pool.hasOwnProperty(relation.field.type) ? /* back relation model */ relation.field.type : /* this model */ relation.backRelationField.type, }, } }) /** * A step unit derived from the order. */ const step: Step = { order: ordinal, amount: order.amount, model: order.model, mapping: order.mapping, relations: fixedRelations, enums: order.enums, } /** * Assumes that there cannot exist two models with the same name. */ const newPool: Pool = { ...pool, [order.model.name]: order.model, } return { step, pool: newPool, } } } /** * Converts steps to tasks. * * Steps to Tasks introduce no non-trivial logic. It's a simple conversion mechanism * to make system more robuts and make the mocking part more granular. * * @param steps */ function getTasksFromSteps(steps: Step[]): Task[] { const tasks = steps.reduce<Task[]>((acc, step) => { const intermediateTasks: Task[] = Array<Task>(step.amount).fill({ order: step.order, model: step.model, mapping: step.mapping, relations: step.relations, enums: step.enums, }) return acc.concat(...intermediateTasks) }, []) const tasksWithCorrectOrder = _.sortBy(tasks, t => t.order).map( (task, i) => ({ ...task, order: i, }), ) return tasksWithCorrectOrder } /** * Converts tasks to fixtures by creating a pool of available instances * and assigning relations to particular types. * * This function assumes that: * 1. Tasks (Steps) are sorted in such an order that pool always possesses * all required instances, * 2. There are enough resources in the pool at all times, * 3. The provided schema is valid. * * @param steps */ async function seedTasks<Client extends PrismaClientType>( client: Client, faker: Chance.Chance, seedModels: SeedModels, orders: Order[], tasks: Task[], ): Promise<Fixture[]> { /** * Pool describes the resources made available by a parent type to its children. */ type Pool = Dictionary<{ [child: string]: ID[] }> const initialPool: Pool = {} const { fixtures } = await iterate( _.sortBy(tasks, t => t.order), initialPool, ) return fixtures /** * Iteration represents a single seed exeuction cycle. */ type Iteration = { fixtures: Fixture[] pool: Pool } /** * Recursively seeds tasks to database. */ async function iterate( [currentTask, ...remainingTasks]: Task[], availablePool: Pool, iteration: number = 0, ): Promise<Iteration> { /* Edge case */ if (currentTask === undefined) { return { fixtures: [], pool: availablePool, } } /* Recursive step */ /* Fixture calculation */ const { data, pool: newPool, tasks: newTasks, include } = getMockForTask( availablePool, remainingTasks, currentTask, ) const methodName = _.lowerFirst(currentTask.mapping.model) /** * Make sure that client packs everyting. */ if (!client[methodName]) { throw new Error( `Client is missing method for ${currentTask.model.name} (methodName = ${methodName}, mappingModel = ${currentTask.mapping.model})`, ) } /** * Load the data to database. */ const seed = await client[methodName].create({ data, // TODO: include statement should possibly be empty ...(Object.keys(include).length ? { include, } : {}), }) const fixture: Fixture = { model: currentTask.model, seed: seed, relations: currentTask.relations, } /** * Save the id to the pool by figuring out which fields are parents and which are children. */ const poolWithFixture = insertFixtureIntoPool(fixture, newPool, orders) /* Recurse */ const recursed = await iterate(newTasks, poolWithFixture, iteration + 1) return { fixtures: [fixture, ...recursed.fixtures], pool: recursed.pool, } } type Mock = { pool: Pool tasks: Task[] data: FixtureData include: { [field: string]: true | { include: Mock['include'] } } } /** * Generates mock data from the provided model. Scalars return a mock scalar or * list of mock scalars, relations return an ID or lists of IDs. * * Generates mock data for scalars and relations, but skips id fields with default setting. */ function getMockForTask( availablePool: Pool, otherTasks: Task[], task: Task, ): Mock { const initialMock: Mock = { pool: availablePool, tasks: otherTasks, data: {}, include: {}, } return task.model.fields .filter( field => /* ID fields with default shouldn't have a generated id. */ !(field.isId && field.default !== undefined), ) .reduce<Mock>(getMockDataForField, initialMock) function getMockDataForField( { pool, tasks, data, include }: Mock, field: DMMF.Field, ): Mock { const fieldModel = task.model /* Custom field mocks */ if (seedModels[task.model.name]?.factory) { const mock = seedModels[task.model.name]!.factory![field.name] switch (typeof mock) { case 'function': { /* Custom function */ if (field.isList) { const values = (mock as () => SeedModelFieldDefinition[]).call( faker, ) return { pool, tasks, data: { ...data, [field.name]: { set: values }, }, include, } } else { const value = (mock as () => SeedModelFieldDefinition).call( faker, ) return { pool, tasks, data: { ...data, [field.name]: value, }, include, } } } case 'object': { /* Relation or scalar list */ if (field.isList) { /* Scalar list */ const values = mock as SeedModelFieldDefinition[] return { pool, tasks, data: { ...data, [field.name]: { set: values }, }, include, } } else { /* Relation */ break } } case 'bigint': case 'boolean': case 'number': case 'string': { /* A constant value. */ const value = mock return { pool, tasks, data: { ...data, [field.name]: value, }, include, } } case 'symbol': case 'undefined': { /* Skipped definitions */ break } default: { throw new Error(`Unsupported type of mock "${typeof mock}".`) } } } /* ID field */ if (field.isId || fieldModel.idFields.includes(field.name)) { switch (field.type) { case Scalar.string: { /* GUID id for strings */ return { pool, tasks, data: { ...data, [field.name]: faker.guid(), }, include, } } case Scalar.int: { /* Autoincrement based on task order. */ return { pool, tasks, data: { ...data, [field.name]: task.order, }, include, } } default: { throw new Error(`Unsupported ID type "${field.type}"`) } } } /* Scalar and relation field mocks */ switch (field.kind) { case 'scalar': { /** * List scalar mocks. * * We provide good default mocks for functions. Anything more complex * or flexible can be achieved using the exposed Chance.js library. */ if (field.isList) { switch (field.type) { /** * Scalars */ case Scalar.string: { const strings = faker.n(faker.string, 3) return { pool, tasks, data: { ...data, [field.name]: { set: strings, }, }, include, } } case Scalar.int: { const numbers = faker.n(faker.integer, 3, { min: -2000, max: 2000, }) return { pool, tasks, data: { ...data, [field.name]: { set: numbers }, }, include, } } case Scalar.float: { const floats = faker.n(faker.floating, 3, { min: -1000, max: 1000, fixed: 2, }) return { pool, tasks, data: { ...data, [field.name]: { set: floats }, }, include, } } case Scalar.date: { const dates = faker.n(faker.date, 3) return { pool, tasks, data: { ...data, [field.name]: { set: dates }, }, include, } } case Scalar.bool: { const booleans = faker.n(faker.bool, 3) return { pool, tasks, data: { ...data, [field.name]: { set: booleans }, }, include, } } /* Unsupported scalar */ default: { throw new Error( `Unsupported scalar field ${task.model.name}${field.name} of type ${field.type}`, ) } } } /** * Scalar mocks. */ switch (field.type) { /** * Scalars */ case Scalar.string: { const string = faker.word() return { pool, tasks, data: { ...data, [field.name]: string, }, include, } } case Scalar.int: { const number = faker.integer({ min: -2000, max: 2000, }) return { pool, tasks, data: { ...data, [field.name]: number, }, include, } } case Scalar.float: { const float = faker.floating({ min: -1000, max: 1000, fixed: 2, }) return { pool, tasks, data: { ...data, [field.name]: float, }, include, } } case Scalar.date: { const date = faker.date() return { pool, tasks, data: { ...data, [field.name]: date, }, include, } } case Scalar.bool: { const boolean = faker.bool() return { pool, tasks, data: { ...data, [field.name]: boolean, }, include, } } /* Unsupported scalar */ default: { throw new Error( `Unsupported scalar field ${task.model.name}${field.name} of type ${field.type}`, ) } } } /** * Relations * * NOTE: this function assumes that we've sorted orders in * such an order that this is the most crucial step that * needs to be finished. */ case 'object': { /* Resources calculation */ const relation = task.relations[field.name] switch (relation.type) { case '1-to-1': { if (relation.field.isRequired) { /** * model A { * b: B * } * model B { * a: A * } * * We are creating model A. * * NOTE: field a in model B could also be optional. * This function assumes that the order is such that * this step should also create an instance of model B * regardless of the meaning. */ /* Creates the instances while creating itself. */ /** * The other part of this relation will be taken out by the * creation step below using getMockOfModel. */ const { tasks: newTasks, pool: newPool, data: instance, include: mockInclude, } = getMockOfModel(tasks, pool, relation.field) return { pool: newPool, tasks: newTasks, data: { ...data, [field.name]: { create: instance, }, }, include: { ...include, [field.name]: Object.keys(mockInclude).length !== 0 ? { include: mockInclude } : true, }, } } else if ( /* If this model is second made */ relation.direction.from !== fieldModel.name && !relation.backRelationField.isRequired ) { /** * model A { * b: B * } * model B { * a?: A * } * * We are creating model B. */ const units = faker.integer({ min: relation.min, max: relation.max, }) /* Create an instance and connect it to the relation. */ const [newPool, ids] = getIDInstancesFromPool( pool, fieldModel.name, field.type, units, ) /** * This makes sure that relations are properly connected. */ switch (ids.length) { case 0: { return { pool: newPool, tasks, data, include, } } case 1: { const [id] = ids return { pool: newPool, tasks, data: { ...data, [field.name]: { connect: id, }, }, include: { ...include, [field.name]: true, }, } } /* istanbul ignore next */ default: { throw new Error(`Something truly unexpected happened.`) } } } else { /** * It is possible that this is the other side of the relation * that has already been created in another process. * * We should't do anything in that case. */ return { pool, tasks, data, include, } } } case '1-to-many': { if ( /* This model is created first. */ relation.direction.from === fieldModel.name ) { /** * model A { * bs: B[] * } * model B { * a: A * } * * We are creating model A. */ /* Skip creating the relation as we'll connect to it when creating model B. */ return { pool, tasks, data, include, } } else { /* This is the second model in relation. */ /** * model A { * bs: B[] * } * model B { * a: A * } * * We are creating model B, As already exist. */ const units = faker.integer({ min: relation.min, max: relation.max, }) /* Create this instance and connect to others. */ const [newPool, ids] = getIDInstancesFromPool( pool, fieldModel.name, field.type, units, ) return { pool: newPool, tasks, data: { ...data, [field.name]: { connect: ids, }, }, include: { ...include, [field.name]: true, }, } } } case 'many-to-1': { if ( /* This is the first model to be created in the relation. */ relation.direction.from === fieldModel.name && relation.field.isRequired ) { /** * model A { * b: B * } * model B { * a: A[] * } * * We are creating A. */ const { tasks: newTasks, pool: newPool, data: instance, include: mockInclude, } = getMockOfModel(tasks, pool, relation.field) return { pool: newPool, tasks: newTasks, data: { ...data, [field.name]: { create: instance, }, }, include: { ...include, [field.name]: Object.keys(mockInclude).length !== 0 ? { include: mockInclude } : true, }, } } /* This model is created second. */ else if ( relation.direction.from !== fieldModel.name ) { /** * model A { * b: B * } * model B { * a: A[] * } * * We are creating A, B already exists. */ const units = faker.integer({ min: relation.min, max: relation.max, }) /* Create this instance and connects it. */ const [newPool, [id]] = getIDInstancesFromPool( pool, fieldModel.name, field.type, units, ) if (!id && relation.field.isRequired) { throw new Error( `Missing data for required relation: ${relation.field.relationName}`, ) } if (!id && !relation.field.isRequired) { return { pool: newPool, tasks, data, include, } } return { pool: newPool, tasks, data: { ...data, [field.name]: { connect: id, }, }, include: { ...include, [field.name]: true, }, } } else { /* Some other task will create this relation. */ return { pool, tasks, data, include, } } } case 'many-to-many': { if (relation.direction.from === fieldModel.name) { /** * model A { * bs: B[] * } * model B { * as: A[] * } */ /* Insert IDs of this instance to the pool. */ return { pool, tasks, data, include, } } else { /** * model A { * bs: B[] * } * model B { * as: A[] * } */ const units = faker.integer({ min: relation.min, max: relation.max, }) /* Create instances and connect to relation instances. */ const [newPool, ids] = getIDInstancesFromPool( pool, fieldModel.name, field.type, units, ) return { pool: newPool, tasks, data: { ...data, [field.name]: { connect: ids, }, }, include: { ...include, [field.name]: true, }, } } } /* end of relation kind switches */ } } /** * Enums */ case 'enum': { const { values } = task.enums[field.name]! const enume = faker.pickone(values) return { pool, tasks, data: { ...data, [field.name]: enume, }, include, } } /** * Default field type fallback. */ default: { /* istanbul ignore next */ throw new Error( /* prettier-ignore */ mls` | Unsupported field type "${field.type}". | Please use a custom mock function or change your model definition. `, ) } } } } /** * Recursively retrives n unique ids and removes them from the pool. */ function getIDInstancesFromPool( pool: Pool, parent: string, child: string, n: number, /* Internals */ // _ids: ID[] = [], ): [Pool, ID[]] { /* All available ids for this field (includes duplicates). */ const allIds: ID[] = _.get(pool, [parent, child], []) /* Used ids */ let ids: ID[] = [] let remainingIds: ID[] = [] for (let index = 0; index < allIds.length; index++) { const id = allIds[index] /* Makes sure that ids are unique */ if (ids.some(_id => isId(_id, id))) { remainingIds.push(id) continue } /* Fill the list. */ if (ids.length < n) { ids.push(id) } else { remainingIds.push(id) } } if (ids.length < n) { throw new Error( `Requesting more ${parent}.${child} ids than available.`, ) } /* Clear ids from the pool. */ const poolWithoutIds = _.set(pool, [parent, child], remainingIds) return [poolWithoutIds, ids] } /** * Tells whether two ids are the same. * * @param id * @param comparable */ function isId(id: ID, comparable: ID): boolean { return [...Object.keys(id), ...Object.keys(comparable)].every( key => id[key] === comparable[key], ) } /** * Inserts n-replications of ID into the pool and returns the new pool. */ function insertIDInstancesIntoPool( pool: Pool, parent: string, child: string, id: ID, n: number, ): Pool { const ids = _.get(pool, [parent, child], []) return _.set(pool, [parent, child], [...ids, ...Array(n).fill(id)]) } /** * Inserts an id of a task into all parent fields it covers. * * @param id * @param task * @param pool */ function insertFixtureIntoPool( fixture: Fixture, initialPool: Pool, orders: Order[], ): Pool { /** * Calculates the id of this fixture. */ const id = fixture.model.fields .filter( field => fixture.model.idFields.includes(field.name) || field.isId, ) .reduce<ID>((acc, field) => { if (!fixture.seed.hasOwnProperty(field.name)) { throw new Error( `Return data of ${fixture.model.name} is missing id field data for ${field.name}.`, ) } return { ...acc, [field.name]: fixture.seed[field.name], } }, {}) return fixture.model.fields .filter(field => field.kind === 'object') .reduce<Pool>(insertFieldIntoPool, initialPool) /** * This complements getMockDataForField's relations part. * * For every relation that returns unchanged mock, this should * insert id into the pool. * * For every nested create relation it should extract child fixture. * * @param pool * @param field */ function insertFieldIntoPool(pool: Pool, field: DMMF.Field): Pool { const fieldModel = fixture.model switch (field.kind) { /** * Scalars, Enums */ case 'scalar': case 'enum': { return pool } /** * Relations */ case 'object': { /* Resources calculation */ const relation = fixture.relations[field.name] switch (relation.type) { case '1-to-1': { if (relation.field.isRequired) { /** * Extracts a subfixture from compound create relation. */ const subfixtureOrder: Order = getFieldOrder(field) const subfixture: Fixture = { seed: fixture.seed[field.name]!, model: { ...subfixtureOrder.model, fields: subfixtureOrder.model.fields.filter( ({ relationName }) => relationName !== field.relationName, ), }, relations: filterKeys( subfixtureOrder.relations, (key, relation) => relation.field.relationName !== field.relationName, ), } return insertFixtureIntoPool(subfixture, pool, orders) } else if ( relation.direction.from === fieldModel.name && !relation.field.isRequired ) { /** * model A { * b: B * } * model B { * a: A * } * * 1-to-1 relation should take at most one id from the resource pool * and submit no new ids. Because we already manage constraints during * order creation step, we can ignore it now. */ /* Insert the ID of an instance into the pool. */ const newPool = insertIDInstancesIntoPool( pool, field.type, fieldModel.name, id, 1, ) return newPool } else { /* Relation doesn't create any child properties. */ return pool } } case '1-to-many': { /** * model A { * bs: B[] * } * model B { * a: A * } * * 1-to-many creates the model instance and makes its ID available for later connections. */ if (relation.direction.from === fieldModel.name) { /* Create the relation while creating this model instance. */ // const units = faker.integer({ // min: relation.min, // max: relation.max, // }) const units = Math.max(1, relation.max) const newPool = insertIDInstancesIntoPool( pool, field.type, fieldModel.name, id, units, ) return newPool } else { return pool } } case 'many-to-1': { if ( /* This is the first model to be created in the relation. */ relation.direction.from === fieldModel.name && relation.field.isRequired ) { /** * Extracts a subfixture from compound create relation. */ const subfixtureOrder: Order = getFieldOrder(field) const subfixture: Fixture = { seed: fixture.seed[field.name]!, model: { ...subfixtureOrder.model, fields: subfixtureOrder.model.fields.filter( ({ relationName }) => relationName !== field.relationName, ), }, relations: filterKeys( subfixtureOrder.relations, (key, relation) => relation.field.relationName !== field.relationName, ), } return insertFixtureIntoPool(subfixture, pool, orders) } else if ( relation.direction.from === fieldModel.name && !relation.field.isRequired ) { /** * model A { * b: B * } * model B { * a: A[] * } * * Many-to-1 relations either create an instance and make it available for later use, * or connect to existing instance. */ /* Insert IDs of model instance into the pool. */ // const units = faker.integer({ // min: relation.min, // max: relation.max, // }) const units = Math.max(1, relation.max) const newPool = insertIDInstancesIntoPool( pool, field.type, fieldModel.name, id, units, ) return newPool } else { return pool } } case 'many-to-many': { /** * model A { * bs: B[] * } * model B { * as: A[] * } * * Many-to-many relationships simply have to follow consistency. They can either * create ID instances in the pool or connect to them. */ if (relation.direction.from === fieldModel.name) { /* Insert IDs of this instance to the pool. */ // const units = faker.integer({ // min: relation.min, // max: relation.max, // }) const units = Math.max(1, relation.max) const newPool = insertIDInstancesIntoPool( pool, field.type, fieldModel.name, id, units, ) return newPool } else { return pool } } /* end of relation kind switches */ } } } } /** * Finds the order of type of the field. * @param field */ function getFieldOrder(field: DMMF.Field): Order { return orders.find(order => order.model.name === field.type)! } } /** * Creates instances of a requested relation and drains the remaining tasks. */ function getMockOfModel( tasks: Task[], availablePool: Pool, field: DMMF.Field, ): Mock { // TODO: this doesn't put an id into fixture in the end. /* Find the requested tasks. */ const mockTask = tasks.find(task => task.model.name === field.type) /* Validation check, though it should never trigger */ /* istanbul ignore next */ if (mockTask === undefined) { throw new Error('Something very unexpected occured.') } /* Delete backrelation */ const mockTaskWithoutBackrelation: Task = { ...mockTask, model: { ...mockTask.model, fields: mockTask.model.fields.filter( ({ relationName }) => relationName !== field.relationName, ), }, relations: filterKeys( mockTask.relations, (key, relation) => relation.field.relationName !== field.relationName, ), } const remainingTasks = tasks.filter(task => task.order !== mockTask.order) return getMockForTask( availablePool, remainingTasks, mockTaskWithoutBackrelation, ) } } /** * Cleverly groups the data so it's useful for the end user. * * @param fixtures */ function groupFixtures(fixtures: Fixture[]): Dictionary<object[]> { return fixtures.reduce<Dictionary<object[]>>((acc, fixture) => { const model = fixture.model.name if (acc.hasOwnProperty(model)) { return { ...acc, [model]: acc[model].concat(fixture.seed), } } else { return { ...acc, [model]: [fixture.seed], } } }, {}) } }
the_stack
import { Promise } from 'bluebird'; // ----------------------------------------------------------------------------- // Typedefs // ----------------------------------------------------------------------------- /** * Chunk uploaded event * @event Chunk#uploaded * @param {UploadPart} data The data of the uploaded chunk * @private */ /** * Chunk error event * @event Chunk#error * @param {Error} err The error that occurred * @private */ /** * Event for when the upload is successfully aborted * @event ChunkedUploader#aborted */ /** * Event for when the abort fails because the upload session is not destroyed. * In general, the abort can be retried, and no new chunks will be uploaded. * @event ChunkedUploader#abortFailed * @param {Error} err The error that occurred */ /** * Event for when a chunk fails to upload. Note that the chunk will automatically * retry until it is successfully uploaded. * @event ChunkedUploader#chunkError * @param {Error} err The error that occurred during chunk upload */ /** * Event for when a chunk is successfully uploaded * @event ChunkedUploader#chunkUploaded * @param {UploadPart} data The data for the uploaded chunk */ /** * Event for when the entire upload is complete * @event ChunkedUploader#uploadComplete * @param {Object} file The file object for the newly-uploaded file */ /** * Event for when an upload fails * @event ChunkedUploader#error * @param {Error} err The error that occurred */ type ChunkedUploaderOptions = { retryInterval?: number; parallelism?: number; fileAttributes?: Record<string, any>; }; type UploadSessionInfo = { id: string; part_size: number; }; // ----------------------------------------------------------------------------- // Requirements // ----------------------------------------------------------------------------- import { EventEmitter } from 'events'; import { Readable as ReadableStream } from 'stream'; import crypto from 'crypto'; import BoxClient from './box-client'; // ----------------------------------------------------------------------------- // Private // ----------------------------------------------------------------------------- const DEFAULT_OPTIONS = Object.freeze({ parallelism: 4, retryInterval: 1000, }); /** * Chunk of a file to be uploaded, which handles trying to upload itself until * it succeeds. * @private */ class Chunk extends EventEmitter { client: BoxClient; sessionID: string; chunk: Buffer | string | null; length: number; offset: number; totalSize: number; options: ChunkedUploaderOptions; data: any /* FIXME */; retry: number | NodeJS.Timeout | null; canceled: boolean; /** * Create a Chunk, representing a part of a file being uploaded * @param {BoxClient} client The Box SDK client * @param {string} sessionID The ID of the upload session the chunk belongs to * @param {Buffer|string} chunk The chunk that was uploaded * @param {int} offset The byte offset within the file where this chunk begins * @param {int} totalSize The total size of the file this chunk belongs to * @param {Object} options The options from the ChunkedUploader * @param {int} options.retryInterval The number of ms to wait before retrying a chunk upload */ constructor( client: BoxClient, sessionID: string, chunk: Buffer | string, offset: number, totalSize: number, options: ChunkedUploaderOptions ) { super(); this.client = client; this.sessionID = sessionID; this.chunk = chunk; this.length = chunk.length; this.offset = offset; this.totalSize = totalSize; this.options = options; this.data = null; this.retry = null; this.canceled = false; } /** * Get the final object representation of this chunk for the API * @returns {UploadPart} The chunk object */ getData() { return this.data.part; } /** * Upload a chunk to the API * @returns {void} * @emits Chunk#uploaded * @emits Chunk#error */ upload() { this.client.files.uploadPart( this.sessionID, this.chunk, this.offset, this.totalSize, (err: any /* FIXME */, data: any /* FIXME */) => { if (this.canceled) { this.chunk = null; return; } if (err) { // handle the error or retry if (err.statusCode) { // an API error, probably not retryable! this.emit('error', err); } else { // maybe a network error, retry this.retry = setTimeout( () => this.upload(), this.options.retryInterval ); } return; } // Record the chunk data for commit, and try to free up the chunk buffer this.data = data; this.chunk = null; this.emit('uploaded', data); } ); } /** * Cancel trying to upload a chunk, preventing it from retrying and clearing * the associated buffer * @returns {void} */ cancel() { clearTimeout(this.retry as any); // number or NodeJS.Timeout this.chunk = null; this.canceled = true; } } // ----------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------- /** Manager for uploading a file in chunks */ class ChunkedUploader extends EventEmitter { _client: BoxClient; _sessionID: string; _partSize: number; _uploadSessionInfo: UploadSessionInfo; _stream!: ReadableStream | null; _streamBuffer!: Array<any>; _file!: Buffer | string | null; _size: number; _options: Required<ChunkedUploaderOptions>; _isStarted: boolean; _numChunksInFlight: number; _chunks: Array<any>; _position: number; _fileHash: crypto.Hash; _promise?: Promise<any>; _resolve?: Function; _reject?: Function; /** * Create an upload manager * @param {BoxClient} client The client to use to upload the file * @param {Object} uploadSessionInfo The upload session info to use for chunked upload * @param {ReadableStream|Buffer|string} file The file to upload * @param {int} size The size of the file to be uploaded * @param {Object} [options] Optional parameters * @param {int} [options.retryInterval=1000] The number of ms to wait before retrying operations * @param {int} [options.parallelism=4] The number of concurrent chunks to upload * @param {Object} [options.fileAttributes] Attributes to set on the file during commit */ constructor( client: BoxClient, uploadSessionInfo: UploadSessionInfo, file: ReadableStream | Buffer | string, size: number, options?: ChunkedUploaderOptions ) { super(); this._client = client; this._sessionID = uploadSessionInfo.id; this._partSize = uploadSessionInfo.part_size; this._uploadSessionInfo = uploadSessionInfo; if (file instanceof ReadableStream) { // Pause the stream so we can read specific chunks from it this._stream = file.pause(); this._streamBuffer = []; } else if (file instanceof Buffer || typeof file === 'string') { this._file = file; } else { throw new TypeError('file must be a Stream, Buffer, or string!'); } this._size = size; this._options = Object.assign( {}, DEFAULT_OPTIONS, options ) as Required<ChunkedUploaderOptions>; this._isStarted = false; this._numChunksInFlight = 0; this._chunks = []; this._position = 0; this._fileHash = crypto.createHash('sha1'); } /** * Start an upload * @returns {Promise<Object>} A promise resolving to the uploaded file */ start() { if (this._isStarted) { return this._promise; } // Create the initial chunks for (let i = 0; i < this._options.parallelism; i++) { this._getNextChunk((chunk: any /* FIXME */) => chunk ? this._uploadChunk(chunk) : this._commit() ); } this._isStarted = true; /* eslint-disable promise/avoid-new */ this._promise = new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; }); /* eslint-enable promise/avoid-new */ return this._promise; } /** * Abort a running upload, which cancels all currently uploading chunks, * attempts to free up held memory, and aborts the upload session. This * cannot be undone or resumed. * @returns {Promise} A promise resolving when the upload is aborted * @emits ChunkedUploader#aborted * @emits ChunkedUploader#abortFailed */ abort() { this._chunks.forEach((chunk) => chunk.removeAllListeners().cancel()); this._chunks = []; this._file = null; this._stream = null; return ( this._client.files .abortUploadSession(this._sessionID) /* eslint-disable promise/always-return */ .then(() => { this.emit('aborted'); }) /* eslint-enable promise/always-return */ .catch((err: any /* FIXME */) => { this.emit('abortFailed', err); throw err; }) ); } /** * Get the next chunk of the file to be uploaded * @param {Function} callback Called with the next chunk of the file to be uploaded * @returns {void} * @private */ _getNextChunk(callback: Function) { if (this._position >= this._size) { callback(null); return; } let buf; if (this._file) { // Buffer/string case, just get the slice we need buf = this._file.slice(this._position, this._position + this._partSize); } else if (this._streamBuffer.length > 0) { buf = this._streamBuffer.shift(); } else { // Stream case, need to read buf = (this._stream as ReadableStream).read(this._partSize); if (!buf) { // stream needs to read more, retry later setImmediate(() => this._getNextChunk(callback)); return; } else if (buf.length > this._partSize) { // stream is done reading and had extra data, buffer the remainder of the file for (let i = 0; i < buf.length; i += this._partSize) { this._streamBuffer.push(buf.slice(i, i + this._partSize)); } buf = this._streamBuffer.shift(); } } this._fileHash.update(buf); let chunk = new Chunk( this._client, this._sessionID, buf, this._position, this._size, this._options ); this._position += buf.length; callback(chunk); } /** * Upload a chunk * @param {Chunk} chunk The chunk to upload * @returns {void} * @emits ChunkedUploader#chunkError * @emits ChunkedUploader#chunkUploaded */ _uploadChunk(chunk: any /* FIXME */) { this._numChunksInFlight += 1; chunk.on('error', (err: any /* FIXME */) => this.emit('chunkError', err)); chunk.on('uploaded', (data: any /* FIXME */) => { this._numChunksInFlight -= 1; this.emit('chunkUploaded', data); this._getNextChunk((nextChunk: any /* FIXME */) => nextChunk ? this._uploadChunk(nextChunk) : this._commit() ); }); chunk.upload(); this._chunks.push(chunk); } /** * Commit the upload, finalizing it * @returns {void} * @emits ChunkedUploader#uploadComplete * @emits ChunkedUploader#error */ _commit() { if (!this._isStarted || this._numChunksInFlight > 0) { return; } let hash = this._fileHash.digest('base64'); this._isStarted = false; let options = Object.assign( { parts: this._chunks.map((c) => c.getData()), }, this._options.fileAttributes ); this._client.files.commitUploadSession(this._sessionID, hash, options, ( err: any /* FIMXE */, file: any /* FIMXE */ ) => { // It's not clear what the SDK can do here, so we just return the error and session info // so users can retry if they wish if (err) { this.emit('error', { uploadSession: this._uploadSessionInfo, error: err, }); this._reject!(err); return; } this.emit('uploadComplete', file); this._resolve!(file); }); } } export = ChunkedUploader;
the_stack
import React from 'react' import { render, fireEvent, act, createEvent } from '@testing-library/react' import { axe } from 'jest-axe' import Carousel from './Carousel' const wait = (amount = 0) => new Promise((resolve) => setTimeout(resolve, amount)) const SLIDING_TRANSITION_DURATION = 100 describe('Carousel component', () => { it('should have `data-store-carousel` attribute in the section tag', () => { const { getByTestId } = render( <Carousel> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const carouselSection = getByTestId('store-carousel') expect(carouselSection).toHaveAttribute('data-store-carousel') }) it('should have `data-carousel-track-container` and `data-carousel-track` attributes', () => { const { getByTestId } = render( <Carousel> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> <div>Slide 4</div> <div>Slide 5</div> </Carousel> ) const carouselSection = getByTestId('store-carousel') const trackContainer = carouselSection.querySelectorAll( '[data-carousel-track-container]' ) const track = carouselSection.querySelectorAll('[data-carousel-track]') expect(trackContainer).toHaveLength(1) expect(trackContainer[0]).toBeInTheDocument() expect(track).toHaveLength(1) expect(track[0]).toBeInTheDocument() }) it('should have `data-carousel-controls` and `data-carousel-bullets` attributes', () => { const { getByTestId } = render( <Carousel> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const carouselSection = getByTestId('store-carousel') const controls = carouselSection.querySelectorAll( '[data-carousel-controls]' ) const bulletsContainer = carouselSection.querySelectorAll( '[data-carousel-bullets]' ) expect(controls).toHaveLength(1) expect(controls[0]).toBeInTheDocument() expect(bulletsContainer).toHaveLength(1) expect(bulletsContainer[0]).toBeInTheDocument() }) it('should render 5 slides with `data-carousel-item` attributes', () => { const { getByTestId } = render( <Carousel infiniteMode={false}> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> <div>Slide 4</div> <div>Slide 5</div> </Carousel> ) const carouselSection = getByTestId('store-carousel') const items = carouselSection.querySelectorAll('[data-carousel-item]') expect(items).toHaveLength(5) }) it('should add `data-visible` attribute to currently visible carousel items', () => { const { getByTestId } = render( <Carousel> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> <div>Slide 4</div> <div>Slide 5</div> </Carousel> ) const carouselSection = getByTestId('store-carousel') const items = carouselSection.querySelectorAll('[data-carousel-item]') expect(items).toHaveLength(7) // Only the first item should have `data-visible` attributes expect(items[0]).not.toHaveAttribute('data-visible') expect(items[1]).toHaveAttribute('data-visible') expect(items[2]).not.toHaveAttribute('data-visible') expect(items[3]).not.toHaveAttribute('data-visible') expect(items[4]).not.toHaveAttribute('data-visible') expect(items[5]).not.toHaveAttribute('data-visible') expect(items[6]).not.toHaveAttribute('data-visible') }) it('should allow users to navigate through pages using the `Arrows` controls', async () => { const { getByTestId, getByLabelText } = render( <Carousel transition={{ property: 'transform', duration: SLIDING_TRANSITION_DURATION, }} infiniteMode={false} > <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> <div>Slide 4</div> <div>Slide 5</div> </Carousel> ) const carouselSection = getByTestId('store-carousel') const goToNextPageButton = getByLabelText('next') const goToPreviousPageButton = getByLabelText('previous') const carouselTrack = carouselSection.querySelector('[data-carousel-track]') expect(goToNextPageButton).toBeInTheDocument() expect(goToPreviousPageButton).toBeInTheDocument() // Go from page 0 to 1 act(() => { fireEvent.click(goToNextPageButton) }) let items = carouselSection.querySelectorAll('[data-carousel-item]') // Only the second item should be visible expect(items[0]).not.toHaveAttribute('data-visible') expect(items[1]).toHaveAttribute('data-visible') expect(items[2]).not.toHaveAttribute('data-visible') expect(items[3]).not.toHaveAttribute('data-visible') expect(items[4]).not.toHaveAttribute('data-visible') // Go from page 1 back to 0 await act(async () => { /** * These two lines simulate what happens after a user navigates: * * 1. Wait for the animation triggered by the `goToNextPageButton` click * to finish. * 2. `onTransitionEnd` event is triggered. * 3. User is then able to click the `goToPreviousPageButton` button. * * react-testing-library (or dom-testing-library) doesn't trigger the * `onTransitionEnd` event, so we need to do it manually. */ await wait(SLIDING_TRANSITION_DURATION) carouselTrack && fireEvent.transitionEnd(carouselTrack) fireEvent.click(goToPreviousPageButton) }) items = carouselSection.querySelectorAll('[data-carousel-item]') // Only the first item should be visible expect(items[0]).toHaveAttribute('data-visible') expect(items[1]).not.toHaveAttribute('data-visible') expect(items[2]).not.toHaveAttribute('data-visible') expect(items[3]).not.toHaveAttribute('data-visible') expect(items[4]).not.toHaveAttribute('data-visible') }) it('should allow users to navigate through pages by clicking on a pagination bullet', async () => { const { getByTestId, queryAllByTestId, getByLabelText } = render( <Carousel transition={{ property: 'transform', duration: SLIDING_TRANSITION_DURATION, }} infiniteMode={false} > <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> <div>Slide 4</div> <div>Slide 5</div> </Carousel> ) const carouselSection = getByTestId('store-carousel') const bullets = queryAllByTestId('store-bullets-item') const carouselTrack = carouselSection.querySelector('[data-carousel-track]') expect(bullets).toHaveLength(5) const secondPageBullet = getByLabelText('Go to page 2') act(() => { fireEvent.click(secondPageBullet) }) let items = carouselSection.querySelectorAll('[data-carousel-item]') // Only the second item should be visible expect(items[0]).not.toHaveAttribute('data-visible') expect(items[1]).toHaveAttribute('data-visible') expect(items[2]).not.toHaveAttribute('data-visible') expect(items[3]).not.toHaveAttribute('data-visible') expect(items[4]).not.toHaveAttribute('data-visible') const thirdPageBullet = getByLabelText('Go to page 3') await act(async () => { /** * These two lines simulate what happens after a user navigates. * * 1. Wait for the animation triggered by the `secondPageBullet` click * to finish. * 2. `onTransitionEnd` event is triggered. * 3. User is then able to click the `thirdPageBullet` button. * * react-testing-library (or dom-testing-library) doesn't trigger the * `onTransitionEnd` event, so we need to do it manually. */ await wait(SLIDING_TRANSITION_DURATION) carouselTrack && fireEvent.transitionEnd(carouselTrack) fireEvent.click(thirdPageBullet) }) items = carouselSection.querySelectorAll('[data-carousel-item]') // Only the 3rd item should be visible expect(items[0]).not.toHaveAttribute('data-visible') expect(items[1]).not.toHaveAttribute('data-visible') expect(items[2]).toHaveAttribute('data-visible') expect(items[3]).not.toHaveAttribute('data-visible') expect(items[4]).not.toHaveAttribute('data-visible') }) describe('Accessibility', () => { it('should have no violations on a default use case', async () => { const { container } = render( <Carousel> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) expect(await axe(container)).toHaveNoViolations() }) it('should have no violations with infiniteMode false', async () => { const { container } = render( <Carousel infiniteMode={false}> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) expect(await axe(container)).toHaveNoViolations() }) it('should have necessary roles and aria-roledescriptions attributes', () => { const { getByTestId, getAllByRole } = render( <Carousel infiniteMode={false}> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) // Check aria-roledescriptions expect(getByTestId('store-carousel')).toHaveAttribute( 'aria-roledescription', 'carousel' ) expect( getByTestId('store-carousel').querySelectorAll( '[aria-roledescription="slide"]' ) ).toHaveLength(3) // Check roles expect(getAllByRole('tablist')).toHaveLength(1) expect(getAllByRole('tab')).toHaveLength(3) expect(getAllByRole('tab', { selected: true })).toHaveLength(1) expect(getAllByRole('tabpanel')).toHaveLength(3) // Check bullets aria-controls expect( getByTestId('store-bullets').querySelectorAll('[aria-controls]') ).toHaveLength(3) }) describe('Tablist', () => { it('should be focused when a component with role `tablist` or `tab` is focused', () => { const { getByRole, getAllByRole } = render( <Carousel> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const tablist = getByRole('tablist') fireEvent.focus(tablist) expect(tablist).toHaveFocus() const [, sndTab] = getAllByRole('tab') fireEvent.focus(sndTab) expect(tablist).toHaveFocus() }) describe('Keyboard navigation', () => { it('should slide to the next page on `ArrowRight` press', async () => { const { getAllByRole, getByRole, getByTestId } = render( <Carousel transition={{ duration: 0, property: 'transform', }} > <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const carouselTrack = getByTestId('store-carousel').querySelector( '[data-carousel-track]' ) as Element const tabs = getAllByRole('tab') // Select last tab fireEvent.click(tabs[2]) fireEvent.transitionEnd(carouselTrack) expect(tabs[2]).toHaveAttribute('aria-selected', 'true') const tablist = getByRole('tablist') fireEvent.focus(tablist) // Loop fireEvent.keyDown(tablist, { key: 'ArrowRight', }) fireEvent.transitionEnd(carouselTrack) expect(tabs[2]).toHaveAttribute('aria-selected', 'false') expect(tabs[0]).toHaveAttribute('aria-selected', 'true') }) it('should not slide to the next page on `ArrowRight` when infiniteMode is false', () => { const { getAllByRole, getByRole, getByTestId } = render( <Carousel transition={{ duration: 0, property: 'transform', }} infiniteMode={false} > <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const carouselTrack = getByTestId('store-carousel').querySelector( '[data-carousel-track]' ) as Element const tabs = getAllByRole('tab') // Select last tab fireEvent.click(tabs[2]) fireEvent.transitionEnd(carouselTrack) expect(tabs[2]).toHaveAttribute('aria-selected', 'true') const tablist = getByRole('tablist') fireEvent.focus(tablist) // Try to loop fireEvent.keyDown(tablist, { key: 'ArrowRight', }) fireEvent.transitionEnd(carouselTrack) expect(tabs[0]).toHaveAttribute('aria-selected', 'false') expect(tabs[2]).toHaveAttribute('aria-selected', 'true') }) it('should slide to the next page on `ArrowLeft` press', () => { const { getAllByRole, getByRole, getByTestId } = render( <Carousel transition={{ duration: 0, property: 'transform', }} > <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const carouselTrack = getByTestId('store-carousel').querySelector( '[data-carousel-track]' ) as Element const tabs = getAllByRole('tab') expect(tabs[0]).toHaveAttribute('aria-selected', 'true') const tablist = getByRole('tablist') fireEvent.focus(tablist) // Loop back. From first to last fireEvent.keyDown(tablist, { key: 'ArrowLeft', }) fireEvent.transitionEnd(carouselTrack) expect(tabs[0]).toHaveAttribute('aria-selected', 'false') expect(tabs[2]).toHaveAttribute('aria-selected', 'true') }) it('should not slide to the next page on `ArrowLeft` press when infiniteMode is false', () => { const { getAllByRole, getByRole, getByTestId } = render( <Carousel transition={{ duration: 0, property: 'transform', }} infiniteMode={false} > <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const carouselTrack = getByTestId('store-carousel').querySelector( '[data-carousel-track]' ) as Element const tabs = getAllByRole('tab') expect(tabs[0]).toHaveAttribute('aria-selected', 'true') const tablist = getByRole('tablist') fireEvent.focus(tablist) // Try to loop back. From first to last fireEvent.keyDown(tablist, { key: 'ArrowLeft', }) fireEvent.transitionEnd(carouselTrack) expect(tabs[2]).toHaveAttribute('aria-selected', 'false') expect(tabs[0]).toHaveAttribute('aria-selected', 'true') }) it('should slide to the first slide on `Home` press', () => { const { getAllByRole, getByRole, getByTestId } = render( <Carousel transition={{ duration: 0, property: 'transform', }} > <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const carouselTrack = getByTestId('store-carousel').querySelector( '[data-carousel-track]' ) as Element const tabs = getAllByRole('tab') // Select last tab fireEvent.click(tabs[2]) fireEvent.transitionEnd(carouselTrack) expect(tabs[2]).toHaveAttribute('aria-selected', 'true') const tablist = getByRole('tablist') fireEvent.focus(tablist) fireEvent.keyDown(tablist, { key: 'Home', }) fireEvent.transitionEnd(carouselTrack) expect(tabs[2]).toHaveAttribute('aria-selected', 'false') expect(tabs[0]).toHaveAttribute('aria-selected', 'true') }) it('should slide to the last slide on `End` press', () => { const { getAllByRole, getByRole, getByTestId } = render( <Carousel transition={{ duration: 0, property: 'transform', }} > <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const carouselTrack = getByTestId('store-carousel').querySelector( '[data-carousel-track]' ) as Element const tabs = getAllByRole('tab') expect(tabs[0]).toHaveAttribute('aria-selected', 'true') const tablist = getByRole('tablist') fireEvent.focus(tablist) fireEvent.keyDown(tablist, { key: 'End', }) fireEvent.transitionEnd(carouselTrack) expect(tabs[0]).toHaveAttribute('aria-selected', 'false') expect(tabs[2]).toHaveAttribute('aria-selected', 'true') }) it('check the tablist event is not prevented from propagating', () => { const mockPreventDefault = jest.fn() const { getByRole } = render( <Carousel> <div>Slide 1</div> <div>Slide 2</div> <div>Slide 3</div> </Carousel> ) const tablist = getByRole('tablist') const event = createEvent.keyDown(tablist, { key: 'Tab' }) event.preventDefault = mockPreventDefault fireEvent.focus(tablist) fireEvent(tablist, event) expect(mockPreventDefault).not.toHaveBeenCalled() }) }) }) }) })
the_stack
import { Dorm } from '../lib/query-builder.ts'; import { assertEquals, assertNotEquals} from "../deps.ts"; import { config } from '../deps.ts'; /* ------------------------------ TESTING SCOPE ----------------------------- */ /* * @basic_cases {Query Completion, Data update,} * @edge_cases {Invalid strings, multiple methods, postgre error return, error handling} */ const env = config(); // create .env file and add your database inside it. using followin variables USERNAME, PASSWORD, SERVER const URL = `postgres://${env.USERNAME}:${env.PASSWORD}@${env.SERVER}:5432/${env.USERNAME}`; const database = URL; // Or you can add your url here const dorm = new Dorm(database); /* --------------------------- CREATING TESTING ID -------------------------- */ var updateId = 2; /* -------------------------------------------------------------------------- */ /* MAKING INITIAL QUERIES FOR TESTS */ /* -------------------------------------------------------------------------- */ const initialSetup1 = await dorm .insert([ { 'username':'Golden_Retreiver', 'email':'iamagooddog@dogs.com', }, { 'username':'Superman', 'email':'superman@superman.com', }, { 'username':'MrBing', 'email':'chandlerbing@bings.com', }, { 'username':'Golden_Retreiver', 'email':'iamagooddog@dogs.com', }, { 'username':'Superman', 'email':'superman@superman.com', }, { 'username':'MrBing', 'email':'chandlerbing@bings.com', } ]) .table('dropthis') .returning() .then((data:any) => data.rows) .catch((e:any) => e); const initialSetup3 = `INSERT INTO dropthis (username, email) VALUES ('dorm Member 1', 'chandlerbing@bings.com'), ('dorm Member 2', 'chandlerbing@bings.com'), ('dorm Member 3', 'chandlerbing@bings.com'), ('dorm Member 4', 'chandlerbing@bings.com'), ('dorm Member 5', 'chandlerbing@bings.com');` const insertToUser = await dorm.raw(initialSetup3); /* -------------------------------------------------------------------------- */ /* PARAMETERIZED STRING TEST */ /* -------------------------------------------------------------------------- */ Deno.test(`parameterized all column and values in all methods:`, () => { const columnNames = [ { 'username':'Golden_Retreiver', 'password': 'golDenR', 'email':'iamagooddog@dogs.com', 'created_on': 'NOW()' }, { 'username':'Superman', 'password':'IamnotHuman', 'email':'superman@superman.com', 'created_on': 'NOW()' }, { 'username':'MrBing', 'password':'BingbingBing', 'email':'chandlerbing@bings.com', 'created_on': 'NOW()' } ]; const tableName = 'userprofile'; const test = dorm .insert(columnNames) .table(tableName) .toObj() console.log('test:', test.text) assertEquals(test, { text: "INSERT INTO userprofile (username, password, email, created_on) VALUES ($1, $2, $3, $4), ($5, $6, $7, $8), ($9, $10, $11, $12)", values: [ "Golden_Retreiver", "golDenR", "iamagooddog@dogs.com", "NOW()", "Superman", "IamnotHuman", "superman@superman.com", "NOW()", "MrBing", "BingbingBing", "chandlerbing@bings.com", "NOW()" ] }, 'Error:Querybuilder is returning unparametrized query string!!' ) }); /* -------------------------------------------------------------------------- */ /* SELECT METHOD */ /* -------------------------------------------------------------------------- */ /* ------------------------------ NORMAL SELECT ----------------------------- */ const selectQuery = await dorm .select() .from('people') .where('_id=1') .then((data: any) => { return data.rows; }) .catch((e:any)=> {throw e}) Deno.test(`connection to the database:`, () => { assertNotEquals(selectQuery,undefined, 'connect should be returning a query.'); }); Deno.test(`"SELECT" method:`, () => { assertNotEquals(selectQuery,undefined, `Error:the method should return a query result.`); }); /* ------------------------- INVALAID SELECT METHOD ------------------------- */ const invalidSelect = await dorm .select() .from('userprofile') .where('_id=1') .then((data: any) => { return data.rows; }).catch((e:any)=> {return false}) Deno.test(`all queries to be valid in "SELECT" method:`,() => { assertEquals(invalidSelect, false, `Error:INVALID query found!!!! It should return an error for invalid query request from Postgres.`) }) /* ----------------------- SINGLE COLUMN SELECT METHOD ---------------------- */ Deno.test(`single-column query in "SELECT" method:`, () => { const tableName = 'userprofile'; const condition = 'user_id = 2' const test = dorm.select().from('userprofile').where('user_id = 2'); assertEquals(test.info.action.type , 'SELECT', `Error:type is not updated to SELECT`); assertEquals(test.info.action.table , tableName, `Error:table is not updated to ${tableName}`); assertEquals(test.info.filter.where , true, `Error:where is not updated to true`); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ const testQuery = test.toString(); assertEquals(testQuery , `SELECT * FROM userprofile WHERE user_id = $1`, 'Error:Querybuilder is returning unparametrized query string!!'); assertEquals(test.info.action.type , null, 'Error:Type is not reset after query'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset after query'); assertEquals(test.info.action.table , null, 'Error:Table is not reset after query'); assertEquals(test.info.filter.where , false, `Error:where is not reset after query`); assertEquals(test.info.filter.condition , null, `Error:condition is not reset after query`); }) /* --------------------- MULTIPLE COLUMNS SELECT METHOD --------------------- */ Deno.test(`multiple-columns query in "SELECT" method:`, () => { const columnName = 'username, email'; const tableName = 'userprofile'; const condition = 'user_id = 1' const test = dorm.select(columnName).from(tableName).where(condition); assertEquals(test.info.action.type , 'SELECT', 'Error:Type is not updated to SELECT'); assertEquals(test.info.action.columns , columnName, `Error:column/columns are updated to ${columnName}`); assertEquals(test.info.filter.where , true, `Error:where is not updated to true`); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ const testQuery = test.toString(); assertEquals(testQuery , `SELECT username, email FROM userprofile WHERE user_id = $1`, 'Error:Querybuilder is returning unparametrized query string!!'); assertEquals(test.info.action.type , null, 'Error:Type is not reset after query'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset'); assertEquals(test.info.action.table , null, 'Error:Table is not reset after query'); assertEquals(test.info.filter.where , false, `Error:where is not reset after query`); assertEquals(test.info.filter.condition , null, `Error:condition is not reset after query`); }) /* -------------------------------------------------------------------------- */ /* INSERT METHOD */ /* -------------------------------------------------------------------------- */ const insertQuery = await dorm .insert([{'username':'newDogs', 'email': 'newdog@dog.com' }]) .table('dropthis') .returning() .then((data: any) => { return data; }) const insertSelectQuery1 = await dorm .select() .table('dropthis') .then((data: any) => { return data.rows; }) /* ----------------------- VALIDATION OF INSERT METHOD ---------------------- */ Deno.test(`all queries to be valid in "INSERT" method:`, () => { assertNotEquals(insertQuery, undefined, 'Error:the method should return a query result.') assertNotEquals(insertQuery, insertSelectQuery1, `Expected value: ${insertQuery} not to be equal to Received:${insertSelectQuery1}`) }); const invalidInsert = await dorm .insert([{'user':'newDogs'}]) .delete('dropthis') .table('dropthis') .where('_id=1') .then((data: any) => { return data.rows; }).catch((e:any)=> {return e}) Deno.test(`all invalid queries should not work in "INSERT" method:`,() => { assertEquals(invalidInsert, 'No multiple actions', `Error:INVALID query found!!!! It should return an error for invalid query request from Postgres.`) }) /* -------------------- SINGLE ROW QUERY IN INSERT METHOD ------------------- */ Deno.test(`single-row query in "INSERT" method:`, () => { const columnName = [{'username':'singleLady'}]; const tableName = 'users'; const returning = '*' const test = dorm .insert(columnName) .from(`${tableName}`) .returning(returning); assertEquals(test.info.action.type , 'INSERT', `Error:type is not updated to SELECT`); assertEquals(test.info.action.table , tableName, `Error:table is not updated to ${tableName}`); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ const testQuery = test.toString(); assertEquals(testQuery , `INSERT INTO users (username) VALUES ($1) RETURNING *`, 'Error:Querybuilder is returning unparametrized query string!!'); assertEquals(test.info.action.type , null, 'Error:Type is not reset after query'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset after query'); assertEquals(test.info.action.table , null, 'Error:Table is not reset after query'); assertEquals(test.info.action.values , [], 'Error:Value is not reset after query'); }); /* ------------------ MULTIPLE ROWS QUERY IN INSERT METHOD ------------------ */ Deno.test(`multiple-rows query in "INSERT" method:`, () => { const columnNames = [ { 'username':'Golden_Retreiver', 'password': 'golDenR', 'email':'iamagooddog@dogs.com', 'created_on': 'NOW()' }, { 'username':'Superman', 'password':'IamnotHuman', 'email':'superman@superman.com', 'created_on': 'NOW()' }, { 'username':'MrBing', 'password':'BingbingBing', 'email':'chandlerbing@bings.com', 'created_on': 'NOW()' } ]; const tableName = 'userprofile'; const test = dorm .insert(columnNames) .table(tableName) assertEquals(test.info.action.type , 'INSERT', 'Type is not updated to INSERT'); assertEquals(test.info.action.table , tableName, `Error:table is not updated to ${tableName}`); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ test.toString(); assertEquals(test.info.action.type , null, 'Error:Type is not reset after query'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset after query'); assertEquals(test.info.action.table , null, 'Error:Table is not reset after query'); assertEquals(test.info.action.values , [], 'Error:Value is not reset after query'); }); /* -------------------------------------------------------------------------- */ /* UPDATE METHOD */ /* -------------------------------------------------------------------------- */ /* -------------------- SINGLE ROW QUERY IN UPDATE METHOD ------------------- */ const updateQuery = await dorm .update({'username':'updatedDogs', 'email': 'updated@dogs.com'}) .where(`_id = ${updateId}`) .table('dropthis') .returning() .then((data: any) => { return data.rows; }).catch((e:any) => e); const testUpdateQuery1 = await dorm .select() .table('dropthis') .where(`_id=${updateId}`) .then((data: any) => { return data.rows; }).catch((e:any) => e); Deno.test(`a single-row query in "UPDATE" method:`, () => { const test = dorm.update({'username':'newDogs', 'password': 'iLoveDogs'}).where(`user_id = ${updateId+1}`) .from('userprofile') .returning('username') assertEquals(updateQuery, testUpdateQuery1 , 'Error: the method should work more than one row'); assertEquals(test.info.action.type , 'UPDATE', 'Error:Type is not updated to UPDATE'); assertEquals(test.info.action.table , 'userprofile', 'Error:Table is not updated to userprofile'); assertEquals(test.info.returning.active , true, 'Error:Returning is not updated'); assertEquals(test.info.returning.columns , 'username', 'Error:Columns in Returning is not reset'); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ test.toString(); assertEquals(test.info.action.type , null, 'Error:Type is not reset'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset'); assertEquals(test.info.action.values , [], 'Error:Values are not reset'); assertEquals(test.info.action.table , null, 'Error:Table is not reset'); assertEquals(test.info.returning.active , false, 'Error:Returning is not reset'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); }); /* ------------------ MULTIPLE ROWS QUERY IN UPDATE METHOD ------------------ */ const testUpdateQuery2 = await dorm .select() .table('userprofile') .where(`user_id < ${updateId}`) .then((data: any) => { return data.rows; }).catch((e:any) => e); const multipleRowsQuery = await dorm .update({'username':'Dogs', 'email': 'iamnotagooddog@dogs.com'}) .table('dropthis') .where(`_id < ${updateId}`) .returning() .then((data: any) => { return data; }).catch((e:any) => e); Deno.test(`multiple-rows query in "UPDATE" method:`, () => { const test = dorm.update({'username':'Dogs', 'password': 'ihave8Dogs'}).where(`user_id <= ${updateId}`) .from('userprofile') .returning('username'); assertNotEquals(multipleRowsQuery, testUpdateQuery2, `Error:${updateId} rows was not updated `); assertEquals(test.info.action.type , 'UPDATE', 'Error:Type is not updated to UPDATE'); assertEquals(test.info.action.table , 'userprofile', 'Error:Table is not updated to userprofile'); assertEquals(test.info.returning.active , true, 'Error:Returning is not updated'); assertEquals(test.info.returning.columns , 'username', 'Error:Columns in Returning is not reset'); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ const testQuery = test.toString(); assertEquals(testQuery , `UPDATE userprofile SET username = $1, password = $2 WHERE user_id < = $3 RETURNING username`, 'Error:Querybuilder is returning unparametrized query string!!'); assertEquals(test.info.action.type , null, 'Error:Type is not reset'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset'); assertEquals(test.info.action.table , null, 'Error:Table is not reset'); assertEquals(test.info.returning.active , false, 'Error:Returning is not reset'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); }); /* --------------- ALL ROWS TO BE UPDATED USING UPDATE METHOD --------------- */ const allRowsUpdateQuery = await dorm .update({'username':'restarted', 'email': 'iamagoodcat@cats.com'}) .table('dropthis') .returning() .then((data: any) => { return data.rows; }).catch((e:any) => e); Deno.test(`all rows query in "UPDATE" method:`, () => { const test = dorm.update({'username':'restarted', 'password': 'iamADog'}) .from('userprofile') .returning('username'); assertEquals(Array.isArray(allRowsUpdateQuery), true,'Error:The whole table was not updated'); assertEquals(test.info.action.type , 'UPDATE', 'Error:Type is not updated to UPDATE'); assertEquals(test.info.action.table , 'userprofile', 'Error:Table is not updated to userprofile'); assertEquals(test.info.returning.active , true, 'Error:Returning is not updated'); assertEquals(test.info.returning.columns , 'username', 'Error:Columns in Returning is not reset'); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ const testQuery = test.toString(); assertEquals(testQuery , `UPDATE userprofile SET username = $1, password = $2 RETURNING username`, 'Error:Querybuilder is returning unparametrized query string!!'); assertEquals(test.info.action.type , null, 'Error:Type is not reset'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset'); assertEquals(test.info.action.values , [], 'Error:Values are not reset'); assertEquals(test.info.action.table , null, 'Error:Table is not reset'); assertEquals(test.info.returning.active , false, 'Error:Returning is not reset'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); }); /* -------------------------------------------------------------------------- */ /* DELETE METHOD */ /* -------------------------------------------------------------------------- */ Deno.test(`all queries to be valid in "DELETE" method:`, ()=> { const tableName = 'users'; const condition = `user_id = ${updateId+2}` const test = dorm .delete() .from(tableName) .where(condition) .returning(); assertEquals(test.info.action.type , "DELETE", 'Error:Type should be updated to DELETE'); assertEquals(test.info.action.table , tableName, `Error:Table should be updated to ${tableName}`); assertEquals(test.info.filter.where , true, `Error:where should be updated to true`); assertEquals(test.info.returning.active , true, 'Error:Returning should be updated'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning should be pdated'); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ const testQuery = test.toString(); assertEquals(test.info.action.type , null, 'Error:Type is not reset'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset'); assertEquals(test.info.action.values , [], 'Error:Values are not reset'); assertEquals(test.info.action.table , null, 'Error:Table is not reset'); assertEquals(test.info.filter.where , false, `Error:where is not reset after query`); assertEquals(test.info.filter.condition , null, `Error:condition is not reset after query`); assertEquals(test.info.returning.active , false, 'Error:Returning is not reset'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); }) /* ----------------------- SINGLE ROW QUERY IN DELETE ----------------------- */ const deleteOneQuery = await dorm .delete('dropthis') .where(`_id = ${updateId}`) .returning() .then((data:any)=> { return data.rows; }) .catch((e:any) => { console.log('Error: ', e) }); Deno.test(`single-row query in "DELETE" method:`, ()=> { const tableName = 'userprofile'; const condition = `user_id = ${updateId+1}` const test = dorm .delete() .from(tableName) .where(condition) .returning(); assertEquals(Array.isArray(deleteOneQuery),true ,'Error:Delete query is not completed!'); assertEquals(test.info.action.type , 'DELETE', 'Error:Type is not updated to DELETE'); assertEquals(test.info.action.table , tableName, 'Error:Table is not updated to userprofile'); assertEquals(test.info.filter.where , true, `Error:where is not updated to true`); assertEquals(test.info.returning.active , true, 'Error:Returning is not updated'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ const testQuery = test.toString(); assertEquals(test.info.action.type , null, 'Error:Type is not reset'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset'); assertEquals(test.info.action.values , [], 'Error:Values are not reset'); assertEquals(test.info.action.table , null, 'Error:Table is not reset'); assertEquals(test.info.filter.where , false, `Error:where is not reset after query`); assertEquals(test.info.filter.condition , null, `Error:condition is not reset after query`); assertEquals(test.info.returning.active , false, 'Error:Returning is not reset'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); }); /* ------------------ MULTIPLE ROWS QUERY IN DELETE METHOD ------------------ */ const deleteMultipleQuery = await dorm .delete() .from('dropthis') .where(`_id = ${updateId+1}`) .returning() .then((data:any)=> { return data; }).catch((e:any) => e); Deno.test(`multiple-rows query in "DELETE" method:`, ()=> { const tableName = 'users'; const condition = `user_id > ${updateId+2}` const test = dorm .delete() .from(tableName) .where(condition) .returning(); assertEquals(test.info.action.type , 'DELETE', 'Error:Type is not updated to DELETE'); assertEquals(test.info.action.table , tableName, 'Error:Table is not updated to userprofile'); assertEquals(test.info.filter.where , true, `Error:where is not updated to true`); assertEquals(test.info.returning.active , true, 'Error:Returning is not updated'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ test.toString() assertEquals(test.info.action.type , null, 'Error:Type is not reset'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset'); assertEquals(test.info.action.values , [], 'Error:Values are not reset'); assertEquals(test.info.action.table , null, 'Error:Table is not reset'); assertEquals(test.info.filter.where , false, `Error:where is not reset after query`); assertEquals(test.info.filter.condition , null, `Error:condition is not reset after query`); assertEquals(test.info.returning.active , false, 'Error:Returning is not reset'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); }); /* ---------------------- DELETING ALL ROWS IN DELETE ---------------------- */ const deleteAllQuery = await dorm .delete() .from('dropthis') .returning() .then((data:any)=> { return data; }).catch((e:any) => e); Deno.test(`all rows cannot be deleted in "DELETE" method:`, ()=> { const tableName = 'users'; const condition = `` const test = dorm .delete() .from(tableName) .where(condition) .returning(); assertEquals(deleteAllQuery,'No delete without where (use deleteAll to delete all rows)','Error:Multiple DELETE query is not completed!'); assertEquals(test.info.action.type , 'DELETE', 'Error:Type is not updated to DELETE'); assertEquals(test.info.action.table , tableName, 'Error:Table is not updated to userprofile'); assertEquals(test.info.filter.where , true, `Error:where is not updated to true`); assertEquals(test.info.returning.active , true, 'Error:Returning is not updated'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ const reset = (arg:Dorm) => { arg.callOrder = []; arg.error = { id: 0, message: '', }; arg.info = { action: { type: null, table: null, columns: '*', values: [], valuesParam: '', }, join: [], filter: { where: false, condition: null, }, returning: { active: false, columns: '*', }, }; } reset(test); assertEquals(test.info.action.type , null, 'Error:Type is not reset'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset'); assertEquals(test.info.action.values , [], 'Error:Values are not reset'); assertEquals(test.info.action.table , null, 'Error:Table is not reset'); assertEquals(test.info.filter.where , false, `Error:where is not reset after query`); assertEquals(test.info.filter.condition , null, `Error:condition is not reset after query`); assertEquals(test.info.returning.active , false, 'Error:Returning is not reset'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); }); /* -------------------------------------------------------------------------- */ /* DROP METHOD */ /* -------------------------------------------------------------------------- */ const idropThis = dorm .drop('dropthis') .then((data:any)=>{ return data; }).catch((e:any) => e); /* ------------------------- VALIDATION TEST IN DROP ------------------------ */ Deno.test(`all queries to be valid in "DROP" method:`, ()=> { const tableName = 'dropthis'; const test = dorm .drop() .from(tableName) .returning(); assertEquals(idropThis,[],'Error:INVALID query found!!!! It should return an error for invalid query request from Postgres.'); assertEquals(test.info.action.type , 'DROP', 'Error:Type should be updated to DROP'); assertEquals(test.info.action.table , tableName, `Error:Table should be updated to ${tableName}`); assertEquals(test.info.returning.active , true, 'Error:Returning should be updated to true'); /* ------------------------ RESETTING INITIAL VALUES ------------------------ */ test.toString(); assertEquals(test.info.action.type , null, 'Error:Type is not reset'); assertEquals(test.info.action.columns , '*', 'Error:Columns are not reset'); assertEquals(test.info.action.values , [], 'Error:Values are not reset'); assertEquals(test.info.action.table , null, 'Error:Table is not reset'); assertEquals(test.info.filter.where , false, `Error:where is not reset after query`); assertEquals(test.info.filter.condition , null, `Error:condition is not reset after query`); assertEquals(test.info.returning.active , false, 'Error:Returning is not reset'); assertEquals(test.info.returning.columns , '*', 'Error:Columns in Returning is not reset'); }); /* ---------------------- RECREATING THE DROPPED TABLE ---------------------- */ const initialSetup2 = `CREATE TABLE public.dropthis("_id" serial PRIMARY KEY,"username" VARCHAR ( 150 ) NULL,"email" VARCHAR ( 255 ) NULL)WITH (OIDS=FALSE);` const tableToDrop = await dorm.raw(initialSetup2); /* -------------------------------------------------------------------------- */ /* Join Method */ /* -------------------------------------------------------------------------- */ let fromTry:any; try{ fromTry = await dorm .select() .from('people') .join('people_in_films') .on('people._id = people_in_films.person_id'); } catch(err){ console.log('Error:', err); } const fromRaw = await dorm.rawrr(`SELECT * FROM people LEFT OUTER JOIN people_in_films ON people._id = people_in_films.person_id`); /* ---------------------------- SINGLE JOIN TEST ---------------------------- */ Deno.test(`Query completion for single Join in JOIN method:`, () => { assertEquals(Array.isArray(fromTry.rows), true , 'JOIN query is not completed') }); Deno.test(`dORM query vs raw query for single Join in JOIN method:`, () => { assertEquals(fromRaw.rows, fromTry.rows, 'JOIN query and RAW query should be equal.') }); const multiJoinQuery1: any = await dorm .select() .from('people') .join('people_in_films') .on('people._id = people_in_films.person_id') .join('films') .on('people_in_films.film_id = films._id') .then((data:any)=> { return data.rows; }) .catch ((err:any) => { console.log('Error:', err) }) const fromRaw2 = await dorm.rawrr(`SELECT * FROM people LEFT OUTER JOIN "people_in_films" ON people._id = "people_in_films".person_id LEFT OUTER JOIN films ON "people_in_films".film_id = films._id`); /* --------------------------- MULTIPLE JOIN TEST --------------------------- */ Deno.test(`Query completion for two Joins in JOIN method:`, () => { assertEquals(Array.isArray(multiJoinQuery1), true , 'JOIN query is not completed') }); Deno.test(`dORM query vs raw query for two Joins in JOIN method:`, () => { assertEquals(fromRaw2.rows, multiJoinQuery1, 'JOIN query and RAW query should be equal.') }); /* ----------------------------- FLEXIBLITY TEST ---------------------------- */ const multiJoinQuery3: any = await dorm .select() .from('people') .on('people._id = people_in_films.person_id') .on('people_in_films.film_id = films._id') .where('people_in_films._id < 3') .join('people_in_films') .leftJoin('films') .then((data: any) => { return data.rows[0]; }) .catch((err) => { console.log('Error:', err); }); Deno.test( `Query cannot complete without "ON" condition for two Joins in JOIN method:`, () => { assertEquals(multiJoinQuery3.name, "Luke Skywalker", 'JOIN query is not completed'); } );
the_stack
import patchRequire from "./require-rebuild"; patchRequire(); import { app, App, BrowserWindowConstructorOptions, ipcMain, MenuItem, BrowserWindow, dialog, shell, Notification } from "electron"; import { CustomBrowserWindow } from "./browser-window"; import { AppMenu } from "./menu"; import path from "path"; import { CustomAutoUpdater } from "./auto-update"; import i18n from "./i18n"; import urlparse from "url"; import { FileHistory } from "./file-history"; import { FileManager } from "./file-manager"; import { ConfigManager } from "./config-manager"; import { CustomTray } from "./tray"; import ngrok from "ngrok"; import { NodeREDApp, NPM_COMMAND } from "./node-red"; import log from "./log"; import fs from "fs"; import { pathToFileURL } from "url"; import prompt from "electron-prompt"; import semver from "semver"; // import rebuild from "@node-red-desktop/electron-rebuild"; import nodegen from "node-red-nodegen"; import "./debug"; process.env.NODE_ENV = "production"; const macOS = process.platform === "darwin"; const FILE_HISTORY_SIZE = 10; const HELP_NODERED_URL = "https://nodered.org/"; const HELP_NODERED_DESKTOP_URL = "https://sakazuki.github.io/node-red-desktop/"; const HELP_AUTHOR_URL = "https://node-red.exhands.org/"; const NGROK_INSPECT_URL = "http://localhost:4040"; export interface AppStatus { editorEnabled: boolean; ngrokUrl: string; ngrokStarted: boolean; modified: boolean; newfileChanged: boolean; locale: string; userDir: string; credentialSecret: string; currentFile: string; projectsEnabled: boolean; nodesExcludes: string[]; autoCheckUpdate: boolean; allowPrerelease: boolean; autoDownload: boolean; hideOnMinimize: boolean; openLastFile: boolean; nodeCommandEnabled: boolean; npmCommandEnabled: boolean; httpNodeAuth: {user: string, pass: string}; selection: {nodes: any[]}; listenPort: string; debugOut: boolean; } type UserSettings = { userDir: string; credentialSecret: string; projectsEnabled: boolean; nodesExcludes: string; autoCheckUpdate: boolean; allowPrerelease: boolean; autoDownload: boolean; hideOnMinimize: boolean; openLastFile: boolean; httpNodeAuth: {user: string, pass: string}; listenPort: string; debugOut: boolean; } class BaseApplication { private mainWindow: CustomBrowserWindow | null = null; private customAutoUpdater: CustomAutoUpdater | null = null; private appMenu: AppMenu | null = null; private tray: CustomTray | null = null; private app: App; private loadingURL: string = pathToFileURL( path.join(__dirname, "..", "loading.html") ).href; private settingsURL: string = pathToFileURL( path.join(__dirname, "..", "settings.html") ).href; private config: ConfigManager; private fileManager: FileManager; private fileHistory: FileHistory; private status: AppStatus; private red: NodeREDApp; constructor(app: App) { this.app = app; this.app.on("ready", this.onReady.bind(this)); this.app.on("activate", this.onActivated.bind(this)); this.app.on("window-all-closed", this.onWindowAllClosed.bind(this)); this.config = new ConfigManager(app.name); this.fileManager = new FileManager(this.config); this.fileHistory = new FileHistory(FILE_HISTORY_SIZE, ipcMain); this.status = { editorEnabled: false, ngrokUrl: "", ngrokStarted: false, modified: false, newfileChanged: false, locale: this.config.data.locale, userDir: this.config.data.userDir, credentialSecret: this.config.data.credentialSecret, currentFile: this.getStartFlow(), projectsEnabled: this.config.data.projectsEnabled, nodesExcludes: this.config.data.nodesExcludes, autoCheckUpdate: this.config.data.autoCheckUpdate, allowPrerelease: this.config.data.allowPrerelease, autoDownload: this.config.data.autoDownload, hideOnMinimize: this.config.data.hideOnMinimize, openLastFile: this.config.data.openLastFile, nodeCommandEnabled: false, npmCommandEnabled: false, httpNodeAuth: this.config.data.httpNodeAuth, selection: {nodes: []}, listenPort: this.config.data.listenPort, debugOut: this.config.data.debugOut }; this.appMenu = new AppMenu(this.status, this.fileHistory); this.red = new NodeREDApp(this.status); ipcMain.on("browser:focus", this.setTitle.bind(this)); ipcMain.on("browser:show", () => this.getBrowserWindow().show()); ipcMain.on("browser:hide", () => this.getBrowserWindow().hide()); ipcMain.on("browser:minimize", (event: Electron.Event) => this.onMinimize(event) ); ipcMain.on("browser:before-close", (event: Electron.Event) => this.onBeforeClose(event) ); ipcMain.on("browser:closed", this.onClosed.bind(this)); ipcMain.on("browser:restart", this.onRestart.bind(this)); ipcMain.on("browser:relaunch", this.onRelaunch.bind(this)); // @ts-ignore ipcMain.on("browser:message", (text: string) => this.onMessage(text)); ipcMain.on("browser:loading", this.onLoading.bind(this)); // @ts-ignore ipcMain.on("browser:go", (url: string) => this.go(url)); ipcMain.on("browser:update-title", this.setTitle.bind(this)); // @ts-ignore ipcMain.on("browser:progress", (progress: number) => this.setProgress(progress)); ipcMain.on("history:update", this.updateMenu.bind(this)); ipcMain.on("menu:update", this.updateMenu.bind(this)); // @ts-ignore ipcMain.on("window:new", (url: string) => this.onNewWindow(url)); ipcMain.on("auth:signin", (event: Electron.Event, args: any) => this.onSignIn(event, args) ); ipcMain.on("auth:signedin", (event: Electron.Event, args: any) => this.onSignedIn(event, args) ); ipcMain.on("editor:started", (event: Electron.Event, args: any) => this.onEditorStarted(event, args) ); ipcMain.on("nodes:change", (event: Electron.Event, args: {dirty: boolean}) => this.onNodesChange(event, args) ); ipcMain.on("view:selection-changed",(event: Electron.Event, selection: {nodes: any[]}) => this.onSelectionChanged(event, selection) ) ipcMain.on("file:new", this.onFileNew.bind(this)); // @ts-ignore ipcMain.on("file:open", this.onFileOpen.bind(this)); ipcMain.on("file:clear-recent", this.onFileClearHistory.bind(this)); ipcMain.on("file:save", this.onFileSave.bind(this)); ipcMain.on("file:save-as", this.onFileSaveAs.bind(this)); ipcMain.on("file:open-userdir", this.onUserdirOpen.bind(this)); ipcMain.on("file:open-logfile", this.onLogfileOpen.bind(this)); ipcMain.on("settings", this.onSettings.bind(this)); ipcMain.on("endpoint:local", this.onEndpointLocal.bind(this)); ipcMain.on("endpoint:local-admin", this.onEndpointLocalAdmin.bind(this)); ipcMain.on("endpoint:public", this.onEndpointPublic.bind(this)); ipcMain.on("ngrok:connect", this.onNgrokConnect.bind(this)); ipcMain.on("ngrok:disconnect", this.onNgrokDisconnect.bind(this)); ipcMain.on("ngrok:inspect", this.onNgrokInspect.bind(this)); // @ts-ignore ipcMain.on("view:reload", (item: MenuItem, focusedWindow: BrowserWindow) => this.onViewReload(item, focusedWindow) ); ipcMain.on( "view:set-locale", // @ts-ignore (item: MenuItem, focusedWindow: BrowserWindow) => this.onSetLocale(item, focusedWindow) ); ipcMain.on("help:node-red", () => { this.onHelpWeb(HELP_NODERED_URL); }); ipcMain.on("help:node-red-desktop", () => { this.onHelpWeb(HELP_NODERED_DESKTOP_URL); }); ipcMain.on("help:author", () => { this.onHelpWeb(HELP_AUTHOR_URL); }); ipcMain.on("help:check-updates", this.onHelpCheckUpdates.bind(this)); ipcMain.on("help:version", this.onHelpVersion.bind(this)); // @ts-ignore ipcMain.on("dev:tools", (item: MenuItem, focusedWindow: BrowserWindow) => this.onToggleDevTools(item, focusedWindow) ); ipcMain.on("settings:loaded", this.onSettingsLoaded.bind(this)); ipcMain.on("settings:update", (event: Electron.Event, args: UserSettings) => this.onSettingsSubmit(event, args) ); ipcMain.on("settings:cancel", this.onSettingsCancel.bind(this)); ipcMain.on("node:addLocal", this.onNodeAddLocal.bind(this)); ipcMain.on("node:addRemote", this.onNodeAddRemote.bind(this)); // ipcMain.on("node:rebuild", this.onNodeRebuild.bind(this)); ipcMain.on("node:nodegen", this.onNodeGenerator.bind(this)); // @ts-ignore ipcMain.on("dialog:show", (type: "success" | "error" | "info", message: string, timeout?: number) => this.showRedNotify(type, message, timeout) ); ipcMain.on("ext:debugOut", this.onDebugOut.bind(this)) } private create() { const options: BrowserWindowConstructorOptions = { webPreferences: { nodeIntegration: false, nativeWindowOpen: true, contextIsolation: true, preload: path.join(__dirname, "preload.js"), defaultFontFamily: { standard: "Meiryo UI", serif: "MS PMincho", sansSerif: "Meiryo UI", monospace: "MS Gothic" } }, title: app.name, fullscreenable: true, width: 1280, height: 960, minWidth: 500, minHeight: 200, acceptFirstMouse: true, autoHideMenuBar: true, // titleBarStyle: "hidden", icon: path.join(__dirname, "..", "images", "favicon.ico") }; const savedOption = this.config.data.windowBounds || {}; Object.assign(options, savedOption); this.mainWindow = new CustomBrowserWindow(options, this.loadingURL); } private getStartFlow(): string { const firstArg = app.isPackaged ? 1 : 2; const args = process.argv[firstArg]; if (args && fs.existsSync(args)) return args; if (this.config.data.openLastFile) { const lastFile = this.config.data.recentFiles[0]; if (fs.existsSync(lastFile)) return lastFile; } return this.fileManager.createTmp(); } private onReady() { try { i18n.setLocale(this.config.data.locale); } catch (err) { log.error(err); } this.status.locale = i18n.getLocale(); this.create(); this.fileHistory.load(this.config.data.recentFiles); this.customAutoUpdater = new CustomAutoUpdater( this.getBrowserWindow(), this.status ); this.tray = new CustomTray(this.red); this.red.startRED(); } private onActivated() { if (this.mainWindow === null) { this.create(); this.go(this.red.getAdminUrl()); } } private onWindowAllClosed() { if (!macOS) this.app.quit(); } private saveConfig() { this.config.data.recentFiles = this.fileHistory.history; this.config.data.windowBounds = this.getBrowserWindow().getBounds(); this.config.data.locale = this.status.locale; this.config.data.userDir = this.status.userDir; this.config.data.credentialSecret = this.status.credentialSecret; this.config.data.projectsEnabled = this.status.projectsEnabled; this.config.data.nodesExcludes = this.status.nodesExcludes; this.config.data.autoCheckUpdate = this.status.autoCheckUpdate; this.config.data.allowPrerelease = this.status.allowPrerelease; this.config.data.autoDownload = this.status.autoDownload; this.config.data.hideOnMinimize = this.status.hideOnMinimize; this.config.data.openLastFile = this.status.openLastFile; this.config.data.httpNodeAuth = this.status.httpNodeAuth; this.config.data.listenPort = this.status.listenPort; this.config.data.debugOut = this.status.debugOut; this.config.save(); } private usingTmpFile() { return this.fileManager.test(this.status.currentFile); } private checkEphemeralFile() { if (this.usingTmpFile()) { return this.status.newfileChanged; } else { return this.status.modified; } } private leavable(): boolean { if (!this.checkEphemeralFile()) return true; const res = dialog.showMessageBoxSync(this.getBrowserWindow(), { type: "question", title: i18n.__("dialog.confirm"), message: i18n.__("dialog.closeMsg"), buttons: [ i18n.__("dialog.yes"), i18n.__("dialog.no"), i18n.__("dialog.cancel") ] }); if (res === 0) { if (!this.status.projectsEnabled && this.usingTmpFile()) { return this.onFileSaveAs(); } else { return this.onFileSave(); } } else if (res === 1) { return true; } else { return false; } } private onMinimize(event?: Electron.Event) { if (!this.status.hideOnMinimize) return; event!.preventDefault(); this.getBrowserWindow().hide(); } private isSettingsPage() { const url = path.parse(this.getBrowserWindow().webContents.getURL()); return (url.base === path.parse(this.settingsURL).base) } private onBeforeClose(event?: Electron.Event) { if (this.isSettingsPage()) { this.unsetBeforeUnload(); } else if (this.leavable()) { this.unsetBeforeUnload(); this.saveConfig(); } else { if (event) event.preventDefault(); } } private unsetBeforeUnload() { this.getBrowserWindow().webContents.send("force:reload"); } private onClosed() { this.fileManager.clearTmp(); this.tray?.destroy(); this.mainWindow = null; } private onRestart() { this.onBeforeClose(); this.customAutoUpdater!.quitAndInstall(); app.quit(); } private onRelaunch() { this.onBeforeClose(); app.relaunch(); app.quit(); } private setLangUrl(url: string) { const current = urlparse.parse(url); current.search = "?setLng=" + this.status.locale; return urlparse.format(current); } private setTitle() { this.getBrowserWindow().setTitle(this.red.windowTitle()); } private setProgress(progress: number){ this.getBrowserWindow().setProgressBar(progress); } private onLoading() { return this.getBrowserWindow().loadURL(this.loadingURL); } private async go(url: string) { if (!url) throw new Error("no url") await this.getBrowserWindow().loadURL(this.setLangUrl(url)); this.setTitle(); } private onMessage(text: string) { // this.getBrowserWindow().webContents.send("message", text); const msg: Electron.NotificationConstructorOptions = { title: app.name, body: text, closeButtonText: i18n.__("dialog.ok") }; const notification = new Notification(msg); notification.show(); } private onSignIn(event: Electron.Event, args: any) {} private onSignedIn(event: Electron.Event, args: any) {} private async checkNodeVersion() { try { const res: execResult = await this.red.exec.run("node", ["-v"], {}, false); log.info(">>> Check node.js version", res); if (res.code === 0) { const range = semver.validRange(process.version.split(".")[0]); if (!range) throw new Error('Invalid version'); return semver.satisfies(res.stdout.trim(), range); } } catch (err) { log.error(err); } return false; } private async checkNpmVersion() { try { const res: execResult = await this.red.exec._run(NPM_COMMAND, ["-v"], {}, false); log.info(">>> Check npm version", res); return (res.code === 0); } catch (err) { log.error(err); } return false; } private async onEditorStarted(event: Electron.Event, args: any) { this.status.editorEnabled = true; this.status.nodeCommandEnabled = await this.checkNodeVersion(); this.status.npmCommandEnabled = await this.checkNpmVersion(); ipcMain.emit("menu:update"); } private onNodesChange(event: Electron.Event, args: {dirty: boolean}) { this.status.modified = args.dirty; if (args.dirty) this.status.newfileChanged = true; } private onSelectionChanged(event: Electron.Event, selection: {nodes: any[]}){ this.status.selection = selection; this.appMenu!.setMenuItemEnabled("tools.nodegen", selection && selection.nodes && selection.nodes[0] && selection.nodes[0].type === "function" && !!this.red.getNode(selection.nodes[0].id)) } private updateMenu() { this.appMenu!.setup(); } private async openAny(url: string) { await shell.openExternal(url); } private onNewWindow(url: string) { this.openAny(url); } private onFileNew() { const file = this.fileManager.createTmp(); this.status.newfileChanged = false; this.setFlowFileAndRestart(file); } private getBrowserWindow() { if (this.mainWindow === null) { this.create(); this.go(this.red.getAdminUrl()); } return this.mainWindow!.getBrowserWindow()!; } private onFileOpen(file: string = "") { if (!file) { const files = dialog.showOpenDialogSync(this.getBrowserWindow(), { title: i18n.__("dialog.openFlowFile"), properties: ["openFile"], defaultPath: path.dirname(this.status.currentFile), filters: [ { name: "flows file", extensions: ["json"] }, { name: "ALL", extensions: ["*"] } ] }); if (files) file = files[0]; } if (file) { this.fileHistory.add(file); this.setFlowFileAndRestart(file); } } private onFileSave(): boolean { this.getBrowserWindow().webContents.send("editor:deploy"); return true; } private onFileSaveAs(): boolean { const savefile = dialog.showSaveDialogSync(this.getBrowserWindow(), { title: i18n.__("dialog.saveFlowFile"), defaultPath: path.dirname(this.status.currentFile), filters: [ { name: "flows file", extensions: ["json"] }, { name: "ALL", extensions: ["*"] } ] }); if (!savefile) return false; const oldfile = this.status.currentFile; this.red.setFlowFile(savefile); if (this.status.modified) { this.onFileSave(); } else { this.fileManager.saveAs(oldfile, savefile); } this.fileHistory.add(savefile); return true; } private onFileClearHistory() { this.fileHistory.clear(); } private setFlowFileAndRestart(file: string) { if (!this.leavable()) return; this.unsetBeforeUnload(); this.red.setFlowFileAndRestart(file); } private onUserdirOpen() { this.openAny(pathToFileURL(this.status.userDir).href); } private onLogfileOpen() { this.openAny(pathToFileURL(log.transports.file.file!).href); } private onSettings() { return this.getBrowserWindow().loadURL(this.settingsURL); } private onEndpointLocal() { this.openAny(this.red.getHttpUrl()); } private onEndpointLocalAdmin() { this.openAny(this.red.getAdminUrl()); } private async onNgrokConnect() { try { const ngrokOptions: ngrok.INgrokOptions = { proto: "http", addr: this.red.listenPort, binPath: (bin: string) => bin.replace("app.asar", "app.asar.unpacked") }; if (process.env.NRD_NGROK_START_ARGS) { ngrokOptions.startArgs = process.env.NRD_NGROK_START_ARGS } const url = await ngrok.connect(ngrokOptions); this.status.ngrokUrl = url; this.status.ngrokStarted = true; ipcMain.emit("menu:update"); const body = `conntcted with <a href="${this.status.ngrokUrl}" target="_blank">${this.status.ngrokUrl}</a>`; this.showRedNotify("success", body); } catch (err) { log.error(err); this.showRedNotify("error", JSON.stringify(err)); } } private async onNgrokDisconnect() { try { await ngrok.disconnect(this.status.ngrokUrl); await ngrok.disconnect( this.status.ngrokUrl.replace("https://", "http://") ); this.showRedNotify("success", `disconnected ${this.status.ngrokUrl}`, 3000); this.status.ngrokUrl = ""; ipcMain.emit("menu:update"); } catch (err) { log.error(err); } } private onEndpointPublic() { if (!this.status.ngrokUrl) return; this.openAny(this.status.ngrokUrl); } private onNgrokInspect() { if (this.status.ngrokStarted) this.openAny(NGROK_INSPECT_URL); } private async onViewReload(item: MenuItem, focusedWindow: BrowserWindow) { if (focusedWindow) { await focusedWindow.loadURL(focusedWindow.webContents.getURL()); this.setTitle(); } } private onSetLocale(item: MenuItem, focusedWindow: BrowserWindow) { this.status.locale = item.label; if (focusedWindow) { const url = this.setLangUrl(focusedWindow.webContents.getURL()); focusedWindow.loadURL(url); } } private onHelpWeb(url: string) { shell.openExternal(url); } private onHelpCheckUpdates() { this.customAutoUpdater!.checkUpdates(true); } private onHelpVersion() { const body = ` Name: ${app.name} ${i18n.__("version.version")}: ${app.getVersion()} ${this.customAutoUpdater!.info()} ${this.red.info()} ${this.fileManager.info()} `.replace(/^\s*/gm, ""); dialog.showMessageBoxSync(this.getBrowserWindow(), { title: i18n.__("menu.version"), type: "info", message: app.name, detail: body, buttons: [i18n.__("dialog.ok")], noLink: true }); } private showRedNotify(type: "success" | "error" | "info", message: string, timeout?: number) { this.getBrowserWindow().webContents.send("red:notify", type, message, timeout); } private onToggleDevTools(item: MenuItem, focusedWindow: BrowserWindow) { if (focusedWindow) focusedWindow.webContents.toggleDevTools(); } private onSettingsLoaded() { this.getBrowserWindow().webContents.send("settings:set", this.config.data); } private onSettingsSubmit(event: Electron.Event, args: UserSettings) { this.status.userDir = args.userDir; this.status.credentialSecret = args.credentialSecret; this.status.nodesExcludes = args.nodesExcludes.trim().split("\n"); this.status.projectsEnabled = args.projectsEnabled; this.status.autoCheckUpdate = args.autoCheckUpdate; this.status.allowPrerelease = args.allowPrerelease; this.status.autoDownload = args.autoDownload; this.status.hideOnMinimize = args.hideOnMinimize; this.status.openLastFile = args.openLastFile; this.status.httpNodeAuth = args.httpNodeAuth; this.status.listenPort = args.listenPort; this.saveConfig(); app.relaunch(); app.quit(); } private onSettingsCancel() { this.go(this.red.getAdminUrl()); } private showShade() { this.getBrowserWindow().webContents.send("shade:show"); this.appMenu!.enabled = false; } private loadingShade() { this.getBrowserWindow().webContents.send("shade:start"); } private hideShade() { this.appMenu!.enabled = true; this.getBrowserWindow().webContents.send("shade:hide"); } private async onNodeAddLocal() { this.showShade(); const dirs = dialog.showOpenDialogSync(this.getBrowserWindow(), { title: i18n.__("dialog.openNodeDir"), properties: ["openDirectory"], defaultPath: this.status.userDir }); if (dirs) { this.loadingShade(); await this.red.execNpmLink(dirs[0]); } this.hideShade(); } private async onNodeAddRemote() { this.showShade(); const res = await prompt({ width: this.getBrowserWindow().getBounds().width * 0.5, height: 200, resizable: true, title: i18n.__("dialog.npmInstall"), label: i18n.__("dialog.npmInstallDesc"), value: "", inputAttrs: { type: "text", required: true }, useHtmlLabel: true, minimizable: false, maximizable: false }, this.getBrowserWindow()); if (res) { this.loadingShade(); await this.red.execNpmInstall(res); } this.hideShade(); } // private async onNodeRebuild() { // log.info(">>> Rebuild Start") // this.showShade(); // try { // this.loadingShade(); // await rebuild({ // buildPath: this.status.userDir, // electronVersion: process.versions.electron // }); // log.info(">>> Rebuild success"); // } catch(err) { // log.error(">>> Rebuild failed", err); // this.showRedNotify("error", JSON.stringify(err)); // } // this.hideShade(); // } private async onNodeGenerator() { const node = this.red.getNode(this.status.selection.nodes[0].id); if (!node){ dialog.showMessageBox(this.getBrowserWindow(), { title: i18n.__("dialog.nodegen"), type: "info", message: app.name, detail: i18n.__("dialog.nodenotfound"), buttons: [i18n.__("dialog.ok")], noLink: true }); return; } const data = { dst: this.status.userDir, src: [ `// name: ${node.name || "no name"}`, `// outputs: ${node.wires.length}`, node.func, "" ].join("\n") }; const options = {}; log.info(">>> nodegen Start", data) this.showShade(); try { this.loadingShade(); const result = await nodegen.function2node(data, options) log.info(">>> nodegen success", result); this.openAny(pathToFileURL(result).href); // await this.red.execNpmLink(result); } catch(err) { log.error(">>> nodegen failed", err); this.showRedNotify("error", JSON.stringify(err)); } this.hideShade(); } private onDebugOut() { this.status.debugOut = !this.status.debugOut console.log(this.status) } } const main: BaseApplication = new BaseApplication(app);
the_stack
import { v4 } from 'uuid'; import { EventBus } from './core/modules/EventBus'; import { Api } from './modules/Api/Api'; import { Data } from './modules/Data/Data'; import { ApiClient } from './modules/ApiClient/ApiClient'; import { PushServiceDefault, PushServiceSafari } from './services/PushService/PushService'; import { Popup } from './features/Popup/Popup'; import { SubscriptionSegmentsWidget } from './features/SubscriptionSegmentsWidget/SubscriptionSegmentsWidget'; import { SubscriptionPromptWidget } from './features/SubscriptionPromptWidget/SubscriptionPromptWidget'; import { ISubscriptionPromptWidgetParams } from './features/SubscriptionPromptWidget/SubscriptionPromptWidget.types'; import * as CONSTANTS from './constants'; import { IMapResponse } from './modules/ApiClient/ApiClient.types'; import {clearLocationHash} from './functions'; import {PlatformChecker} from './modules/PlatformChecker'; import { Logger } from './logger' import FacebookModule from './modules/FacebookModule'; import {InApps} from './modules/InApps/InApps'; import {keyValue, log as logStorage, message as messageStorage} from './storage'; import InboxMessagesModel from './models/InboxMessages'; import InboxMessagesPublic from './modules/InboxMessagesPublic'; import { IPushService } from './services/PushService/PushService.types'; export default class Pushwoosh { public ready: boolean = false; private readonly eventBus: EventBus; private readonly data: Data; private readonly apiClient: ApiClient; private isCommunicationDisabled?: boolean; public readonly api: Api; public readonly subscriptionSegmentWidget: SubscriptionSegmentsWidget; public readonly subscriptionPromptWidget: SubscriptionPromptWidget; public driver: IPushService; private platformChecker: PlatformChecker; public subscribeWidgetConfig: ISubscribeWidget; public inboxWidgetConfig: IInboxWidget; public subscribePopupConfig: any; public InApps: InApps; // Inbox messages public interface public pwinbox: InboxMessagesPublic; private inboxModel: InboxMessagesModel; constructor() { this.eventBus = new EventBus(); this.data = new Data(); this.apiClient = new ApiClient(this.data); this.api = new Api(this.eventBus, this.data, this.apiClient); this.platformChecker = new PlatformChecker() this.inboxModel = new InboxMessagesModel(this.eventBus, this.data, this.api); this.pwinbox = new InboxMessagesPublic(this.data, this.api, this.inboxModel); // Bindings this.onServiceWorkerMessage = this.onServiceWorkerMessage.bind(this); const popup = new Popup( 'subscription-segments', () => this.eventBus.dispatchEvent('hide-subscription-widget', {}), { position: 'top' } ); // need inject this because need call subscribe method // can't use command bus, because need call synchronically this.subscriptionSegmentWidget = new SubscriptionSegmentsWidget( this.eventBus, this.data, this.apiClient, this.api, popup, this ); // create subscription prompt widget this.subscriptionPromptWidget = new SubscriptionPromptWidget(this.eventBus, this); } /** * Add Web SDK Event Handler. * Alias to addEventHandler method of EventBus module. * * @public * @readonly * * @param {string} name - name of Web SDK event. * @param {function} handler - handler of Web SDK event. * * @returns {void} */ public addEventHandler = <Name extends EventName>( name: Name, handler: EventHandlerMap[Name], ): void => this.eventBus.addEventHandler(name, handler); /** * Remove Web SDK Event Handler. * Alias to removeEventHandler method of EventBus module. * * @public * @readonly * * @param {string} name - name of Web SDK event. * @param {function} handler - handler of Web SDK event. * * @returns {void} */ public removeEventHandler = <Name extends EventName>( name: Name, handler: EventHandlerMap[Name], ): void => this.eventBus.removeEventHandler(name, handler); /** * Dispatch Web SDK Event. * Alias to dispatchEvent method of EventBus module. * * @public * @readonly * * @param {string} name - name of Web SDK event. * @param {object} payload - event payload. * * @returns {string} - event id. */ public dispatchEvent = <Name extends EventName>( name: Name, payload: Omit<Parameters<EventHandlerMap[Name]>[0], 'eventId'> & { eventId?: string }, ): string => this.eventBus.dispatchEvent(name, payload); /** * Method that puts the stored error/info messages to browser console. * @type {{showLog: (() => Promise<any>); showKeyValues: (() => Promise<any>); showMessages: (() => Promise<any>)}} */ public debug = { async showLog() { const items = await logStorage.getAll(); console.log(items); }, async showKeyValues() { const items = await keyValue.getAll(); console.log(items); }, async showMessages() { const items = await messageStorage.getAll(); items.forEach((i: any) => console.log(i)); } }; /** * Polymorph PW method. * Can get array in format [string, params | callback] or function. * * // with callback: * Pushwoosh.push(['onNotificationClick', function(api, payload) { * // click on the notificationn * }]); * * // with function: * Pushwoosh.push(function(api) { * // this is a bit easier way to subscribe to onReady * }); * * // with params: * // initiates Pushwoosh service and notification subscription * Pushwoosh.push(['init', { * applicationCode: 'XXXXX-XXXXX', * // see more about params in documentation * // https://docs.pushwoosh.com/docs/web-push-sdk-30#section-integration * }]); * * @param command */ public push(command: PWInput) { if (typeof command === 'function') { this.subscribeToLegacyEvents('onReady', command); return; } if (!Array.isArray(command)) { throw new Error('Invalid command!'); } switch (command[0]) { case 'init': this.initialize(command[1]); break; case CONSTANTS.EVENT_ON_LOAD: case CONSTANTS.EVENT_ON_READY: case CONSTANTS.EVENT_ON_REGISTER: case CONSTANTS.EVENT_ON_SUBSCRIBE: case CONSTANTS.EVENT_ON_UNSUBSCRIBE: case CONSTANTS.EVENT_ON_SW_INIT_ERROR: case CONSTANTS.EVENT_ON_PUSH_DELIVERY: case CONSTANTS.EVENT_ON_NOTIFICATION_CLICK: case CONSTANTS.EVENT_ON_NOTIFICATION_CLOSE: case CONSTANTS.EVENT_ON_CHANGE_COMMUNICATION_ENABLED: case CONSTANTS.EVENT_ON_PUT_NEW_MESSAGE_TO_INBOX_STORE: case CONSTANTS.EVENT_ON_UPDATE_INBOX_MESSAGES: case CONSTANTS.EVENT_ON_SHOW_NOTIFICATION_PERMISSION_DIALOG: case CONSTANTS.EVENT_ON_HIDE_NOTIFICATION_PERMISSION_DIALOG: case CONSTANTS.EVENT_ON_SHOW_SUBSCRIPTION_WIDGET: case CONSTANTS.EVENT_ON_HIDE_SUBSCRIPTION_WIDGET: case CONSTANTS.EVENT_ON_PERMISSION_DENIED: case CONSTANTS.EVENT_ON_PERMISSION_PROMPT: case CONSTANTS.EVENT_ON_PERMISSION_GRANTED: this.subscribeToLegacyEvents(command[0], command[1]); break; default: throw new Error('Unknown command!'); } } /** * Method initializes the permission dialog on the device * and registers through the API in case the device hasn't been registered before. * @returns {Promise<void>} */ public async subscribe(isForceSubscribe = true): Promise<void> { if (this.isCommunicationDisabled) { Logger.error('Communication is disabled!'); } const isPermissionDefault = this.driver.checkIsPermissionDefault(); // if permission granted need ask permission for send notifications if (isPermissionDefault) { // emit event when permission dialog show this.eventBus.dispatchEvent('show-notification-permission-dialog', {}); // all action before this MUST be a synchrony because // in new release in ff 72 we must call this event by user // ask permission // ask permissions only show prompt window, not register device for send push notifications await this.driver.askPermission(); const permission = this.driver.getPermission(); // emit event when permission dialog hide with permission state this.eventBus.dispatchEvent('hide-notification-permission-dialog', { permission }); } const permission = this.driver.getPermission(); const isManualUnsubscribed = await this.data.getStatusManualUnsubscribed(); const isDeviceRegister = await this.api.checkDeviceSubscribeForPushNotifications(false); // if permission granted emit event and register device into pushwoosh if (permission === CONSTANTS.PERMISSION_GRANTED) { this.eventBus.dispatchEvent('permission-granted', {}); const needSubscribe = isForceSubscribe || !isManualUnsubscribed; if (needSubscribe && !isDeviceRegister) { await this.driver.subscribe(); } this.eventBus.dispatchEvent('subscribe', {}); return; } // if permission denied emit event if (permission === CONSTANTS.PERMISSION_DENIED) { this.eventBus.dispatchEvent('permission-denied', {}); if (isDeviceRegister) { await this.driver.unsubscribe(); } return; } } /** * Unsubscribe device. * @returns {Promise<void>} */ public async unsubscribe() { try { await this.driver.unsubscribe(); } catch (error) { Logger.error(error, 'Error occurred during the unsubscribe'); } } /** * force subscribe if there was a manual unsubscribe * @returns {Promise<void>} */ public async forceSubscribe() { await this.subscribe(true); } /** * Check device's registration status * @returns {boolean} */ public isDeviceRegistered(): boolean { return localStorage.getItem(CONSTANTS.KEY_DEVICE_REGISTRATION_STATUS) === CONSTANTS.DEVICE_REGISTRATION_STATUS_REGISTERED; } public isDeviceUnregistered(): boolean { return localStorage.getItem(CONSTANTS.KEY_DEVICE_REGISTRATION_STATUS) === CONSTANTS.DEVICE_REGISTRATION_STATUS_UNREGISTERED; } /** * Check device's subscription status * @returns {Promise<boolean>} */ public async isSubscribed(): Promise<boolean> { return this.api.checkDeviceSubscribeForPushNotifications(); } /** * Check current communication state * @returns {Promise<boolean>} */ public async isCommunicationEnabled() { const isCommunicationDisabled = await this.data.getStatusCommunicationDisabled(); return !isCommunicationDisabled; } /** * Send "GDPRConsent" postEvent and depends on param "isEnabled" * device will be registered/unregistered from all communication channels. * @param {boolean} isEnabled * @returns {Promise<void>} */ public async setCommunicationEnabled(isEnabled: boolean = true) { const deviceType = await this.data.getDeviceType(); const isPermissionGranted = this.driver.checkIsPermissionGranted(); await this.data.setStatusCommunicationDisabled(!isEnabled); if (isEnabled) { await this.data.setStatusDropAllData(false); if (isPermissionGranted) { await this.api.registerDevice(); } } else { await this.api.unregisterDevice(); } this.eventBus.dispatchEvent('change-enabled-communication', { isEnabled }); await this.api.postEvent(CONSTANTS.EVENT_GDPR_CONSENT, { channel: isEnabled, device_type: deviceType, }); } /** * Send "GDPRDelete" postEvent and remove all device device data from Pushwoosh. * @returns {Promise<void>} */ public async removeAllDeviceData() { const deviceType = await this.data.getDeviceType(); await this.api.postEvent(CONSTANTS.EVENT_GDPR_DELETE, { status: true, device_type: deviceType }); await this.api.deleteDevice(); await this.data.clearAll(); await this.data.setStatusDropAllData(true); } /** * Method returns hardware id. * @returns {Promise<string>} */ public async getHWID(): Promise<string> { return await this.data.getHwid(); } /** * Method returns push token. * @returns {Promise<string>} */ public async getPushToken(): Promise<string | undefined> { const { pushToken } = await this.data.getTokens(); return pushToken; } /** * Method returns userId * @returns {Promise<string | null>} */ public async getUserId(): Promise<string | undefined> { return await this.data.getUserId(); } /** * Method returns an object with all params. * @returns {Promise<IPWParams>} */ public async getParams() { return await this.api.getParams(); } /** * Method returns true if notifications available. * @returns {boolean} */ public isAvailableNotifications() { return this.platformChecker.isAvailableNotifications; } public async sendStatisticsVisitedPage() { const { document: { title }, location: { origin, pathname, href } } = window; await this.api.pageVisit({ title, url_path: `${origin}${pathname}`, url: href }); } public async isEnableChannels(): Promise<boolean> { const features = await this.data.getFeatures(); const channels = features && features['channels']; return Array.isArray(channels) && !!channels.length; } private async initialize(params: IInitParams) { // step 0: base logger configuration const manualDebug = localStorage.getItem(CONSTANTS.MANUAL_SET_LOGGER_LEVEL); Logger.setLevel(manualDebug || params.logLevel || 'error'); // step 0: if not available push notifications -> exit if (!this.platformChecker.isAvailableNotifications) { return; } // step 1: check application code const applicationCode = await this.data.getApplicationCode(); if (!params.applicationCode) { throw new Error('Can\'t find application code!'); } const notSavedApplicationCode = !applicationCode; const isChangeApplicationCode = applicationCode && applicationCode !== params.applicationCode; // if have not old application code or application code was change => remove all info about init params and subscription if (notSavedApplicationCode || isChangeApplicationCode) { await this.data.clearAll(); await this.data.setApplicationCode(params.applicationCode); } // step 2: check hwid const hwid = await this.data.getHwid(); if (!hwid) { const id = params.applicationCode + '_' + v4(); await this.data.setHwid(id); } else { await this.api.checkDevice(); } // step 3: add info about platform await this.data.setDeviceType(this.platformChecker.getPlatformType()); await this.data.setDeviceModel(this.platformChecker.getBrowserVersion()); await this.data.setLanguage(params.tags && params.tags.Language || navigator.language); // step 4: set configuration info if (params.pushwooshUrl) { await this.data.setApiEntrypoint(params.pushwooshUrl); } await this.data.setSdkVersion(__VERSION__); // step 5: get remote config const config = await this.api.getConfig([ 'page_visit', 'vapid_key', 'web_in_apps', 'events', 'subscription_prompt' ]); this.onGetConfig(config && config.features); // set default configs this.subscribeWidgetConfig = { enable: false, ...params.subscribeWidget }; this.inboxWidgetConfig = { enable: false, ...params.inboxWidget }; this.subscribePopupConfig = { enable: false, ...params.subscribePopup }; // step 6: check communication disabled this.isCommunicationDisabled = await this.data.getStatusCommunicationDisabled(); await this.open(); // step 7: check user id const userIdWasChange = await this.data.getStatusUserIdWasChanged(); if (params.userId && params.userId !== 'user_id' && !userIdWasChange) { await this.api.registerUser(params.userId); } // set tags if (params.tags) { this.api.setTags(params.tags); } // step 8: init submodules module in app (need before push notification because in apps use in subscription segments widget) const inAppsConfig: IInitParams['inApps'] = { enable: config.features.web_in_apps && config.features.web_in_apps.enabled, ...params.inApps, }; // step 9: init submodules module in app (need before push notification because in apps use in subscription segments widget) await this.initInApp(inAppsConfig); // step 10: init push notification if (this.platformChecker.isAvailableNotifications) { await this.initPushNotifications(params); } // step 11: init submodules (inbox, facebook) try { await this.inboxModel.updateMessages(); } catch (error) { Logger.write('error', error); } try { await this.initFacebook(params); } catch (error) { Logger.write('error', error); } // step 12: ready this.ready = true; this.eventBus.dispatchEvent('ready', {}); const delayedEvent = await this.data.getDelayedEvent(); if (delayedEvent) { const { type, payload } = delayedEvent; await this.emitLegacyEventsFromServiceWorker(type, payload); await this.data.setDelayedEvent(null); } if ('serviceWorker' in navigator) { // @ts-ignore navigator.serviceWorker.onmessage = this.onServiceWorkerMessage; } localStorage.setItem('pushwoosh-websdk-status', 'init'); // Dispatch 'pushwoosh.initialized' event document.dispatchEvent(new CustomEvent('pushwoosh.initialized', { detail: { pw: this } })); // send push stat only in safari, because safari haven't service worker // in other browsers stat will be send in service worker if (this.platformChecker.isSafari) { const hashReg: any = /#P(.*)/; const hash = decodeURIComponent(document.location.hash); if (hashReg.test(hash)) { this.api .pushStat(hashReg.exec(hash)[1]) .then(clearLocationHash); } } } /** * Default process during PW initialization. * Init API. Subscription to notifications. * Emit delayed events. * @returns {Promise<void>} */ private async defaultProcess(initParams: IInitParams) { const permission = this.driver.getPermission(); if (permission === 'granted') { await this.data.setLastPermissionStatus(permission); } const isCommunicationDisabled = await this.data.getStatusCommunicationDisabled(); const isDropAllData = await this.data.getStatusDropAllData(); const isNeedResubscribe = await this.driver.checkIsNeedResubscribe(); const features = await this.data.getFeatures(); const currentPromptUseCase = features['subscription_prompt'] && features['subscription_prompt']['use_case']; if (isCommunicationDisabled || isDropAllData) { await this.unsubscribe(); return; } if (isNeedResubscribe) { await this.unsubscribe(); await this.data.setStatusManualUnsubscribed(false); } const { autoSubscribe } = initParams; const isManualUnsubscribed = await this.data.getStatusManualUnsubscribed(); // update status is register const isRegister = await this.api.checkDeviceSubscribeForPushNotifications(false); // Actions depending of the permissions switch (permission) { case CONSTANTS.PERMISSION_PROMPT: // emit event permission default this.eventBus.dispatchEvent('permission-default', {}); // device can't be register if permission default if (isRegister) { await this.unsubscribe(); } // topic based widget have not capping params, get defaults const widgetConfig = await this.getWidgetConfig(); const canShowByCapping = await this.checkCanShowByCapping(widgetConfig); if (!canShowByCapping) { break; } // show subscription segment widget const isTopicBasedUseCase = currentPromptUseCase === CONSTANTS.SUBSCRIPTION_WIDGET_USE_CASE_TOPIC_BASED; if (isTopicBasedUseCase) { await this.subscriptionSegmentWidget.init(); } // show subscription prompt widget const isDefaultUseCase = currentPromptUseCase === CONSTANTS.SUBSCRIPTION_WIDGET_USE_CASE_DEFAULT; const isNotSetUseCase = currentPromptUseCase === CONSTANTS.SUBSCRIPTION_WIDGET_USE_CASE_NOT_SET && autoSubscribe; // show subscription prompt widget if (isDefaultUseCase || isNotSetUseCase) { this.subscriptionPromptWidget.init(widgetConfig); this.subscriptionPromptWidget.show(); } await this.updateCappingParams(); break; case CONSTANTS.PERMISSION_DENIED: // emit event permission denied this.eventBus.dispatchEvent('permission-denied', {}); // device can't be register if permission default if (isRegister) { await this.unsubscribe(); } break; case CONSTANTS.PERMISSION_GRANTED: // emit event permission granted this.eventBus.dispatchEvent('permission-granted', {}); // device can't be register if manual unsubscribed if (isManualUnsubscribed && isRegister) { await this.unsubscribe(); } // device must be register if not manual unsubscribed // or if change configuration -> resubscribe device for get new push token if (!isRegister && !isManualUnsubscribed || isNeedResubscribe) { await this.subscribe(true); // show subscription segment widget const isTopicBasedUseCase = currentPromptUseCase === CONSTANTS.SUBSCRIPTION_WIDGET_USE_CASE_TOPIC_BASED; // if topic based widget need set default channels if (isTopicBasedUseCase) { const result = features.channels.map((channel: { code: string }) => channel.code); await this.api.setTags({ 'Subscription Segments': result }) } } break; } } private async getWidgetConfig(): Promise<ISubscriptionPromptWidgetParams> { const features = await this.data.getFeatures(); // get config by features from get config method const currentConfig = features['subscription_prompt_widget'] && features['subscription_prompt_widget'].params; // merge current config with capping defaults const configWithDefaultCapping: ISubscriptionPromptWidgetParams = { cappingCount: CONSTANTS.SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG.cappingCount, cappingDelay: CONSTANTS.SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG.cappingDelay, ...currentConfig }; // if current config is not exist show with default values return currentConfig ? configWithDefaultCapping : CONSTANTS.SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG; } private async checkCanShowByCapping(widgetConfig: ISubscriptionPromptWidgetParams): Promise<boolean> { const currentTime = new Date().getTime(); const displayCount = await this.data.getPromptDisplayCount(); const lastSeenTime = await this.data.getPromptLastSeenTime(); // can show by max display count const canShowByCapping = widgetConfig.cappingCount > displayCount; // can show last seen time const canShowByLastTime = currentTime - lastSeenTime > widgetConfig.cappingDelay; return canShowByCapping && canShowByLastTime; } private async updateCappingParams(): Promise<void> { const displayCount = await this.data.getPromptDisplayCount(); const currentTime = new Date().getTime(); await this.data.setPromptDisplayCount(displayCount + 1); await this.data.setPromptLastSeenTime(currentTime); } /** * Method initiates Facebook * @param {IInitParams} initParams * @returns {Promise<void>} */ private initFacebook(initParams: IInitParams) { const facebook = { enable: false, pageId: '', containerClass: '', ...initParams.facebook }; if (facebook && facebook.enable) { try { new FacebookModule({ pageId: facebook.pageId, containerClass: facebook.containerClass, applicationCode: initParams.applicationCode, userId: initParams.userId || '' }); } catch (error) { Logger.error(error, 'facebook module initialization failed'); } } } /** * Method for init InApp module * @param {IInitParams} params * @return {Promise<void>} */ private async initInApp(params: IInitParams['inApps']) { if (params && params.enable) { try { this.InApps = new InApps(params, this, this.eventBus, this.api); await this.InApps.init() .then(() => { Logger.info('InApps module has been initialized'); this.eventBus.dispatchEvent('initialize-in-apps-module', {}); }) .catch((error) => { Logger.error(error, 'InApps module initialization has been failed'); }); } catch (error) { Logger.error(error, 'InApp module initialization has been failed') } } } /** * * @param {MessageEvent} event */ private onServiceWorkerMessage(event: ServiceWorkerMessageEvent) { const {data = {}} = event || {}; const {type = '', payload = {}} = data || {}; this.emitLegacyEventsFromServiceWorker(type, payload); } /** * Check device's session and call the appOpen method, * no more than once an hour. * Force need to Safari await subscribe status * @param {boolean} isForce * @returns {Promise<void>} */ private async open(isForce?: boolean) { let lastApplicationOpenTime = await this.data.getLastOpenApplicationTime(); const currentTime = Date.now(); if (!lastApplicationOpenTime) { lastApplicationOpenTime = 0; } const isSendingPeriodExceeded = currentTime - lastApplicationOpenTime < CONSTANTS.PERIOD_SEND_APP_OPEN; const needSendOpenStatistics = isForce || !isSendingPeriodExceeded; if (!needSendOpenStatistics) { return; } await this.data.setLastOpenApplicationTime(currentTime); await this.api.applicationOpen(); } private async onGetConfig(features: IMapResponse['getConfig']['features']) { await this.data.setFeatures(features); if (features) { // page visited feature if (features.page_visit && features.page_visit.enabled) { await keyValue.set(CONSTANTS.PAGE_VISITED_URL, features.page_visit.entrypoint); this.sendStatisticsVisitedPage(); } // send default event, page visited if (features.events && features.events.length) { const isPageVisitedEvent = features.events.some( ((event: string): boolean => event === CONSTANTS.EVENT_PW_SITE_OPENED) ); if (isPageVisitedEvent) { this.sendPostEventVisitedPage(); } } // vapid key if (features.vapid_key) { await this.data.setApplicationServerKey(features.vapid_key) } } } private async initPushNotifications(params: IInitParams): Promise<void> { await this.data.setDefaultNotificationImage(params.defaultNotificationImage); await this.data.setDefaultNotificationTitle(params.defaultNotificationTitle); await this.data.setServiceWorkerUrl(params.serviceWorkerUrl); await this.data.setServiceWorkerScope(params.scope); await this.data.setInitParams({ autoSubscribe: true, ...params, }); await this.initDriver(); // Default actions on init try { await this.defaultProcess(params); } catch (error) { Logger.error(error, 'Internal error: defaultProcess fail'); } } private async initDriver(): Promise<void> { if (this.platformChecker.isSafari) { const { safariWebsitePushID: webSitePushId } = await this.data.getInitParams(); if (!webSitePushId) { throw new Error('For work with Safari Push Notification add safariWebsitePushID to initParams!'); } this.driver = new PushServiceSafari(this.api, this.data, { webSitePushId }); return; } if (this.platformChecker.isAvailableServiceWorker) { this.driver = new PushServiceDefault(this.api, this.data, {}); return; } } public async sendPostEventVisitedPage() { const { document: { title }, location: { href } } = window; this.api.postEvent(CONSTANTS.EVENT_PW_SITE_OPENED, { url: href, title: title, device_type: this.platformChecker.platform }); } /** * @private * * @param {string} type - legacy event type * @param {function} handler - legacy handler */ private subscribeToLegacyEvents(type: string, handler: (api?: Api, payload?: any) => void): void { switch (type) { case CONSTANTS.EVENT_ON_LOAD: handler(); break; case CONSTANTS.EVENT_ON_READY: if (this.ready) { handler(this.api); break; } this.eventBus.addEventHandler( 'ready', () => handler(this.api), ); break; case CONSTANTS.EVENT_ON_REGISTER: this.eventBus.addEventHandler( 'register', () => handler(this.api), ); break; case CONSTANTS.EVENT_ON_SUBSCRIBE: this.eventBus.addEventHandler( 'subscribe', () => handler(this.api), ); break; case CONSTANTS.EVENT_ON_UNSUBSCRIBE: this.eventBus.addEventHandler( 'unsubscribe', () => handler(this.api), ); break; case CONSTANTS.EVENT_ON_SW_INIT_ERROR: this.eventBus.addEventHandler( 'initialize-service-worker-error', ({ error }) => handler(this.api, error), ); break; case CONSTANTS.EVENT_ON_PUSH_DELIVERY: this.eventBus.addEventHandler( 'receive-push', ({ notification }) => handler(this.api, notification), ); break; case CONSTANTS.EVENT_ON_NOTIFICATION_CLICK: this.eventBus.addEventHandler( 'open-notification', ({ notification }) => handler(this.api, notification), ); break; case CONSTANTS.EVENT_ON_NOTIFICATION_CLOSE: this.eventBus.addEventHandler( 'hide-notification', ({ notification }) => handler(this.api, notification), ); break; case CONSTANTS.EVENT_ON_CHANGE_COMMUNICATION_ENABLED: this.eventBus.addEventHandler( 'change-enabled-communication', ({ isEnabled }) => handler(this.api, isEnabled), ); break; case CONSTANTS.EVENT_ON_PUT_NEW_MESSAGE_TO_INBOX_STORE: this.eventBus.addEventHandler( 'receive-inbox-message', ({ message }) => handler(this.api, message), ); break; case CONSTANTS.EVENT_ON_UPDATE_INBOX_MESSAGES: this.eventBus.addEventHandler( 'update-inbox-messages', ({ messages }) => handler(this.api, messages), ); break; case CONSTANTS.EVENT_ON_SHOW_NOTIFICATION_PERMISSION_DIALOG: this.eventBus.addEventHandler( 'show-notification-permission-dialog', () => handler(this.api), ); break; case CONSTANTS.EVENT_ON_HIDE_NOTIFICATION_PERMISSION_DIALOG: this.eventBus.addEventHandler( 'hide-notification-permission-dialog', ({ permission }) => handler(this.api, permission), ); break; case CONSTANTS.EVENT_ON_SHOW_SUBSCRIPTION_WIDGET: this.eventBus.addEventHandler( 'show-subscription-widget', () => handler(this.api), ); break; case CONSTANTS.EVENT_ON_HIDE_SUBSCRIPTION_WIDGET: this.eventBus.addEventHandler( 'hide-subscription-widget', () => handler(this.api), ); break; case CONSTANTS.EVENT_ON_PERMISSION_DENIED: this.eventBus.addEventHandler( 'permission-denied', () => handler(this.api), ); break; case CONSTANTS.EVENT_ON_PERMISSION_PROMPT: this.eventBus.addEventHandler( 'permission-default', () => handler(this.api), ); break; case CONSTANTS.EVENT_ON_PERMISSION_GRANTED: this.eventBus.addEventHandler( 'permission-granted', () => handler(this.api), ); break; } } private emitLegacyEventsFromServiceWorker(type: string, payload?: any): void { switch (type) { case CONSTANTS.EVENT_ON_PUSH_DELIVERY: this.eventBus.dispatchEvent('receive-push', { notification: payload }); break; case CONSTANTS.EVENT_ON_NOTIFICATION_CLICK: this.eventBus.dispatchEvent('open-notification', { notification: payload }); break; case CONSTANTS.EVENT_ON_NOTIFICATION_CLOSE: this.eventBus.dispatchEvent('hide-notification', { notification: payload }); break; case CONSTANTS.EVENT_ON_PUT_NEW_MESSAGE_TO_INBOX_STORE: this.eventBus.dispatchEvent('receive-inbox-message', { message: payload }); break; } } }
the_stack
"use strict"; import { closeSync, copyFileSync, existsSync, openSync, readdirSync, readFileSync, renameSync, writeFileSync, writeSync, } from "fs"; import { basename, dirname, extname, join } from "path"; import * as vscode from "vscode"; import { startCompetitiveCompanionService } from "./companion"; import { EMPTY } from "./conn"; import { currentProblem, getSolutionPath, initAcmX, newContestFromId, newProblemFromId, pathToStatic, stressSolution, testSolution, upgradeArena, mainSolution, globalLanguagePath, getMainSolutionPath, } from "./core"; import { SiteDescription, Verdict, ATTIC, FRIEND_TIMEOUT, verdictName, ConfigFile, Option, } from "./primitives"; import * as clipboardy from "clipboardy"; import * as tmp from "tmp"; import { debug, getExtension, removeExtension } from "./utils"; import { preRun, runSingle } from "./runner"; import { acmxTerminal } from "./terminal"; const TESTCASES = "testcases"; // Create a new problem async function addProblem() { // Use default site when creating a problem from the vscode. let site: SiteDescription = EMPTY; let id = await vscode.window.showInputBox({ placeHolder: site.problemIdPlaceholder, }); if (id === undefined) { vscode.window.showErrorMessage("Problem ID not provided."); return; } let path = getSolutionPath(); path = join(path!, site.name, "single"); let problemPath = newProblemFromId(path, site, id); await vscode.commands.executeCommand( "vscode.openFolder", vscode.Uri.file(problemPath) ); } function parseNumberOfProblems(numberOfProblems: string | undefined) { if (numberOfProblems === undefined) { return undefined; } numberOfProblems = numberOfProblems.toLowerCase(); if (numberOfProblems.length === 1) { let value = numberOfProblems.charCodeAt(0); if (97 <= value && value <= 122) { return value - 97 + 1; } } let res = Number.parseInt(numberOfProblems); if (Number.isNaN(res)) { return undefined; } else { return res; } } async function addContest() { let path = getSolutionPath(); let site: SiteDescription = EMPTY; let id = undefined; let name = await vscode.window.showInputBox({ placeHolder: site.contestIdPlaceholder, }); if (name === undefined) { vscode.window.showErrorMessage("Name not provided."); return; } let probCountStr = await vscode.window.showInputBox({ placeHolder: "Number of problems", }); let probCount = parseNumberOfProblems(probCountStr); if (probCount === undefined) { vscode.window.showErrorMessage("Number of problems not provided."); return; } id = name + "-" + probCount.toString(); let contestPath = await newContestFromId(path!, site, id); vscode.commands.executeCommand( "vscode.openFolder", vscode.Uri.file(contestPath) ); } async function debugTestCase(path: string, tcId: string) { // Change editor layout to show failing test await vscode.commands.executeCommand("vscode.setEditorLayout", { orientation: 0, groups: [ { groups: [{}], size: 0.5 }, { groups: [{ groups: [{}, {}] }, {}], size: 0.5, }, ], }); let sol = mainSolution(path); let inp = join(path, TESTCASES, `${tcId}.in`); let ans = join(path, TESTCASES, `${tcId}.ans`); let out = join(path, TESTCASES, `${tcId}.out`); await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(sol), vscode.ViewColumn.One ); await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(inp), vscode.ViewColumn.Two ); // This file might not exist! if (existsSync(out)) { await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(ans), vscode.ViewColumn.Three ); await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(out), vscode.ViewColumn.Four ); } else { await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(ans), vscode.ViewColumn.Four ); } } async function runSolution() { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); debug("run-solution", `${path}`); await vscode.window.activeTextEditor?.document.save().then(() => { let result_ = testSolution(path); if (result_.isNone()) { return; } let result = result_.unwrap(); if (result.isOk()) { vscode.window.showInformationMessage( `OK. Time ${result.getMaxTime()}ms` ); } else if (result.status === Verdict.NO_TESTCASES) { vscode.window.showErrorMessage(`No testcases.`); } else { let failTestCaseId = result.getFailTestCaseId(); vscode.window.showErrorMessage( `${verdictName(result.status)} on test ${failTestCaseId}` ); debugTestCase(path, failTestCaseId); } }); } async function compile() { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); debug("compile", `${path}`); let sol = mainSolution(path); let out = join(path, ATTIC, "sol"); if (!existsSync(sol)) { vscode.window.showErrorMessage("Open a coding environment first."); return; } await vscode.window.activeTextEditor?.document.save().then(() => { // Compile solution let result = preRun(sol, out, path!, FRIEND_TIMEOUT); if (result.isNone()) { vscode.window.showInformationMessage("No compilation needed."); } else if (!result.unwrap().failed()) { vscode.window.showInformationMessage("Compilation successful."); } }); } async function openTestCase() { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let testCases: any[] = []; // Read testcases readdirSync(join(path, TESTCASES)) .filter(function (testCasePath) { return extname(testCasePath) === ".in"; }) .map(function (testCasePath) { let name = removeExtension(testCasePath); testCases.push({ label: name, target: name, }); }); let tc = await vscode.window.showQuickPick(testCases, { placeHolder: "Select test case", }); if (tc !== undefined) { let inp = join(path, TESTCASES, `${tc.target}.in`); let out = join(path, TESTCASES, `${tc.target}.ans`); await vscode.commands.executeCommand("vscode.setEditorLayout", { orientation: 0, groups: [{}, {}], }); await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(inp), vscode.ViewColumn.One ); await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(out), vscode.ViewColumn.Two ); } } async function addTestCase() { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let index = 0; while (existsSync(join(path, TESTCASES, `${index}.hand.in`))) { index += 1; } let inp = join(path, TESTCASES, `${index}.hand.in`); let out = join(path, TESTCASES, `${index}.hand.ans`); writeFileSync(inp, ""); writeFileSync(out, ""); await vscode.commands.executeCommand("vscode.setEditorLayout", { orientation: 0, groups: [{}, {}], }); await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(inp), vscode.ViewColumn.One ); await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(out), vscode.ViewColumn.Two ); } async function coding() { vscode.window.terminals.forEach((ter) => { ter.hide(); }); //hides terminals let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); await vscode.commands.executeCommand("vscode.setEditorLayout", { groups: [{}], }); let sol = mainSolution(path); await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(sol), vscode.ViewColumn.One ); } async function stress() { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let _stressTimes: number | undefined = vscode.workspace .getConfiguration("acmx.stress", null) .get("times"); // Default stress times is 10 let stressTimes = 10; if (_stressTimes !== undefined) { stressTimes = _stressTimes; } await vscode.window.activeTextEditor?.document.save().then(() => { let result_ = stressSolution(path, stressTimes); if (result_.isNone()) { return; } let result = result_.unwrap(); if (result.isOk()) { vscode.window.showInformationMessage( `OK. Time ${result.getMaxTime()}ms` ); } else { let failTestCaseId = result.getFailTestCaseId(); vscode.window.showErrorMessage( `${verdictName(result.status)} on test ${failTestCaseId}` ); debugTestCase(path, failTestCaseId); } }); } async function upgrade() { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); upgradeArena(path); } function fileList(dir: string): string[] { return readdirSync(dir).reduce((list: string[], file: string) => { return list.concat([file]); }, []); } async function setChecker() { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let allCheckersPlain = fileList(join(pathToStatic(), "checkers")).filter( (name: string) => name !== "testlib.h" ); let allChecker = allCheckersPlain.map((value: string) => { var data = readFileSync( join(pathToStatic(), "checkers", value), "utf8" ); var regex = /setName\("(.*?)"\)/; var matched = regex.exec(data)![1]; return { label: value.slice(0, value.length - 4), detail: matched, target: value, }; }); let checkerInfo = await vscode.window.showQuickPick(allChecker, { placeHolder: "Select custom checker.", }); if (checkerInfo === undefined) { vscode.window.showErrorMessage("Checker not provided."); return; } let checker = checkerInfo.target; let checkerPath = join(pathToStatic(), "checkers", checker); let checkerDest = join(path, ATTIC, "checker.cpp"); copyFileSync(checkerPath, checkerDest); let config = ConfigFile.loadConfig(path).unwrapOr(ConfigFile.empty()); config.checker = Option.some(checkerDest); config.dump(path); } async function selectDebugTestCase(uriPath: vscode.Uri) { let testCaseName = basename(uriPath.path); let path = dirname(uriPath.path); const MAX_DEPTH = 2; for (let i = 0; i < MAX_DEPTH && !existsSync(join(path, ".vscode")); i++) { path = dirname(path); } let launchTaskPath = join(path, ".vscode", "launch.json"); if (!existsSync(launchTaskPath)) { return undefined; } let launchTaskData = readFileSync(launchTaskPath, "utf8"); // TODO(#20): Don't use regular expression to replace this. Use JSON parser instead. let newTaskData = launchTaskData.replace( /\"stdio\"\:.+/, `"stdio": ["\${fileDirname}/testcases/${testCaseName}"],` ); let launchTaskFdW = openSync(launchTaskPath, "w"); writeSync(launchTaskFdW, newTaskData); closeSync(launchTaskFdW); } async function selectMainSolution(uriPath: vscode.Uri) { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let config = ConfigFile.loadConfig(path).unwrapOr(ConfigFile.empty()); config.mainSolution = Option.some(uriPath.path); config.dump(path); console.log(uriPath); } async function selectBruteSolution(uriPath: vscode.Uri) { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let config = ConfigFile.loadConfig(path).unwrapOr(ConfigFile.empty()); config.bruteSolution = Option.some(uriPath.path); config.dump(path); console.log(uriPath); } async function selectGenerator(uriPath: vscode.Uri) { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let config = ConfigFile.loadConfig(path).unwrapOr(ConfigFile.empty()); config.generator = Option.some(uriPath.path); config.dump(path); console.log(uriPath); } async function selectChecker(uriPath: vscode.Uri) { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let config = ConfigFile.loadConfig(path).unwrapOr(ConfigFile.empty()); config.checker = Option.some(uriPath.path); config.dump(path); console.log(uriPath); } function assignedCopyToClipboardCommand(): Boolean { let generateCodeCommand: | string | undefined = vscode.workspace .getConfiguration("acmx.configuration", null) .get("copyToClipboardCommand"); return generateCodeCommand !== undefined; } // Run `copyToClipboardCommand` command to convert current code // in code ready for submission. This is useful when we want to apply // some filters to the code, or some libraries should be inlined. function codeToSubmit(): string | undefined { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let generateCodeCommand: | string | undefined = vscode.workspace .getConfiguration("acmx.configuration", null) .get("copyToClipboardCommand"); let sol = mainSolution(path); let content = ""; if (generateCodeCommand === undefined || generateCodeCommand === "") { content = readFileSync(sol, "utf8"); } else { let generateCodeCommands = generateCodeCommand!.split(" "); for (let i = 0; i < generateCodeCommands.length; i++) { generateCodeCommands[i] = generateCodeCommands[i].replace( "$CODE", sol ); } let execution = runSingle(generateCodeCommands, FRIEND_TIMEOUT, ""); if (execution.failed()) { vscode.window.showErrorMessage("Fail generating submission."); return; } content = execution.stdout().toString("utf8"); } return content; } async function copySubmissionToClipboard() { let content = codeToSubmit(); if (content !== undefined) { clipboardy.writeSync(content); vscode.window.showInformationMessage("Submission copied to clipboard!"); } } async function submitSolution() { let path_ = currentProblem(); if (path_.isNone()) { vscode.window.showErrorMessage("No active problem"); return; } let path = path_.unwrap(); let config = ConfigFile.loadConfig(path, true).unwrap(); let compileResult = getMainSolutionPath(path, config); if (compileResult.isNone()) { vscode.window.showErrorMessage("Could not get the code"); return; } let mainSolutionPath = compileResult.unwrap().code; debug("submit-main-solution-path", `${mainSolutionPath}`); let url_ = config.url(); if (url_.isNone()) { vscode.window.showErrorMessage("No active url"); return; } let submitCommand: string | undefined = vscode.workspace .getConfiguration("acmx.configuration", null) .get("submitCommand"); if (submitCommand === undefined || submitCommand === "") { vscode.window.showErrorMessage( "acmx.configuration.submitCommand not set" ); return; } if (assignedCopyToClipboardCommand()) { let content = codeToSubmit(); let outputFile = tmp.fileSync(); writeSync(outputFile.fd, content); let nameWithExtension = outputFile.name + getExtension(mainSolutionPath); renameSync(outputFile.name, nameWithExtension); mainSolutionPath = nameWithExtension; } submitCommand = submitCommand .replace("$CODE", mainSolutionPath) .replace("$URL", url_.unwrap()); debug("submit-solution-command", `${submitCommand}`); await vscode.window.activeTextEditor?.document.save().then(() => { let ter = acmxTerminal(); ter.show(); ter.sendText(submitCommand!); }); } async function editLanguage() { let languages: any[] = []; readdirSync(globalLanguagePath()) .filter(function (testCasePath) { return extname(testCasePath) === ".json"; }) .map(function (testCasePath) { let name = removeExtension(testCasePath); languages.push({ label: name, target: testCasePath, }); }); let selectedLanguage = await vscode.window.showQuickPick(languages, { placeHolder: "Select language", }); if (selectedLanguage !== undefined) { await vscode.commands.executeCommand( "vscode.open", vscode.Uri.file(join(globalLanguagePath(), selectedLanguage.target)) ); } } async function debugTest() { vscode.window.showInformationMessage(String.fromCharCode(65)); } // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { initAcmX(); startCompetitiveCompanionService(); let addProblemCommand = vscode.commands.registerCommand( "acmx.addProblem", addProblem ); let addContestCommand = vscode.commands.registerCommand( "acmx.addContest", addContest ); let runSolutionCommand = vscode.commands.registerCommand( "acmx.runSolution", runSolution ); let openTestCaseCommand = vscode.commands.registerCommand( "acmx.openTestCase", openTestCase ); let addTestCaseCommand = vscode.commands.registerCommand( "acmx.addTestCase", addTestCase ); let codingCommand = vscode.commands.registerCommand("acmx.coding", coding); let stressCommand = vscode.commands.registerCommand("acmx.stress", stress); let upgradeCommand = vscode.commands.registerCommand( "acmx.upgrade", upgrade ); let compileCommand = vscode.commands.registerCommand( "acmx.compile", compile ); let setCheckerCommand = vscode.commands.registerCommand( "acmx.setChecker", setChecker ); let selectDebugTestCaseCommand = vscode.commands.registerCommand( "acmx.selectDebugTestCase", selectDebugTestCase ); let selectMainSolutionCommand = vscode.commands.registerCommand( "acmx.selectMainSolution", selectMainSolution ); let selectBruteSolutionCommand = vscode.commands.registerCommand( "acmx.selectBruteSolution", selectBruteSolution ); let selectGeneratorCommand = vscode.commands.registerCommand( "acmx.selectGenerator", selectGenerator ); let selectCheckerCommand = vscode.commands.registerCommand( "acmx.selectChecker", selectChecker ); let copySubmissionToClipboardCommand = vscode.commands.registerCommand( "acmx.copyToClipboard", copySubmissionToClipboard ); let editLanguageCommand = vscode.commands.registerCommand( "acmx.editLanguage", editLanguage ); let submitSolutionCommand = vscode.commands.registerCommand( "acmx.submitSolution", submitSolution ); let debugTestCommand = vscode.commands.registerCommand( "acmx.debugTest", debugTest ); context.subscriptions.push(addProblemCommand); context.subscriptions.push(addContestCommand); context.subscriptions.push(runSolutionCommand); context.subscriptions.push(openTestCaseCommand); context.subscriptions.push(addTestCaseCommand); context.subscriptions.push(codingCommand); context.subscriptions.push(stressCommand); context.subscriptions.push(upgradeCommand); context.subscriptions.push(compileCommand); context.subscriptions.push(setCheckerCommand); context.subscriptions.push(selectDebugTestCaseCommand); context.subscriptions.push(selectMainSolutionCommand); context.subscriptions.push(selectBruteSolutionCommand); context.subscriptions.push(selectGeneratorCommand); context.subscriptions.push(selectCheckerCommand); context.subscriptions.push(copySubmissionToClipboardCommand); context.subscriptions.push(editLanguageCommand); context.subscriptions.push(submitSolutionCommand); context.subscriptions.push(debugTestCommand); } // this method is called when your extension is deactivated export function deactivate() {}
the_stack
import { NativeModules, DeviceEventEmitter, NativeEventEmitter, AppState, AppStateStatus, Platform, EmitterSubscription, } from 'react-native'; import { queue } from 'async'; type SocksPortNumber = number; export type RequestHeaders = { [header: string]: string } | {}; export type ResponseHeaders = { [header: string]: string | string[] }; /** * Supported Request types * @todo PUT */ export enum RequestMethod { 'GET' = 'get', 'POST' = 'post', 'DELETE' = 'delete', } /** * Supported Body Payloads for the respective RequestMethod */ export interface RequestBody { [RequestMethod.GET]: undefined; [RequestMethod.POST]: string; [RequestMethod.DELETE]: string | undefined; } /** * Response returned from a successfully executed request */ export interface RequestResponse<T = any> { /** * Content mimeType returned by server */ mimeType: string; /** * Base64 encoded string of data returned by server */ b64Data: string; /** * String indexed object for headers returned by Server */ headers: ResponseHeaders; /** * The response code for the request as returned by the server * Note: a respCode > 299 is considered an error by the client and throws */ respCode: number; /** * If the mimeType of the payload is valid JSON then this field will * be populated with parsed JSON (object) */ json?: T; } interface ProcessedRequestResponse extends RequestResponse {} /** * Native module interface * Used internally, public calls should be made on the returned TorType */ interface NativeTor { startDaemon(timeoutMs: number): Promise<SocksPortNumber>; stopDaemon(): Promise<void>; getDaemonStatus(): Promise<string>; request<T extends RequestMethod>( url: string, method: T, data: string, // native side expects string for body headers: RequestHeaders, trustInvalidSSL: boolean ): Promise<RequestResponse>; startTcpConn(target: string, timeoutMs: number): Promise<string>; sendTcpConnMsg( target: string, msg: string, timeoutSeconds: number ): Promise<boolean>; stopTcpConn(target: string): Promise<boolean>; } /** * Tcpstream data handler. * If err is populated then there was an error */ type TcpConnDatahandler = (data?: string, err?: string) => void; /** * Interface returned by createTcpConnection factory */ interface TcpStream { /** * Called to close and end the Tcp connection */ close(): Promise<boolean>; /** * Send a message (write on socket) * @param msg */ write(msg: string): Promise<boolean>; } /** * /** * Factory function to create a persistent TcpStream connection to a target. * Wraps the native side emitter and subscribes to the targets data messages (string). * The TcpStream currently emits per line of data received . That is it reads data from the socket until a new line is reached, at which time * it will emit the data read (by calling onData(data,null). If an error is received or the connection is dropped it onData will be called * with the second parameter containing the error string (ie onData(null,'some error'); * Note: Receiving an 'EOF' error from the target we're connected to signifies the end of a stream or the target dropped the connection. * This will cause the module to drop the TcpConnection and remove all data event listeners. * Should you wish to reconnect to the target you must initiate a new connection by calling createTcpConnection again. * @param param {target: string, writeTimeout: number, connectionTimeout: number } : * `target` onion to connect to (ex: kciybn4d4vuqvobdl2kdp3r2rudqbqvsymqwg4jomzft6m6gaibaf6yd.onion:50001) * 'writeTimeout' in seconds to wait before timing out on writing to the socket (Defaults to 7) * 'connectionTimeout' in MilliSeconds to wait before timing out on connecting to the Target (Defaults to 15000 = 15 seconds) * 'numberConcurrentWrites' Number of maximum messages to write concurrently on the Tcp socket. Defaults to 4. If more than numberConcurrentWrites messages are recieved they are placed on queue to be dispatched as soon as a previous message write resolves. * @param onData TcpConnDatahandler node style callback called when data or an error is received for this connection * @returns TcpStream */ const _createTcpConnection = async ( param: { target: string; connectionTimeout?: number; writeTimeout?: number; numberConcurrentWrites?: number; }, onData: TcpConnDatahandler ): Promise<TcpStream> => { const { target } = param; const connectionTimeout = param.connectionTimeout || 15000; const writeQueueConcurrency = param.numberConcurrentWrites || 4; const connId = await NativeModules.TorBridge.startTcpConn( target, connectionTimeout ); let lsnr_handle: EmitterSubscription[] = []; /** * Handles errors from Tcp Connection * Mainly check for EOF (connection closed/end of stream) and removes lnsers */ const onError = async (event: string) => { if (event.toLowerCase() === 'eof') { console.warn( `Got to end of stream on TcpStream to ${target} having connection Id ${connId}. Removing listners` ); try { await close(); } catch (err) { console.warn('RnTor: onError close execution error', err); } } }; if (Platform.OS === 'android') { lsnr_handle.push( DeviceEventEmitter.addListener(`${connId}-data`, (event) => { onData(event); }) ); lsnr_handle.push( DeviceEventEmitter.addListener(`${connId}-error`, async (event) => { await onError(event); await onData(undefined, event); }) ); } else if (Platform.OS === 'ios') { const emitter = new NativeEventEmitter(NativeModules.TorBridge); lsnr_handle.push( emitter.addListener(`torTcpStreamData`, (event) => { const [uuid, data] = event.split('||', 2); if (connId === uuid) { onData(data); } }) ); lsnr_handle.push( emitter.addListener(`torTcpStreamError`, async (event) => { const [uuid, data] = event.split('||', 2); if (connId === uuid) { await onError(data); await onData(undefined, data); } }) ); } const writeTimeout = param.writeTimeout || 7; const write = (msg: string) => NativeModules.TorBridge.sendTcpConnMsg(connId, msg, writeTimeout); const close = () => { lsnr_handle.map((e) => e.remove()); return NativeModules.TorBridge.stopTcpConn(connId); }; /** * Wrap write with a JS queue for non V8 engines */ const writeMessageQueue = queue<{ msg: string; res: (x: any) => void; rej: (x: any) => void; }>(async (payload, cb) => { const { msg, res, rej } = payload; try { const result = await write(msg); res(result); } catch (err) { rej(err); } finally { cb(); } }, writeQueueConcurrency); writeMessageQueue.drain(() => console.log( 'notice: All tcpConnection write messages requests have been disptached..' ) ); return { close, write: (msg: string) => new Promise((res, rej) => writeMessageQueue.push({ msg, res, rej })), }; }; const createTcpConnQueue = queue<{ param: Parameters<typeof _createTcpConnection>; res: (x: any) => void; rej: (x: any) => void; }>(async (payload, cb) => { const { param, res, rej } = payload; try { const result = await _createTcpConnection(...param); res(result); } catch (err) { console.error('error creating tcp conn', err); rej(err); } finally { cb(); } }, 1); createTcpConnQueue.drain(() => console.log( 'notice: All requested TcpConnections requests have been dispatched..' ) ); /** * We expose _createTcpConnection publicly as a wrapped queue to avoid JS->Native bridge hang issue for non V8 engines */ const createTcpConnection = ( ...param: Parameters<typeof _createTcpConnection> ): ReturnType<typeof _createTcpConnection> => new Promise((res, rej) => { createTcpConnQueue.push({ param, res, rej }); }); type TorType = { /** * Send a GET request routed through the SOCKS proxy on the native side * Starts the Tor Daemon automatically if not already started * @param url * @param headers * @param trustSSL */ get( url: string, headers?: RequestHeaders, trustSSL?: boolean ): Promise<ProcessedRequestResponse>; /** * Send a POST request routed through the SOCKS proxy on the native side * Starts the Tor Daemon automatically if not already started * @param url * @param body * @param headers * @param trustSSL */ post( url: string, body: RequestBody[RequestMethod.POST], headers?: RequestHeaders, trustSSL?: boolean ): Promise<ProcessedRequestResponse>; /** * Send a DELETE request routed through the SOCKS proxy on the native side * Starts the Tor Daemon automatically if not already started * @param url * @param headers * @param trustSSL */ delete( url: string, body?: RequestBody[RequestMethod.DELETE], headers?: RequestHeaders, trustSSL?: boolean ): Promise<ProcessedRequestResponse>; /** Starts the Tor Daemon if not started and returns a promise that fullfills with the socks port number when boostraping is complete. * If the function was previously called it will return the promise without attempting to start the daemon again. * Useful when used as a guard in your transport or action layer */ startIfNotStarted(): Promise<SocksPortNumber>; /** * Stops a running Tor Daemon */ stopIfRunning(): Promise<void>; /** * Returns the current status of the Daemon * Some : * NOTINIT - Not initialized or run (call startIfNotStarted to the startDaemon) * STARTING - Daemon is starting and bootsraping * DONE - Daemon has completed boostraing and socks proxy is ready to be used to route traffic. * <other> - A status returned directly by the Daemon that can indicate a transient state or error. */ getDaemonStatus(): Promise<string>; /** * Accessor the Native request function * Should not be used unless you know what you are doing. */ request: NativeTor['request']; /** * Factory function for creating a peristant Tcp connection to a target * See createTcpConnectio; */ createTcpConnection: typeof createTcpConnection; }; const TorBridge: NativeTor = NativeModules.TorBridge; /** * Tor module factory function * @param stopDaemonOnBackground * @default true * When set to true will shutdown the Tor daemon when the application is backgrounded preventing pre-emitive shutdowns by the OS * @param startDaemonOnActive * @default false * When set to true will automatically start/restart the Tor daemon when the application is bought back to the foreground (from the background) * @param numberConcurrentRequests If sent to > 0 this will instruct the module to queue requests on the JS side before sending them over the Native bridge. Requests will get exectued with numberConcurrentRequests concurent requests. Note setting this to 0 disables JS sided queueing and sends requests directly to Native bridge as they are recieved. This is useful if you're running the stock/hermes RN JS engine that has a tendency off breaking under heavy multithreaded work. If you using V8 you can set this to 0 to disable JS sided queueing and thus get maximum performance. * @default 4 * @param os The OS the module is running on (Set automatically and is provided as an injectable for testing purposes) * @default The os the module is running on. */ export default ({ stopDaemonOnBackground = true, startDaemonOnActive = false, bootstrapTimeoutMs = 25000, numberConcurrentRequests = 4, os = Platform.OS, } = {}): TorType => { let bootstrapPromise: Promise<number> | undefined; let lastAppState: AppStateStatus = 'active'; let _appStateLsnerSet: boolean = false; let requestQueue: ReturnType<typeof queue> | undefined; if (numberConcurrentRequests > 0) { requestQueue = queue<{ res: (x: any) => void; rej: (x: any) => void; request: () => Promise<RequestResponse>; }>(async (task, cb) => { const { res, rej, request } = task; try { const result = await request(); res(result); } catch (err) { rej(err); } finally { cb(); } }, numberConcurrentRequests); requestQueue.drain(() => console.log('notice: Request queue has been processed') ); } const _handleAppStateChange = async (nextAppState: AppStateStatus) => { if ( startDaemonOnActive && lastAppState.match(/background/) && nextAppState === 'active' ) { const status = NativeModules.TorBridge.getDaemonStatus(); // Daemon should be in NOTINIT status if coming from background and this is enabled, so if not shutodwn and start again if (status !== 'NOTINIT') { await stopIfRunning(); } startIfNotStarted(); } if ( stopDaemonOnBackground && lastAppState.match(/active/) && nextAppState === 'background' ) { const status = NativeModules.TorBridge.getDaemonStatus(); if (status !== 'NOTINIT') { await stopIfRunning(); } } lastAppState = nextAppState; }; const startIfNotStarted = () => { if (!bootstrapPromise) { bootstrapPromise = NativeModules.TorBridge.startDaemon( bootstrapTimeoutMs ); } return bootstrapPromise; }; const stopIfRunning = async () => { console.warn('Stopping Tor daemon.'); bootstrapPromise = undefined; await NativeModules.TorBridge.stopDaemon(); }; /** * Post process request result */ const onAfterRequest = async ( res: RequestResponse ): Promise<RequestResponse> => { if (os === 'android') { // Mapping JSONObject to ReadableMap for the bridge is a bit of a manual shitshow // so android JSON will be returned as string from the other side and we parse it here // if (res?.json) { const json = JSON.parse(res.json); return { ...res, json, }; } } return res; }; // Register app state lsner only once if (!_appStateLsnerSet) { AppState.addEventListener('change', _handleAppStateChange); } /** * Wraps requests to be queued or executed directly. * numberConcurrentRequests > 0 will cause tasks to be wrapped in a JS side queue */ const requestQueueWrapper = ( request: () => Promise<RequestResponse> ): Promise<RequestResponse> => { return new Promise((res, rej) => numberConcurrentRequests > 0 ? requestQueue?.push({ request, res, rej }) : request().then(res).catch(rej) ); }; return { async get(url: string, headers?: Headers, trustSSL: boolean = true) { await startIfNotStarted(); return await onAfterRequest( await requestQueueWrapper(() => TorBridge.request(url, RequestMethod.GET, '', headers || {}, trustSSL) ) ); }, async post( url: string, body: RequestBody[RequestMethod.POST], headers?: RequestHeaders, trustSSL: boolean = true ) { await startIfNotStarted(); return await onAfterRequest( await requestQueueWrapper(() => TorBridge.request( url, RequestMethod.POST, body, headers || {}, trustSSL ) ) ); }, async delete( url: string, body: RequestBody[RequestMethod.DELETE], headers?: RequestHeaders, trustSSL: boolean = true ) { await startIfNotStarted(); return await onAfterRequest( await requestQueueWrapper(() => TorBridge.request( url, RequestMethod.DELETE, body || '', headers || {}, trustSSL ) ) ); }, startIfNotStarted, stopIfRunning, request: TorBridge.request, getDaemonStatus: TorBridge.getDaemonStatus, createTcpConnection, } as TorType; };
the_stack
import * as mongoose from 'mongoose'; import * as bcrypt from 'bcrypt'; import {IUser} from '../../../shared/models/IUser'; import {IUserSubSafe} from '../../../shared/models/IUserSubSafe'; import {IUserSubTeacher} from '../../../shared/models/IUserSubTeacher'; import {IUserSubCourseView} from '../../../shared/models/IUserSubCourseView'; import {NativeError} from 'mongoose'; import * as crypto from 'crypto'; import {isNullOrUndefined} from 'util'; import {isEmail} from 'validator'; import {errorCodes} from '../config/errorCodes'; import {allRoles} from '../config/roles'; import {extractMongoId} from '../utilities/ExtractMongoId'; import {ensureMongoToObject} from '../utilities/EnsureMongoToObject'; import {Course, ICourseModel} from './Course'; import {NotificationSettings} from './NotificationSettings'; import {Notification} from './Notification'; import {WhitelistUser} from './WhitelistUser'; import {Progress} from './progress/Progress'; import fs = require('fs'); export interface IUserPrivileges { userIsAdmin: boolean; userIsTeacher: boolean; userIsStudent: boolean; userEditLevel: number; } export interface IUserEditPrivileges extends IUserPrivileges { currentEditLevel: number; targetEditLevel: number; editSelf: boolean; editLevelHigher: boolean; editAllowed: boolean; } interface IUserModel extends IUser, mongoose.Document { exportPersonalData: () => Promise<IUser>; isValidPassword: (candidatePassword: string) => Promise<boolean>; checkPrivileges: () => IUserPrivileges; checkEditUser: (targetUser: IUser) => IUserEditPrivileges; checkEditableBy: (currentUser: IUser) => IUserEditPrivileges; forSafe: () => IUserSubSafe; forTeacher: () => IUserSubTeacher; forCourseView: () => IUserSubCourseView; forUser: (otherUser: IUser) => IUserSubSafe | IUserSubTeacher | IUser; authenticationToken: string; resetPasswordToken: string; resetPasswordExpires: Date; isActive: boolean; updatedAt: Date; } interface IUserMongoose extends mongoose.Model<IUserModel> { getEditLevel: (user: IUser) => number; getEditLevelUnsafe: (user: any) => number | undefined; checkPrivileges: (user: IUser) => IUserPrivileges; checkEditUser: (currentUser: IUser, targetUser: IUser) => IUserEditPrivileges; forSafe: (user: IUser | IUserModel) => IUserSubSafe; forTeacher: (user: IUser | IUserModel) => IUserSubTeacher; forCourseView: (user: IUser | IUserModel) => IUserSubCourseView; forUser: (user: IUser | IUserModel, otherUser: IUser) => IUserSubSafe | IUserSubTeacher | IUser; } let User: IUserMongoose; const userSchema = new mongoose.Schema({ uid: { type: String, lowercase: true, unique: true, sparse: true, index: true }, email: { type: String, lowercase: true, unique: true, required: true, validate: [{validator: (value: any) => isEmail(value), msg: 'Invalid email.'}], index: true }, password: { type: String, required: true, validate: new RegExp(errorCodes.password.regex.regex) }, profile: { firstName: { type: String, index: true, maxlength: 64 }, lastName: { type: String, index: true, maxlength: 64 }, picture: { path: {type: String}, name: {type: String}, alias: {type: String} }, theme: {type: String} }, role: { type: String, 'enum': allRoles, 'default': 'student' }, lastVisitedCourses: [ { type: String }], authenticationToken: {type: String}, resetPasswordToken: {type: String}, resetPasswordExpires: {type: Date}, isActive: {type: Boolean, 'default': false}, updatedAt: { type: Date, required: true, default: Date.now } }, { timestamps: true, toObject: { virtuals: true, transform: function (doc: any, ret: any) { ret._id = ret._id.toString(); delete ret.password; } } }); userSchema.index({ uid: 'text', email: 'text', 'profile.firstName': 'text', 'profile.lastName': 'text' }, {name: 'user_combined'}); function hashPassword(next: (err?: NativeError) => void) { const user = this, SALT_FACTOR = 5; if (!user.isModified('password')) { return next(); } bcrypt.hash(user.password, SALT_FACTOR) .then((hash) => { user.password = hash; }) .then(() => next()) .catch(next); } function generateActivationToken(next: (err?: NativeError) => void) { // check if user wasn't activated by the creator if ( !this.isActive && isNullOrUndefined(this.authenticationToken)) { // set new authenticationToken this.authenticationToken = generateSecureToken(); } next(); } function generatePasswordResetToken(next: (err?: NativeError) => void) { // check if passwordReset is requested -> (resetPasswordExpires is set) if (!isNullOrUndefined(this.resetPasswordExpires) && isNullOrUndefined(this.resetPasswordToken)) { this.resetPasswordToken = generateSecureToken(); } next(); } // returns random 64 byte long base64 encoded Token // maybe this could be shortened function generateSecureToken() { return crypto.randomBytes(64).toString('base64'); } function removeEmptyUid(next: (err?: NativeError) => void) { if (this.uid != null && this.uid.length === 0) { this.uid = undefined; } next(); } // Pre-save of user to database, hash password if password is modified or new userSchema.pre('save', hashPassword); userSchema.pre('save', generateActivationToken); userSchema.pre('save', generatePasswordResetToken); userSchema.pre('save', removeEmptyUid); // TODO: Move shared code of save and findOneAndUpdate hook to one function userSchema.pre('findOneAndUpdate', function (next) { const SALT_FACTOR = 5; const newPassword = this.getUpdate().password; if (typeof newPassword !== 'undefined') { bcrypt.hash(newPassword, SALT_FACTOR) .then((hash) => { this.findOneAndUpdate({}, {password: hash}); }) .then(() => next()) .catch(next); } else { next(); } }); // delete all user data userSchema.pre('remove', async function () { const localUser = <IUserModel><any>this; try { const promises = []; // notifications promises.push(Notification.deleteMany({user: localUser._id})); // notificationsettings promises.push(NotificationSettings.deleteMany({user: localUser._id})); // whitelists promises.push(WhitelistUser.deleteMany({uid: localUser.uid})); // remove user form courses promises.push(Course.updateMany( {$or: [ {students: localUser._id}, {teachers: localUser._id} ]}, {$pull: { 'students': localUser._id, 'teachers': localUser._id } })); // progress promises.push(Progress.deleteMany({user: localUser._id})); // image const path = localUser.profile.picture.path; if (path && fs.existsSync(path)) { fs.unlinkSync(path); } await Promise.all(promises); } catch (e) { throw new Error('Delete Error: ' + e.toString()); } }); // Method to compare password for login userSchema.methods.isValidPassword = function (candidatePassword: string) { if (typeof candidatePassword === 'undefined') { candidatePassword = ''; } return bcrypt.compare(candidatePassword, this.password); }; userSchema.methods.checkPrivileges = function (): IUserPrivileges { return User.checkPrivileges(this); }; userSchema.methods.checkEditUser = function (targetUser: IUser): IUserEditPrivileges { return User.checkEditUser(this, targetUser); }; userSchema.methods.checkEditableBy = function (currentUser: IUser): IUserEditPrivileges { return User.checkEditUser(currentUser, this); }; userSchema.methods.forSafe = function (): IUserSubSafe { return User.forSafe(this); }; userSchema.methods.forTeacher = function (): IUserSubTeacher { return User.forTeacher(this); }; userSchema.methods.forCourseView = function (): IUserSubCourseView { return User.forCourseView(this); }; userSchema.methods.forUser = function (otherUser: IUser): IUserSubSafe | IUserSubTeacher | IUser { return User.forUser(this, otherUser); }; userSchema.methods.exportPersonalData = async function () { await this.populate( { path: 'lastVisitedCourses', model: Course, select: 'name description -_id teachers' }) .execPopulate(); const lastVisitedCourses = await Promise.all(this.lastVisitedCourses.map( async (course: ICourseModel) => { return await course.exportJSON(true, true); })); const obj = this.toObject(); obj.lastVisitedCourses = lastVisitedCourses; // remove unwanted informations // mongo properties delete obj._id; delete obj.createdAt; delete obj.__v; delete obj.updatedAt; delete obj.id; // custom properties return obj; }; userSchema.methods.getCourses = async function () { const localUser = <IUserModel><any>this; return Course.find({courseAdmin: localUser._id}); }; // The idea behind the editLevels is to only allow updates if the currentUser "has a higher level" than the target. // (Or when the currentUser is an admin or targets itself.) const editLevels: {[key: string]: number} = { student: 0, teacher: 0, admin: 2, }; userSchema.statics.getEditLevel = function (user: IUser): number { return editLevels[user.role]; }; userSchema.statics.getEditLevelUnsafe = function (user: any): number | undefined { return editLevels[user.role]; }; userSchema.statics.checkPrivileges = function (user: IUser): IUserPrivileges { const userIsAdmin: boolean = user.role === 'admin'; const userIsTeacher: boolean = user.role === 'teacher'; const userIsStudent: boolean = user.role === 'student'; // NOTE: The 'tutor' role is currently unused / disabled. // const userIsTutor: boolean = user.role === 'tutor'; const userEditLevel: number = User.getEditLevel(user); return {userIsAdmin, userIsTeacher, userIsStudent, userEditLevel}; }; userSchema.statics.checkEditUser = function (currentUser: IUser, targetUser: IUser): IUserEditPrivileges { const {userIsAdmin, ...userIs} = User.checkPrivileges(currentUser); const currentEditLevel = User.getEditLevel(currentUser); const targetEditLevel = User.getEditLevel(targetUser); const editSelf = extractMongoId(currentUser._id) === extractMongoId(targetUser._id); const editLevelHigher = currentEditLevel > targetEditLevel; // Note that editAllowed only means authorization to edit SOME (herein unspecified) properties. // If false, it serves as a definite indicator that absolutely NO edit access is to be granted, // but if true, it by itself is not enough information to know what exactly is allowed. // (I.e. it DOES NOT mean unrestricted editing capabilties.) const editAllowed = userIsAdmin || editSelf || editLevelHigher; return { userIsAdmin, ...userIs, currentEditLevel, targetEditLevel, editSelf, editLevelHigher, editAllowed }; }; userSchema.statics.forSafe = function (user: IUser | IUserModel): IUserSubSafe { const { profile: {firstName, lastName} } = user; const result: IUserSubSafe = { _id: <string>extractMongoId(user._id), profile: {firstName, lastName} }; const picture = ensureMongoToObject(user.profile.picture); if (Object.keys(picture).length) { result.profile.picture = picture; } return result; }; userSchema.statics.forTeacher = function (user: IUser | IUserModel): IUserSubTeacher { const { uid, email } = user; return { ...User.forSafe(user), uid, email }; }; userSchema.statics.forCourseView = function (user: IUser | IUserModel): IUserSubCourseView { const { email } = user; return { ...User.forSafe(user), email }; }; userSchema.statics.forUser = function (user: IUser | IUserModel, otherUser: IUser): IUserSubSafe | IUserSubTeacher | IUser { const {userIsTeacher, userIsAdmin} = User.checkPrivileges(otherUser); const isSelf = extractMongoId(user._id) === extractMongoId(otherUser._id); if (isSelf || userIsAdmin) { return ensureMongoToObject(user); } else if (userIsTeacher) { return User.forTeacher(user); } else { return User.forSafe(user); } }; User = mongoose.model<IUserModel, IUserMongoose>('User', userSchema); export {User, IUserModel};
the_stack
import * as chai from 'chai'; import { StorageService } from '../../src/services/storage.service'; //const assert = chai.assert; const expect = chai.expect; const storageService = new StorageService(); describe('Storage Service uncategorized Methods', ()=>{ beforeEach('Setting up the storage data', () => { storageService.addFollower('1'); storageService.addFollower('10'); storageService.addFollower('101'); storageService.addFollower('1010'); }); afterEach('Resetting storage data', () => { storageService.wipeData(); }); /** * @link StorageService.setWaitTimeBeforeDelete * */ it('should set the wait time before delete in seconds', () => { storageService['setWaitTimeBeforeDelete'](50); //setting minutes expect(storageService['waitTimeBeforeDeleteData']).be.equal(50 * 60); }); /** * @link StorageService.wipeData * */ it('should reset whole database', () => { storageService.wipeData(); expect(storageService.getLikesLength()).to.be.an('number').and.be.equal(0); expect(storageService.getDisLikesLength()).to.be.an('number').and.be.equal(0); expect(storageService.getFollowersLength()).to.be.an('number').and.be.equal(0); expect(storageService.getUnFollowsLength()).to.be.an('number').and.be.equal(0); }); /** * @link StorageService.cleanUp * */ it('should clean all outdated data saved in the database', ()=>{ storageService['database'] .set(storageService['dislikesPath'], { '345905345': Date.now(), '458305953': new Date(Date.now() - 30 * 1000).getTime(), // + 30 seconds '384595398': new Date(Date.now() - 90 * 1000).getTime(), // + 90 seconds }) .write(); storageService['database'] .set(storageService['unfollowsPath'], { '34590348905': Date.now(), '45830958903': new Date(Date.now() - 30 * 1000).getTime(), // + 30 seconds '38459398908': new Date(Date.now() - 90 * 1000).getTime(), // + 90 seconds }) .write(); // declare data as outdated if older than 1 minute storageService['setWaitTimeBeforeDelete'](1); // only two record of each should stay storageService.cleanUp(); expect(storageService.getDisLikesLength()).be.equal(2); expect(storageService.getUnFollowsLength()).be.equal(2); }) }); describe('Storage Service Like/Dislike Tests', () => { const likeId: string = '23457235802395023'; beforeEach('Setting up the storage data', () => { storageService.addLike(likeId); }); afterEach('Resetting storage data', () => { storageService.wipeData(); }); /** * @link StorageService.addLike * */ it('should add a new like to database', () => { expect(storageService.hasLike('3495834')).to.be.false; storageService.addLike('3495834'); expect(storageService.hasLike('3495834')).to.be.true; }); /** * @link StorageService.addDisLiked * */ it('should add a new dislike to database', () => { storageService.addLike('3495834'); expect(storageService.hasDisLike('3495834')).to.be.false; storageService['addDisLiked']('3495834'); expect(storageService.hasDisLike('3495834')).to.be.true; }); /** * @link StorageService.hasLike * */ it('checks if posts already has been liked', () => { expect(storageService.hasLike(likeId)).be.true; }); /** * @link StorageService.getLikesLength * */ it('should return the length of the actual saved likes in the database', () => { storageService.addLike('48375984343'); // 2 storageService.addLike('34583485347'); // 3 storageService.addLike('83459345345'); // 4 storageService.addLike('83459345345'); // still 4, same number as above expect(storageService.getLikesLength()).to.be.an('number'); expect(storageService.getLikesLength()).to.be.equal(4); }); /** * @link StorageService.hasDisLike * */ it('checks if posts already has been disliked', () => { expect(storageService.hasDisLike(likeId)).be.false; storageService.disLiked(likeId); expect(storageService.hasDisLike(likeId)).be.true; }); /** * @link StorageService.getDisLikesLength * */ it('should return the length of the actual saved dislikes in the database', () => { storageService.addLike('48375984343'); storageService.addLike('34583485347'); storageService.addLike('83459345345'); storageService.disLiked('48375984343'); // 1 storageService.disLiked('34583485347'); // 2 storageService.disLiked('83459345345'); // 3 storageService.disLiked('83459345345'); // still 3 expect(storageService.getDisLikesLength()).to.be.an('number'); expect(storageService.getDisLikesLength()).to.be.equal(3); }); /** * @link StorageService.getDislikeableLength * */ it('should return a count of posts that can be disliked', () => { storageService['database'] .set(storageService['likesPath'], { '34590345': Date.now(), '45830953': new Date(Date.now() - 30 * 1000).getTime(), // + 30 seconds '38457937': new Date(Date.now() - 50 * 1000).getTime(), // + 60 seconds '38459398': new Date(Date.now() - 90 * 1000).getTime(), // + 90 seconds }) .write(); expect(storageService.getDislikeableLength(60)).to.be.an('number'); expect(storageService.getDislikeableLength(60)).be.equal(1); }); /** * @link StorageService.getLikes * */ it('should return all saved liked posts in the database', () => { expect(storageService.getLikes()) .to.be.an('object') .and.haveOwnProperty(likeId); }); /** * @link StorageService.getDisLikes * */ it('should return all saved dislikes posts in the database', () => { storageService.disLiked(likeId); expect(storageService.getDisLikes()) .to.be.an('object') .and.haveOwnProperty(likeId); }); /** * @link StorageService.canLike * */ it('should return if postId is likeable', () => { expect(storageService.canLike(likeId)).to.be.false; expect(storageService.canLike('likableId')).to.be.true; }); /** * @link StorageService.getDislikeable * */ it('should return all dislikeable posts at the moment', () => { storageService['database'] .set(storageService['likesPath'], { '34590345': Date.now(), '45830953': new Date(Date.now() - 30 * 1000).getTime(), // + 30 seconds '38457937': new Date(Date.now() - 50 * 1000).getTime(), // + 50 seconds '38459398': new Date(Date.now() - 90 * 1000).getTime(), // + 90 seconds }) .write(); expect(storageService.getDislikeable(45)) .to.be.an('object') .and.keys('38457937', '38459398'); }); /** * @link StorageService.disLiked * */ it('should remove like and add dislike', () => { expect(storageService.hasLike(likeId)).to.be.true; storageService.disLiked(likeId); expect(storageService.hasLike(likeId)).to.be.false; expect(storageService.hasDisLike(likeId)).to.be.true; }); /** * @link StorageService.removeLike * */ it('should only remove one like', () => { storageService.addLike('1'); storageService.addLike('2'); storageService.addLike('3'); expect(storageService.hasLike('1')).to.be.true; storageService['removeLike']('1'); expect(storageService.hasLike('1')).to.be.false; expect(storageService.hasLike('2')).to.be.true; expect(storageService.hasLike('3')).to.be.true; expect(storageService.hasDisLike('1')).to.be.false; }); /** * @link StorageService.removeDisLike * */ it('should only remove one dislike', () => { storageService.disLiked('1'); storageService.disLiked('2'); storageService.disLiked('3'); expect(storageService.hasDisLike('1')).be.true; storageService['removeDisLike']('1'); expect(storageService.hasDisLike('1')).be.false; expect(storageService.hasDisLike('2')).be.true; expect(storageService.hasDisLike('3')).be.true; expect(storageService.hasLike('1')).be.false; }); }); describe('Storage Service Follow/Unfollow Tests', () => { const followerId: string = '32487958347258937'; beforeEach('Setting up the storage data', () => { storageService.addFollower(followerId); }); afterEach('Resetting storage data', () => { storageService.wipeData(); }); /** * @link StorageService.hasFollower * */ it('checks if follower already has been followed', () => { expect(storageService.hasFollower('followerId')).to.be.false; storageService.addFollower('followerId'); expect(storageService.hasFollower('followerId')).to.be.true; }); /** * @link StorageService.hasUnFollowed * */ it('checks if follower already has been unfollowed', () => { expect(storageService.hasUnFollowed('followerId')).to.be.false; storageService.unFollowed('followerId'); expect(storageService.hasUnFollowed('followerId')).to.be.true; }); /** * @link StorageService.getFollowersLength * */ it('should return saved followers length inside database', () => { expect(storageService.getFollowersLength()).to.equal(1); storageService.addFollower('theFollower123'); expect(storageService.getFollowersLength()).to.equal(2); }); /** * @link StorageService.getUnFollowsLength * */ it('should return saved unfollowed length inside database', () => { expect(storageService.getUnFollowsLength()).to.equal(0); storageService.unFollowed('firstFollower'); expect(storageService.getUnFollowsLength()).to.equal(1); storageService.unFollowed('theFollower123'); expect(storageService.getUnFollowsLength()).to.equal(2); }); /** * @link StorageService.getUnfollowableLength * */ it('should return a count of unfollowable users', () => { storageService['database'] .set(storageService['followerPath'], { '34590345': Date.now(), '45830953': new Date(Date.now() - 30 * 1000).getTime(), // + 30 seconds '38457937': new Date(Date.now() - 50 * 1000).getTime(), // + 60 seconds '38459398': new Date(Date.now() - 90 * 1000).getTime(), // + 90 seconds }) .write(); expect(storageService.getUnfollowableLength(60)).to.be.an('number'); expect(storageService.getUnfollowableLength(60)).be.equal(1); }); /** * @link StorageService.getFollowers * */ it('should return all saved followers in the database', () => { expect(storageService.getFollowers()) .to.be.an('object') .and.haveOwnProperty(followerId); }); /** * @link StorageService.getUnfollowed * */ it('should return all saved unfollowed in the database', () => { storageService.unFollowed('aCrazyDude'); expect(storageService.getUnfollowed()) .to.be.an('object') .and.haveOwnProperty('aCrazyDude'); }); /** * @link StorageService.canFollow * */ it('should return if user can be followed', () => { expect(storageService.canFollow(followerId)).to.be.false; expect(storageService.canFollow('f299403')).to.be.true; }); /** * @link StorageService.getUnfollowable * */ it('should return all unfollowable users at the moment', () => { storageService['database'] .set(storageService['followerPath'], { '34590345': Date.now(), '45830953': new Date(Date.now() - 30 * 1000).getTime(), // + 30 seconds '38457937': new Date(Date.now() - 50 * 1000).getTime(), // + 50 seconds '38459398': new Date(Date.now() - 90 * 1000).getTime(), // + 90 seconds }) .write(); expect(storageService.getUnfollowable(45)) .to.be.an('object') .and.keys('38457937', '38459398'); }); /** * @link StorageService.unFollowed * */ it('should remove like and add dislike', () => { expect(storageService.hasFollower(followerId)).to.be.true; storageService.unFollowed(followerId); expect(storageService.hasFollower(followerId)).to.be.false; expect(storageService.hasUnFollowed(followerId)).to.be.true; }); /** * @link StorageService.removeFollower * */ it('should remove a follower from database', () => { expect(storageService.hasFollower(followerId)).to.be.true; storageService['removeFollower'](followerId); expect(storageService.hasFollower(followerId)).to.be.false; }); /** * @link StorageService.removeUnfollowed * */ it('should remove a unfollowed from database', () => { expect(storageService.hasUnFollowed(followerId)).to.be.false; storageService.unFollowed(followerId); expect(storageService.hasUnFollowed(followerId)).to.be.true; storageService['removeUnfollowed'](followerId); expect(storageService.hasFollower(followerId)).to.be.false; }); /** * @link StorageService.addFollower * */ it('should add a follower to the database', () => { expect(storageService.hasFollower('fofo')).to.be.false; storageService.addFollower('fofo'); expect(storageService.hasFollower('fofo')).to.be.true; }); /** * @link StorageService.addUnfollowed * */ it('should add a unfollowed to the database', () => { expect(storageService.hasUnFollowed('uouo')).to.be.false; storageService['addUnfollowed']('uouo'); expect(storageService.hasUnFollowed('uouo')).to.be.true; }); });
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a Virtual Desktop Application. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const example = new azure.core.ResourceGroup("example", {location: "West Europe"}); * const pooledbreadthfirst = new azure.desktopvirtualization.HostPool("pooledbreadthfirst", { * location: example.location, * resourceGroupName: example.name, * type: "Pooled", * loadBalancerType: "BreadthFirst", * }); * const personalautomatic = new azure.desktopvirtualization.HostPool("personalautomatic", { * location: example.location, * resourceGroupName: example.name, * type: "Personal", * personalDesktopAssignmentType: "Automatic", * }); * const remoteapp = new azure.desktopvirtualization.ApplicationGroup("remoteapp", { * location: example.location, * resourceGroupName: example.name, * type: "RemoteApp", * hostPoolId: pooledbreadthfirst.id, * friendlyName: "TestAppGroup", * description: "Acceptance Test: An application group", * }); * const chrome = new azure.desktopvirtualization.Application("chrome", { * applicationGroupId: remoteapp.id, * friendlyName: "Google Chrome", * description: "Chromium based web browser", * path: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", * commandLineArgumentPolicy: "DoNotAllow", * commandLineArguments: "--incognito", * showInPortal: false, * iconPath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", * iconIndex: 0, * }); * ``` * * ## Import * * Virtual Desktop Application can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:desktopvirtualization/application:Application example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup1/providers/Microsoft.DesktopVirtualization/applicationGroups/myapplicationgroup/applications/myapplication * ``` */ export class Application extends pulumi.CustomResource { /** * Get an existing Application resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ApplicationState, opts?: pulumi.CustomResourceOptions): Application { return new Application(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:desktopvirtualization/application:Application'; /** * Returns true if the given object is an instance of Application. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Application { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Application.__pulumiType; } /** * Resource ID for a Virtual Desktop Application Group to associate with the * Virtual Desktop Application. Changing the ID forces a new resource to be created. */ public readonly applicationGroupId!: pulumi.Output<string>; /** * Specifies whether this published application can be launched with command line arguments provided by the client, command line arguments specified at publish time, or no command line arguments at all. Possible values include: `DoNotAllow`, `Allow`, `Require`. */ public readonly commandLineArgumentPolicy!: pulumi.Output<string>; /** * Command Line Arguments for Virtual Desktop Application. */ public readonly commandLineArguments!: pulumi.Output<string | undefined>; /** * Option to set a description for the Virtual Desktop Application. */ public readonly description!: pulumi.Output<string | undefined>; /** * Option to set a friendly name for the Virtual Desktop Application. */ public readonly friendlyName!: pulumi.Output<string>; /** * The index of the icon you wish to use. */ public readonly iconIndex!: pulumi.Output<number | undefined>; /** * Specifies the path for an icon which will be used for this Virtual Desktop Application. */ public readonly iconPath!: pulumi.Output<string>; /** * The name of the Virtual Desktop Application. Changing the name forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * The file path location of the app on the Virtual Desktop OS. */ public readonly path!: pulumi.Output<string>; /** * Specifies whether to show the RemoteApp program in the RD Web Access server. */ public readonly showInPortal!: pulumi.Output<boolean | undefined>; /** * Create a Application resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ApplicationArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ApplicationArgs | ApplicationState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ApplicationState | undefined; inputs["applicationGroupId"] = state ? state.applicationGroupId : undefined; inputs["commandLineArgumentPolicy"] = state ? state.commandLineArgumentPolicy : undefined; inputs["commandLineArguments"] = state ? state.commandLineArguments : undefined; inputs["description"] = state ? state.description : undefined; inputs["friendlyName"] = state ? state.friendlyName : undefined; inputs["iconIndex"] = state ? state.iconIndex : undefined; inputs["iconPath"] = state ? state.iconPath : undefined; inputs["name"] = state ? state.name : undefined; inputs["path"] = state ? state.path : undefined; inputs["showInPortal"] = state ? state.showInPortal : undefined; } else { const args = argsOrState as ApplicationArgs | undefined; if ((!args || args.applicationGroupId === undefined) && !opts.urn) { throw new Error("Missing required property 'applicationGroupId'"); } if ((!args || args.commandLineArgumentPolicy === undefined) && !opts.urn) { throw new Error("Missing required property 'commandLineArgumentPolicy'"); } if ((!args || args.path === undefined) && !opts.urn) { throw new Error("Missing required property 'path'"); } inputs["applicationGroupId"] = args ? args.applicationGroupId : undefined; inputs["commandLineArgumentPolicy"] = args ? args.commandLineArgumentPolicy : undefined; inputs["commandLineArguments"] = args ? args.commandLineArguments : undefined; inputs["description"] = args ? args.description : undefined; inputs["friendlyName"] = args ? args.friendlyName : undefined; inputs["iconIndex"] = args ? args.iconIndex : undefined; inputs["iconPath"] = args ? args.iconPath : undefined; inputs["name"] = args ? args.name : undefined; inputs["path"] = args ? args.path : undefined; inputs["showInPortal"] = args ? args.showInPortal : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Application.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Application resources. */ export interface ApplicationState { /** * Resource ID for a Virtual Desktop Application Group to associate with the * Virtual Desktop Application. Changing the ID forces a new resource to be created. */ applicationGroupId?: pulumi.Input<string>; /** * Specifies whether this published application can be launched with command line arguments provided by the client, command line arguments specified at publish time, or no command line arguments at all. Possible values include: `DoNotAllow`, `Allow`, `Require`. */ commandLineArgumentPolicy?: pulumi.Input<string>; /** * Command Line Arguments for Virtual Desktop Application. */ commandLineArguments?: pulumi.Input<string>; /** * Option to set a description for the Virtual Desktop Application. */ description?: pulumi.Input<string>; /** * Option to set a friendly name for the Virtual Desktop Application. */ friendlyName?: pulumi.Input<string>; /** * The index of the icon you wish to use. */ iconIndex?: pulumi.Input<number>; /** * Specifies the path for an icon which will be used for this Virtual Desktop Application. */ iconPath?: pulumi.Input<string>; /** * The name of the Virtual Desktop Application. Changing the name forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The file path location of the app on the Virtual Desktop OS. */ path?: pulumi.Input<string>; /** * Specifies whether to show the RemoteApp program in the RD Web Access server. */ showInPortal?: pulumi.Input<boolean>; } /** * The set of arguments for constructing a Application resource. */ export interface ApplicationArgs { /** * Resource ID for a Virtual Desktop Application Group to associate with the * Virtual Desktop Application. Changing the ID forces a new resource to be created. */ applicationGroupId: pulumi.Input<string>; /** * Specifies whether this published application can be launched with command line arguments provided by the client, command line arguments specified at publish time, or no command line arguments at all. Possible values include: `DoNotAllow`, `Allow`, `Require`. */ commandLineArgumentPolicy: pulumi.Input<string>; /** * Command Line Arguments for Virtual Desktop Application. */ commandLineArguments?: pulumi.Input<string>; /** * Option to set a description for the Virtual Desktop Application. */ description?: pulumi.Input<string>; /** * Option to set a friendly name for the Virtual Desktop Application. */ friendlyName?: pulumi.Input<string>; /** * The index of the icon you wish to use. */ iconIndex?: pulumi.Input<number>; /** * Specifies the path for an icon which will be used for this Virtual Desktop Application. */ iconPath?: pulumi.Input<string>; /** * The name of the Virtual Desktop Application. Changing the name forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The file path location of the app on the Virtual Desktop OS. */ path: pulumi.Input<string>; /** * Specifies whether to show the RemoteApp program in the RD Web Access server. */ showInPortal?: pulumi.Input<boolean>; }
the_stack
import type {Mutable, ObserverType, AnyTiming, ContinuousScale} from "@swim/util"; import type {FastenerOwner, FastenerFlags} from "@swim/component"; import type {R2Box} from "@swim/math"; import type {GestureInputType} from "./GestureInput"; import type {GestureMethod} from "./Gesture"; import {MomentumGestureInit, MomentumGestureClass, MomentumGesture} from "./MomentumGesture"; import {ScaleGestureInput} from "./ScaleGestureInput"; import {MouseScaleGesture} from "./"; // forward import import {TouchScaleGesture} from "./"; // forward import import {PointerScaleGesture} from "./"; // forward import import type {ViewContext} from "../view/ViewContext"; import {View} from "../"; // forward import /** @public */ export interface ScaleGestureInit<V extends View = View, X = unknown, Y = unknown> extends MomentumGestureInit<V> { extends?: {prototype: ScaleGesture<any, any, any, any>} | string | boolean | null; /** * The minimum radial distance between input positions, in pixels. * Used to avoid scale gesture singularities. */ distanceMin?: number; preserveAspectRatio?: boolean; wheel?: boolean; getXScale?(): ContinuousScale<X, number> | null; setXScale?(xScale: ContinuousScale<X, number> | null, timing?: AnyTiming | boolean): void; getYScale?(): ContinuousScale<Y, number> | null; setYScale?(yScale: ContinuousScale<Y, number> | null, timing?: AnyTiming | boolean): void; willBeginHover?(input: ScaleGestureInput<X, Y>, event: Event | null): void; didBeginHover?(input: ScaleGestureInput<X, Y>, event: Event | null): void; willEndHover?(input: ScaleGestureInput<X, Y>, event: Event | null): void; didEndHover?(input: ScaleGestureInput<X, Y>, event: Event | null): void; willBeginPress?(input: ScaleGestureInput<X, Y>, event: Event | null): boolean | void; didBeginPress?(input: ScaleGestureInput<X, Y>, event: Event | null): void; willMovePress?(input: ScaleGestureInput<X, Y>, event: Event | null): void; didMovePress?(input: ScaleGestureInput<X, Y>, event: Event | null): void; willEndPress?(input: ScaleGestureInput<X, Y>, event: Event | null): void; didEndPress?(input: ScaleGestureInput<X, Y>, event: Event | null): void; willCancelPress?(input: ScaleGestureInput<X, Y>, event: Event | null): void; didCancelPress?(input: ScaleGestureInput<X, Y>, event: Event | null): void; willPress?(input: ScaleGestureInput<X, Y>, event: Event | null): void; didPress?(input: ScaleGestureInput<X, Y>, event: Event | null): void; willLongPress?(input: ScaleGestureInput<X, Y>): void; didLongPress?(input: ScaleGestureInput<X, Y>): void; willBeginCoast?(input: ScaleGestureInput<X, Y>, event: Event | null): boolean | void; didBeginCoast?(input: ScaleGestureInput<X, Y>, event: Event | null): void; willEndCoast?(input: ScaleGestureInput<X, Y>, event: Event | null): void; didEndCoast?(input: ScaleGestureInput<X, Y>, event: Event | null): void; } /** @public */ export type ScaleGestureDescriptor<O = unknown, V extends View = View, X = unknown, Y = unknown, I = {}> = ThisType<ScaleGesture<O, V, X, Y> & I> & ScaleGestureInit<V, X, Y> & Partial<I>; /** @public */ export interface ScaleGestureClass<G extends ScaleGesture<any, any, any, any> = ScaleGesture<any, any, any, any>> extends MomentumGestureClass<G> { /** @internal */ readonly DistanceMin: number; /** @internal */ readonly PreserveAspectRatioFlag: FastenerFlags; /** @internal */ readonly WheelFlag: FastenerFlags; /** @internal */ readonly NeedsRescale: FastenerFlags; /** @internal @override */ readonly FlagShift: number; /** @internal @override */ readonly FlagMask: FastenerFlags; } /** @public */ export interface ScaleGestureFactory<G extends ScaleGesture<any, any, any, any> = ScaleGesture<any, any, any, any>> extends ScaleGestureClass<G> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): ScaleGestureFactory<G> & I; specialize(method: GestureMethod): ScaleGestureFactory | null; define<O, V extends View = View, X = unknown, Y = unknown>(className: string, descriptor: ScaleGestureDescriptor<O, V, X, Y>): ScaleGestureFactory<ScaleGesture<any, V, X, Y>>; define<O, V extends View = View, X = unknown, Y = unknown>(className: string, descriptor: {observes: boolean} & ScaleGestureDescriptor<O, V, X, Y, ObserverType<V>>): ScaleGestureFactory<ScaleGesture<any, V, X, Y>>; define<O, V extends View = View, X = unknown, Y = unknown, I = {}>(className: string, descriptor: {implements: unknown} & ScaleGestureDescriptor<O, V, X, Y, I>): ScaleGestureFactory<ScaleGesture<any, V, X, Y> & I>; define<O, V extends View = View, X = unknown, Y = unknown, I = {}>(className: string, descriptor: {implements: boolean; observes: boolean} & ScaleGestureDescriptor<O, V, X, Y, I & ObserverType<V>>): ScaleGestureFactory<ScaleGesture<any, V, X, Y> & I>; <O, V extends View = View, X = unknown, Y = unknown>(descriptor: ScaleGestureDescriptor<O, V, X, Y>): PropertyDecorator; <O, V extends View = View, X = unknown, Y = unknown>(descriptor: {observes: boolean} & ScaleGestureDescriptor<O, V, X, Y, ObserverType<V>>): PropertyDecorator; <O, V extends View = View, X = unknown, Y = unknown, I = {}>(descriptor: {implements: unknown} & ScaleGestureDescriptor<O, V, X, Y, I>): PropertyDecorator; <O, V extends View = View, X = unknown, Y = unknown, I = {}>(descriptor: {implements: boolean; observes: boolean} & ScaleGestureDescriptor<O, V, X, Y, I & ObserverType<V>>): PropertyDecorator; } /** @public */ export interface ScaleGesture<O = unknown, V extends View = View, X = unknown, Y = unknown> extends MomentumGesture<O, V> { /** @internal @override */ readonly inputs: {readonly [inputId: string]: ScaleGestureInput<X, Y> | undefined}; /** @override */ getInput(inputId: string | number): ScaleGestureInput<X, Y> | null; /** @internal @override */ createInput(inputId: string, inputType: GestureInputType, isPrimary: boolean, x: number, y: number, t: number): ScaleGestureInput<X, Y>; /** @internal @override */ getOrCreateInput(inputId: string | number, inputType: GestureInputType, isPrimary: boolean, x: number, y: number, t: number): ScaleGestureInput<X, Y>; /** @internal @override */ clearInput(input: ScaleGestureInput<X, Y>): void; /** @internal @override */ clearInputs(): void; distanceMin: number; get preserveAspectRatio(): boolean; set preserveAspectRatio(preserveAspectRatio: boolean); get wheel(): boolean; set wheel(wheel: boolean); getXScale(): ContinuousScale<X, number> | null; setXScale(xScale: ContinuousScale<X, number> | null, timing?: AnyTiming | boolean): void; getYScale(): ContinuousScale<Y, number> | null; setYScale(yScale: ContinuousScale<Y, number> | null, timing?: AnyTiming | boolean): void; /** @internal */ clientToRangeX(clientX: number, xScale: ContinuousScale<X, number>, bounds: R2Box): number; /** @internal */ clientToRangeY(clientY: number, yScale: ContinuousScale<Y, number>, bounds: R2Box): number; /** @internal */ unscaleX(clientX: number, xScale: ContinuousScale<X, number>, bounds: R2Box): X; /** @internal */ unscaleY(clientY: number, yScale: ContinuousScale<Y, number>, bounds: R2Box): Y; /** @internal @override */ viewWillAnimate(viewContext: ViewContext): void; /** @protected @override */ onBeginPress(input: ScaleGestureInput<X, Y>, event: Event | null): void; /** @protected @override */ onMovePress(input: ScaleGestureInput<X, Y>, event: Event | null): void; /** @protected @override */ onEndPress(input: ScaleGestureInput<X, Y>, event: Event | null): void; /** @protected @override */ onCancelPress(input: ScaleGestureInput<X, Y>, event: Event | null): void; /** @internal @override */ beginCoast(input: ScaleGestureInput<X, Y>, event: Event | null): void; /** @protected @override */ onBeginCoast(input: ScaleGestureInput<X, Y>, event: Event | null): void; /** @protected @override */ onEndCoast(input: ScaleGestureInput<X, Y>, event: Event | null): void; /** @protected @override */ onCoast(): void; /** @internal */ updateInputDomain(input: ScaleGestureInput<X, Y>, xScale?: ContinuousScale<X, number> | null, yScale?: ContinuousScale<Y, number> | null, bounds?: R2Box): void; /** @internal */ neutralizeX(): void; /** @internal */ neutralizeY(): void; /** @internal */ rescale(): void; /** @internal */ rescaleRadial(oldXScale: ContinuousScale<X, number>, oldYScale: ContinuousScale<Y, number>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y>, bounds: R2Box): void; /** @internal */ rescaleXY(oldXScale: ContinuousScale<X, number>, oldYScale: ContinuousScale<Y, number>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y> | undefined, bounds: R2Box): void; /** @internal */ rescaleX(oldXScale: ContinuousScale<X, number>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y> | undefined, bounds: R2Box): void; /** @internal */ rescaleY(oldYScale: ContinuousScale<Y, number>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y> | undefined, bounds: R2Box): void; /** @internal */ conserveMomentum(input0: ScaleGestureInput<X, Y>): void; /** @internal */ distributeXYMomentum(input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y>): void; /** @internal */ distributeXMomentum(input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y>): void; /** @internal */ distributeYMomentum(input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y>): void; /** @internal @override */ integrate(t: number): void; /** @internal */ zoom(x: number, y: number, dz: number, event: Event | null): void; /** @internal @override */ get observes(): boolean; } /** @public */ export const ScaleGesture = (function (_super: typeof MomentumGesture) { const ScaleGesture: ScaleGestureFactory = _super.extend("ScaleGesture"); ScaleGesture.prototype.createInput = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, inputId: string, inputType: GestureInputType, isPrimary: boolean, x: number, y: number, t: number): ScaleGestureInput<X, Y> { return new ScaleGestureInput(inputId, inputType, isPrimary, x, y, t); }; ScaleGesture.prototype.clearInputs = function (this: ScaleGesture): void { MomentumGesture.prototype.clearInputs.call(this); this.setFlags(this.flags & ~ScaleGesture.NeedsRescale); }; Object.defineProperty(ScaleGesture.prototype, "preserveAspectRatio", { get(this: ScaleGesture): boolean { return (this.flags & ScaleGesture.PreserveAspectRatioFlag) !== 0; }, set(this: ScaleGesture, preserveAspectRatio: boolean): void { if (preserveAspectRatio) { this.setFlags(this.flags | ScaleGesture.PreserveAspectRatioFlag); } else { this.setFlags(this.flags & ~ScaleGesture.PreserveAspectRatioFlag); } }, configurable: true, }); Object.defineProperty(ScaleGesture.prototype, "wheel", { get(this: ScaleGesture): boolean { return (this.flags & ScaleGesture.WheelFlag) !== 0; }, set(this: ScaleGesture, wheel: boolean): void { if (wheel) { this.setFlags(this.flags | ScaleGesture.WheelFlag); } else { this.setFlags(this.flags & ~ScaleGesture.WheelFlag); } }, configurable: true, }); ScaleGesture.prototype.getXScale = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>): ContinuousScale<X, number> | null { return null; // hook }; ScaleGesture.prototype.setXScale = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, xScale: ContinuousScale<X, number> | null, timing?: AnyTiming | boolean): void { // hook }; ScaleGesture.prototype.getYScale = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>): ContinuousScale<Y, number> | null { return null; // hook }; ScaleGesture.prototype.setYScale = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, yScale: ContinuousScale<Y, number> | null, timing?: AnyTiming | boolean): void { // hook }; ScaleGesture.prototype.clientToRangeX = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, clientX: number, xScale: ContinuousScale<X, number>, bounds: R2Box): number { const viewX = clientX - bounds.xMin; const xRange = xScale.range; if (xRange[0] <= xRange[1]) { return xRange[0] + viewX; } else { return bounds.xMax + viewX - xRange[0]; } }; ScaleGesture.prototype.clientToRangeY = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, clientY: number, yScale: ContinuousScale<Y, number>, bounds: R2Box): number { const viewY = clientY - bounds.yMin; const yRange = yScale.range; if (yRange[0] <= yRange[1]) { return yRange[0] + viewY; } else { return bounds.yMax + viewY - yRange[0]; } }; ScaleGesture.prototype.unscaleX = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, clientX: number, xScale: ContinuousScale<X, number>, bounds: R2Box): X { return xScale.inverse(this.clientToRangeX(clientX, xScale, bounds)); }; ScaleGesture.prototype.unscaleY = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, clientY: number, yScale: ContinuousScale<Y, number>, bounds: R2Box): Y { return yScale.inverse(this.clientToRangeY(clientY, yScale, bounds)); }; ScaleGesture.prototype.viewWillAnimate = function (this: ScaleGesture, viewContext: ViewContext): void { MomentumGesture.prototype.viewWillAnimate.call(this, viewContext); if ((this.flags & ScaleGesture.NeedsRescale) !== 0) { this.rescale(); } }; ScaleGesture.prototype.onBeginPress = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input: ScaleGestureInput<X, Y>, event: Event | null): void { MomentumGesture.prototype.onBeginPress.call(this, input, event); this.updateInputDomain(input); this.view!.requireUpdate(View.NeedsAnimate); this.setFlags(this.flags | ScaleGesture.NeedsRescale); }; ScaleGesture.prototype.onMovePress = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input: ScaleGestureInput<X, Y>, event: Event | null): void { MomentumGesture.prototype.onMovePress.call(this, input, event); this.view!.requireUpdate(View.NeedsAnimate); this.setFlags(this.flags | ScaleGesture.NeedsRescale); }; ScaleGesture.prototype.onEndPress = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input: ScaleGestureInput<X, Y>, event: Event | null): void { MomentumGesture.prototype.onEndPress.call(this, input, event); this.updateInputDomain(input); this.view!.requireUpdate(View.NeedsAnimate); this.setFlags(this.flags | ScaleGesture.NeedsRescale); }; ScaleGesture.prototype.onCancelPress = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input: ScaleGestureInput<X, Y>, event: Event | null): void { MomentumGesture.prototype.onCancelPress.call(this, input, event); this.updateInputDomain(input); this.view!.requireUpdate(View.NeedsAnimate); this.setFlags(this.flags | ScaleGesture.NeedsRescale); }; ScaleGesture.prototype.beginCoast = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input: ScaleGestureInput<X, Y>, event: Event | null): void { if (this.coastCount < 2) { MomentumGesture.prototype.beginCoast.call(this, input, event); } }; ScaleGesture.prototype.onBeginCoast = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input: ScaleGestureInput<X, Y>, event: Event | null): void { MomentumGesture.prototype.onBeginCoast.call(this, input, event); this.updateInputDomain(input); this.conserveMomentum(input); this.view!.requireUpdate(View.NeedsAnimate); this.setFlags(this.flags | ScaleGesture.NeedsRescale); }; ScaleGesture.prototype.onEndCoast = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input: ScaleGestureInput<X, Y>, event: Event | null): void { MomentumGesture.prototype.onEndCoast.call(this, input, event); input.disableX = false; input.disableY = false; this.view!.requireUpdate(View.NeedsAnimate); this.setFlags(this.flags | ScaleGesture.NeedsRescale); }; ScaleGesture.prototype.onCoast = function (this: ScaleGesture): void { MomentumGesture.prototype.onCoast.call(this); this.view!.requireUpdate(View.NeedsAnimate); this.setFlags(this.flags | ScaleGesture.NeedsRescale); }; ScaleGesture.prototype.updateInputDomain = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input: ScaleGestureInput<X, Y>, xScale?: ContinuousScale<X, number> | null, yScale?: ContinuousScale<Y, number> | null, bounds?: R2Box): void { if (xScale === void 0) { xScale = this.getXScale(); } if (xScale !== null) { if (bounds === void 0) { bounds = this.view!.clientBounds; } input.xCoord = this.unscaleX(input.x0, xScale, bounds); } if (yScale === void 0) { yScale = this.getYScale(); } if (yScale !== null) { if (bounds === void 0) { bounds = this.view!.clientBounds; } input.yCoord = this.unscaleY(input.y0, yScale, bounds); } }; ScaleGesture.prototype.neutralizeX = function (this: ScaleGesture): void { const inputs = this.inputs; for (const inputId in inputs) { const input = inputs[inputId]!; if (input.coasting) { input.disableX = true; input.vx = 0; input.ax = 0; } } }; ScaleGesture.prototype.neutralizeY = function (this: ScaleGesture): void { const inputs = this.inputs; for (const inputId in inputs) { const input = inputs[inputId]!; if (input.coasting) { input.disableY = true; input.vy = 0; input.ay = 0; } } }; ScaleGesture.prototype.rescale = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>): void { let input0: ScaleGestureInput<X, Y> | undefined; let input1: ScaleGestureInput<X, Y> | undefined; const inputs = this.inputs; for (const inputId in inputs) { const input = inputs[inputId]!; if (input.pressing || input.coasting) { if (input0 === void 0) { input0 = input; } else if (input1 === void 0) { input1 = input; } else if (input.t0 < input0.t0) { input0 = input; } else if (input.t0 < input1.t0) { input1 = input; } } } if (input0 !== void 0) { const bounds = this.view!.clientBounds; const xScale = this.getXScale(); const yScale = this.getYScale(); if (xScale !== null && yScale !== null) { if (input1 !== void 0 && this.preserveAspectRatio) { this.rescaleRadial(xScale, yScale, input0, input1, bounds); } else { this.rescaleXY(xScale, yScale, input0, input1, bounds); } } else if (xScale !== null) { this.rescaleX(xScale, input0, input1, bounds); } else if (yScale !== null) { this.rescaleY(yScale, input0, input1, bounds); } } this.setFlags(this.flags & ~ScaleGesture.NeedsRescale); }; ScaleGesture.prototype.rescaleRadial = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, oldXScale: ContinuousScale<X, number>, oldYScale: ContinuousScale<Y, number>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y>, bounds: R2Box): void { const x0 = input0.xCoord!; const y0 = input0.yCoord!; const px0 = this.clientToRangeX(input0.x0, oldXScale, bounds); const py0 = this.clientToRangeY(input0.y0, oldYScale, bounds); const qx0 = this.clientToRangeX(input0.x, oldXScale, bounds); const qy0 = this.clientToRangeY(input0.y, oldYScale, bounds); const vx0 = input0.vx; const vy0 = input0.vy; const ax0 = input0.ax; const ay0 = input0.ay; const x1 = input1.xCoord!; const y1 = input1.yCoord!; const px1 = this.clientToRangeX(input1.x0, oldXScale, bounds); const py1 = this.clientToRangeY(input1.y0, oldYScale, bounds); const qx1 = this.clientToRangeX(input1.x, oldXScale, bounds); const qy1 = this.clientToRangeY(input1.y, oldYScale, bounds); const vx1 = input1.vx; const vy1 = input1.vy; const ax1 = input1.ax; const ay1 = input1.ay; // Compute the difference vector between previous input positions. const dpx = px1 - px0; const dpy = py1 - py0; // Normalize the previous input distance vector. const dp = Math.max(this.distanceMin, Math.sqrt(dpx * dpx + dpy * dpy)); const upx = dpx / dp; const upy = dpy / dp; // Compute the translation vectors from the previous input positions // to the current input positions. const dpqx0 = qx0 - px0; const dpqy0 = qy0 - py0; const dpqx1 = qx1 - px1; const dpqy1 = qy1 - py1; // Project the current input positions onto the unit vector separating // the previous input positions. const ip0 = dpqx0 * upx + dpqy0 * upy; const ip1 = dpqx1 * upx + dpqy1 * upy; const ix0 = ip0 * upx; const iy0 = ip0 * upy; const ix1 = ip1 * upx; const iy1 = ip1 * upy; // Project the current input positions onto the unit vector orthogonal // to the previous input positions. const jp0 = dpqx0 * upy + dpqy0 * -upx; const jp1 = dpqx1 * upy + dpqy1 * -upx; const jx0 = jp0 * upy; const jy0 = jp0 * -upx; const jx1 = jp1 * upy; const jy1 = jp1 * -upx; // Average the mean orthogonal projection of the input translations. const jpx = (jx0 + jx1) / 2; const jpy = (jy0 + jy1) / 2; // Offset the previous input positions by the radial and mean orthogonal // projections of the input translations. const rx0 = px0 + ix0 + jpx; const ry0 = py0 + iy0 + jpy; const rx1 = px1 + ix1 + jpx; const ry1 = py1 + iy1 + jpy; // Project the velocity vectors onto the unit vector separating // the previous input positions. const iv0 = vx0 * upx + vy0 * upy; const iv1 = vx1 * upx + vy1 * upy; const ivx0 = iv0 * upx; const ivy0 = iv0 * upy; const ivx1 = iv1 * upx; const ivy1 = iv1 * upy; // Project the velocity vectors onto the unit vector orthogonal // to the previous input positions. const jv0 = vx0 * upy + vy0 * -upx; const jv1 = vx1 * upy + vy1 * -upx; const jvx0 = jv0 * upy; const jvy0 = jv0 * -upx; const jvx1 = jv1 * upy; const jvy1 = jv1 * -upx; // Average the mean orthogonal projection of the input velocity. const jvx = (jvx0 + jvx1) / 2; const jvy = (jvy0 + jvy1) / 2; // Recombine the radial and mean orthogonal velocity components. let rvx0 = ivx0 + jvx; let rvy0 = ivy0 + jvy; let rvx1 = ivx1 + jvx; let rvy1 = ivy1 + jvy; // Normalize the recombined velocity vectors. const v0 = Math.sqrt(rvx0 * rvx0 + rvy0 * rvy0); const v1 = Math.sqrt(rvx1 * rvx1 + rvy1 * rvy1); const uvx0 = v0 !== 0 ? rvx0 / v0 : 0; const uvy0 = v0 !== 0 ? rvy0 / v0 : 0; const uvx1 = v1 !== 0 ? rvx1 / v1 : 0; const uvy1 = v1 !== 0 ? rvy1 / v1 : 0; // Scale the recombined velocity vectors back to their original magnitudes. rvx0 = uvx0 * v0; rvy0 = uvy0 * v0; rvx1 = uvx1 * v1; rvy1 = uvy1 * v1; // Compute the magnitudes of the acceleration vectors. const a0 = Math.sqrt(ax0 * ax0 + ay0 * ay0); const a1 = Math.sqrt(ax1 * ax1 + ay1 * ay1); // Rotate the acceleration vectors to opposite the updated velocity vectors. const rax0 = a0 * -uvx0; const ray0 = a0 * -uvy0; const rax1 = a1 * -uvx1; const ray1 = a1 * -uvy1; let newXScale: ContinuousScale<X, number> | null = null; const solvedXScale = oldXScale.solveDomain(x0, rx0, x1, rx1); if (!solvedXScale.equals(oldXScale)) { newXScale = solvedXScale; this.setXScale(newXScale); } let newYScale: ContinuousScale<Y, number> | null = null; const solvedYScale = oldYScale.solveDomain(y0, ry0, y1, ry1); if (!solvedYScale.equals(oldYScale)) { newYScale = solvedYScale; this.setYScale(newYScale); } if (newXScale !== null || newYScale !== null) { if (newXScale !== null) { input0.x0 = input0.x; input0.dx = 0; input0.vx = rvx0; input0.ax = rax0; input0.xCoord = this.unscaleX(input0.x0, newXScale, bounds); input1.x0 = input1.x; input1.dx = 0; input1.vx = rvx1; input1.ax = rax1; input1.xCoord = this.unscaleX(input1.x0, newXScale, bounds); } if (newYScale !== null) { input0.y0 = input0.y; input0.dy = 0; input0.vy = rvy0; input0.ay = ray0; input0.yCoord = this.unscaleY(input0.y0, newYScale, bounds); input1.y0 = input1.y; input1.dy = 0; input1.vy = rvy1; input1.ay = ray1; input1.yCoord = this.unscaleY(input1.y0, newYScale, bounds); } if (this.inputCount > 2) { const inputs = this.inputs; for (const inputId in inputs) { const input = inputs[inputId]!; if (input !== input0 && input !== input1) { if (newXScale !== null) { input.x0 = input.x; input.dx = 0; input.xCoord = this.unscaleX(input.x0, newXScale, bounds); } if (newYScale !== null) { input.y0 = input.y; input.dy = 0; input.yCoord = this.unscaleY(input.y0, newYScale, bounds); } } } } } }; ScaleGesture.prototype.rescaleXY = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, oldXScale: ContinuousScale<X, number>, oldYScale: ContinuousScale<Y, number>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y> | undefined, bounds: R2Box): void { const x0 = input0.xCoord!; const y0 = input0.yCoord!; let sx0 = this.clientToRangeX(input0.x, oldXScale, bounds); let sy0 = this.clientToRangeY(input0.y, oldYScale, bounds); let disableX = input0.disableX; let disableY = input0.disableY; let x1: X | undefined; let y1: Y | undefined; let sx1: number | undefined; let sy1: number | undefined; if (input1 !== void 0) { x1 = input1.xCoord!; y1 = input1.yCoord!; sx1 = this.clientToRangeX(input1.x, oldXScale, bounds); sy1 = this.clientToRangeY(input1.y, oldYScale, bounds); disableX = disableX || input1.disableX; disableY = disableY || input1.disableY; const dsx = Math.abs(sx1 - sx0); const dsy = Math.abs(sy1 - sy0); const distanceMin = this.distanceMin; if (dsx < distanceMin) { const esx = (distanceMin - dsx) / 2; if (sx0 <= sx1) { sx0 -= esx; sx1 += esx; } else { sx0 += esx; sx1 -= esx; } } if (dsy < distanceMin) { const esy = (distanceMin - dsy) / 2; if (sy0 <= sy1) { sy0 -= esy; sy1 += esy; } else { sy0 += esy; sy1 -= esy; } } } let newXScale: ContinuousScale<X, number> | null = null; if (!disableX) { newXScale = oldXScale.solveDomain(x0, sx0, x1, sx1); if (!newXScale.equals(oldXScale)) { this.setXScale(newXScale); } } let newYScale: ContinuousScale<Y, number> | null = null; if (!disableY) { newYScale = oldYScale.solveDomain(y0, sy0, y1, sy1); if (!newYScale.equals(oldYScale)) { this.setYScale(newYScale); } } if ((newXScale !== null || newYScale !== null) && this.preserveAspectRatio) { const inputs = this.inputs; for (const inputId in inputs) { const input = inputs[inputId]!; if (newXScale !== null) { input.x0 = input.x; input.dx = 0; input.xCoord = this.unscaleX(input.x0, newXScale, bounds); } if (newYScale !== null) { input.y0 = input.y; input.dy = 0; input.yCoord = this.unscaleY(input.y0, newYScale, bounds); } } } }; ScaleGesture.prototype.rescaleX = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, oldXScale: ContinuousScale<X, number>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y> | undefined, bounds: R2Box): void { const x0 = input0.xCoord!; let sx0 = this.clientToRangeX(input0.x, oldXScale, bounds); let sx1: number | undefined; let x1: X | undefined; let disableX = input0.disableX; if (input1 !== void 0) { x1 = input1.xCoord!; sx1 = this.clientToRangeX(input1.x, oldXScale, bounds); disableX = disableX || input1.disableX; const dsx = Math.abs(sx1 - sx0); const distanceMin = this.distanceMin; if (dsx < distanceMin) { const esx = (distanceMin - dsx) / 2; if (sx0 <= sx1) { sx0 -= esx; sx1 += esx; } else { sx0 += esx; sx1 -= esx; } } } if (!disableX) { const newXScale = oldXScale.solveDomain(x0, sx0, x1, sx1); if (!newXScale.equals(oldXScale)) { this.setXScale(newXScale); } } }; ScaleGesture.prototype.rescaleY = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, oldYScale: ContinuousScale<Y, number>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y> | undefined, bounds: R2Box): void { const y0 = input0.yCoord!; let sy0 = this.clientToRangeY(input0.y, oldYScale, bounds); let sy1: number | undefined; let y1: Y | undefined; let disableY = input0.disableY; if (input1 !== void 0) { y1 = input1.yCoord!; sy1 = this.clientToRangeY(input1.y, oldYScale, bounds); disableY = disableY || input1.disableY; const dsy = Math.abs(sy1 - sy0); const distanceMin = this.distanceMin; if (dsy < distanceMin) { const esy = (distanceMin - dsy) / 2; if (sy0 <= sy1) { sy0 -= esy; sy1 += esy; } else { sy0 += esy; sy1 -= esy; } } } if (!disableY) { const newYScale = oldYScale.solveDomain(y0, sy0, y1, sy1); if (!newYScale.equals(oldYScale)) { this.setYScale(newYScale); } } }; ScaleGesture.prototype.conserveMomentum = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input0: ScaleGestureInput<X, Y>): void { let input1: ScaleGestureInput<X, Y> | undefined; const inputs = this.inputs; for (const inputId in inputs) { const input = inputs[inputId]!; if (input.coasting) { if (input1 === void 0) { input1 = input; } else if (input.t0 < input1.t0) { input1 = input; } } } if (input1 !== void 0) { const xScale = this.getXScale(); const yScale = this.getYScale(); if (xScale !== null && yScale !== null) { this.distributeXYMomentum(input0, input1); } else if (xScale !== null) { this.distributeXMomentum(input0, input1); } else if (yScale !== null) { this.distributeYMomentum(input0, input1); } } }; ScaleGesture.prototype.distributeXYMomentum = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y>): void { const vx0 = input0.vx; const vy0 = input0.vy; const vx1 = input1.vx; const vy1 = input1.vy; const v0 = Math.sqrt(vx0 * vx0 + vy0 * vy0); const v1 = Math.sqrt(vx1 * vx1 + vy1 * vy1); const uvx0 = v0 !== 0 ? vx0 / v0 : 0; const uvy0 = v0 !== 0 ? vy0 / v0 : 0; const uvx1 = v1 !== 0 ? vx1 / v1 : 0; const uvy1 = v1 !== 0 ? vy1 / v1 : 0; const v = (v0 + v1) / 2; input0.vx = uvx0 * v; input0.vy = uvy0 * v; input1.vx = uvx1 * v; input1.vy = uvy1 * v; const ax0 = input0.ax; const ay0 = input0.ay; const ax1 = input1.ax; const ay1 = input1.ay; const a0 = Math.sqrt(ax0 * ax0 + ay0 * ay0); const a1 = Math.sqrt(ax1 * ax1 + ay1 * ay1); const uax0 = a0 !== 0 ? ax0 / a0 : 0; const uay0 = a0 !== 0 ? ay0 / a0 : 0; const uax1 = a1 !== 0 ? ax1 / a1 : 0; const uay1 = a1 !== 0 ? ay1 / a1 : 0; const a = (a0 + a1) / 2; input0.ax = uax0 * a; input0.ay = uay0 * a; input1.ax = uax1 * a; input1.ay = uay1 * a; }; ScaleGesture.prototype.distributeXMomentum = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y>): void { const vx0 = input0.vx; const vx1 = input1.vx; const v0 = Math.abs(vx0); const v1 = Math.abs(vx1); const uvx0 = v0 !== 0 ? vx0 / v0 : 0; const uvx1 = v1 !== 0 ? vx1 / v1 : 0; const v = (v0 + v1) / 2; input0.vx = uvx0 * v; input1.vx = uvx1 * v; const ax0 = input0.ax; const ax1 = input1.ax; const a0 = Math.abs(ax0); const a1 = Math.abs(ax1); const uax0 = a0 !== 0 ? ax0 / a0 : 0; const uax1 = a1 !== 0 ? ax1 / a1 : 0; const a = (a0 + a1) / 2; input0.ax = uax0 * a; input1.ax = uax1 * a; }; ScaleGesture.prototype.distributeYMomentum = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, input0: ScaleGestureInput<X, Y>, input1: ScaleGestureInput<X, Y>): void { const vy0 = input0.vy; const vy1 = input1.vy; const v0 = Math.sqrt(vy0); const v1 = Math.sqrt(vy1); const uvy0 = v0 !== 0 ? vy0 / v0 : 0; const uvy1 = v1 !== 0 ? vy1 / v1 : 0; const v = (v0 + v1) / 2; input0.vy = uvy0 * v; input1.vy = uvy1 * v; const ay0 = input0.ay; const ay1 = input1.ay; const a0 = Math.sqrt(ay0); const a1 = Math.sqrt(ay1); const uay0 = a0 !== 0 ? ay0 / a0 : 0; const uay1 = a1 !== 0 ? ay1 / a1 : 0; const a = (a0 + a1) / 2; input0.ay = uay0 * a; input1.ay = uay1 * a; }; ScaleGesture.prototype.integrate = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, t: number): void { let coast0: ScaleGestureInput<X, Y> | undefined; let coast1: ScaleGestureInput<X, Y> | undefined; const inputs = this.inputs; for (const inputId in inputs) { const input = inputs[inputId]!; if (input.coasting) { if (coast0 === void 0) { coast0 = input; } else if (coast1 === void 0) { coast1 = input; const dx0 = coast1.x - coast0.x; const dy0 = coast1.y - coast0.y; const d0 = Math.sqrt(dx0 * dx0 + dy0 * dy0); coast0.integrateVelocity(t); coast1.integrateVelocity(t); const dx1 = coast1.x - coast0.x; const dy1 = coast1.y - coast0.y; const d1 = Math.sqrt(dx1 * dx1 + dy1 * dy1); const s = d1 / d0; coast0.vx *= s; coast0.vy *= s; coast0.ax *= s; coast0.ay *= s; coast1.vx *= s; coast1.vy *= s; coast1.ax *= s; coast1.ay *= s; } else { input.integrateVelocity(t); } } } if (coast0 !== void 0 && coast1 === void 0) { coast0.integrateVelocity(t); } }; ScaleGesture.prototype.zoom = function <X, Y>(this: ScaleGesture<unknown, View, X, Y>, x: number, y: number, dz: number, event: Event | null): void { if (dz === 0) { return; } const t = event !== null ? event.timeStamp : performance.now(); const a = this.acceleration; let ax = a * Math.cos(Math.PI / 4); let ay = a * Math.sin(Math.PI / 4); const vMax = this.velocityMax; const vx = 0.5 * vMax * Math.cos(Math.PI / 4); const vy = 0.5 * vMax * Math.sin(Math.PI / 4); const dx = (4 * vx * vx) / ax; const dy = (4 * vy * vy) / ay; const inputs = this.inputs as {[inputId: string]: ScaleGestureInput<X, Y> | undefined}; let zoom0 = inputs.zoom0; let zoom1 = inputs.zoom1; if (zoom0 !== void 0 && zoom1 !== void 0) { const dt = t - zoom0.t; if (dt > 0) { const dzx = Math.abs(zoom1.x - zoom0.x) / 2; const dzy = Math.abs(zoom1.y - zoom0.y) / 2; dz = Math.min(Math.max(-vMax * dt, dz), vMax * dt); const zx = (dz * dzx * Math.cos(Math.PI / 4)) / dx; const zy = (dz * dzy * Math.sin(Math.PI / 4)) / dy; ax = (ax * dzx) / dx; ay = (ay * dzy) / dy; zoom0.x += zx; zoom0.y += zy; zoom0.t = t; zoom0.dx = zx; zoom0.dy = zy; zoom0.dt = dt; zoom0.vx = zx / dt; zoom0.vy = zy / dt; zoom0.ax = zoom0.vx < 0 ? ax : zoom0.vx > 0 ? -ax : 0; zoom0.ay = zoom0.vy < 0 ? ay : zoom0.vy > 0 ? -ay : 0; zoom1.x -= zx; zoom1.y -= zy; zoom1.t = t; zoom0.dx = -zx; zoom0.dy = -zy; zoom0.dt = dt; zoom1.vx = -zx / dt; zoom1.vy = -zy / dt; zoom1.ax = zoom1.vx < 0 ? ax : zoom1.vx > 0 ? -ax : 0; zoom1.ay = zoom1.vy < 0 ? ay : zoom1.vy > 0 ? -ay : 0; } } else { this.interrupt(event); if (dz < 0) { zoom0 = this.createInput("zoom0", "unknown", false, x - dx, y - dy, t); zoom0.vx = -vx; zoom0.vy = -vy; zoom0.ax = ax; zoom0.ay = ay; zoom1 = this.createInput("zoom1", "unknown", false, x + dx, y + dy, t); zoom1.vx = vx; zoom1.vy = vy; zoom1.ax = -ax; zoom1.ay = -ay; } else { zoom0 = this.createInput("zoom0", "unknown", false, x - dx, y - dy, t); zoom0.vx = vx; zoom0.vy = vy; zoom0.ax = -ax; zoom0.ay = -ay; zoom1 = this.createInput("zoom1", "unknown", false, x + dx, y + dy, t); zoom1.vx = -vx; zoom1.vy = -vy; zoom1.ax = ax; zoom1.ay = ay; } inputs.zoom0 = zoom0; inputs.zoom1 = zoom1; (this as Mutable<typeof this>).inputCount += 2; this.beginCoast(zoom0, event); this.beginCoast(zoom1, event); } }; Object.defineProperty(ScaleGesture.prototype, "observes", { value: true, enumerable: true, configurable: true, }); ScaleGesture.construct = function <G extends ScaleGesture<any, any, any, any>>(gestureClass: {prototype: G}, gesture: G | null, owner: FastenerOwner<G>): G { gesture = _super.construct(gestureClass, gesture, owner) as G; gesture.distanceMin = ScaleGesture.DistanceMin; gesture.setFlags(gesture.flags | ScaleGesture.WheelFlag); return gesture; }; ScaleGesture.specialize = function (method: GestureMethod): ScaleGestureFactory | null { if (method === "pointer") { return PointerScaleGesture; } else if (method === "touch") { return TouchScaleGesture; } else if (method === "mouse") { return MouseScaleGesture; } else if (typeof PointerEvent !== "undefined") { return PointerScaleGesture; } else if (typeof TouchEvent !== "undefined") { return TouchScaleGesture; } else { return MouseScaleGesture; } }; ScaleGesture.define = function <O, V extends View, X, Y>(className: string, descriptor: ScaleGestureDescriptor<O, V, X, Y>): ScaleGestureFactory<ScaleGesture<any, V, X, Y>> { let superClass = descriptor.extends as ScaleGestureFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; let method = descriptor.method; const hysteresis = descriptor.hysteresis; const acceleration = descriptor.hysteresis; const velocityMax = descriptor.hysteresis; const distanceMin = descriptor.distanceMin; const preserveAspectRatio = descriptor.preserveAspectRatio; const wheel = descriptor.wheel; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.method; delete descriptor.hysteresis; delete descriptor.acceleration; delete descriptor.velocityMax; delete descriptor.distanceMin; delete descriptor.preserveAspectRatio; delete descriptor.wheel; if (descriptor.key === true) { Object.defineProperty(descriptor, "key", { value: className, configurable: true, }); } else if (descriptor.key === false) { Object.defineProperty(descriptor, "key", { value: void 0, configurable: true, }); } if (method === void 0) { method = "auto"; } if (superClass === void 0 || superClass === null) { superClass = ScaleGesture.specialize(method); } if (superClass === null) { superClass = this; } const gestureClass = superClass.extend(className, descriptor); gestureClass.construct = function (gestureClass: {prototype: ScaleGesture<any, any, any, any>}, gesture: ScaleGesture<O, V, X, Y> | null, owner: O): ScaleGesture<O, V, X, Y> { gesture = superClass!.construct(gestureClass, gesture, owner); if (affinity !== void 0) { gesture.initAffinity(affinity); } if (inherits !== void 0) { gesture.initInherits(inherits); } if (hysteresis !== void 0) { gesture.hysteresis = hysteresis; } if (acceleration !== void 0) { gesture.acceleration = acceleration; } if (velocityMax !== void 0) { gesture.velocityMax = velocityMax; } if (distanceMin !== void 0) { gesture.distanceMin = distanceMin; } if (preserveAspectRatio !== void 0) { gesture.preserveAspectRatio = preserveAspectRatio; } if (wheel !== void 0) { gesture.wheel = wheel; } return gesture; }; return gestureClass; }; (ScaleGesture as Mutable<typeof ScaleGesture>).DistanceMin = 10; (ScaleGesture as Mutable<typeof ScaleGesture>).PreserveAspectRatioFlag = 1 << (_super.FlagShift + 0); (ScaleGesture as Mutable<typeof ScaleGesture>).WheelFlag = 1 << (_super.FlagShift + 1); (ScaleGesture as Mutable<typeof ScaleGesture>).NeedsRescale = 1 << (_super.FlagShift + 2); (ScaleGesture as Mutable<typeof ScaleGesture>).FlagShift = _super.FlagShift + 3; (ScaleGesture as Mutable<typeof ScaleGesture>).FlagMask = (1 << ScaleGesture.FlagShift) - 1; return ScaleGesture; })(MomentumGesture);
the_stack
import { KeyPair, PublicKey, PrivateKey, SymmetricKey } from "./secure_keygen"; import context from "./context"; import { ThemisError, ThemisErrorCode } from "./themis_error"; import { coerceToBytes, heapFree, heapGetArray, heapPutArray, heapAlloc, } from "./utils"; const cryptosystem_name = "SecureSession"; function isFunction(obj: any) { return !!(obj && obj.constructor && obj.call && obj.apply); } // Secure Session C API operatates with "secure_session_user_callbacks_t" context structure // defined in <themis/secure_session.h>. It must be filled in with C function pointers and // an arbitrary C context pointer. Associated C functions are called by Secure Session // at appropriate moments. They receive the C context pointer as their last argument which // allows to restore context. // // First, we need to be able to allocate and free "secure_session_user_callbacks_t", and to // initialize it before passing them to Secure Session constructor. // // Here's how it looks in C: // // struct secure_session_user_callbacks_type { // send_protocol_data_callback send_data; // receive_protocol_data_callback receive_data; // protocol_state_changed_callback state_changed; // get_public_key_for_id_callback get_public_key_for_id; // // void *user_data; // }; // // On Emscripten target all pointers take up 4 bytes and are aligned at 4-byte boundary. // Hence the following sizes and offsets: const sizeof_secure_session_user_callbacks_t = 20; const offsetof_user_data = 16; const offsetof_get_public_key_for_id = 12; // One does not simply pass JavaScript function into Emscripten memory. We need to use // the "addFunction" API which registers a limited number of JavaScript functions and // provides corresponding C function pointers to thunks. We need only one callback so // it's relatively easy for us. We just need to ensure that the function is registered // only once. // // As for the context, we'll save a pointer to "secure_session_user_callbacks_t" itself // in its "user_data" field. var getPublicKeyForIdThunkPtr = 0; function initUserCallbacks(callbacksPtr: number) { if (getPublicKeyForIdThunkPtr == 0) { // LLVM needs to know the prototype of the corresponding C function. // See comment for "getPublicKeyForIdThunk" below. getPublicKeyForIdThunkPtr = context.libthemis!!.addFunction( getPublicKeyForIdThunk, "iiiiii" ); } context.libthemis!!._memset( callbacksPtr, 0, sizeof_secure_session_user_callbacks_t ); // We're writing LLVM pointers into memory, hence the '*' type specifier context.libthemis!!.setValue( callbacksPtr + offsetof_get_public_key_for_id, getPublicKeyForIdThunkPtr, "*" ); context.libthemis!!.setValue( callbacksPtr + offsetof_user_data, callbacksPtr, "*" ); } // Now we need to be able to identify JavaScript Secure Session object associated with // a particular "secure_session_user_callbacks_t" instance. Unfortunately, keeping another // global registry in JavaScript is the only feasible choice because JavaScript object // memory is managed completely opaquely. var SecureSessionCallbackRegistry: { [callbackPtr: number]: SecureSession; } = {}; const registerSecureSession = ( callbacksPtr: number, session: SecureSession ) => { SecureSessionCallbackRegistry[callbacksPtr] = session; }; const unregisterSecureSession = (callbacksPtr: number) => { delete SecureSessionCallbackRegistry[callbacksPtr]; }; const getSecureSession = (callbacksPtr: number): SecureSession => SecureSessionCallbackRegistry[callbacksPtr]; // Finally, here's our JavaScript implementation of the C function callback. // It has the following prototype: // // int get_public_key_for_id_callback( // const void* id, size_t id_length, // void* key_buffer, size_t key_buffer_length, // void* user_data // ); // // It is expected to look up a public key corresponding to the provided session ID, // write the key into provided buffer, and return zero on success. Non-zero return // values are considered errors. // // The function accepts five integer argumentes and returns an integer. Hence its // LLVM signature is "iiiiii". // // We can throw JavaScript exceptions from inside the function, thanks to Emscripten. const GetPublicKeySuccess = 0; const GetPublicKeyFailure = -1; const getPublicKeyForIdThunk = ( idPtr: number, idLen: number, keyPtr: number, keyLen: number, userData: number ) => { let id = context.libthemis!!.HEAPU8.slice(idPtr, idPtr + idLen); let session = getSecureSession(userData); let publicKey = session.keyCallback(id); if (publicKey == null) { return GetPublicKeyFailure; } if (!(publicKey instanceof PublicKey)) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.INVALID_PARAMETER, "Secure Session callback must return PublicKey or null" ); } if (publicKey.length > keyLen) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.BUFFER_TOO_SMALL, "public key cannot fit into provided buffer" ); } heapPutArray(publicKey, keyPtr); return GetPublicKeySuccess; }; type KeyCallback = (id: Uint8Array) => PublicKey; export class SecureSession { private sessionPtr: number | null; public readonly keyCallback: KeyCallback; private callbacksPtr: number | null; constructor( sessionID: Uint8Array, privateKey: PrivateKey, keyCallback: KeyCallback ) { sessionID = coerceToBytes(sessionID); if (sessionID.length == 0) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.INVALID_PARAMETER, "session ID must be not empty" ); } if (!(privateKey instanceof PrivateKey)) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.INVALID_PARAMETER, "expected PrivateKey as second argument" ); } if (!isFunction(keyCallback)) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.INVALID_PARAMETER, "expected callback as third argument" ); } let session_id_ptr, private_key_ptr, callbacks_ptr; try { session_id_ptr = heapAlloc(sessionID.length); private_key_ptr = heapAlloc(privateKey.length); callbacks_ptr = heapAlloc(sizeof_secure_session_user_callbacks_t); if (!session_id_ptr || !private_key_ptr || !callbacks_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } heapPutArray(sessionID, session_id_ptr); heapPutArray(privateKey, private_key_ptr); this.keyCallback = keyCallback; initUserCallbacks(callbacks_ptr); this.sessionPtr = context.libthemis!!._secure_session_create( session_id_ptr, sessionID.length, private_key_ptr, privateKey.length, callbacks_ptr ); if (!this.sessionPtr) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.NO_MEMORY, "failed to allocate Secure Session" ); } registerSecureSession(callbacks_ptr, this); this.callbacksPtr = callbacks_ptr; callbacks_ptr = null; } finally { heapFree(private_key_ptr, privateKey.length); heapFree(session_id_ptr, sessionID.length); heapFree(callbacks_ptr, sizeof_secure_session_user_callbacks_t); } } destroy() { let status = context.libthemis!!._secure_session_destroy(this.sessionPtr!!); if (status != ThemisErrorCode.SUCCESS) { throw new ThemisError( cryptosystem_name, status, "failed to destroy Secure Session" ); } this.sessionPtr = null; unregisterSecureSession(this.callbacksPtr!!); heapFree(this.callbacksPtr, sizeof_secure_session_user_callbacks_t); this.callbacksPtr = null; } established() { let value = context.libthemis!!._secure_session_is_established( this.sessionPtr!! ); return !(value == 0); } connectionRequest() { let status; /// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten let request_length_ptr = context.libthemis!!.allocate( new ArrayBuffer(4), context.libthemis!!.ALLOC_STACK ); let request_ptr, request_length; try { status = context.libthemis!!._secure_session_generate_connect_request( this.sessionPtr!!, null, request_length_ptr ); if (status != ThemisErrorCode.BUFFER_TOO_SMALL) { throw new ThemisError(cryptosystem_name, status); } request_length = context.libthemis!!.getValue(request_length_ptr, "i32"); request_ptr = heapAlloc(request_length); if (!request_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } status = context.libthemis!!._secure_session_generate_connect_request( this.sessionPtr!!, request_ptr, request_length_ptr ); if (status != ThemisErrorCode.SUCCESS) { throw new ThemisError(cryptosystem_name, status); } request_length = context.libthemis!!.getValue(request_length_ptr, "i32"); return heapGetArray(request_ptr, request_length); } finally { heapFree(request_ptr, request_length); } } negotiateReply(message: Uint8Array) { message = coerceToBytes(message); if (message.length == 0) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.INVALID_PARAMETER, "message must be not empty" ); } let status; /// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten let reply_length_ptr = context.libthemis!!.allocate( new ArrayBuffer(4), context.libthemis!!.ALLOC_STACK ); let message_ptr, reply_ptr, reply_length; try { message_ptr = heapAlloc(message.length); if (!message_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } heapPutArray(message, message_ptr); status = context.libthemis!!._secure_session_unwrap( this.sessionPtr!!, message_ptr, message.length, null, reply_length_ptr ); if (status == ThemisErrorCode.SUCCESS) { return new Uint8Array(); } if (status != ThemisErrorCode.BUFFER_TOO_SMALL) { throw new ThemisError(cryptosystem_name, status); } reply_length = context.libthemis!!.getValue(reply_length_ptr, "i32"); reply_ptr = heapAlloc(reply_length); if (!reply_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } status = context.libthemis!!._secure_session_unwrap( this.sessionPtr!!, message_ptr, message.length, reply_ptr, reply_length_ptr ); if (status != ThemisErrorCode.SSESSION_SEND_OUTPUT_TO_PEER) { throw new ThemisError(cryptosystem_name, status); } reply_length = context.libthemis!!.getValue(reply_length_ptr, "i32"); return heapGetArray(reply_ptr, reply_length); } finally { heapFree(message_ptr, message.length); heapFree(reply_ptr, reply_length); } } wrap(message: Uint8Array) { message = coerceToBytes(message); if (message.length == 0) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.INVALID_PARAMETER, "message must be not empty" ); } let status; /// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten let wrapped_length_ptr = context.libthemis!!.allocate( new ArrayBuffer(4), context.libthemis!!.ALLOC_STACK ); let message_ptr, wrapped_ptr, wrapped_length; try { message_ptr = heapAlloc(message.length); if (!message_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } heapPutArray(message, message_ptr); status = context.libthemis!!._secure_session_wrap( this.sessionPtr!!, message_ptr, message.length, null, wrapped_length_ptr ); if (status != ThemisErrorCode.BUFFER_TOO_SMALL) { throw new ThemisError(cryptosystem_name, status); } wrapped_length = context.libthemis!!.getValue(wrapped_length_ptr, "i32"); wrapped_ptr = heapAlloc(wrapped_length); if (!wrapped_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } status = context.libthemis!!._secure_session_wrap( this.sessionPtr!!, message_ptr, message.length, wrapped_ptr, wrapped_length_ptr ); if (status != ThemisErrorCode.SUCCESS) { throw new ThemisError(cryptosystem_name, status); } wrapped_length = context.libthemis!!.getValue(wrapped_length_ptr, "i32"); return heapGetArray(wrapped_ptr, wrapped_length); } finally { heapFree(message_ptr, message.length); heapFree(wrapped_ptr, wrapped_length); } } unwrap(message: Uint8Array) { message = coerceToBytes(message); if (message.length == 0) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.INVALID_PARAMETER, "message must be not empty" ); } let status; /// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten let unwrapped_length_ptr = context.libthemis!!.allocate( new ArrayBuffer(4), context.libthemis!!.ALLOC_STACK ); let message_ptr, unwrapped_ptr, unwrapped_length; try { message_ptr = heapAlloc(message.length); if (!message_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } heapPutArray(message, message_ptr); status = context.libthemis!!._secure_session_unwrap( this.sessionPtr!!, message_ptr, message.length, null, unwrapped_length_ptr ); if (status != ThemisErrorCode.BUFFER_TOO_SMALL) { throw new ThemisError(cryptosystem_name, status); } unwrapped_length = context.libthemis!!.getValue( unwrapped_length_ptr, "i32" ); unwrapped_ptr = heapAlloc(unwrapped_length); if (!unwrapped_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } status = context.libthemis!!._secure_session_unwrap( this.sessionPtr!!, message_ptr, message.length, unwrapped_ptr, unwrapped_length_ptr ); if (status != ThemisErrorCode.SUCCESS) { throw new ThemisError(cryptosystem_name, status); } unwrapped_length = context.libthemis!!.getValue( unwrapped_length_ptr, "i32" ); return heapGetArray(unwrapped_ptr, unwrapped_length); } finally { heapFree(message_ptr, message.length); heapFree(unwrapped_ptr, unwrapped_length); } } }
the_stack
/* * Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info. */ namespace LiteMol.Core.Structure { "use strict"; import DataTable = Utils.DataTable export interface Position { x: number, y: number, z: number } export interface Atom { id: number, name: string, authName: string, elementSymbol: string, altLoc: string | null, occupancy: number, tempFactor: number, residueIndex: number, chainIndex: number, entityIndex: number, rowIndex: number } export interface Residue { name: string, seqNumber: number, asymId: string, authName: string, authSeqNumber: number, authAsymId: string, insCode: string | null, entityId: string, isHet: number, atomStartIndex: number, atomEndIndex: number, chainIndex: number, entityIndex: number, secondaryStructureIndex: number } export interface Chain { asymId: string, authAsymId: string, entityId: string, atomStartIndex: number, atomEndIndex: number, residueStartIndex: number, residueEndIndex: number, entityIndex: number, // used by computed molecules (symmetry, assembly) sourceChainIndex: number, operatorIndex: number } export interface Entity { entityId: string, atomStartIndex: number, atomEndIndex: number, residueStartIndex: number, residueEndIndex: number, chainStartIndex: number, chainEndIndex: number, type: Entity.Type } export namespace Entity { export type Type = 'polymer' | 'non-polymer' | 'water' | 'unknown' } export interface Bond { atomAIndex: number, atomBIndex: number, type: BondType } export interface ModifiedResidue { asymId: string, seqNumber: number, insCode: string | null, parent: string, details: string | null } export class ComponentBondInfoEntry { map: Utils.FastMap<string, Utils.FastMap<string, BondType>> = Utils.FastMap.create<string, Utils.FastMap<string, BondType>>(); add(a: string, b: string, order: BondType, swap = true) { let e = this.map.get(a); if (e !== void 0) { let f = e.get(b); if (f === void 0) { e.set(b, order); } } else { let map = Utils.FastMap.create<string, BondType>(); map.set(b, order); this.map.set(a, map); } if (swap) this.add(b, a, order, false); } constructor(public id: string) { } } export class ComponentBondInfo { entries: Utils.FastMap<string, ComponentBondInfoEntry> = Utils.FastMap.create<string, ComponentBondInfoEntry>(); newEntry(id: string) { let e = new ComponentBondInfoEntry(id); this.entries.set(id, e); return e; } } /** * Identifier for a reside that is a part of the polymer. */ export class PolyResidueIdentifier { constructor(public asymId: string, public seqNumber: number, public insCode: string | null) { } static areEqual(a: PolyResidueIdentifier, index: number, bAsymId: string[], bSeqNumber: number[], bInsCode: string[]) { return a.asymId === bAsymId[index] && a.seqNumber === bSeqNumber[index] && a.insCode === bInsCode[index]; } static compare(a: PolyResidueIdentifier, b: PolyResidueIdentifier) { if (a.asymId === b.asymId) { if (a.seqNumber === b.seqNumber) { if (a.insCode === b.insCode) return 0; if (a.insCode === void 0) return -1; if (b.insCode === void 0) return 1; return a.insCode! < b.insCode! ? -1 : 1; } return a.seqNumber < b.seqNumber ? -1 : 1; } return a.asymId < b.asymId ? -1 : 1; } static compareResidue(a: PolyResidueIdentifier, index: number, bAsymId: string[], bSeqNumber: number[], bInsCode: string[]) { if (a.asymId === bAsymId[index]) { if (a.seqNumber === bSeqNumber[index]) { if (a.insCode === bInsCode[index]) return 0; if (a.insCode === void 0) return -1; if (bInsCode[index] === void 0) return 1; return a.insCode! < bInsCode[index] ? -1 : 1; } return a.seqNumber < bSeqNumber[index] ? -1 : 1; } return a.asymId < bAsymId[index] ? -1 : 1; } } export const enum SecondaryStructureType { None = 0, Helix = 1, Turn = 2, Sheet = 3, AminoSeq = 4, Strand = 5 } export class SecondaryStructureElement { startResidueIndex: number = -1; endResidueIndex: number = -1; get length() { return this.endResidueIndex - this.startResidueIndex; } constructor( public type: SecondaryStructureType, public startResidueId: PolyResidueIdentifier, public endResidueId: PolyResidueIdentifier, public info: any = {}) { } } export class SymmetryInfo { constructor( public spacegroupName: string, public cellSize: number[], public cellAngles: number[], public toFracTransform: number[], public isNonStandardCrytalFrame: boolean) { } } /** * Wraps _struct_conn mmCIF category. */ export class StructConn { private _residuePairIndex: Utils.FastMap<string, StructConn.Entry[]> | undefined = void 0; private _atomIndex: Utils.FastMap<number, StructConn.Entry[]> | undefined = void 0; private static _resKey(rA: number, rB: number) { if (rA < rB) return `${rA}-${rB}`; return `${rB}-${rA}`; } private getResiduePairIndex() { if (this._residuePairIndex) return this._residuePairIndex; this._residuePairIndex = Utils.FastMap.create(); for (const e of this.entries) { const ps = e.partners; const l = ps.length; for (let i = 0; i < l - 1; i++) { for (let j = i + i; j < l; j++) { const key = StructConn._resKey(ps[i].residueIndex, ps[j].residueIndex); if (this._residuePairIndex.has(key)) { this._residuePairIndex.get(key)!.push(e); } else { this._residuePairIndex.set(key, [e]); } } } } return this._residuePairIndex; } private getAtomIndex() { if (this._atomIndex) return this._atomIndex; this._atomIndex = Utils.FastMap.create(); for (const e of this.entries) { for (const p of e.partners) { const key = p.atomIndex; if (this._atomIndex.has(key)) { this._atomIndex.get(key)!.push(e); } else { this._atomIndex.set(key, [e]); } } } return this._atomIndex; } private static _emptyEntry = []; getResidueEntries(residueAIndex: number, residueBIndex: number): ReadonlyArray<StructConn.Entry> { return this.getResiduePairIndex().get(StructConn._resKey(residueAIndex, residueBIndex)) || StructConn._emptyEntry; } getAtomEntries(atomIndex: number): ReadonlyArray<StructConn.Entry> { return this.getAtomIndex().get(atomIndex) || StructConn._emptyEntry; } constructor(public entries: StructConn.Entry[]) { } } export namespace StructConn { export interface Entry { distance: number, bondType: BondType, partners: { residueIndex: number, atomIndex: number, symmetry: string }[] } } /** * Wraps an assembly operator. */ export class AssemblyOperator { constructor(public id: string, public name: string, public operator: number[]) { } } /** * Wraps a single assembly gen entry. */ export class AssemblyGenEntry { constructor(public operators: string[][], public asymIds: string[]) { } } /** * Wraps an assembly generation template. */ export class AssemblyGen { gens: AssemblyGenEntry[] = []; constructor(public name: string) { } } /** * Information about the assemblies. */ export class AssemblyInfo { constructor(public operators: { [id: string]: AssemblyOperator }, public assemblies: AssemblyGen[]) { } } export type PositionTable = DataTable<Position> export type AtomTable = DataTable<Atom> export type ResidueTable = DataTable<Residue> export type ChainTable = DataTable<Chain> export type EntityTable = DataTable<Entity> export type BondTable = DataTable<Bond> export type ModifiedResidueTable = DataTable<ModifiedResidue> /** * Default Builders */ export namespace Tables { const int32 = DataTable.typedColumn(Int32Array); const float32 = DataTable.typedColumn(Float32Array); const str = DataTable.stringColumn; const nullStr = DataTable.stringNullColumn; export const Positions: DataTable.Definition<Position> = { x: float32, y: float32, z: float32 }; export const Atoms: DataTable.Definition<Atom> = { id: int32, altLoc: str, residueIndex: int32, chainIndex: int32, entityIndex: int32, name: str, elementSymbol: str, occupancy: float32, tempFactor: float32, authName: str, rowIndex: int32 }; export const Residues: DataTable.Definition<Residue> = { name: str, seqNumber: int32, asymId: str, authName: str, authSeqNumber: int32, authAsymId: str, insCode: nullStr, entityId: str, isHet: DataTable.typedColumn(Int8Array), atomStartIndex: int32, atomEndIndex: int32, chainIndex: int32, entityIndex: int32, secondaryStructureIndex: int32 }; export const Chains: DataTable.Definition<Chain> = { asymId: str, entityId: str, authAsymId: str, atomStartIndex: int32, atomEndIndex: int32, residueStartIndex: int32, residueEndIndex: int32, entityIndex: int32, sourceChainIndex: void 0, operatorIndex: void 0 }; export const Entities: DataTable.Definition<Entity> = { entityId: str, type: DataTable.customColumn<Entity.Type>(), atomStartIndex: int32, atomEndIndex: int32, residueStartIndex: int32, residueEndIndex: int32, chainStartIndex: int32, chainEndIndex: int32 }; export const Bonds: DataTable.Definition<Bond> = { atomAIndex: int32, atomBIndex: int32, type: DataTable.typedColumn(Int8Array) }; export const ModifiedResidues: DataTable.Definition<ModifiedResidue> = { asymId: str, seqNumber: int32, insCode: nullStr, parent: str, details: nullStr }; } export class Operator { apply(v: Geometry.LinearAlgebra.Vector3) { Geometry.LinearAlgebra.Vector3.transformMat4(v, v, this.matrix) } static applyToModelUnsafe(matrix: number[], m: Molecule.Model) { let v = Geometry.LinearAlgebra.Vector3.zero(); let {x, y, z} = m.positions; for (let i = 0, _b = m.positions.count; i < _b; i++) { v[0] = x[i]; v[1] = y[i]; v[2] = z[i]; Geometry.LinearAlgebra.Vector3.transformMat4(v, v, matrix); x[i] = v[0]; y[i] = v[1]; z[i] = v[2]; } } constructor(public matrix: number[], public id: string, public isIdentity: boolean) { } } export interface Molecule { readonly properties: Molecule.Properties, readonly id: string, readonly models: Molecule.Model[] } export namespace Molecule { export function create(id: string, models: Model[], properties: Properties = {}): Molecule { return { id, models, properties }; } export interface Properties { experimentMethods?: string[] } export interface Bonds { readonly structConn?: StructConn, readonly input?: BondTable, readonly component?: ComponentBondInfo } export interface Model extends Model.Base { readonly queryContext: Query.Context } export namespace Model { export function create(model: Base): Model { let ret = Utils.extend({}, model); let queryContext: Query.Context | undefined = void 0 Object.defineProperty(ret, 'queryContext', { enumerable: true, configurable: false, get: function() { if (queryContext) return queryContext; queryContext = Query.Context.ofStructure(ret as Model); return queryContext; }}); return ret as Model; } export enum Source { File, Computed } export interface Base { readonly id: string, readonly modelId: string, readonly positions: PositionTable, readonly data: Data, readonly source: Source, readonly parent?: Model, readonly operators?: Operator[], } export interface Data { readonly atoms: AtomTable, readonly residues: ResidueTable, readonly chains: ChainTable, readonly entities: EntityTable, readonly bonds: Bonds, readonly secondaryStructure: SecondaryStructureElement[], readonly modifiedResidues?: ModifiedResidueTable, readonly symmetryInfo?: SymmetryInfo, readonly assemblyInfo?: AssemblyInfo } export function withTransformedXYZ<T>( model: Model, ctx: T, transform: (ctx: T, x: number, y: number, z: number, out: Geometry.LinearAlgebra.Vector3) => void) { const {x,y,z} = model.positions; const tAtoms = model.positions.getBuilder(model.positions.count).seal(); const {x:tX, y:tY, z:tZ} = tAtoms; const t = Geometry.LinearAlgebra.Vector3.zero(); for (let i = 0, _l = model.positions.count; i < _l; i++) { transform(ctx, x[i], y[i], z[i], t); tX[i] = t[0]; tY[i] = t[1]; tZ[i] = t[2]; } return create({ id: model.id, modelId: model.modelId, data: model.data, positions: tAtoms, parent: model.parent, source: model.source, operators: model.operators }); } } } }
the_stack
import { GlobalProps } from 'ojs/ojvcomponent'; import { ComponentChildren } from 'preact'; import CommonTypes = require('../ojcommontypes'); import { KeySet } from '../ojkeyset'; import { DataProvider, ItemMetadata } from '../ojdataprovider'; import { ojSelectBase, ojSelectBaseEventMap, ojSelectBaseSettableProperties } from '../ojselectbase'; import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojSelectSingle<V, D> extends ojSelectBase<V, D, ojSelectSingleSettableProperties<V, D>> { displayOptions: { helpInstruction: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages: 'display' | 'none'; }; value: V | null; valueItem: CommonTypes.ItemContext<V, D>; translations: { cancel?: string; labelAccClearValue?: string; labelAccOpenDropdown?: string; multipleMatchesFound?: string; nOrMoreMatchesFound?: string; noMatchesFound?: string; noResultsLine1?: string; noResultsLine2?: string; oneMatchFound?: string; required?: { hint?: string; messageDetail?: string; messageSummary?: string; }; }; addEventListener<T extends keyof ojSelectSingleEventMap<V, D>>(type: T, listener: (this: HTMLElement, ev: ojSelectSingleEventMap<V, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojSelectSingleSettableProperties<V, D>>(property: T): ojSelectSingle<V, D>[T]; getProperty(property: string): any; setProperty<T extends keyof ojSelectSingleSettableProperties<V, D>>(property: T, value: ojSelectSingleSettableProperties<V, D>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSelectSingleSettableProperties<V, D>>): void; setProperties(properties: ojSelectSingleSettablePropertiesLenient<V, D>): void; } export namespace ojSelectSingle { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } interface ojValueAction<V, D> extends CustomEvent<{ itemContext: CommonTypes.ItemContext<V, D>; previousValue: V | null; value: V | null; [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged<V, D> = JetElementCustomEvent<ojSelectSingle<V, D>["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V, D> = JetElementCustomEvent<ojSelectSingle<V, D>["value"]>; // tslint:disable-next-line interface-over-type-literal type valueItemChanged<V, D> = JetElementCustomEvent<ojSelectSingle<V, D>["valueItem"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type dataChanged<V, D> = ojSelectBase.dataChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type describedByChanged<V, D> = ojSelectBase.describedByChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V, D> = ojSelectBase.disabledChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V, D> = ojSelectBase.helpChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V, D> = ojSelectBase.helpHintsChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type itemTextChanged<V, D> = ojSelectBase.itemTextChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V, D> = ojSelectBase.labelEdgeChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V, D> = ojSelectBase.labelHintChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V, D> = ojSelectBase.labelledByChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V, D> = ojSelectBase.messagesCustomChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V, D> = ojSelectBase.placeholderChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V, D> = ojSelectBase.readonlyChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V, D> = ojSelectBase.requiredChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V, D> = ojSelectBase.userAssistanceDensityChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type validChanged<V, D> = ojSelectBase.validChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type virtualKeyboardChanged<V, D> = ojSelectBase.virtualKeyboardChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type CollectionTemplateContext<V, D> = { currentRow: { rowKey: V; }; data: DataProvider<V, D>; handleRowAction: ((event: Event, context: CommonTypes.ItemContext<V, D>) => void); searchText: string; selected: KeySet<V>; selectedItem: CommonTypes.ItemContext<V, D>; }; // tslint:disable-next-line interface-over-type-literal type ItemTemplateContext<V, D> = { componentElement: Element; data: D; depth: number; index: number; key: V; leaf: boolean; metadata: ItemMetadata<V>; parentKey: V; searchText: string; }; } export interface ojSelectSingleEventMap<V, D> extends ojSelectBaseEventMap<V, D, ojSelectSingleSettableProperties<V, D>> { 'ojAnimateEnd': ojSelectSingle.ojAnimateEnd; 'ojAnimateStart': ojSelectSingle.ojAnimateStart; 'ojValueAction': ojSelectSingle.ojValueAction<V, D>; 'displayOptionsChanged': JetElementCustomEvent<ojSelectSingle<V, D>["displayOptions"]>; 'valueChanged': JetElementCustomEvent<ojSelectSingle<V, D>["value"]>; 'valueItemChanged': JetElementCustomEvent<ojSelectSingle<V, D>["valueItem"]>; 'dataChanged': JetElementCustomEvent<ojSelectSingle<V, D>["data"]>; 'describedByChanged': JetElementCustomEvent<ojSelectSingle<V, D>["describedBy"]>; 'disabledChanged': JetElementCustomEvent<ojSelectSingle<V, D>["disabled"]>; 'helpChanged': JetElementCustomEvent<ojSelectSingle<V, D>["help"]>; 'helpHintsChanged': JetElementCustomEvent<ojSelectSingle<V, D>["helpHints"]>; 'itemTextChanged': JetElementCustomEvent<ojSelectSingle<V, D>["itemText"]>; 'labelEdgeChanged': JetElementCustomEvent<ojSelectSingle<V, D>["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<ojSelectSingle<V, D>["labelHint"]>; 'labelledByChanged': JetElementCustomEvent<ojSelectSingle<V, D>["labelledBy"]>; 'messagesCustomChanged': JetElementCustomEvent<ojSelectSingle<V, D>["messagesCustom"]>; 'placeholderChanged': JetElementCustomEvent<ojSelectSingle<V, D>["placeholder"]>; 'readonlyChanged': JetElementCustomEvent<ojSelectSingle<V, D>["readonly"]>; 'requiredChanged': JetElementCustomEvent<ojSelectSingle<V, D>["required"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<ojSelectSingle<V, D>["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<ojSelectSingle<V, D>["valid"]>; 'virtualKeyboardChanged': JetElementCustomEvent<ojSelectSingle<V, D>["virtualKeyboard"]>; } export interface ojSelectSingleSettableProperties<V, D> extends ojSelectBaseSettableProperties<V, D> { displayOptions: { helpInstruction: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages: 'display' | 'none'; }; value: V | null; valueItem: CommonTypes.ItemContext<V, D>; translations: { cancel?: string; labelAccClearValue?: string; labelAccOpenDropdown?: string; multipleMatchesFound?: string; nOrMoreMatchesFound?: string; noMatchesFound?: string; noResultsLine1?: string; noResultsLine2?: string; oneMatchFound?: string; required?: { hint?: string; messageDetail?: string; messageSummary?: string; }; }; } export interface ojSelectSingleSettablePropertiesLenient<V, D> extends Partial<ojSelectSingleSettableProperties<V, D>> { [key: string]: any; } export type SelectSingleElement<V, D> = ojSelectSingle<V, D>; export namespace SelectSingleElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } interface ojValueAction<V, D> extends CustomEvent<{ itemContext: CommonTypes.ItemContext<V, D>; previousValue: V | null; value: V | null; [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged<V, D> = JetElementCustomEvent<ojSelectSingle<V, D>["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V, D> = JetElementCustomEvent<ojSelectSingle<V, D>["value"]>; // tslint:disable-next-line interface-over-type-literal type valueItemChanged<V, D> = JetElementCustomEvent<ojSelectSingle<V, D>["valueItem"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type dataChanged<V, D> = ojSelectBase.dataChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type describedByChanged<V, D> = ojSelectBase.describedByChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V, D> = ojSelectBase.disabledChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V, D> = ojSelectBase.helpChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V, D> = ojSelectBase.helpHintsChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type itemTextChanged<V, D> = ojSelectBase.itemTextChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V, D> = ojSelectBase.labelEdgeChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V, D> = ojSelectBase.labelHintChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V, D> = ojSelectBase.labelledByChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V, D> = ojSelectBase.messagesCustomChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V, D> = ojSelectBase.placeholderChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V, D> = ojSelectBase.readonlyChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V, D> = ojSelectBase.requiredChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V, D> = ojSelectBase.userAssistanceDensityChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type validChanged<V, D> = ojSelectBase.validChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type virtualKeyboardChanged<V, D> = ojSelectBase.virtualKeyboardChanged<V, D, ojSelectSingleSettableProperties<V, D>>; // tslint:disable-next-line interface-over-type-literal type CollectionTemplateContext<V, D> = { currentRow: { rowKey: V; }; data: DataProvider<V, D>; handleRowAction: ((event: Event, context: CommonTypes.ItemContext<V, D>) => void); searchText: string; selected: KeySet<V>; selectedItem: CommonTypes.ItemContext<V, D>; }; } export interface SelectSingleIntrinsicProps extends Partial<Readonly<ojSelectSingleSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAnimateEnd?: (value: ojSelectSingleEventMap<any, any>['ojAnimateEnd']) => void; onojAnimateStart?: (value: ojSelectSingleEventMap<any, any>['ojAnimateStart']) => void; onojValueAction?: (value: ojSelectSingleEventMap<any, any>['ojValueAction']) => void; ondisplayOptionsChanged?: (value: ojSelectSingleEventMap<any, any>['displayOptionsChanged']) => void; onvalueChanged?: (value: ojSelectSingleEventMap<any, any>['valueChanged']) => void; onvalueItemChanged?: (value: ojSelectSingleEventMap<any, any>['valueItemChanged']) => void; ondataChanged?: (value: ojSelectSingleEventMap<any, any>['dataChanged']) => void; ondescribedByChanged?: (value: ojSelectSingleEventMap<any, any>['describedByChanged']) => void; ondisabledChanged?: (value: ojSelectSingleEventMap<any, any>['disabledChanged']) => void; onhelpChanged?: (value: ojSelectSingleEventMap<any, any>['helpChanged']) => void; onhelpHintsChanged?: (value: ojSelectSingleEventMap<any, any>['helpHintsChanged']) => void; onitemTextChanged?: (value: ojSelectSingleEventMap<any, any>['itemTextChanged']) => void; onlabelEdgeChanged?: (value: ojSelectSingleEventMap<any, any>['labelEdgeChanged']) => void; onlabelHintChanged?: (value: ojSelectSingleEventMap<any, any>['labelHintChanged']) => void; onlabelledByChanged?: (value: ojSelectSingleEventMap<any, any>['labelledByChanged']) => void; onmessagesCustomChanged?: (value: ojSelectSingleEventMap<any, any>['messagesCustomChanged']) => void; onplaceholderChanged?: (value: ojSelectSingleEventMap<any, any>['placeholderChanged']) => void; onreadonlyChanged?: (value: ojSelectSingleEventMap<any, any>['readonlyChanged']) => void; onrequiredChanged?: (value: ojSelectSingleEventMap<any, any>['requiredChanged']) => void; onuserAssistanceDensityChanged?: (value: ojSelectSingleEventMap<any, any>['userAssistanceDensityChanged']) => void; onvalidChanged?: (value: ojSelectSingleEventMap<any, any>['validChanged']) => void; onvirtualKeyboardChanged?: (value: ojSelectSingleEventMap<any, any>['virtualKeyboardChanged']) => void; children?: ComponentChildren; } declare global { namespace preact.JSX { interface IntrinsicElements { "oj-select-single": SelectSingleIntrinsicProps; } } }
the_stack
import { expect } from "chai"; import * as Enzyme from "enzyme"; import "mocha"; import * as React from "react"; import { Subject, Subscription, Observable, of } from "rxjs"; import { take, skip } from "rxjs/operators"; import { ActionMap, connect, ConnectResult, StoreProvider } from "../react"; import { Store } from "../src/index"; import { setupJSDomEnv } from "./test_enzyme_helper"; const globalClicked = new Subject<void>(); const nextMessage = new Subject<string>(); export interface TestState { message: string; slice?: SliceState; } export interface SliceState { sliceMessage: string; } export interface TestComponentProps { message: string; onClick: (arg1: any) => void; } export class TestComponent extends React.Component<TestComponentProps, {}> { render() { return ( <div> <h1>{this.props.message}</h1> <button onClick={this.props.onClick} /> </div> ); } componentDidCatch() {} } function getConnectedComponent(connectResultOverride?: ConnectResult<TestState, TestComponentProps> | null) { return connect( TestComponent, (store: Store<TestState>) => { store.destroyed.subscribe(() => cleanup.unsubscribe()); const props = store.createSlice("message").watch(message => ({ message })); const actionMap: ActionMap<typeof TestComponent> = { onClick: globalClicked, }; if (connectResultOverride === null) { return {}; } return { actionMap, props, ...connectResultOverride, }; }, ); } let cleanup: Subscription; describe("react bridge: connect() tests", () => { let store: Store<TestState>; let mountInsideStoreProvider: (elem: JSX.Element) => Enzyme.ReactWrapper<any, any>; let ConnectedTestComponent: any; const initialState: TestState = { message: "initialMessage", slice: { sliceMessage: "initialSliceMessage", }, }; beforeEach(() => { setupJSDomEnv(); cleanup = new Subscription(); ConnectedTestComponent = getConnectedComponent(); store = Store.create(initialState); store.addReducer(nextMessage, (state, message) => { return { ...state, message, }; }); store.destroyed.subscribe(() => cleanup.unsubscribe()); mountInsideStoreProvider = (elem: JSX.Element) => Enzyme.mount(<StoreProvider store={store}>{elem}</StoreProvider>); }); it("should map a prop from the state to the prop of the component using props observable", () => { const wrapper = mountInsideStoreProvider(<ConnectedTestComponent />); const messageText = wrapper.find("h1").text(); expect(messageText).to.equal(initialState.message); }); it("should receive prop updates from the store using mapStateToProps", () => { const wrapper = mountInsideStoreProvider(<ConnectedTestComponent />); expect(wrapper.find("h1").text()).to.equal(initialState.message); nextMessage.next("Message1"); expect(wrapper.find("h1").text()).to.equal("Message1"); nextMessage.next("Message2"); expect(wrapper.find("h1").text()).to.equal("Message2"); }); it("should trigger an action on a callback function in the actionMap", done => { const wrapper = mountInsideStoreProvider(<ConnectedTestComponent />); globalClicked.pipe(take(1)).subscribe(() => { expect(true).to.be.true; done(); }); wrapper.find("button").simulate("click"); }); it("should allow to override props on the connected component", done => { const onClick = () => { done(); }; const wrapper = mountInsideStoreProvider(<ConnectedTestComponent message="Barfoos" onClick={onClick} />); const messageText = wrapper.find("h1").text(); expect(messageText).to.equal("Barfoos"); wrapper.find("button").simulate("click"); }); it("should use the provided props if there is no store in context", done => { const clicked = new Subject<void>(); const onClick = () => setTimeout(() => done(), 50); clicked.subscribe(() => { done("Error: called the subject"); }); const wrapper = Enzyme.mount(<ConnectedTestComponent message="Barfoos" onClick={onClick} />); const messageText = wrapper.find("h1").text(); expect(messageText).to.equal("Barfoos"); wrapper.find("button").simulate("click"); wrapper.unmount(); }); it("should use a props if it updated later on", done => { const Root: React.SFC<{ message?: string }> = props => { return ( <StoreProvider store={store}> <ConnectedTestComponent message={props.message} /> </StoreProvider> ); }; const wrapper = Enzyme.mount(<Root />); const textMessage = wrapper.find("h1").text(); // we provided a message props - even though its undefined at first, its mere presence should supersede the // connected prop of message expect(textMessage).to.equal(""); setTimeout(() => { wrapper.setProps({ message: "Bla" }); const textMessage = wrapper.find("h1").text(); expect(textMessage).to.equal("Bla"); done(); }, 50); }); it("unsubscribe the cleanup subscription on component unmount", done => { cleanup.add(() => done()); const wrapper = mountInsideStoreProvider(<ConnectedTestComponent />); wrapper.unmount(); }); it("should allow the connect callback to return empty result object and then use the provided props", done => { ConnectedTestComponent = getConnectedComponent(null); const onClick = () => done(); const wrapper = mountInsideStoreProvider(<ConnectedTestComponent message="Bla" onClick={onClick} />); const textMessage = wrapper.find("h1").text(); expect(textMessage).to.equal("Bla"); wrapper.find("button").simulate("click"); }); it("should allow an observer in an actionMap", done => { const onClick = new Subject<void>(); const actionMap: ActionMap<typeof TestComponent> = { onClick, }; onClick.subscribe(() => done()); ConnectedTestComponent = getConnectedComponent({ actionMap }); const wrapper = mountInsideStoreProvider(<ConnectedTestComponent />); wrapper.find("button").simulate("click"); }); it("should allow callback functions in an actionMap", done => { const actionMap: ActionMap<typeof TestComponent> = { onClick: () => done(), }; ConnectedTestComponent = getConnectedComponent({ actionMap }); const wrapper = mountInsideStoreProvider(<ConnectedTestComponent />); wrapper.find("button").simulate("click"); }); it("should throw an error for invalid entries in the action map", () => { const actionMap: ActionMap<typeof TestComponent> = { onClick: 5 as any, }; expect(() => { ConnectedTestComponent = getConnectedComponent({ actionMap }); const wrapper = mountInsideStoreProvider(<ConnectedTestComponent />); wrapper.find("button").simulate("click"); }).to.throw(); }); it("should allow undefined fields in an actionMap to ignore callbacks", done => { const actionMap: ActionMap<typeof TestComponent> = { onClick: undefined, }; ConnectedTestComponent = getConnectedComponent({ actionMap }); cleanup.add(() => done()); const wrapper = mountInsideStoreProvider(<ConnectedTestComponent />); wrapper.find("button").simulate("click"); wrapper.unmount(); }); // Typing regression it("should be possible for props to operate on any store/slice", () => { const ConnectedTestComponent = connect( TestComponent, (store: Store<TestState>) => { const slice = store.createSlice("message", "Blafoo"); const props = slice.watch(message => ({ message })); return { props, }; }, ); const wrapper = mountInsideStoreProvider(<ConnectedTestComponent />); const messageText = wrapper.find("h1").text(); expect(messageText).to.equal("Blafoo"); }); it("should be possible to add additional props to a connected component and subscribe to it in the connect callback", done => { type ComponentProps = { message: string }; const Component: React.SFC<ComponentProps> = props => <h1>{props.message}</h1>; // add another prop field to our component type InputProps = ComponentProps & { additionalProp: number }; const ConnectedTestComponent = connect( Component, (store: Store<TestState>, inputProps: Observable<InputProps>) => { inputProps.pipe(take(1)).subscribe(props => { expect(props).to.deep.equal({ test: 1 }); }); inputProps .pipe( skip(1), take(1), ) .subscribe(props => { expect(props).to.deep.equal({ test: 2 }); setTimeout(() => done(), 100); }); return { props: of({ message: "Foobar" }), }; }, ); const Root: React.SFC<any> = (props: any) => ( <StoreProvider store={store}> <ConnectedTestComponent {...props} /> </StoreProvider> ); const wrapper = Enzyme.mount(<Root test={1} />); wrapper.setProps({ test: 2, }); const messageText = wrapper.find("h1").text(); expect(messageText).to.equal("Foobar"); wrapper.unmount(); }); // this is a compilation test to assert that the type inference for connect() works when manually specifing type arguments it("should be possible to infer the inputProps type", done => { type ComponentProps = { message: string }; const Component: React.SFC<ComponentProps> = props => <h1>{props.message}</h1>; // add another prop field to our component type InputProps = { additionalProp: number }; const ConnectedTestComponent = connect<TestState, ComponentProps, InputProps>( Component, (store, inputProps) => { const props = of({ message: "Foobar", additionalProp: 5 }); return { props }; }, ); console.info(ConnectedTestComponent); done(); }); });
the_stack
module HubTests { export module Utilities { "use strict"; // Helper functions export var HubHeaderTestTemplateJS = WinJS.Utilities.markSupportedForProcessing(function HubHeaderTestTemplateJS(item) { var div = document.createElement("div"); div.textContent = item.header; div.className += " testHeaderTemplateJS"; return div; }); var HubSection = <typeof WinJS.UI.PrivateHubSection>WinJS.UI.HubSection; var Hub = <typeof WinJS.UI.PrivateHub>WinJS.UI.Hub; window['HubHeaderTestTemplateJS'] = HubHeaderTestTemplateJS; function getConfigurations() { function getListViewContent(testHost) { var elementHost = document.createElement("DIV"); var element = document.createElement("DIV"); elementHost.appendChild(element); var list = new WinJS.Binding.List(); for (var i = 0; i < 10; i++) { list.push({ item: i }); } function itemTemplate(itemPromise) { var element = document.createElement("div"); return itemPromise.then(function () { return element; }); } new WinJS.UI.ListView(element, { itemDataSource: list.dataSource, itemTemplate: itemTemplate }); //Give the Hub a chance to append the element in DOM before we show the ListView WinJS.Utilities._setImmediate(function () { element && element.winControl && element.winControl.forceLayout(); }); return elementHost; } return [ { initialize: function (testHost) { return { method: 'JS', headerTemplate: undefined, sectionsArray: [ //metadata for sections new HubSection(getListViewContent(testHost), { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.horizontal }; } }, { initialize: function () { return { method: 'JS', headerTemplate: HubHeaderTestTemplateJS, sectionsArray: [ //metadata for sections new HubSection(undefined, { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.vertical }; } }, { initialize: function () { return { method: 'JS', headerTemplate: { id: "myHeaderTemplate", html: "<div id='myHeaderTemplate' data-win-control='WinJS.Binding.Template'><span data-win-bind='textContent: this.header'></span></div>" }, sectionsArray: [ //metadata for sections new HubSection(undefined, { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.horizontal }; } }, { initialize: function () { return { method: 'JS', sectionOnScreen: 2, headerTemplate: HubHeaderTestTemplateJS, sectionsArray: [ //metadata for sections new HubSection(undefined, { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.horizontal }; } }, { initialize: function () { return { method: 'JS', sectionOnScreen: 2, headerTemplate: HubHeaderTestTemplateJS, sectionsArray: [ //metadata for sections new HubSection(undefined, { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.vertical }; } }, { initialize: function (testHost) { return { method: 'HTML', headerTemplate: undefined, sectionsArray: [ //metadata for sections new HubSection(getListViewContent(testHost), { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.horizontal }; } }, { initialize: function () { return { method: 'HTML', headerTemplate: "HubHeaderTestTemplateJS", sectionsArray: [ //metadata for sections new HubSection(undefined, { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.vertical }; } }, { initialize: function () { return { method: 'HTML', headerTemplate: { id: "myHeaderTemplate", html: "<div id='myHeaderTemplate' data-win-control='WinJS.Binding.Template'><span data-win-bind='textContent: this.header'></span></div>" }, sectionsArray: [ //metadata for sections new HubSection(undefined, { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.vertical }; } }, { initialize: function () { return { method: 'HTML', headerTemplate: { id: "myHeaderTemplate", html: "<div id='myHeaderTemplate' data-win-control='WinJS.Binding.Template'><span data-win-bind='textContent: this.header'></span></div>" }, sectionOnScreen: 2, sectionsArray: [ //metadata for sections new HubSection(undefined, { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.horizontal }; } }, { initialize: function () { return { method: 'HTML', headerTemplate: { id: "myHeaderTemplate", html: "<div id='myHeaderTemplate' data-win-control='WinJS.Binding.Template'><span data-win-bind='textContent: this.header'></span></div>" }, sectionOnScreen: 2, sectionsArray: [ //metadata for sections new HubSection(undefined, { header: 'Section 0', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 1' }), new HubSection(undefined, { header: 'Section 2' }), new HubSection(undefined, { header: 'Section 3', isHeaderStatic: true }), new HubSection(undefined, { header: 'Section 4' }) ], orientation: WinJS.UI.Orientation.vertical }; } } ]; } export function test(that, testHostSelector, testNamePrefix, testFunction, options?, filter?) { //for each configuration, build a hub and execute the test var configurations = getConfigurations(); for (var i in configurations) { if (!filter || filter(configurations[i])) { (function (i) { var testName = "test" + testNamePrefix + "_config" + i; that[testName] = function (complete) { var testHost = document.querySelector(testHostSelector); var config = configurations[i].initialize(testHost); insertHub(testHost, config); testFunction(testHost, config). done(complete); }; if (options) { var optionKeys = Object.keys(options); for (var x = 0; x < optionKeys.length; x++) { var key = optionKeys[x]; var value = options[key]; that[testName][key] = value; } } })(i); } } } export function insertHub(testHost, config) { var control; //Check to see if we need to insert a Binding.Template if (config.headerTemplate && config.headerTemplate.html) { var template = document.createElement("div"); template.innerHTML = config.headerTemplate.html; testHost.appendChild(template.firstElementChild); //update headerTemplate property and re-add the metadata for test validation var temp = { html: config.headerTemplate.html, id: config.headerTemplate.id }; config.headerTemplate = document.getElementById(temp.id); config.headerTemplate.html = temp.html; config.headerTemplate.id = temp.id; } config.sections = new WinJS.Binding.List(config.sectionsArray); switch (config.method) { case 'HTML': var extraHTML = ""; var optionsString = "{ "; var configProperties = Object.keys(config); for (var i = 0; i < configProperties.length; i++) { var prop = configProperties[i]; switch (prop) { case 'sections': if (optionsString.length > 2) { optionsString += ','; } window['sectionsList'] = config.sections; optionsString += prop + ": sectionsList"; break; case 'headerTemplate': if (optionsString.length > 2) { optionsString += ','; } if (config[prop]) { if (typeof config[prop] === "string") { //If a string is passed, assume it's the name of a function optionsString += prop + ": " + config[prop]; } else if (config[prop].id) { //Another special case we accept is an object with an id and html property optionsString += prop + ": " + config[prop].id; } else { LiveUnit.Assert.fail("Oops! bad headerTemplate"); } } break; case 'sectionOnScreen': case 'orientation': if (optionsString.length > 2) { optionsString += ','; } optionsString += prop + ": \"" + config[prop] + "\""; break; default: break; } } optionsString += " }"; var hub = document.createElement("div"); hub.innerHTML = "\ <div class=\'myHub\' data-win-control=\'WinJS.UI.Hub\' data-win-options=\'" + optionsString + "\'>\ \ </div>\ "; testHost.appendChild(hub.firstElementChild); WinJS.UI.processAll(); control = testHost.querySelector(".myHub").winControl; break; case 'JS': default: //ensure the Binding.Template is processed WinJS.UI.processAll(); control = new WinJS.UI.Hub(null, config); testHost.appendChild(control.element); break; } return control; } export function verifyOrientation(control, expected) { LiveUnit.Assert.areEqual(expected, control.orientation, "Control orientation does not match config input"); if (control.orientation === WinJS.UI.Orientation.horizontal) { LiveUnit.Assert.isTrue(control.element.className.indexOf("win-hub-horizontal") !== -1, "Expecting win-hub-horizontal CSS class"); } else { LiveUnit.Assert.isTrue(control.element.className.indexOf("win-hub-vertical") !== -1, "Expecting win-hub-vertical CSS class"); } } export function getAllHeaderElements(control) { return control.element.querySelectorAll("." + HubSection._ClassName.hubSectionHeader); } export function verifySections(control, sections, headerTemplate) { var sectionsInDOM = control.element.querySelectorAll("." + HubSection._ClassName.hubSection); //verify # of sections LiveUnit.Assert.areEqual(sections.length, control.sections.length, "Number of sections does not match config input"); LiveUnit.Assert.areEqual(sections.length, sectionsInDOM.length || 0, "Number of sections in DOM does not match config input"); //Verify header content for (var i = 0; i < sections.length; i++) { var currentSection = sectionsInDOM[i]; switch (typeof headerTemplate) { case "object": var expectedHeader: any = document.createElement("div"); if (headerTemplate.render) { headerTemplate.render(sections[i], expectedHeader); } else if (headerTemplate.winControl && headerTemplate.winControl.render) { headerTemplate.winControl.render(sections[i], expectedHeader); } else { LiveUnit.Assert.fail("Unrecognized headerTemplate"); } LiveUnit.Assert.areEqual(expectedHeader.firstElementChild.innerHTML, currentSection.querySelector("." + HubSection._ClassName.hubSectionHeaderContent).firstElementChild.innerHTML, "Header content does not match input"); break; default: //simulate HubSection's header elements var headerElement = document.createElement("button"); headerElement.innerHTML = '<span class="' + HubSection._ClassName.hubSectionHeaderContent + '"></span>'; var headerElementContent = <HTMLElement>headerElement.firstElementChild; var expectedHeader = typeof headerTemplate === "string" ? eval(headerTemplate)(sections[i]) : headerTemplate(sections[i]); headerElementContent.appendChild(expectedHeader); LiveUnit.Assert.areEqual(headerElementContent.innerHTML, currentSection.querySelector("." + HubSection._ClassName.hubSectionHeaderContent).innerHTML, "Header content does not match input"); } } } export function waitForReady(control, delay?) { return function (x?) { return new WinJS.Promise(function waitForReady_Promise(c, e, p) { function waitForReady_handler(ev) { if (control.loadingState === "complete") { c(x); control.removeEventListener(Hub._EventName.loadingStateChanged, waitForReady_handler); } else { p(control.loadingState); } } function waitForReady_work() { if (control.loadingState === "complete") { c(x); } else { control.addEventListener(Hub._EventName.loadingStateChanged, waitForReady_handler); } } if (delay >= 0) { setTimeout(waitForReady_work, delay); } else { WinJS.Utilities._setImmediate(waitForReady_work); } }); }; } export function getScrollRange(control) { var viewportElement = control.element.firstElementChild; var scrollMin = 0; var scrollMax = control.orientation === WinJS.UI.Orientation.vertical ? viewportElement.scrollHeight - viewportElement.clientHeight : viewportElement.scrollWidth - viewportElement.clientWidth; return { min: scrollMin, max: scrollMax }; } export function getSurfaceSpacers(control) { var surface = control.element.querySelector("." + Hub._ClassName.hubSurface); var computedSurfaceStyles = getComputedStyle(surface); return { right: parseFloat(computedSurfaceStyles.marginRight) + parseFloat(computedSurfaceStyles.borderRightWidth) + parseFloat(computedSurfaceStyles.paddingRight), left: parseFloat(computedSurfaceStyles.marginLeft) + parseFloat(computedSurfaceStyles.borderLeftWidth) + parseFloat(computedSurfaceStyles.paddingLeft), bottom: parseFloat(computedSurfaceStyles.marginBottom) + parseFloat(computedSurfaceStyles.borderBottomWidth) + parseFloat(computedSurfaceStyles.paddingBottom), top: parseFloat(computedSurfaceStyles.marginTop) + parseFloat(computedSurfaceStyles.borderTopWidth) + parseFloat(computedSurfaceStyles.paddingTop) }; } export function findCurrentSectionOnScreen(control) { function isSectionOnScreen(control, section, surfaceSpacers) { var isLTR = getComputedStyle(control.element).direction === "ltr"; var currentSectionRect = section.getBoundingClientRect(); var computedSectionStyle = getComputedStyle(section); var viewportRect = control._viewportElement.getBoundingClientRect(); var offset; var collapsedSignificantEdgePosition; if (control.orientation === WinJS.UI.Orientation.horizontal) { if (isLTR) { offset = surfaceSpacers.left + viewportRect.left; collapsedSignificantEdgePosition = currentSectionRect.right - parseFloat(computedSectionStyle.paddingRight) - parseFloat(computedSectionStyle.paddingLeft) - parseFloat(computedSectionStyle.borderRightWidth) - parseFloat(computedSectionStyle.borderLeftWidth); } else { //reflect every value so that the same return statement can be used offset = surfaceSpacers.right - viewportRect.right; collapsedSignificantEdgePosition = -(currentSectionRect.left - parseFloat(computedSectionStyle.paddingRight) - parseFloat(computedSectionStyle.paddingLeft) - parseFloat(computedSectionStyle.borderRightWidth) - parseFloat(computedSectionStyle.borderLeftWidth)); } } else { //control.orientation === WinJS.UI.Orientation.vertical offset = surfaceSpacers.top + viewportRect.top; collapsedSignificantEdgePosition = currentSectionRect.bottom - parseFloat(computedSectionStyle.paddingTop) - parseFloat(computedSectionStyle.paddingBottom) - parseFloat(computedSectionStyle.borderTopWidth) - parseFloat(computedSectionStyle.borderBottomWidth); } return (collapsedSignificantEdgePosition > offset); } var sectionElements = control.element.querySelectorAll("." + HubSection._ClassName.hubSection); var surfaceSpacers = this.getSurfaceSpacers(control); //walk up until we find the element which should be the sectionOnScreen, left edge should be closest to the left spacer var index = 0; var currentSection = sectionElements[index]; while ((currentSection = sectionElements[index]) && !isSectionOnScreen(control, currentSection, surfaceSpacers)) { index++; } return index; } } }
the_stack
import * as _ from 'lodash'; import * as path from 'path'; import * as fs from 'fs'; import * as process from 'process'; // reuse http connections to aws to improve perf. Set it here before import of aws. process.env.AWS_NODEJS_CONNECTION_REUSE_ENABLED = '1'; const awsUserDir = process.env.HOME ? path.join(process.env.HOME as string, '.aws') : null; if (awsUserDir && fs.existsSync(awsUserDir)) { // We need to set this early because of https://github.com/aws/aws-sdk-js/pull/1391 // We also set this env-var in the main cli entry-point process.env.AWS_SDK_LOAD_CONFIG = '1'; // see https://github.com/aws/aws-sdk-js/pull/1391 // Note: // if this is set and ~/.aws doesn't exist we run into issue #17 as soon as the sdk is loaded: // Error: ENOENT: no such file or directory, open '.../.aws/credentials } // Use bluebird promises globally. We need to load this prior to 'aws-sdk' import * as bluebird from 'bluebird'; global.Promise = bluebird; import * as yargs from 'yargs'; import * as cli from 'cli-color'; import {Handler, description, fakeCommandSeparator, wrapCommandHandler, stackNameOpt, lintTemplateOpt} from './cli/utils'; import {Commands} from './cli/command-types'; // TODO bring these two in line with the new lazy load scheme import {buildParamCommands} from './params/cli' import {buildApprovalCommands} from './cfn/approval/cli' // We lazy load the actual command fns to make bash command completion // faster. See the git history of this file to see the non-lazy form. // Investigate this again if we can use babel/webpack to shrinkwrap export function lazyLoad(fnname: keyof Commands): Handler { return (args) => { const {implementations} = require('./cli/command-implementations'); return implementations[fnname](args); } } function lazyGetter(target: Commands, key: keyof Commands) { Object.defineProperty(target, key, {value: lazyLoad(key)}); } class LazyCommands implements Commands { @lazyGetter createStackMain: Handler @lazyGetter createOrUpdateStackMain: Handler @lazyGetter updateStackMain: Handler @lazyGetter listStacksMain: Handler @lazyGetter watchStackMain: Handler @lazyGetter describeStackMain: Handler @lazyGetter describeStackDriftMain: Handler @lazyGetter getStackTemplateMain: Handler @lazyGetter getStackInstancesMain: Handler @lazyGetter deleteStackMain: Handler @lazyGetter createChangesetMain: Handler @lazyGetter executeChangesetMain: Handler @lazyGetter lintMain: Handler @lazyGetter renderMain: Handler @lazyGetter getImportMain: Handler @lazyGetter estimateCost: Handler @lazyGetter demoMain: Handler @lazyGetter convertStackToIIDY: Handler @lazyGetter initStackArgs: Handler } const environmentOpt: yargs.Options = { type: 'string', default: 'development', alias: 'e', description: description('used to load environment based settings: AWS Profile, Region, etc.') }; export function buildArgs(commands = new LazyCommands(), wrapMainHandler = wrapCommandHandler) { const usage = (`${cli.bold(cli.green('iidy'))} - ${cli.green('CloudFormation with Confidence')}` + ` ${' '.repeat(18)} ${cli.blackBright('An acronym for "Is it done yet?"')}`); const epilogue = ('Status Codes:\n' + ' Success (0) Command successfully completed\n' + ' Error (1) An error was encountered while executing command\n' + ' Cancelled (130) User responded \'No\' to iidy prompt or interrupt (CTRL-C) was received'); return yargs .scriptName('iidy') .env('IIDY') .command( 'create-stack <argsfile>', description('create a cfn stack based on stack-args.yaml'), (args) => args .demandCommand(0, 0) .usage('Usage: iidy create-stack <stack-args.yaml>') .option('stack-name', stackNameOpt) .option('lint-template', lintTemplateOpt(false)), wrapMainHandler(commands.createStackMain)) .command( 'update-stack <argsfile>', description('update a cfn stack based on stack-args.yaml'), (args) => args .demandCommand(0, 0) .usage('Usage: iidy update-stack <stack-args.yaml>') .option('stack-name', stackNameOpt) .option('lint-template', lintTemplateOpt(false)) .option('changeset', { type: 'boolean', default: false, description: description('review & confirm changes via a changeset') }) .option('yes', { type: 'boolean', default: false, description: description('Confirm and execute changeset if --changeset option is used') }) .option('diff', { type: 'boolean', default: true, description: description('diff & review changes to the template body as part of changeset review') }) .option('stack-policy-during-update', { type: 'string', default: null, description: description('override original stack-policy for this update only') }), wrapMainHandler(commands.updateStackMain)) .command( 'create-or-update <argsfile>', description('create or update a cfn stack based on stack-args.yaml'), (args) => args .demandCommand(0, 0) .usage('Usage: iidy create-or-update <stack-args.yaml>') .option('stack-name', stackNameOpt) .option('lint-template', lintTemplateOpt(false)) .option('changeset', { type: 'boolean', default: false, description: description('review & confirm changes via a changeset') }) .option('yes', { type: 'boolean', default: false, description: description('Confirm and execute changeset if --changeset option is used') }) .option('diff', { type: 'boolean', default: true, description: description('diff & review changes to the template body as part of changeset review') }) .option('stack-policy-during-update', { type: 'string', default: null, description: description('override original stack-policy for this update only') }), wrapMainHandler(commands.createOrUpdateStackMain)) .command( 'estimate-cost <argsfile>', description('estimate aws costs based on stack-args.yaml'), (args) => args .demandCommand(0, 0) .option('stack-name', stackNameOpt), wrapMainHandler(commands.estimateCost)) .command(fakeCommandSeparator, '') .command( 'create-changeset <argsfile> [changesetName]', description('create a cfn changeset based on stack-args.yaml'), (args) => args .demandCommand(0, 0) .option('watch', { type: 'boolean', default: false, description: description('Watch stack after creating changeset. This is useful when exec-changeset is called by others.') }) .option('watch-inactivity-timeout', { type: 'number', default: (60 * 3), description: description('how long to wait for events when the stack is in a terminal state') }) .option('description', { type: 'string', default: undefined, description: description('optional description of changeset') }) .option('stack-name', stackNameOpt), wrapMainHandler(commands.createChangesetMain)) .command( 'exec-changeset <argsfile> <changesetName>', description('execute a cfn changeset based on stack-args.yaml'), (args) => args .demandCommand(0, 0) .option('stack-name', stackNameOpt), wrapMainHandler(commands.executeChangesetMain)) .command(fakeCommandSeparator, '') .command( 'describe-stack <stackname>', description('describe a stack'), (args) => args .demandCommand(0, 0) .option('events', { type: 'number', default: 50, description: description('how many stack events to display') }) .option('query', { type: 'string', default: null, description: description('jmespath search query to select a subset of the output') }) .usage('Usage: iidy describe-stack <stackname-or-argsfile>'), wrapMainHandler(commands.describeStackMain)) .command( 'watch-stack <stackname>', description('watch a stack that is already being created or updated'), (args) => args .demandCommand(0, 0) .option('inactivity-timeout', { type: 'number', default: (60 * 3), description: description('how long to wait for events when the stack is in a terminal state') }) .usage('Usage: iidy watch-stack <stackname-or-argsfile>'), wrapMainHandler(commands.watchStackMain)) .command( 'describe-stack-drift <stackname>', description('describe stack drift'), (args) => args .demandCommand(0, 0) .option('drift-cache', { type: 'number', default: (60 * 5), description: description('how long to cache previous drift detection results (seconds)') }) .usage('Usage: iidy describe-stack-drift <stackname-or-argsfile>'), wrapMainHandler(commands.describeStackDriftMain)) .command( 'delete-stack <stackname>', description('delete a stack (after confirmation)'), (args) => args .demandCommand(0, 0) .option('role-arn', { type: 'string', description: description('Role to assume for delete operation') }) .option('retain-resources', { type: 'string', array: true, description: description('For stacks in the DELETE_FAILED, list of logical resource ids to retain') }) .option('yes', { type: 'boolean', default: false, description: description('Confirm deletion of stack') }) .option('fail-if-absent', { type: 'boolean', default: false, description: description('Fail if stack is absent (exit code = 1). Default is to tolerate absence.') }) .usage('Usage: iidy delete-stack <stackname-or-argsfile>'), wrapMainHandler(commands.deleteStackMain)) .command( 'get-stack-template <stackname>', description('download the template of a live stack'), (args) => args .demandCommand(0, 0) .option('format', { type: 'string', default: 'original', choices: ['original', 'yaml', 'json'], description: description('Template stage to show') }) .option('stage', { type: 'string', default: 'Original', choices: ['Original', 'Processed'], description: description('Template stage to show') }) .usage('Usage: iidy get-stack-template <stackname-or-argsfile>'), wrapMainHandler(commands.getStackTemplateMain)) .command( 'get-stack-instances <stackname>', description('list the ec2 instances of a live stack'), (args) => args .demandCommand(0, 0) .option('short', { type: 'boolean', default: false, description: description('Show only instance dns names') }) .usage('Usage: iidy get-stack-instances <stackname-or-argsfile>'), wrapMainHandler(commands.getStackInstancesMain)) .command( 'list-stacks', description('list all stacks within a region'), (args) => args .demandCommand(0, 0) .option('tag-filter', { type: 'string', default: [], array: true, description: description('Filter by tags: key=value') }) .option('jmespath-filter', { type: 'string', default: null, description: description('jmespath search query to select a subset of the stacks') }) .option('query', { type: 'string', default: null, description: description('jmespath search query to select a subset of the output') }) .option('tags', { type: 'boolean', default: false, description: description('Show stack tags') }), wrapMainHandler(commands.listStacksMain)) .command(fakeCommandSeparator, '') .command('param', description('sub commands for working with AWS SSM Parameter Store'), buildParamCommands) .command(fakeCommandSeparator, '') .command('template-approval', description('sub commands for template approval'), buildApprovalCommands) .command(fakeCommandSeparator, '') .command( 'render <template>', description('pre-process and render yaml template'), (args) => args .demandCommand(0, 0) .usage('Usage: iidy render <input-template.yaml>') .positional('template', { description: 'template file to render, `-` for STDIN, can also be a directory of templates (will only render *.yml and *.yaml files in directory)' }) .option('outfile', { type: 'string', default: 'stdout', description: description('yaml input template to preprocess') }) .option('format', { type: 'string', default: 'yaml', choices: ['yaml', 'json'], description: description('output serialization syntax') }) .option('query', { type: 'string', default: null, description: description('jmespath search query to select a subset of the output') }) .option('overwrite', { type: 'boolean', default: false, description: description('Whether to overwrite an existing <outfile>.') }) .strict(), wrapMainHandler(commands.renderMain)) .command( 'get-import <import>', description('retrieve and print an $import value directly'), (args) => args .demandCommand(0, 0) .usage('Usage: iidy get-import <import>') .option('format', { type: 'string', default: 'yaml', choices: ['yaml', 'json'], description: description('output serialization syntax') }) .option('query', { type: 'string', default: null, description: description('jmespath search query to select a subset of the output') }) .strict(), wrapMainHandler(commands.getImportMain)) .command( 'demo <demoscript>', description('run a demo script'), (args) => args .demandCommand(0, 0) .option('timescaling', { type: 'number', default: 1, description: description('time scaling factor for sleeps, etc.') }) .strict(), wrapMainHandler(commands.demoMain)) .command( 'lint-template <argsfile>', description('lint a CloudFormation template'), (args) => args .demandCommand(0, 0) .option('use-parameters', { type: 'boolean', default: false, description: description('use parameters to improve linting accuracy') }) .strict(), wrapMainHandler(commands.lintMain)) .command( 'convert-stack-to-iidy <stackname> <outputDir>', description('create an iidy project directory from an existing CFN stack'), (args) => args .demandCommand(0, 0) .option('move-params-to-ssm', { type: 'boolean', default: false, description: description('automatically create an AWS SSM parameter namespace populated with the stack Parameters') }) .option('sortkeys', { type: 'boolean', default: true, description: description('sort keys in cloudformation maps') }) .option('project', { type: 'string', default: null, description: description('The name of the project (service or app). If not specified the "project" Tag is checked.') }), wrapMainHandler(commands.convertStackToIIDY)) .command( 'init-stack-args', description('initialize stack-args.yaml and cfn-template.yaml'), (args) => args .demandCommand(0, 0) .option('force', { type: 'boolean', default: false, description: description('Overwrite the current stack-args.yaml and cfn-template.yaml') }) .option('force-stack-args', { type: 'boolean', default: false, description: description('Overwrite the current stack-args.yaml') }) .option('force-cfn-template', { type: 'boolean', default: false, description: description('Overwrite the current cfn-template.yaml') }), wrapMainHandler(commands.initStackArgs)) .option('environment', environmentOpt) .option('client-request-token', { type: 'string', default: null, group: 'AWS Options:', description: description('a unique, case-sensitive string of up to 64 ASCII characters used to ensure idempotent retries.') }) .option('region', { type: 'string', default: null, group: 'AWS Options:', description: description('AWS region. Can also be set via --environment & stack-args.yaml:Region.') }) .option('profile', { type: 'string', default: null, group: 'AWS Options:', description: description( 'AWS profile. Can also be set via --environment & stack-args.yaml:Profile. ' + 'Use --profile=no-profile to override values in stack-args.yaml and use AWS_* env vars.') }) .option('assume-role-arn', { type: 'string', default: null, group: 'AWS Options:', description: description( 'AWS role. Can also be set via --environment & stack-args.yaml:AssumeRoleArn. ' + 'This is mutually exclusive with --profile. ' + 'Use --assume-role-arn=no-role to override values in stack-args.yaml and use AWS_* env vars.') }) .option('color', { type: 'string', default: 'auto', choices: ['auto', 'always', 'never'], description: description('whether to color output using ANSI escape codes') }) .middleware((args) => { if (args.color === 'never' || (args.color === 'auto' && ! process.stdout.columns)) { process.env.NO_COLOR='1'; } }) .option('debug', { type: 'boolean', default: false, description: description('log debug information to stderr.') }) .option('log-full-error', { type: 'boolean', default: false, description: description('log full error information to stderr.') }) .command(fakeCommandSeparator, '') .demandCommand(1) .usage(usage) .version() .alias('v', 'version') .describe('version', description('show version information')) .help('help', description('show help')) .alias('h', 'help') .completion('completion', description('generate bash completion script. To use: "source <(iidy completion)"')) .recommendCommands() .epilogue(epilogue) .strict() .wrap(yargs.terminalWidth()); } export async function main() { // called for side-effect to force parsing / handling // tslint:disable-next-line buildArgs().argv; // NOSONAR } if (module.parent === null) { main(); };
the_stack
import {TypedNode} from '../../../nodes/_Base'; import {Vector2} from 'three/src/math/Vector2'; import {JsonImportDispatcher} from './Dispatcher'; import {ParamType} from '../../../poly/ParamType'; import {ParamsUpdateOptions} from '../../../nodes/utils/params/ParamsController'; import {SceneJsonImporter} from '../../../io/json/import/Scene'; import {NodeContext} from '../../../poly/NodeContext'; import {NodeJsonExporterData, NodeJsonExporterUIData, InputData, IoConnectionPointsData} from '../export/Node'; import { ParamJsonExporterData, SimpleParamJsonExporterData, ComplexParamJsonExporterData, } from '../../../nodes/utils/io/IOController'; import {NodesJsonImporter} from './Nodes'; import {Poly} from '../../../Poly'; import {CoreType} from '../../../../core/Type'; import {CoreString} from '../../../../core/String'; import {PolyDictionary} from '../../../../types/GlobalTypes'; const COMPLEX_PARAM_DATA_KEYS: Readonly<string[]> = ['overriden_options', 'type']; type BaseNodeTypeWithIO = TypedNode<NodeContext, any>; export class NodeJsonImporter<T extends BaseNodeTypeWithIO> { constructor(protected _node: T) {} process_data(scene_importer: SceneJsonImporter, data: NodeJsonExporterData) { this.set_connection_points(data['connection_points']); // rather than having the children creation dependent on the persisted config and player mode, use the childrenAllowed() method // const skip_create_children = Poly.playerMode() && data.persisted_config; if (this._node.childrenAllowed()) { this.create_nodes(scene_importer, data['nodes']); } this.set_selection(data['selection']); // inputs clone if (this._node.io.inputs.overrideClonedStateAllowed()) { const override = data['cloned_state_overriden']; if (override) { this._node.io.inputs.overrideClonedState(override); } } this.set_flags(data); // params // const spare_params_data = ParamJsonImporter.spare_params_data(data['params']); // this.set_params(spare_params_data); this.set_params(data['params']); if (data.persisted_config) { this.set_persisted_config(data.persisted_config); } this.from_data_custom(data); // already called in create_node() // this._node.lifecycle.set_creation_completed(); } process_inputs_data(data: NodeJsonExporterData) { const maxInputsCount = data.maxInputsCount; if (maxInputsCount != null) { this._node.io.inputs.setCount(1, maxInputsCount); } this.setInputs(data['inputs']); } process_ui_data(scene_importer: SceneJsonImporter, data: NodeJsonExporterUIData) { if (!data) { return; } if (Poly.playerMode()) { return; } const ui_data = this._node.uiData; const pos = data['pos']; if (pos) { const vector = new Vector2().fromArray(pos); ui_data.setPosition(vector); } const comment = data['comment']; if (comment) { ui_data.setComment(comment); } if (this._node.childrenAllowed()) { this.process_nodes_ui_data(scene_importer, data['nodes']); } } create_nodes(scene_importer: SceneJsonImporter, data?: PolyDictionary<NodeJsonExporterData>) { if (!data) { return; } const nodes_importer = new NodesJsonImporter(this._node); nodes_importer.process_data(scene_importer, data); } set_selection(data?: string[]) { if (this._node.childrenAllowed() && this._node.childrenController) { if (data && data.length > 0) { const selected_nodes: BaseNodeTypeWithIO[] = []; data.forEach((node_name) => { const node = this._node.node(node_name); if (node) { selected_nodes.push(node); } }); this._node.childrenController.selection.set(selected_nodes); } } } set_flags(data: NodeJsonExporterData) { const flags = data['flags']; if (flags) { const bypass = flags['bypass']; if (bypass != null) { this._node.flags?.bypass?.set(bypass); } const display = flags['display']; if (display != null) { this._node.flags?.display?.set(display); } const optimize = flags['optimize']; if (optimize != null) { this._node.flags?.optimize?.set(optimize); } } } set_connection_points(connection_points_data: IoConnectionPointsData | undefined) { if (!connection_points_data) { return; } if (connection_points_data['in']) { this._node.io.saved_connection_points_data.set_in(connection_points_data['in']); } if (connection_points_data['out']) { this._node.io.saved_connection_points_data.set_out(connection_points_data['out']); } if (this._node.io.has_connection_points_controller) { this._node.io.connection_points.update_signature_if_required(); } } private setInputs(inputs_data?: InputData[]) { if (!inputs_data) { return; } let input_data: InputData; for (let i = 0; i < inputs_data.length; i++) { input_data = inputs_data[i]; if (input_data && this._node.parent()) { if (CoreType.isString(input_data)) { const input_node_name = input_data; const input_node = this._node.nodeSibbling(input_node_name); this._node.setInput(i, input_node); } else { const input_node = this._node.nodeSibbling(input_data['node']); const input_index = input_data['index']; this._node.setInput(input_index, input_node, input_data['output']); } } } } process_nodes_ui_data(scene_importer: SceneJsonImporter, data: PolyDictionary<NodeJsonExporterUIData>) { if (!data) { return; } if (Poly.playerMode()) { return; } const node_names = Object.keys(data); for (let node_name of node_names) { const node = this._node.node(node_name); if (node) { const node_data = data[node_name]; JsonImportDispatcher.dispatch_node(node).process_ui_data(scene_importer, node_data); // node.visit(JsonImporterVisitor).process_ui_data(node_data); } } } // // // PARAMS // // set_params(data?: PolyDictionary<ParamJsonExporterData<ParamType>>) { if (!data) { return; } const param_names = Object.keys(data); const params_update_options: ParamsUpdateOptions = {}; for (let param_name of param_names) { const param_data = data[param_name] as ComplexParamJsonExporterData<ParamType>; const options = param_data['options']; // const is_spare = options && options['spare'] === true; // make camelCase if required if (false && param_name.includes('_')) { param_name = CoreString.camelCase(param_name); } const param_type = param_data['type']!; const has_param = this._node.params.has_param(param_name); let has_param_and_same_type = false; let param; if (has_param) { param = this._node.params.get(param_name); // we can safely consider same type if param_type is not mentioned if ((param && param.type() == param_type) || param_type == null) { has_param_and_same_type = true; } } if (has_param_and_same_type) { if (this._is_param_data_complex(param_data)) { this._process_param_data_complex(param_name, param_data); } else { this._process_param_data_simple(param_name, param_data as SimpleParamJsonExporterData<ParamType>); } } else { // it the param is a spare one, // we check if it is currently exists with same type first. // - if it is, we only update the value // - if it's not, we delete it and add it again params_update_options.namesToDelete = params_update_options.namesToDelete || []; params_update_options.namesToDelete.push(param_name); params_update_options.toAdd = params_update_options.toAdd || []; params_update_options.toAdd.push({ name: param_name, type: param_type, init_value: param_data['default_value'] as any, raw_input: param_data['raw_input'] as any, options: options, }); // if (options && param_type) { // if (param_data['default_value']) { // if (has_param) { // this._node.params.delete_param(param_name); // } // param = this._node.add_param(param_type, param_name, param_data['default_value'], options); // if (param) { // JsonImportDispatcher.dispatch_param(param).process_data(param_data); // } // } // } } } // delete and create the spare params we need to const params_delete_required = params_update_options.namesToDelete && params_update_options.namesToDelete.length > 0; const params_add_required = params_update_options.toAdd && params_update_options.toAdd.length > 0; if (params_delete_required || params_add_required) { this._node.params.updateParams(params_update_options); // update them based on the imported data for (let spare_param of this._node.params.spare) { const param_data = data[spare_param.name()] as ComplexParamJsonExporterData<ParamType>; // JsonImportDispatcher.dispatch_param(spare_param).process_data(param_data); if (!spare_param.parent_param && param_data) { if (this._is_param_data_complex(param_data)) { this._process_param_data_complex(spare_param.name(), param_data); } else { this._process_param_data_simple( spare_param.name(), param_data as SimpleParamJsonExporterData<ParamType> ); } } } } // those hooks are useful for some gl nodes, // such as the constant, which needs to update its connections // based on another parameter, which will be set just before this._node.params.runOnSceneLoadHooks(); } private _process_param_data_simple(param_name: string, param_data: SimpleParamJsonExporterData<ParamType>) { this._node.params.get(param_name)?.set(param_data); } private _process_param_data_complex(param_name: string, param_data: ComplexParamJsonExporterData<ParamType>) { const param = this._node.params.get(param_name); if (param) { JsonImportDispatcher.dispatch_param(param).process_data(param_data); } // return // const has_param = this._node.params.has_param(param_name); // const param_type = param_data['type']!; // let has_param_and_same_type = false; // let param; // if (has_param) { // param = this._node.params.get(param_name); // // we can safely consider same type if param_type is not mentioned // if ((param && param.type == param_type) || param_type == null) { // has_param_and_same_type = true; // } // } // if (has_param_and_same_type) { // param = this._node.params.get(param_name); // if (param) { // JsonImportDispatcher.dispatch_param(param).process_data(param_data); // // param.visit(JsonImporterVisitor).process_data(param_data); // } // } else { // const options = param_data['options']; // if (options && param_type) { // const is_spare = options['spare'] === true; // if (is_spare && param_data['default_value']) { // if (has_param) { // this._node.params.delete_param(param_name); // } // param = this._node.add_param(param_type, param_name, param_data['default_value'], options); // if (param) { // JsonImportDispatcher.dispatch_param(param).process_data(param_data); // } // } // } // } } private _is_param_data_complex(param_data: ParamJsonExporterData<ParamType>): boolean { // we can test here most param value serialized, except for ramp if ( CoreType.isString(param_data) || CoreType.isNumber(param_data) || CoreType.isArray(param_data) || CoreType.isBoolean(param_data) ) { return false; } if (CoreType.isObject(param_data)) { const keys = Object.keys(param_data); for (let complex_key of COMPLEX_PARAM_DATA_KEYS) { if (keys.includes(complex_key)) { return true; } } } return false; } set_persisted_config(persisted_config_data: object) { if (this._node.persisted_config) { this._node.persisted_config.load(persisted_config_data); } } from_data_custom(data: NodeJsonExporterData) {} }
the_stack
import { toSemver, maximum } from "@azure-tools/codegen"; import { visit } from "@azure-tools/datastore"; import { areSimilar } from "@azure-tools/object-comparison"; import { YieldCPU } from "@azure-tools/tasks"; import compareVersions from "compare-versions"; import { cloneDeep } from "lodash"; type componentType = | "schemas" | "responses" | "parameters" | "examples" | "requestBodies" | "headers" | "securitySchemes" | "links" | "callbacks"; function getMergedProfilesMetadata( dict1: Record<string, string>, dict2: Record<string, string>, path: string, originalLocations: Array<string>, ): { [key: string]: string } { const result: { [key: string]: string } = {}; for (const [key, value] of Object.entries(dict1)) { result[key] = value; } for (const [key, value] of Object.entries(dict2)) { if (result[key] !== undefined && result[key] !== value) { throw Error( `Deduplicator: There's a conflict trying to deduplicate these two path objects with path ${path}, and with original locations ${originalLocations}. Both come from the same profile ${key}, but they have different api-versions: ${result[key]} and ${value}`, ); } result[key] = value; } return result; } export class Deduplicator { private hasRun = false; // table: // prevPointers -> newPointers // this will serve to generate a source map externally private mappings: Record<string, string> = {}; // table: // oldRefs -> newRefs private refs: Record<string, string> = {}; // sets containing the UIDs of already deduplicated components private deduplicatedComponents = { schemas: new Set<string>(), responses: new Set<string>(), parameters: new Set<string>(), examples: new Set<string>(), requestBodies: new Set<string>(), headers: new Set<string>(), securitySchemes: new Set<string>(), links: new Set<string>(), callbacks: new Set<string>(), }; // sets containing the UIDs of components already crawled private crawledComponents = { schemas: new Set<string>(), responses: new Set<string>(), parameters: new Set<string>(), examples: new Set<string>(), requestBodies: new Set<string>(), headers: new Set<string>(), securitySchemes: new Set<string>(), links: new Set<string>(), callbacks: new Set<string>(), }; // sets containing the UIDs of components already visited. // This is used to prevent circular references. private visitedComponents = { schemas: new Set<string>(), responses: new Set<string>(), parameters: new Set<string>(), examples: new Set<string>(), requestBodies: new Set<string>(), headers: new Set<string>(), securitySchemes: new Set<string>(), links: new Set<string>(), callbacks: new Set<string>(), }; // initially the target is the same as the original object private target: any; constructor(originalFile: any, protected deduplicateInlineModels = false) { this.target = cloneDeep(originalFile); this.target.info["x-ms-metadata"].deduplicated = true; } private async init() { // set initial refs table // NOTE: The deduplicator assumes that the document is merged-document from multiple tree-shaken files, // and for that reason the only references in the document are local component references. for (const { key: type, children } of visit(this.target.components)) { for (const { key: uid } of children) { this.refs[`#/components/${type}/${uid}`] = `#/components/${type}/${uid}`; } } // 1. deduplicate components if (this.target.components) { await this.deduplicateComponents(); } // 2. deduplicate remaining fields for (const { key: fieldName } of visit(this.target)) { if (fieldName === "paths") { if (this.target.paths) { this.deduplicatePaths(); } } else if (fieldName !== "components" && fieldName !== "openapi") { if (this.target[fieldName]) { this.deduplicateAdditionalFieldMembers(fieldName); } } } } private deduplicateAdditionalFieldMembers(fieldName: string) { const deduplicatedMembers = new Set<string>(); const element = this.target[fieldName]; // If it is a string there is nothing to deduplicate. if (typeof element === "string") { return; } // TODO: remaining fields are arrays and not maps, so when a member is deleted // it leaves an empty item. Figure out what is the best way to handle this. // convert to map and then delete? for (const { key: memberUid } of visit(element)) { if (!deduplicatedMembers.has(memberUid)) { const member = element[memberUid]; // iterate over all the members for (const { key: anotherMemberUid, value: anotherMember } of visit(element)) { // ignore merge with itself if (memberUid !== anotherMemberUid && areSimilar(member, anotherMember)) { // finish up delete element[anotherMemberUid]; this.updateMappings(`/${fieldName}/${anotherMemberUid}`, `/${fieldName}/${memberUid}`); deduplicatedMembers.add(anotherMemberUid); } } deduplicatedMembers.add(memberUid); } } let counter = 0; // clean up empty items if it was an array and update mappings if (Array.isArray(this.target[fieldName])) { this.target[fieldName] = this.target[fieldName].filter((element: any, index: number) => { if (element) { this.updateMappings(`/${fieldName}/${index}`, `/${fieldName}/${counter}`); counter++; return element; } }); } } private deduplicatePaths() { const deduplicatedPaths = new Set<string>(); for (let { key: pathUid } of visit(this.target.paths)) { if (!deduplicatedPaths.has(pathUid)) { const xMsMetadata = "x-ms-metadata"; const path = this.target.paths[pathUid]; // extract metadata to be merged let apiVersions = path[xMsMetadata].apiVersions; let filename = path[xMsMetadata].filename; let originalLocations = path[xMsMetadata].originalLocations; const pathFromMetadata = path[xMsMetadata].path; let profiles = path[xMsMetadata].profiles; // extract path properties excluding metadata const { "x-ms-metadata": metadataCurrent, ...filteredPath } = path; // iterate over all the paths for (const { key: anotherPathUid, value: anotherPath } of visit(this.target.paths)) { // ignore merge with itself && anotherPath already deleted (i.e. undefined) if (anotherPath !== undefined && pathUid !== anotherPathUid) { // extract the another path's properties excluding metadata const { "x-ms-metadata": metadataSchema, ...filteredAnotherPath } = anotherPath; // TODO: Add more keys to ignore. const keysToIgnore: Array<string> = ["description", "tags", "x-ms-original", "x-ms-examples"]; // they should have the same name to be merged and they should be similar if ( path[xMsMetadata].path === anotherPath[xMsMetadata].path && areSimilar(filteredPath, filteredAnotherPath, ...keysToIgnore) ) { // merge metadata apiVersions = apiVersions.concat(anotherPath[xMsMetadata].apiVersions); filename = filename.concat(anotherPath[xMsMetadata].filename); originalLocations = originalLocations.concat(anotherPath[xMsMetadata].originalLocations); profiles = getMergedProfilesMetadata( profiles, anotherPath[xMsMetadata].profiles, path[xMsMetadata].path, originalLocations, ); // the discriminator to take contents is the api version const maxApiVersionPath = maximum(path[xMsMetadata].apiVersions); const maxApiVersionAnotherPath = maximum(anotherPath[xMsMetadata].apiVersions); let uidPathToDelete = anotherPathUid; if (compareVersions(toSemver(maxApiVersionPath), toSemver(maxApiVersionAnotherPath)) === -1) { // if the current path max api version is less than the another path, swap ids. uidPathToDelete = pathUid; pathUid = anotherPathUid; } // finish up delete this.target.paths[uidPathToDelete]; this.updateMappings(`/paths/${uidPathToDelete}`, `/paths/${pathUid}`); deduplicatedPaths.add(uidPathToDelete); } } } this.target.paths[pathUid][xMsMetadata] = { apiVersions: [...new Set([...apiVersions])], filename: [...new Set([...filename])], path: pathFromMetadata, profiles, originalLocations: [...new Set([...originalLocations])], }; deduplicatedPaths.add(pathUid); } } } private async deduplicateComponents() { for (const { key: type, children: componentsMember } of visit(this.target.components)) { for (const { key: componentUid } of componentsMember) { await YieldCPU(); await this.deduplicateComponent(componentUid, type); } } } private async deduplicateComponent(componentUid: string, type: string) { switch (type) { case "schemas": case "responses": case "parameters": case "examples": case "requestBodies": case "headers": case "links": case "callbacks": case "securitySchemes": if (!this.deduplicatedComponents[type].has(componentUid)) { if (!this.crawledComponents[type].has(componentUid)) { await YieldCPU(); await this.crawlComponent(componentUid, type); } // Just try to deduplicate if it was not deduplicated while crawling another component. if (!this.deduplicatedComponents[type].has(componentUid)) { // deduplicate crawled component const xMsMetadata = "x-ms-metadata"; const component = this.target.components[type][componentUid]; // extract metadata to be merged let apiVersions = component[xMsMetadata].apiVersions; let filename = component[xMsMetadata].filename; let originalLocations = component[xMsMetadata].originalLocations; let name = component[xMsMetadata].name; // extract component properties excluding metadata const { "x-ms-metadata": metadataCurrent, ...filteredComponent } = component; // iterate over all the components of the same type of the component for (const { key: anotherComponentUid, value: anotherComponent } of visit(this.target.components[type])) { // ignore merge with itself && anotherComponent already deleted (i.e. undefined) if (anotherComponent !== undefined && componentUid !== anotherComponentUid) { // extract the another component's properties excluding metadata const { "x-ms-metadata": metadataSchema, ...filteredAnotherComponent } = anotherComponent; // TODO: Add more keys to ignore. const keysToIgnore: Array<string> = ["description", "x-ms-original", "x-ms-examples"]; const namesMatch = this.deduplicateInlineModels ? anotherComponent[xMsMetadata].name.replace(/\d*$/, "") === component[xMsMetadata].name.replace(/\d*$/, "") || (anotherComponent[xMsMetadata].name.indexOf("·") > -1 && component[xMsMetadata].name.indexOf("·") > -1) : anotherComponent[xMsMetadata].name.replace(/\d*$/, "") === component[xMsMetadata].name.replace(/\d*$/, ""); // const t1 = component['type']; // const t2 = anotherComponent['type']; // const typesAreSame = t1 === t2; // const isObjectSchema = t1 === 'object' || t1 === undefined; // const isStringSchemaWithFormat = !!(t1 === 'string' && component['format']); // (type === 'schemas' && t1 === t2 && (t1 === 'object' || (t1 === 'string' && component['format']) || t1 === undefined)) // they should have the same name to be merged and they should be similar if ( namesMatch && // typesAreSame && // (isObjectSchema || isStringSchemaWithFormat) && areSimilar(filteredAnotherComponent, filteredComponent, ...keysToIgnore) ) { // if the primary has a synthetic name, and the secondary doesn't use the secondary's name if (name.indexOf("·") > 0 && anotherComponent[xMsMetadata].name.indexOf("·") === -1) { name = anotherComponent[xMsMetadata].name; } // merge metadata apiVersions = apiVersions.concat(anotherComponent[xMsMetadata].apiVersions); filename = filename.concat(anotherComponent[xMsMetadata].filename); originalLocations = originalLocations.concat(anotherComponent[xMsMetadata].originalLocations); // the discriminator to take contents is the api version const maxApiVersionComponent = maximum(component[xMsMetadata].apiVersions); const maxApiVersionAnotherComponent = maximum(anotherComponent[xMsMetadata].apiVersions); let uidComponentToDelete = anotherComponentUid; if ( compareVersions(toSemver(maxApiVersionComponent), toSemver(maxApiVersionAnotherComponent)) === -1 ) { // if the current component max api version is less than the another component, swap ids. uidComponentToDelete = componentUid; componentUid = anotherComponentUid; } // finish up delete this.target.components[type][uidComponentToDelete]; this.refs[`#/components/${type}/${uidComponentToDelete}`] = `#/components/${type}/${componentUid}`; this.updateRefs(this.target); this.updateMappings( `/components/${type}/${uidComponentToDelete}`, `/components/${type}/${componentUid}`, ); this.deduplicatedComponents[type].add(uidComponentToDelete); } } } this.target.components[type][componentUid][xMsMetadata] = { apiVersions: [...new Set([...apiVersions])], filename: [...new Set([...filename])], name, originalLocations: [...new Set([...originalLocations])], }; this.deduplicatedComponents[type].add(componentUid); } } break; default: throw new Error(`Unknown component type: '${type}'`); } } private async crawlComponent(uid: string, type: componentType) { if (!this.visitedComponents[type].has(uid)) { if (this.target.components[type][uid]) { this.visitedComponents[type].add(uid); await this.crawlObject(this.target.components[type][uid]); } else { throw new Error(`Trying to crawl undefined component with uid '${uid}' and type '${type}'!`); } } this.crawledComponents[type].add(uid); } private async crawlObject(obj: any) { for (const { key, value } of visit(obj)) { // We don't want to navigate the examples. if (key === "x-ms-examples") { continue; } if (key === "$ref") { const refParts = value.split("/"); const componentUid = refParts.pop(); const type = refParts.pop(); await this.deduplicateComponent(componentUid, type); } else if (value && typeof value === "object") { await this.crawlObject(value); } } } private updateRefs(obj: any): void { for (const { key, value } of visit(obj)) { // We don't want to navigate the examples. if (key === "x-ms-examples") { continue; } if (value && typeof value === "object") { const ref = value.$ref; if (ref) { // see if this object has a $ref const newRef = this.refs[ref]; if (newRef) { value.$ref = newRef; } else { throw new Error(`$ref to original location '${ref}' is not found in the new refs collection`); } } // now, recurse into this object this.updateRefs(value); } } } private updateMappings(oldPointer: string, newPointer: string): void { this.mappings[oldPointer] = newPointer; for (const [key, value] of Object.entries(this.mappings)) { if (value === oldPointer) { this.mappings[key] = newPointer; } } } public async getOutput() { if (!this.hasRun) { await this.init(); this.hasRun = true; } return this.target; } public async getSourceMappings() { if (!this.hasRun) { await this.init(); this.hasRun = true; } return this.mappings; } }
the_stack
import type { DataItem } from "../../core/render/Component"; import type { Color } from "../../core/util/Color"; import type { FlowLink } from "./FlowLink"; import type { FlowNodes, IFlowNodesDataItem } from "./FlowNodes"; import type { ListTemplate } from "../../core/util/List"; import type { Bullet } from "../../core/render/Bullet"; import type * as d3sankey from "d3-sankey"; import { FlowDefaultTheme } from "./FlowDefaultTheme"; import { Series, ISeriesSettings, ISeriesDataItem, ISeriesPrivate, ISeriesEvents } from "../../core/render/Series"; import { Container } from "../../core/render/Container"; import { LinearGradient } from "../../core/render/gradients/LinearGradient"; import * as $array from "../../core/util/Array"; import * as $type from "../../core/util/Type"; export interface IFlowDataItem extends ISeriesDataItem { /** * Link value. */ value: number; /** * @ignore */ valueWorking: number; /** * Associated link element. */ link: FlowLink; /** * Link's color. */ fill: Color; /** * @ignore */ d3SankeyLink: d3sankey.SankeyLink<d3sankey.SankeyExtraProperties, d3sankey.SankeyExtraProperties>; /** * An ID of the target node. */ targetId: string; /** * An ID of the source node. */ sourceId: string; /** * A data item of the source node. */ source: DataItem<IFlowNodesDataItem>; /** * A data item of the target node. */ target: DataItem<IFlowNodesDataItem>; } export interface IFlowSettings extends ISeriesSettings { /** * A field in data which holds source node ID. */ sourceIdField?: string; /** * A field in data which holds target node ID. */ targetIdField?: string; /** * The thickness of node strip in pixels. * * @default 10 */ nodeWidth?: number; /** * Minimum gap between adjacent nodes. * * @default 10 */ nodePadding?: number; } export interface IFlowPrivate extends ISeriesPrivate { valueSum?: number; valueLow?: number; valueHigh?: number; } export interface IFlowEvents extends ISeriesEvents { } /** * A base class for all flow type series: [[Sankey]] and [[Chord]]. * * @see {@link https://www.amcharts.com/docs/v5/charts/flow-charts/} for more info */ export abstract class Flow extends Series { public static className: string = "Flow"; public static classNames: Array<string> = Series.classNames.concat([Flow.className]); declare public _settings: IFlowSettings; declare public _privateSettings: IFlowPrivate; declare public _dataItemSettings: IFlowDataItem; declare public _events: IFlowEvents; /** * @ignore */ declare public readonly nodes: FlowNodes; /** * Container series will place their links in. * * @default Container.new() */ public readonly linksContainer = this.children.push(Container.new(this._root, {})); /** * @ignore */ public abstract readonly links: ListTemplate<FlowLink>; protected _nodesData: d3sankey.SankeyNodeMinimal<{}, {}>[] = []; protected _linksData: { source: d3sankey.SankeyNodeMinimal<{}, {}>, target: d3sankey.SankeyNodeMinimal<{}, {}>, value: number }[] = []; protected _index = 0; protected _linksByIndex: { [index: string]: any } = {}; protected _afterNew() { this._defaultThemes.push(FlowDefaultTheme.new(this._root)); this.fields.push("disabled", "sourceId", "targetId"); if (this.nodes) { this.nodes.flow = this; } super._afterNew(); this.children.push(this.bulletsContainer); } /** * @ignore */ public abstract makeLink(dataItem: DataItem<this["_dataItemSettings"]>): FlowLink; protected processDataItem(dataItem: DataItem<this["_dataItemSettings"]>) { super.processDataItem(dataItem); const nodes = this.nodes; if (nodes) { let unknown = false; let sourceId = dataItem.get("sourceId"); let sourceDataItem = nodes.getDataItemById(sourceId); if (!sourceDataItem) { if (sourceId == null) { sourceId = "undefined" + this._index; this._index++; unknown = true; } nodes.data.push({ id: sourceId, unknown: unknown }); sourceDataItem = nodes.getDataItemById(sourceId)!; if (!unknown) { sourceDataItem.set("name", sourceId); } } unknown = false; let targetId = dataItem.get("targetId"); let targetDataItem = nodes.getDataItemById(targetId); if (!targetDataItem) { if (targetId == null) { targetId = "undefined" + this._index; this._index++; unknown = true; } nodes.data.push({ id: targetId, unknown: unknown }); targetDataItem = nodes.getDataItemById(targetId)!; if (!unknown) { targetDataItem.set("name", targetId); } } if (sourceDataItem) { dataItem.set("source", sourceDataItem); nodes.addOutgoingLink(sourceDataItem, dataItem); } if (targetDataItem) { dataItem.set("target", targetDataItem); nodes.addincomingLink(targetDataItem, dataItem); } dataItem.set("link", this.makeLink(dataItem)); const sourceIndex = this.nodes.dataItems.indexOf(sourceDataItem); const targetIndex = this.nodes.dataItems.indexOf(targetDataItem); this._linksByIndex[sourceIndex + "_" + targetIndex] = dataItem; if (sourceDataItem.get("unknown")) { if (targetDataItem) { sourceDataItem.set("fill", targetDataItem.get("fill")); } dataItem.get("link").set("fillStyle", "gradient"); } if (targetDataItem.get("unknown")) { if (sourceDataItem) { targetDataItem.set("fill", sourceDataItem.get("fill")); } dataItem.get("link").set("fillStyle", "gradient"); } this._updateLinkColor(dataItem); } } public _prepareChildren() { super._prepareChildren(); let valueLow = Infinity; let valueHigh = -Infinity; let valueSum = 0; if (this._valuesDirty) { this._nodesData = []; const nodes = this.nodes; if (nodes) { $array.each(nodes.dataItems, (dataItem) => { this._nodesData.push(dataItem.get("d3SankeyNode")); const incoming = dataItem.get("incomingLinks") let sumIncoming = 0; let sumIncomingWorking = 0; if (incoming) { $array.each(incoming, (link) => { const value = link.get("value"); const workingValue = link.get("valueWorking"); sumIncoming += value; sumIncomingWorking += workingValue; }) } dataItem.set("sumIncoming", sumIncoming); dataItem.set("sumIncomingWorking", sumIncomingWorking); const outgoing = dataItem.get("outgoingLinks") let sumOutgoing = 0; let sumOutgoingWorking = 0; if (outgoing) { $array.each(outgoing, (link) => { const value = link.get("value"); const workingValue = link.get("valueWorking"); sumOutgoing += value; sumOutgoingWorking += workingValue; }) } dataItem.set("sumOutgoing", sumOutgoing); dataItem.set("sumOutgoingWorking", sumOutgoingWorking); dataItem.set("sum", sumIncoming + sumOutgoing); dataItem.set("sumWorking", sumIncomingWorking + sumOutgoingWorking); nodes.updateLegendValue(dataItem); }) } this._linksData = []; $array.each(this.dataItems, (dataItem) => { let value = dataItem.get("value"); if ($type.isNumber(value)) { let valueWorking = dataItem.get("valueWorking"); let d3SankeyLink = { source: dataItem.get("source").get("d3SankeyNode"), target: dataItem.get("target").get("d3SankeyNode"), value: valueWorking }; dataItem.setRaw("d3SankeyLink", d3SankeyLink); this._linksData.push(d3SankeyLink); if (value < valueLow) { valueLow = value; } if (value > valueHigh) { valueHigh = value; } valueSum += value; this.updateLegendValue(dataItem); } }) this.setPrivateRaw("valueHigh", valueHigh); this.setPrivateRaw("valueLow", valueLow); this.setPrivateRaw("valueSum", valueSum); } } public _updateLinkColor(dataItem: DataItem<this["_dataItemSettings"]>) { const link = dataItem.get("link"); const fillStyle = link.get("fillStyle"); const strokeStyle = link.get("strokeStyle"); const source = dataItem.get("source"); const target = dataItem.get("target"); const sourceFill = source.get("fill"); const targetFill = target.get("fill"); link.remove("fillGradient"); link.remove("strokeGradient"); switch (fillStyle) { case "solid": link._applyTemplates(); break; case "source": link.set("fill", sourceFill); break; case "target": link.set("fill", targetFill); break; case "gradient": let gradient = link._fillGradient; if (!gradient) { gradient = LinearGradient.new(this._root, {}); const sourceStop: any = { color: sourceFill } if (source.get("unknown")) { sourceStop.opacity = 0; } const targetStop: any = { color: targetFill }; if (target.get("unknown")) { targetStop.opacity = 0; } gradient.set("stops", [sourceStop, targetStop]); link._fillGradient = gradient; } link.set("fillGradient", gradient); break; case "none": link.set("fill", undefined); // do not use remove! break; } switch (strokeStyle) { case "solid": link._applyTemplates(); break; case "source": link.set("stroke", sourceFill); break; case "target": link.set("stroke", targetFill); case "gradient": let gradient = link._strokeGradient; if (!gradient) { gradient = LinearGradient.new(this._root, {}); const sourceStop: any = { color: sourceFill } if (source.get("unknown")) { sourceStop.opacity = 0; } const targetStop: any = { color: targetFill }; if (target.get("unknown")) { targetStop.opacity = 0; } gradient.set("stops", [sourceStop, targetStop]); link._strokeGradient = gradient; } link.set("strokeGradient", gradient); break; case "none": link.remove("stroke"); break; } } /** * @ignore */ public disposeDataItem(dataItem: DataItem<this["_dataItemSettings"]>) { super.disposeDataItem(dataItem); let link = dataItem.get("link"); if (link) { this.links.removeValue(link); link.dispose(); } } /** * Shows diagram's data item. * * @param dataItem Data item * @param duration Animation duration in milliseconds * @return Promise */ public async hideDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> { const promises = [super.hideDataItem(dataItem, duration)]; const hiddenState = this.states.create("hidden", {}) const stateAnimationDuration = "stateAnimationDuration"; const stateAnimationEasing = "stateAnimationEasing"; if (!$type.isNumber(duration)) { duration = hiddenState.get(stateAnimationDuration, this.get(stateAnimationDuration, 0)); } const easing = hiddenState.get(stateAnimationEasing, this.get(stateAnimationEasing)); promises.push(dataItem.animate({ key: "valueWorking" as any, to: 0, duration: duration, easing: easing }).waitForStop()); const linkGraphics = dataItem.get("link"); linkGraphics.hide(); await Promise.all(promises); } /** * Shows diagram's data item. * * @param dataItem Data item * @param duration Animation duration in milliseconds * @return Promise */ public async showDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> { const promises = [super.showDataItem(dataItem, duration)]; if (!$type.isNumber(duration)) { duration = this.get("stateAnimationDuration", 0); } const easing = this.get("stateAnimationEasing"); promises.push(dataItem.animate({ key: "valueWorking" as any, to: dataItem.get("value"), duration: duration, easing: easing }).waitForStop()); const linkGraphics = dataItem.get("link"); linkGraphics.show(); await Promise.all(promises); } public _positionBullet(bullet: Bullet) { const sprite = bullet.get("sprite"); if (sprite) { const dataItem = sprite.dataItem as DataItem<this["_dataItemSettings"]>; if (dataItem) { const link = dataItem.get("link"); const sprite = bullet.get("sprite"); if (sprite) { const point = link.getPoint(this._getBulletLocation(bullet)); sprite.setAll({ x: point.x, y: point.y }); if (bullet.get("autoRotate")) { sprite.set("rotation", point.angle + bullet.get("autoRotateAngle", 0)); } } } } } protected _getBulletLocation(bullet: Bullet): number { return bullet.get("locationY", 0); } }
the_stack
import * as fs from 'fs-extra' import * as glob from 'globby' import 'mocha' import * as ppath from 'path' import * as os from 'os' import * as assert from 'assert' import * as gen from '../src/dialogGenerator' import {compareToOracle} from './generate.test' type Diff = { file: string, position: number } type Comparison = { original: string, originalFiles: string[], originalOnly: string[], merged: string, mergedFiles: string[], mergedOnly: string[], same: string[], different: Diff[] } function filePaths(files: string[], base: string): string { return files.map(f => ppath.resolve(base, f)).join('\n ') } function displayCompare(comparison: Comparison) { console.log(`Compare ${comparison.original} to ${comparison.merged}`) console.log(` originalOnly:\n ${filePaths(comparison.originalOnly, comparison.original)}`) console.log(` mergedOnly:\n ${filePaths(comparison.mergedOnly, comparison.merged)}`) console.log(` same:\n ${comparison.same.join('\n ')}`) console.log(` different:\n ${comparison.different.map(d => `${d.position}: ${ppath.resolve(comparison.original, d.file)} != ${ppath.resolve(comparison.merged, d.file)}`).join('\n ')}`) } function assertCheck(comparison: Comparison, errors: string[]) { if (errors.length > 0) { displayCompare(comparison) assert.fail(os.EOL + errors.join(os.EOL)) } } async function allFiles(base: string, path: string, files: Set<string>) { const stats = await fs.lstat(path) if (stats.isDirectory()) { for (const child of await fs.readdir(path)) { await allFiles(base, ppath.join(path, child), files) } } else { files.add(ppath.relative(base, path)) } } async function compareDirs(original: string, merged: string): Promise<Comparison> { const comparison: Comparison = {original, originalFiles: [], merged, mergedFiles: [], originalOnly: [], mergedOnly: [], same: [], different: []} const originalFiles = new Set<string>() const mergedFiles = new Set<string>() await allFiles(original, original, originalFiles) await allFiles(merged, merged, mergedFiles) comparison.originalFiles = Array.from(originalFiles) comparison.mergedFiles = Array.from(mergedFiles) for (const file1 of originalFiles) { if (mergedFiles.has(file1)) { // See if files are the same const originalVal = await fs.readFile(ppath.join(original, file1), 'utf-8') const mergedVal = await fs.readFile(ppath.join(merged, file1), 'utf-8') if (originalVal === mergedVal) { comparison.same.push(file1) } else { let pos = 0 while (pos < originalVal.length && pos < mergedVal.length) { if (originalVal[pos] !== mergedVal[pos]) { break } ++pos } comparison.different.push({file: file1, position: pos}) } } else { comparison.originalOnly.push(file1) } } comparison.mergedOnly = [...mergedFiles].filter(x => !originalFiles.has(x)) return comparison } function entryCompare(comparison: Comparison, name: string, expected: number | string[] | undefined, errors: string[]) { if (expected) { const value = comparison[name] as string[] if (typeof expected === 'number') { if (value.length !== expected) { errors.push(`${name}: ${value.length} != ${expected}`) } } else { for (const expect of expected as string[]) { if (!value.includes(expect)) { errors.push(`${name} does not contain ${expect}`) } } } } } function assertCompare( comparison: Comparison, errors: string[], same?: number | string[], different?: number | string[], originalOnly?: number | string[], mergedOnly?: number | string[]): boolean { entryCompare(comparison, 'same', same, errors) entryCompare(comparison, 'different', different, errors) entryCompare(comparison, 'originalOnly', originalOnly, errors) entryCompare(comparison, 'mergedOnly', mergedOnly, errors) return errors.length > 0 } function assertRemoved(comparison: Comparison, file: string, errors: string[]) { if (comparison.mergedFiles.includes(file)) { errors.push(`Did not expect ${file} in merged`) } } function assertAddedProperty(comparison: Comparison, added: string, errors: string[]): string[] { const found: string[] = [] for (const file of comparison.mergedFiles) { if (file.includes(added)) { found.push(file) } } if (found.length === 0) { errors.push(`Missing ${added} in merged files`) } return found } function assertRemovedProperty(comparison: Comparison, removed: string, errors: string[]): string[] { const found: string[] = [] for (const file of comparison.mergedFiles) { if (file.includes(removed)) { found.push(file) } } if (found.length > 0) { errors.push(`Found ${removed} in merged files`) } return found } const output_dir = ppath.join(os.tmpdir(), 'mergeTest') const merge_data = 'test/merge_data' const modified_data = `${merge_data}/modified` const originalSchema = ppath.join(merge_data, 'sandwichMerge.form') const modifiedSchema = ppath.join(merge_data, 'sandwichMerge-modified.form') const originalDir = ppath.join(output_dir, 'sandwichMerge-original') const mergedDir = ppath.join(output_dir, 'sandwichMerge-merged') function errorOnly(type: gen.FeedbackType, msg: string): void { if ((type === gen.FeedbackType.warning && !msg.startsWith('Replace')) || type === gen.FeedbackType.error) { assert.fail(`${type}: ${msg}`) } } function feedback(type: gen.FeedbackType, msg: string): void { if (type !== gen.FeedbackType.debug) { console.log(`${type}: ${msg}`) } if ((type === gen.FeedbackType.warning && !msg.startsWith('Replace')) || type === gen.FeedbackType.error) { assert.fail(`${type}: ${msg}`) } } async function assertContains(file: string, regex: RegExp, errors: string[]) { const val = await fs.readFile(ppath.join(mergedDir, file), 'utf8') if (!val.match(regex)) { errors.push(`${file} does not contain expected ${regex}`) } } async function assertMissing(file: string, regex: RegExp, errors: string[]) { const val = await fs.readFile(ppath.join(mergedDir, file), 'utf8') if (val.match(regex)) { errors.push(`${file} contains unexpected ${regex}`) } } async function assertUnchanged(file: string, expected: boolean, errors: string[]) { const unchanged = await gen.isUnchanged(ppath.join(mergedDir, file)) if (unchanged !== expected) { errors.push(`${file} is unexpectedly ${expected ? 'changed' : 'unchanged'}`) } } async function copyToMerged(pattern: string) { const pathPattern = ppath.join(modified_data, pattern).replace(/\\/g, '/') for (const path of await glob(pathPattern)) { const file = ppath.relative(modified_data, path) const dest = ppath.join(mergedDir, file) console.log(`Modifying ${dest}`) await fs.copyFile(path, dest) } } async function deleteMerged(pattern: string) { const pathPattern = ppath.join(mergedDir, pattern).replace(/\\/g, '/') for (const file of await glob(pathPattern)) { console.log(`Deleting ${file}`) await fs.unlink(file) } } function beforeSetup(singleton: boolean) { return async function () { try { console.log('Deleting output directory') await fs.remove(output_dir) console.log('Generating original files') await gen.generate(originalSchema, { prefix: 'sandwichMerge', outDir: originalDir, singleton: singleton, feedback: errorOnly }) } catch (e) { assert.fail((e as Error).message) } } } function beforeEachSetup() { return async function () { try { console.log('\n\nCopying original generated to merged') await fs.remove(mergedDir) await fs.copy(originalDir, mergedDir) } catch (e) { assert.fail((e as Error).message) } } } describe('dialog:generate --merge files', async function () { before(beforeSetup(false)) beforeEach(beforeEachSetup()) // Ensure merge with no changes is unchanged it('merge: self', async function () { try { console.log('Self merging') await gen.generate(originalSchema, { outDir: mergedDir, merge: true, feedback }) const comparison = await compareDirs(originalDir, mergedDir) const errors: string[] = [] assertCompare(comparison, errors, comparison.originalFiles.length) assertCheck(comparison, errors) } catch (e) { assert.fail((e as Error).message) } }) // Ensure merge with modified schema changes as expected it('merge: modified', async function () { try { console.log('Modified merge') await gen.generate(modifiedSchema, { prefix: 'sandwichMerge', outDir: mergedDir, merge: true, feedback }) const comparison = await compareDirs(originalDir, mergedDir) const errors = [] assertAddedProperty(comparison, 'Hobby', errors) assertRemovedProperty(comparison, 'Meat', errors) assertRemovedProperty(comparison, 'Toppings', errors) assertRemovedProperty(comparison, 'Sauces', errors) await assertContains('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', /black/, errors) await assertMissing('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', /white/, errors) //sandwichMerge await assertContains('language-generation/en-us/CheeseValue/sandwichMerge-CheeseValue.en-us.lg', /brie/, errors) // Unchanged hash + optional enum fixes = hash updated await assertUnchanged('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', true, errors) await assertUnchanged('language-generation/en-us/Name/sandwichMerge-Name.en-us.lg', true, errors) assertCheck(comparison, errors) } catch (e) { assert.fail((e as Error).message) } }) // Respect user changes it('merge: respect changes', async function () { try { // Modify a dialog file it should stay unchanged except for main.dialog which should be updated, but not hash updated // Remove a dialog file and it should not come back // Modify an .lu file and it should have enum updated, but not hash // Modify an .lg file and it should have enum updated, but not hash console.log('Respect changes merge') await copyToMerged('**/language-generation/en-us/Bread/*') await copyToMerged('**/language-generation/en-us/BreadValue/*') await copyToMerged('**/language-understanding/en-us/Bread/*') await copyToMerged('**/language-understanding/en-us/form/*') const dialogPath = ppath.join(mergedDir, 'sandwichMerge.dialog') const old = await fs.readJSON(dialogPath) old.$comment = 'changed dialog' old.triggers = ["sandwichMerge-foo-missing", ...old.triggers.filter(t => t !== 'sandwichMerge-price-remove-money')] await fs.writeJSON(dialogPath, old) await copyToMerged('dialogs/sandwichMerge-foo-missing.dialog') await deleteMerged('dialogs/Price/sandwichMerge-price-remove-money.dialog') await gen.generate(modifiedSchema, { prefix: 'sandwichMerge', outDir: mergedDir, merge: true, feedback }) const comparison = await compareDirs(originalDir, mergedDir) const errors = [] // Changed + optional enum fixes = hash not updated, so still changed await assertUnchanged('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', false, errors) await assertUnchanged('sandwichMerge.dialog', false, errors) // Despite enum update, hash updated so unchanged await assertUnchanged('language-generation/en-us/CheeseValue/sandwichMerge-CheeseValue.en-us.lg', true, errors) // Main should still be updated await assertContains('sandwichMerge.dialog', /sandwichMerge-foo/, errors) await assertMissing('sandwichMerge.dialog', /sandwichMerge-price-remove-money/, errors) await assertContains('sandwichMerge.dialog', /changed dialog/, errors) // Removed should stay removed assertRemoved(comparison, 'dialogs/sandwichMerged-price-remove-money.dialog', errors) // Still get enum updates await assertContains('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', /black/, errors) await assertMissing('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', /white/, errors) //sandwichMerge await assertMissing('language-understanding/en-us/sandwichMerge.en-us.lu', /pulled/, errors) await assertContains('language-understanding/en-us/Bread/sandwichMerge-Bread-BreadValue.en-us.lu', />- {BreadProperty={BreadValue=rye}}/, errors) await assertContains('language-understanding/en-us/Bread/sandwichMerge-Bread-BreadValue.en-us.lu', /black/, errors) assertCheck(comparison, errors) } catch (e) { assert.fail((e as Error).message) } }) }) describe('dialog:generate --merge singleton', async function () { before(beforeSetup(true)) beforeEach(beforeEachSetup()) // Ensure merge with no changes is unchanged it('merge singleton: self', async function () { try { console.log('Self merging') await gen.generate(originalSchema, { outDir: mergedDir, merge: true, singleton: true, feedback }) const comparison = await compareDirs(originalDir, mergedDir) const errors: string[] = [] assertCompare(comparison, errors, comparison.originalFiles.length) assertCheck(comparison, errors) } catch (e) { assert.fail((e as Error).message) } }) // Ensure merge with modified schema changes as expected it('merge singleton: modified', async function () { try { console.log('Modified merge') await gen.generate(modifiedSchema, { prefix: 'sandwichMerge', outDir: mergedDir, merge: true, singleton: true, feedback }) const comparison = await compareDirs(originalDir, mergedDir) const errors = [] assertAddedProperty(comparison, 'Hobby', errors) assertRemovedProperty(comparison, 'Meat', errors) assertRemovedProperty(comparison, 'Toppings', errors) assertRemovedProperty(comparison, 'Sauces', errors) await assertContains('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', /black/, errors) await assertMissing('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', /white/, errors) await assertContains('language-generation/en-us/CheeseValue/sandwichMerge-CheeseValue.en-us.lg', /brie/, errors) // Unchanged hash + optional enum fixes = hash updated await assertUnchanged('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', true, errors) await assertUnchanged('language-generation/en-us/Name/sandwichMerge-Name.en-us.lg', true, errors) assertCheck(comparison, errors) await compareToOracle(ppath.join(mergedDir, 'sandwichMerge.dialog')) } catch (e) { assert.fail((e as Error).message) } }) // Respect user changes it('merge singleton: respect changes', async function () { try { // Modify a dialog file it should stay unchanged except for main.dialog which should be updated, but not hash updated // Remove a dialog file and it should not come back // Modify an .lu file and it should have enum updated, but not hash // Modify an .lg file and it should have enum updated, but not hash console.log('Respect changes merge') await copyToMerged('**/language-generation/en-us/Bread/*') await copyToMerged('**/language-generation/en-us/BreadValue/*') await copyToMerged('**/language-understanding/en-us/Bread/*') await copyToMerged('**/language-understanding/en-us/sandwichMerge.en-us.lu') // Modify an existing trigger and add a custom trigger const dialogPath = ppath.join(mergedDir, 'sandwichMerge.dialog') const oldDialog = await fs.readJSON(dialogPath) const modifiedTrigger = oldDialog.triggers[1] const reorderedTrigger = oldDialog.triggers[2] modifiedTrigger.actions.push({$kind: "Microsoft.SetProperty"}) const newTrigger = {$kind: "Microsoft.OnCondition", actions: []} oldDialog.triggers.splice(3, 1, newTrigger, reorderedTrigger) oldDialog.triggers.splice(2, 1) await fs.writeFile(dialogPath, gen.stringify(oldDialog)) await gen.generate(modifiedSchema, { prefix: 'sandwichMerge', outDir: mergedDir, merge: true, singleton: true, feedback }) const comparison = await compareDirs(originalDir, mergedDir) const errors = [] // Changed + optional enum fixes = hash not updated, so still changed await assertUnchanged('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', false, errors) await assertUnchanged('sandwichMerge.dialog', false, errors) // Despite enum update, hash updated so unchanged await assertUnchanged('language-generation/en-us/CheeseValue/sandwichMerge-CheeseValue.en-us.lg', true, errors) // Still get enum updates await assertContains('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', /black/, errors) await assertMissing('language-generation/en-us/BreadValue/sandwichMerge-BreadValue.en-us.lg', /white/, errors) await assertMissing('language-understanding/en-us/sandwichMerge.en-us.lu', /pulled/, errors) await assertContains('language-understanding/en-us/Bread/sandwichMerge-Bread-BreadValue.en-us.lu', />- {BreadProperty={BreadValue=rye}}/, errors) await assertContains('language-understanding/en-us/Bread/sandwichMerge-Bread-BreadValue.en-us.lu', /black/, errors) assertCheck(comparison, errors) const mergedDialog = await fs.readJSON(dialogPath) assert.deepStrictEqual(mergedDialog.triggers[1], modifiedTrigger, 'Did not preserve modified trigger') assert.deepStrictEqual(mergedDialog.triggers[2], newTrigger, 'Did not preserve custom trigger') assert.deepStrictEqual(mergedDialog.triggers[3], reorderedTrigger, 'Did not preserve reordered trigger') } catch (e) { assert.fail((e as Error).message) } }) })
the_stack
import EventEmitter from 'eventemitter3' import { Aperture, BatteryLevel, ConfigName, ConfigType, DriveMode, ExposureMeteringMode, ExposureMode, FlashMode, FocalLength, FocusMeteringMode, FocusMode, FunctionalMode, ISO, ManualFocusOption, WhiteBalance, } from './configs' import {TethrObject} from './TethrObject' export type OperationResultStatus = | 'ok' | 'unsupported' | 'invalid parameter' | 'busy' | 'general error' export type OperationResult<T> = T extends void ? {status: OperationResultStatus} : | {status: Exclude<OperationResultStatus, 'ok'>} | { status: 'ok' value: T } export type ConfigDesc<T> = { value: T | null writable: boolean option?: | {type: 'enum'; values: T[]} | {type: 'range'; min: T; max: T; step: T} } export interface TakePhotoOption { download?: boolean } type EventTypes = { [N in ConfigName as `${N}Changed`]: ConfigDesc<ConfigType[N]> } & { disconnect: void liveviewStreamUpdate: MediaStream } type ConfigGetters = { [N in ConfigName as `get${Capitalize<N>}`]: () => Promise< ConfigType[N] | null > } type ConfigSetters = { [N in ConfigName as `set${Capitalize<N>}`]: ( value: ConfigType[N] ) => Promise<OperationResult<void>> } type ConfigDescGetters = { [N in ConfigName as `get${Capitalize<N>}Desc`]: () => Promise< ConfigDesc<ConfigType[N]> > } export function createUnsupportedConfigDesc<T>(): ConfigDesc<T> { return { writable: false, value: null, } } export function createReadonlyConfigDesc<T>(value: T): ConfigDesc<T> { return { writable: false, value, } } export abstract class Tethr extends EventEmitter<EventTypes> implements ConfigGetters, ConfigSetters, ConfigDescGetters { public abstract open(): Promise<void> public abstract close(): Promise<void> public abstract get opened(): boolean // Config public async get<N extends ConfigName>( name: N ): Promise<ConfigType[N] | null> { return (await this.getDesc(name)).value } public async set<N extends ConfigName>( name: N, value: ConfigType[N] ): Promise<OperationResult<void>> { switch (name) { case 'aperture': return this.setAperture(value as Aperture) case 'batteryLevel': return this.setBatteryLevel(value as BatteryLevel) case 'burstInterval': return this.setBurstInterval(value as number) case 'burstNumber': return this.setBurstNumber(value as number) case 'canRunAutoFocus': return this.setCanRunAutoFocus(value as boolean) case 'canRunManualFocus': return this.setCanRunManualFocus(value as boolean) case 'canStartLiveview': return this.setCanStartLiveview(value as boolean) case 'canTakePhoto': return this.setCanTakePhoto(value as boolean) case 'captureDelay': return this.setCaptureDelay(value as number) case 'colorMode': return this.setColorMode(value as string) case 'colorTemperature': return this.setColorTemperature(value as number) case 'contrast': return this.setContrast(value as number) case 'dateTime': return this.setDateTime(value as Date) case 'digitalZoom': return this.setDigitalZoom(value as number) case 'driveMode': return this.setDriveMode(value as DriveMode) case 'exposureComp': return this.setExposureComp(value as string) case 'exposureMeteringMode': return this.setExposureMeteringMode(value as ExposureMeteringMode) case 'exposureMode': return this.setExposureMode(value as ExposureMode) case 'facingMode': return this.setFacingMode(value as string) case 'flashMode': return this.setFlashMode(value as FlashMode) case 'focalLength': return this.setFocalLength(value as FocalLength) case 'focusDistance': return this.setFocusDistance(value as number) case 'focusMeteringMode': return this.setFocusMeteringMode(value as FocusMeteringMode) case 'focusMode': return this.setFocusMode(value as FocusMode) case 'functionalMode': return this.setFunctionalMode(value as FunctionalMode) case 'imageAspect': return this.setImageAspect(value as string) case 'imageQuality': return this.setImageQuality(value as string) case 'imageSize': return this.setImageSize(value as string) case 'iso': return this.setIso(value as ISO) case 'liveviewEnabled': return this.setLiveviewEnabled(value as boolean) case 'liveviewMagnifyRatio': return this.setLiveviewMagnifyRatio(value as number) case 'liveviewSize': return this.setLiveviewSize(value as string) case 'manualFocusOptions': return this.setManualFocusOptions(value as ManualFocusOption[]) case 'manufacturer': return this.setManufacturer(value as string) case 'model': return this.setModel(value as string) case 'sharpness': return this.setSharpness(value as number) case 'shutterSpeed': return this.setShutterSpeed(value as string) case 'timelapseInterval': return this.setTimelapseInterval(value as number) case 'timelapseNumber': return this.setTimelapseNumber(value as number) case 'whiteBalance': return this.setWhiteBalance(value as WhiteBalance) } return {status: 'unsupported'} } public async getDesc<N extends ConfigName>( // eslint-disable-next-line @typescript-eslint/no-unused-vars name: N ): Promise<ConfigDesc<ConfigType[N]>> { type ReturnType = Promise<ConfigDesc<ConfigType[N]>> switch (name) { case 'aperture': return this.getApertureDesc() as ReturnType case 'batteryLevel': return this.getBatteryLevelDesc() as ReturnType case 'burstInterval': return this.getBurstIntervalDesc() as ReturnType case 'burstNumber': return this.getBurstNumberDesc() as ReturnType case 'canRunAutoFocus': return this.getCanRunAutoFocusDesc() as ReturnType case 'canRunManualFocus': return this.getCanRunManualFocusDesc() as ReturnType case 'canStartLiveview': return this.getCanStartLiveviewDesc() as ReturnType case 'canTakePhoto': return this.getCanTakePhotoDesc() as ReturnType case 'captureDelay': return this.getCaptureDelayDesc() as ReturnType case 'colorMode': return this.getColorModeDesc() as ReturnType case 'colorTemperature': return this.getColorTemperatureDesc() as ReturnType case 'contrast': return this.getContrastDesc() as ReturnType case 'dateTime': return this.getDateTimeDesc() as ReturnType case 'digitalZoom': return this.getDigitalZoomDesc() as ReturnType case 'driveMode': return this.getDriveModeDesc() as ReturnType case 'exposureComp': return this.getExposureCompDesc() as ReturnType case 'exposureMeteringMode': return this.getExposureMeteringModeDesc() as ReturnType case 'exposureMode': return this.getExposureModeDesc() as ReturnType case 'facingMode': return this.getFacingModeDesc() as ReturnType case 'flashMode': return this.getFlashModeDesc() as ReturnType case 'focalLength': return this.getFocalLengthDesc() as ReturnType case 'focusDistance': return this.getFocusDistanceDesc() as ReturnType case 'focusMeteringMode': return this.getFocusMeteringModeDesc() as ReturnType case 'focusMode': return this.getFocusModeDesc() as ReturnType case 'functionalMode': return this.getFunctionalModeDesc() as ReturnType case 'imageAspect': return this.getImageAspectDesc() as ReturnType case 'imageQuality': return this.getImageQualityDesc() as ReturnType case 'imageSize': return this.getImageSizeDesc() as ReturnType case 'iso': return this.getIsoDesc() as ReturnType case 'liveviewEnabled': return this.getLiveviewEnabledDesc() as ReturnType case 'liveviewMagnifyRatio': return this.getLiveviewMagnifyRatioDesc() as ReturnType case 'liveviewSize': return this.getLiveviewSizeDesc() as ReturnType case 'manualFocusOptions': return this.getManualFocusOptionsDesc() as ReturnType case 'manufacturer': return this.getManufacturerDesc() as ReturnType case 'model': return this.getModelDesc() as ReturnType case 'sharpness': return this.getSharpnessDesc() as ReturnType case 'shutterSpeed': return this.getShutterSpeedDesc() as ReturnType case 'timelapseInterval': return this.getTimelapseIntervalDesc() as ReturnType case 'timelapseNumber': return this.getTimelapseNumberDesc() as ReturnType case 'whiteBalance': return this.getWhiteBalanceDesc() as ReturnType } return { writable: false, value: null, } } public async getAperture(): Promise<Aperture | null> { return (await this.getApertureDesc()).value } public async setAperture( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: Aperture ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getApertureDesc(): Promise<ConfigDesc<Aperture>> { return createUnsupportedConfigDesc() } public async getBatteryLevel(): Promise<BatteryLevel | null> { return (await this.getBatteryLevelDesc()).value } public async setBatteryLevel( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: BatteryLevel ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getBatteryLevelDesc(): Promise<ConfigDesc<BatteryLevel>> { return createUnsupportedConfigDesc() } public async getBurstInterval(): Promise<number | null> { return (await this.getBurstIntervalDesc()).value } public async setBurstInterval( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getBurstIntervalDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getBurstNumber(): Promise<number | null> { return (await this.getBurstNumberDesc()).value } public async setBurstNumber( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getBurstNumberDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getCanRunAutoFocus(): Promise<boolean | null> { return (await this.getCanRunAutoFocusDesc()).value } public async setCanRunAutoFocus( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: boolean ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getCanRunAutoFocusDesc(): Promise<ConfigDesc<boolean>> { return createUnsupportedConfigDesc() } public async getCanRunManualFocus(): Promise<boolean | null> { return (await this.getCanRunManualFocusDesc()).value } public async setCanRunManualFocus( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: boolean ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getCanRunManualFocusDesc(): Promise<ConfigDesc<boolean>> { return createUnsupportedConfigDesc() } public async getCanStartLiveview(): Promise<boolean | null> { return (await this.getCanStartLiveviewDesc()).value } public async setCanStartLiveview( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: boolean ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getCanStartLiveviewDesc(): Promise<ConfigDesc<boolean>> { return createUnsupportedConfigDesc() } public async getCanTakePhoto(): Promise<boolean | null> { return (await this.getCanTakePhotoDesc()).value } public async setCanTakePhoto( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: boolean ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getCanTakePhotoDesc(): Promise<ConfigDesc<boolean>> { return createUnsupportedConfigDesc() } public async getCaptureDelay(): Promise<number | null> { return (await this.getCaptureDelayDesc()).value } public async setCaptureDelay( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getCaptureDelayDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getColorMode(): Promise<string | null> { return (await this.getColorModeDesc()).value } public async setColorMode( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getColorModeDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getColorTemperature(): Promise<number | null> { return (await this.getColorTemperatureDesc()).value } public async setColorTemperature( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getColorTemperatureDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getCompressionSetting(): Promise<number | null> { return (await this.getCompressionSettingDesc()).value } public async setCompressionSetting( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getCompressionSettingDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getContrast(): Promise<number | null> { return (await this.getContrastDesc()).value } public async setContrast( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getContrastDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getDateTime(): Promise<Date | null> { return (await this.getDateTimeDesc()).value } public async setDateTime( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: Date ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getDateTimeDesc(): Promise<ConfigDesc<Date>> { return createUnsupportedConfigDesc() } public async getDigitalZoom(): Promise<number | null> { return (await this.getDigitalZoomDesc()).value } public async setDigitalZoom( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getDigitalZoomDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getDriveMode(): Promise<DriveMode | null> { return (await this.getDriveModeDesc()).value } public async setDriveMode( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: DriveMode ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getDriveModeDesc(): Promise<ConfigDesc<DriveMode>> { return createUnsupportedConfigDesc() } public async getExposureComp(): Promise<string | null> { return (await this.getExposureCompDesc()).value } public async setExposureComp( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getExposureCompDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getExposureMeteringMode(): Promise<ExposureMeteringMode | null> { return (await this.getExposureMeteringModeDesc()).value } public async setExposureMeteringMode( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getExposureMeteringModeDesc(): Promise< ConfigDesc<ExposureMeteringMode> > { return createUnsupportedConfigDesc() } public async getExposureMode(): Promise<ExposureMode | null> { return (await this.getExposureModeDesc()).value } public async setExposureMode( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: ExposureMode ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getExposureModeDesc(): Promise<ConfigDesc<ExposureMode>> { return createUnsupportedConfigDesc() } public async getFacingMode(): Promise<string | null> { return (await this.getFacingModeDesc()).value } public async setFacingMode( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getFacingModeDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getFlashMode(): Promise<FlashMode | null> { return (await this.getFlashModeDesc()).value } public async setFlashMode( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: FlashMode ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getFlashModeDesc(): Promise<ConfigDesc<FlashMode>> { return createUnsupportedConfigDesc() } public async getFocalLength(): Promise<FocalLength | null> { return (await this.getFocalLengthDesc()).value } public async setFocalLength( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: FocalLength ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getFocalLengthDesc(): Promise<ConfigDesc<FocalLength>> { return createUnsupportedConfigDesc() } public async getFocusDistance(): Promise<number | null> { return (await this.getFocusDistanceDesc()).value } public async setFocusDistance( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getFocusDistanceDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getFocusMeteringMode(): Promise<FocusMeteringMode | null> { return (await this.getFocusMeteringModeDesc()).value } public async setFocusMeteringMode( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: FocusMeteringMode ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getFocusMeteringModeDesc(): Promise< ConfigDesc<FocusMeteringMode> > { return createUnsupportedConfigDesc() } public async getFocusMode(): Promise<FocusMode | null> { return (await this.getFocusModeDesc()).value } public async setFocusMode( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: FocusMode ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getFocusModeDesc(): Promise<ConfigDesc<FocusMode>> { return createUnsupportedConfigDesc() } public async getFunctionalMode(): Promise<FunctionalMode | null> { return (await this.getFunctionalModeDesc()).value } public async setFunctionalMode( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: FunctionalMode ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getFunctionalModeDesc(): Promise<ConfigDesc<FunctionalMode>> { return createUnsupportedConfigDesc() } public async getImageAspect(): Promise<string | null> { return (await this.getImageAspectDesc()).value } public async setImageAspect( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getImageAspectDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getImageQuality(): Promise<string | null> { return (await this.getImageQualityDesc()).value } public async setImageQuality( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getImageQualityDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getImageSize(): Promise<string | null> { return (await this.getImageSizeDesc()).value } public async setImageSize( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getImageSizeDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getIso(): Promise<ISO | null> { return (await this.getIsoDesc()).value } public async setIso( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: ISO ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getIsoDesc(): Promise<ConfigDesc<ISO>> { return createUnsupportedConfigDesc() } public async getLiveviewEnabled(): Promise<boolean | null> { return (await this.getLiveviewEnabledDesc()).value } public async setLiveviewEnabled( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: boolean ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getLiveviewEnabledDesc(): Promise<ConfigDesc<boolean>> { return createUnsupportedConfigDesc() } public async getLiveviewMagnifyRatio(): Promise<number | null> { return (await this.getLiveviewMagnifyRatioDesc()).value } public async setLiveviewMagnifyRatio( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getLiveviewMagnifyRatioDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getLiveviewSize(): Promise<string | null> { return (await this.getLiveviewSizeDesc()).value } public async setLiveviewSize( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getLiveviewSizeDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getManualFocusOptions(): Promise<ManualFocusOption[] | null> { return (await this.getManualFocusOptionsDesc()).value } public async setManualFocusOptions( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: ManualFocusOption[] ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getManualFocusOptionsDesc(): Promise< ConfigDesc<ManualFocusOption[]> > { return createUnsupportedConfigDesc() } public async getManufacturer(): Promise<string | null> { return (await this.getManufacturerDesc()).value } public async setManufacturer( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getManufacturerDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getModel(): Promise<string | null> { return (await this.getModelDesc()).value } public async setModel( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getModelDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getSharpness(): Promise<number | null> { return (await this.getSharpnessDesc()).value } public async setSharpness( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getSharpnessDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getShutterSpeed(): Promise<string | null> { return (await this.getShutterSpeedDesc()).value } public async setShutterSpeed( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: string ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getShutterSpeedDesc(): Promise<ConfigDesc<string>> { return createUnsupportedConfigDesc() } public async getTimelapseInterval(): Promise<number | null> { return (await this.getTimelapseIntervalDesc()).value } public async setTimelapseInterval( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getTimelapseIntervalDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getTimelapseNumber(): Promise<number | null> { return (await this.getTimelapseNumberDesc()).value } public async setTimelapseNumber( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: number ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getTimelapseNumberDesc(): Promise<ConfigDesc<number>> { return createUnsupportedConfigDesc() } public async getWhiteBalance(): Promise<WhiteBalance | null> { return (await this.getWhiteBalanceDesc()).value } public async setWhiteBalance( // eslint-disable-next-line @typescript-eslint/no-unused-vars value: WhiteBalance ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async getWhiteBalanceDesc(): Promise<ConfigDesc<WhiteBalance>> { return createUnsupportedConfigDesc() } // Actions public async runAutoFocus(): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async runManualFocus( // eslint-disable-next-line @typescript-eslint/no-unused-vars option: ManualFocusOption ): Promise<OperationResult<void>> { return {status: 'unsupported'} } public async takePhoto( // eslint-disable-next-line @typescript-eslint/no-unused-vars option?: TakePhotoOption ): Promise<OperationResult<TethrObject[]>> { return {status: 'unsupported'} } public async startLiveview(): Promise<OperationResult<MediaStream>> { return {status: 'unsupported'} } public async stopLiveview(): Promise<OperationResult<void>> { return {status: 'unsupported'} } }
the_stack
import Aside, {AsideSection} from '~/components/Aside'; import type { Dimension, LabelMetadata, PCAResult, ParseParams, ParseResult, Reduction, Shape, TSNEResult, UMAPResult } from '~/resource/high-dimensional'; import HighDimensionalChart, {HighDimensionalChartRef} from '~/components/HighDimensionalPage/HighDimensionalChart'; import LabelSearchInput, {LabelSearchInputProps} from '~/components/HighDimensionalPage/LabelSearchInput'; import React, {FunctionComponent, useCallback, useEffect, useMemo, useRef, useState} from 'react'; import type {SelectListItem, SelectProps} from '~/components/Select'; import type {BlobResponse} from '~/utils/fetch'; import BodyLoading from '~/components/BodyLoading'; import Button from '~/components/Button'; import Content from '~/components/Content'; import DimensionSwitch from '~/components/HighDimensionalPage/DimensionSwitch'; import Error from '~/components/Error'; import Field from '~/components/Field'; import LabelSearchResult from '~/components/HighDimensionalPage/LabelSearchResult'; import {LabelType} from '~/resource/high-dimensional'; import PCADetail from '~/components/HighDimensionalPage/PCADetail'; import ReductionTab from '~/components/HighDimensionalPage/ReductionTab'; import ScatterChart from '~/components/ScatterChart/ScatterChart'; import Select from '~/components/Select'; import TSNEDetail from '~/components/HighDimensionalPage/TSNEDetail'; import Title from '~/components/Title'; import UMAPDetail from '~/components/HighDimensionalPage/UMAPDetail'; import UploadDialog from '~/components/HighDimensionalPage/UploadDialog'; import queryString from 'query-string'; import {rem} from '~/utils/style'; import styled from 'styled-components'; import {toast} from 'react-toastify'; import useRequest from '~/hooks/useRequest'; import {useTranslation} from 'react-i18next'; import useWorker from '~/hooks/useWorker'; const MODE = import.meta.env.MODE; const MAX_COUNT: Record<Reduction, number | undefined> = { pca: 50000, tsne: 10000, umap: 5000 } as const; const MAX_DIMENSION: Record<Reduction, number | undefined> = { pca: 200, tsne: undefined, umap: undefined }; const AsideTitle = styled.div` font-size: ${rem(16)}; line-height: ${rem(16)}; font-weight: 700; margin-bottom: ${rem(20)}; `; // styled-components cannot infer type of a component... // And I don't want to write a type guard // eslint-disable-next-line @typescript-eslint/no-explicit-any const FullWidthSelect = styled<React.FunctionComponent<SelectProps<any>>>(Select)` width: 100%; `; const FullWidthButton = styled(Button)` width: 100%; `; const HDAside = styled(Aside)` .secondary { color: var(--text-light-color); } `; const RightAside = styled(HDAside)` border-left: 1px solid var(--border-color); `; const LeftAside = styled(HDAside)` border-right: 1px solid var(--border-color); ${AsideSection} { border-bottom: none; } > .aside-top > .search-result { margin-top: 0; margin-left: 0; margin-right: 0; flex: auto; overflow: hidden auto; } `; const HDContent = styled(Content)` background-color: var(--background-color); `; type EmbeddingInfo = { name: string; shape: [number, number]; path?: string; }; const HighDimensional: FunctionComponent = () => { const {t} = useTranslation(['high-dimensional', 'common']); const chart = useRef<HighDimensionalChartRef>(null); const {data: list, loading: loadingList} = useRequest<EmbeddingInfo[]>('/embedding/list'); const embeddingList = useMemo( () => list?.map(item => ({value: item.name, label: item.name, ...item})) ?? [], [list] ); const [selectedEmbeddingName, setSelectedEmbeddingName] = useState<string>(); const selectedEmbedding = useMemo( () => embeddingList.find(embedding => embedding.value === selectedEmbeddingName), [embeddingList, selectedEmbeddingName] ); useEffect(() => { setSelectedEmbeddingName(embeddingList[0]?.value ?? undefined); }, [embeddingList]); const {data: tensorData, loading: loadingTensor} = useRequest<BlobResponse>( selectedEmbeddingName ? `/embedding/tensor?${queryString.stringify({name: selectedEmbeddingName})}` : null ); const {data: metadataData, loading: loadingMetadata} = useRequest<string>( selectedEmbeddingName ? `/embedding/metadata?${queryString.stringify({name: selectedEmbeddingName})}` : null ); const [uploadModal, setUploadModal] = useState(false); const [loading, setLoading] = useState(false); const [loadingPhase, setLoadingPhase] = useState(''); useEffect(() => { if (!loading) { setLoadingPhase(''); } }, [loading]); useEffect(() => { if (loadingPhase) { setLoading(true); } }, [loadingPhase]); useEffect(() => { if (loadingTensor) { setLoading(true); setLoadingPhase('fetching-tensor'); } }, [loadingTensor]); useEffect(() => { if (loadingMetadata) { setLoading(true); setLoadingPhase('fetching-metadata'); } }, [loadingMetadata]); const [vectorFile, setVectorFile] = useState<File | null>(null); const [metadataFile, setMetadataFile] = useState<File | null>(null); const changeVectorFile = useCallback((file: File) => { setVectorFile(file); setMetadataFile(null); }, []); const [vectorContent, setVectorContent] = useState(''); const [metadataContent, setMetadataContent] = useState(''); const [vectors, setVectors] = useState<Float32Array>(new Float32Array()); const [labelList, setLabelList] = useState<LabelMetadata[]>([]); const labelByList = useMemo<SelectListItem<number>[]>( () => labelList.map(({label}, index) => ({label, value: index})), [labelList] ); const [labelByIndex, setLabelByIndex] = useState<number>(0); const colorByList = useMemo<SelectListItem<number>[]>( () => [ { label: t('high-dimensional:no-color-map'), value: -1 }, ...labelList.map((item, index) => ({ label: item.label, value: index, disabled: item.type === LabelType.Null || (item.type === LabelType.Category && item.categories.length > ScatterChart.CATEGORY_COLOR_MAP.length) })) ], [labelList, t] ); const [colorByIndex, setColorByIndex] = useState<number>(-1); const [metadata, setMetadata] = useState<string[][]>([]); // dimension of data const [dim, setDim] = useState<number>(0); const [rawShape, setRawShape] = useState<Shape>([0, 0]); const selectedMetadata = useMemo(() => metadata[labelByIndex], [labelByIndex, metadata]); const selectedColor = useMemo( () => colorByIndex === -1 ? null : { ...labelList[colorByIndex], labels: metadata[colorByIndex] }, [colorByIndex, labelList, metadata] ); // dimension of display const [dimension, setDimension] = useState<Dimension>('3d'); const [reduction, setReduction] = useState<Reduction>('pca'); const is3D = useMemo(() => dimension === '3d', [dimension]); const readFile = useCallback( (phase: string, file: File | null, setter: React.Dispatch<React.SetStateAction<string>>) => { if (file) { setLoading(true); setLoadingPhase(phase); const reader = new FileReader(); reader.readAsText(file, 'utf-8'); reader.onload = () => { setter(content => { const result = reader.result as string; if (content === result) { setLoading(false); } return result; }); }; } else { setter(''); } }, [] ); useEffect(() => readFile('reading-vector', vectorFile, setVectorContent), [vectorFile, readFile]); useEffect(() => readFile('reading-metadata', metadataFile, setMetadataContent), [metadataFile, readFile]); useEffect(() => setVectorFile(null), [selectedEmbeddingName]); const showError = useCallback((e: Error) => { toast(e.message, { position: toast.POSITION.TOP_CENTER, type: toast.TYPE.ERROR }); if (MODE !== 'production') { // eslint-disable-next-line no-console console.error(e); } setLoading(false); }, []); const params = useMemo<ParseParams>(() => { const maxValues = { maxCount: MAX_COUNT[reduction], maxDimension: MAX_DIMENSION[reduction] }; if (vectorContent) { return { from: 'string', params: { vectors: vectorContent, metadata: metadataContent, ...maxValues } }; } if (selectedEmbedding && tensorData) { return { from: 'blob', params: { shape: selectedEmbedding.shape, vectors: tensorData.data, metadata: metadataData ?? '', ...maxValues } }; } return null; }, [reduction, vectorContent, selectedEmbedding, tensorData, metadataContent, metadataData]); const result = useWorker<ParseResult, ParseParams>('high-dimensional/parse-data', params); useEffect(() => { const {error, data} = result; if (error) { showError(error); } else if (data) { setRawShape(data.rawShape); setDim(data.dimension); setVectors(data.vectors); setLabelList(data.labels); setLabelByIndex(0); setColorByIndex(-1); setMetadata(data.metadata); } else if (data !== null) { setLoadingPhase('parsing'); } else { setLoading(false); setLoadingPhase(''); } }, [result, showError]); const hasVector = useMemo(() => dim !== 0, [dim]); const dataPath = useMemo( () => (vectorFile ? vectorFile.name : selectedEmbedding?.path ?? ''), [vectorFile, selectedEmbedding] ); const [perplexity, setPerplexity] = useState(5); const [learningRate, setLearningRate] = useState(10); const [neighbors, setNeighbors] = useState(15); const runUMAP = useCallback((n: number) => { setNeighbors(n); chart.current?.rerunUMAP(); }, []); const [data, setData] = useState<PCAResult | TSNEResult | UMAPResult>(); const calculate = useCallback(() => { setData(undefined); setLoadingPhase('calculating'); }, []); const calculated = useCallback((data: PCAResult | TSNEResult | UMAPResult) => { setData(data); setLoading(false); }, []); const [searchResult, setSearchResult] = useState<Parameters<NonNullable<LabelSearchInputProps['onChange']>>['0']>({ labelIndex: undefined, value: '' }); const searchedResult = useMemo(() => { if (searchResult.labelIndex == null || searchResult.value === '') { return { indices: [], metadata: [] }; } const metadataList = metadata[searchResult.labelIndex]; const metadataResult: string[] = []; const vectorsIndices: number[] = []; for (let i = 0; i < metadataList.length; i++) { if (metadataList[i].includes(searchResult.value)) { metadataResult.push(metadataList[i]); vectorsIndices.push(i); } } // const vectorsResult = new Float32Array(vectorsIndices.length * dim); // for (let i = 0; i < vectorsIndices.length; i++) { // vectorsResult.set(vectors.subarray(vectorsIndices[i] * dim, vectorsIndices[i] * dim + dim), i * dim); // } return { indices: vectorsIndices, metadata: metadataResult }; }, [metadata, searchResult.labelIndex, searchResult.value]); const [hoveredIndices, setHoveredIndices] = useState<number[]>([]); const hoverSearchResult = useCallback( (index?: number) => setHoveredIndices(index == null ? [] : [searchedResult.indices[index]]), [searchedResult.indices] ); const detail = useMemo(() => { switch (reduction) { case 'pca': return ( <PCADetail dimension={dimension} variance={(data as PCAResult)?.variance ?? []} totalVariance={(data as PCAResult)?.totalVariance ?? 0} /> ); case 'tsne': return ( <TSNEDetail iteration={(data as TSNEResult)?.step ?? 0} perplexity={perplexity} learningRate={learningRate} is3D={is3D} onChangePerplexity={setPerplexity} onChangeLearningRate={setLearningRate} onPause={chart.current?.pauseTSNE} onResume={chart.current?.resumeTSNE} onStop={chart.current?.pauseTSNE} onRerun={chart.current?.rerunTSNE} /> ); case 'umap': return <UMAPDetail neighbors={neighbors} onRun={runUMAP} />; default: return null as never; } }, [reduction, dimension, data, perplexity, learningRate, is3D, neighbors, runUMAP]); const aside = useMemo( () => ( <RightAside> <AsideSection> <AsideTitle>{t('high-dimensional:data')}</AsideTitle> <Field label={t('high-dimensional:select-data')}> <FullWidthSelect list={embeddingList} value={selectedEmbeddingName} onChange={setSelectedEmbeddingName} /> </Field> <Field label={t('high-dimensional:select-label')}> <FullWidthSelect list={labelByList} value={labelByIndex} onChange={setLabelByIndex} /> </Field> <Field label={t('high-dimensional:select-color')}> <FullWidthSelect list={colorByList} value={colorByIndex} onChange={setColorByIndex} /> </Field> <Field> <FullWidthButton rounded outline type="primary" onClick={() => setUploadModal(true)}> {t('high-dimensional:upload-data')} </FullWidthButton> </Field> <Field> {dataPath && ( <div className="secondary"> {t('high-dimensional:data-path')} {t('common:colon')} {dataPath} </div> )} </Field> </AsideSection> <AsideSection> <Field> <ReductionTab value={reduction} onChange={setReduction} /> </Field> <Field label={t('high-dimensional:dimension')}> <DimensionSwitch value={dimension} onChange={setDimension} /> </Field> {detail} </AsideSection> </RightAside> ), [ t, embeddingList, selectedEmbeddingName, labelByList, labelByIndex, colorByList, colorByIndex, dataPath, reduction, dimension, detail ] ); const leftAside = useMemo( () => ( <LeftAside> <AsideSection> <Field> <LabelSearchInput labels={labelByList} onChange={setSearchResult} /> </Field> {searchResult.value !== '' && ( <Field className="secondary"> <span> {t('high-dimensional:matched-result-count', { count: searchedResult.metadata.length })} </span> </Field> )} </AsideSection> <AsideSection className="search-result"> <Field> <LabelSearchResult list={searchedResult.metadata} onHovered={hoverSearchResult} /> </Field> </AsideSection> </LeftAside> ), [hoverSearchResult, labelByList, searchResult.value, searchedResult.metadata, t] ); return ( <> <Title>{t('common:high-dimensional')}</Title> {loading || loadingList ? <BodyLoading>{t(`high-dimensional:loading.${loadingPhase}`)}</BodyLoading> : null} <HDContent aside={aside} leftAside={leftAside}> {hasVector ? ( <HighDimensionalChart ref={chart} vectors={vectors} labels={selectedMetadata} colorMap={selectedColor} shape={rawShape} dim={dim} is3D={is3D} reduction={reduction} perplexity={perplexity} learningRate={learningRate} neighbors={neighbors} focusedIndices={hoveredIndices} highlightIndices={searchedResult.indices} onCalculate={calculate} onCalculated={calculated} onError={showError} /> ) : ( <Error /> )} <UploadDialog open={uploadModal} hasVector={hasVector} onClose={() => setUploadModal(false)} onChangeVectorFile={changeVectorFile} onChangeMetadataFile={setMetadataFile} /> </HDContent> </> ); }; export default HighDimensional;
the_stack
import { ArrayUtils, errors, EventContainer, FileUtils, LanguageVariant, libFolderInMemoryPath, Memoize, ScriptKind, ScriptTarget, StandardizedFilePath, StringUtils, ts, } from "@ts-morph/common"; import { Directory } from "../../../fileSystem"; import { getTextFromTextChanges, insertIntoTextRange, replaceNodeText, replaceSourceFileForFilePathMove, replaceSourceFileTextForFormatting, } from "../../../manipulation"; import { getNextMatchingPos, getPreviousMatchingPos } from "../../../manipulation/textSeek"; import { ProjectContext } from "../../../ProjectContext"; import { SourceFileSpecificStructure, SourceFileStructure, StructureKind } from "../../../structures"; import { Constructor } from "../../../types"; import { CharCodes, ModuleUtils, SourceFileReferenceContainer, SourceFileReferencingNodes } from "../../../utils"; import { Diagnostic, EmitOptionsBase, EmitOutput, EmitResult, FormatCodeSettings, TextChange, UserPreferences } from "../../tools"; import { ModuledNode, TextInsertableNode } from "../base"; import { callBaseGetStructure } from "../callBaseGetStructure"; import { callBaseSet } from "../callBaseSet"; import { Node, TextRange } from "../common"; import { StringLiteral } from "../literal"; import { StatementedNode } from "../statement"; import { FileReference, FileSystemRefreshResult } from "./results"; export interface SourceFileCopyOptions { overwrite?: boolean; } export interface SourceFileMoveOptions { overwrite?: boolean; } /** * Options for emitting a source file. */ export interface SourceFileEmitOptions extends EmitOptionsBase { } /** @internal */ export interface SourceFileReferences { literalReferences: [StringLiteral, SourceFile][]; referencingLiterals: StringLiteral[]; } // todo: not sure why I need to explicitly type this in order to get TS to not complain... (TS 2.4.1) export const SourceFileBase: Constructor<ModuledNode> & Constructor<StatementedNode> & Constructor<TextInsertableNode> & typeof Node = ModuledNode( TextInsertableNode(StatementedNode(Node)), ); export class SourceFile extends SourceFileBase<ts.SourceFile> { /** @internal */ private _isSaved = false; /** @internal */ private readonly _modifiedEventContainer = new EventContainer<SourceFile>(); /** @internal */ private readonly _preModifiedEventContainer = new EventContainer<SourceFile>(); /** @internal */ readonly _referenceContainer = new SourceFileReferenceContainer(this); /** @internal */ private _referencedFiles: FileReference[] | undefined; /** @internal */ private _libReferenceDirectives: FileReference[] | undefined; /** @internal */ private _typeReferenceDirectives: FileReference[] | undefined; /** @internal */ _hasBom: true | undefined; /** * Initializes a new instance. * @private * @param context - Project context. * @param node - Underlying node. */ constructor( context: ProjectContext, node: ts.SourceFile, ) { super(context, node, undefined); // typescript doesn't allow calling `super` with `this`, so set this after this.__sourceFile = this; // store this before a modification happens to the file const onPreModified = () => { this.isFromExternalLibrary(); // memoize this._preModifiedEventContainer.unsubscribe(onPreModified); }; this._preModifiedEventContainer.subscribe(onPreModified); } /** * @internal * * WARNING: This should only be called by the compiler factory! */ _replaceCompilerNodeFromFactory(compilerNode: ts.SourceFile) { super._replaceCompilerNodeFromFactory(compilerNode); this._context.resetProgram(); // make sure the program has the latest source file this._isSaved = false; this._modifiedEventContainer.fire(this); } /** @internal */ protected _clearInternals() { super._clearInternals(); clearTextRanges(this._referencedFiles); clearTextRanges(this._typeReferenceDirectives); clearTextRanges(this._libReferenceDirectives); delete this._referencedFiles; delete this._typeReferenceDirectives; delete this._libReferenceDirectives; function clearTextRanges(textRanges: ReadonlyArray<TextRange> | undefined) { textRanges?.forEach(r => r._forget()); } } /** * Gets the file path. */ getFilePath() { return this.compilerNode.fileName as StandardizedFilePath; } /** * Gets the file path's base name. */ getBaseName() { return FileUtils.getBaseName(this.getFilePath()); } /** * Gets the file path's base name without the extension. */ getBaseNameWithoutExtension() { const baseName = this.getBaseName(); const extension = this.getExtension(); return baseName.substring(0, baseName.length - extension.length); } /** * Gets the file path's extension. */ getExtension() { return FileUtils.getExtension(this.getFilePath()); } /** * Gets the directory that the source file is contained in. */ getDirectory(): Directory { return this._context.compilerFactory.getDirectoryFromCache(this.getDirectoryPath())!; } /** * Gets the directory path that the source file is contained in. */ getDirectoryPath(): StandardizedFilePath { return this._context.fileSystemWrapper.getStandardizedAbsolutePath(FileUtils.getDirPath(this.compilerNode.fileName)); } /** * Gets the full text with leading trivia. */ getFullText() { // return the string instead of letting Node.getFullText() do a substring to prevent an extra allocation return this.compilerNode.text; } /** * Gets the line and column number at the provided position (1-indexed). * @param pos - Position in the source file. */ getLineAndColumnAtPos(pos: number) { const fullText = this.getFullText(); return { line: StringUtils.getLineNumberAtPos(fullText, pos), column: StringUtils.getLengthFromLineStartAtPos(fullText, pos) + 1, }; } /** * Gets the character count from the start of the line to the provided position. * @param pos - Position. */ getLengthFromLineStartAtPos(pos: number) { return StringUtils.getLengthFromLineStartAtPos(this.getFullText(), pos); } /** * Copies this source file to the specified directory. * * This will modify the module specifiers in the new file, if necessary. * @param dirPathOrDirectory Directory path or directory object to copy the file to. * @param options Options for copying. * @returns The source file the copy was made to. */ copyToDirectory(dirPathOrDirectory: string | Directory, options?: SourceFileCopyOptions) { const dirPath = typeof dirPathOrDirectory === "string" ? dirPathOrDirectory : dirPathOrDirectory.getPath(); return this.copy(FileUtils.pathJoin(dirPath, this.getBaseName()), options); } /** * Copy this source file to a new file. * * This will modify the module specifiers in the new file, if necessary. * @param filePath - New file path. Can be relative to the original file or an absolute path. * @param options - Options for copying. */ copy(filePath: string, options: SourceFileCopyOptions = {}): SourceFile { this._throwIfIsInMemoryLibFile(); const result = this._copyInternal(filePath, options); if (result === false) return this; const copiedSourceFile = result; if (copiedSourceFile.getDirectoryPath() !== this.getDirectoryPath()) copiedSourceFile._updateReferencesForCopyInternal(this._getReferencesForCopyInternal()); return copiedSourceFile; } /** @internal */ _copyInternal(fileAbsoluteOrRelativePath: string, options: SourceFileCopyOptions = {}) { const { overwrite = false } = options; const { compilerFactory, fileSystemWrapper } = this._context; const standardizedFilePath = fileSystemWrapper.getStandardizedAbsolutePath(fileAbsoluteOrRelativePath, this.getDirectoryPath()); if (standardizedFilePath === this.getFilePath()) return false; return getCopiedSourceFile(this); function getCopiedSourceFile(currentFile: SourceFile) { try { return compilerFactory.createSourceFileFromText(standardizedFilePath, currentFile.getFullText(), { overwrite, markInProject: getShouldBeInProject() }); } catch (err) { if (err instanceof errors.InvalidOperationError) throw new errors.InvalidOperationError(`Did you mean to provide the overwrite option? ` + err.message); else throw err; } function getShouldBeInProject() { if (currentFile._isInProject()) return true; const destinationFile = compilerFactory.getSourceFileFromCacheFromFilePath(standardizedFilePath); return destinationFile != null && destinationFile._isInProject(); } } } /** @internal */ _getReferencesForCopyInternal(): [StringLiteral, SourceFile][] { return Array.from(this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries()); } /** @internal */ _updateReferencesForCopyInternal(literalReferences: ReadonlyArray<[StringLiteral, SourceFile]>) { // update the nodes in this list to point to the nodes in this copied source file for (const reference of literalReferences) reference[0] = this.getChildSyntaxListOrThrow().getDescendantAtStartWithWidth(reference[0].getStart(), reference[0].getWidth())! as StringLiteral; // update the string literals in the copied file updateStringLiteralReferences(literalReferences); } /** * Copy this source file to a new file and immediately saves it to the file system asynchronously. * * This will modify the module specifiers in the new file, if necessary. * @param filePath - New file path. Can be relative to the original file or an absolute path. * @param options - Options for copying. */ async copyImmediately(filePath: string, options?: SourceFileCopyOptions): Promise<SourceFile> { const newSourceFile = this.copy(filePath, options); await newSourceFile.save(); return newSourceFile; } /** * Copy this source file to a new file and immediately saves it to the file system synchronously. * * This will modify the module specifiers in the new file, if necessary. * @param filePath - New file path. Can be relative to the original file or an absolute path. * @param options - Options for copying. */ copyImmediatelySync(filePath: string, options?: SourceFileCopyOptions): SourceFile { const newSourceFile = this.copy(filePath, options); newSourceFile.saveSync(); return newSourceFile; } /** * Moves this source file to the specified directory. * * This will modify the module specifiers in other files that specify this file and the module specifiers in the current file, if necessary. * @param dirPathOrDirectory Directory path or directory object to move the file to. * @param options Options for moving. */ moveToDirectory(dirPathOrDirectory: string | Directory, options?: SourceFileMoveOptions) { const dirPath = typeof dirPathOrDirectory === "string" ? dirPathOrDirectory : dirPathOrDirectory.getPath(); return this.move(FileUtils.pathJoin(dirPath, this.getBaseName()), options); } /** * Moves this source file to a new file. * * This will modify the module specifiers in other files that specify this file and the module specifiers in the current file, if necessary. * @param filePath - New file path. Can be relative to the original file or an absolute path. * @param options - Options for moving. */ move(filePath: string, options: SourceFileMoveOptions = {}): SourceFile { this._throwIfIsInMemoryLibFile(); const oldDirPath = this.getDirectoryPath(); const sourceFileReferences = this._getReferencesForMoveInternal(); const oldFilePath = this.getFilePath(); if (!this._moveInternal(filePath, options)) return this; this._context.fileSystemWrapper.queueFileDelete(oldFilePath); this._updateReferencesForMoveInternal(sourceFileReferences, oldDirPath); // ignore any modifications in other source files this._context.lazyReferenceCoordinator.clearDirtySourceFiles(); // need to add the current source file as being dirty because it was removed and added to the cache in the move this._context.lazyReferenceCoordinator.addDirtySourceFile(this); return this; } /** @internal */ _moveInternal(fileRelativeOrAbsolutePath: string, options: SourceFileMoveOptions = {}) { const { overwrite = false } = options; const filePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(fileRelativeOrAbsolutePath, this.getDirectoryPath()); if (filePath === this.getFilePath()) return false; let markAsInProject = false; if (overwrite) { // remove the past file if it exists const existingSourceFile = this._context.compilerFactory.getSourceFileFromCacheFromFilePath(filePath); if (existingSourceFile != null) { markAsInProject = existingSourceFile._isInProject(); existingSourceFile.forget(); } } else { this._context.compilerFactory.throwIfFileExists(filePath, "Did you mean to provide the overwrite option?"); } replaceSourceFileForFilePathMove({ newFilePath: filePath, sourceFile: this, }); if (markAsInProject) this._markAsInProject(); if (this._isInProject()) this.getDirectory()._markAsInProject(); return true; } /** @internal */ _getReferencesForMoveInternal(): SourceFileReferences { return { literalReferences: Array.from(this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries()), referencingLiterals: Array.from(this._referenceContainer.getReferencingLiteralsInOtherSourceFiles()), }; } /** @internal */ _updateReferencesForMoveInternal(sourceFileReferences: SourceFileReferences, oldDirPath: string) { const { literalReferences, referencingLiterals } = sourceFileReferences; // update the literals in this file if the directory has changed if (oldDirPath !== this.getDirectoryPath()) updateStringLiteralReferences(literalReferences); // update the string literals in other files updateStringLiteralReferences(referencingLiterals.map(node => [node, this] as [StringLiteral, SourceFile])); } /** * Moves this source file to a new file and asynchronously updates the file system immediately. * * This will modify the module specifiers in other files that specify this file and the module specifiers in the current file, if necessary. * @param filePath - New file path. Can be relative to the original file or an absolute path. * @param options - Options for moving. */ async moveImmediately(filePath: string, options?: SourceFileMoveOptions): Promise<SourceFile> { const oldFilePath = this.getFilePath(); const newFilePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(filePath, this.getDirectoryPath()); this.move(filePath, options); if (oldFilePath !== newFilePath) { await this._context.fileSystemWrapper.moveFileImmediately(oldFilePath, newFilePath, this.getFullText()); this._isSaved = true; } else { await this.save(); } return this; } /** * Moves this source file to a new file and synchronously updates the file system immediately. * * This will modify the module specifiers in other files that specify this file and the module specifiers in the current file, if necessary. * @param filePath - New file path. Can be relative to the original file or an absolute path. * @param options - Options for moving. */ moveImmediatelySync(filePath: string, options?: SourceFileMoveOptions): SourceFile { const oldFilePath = this.getFilePath(); const newFilePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(filePath, this.getDirectoryPath()); this.move(filePath, options); if (oldFilePath !== newFilePath) { this._context.fileSystemWrapper.moveFileImmediatelySync(oldFilePath, newFilePath, this.getFullText()); this._isSaved = true; } else { this.saveSync(); } return this; } /** * Queues a deletion of the file to the file system. * * The file will be deleted when you call ast.save(). If you wish to immediately delete the file, then use deleteImmediately(). */ delete() { this._throwIfIsInMemoryLibFile(); const filePath = this.getFilePath(); this.forget(); this._context.fileSystemWrapper.queueFileDelete(filePath); } /** * Asynchronously deletes the file from the file system. */ async deleteImmediately() { this._throwIfIsInMemoryLibFile(); const filePath = this.getFilePath(); this.forget(); await this._context.fileSystemWrapper.deleteFileImmediately(filePath); } /** * Synchronously deletes the file from the file system. */ deleteImmediatelySync() { this._throwIfIsInMemoryLibFile(); const filePath = this.getFilePath(); this.forget(); this._context.fileSystemWrapper.deleteFileImmediatelySync(filePath); } /** * Asynchronously saves this file with any changes. */ async save() { if (this._isLibFileInMemory()) return; await this._context.fileSystemWrapper.writeFile(this.getFilePath(), this._getTextForSave()); this._isSaved = true; } /** * Synchronously saves this file with any changes. */ saveSync() { if (this._isLibFileInMemory()) return; this._context.fileSystemWrapper.writeFileSync(this.getFilePath(), this._getTextForSave()); this._isSaved = true; } /** @internal */ private _getTextForSave() { const text = this.getFullText(); return this._hasBom ? "\uFEFF" + text : text; } /** * Gets any `/// <reference path="..." />` comments. */ getPathReferenceDirectives() { if (this._referencedFiles == null) { this._referencedFiles = (this.compilerNode.referencedFiles || []) .map(f => new FileReference(f, this)); } return this._referencedFiles; } /** * Gets any `/// <reference types="..." />` comments. */ getTypeReferenceDirectives() { if (this._typeReferenceDirectives == null) { this._typeReferenceDirectives = (this.compilerNode.typeReferenceDirectives || []) .map(f => new FileReference(f, this)); } return this._typeReferenceDirectives; } /** * Gets any `/// <reference lib="..." />` comments. */ getLibReferenceDirectives() { if (this._libReferenceDirectives == null) { this._libReferenceDirectives = (this.compilerNode.libReferenceDirectives || []) .map(f => new FileReference(f, this)); } return this._libReferenceDirectives; } /** * Gets any source files that reference this source file. */ getReferencingSourceFiles() { return Array.from(this._referenceContainer.getDependentSourceFiles()); } /** * Gets the import and exports in other source files that reference this source file. */ getReferencingNodesInOtherSourceFiles() { const literals = this.getReferencingLiteralsInOtherSourceFiles(); return Array.from(getNodes()); function* getNodes(): Iterable<SourceFileReferencingNodes> { for (const literal of literals) yield getReferencingNodeFromStringLiteral(literal); } } /** * Gets the string literals in other source files that reference this source file. */ getReferencingLiteralsInOtherSourceFiles() { return Array.from(this._referenceContainer.getReferencingLiteralsInOtherSourceFiles()); } /** * Gets the source files this source file references in string literals. */ getReferencedSourceFiles() { const entries = this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries(); return Array.from(new Set<SourceFile>(getSourceFilesFromEntries()).values()); function* getSourceFilesFromEntries(): Iterable<SourceFile> { for (const [, sourceFile] of entries) yield sourceFile; } } /** * Gets the nodes that reference other source files in string literals. */ getNodesReferencingOtherSourceFiles() { const entries = this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries(); return Array.from(getNodes()); function* getNodes(): Iterable<SourceFileReferencingNodes> { for (const [literal] of entries) yield getReferencingNodeFromStringLiteral(literal); } } /** * Gets the string literals in this source file that references other source files. * @remarks This is similar to `getImportStringLiterals()`, but `getImportStringLiterals()` * will return import string literals that may not be referencing another source file * or have not been able to be resolved. */ getLiteralsReferencingOtherSourceFiles() { const entries = this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries(); return Array.from(getLiteralsFromEntries()); function* getLiteralsFromEntries(): Iterable<StringLiteral> { for (const [literal] of entries) yield literal; } } /** * Gets all the descendant string literals that reference a module. */ getImportStringLiterals() { this._ensureBound(); const literals = ((this.compilerNode as any).imports || []) as ts.StringLiteral[]; // exclude import helpers return literals.filter(l => l.pos !== -1).map(l => this._getNodeFromCompilerNode(l)); } /** * Gets the script target of the source file. */ getLanguageVersion(): ScriptTarget { return this.compilerNode.languageVersion; } /** * Gets the language variant of the source file. */ getLanguageVariant(): LanguageVariant { return this.compilerNode.languageVariant; } /** * Gets the script kind of the source file. */ getScriptKind(): ScriptKind { // todo: open issue on typescript repo about making this not internal? // otherwise, store a collection of what each source file should be. return (this.compilerNode as any).scriptKind; } /** * Gets if this is a declaration file. */ isDeclarationFile() { return this.compilerNode.isDeclarationFile; } /** * Gets if the source file was discovered while loading an external library. */ @Memoize isFromExternalLibrary() { // This needs to be memoized and stored before modification because the TypeScript // compiler does the following code: // // function isSourceFileFromExternalLibrary(file: SourceFile): boolean { // return !!sourceFilesFoundSearchingNodeModules.get(file.path); // } // // So the compiler node will become out of date after a manipulation occurs and // this will return false. // do not create the program if not created before... if the program is // not created then we know this source file wasn't discovered by the program if (!this._context.program._isCompilerProgramCreated()) return false; const compilerProgram = this._context.program.compilerObject; return compilerProgram.isSourceFileFromExternalLibrary(this.compilerNode); } /** * Gets if the source file is a descendant of a node_modules directory. */ isInNodeModules() { return this.getFilePath().indexOf("/node_modules/") >= 0; } /** * Gets if this source file has been saved or if the latest changes have been saved. */ isSaved() { return this._isSaved && !this._isLibFileInMemory(); } /** * Sets if this source file has been saved. * @internal */ _setIsSaved(value: boolean) { this._isSaved = value; } /** * Gets the pre-emit diagnostics of the specified source file. */ getPreEmitDiagnostics(): Diagnostic[] { return this._context.getPreEmitDiagnostics(this); } /** * Deindents the line at the specified position. * @param pos - Position. * @param times - Times to unindent. Specify a negative value to indent. */ unindent(pos: number, times?: number): this; /** * Deindents the lines within the specified range. * @param positionRange - Position range. * @param times - Times to unindent. Specify a negative value to indent. */ unindent(positionRange: [number, number], times?: number): this; /** * @internal */ unindent(positionRangeOrPos: [number, number] | number, times?: number): this; unindent(positionRangeOrPos: [number, number] | number, times = 1) { return this.indent(positionRangeOrPos, times * -1); } /** * Indents the line at the specified position. * @param pos - Position. * @param times - Times to indent. Specify a negative value to unindent. */ indent(pos: number, times?: number): this; /** * Indents the lines within the specified range. * @param positionRange - Position range. * @param times - Times to indent. Specify a negative value to unindent. */ indent(positionRange: [number, number], times?: number): this; /** * @internal */ indent(positionRangeOrPos: [number, number] | number, times?: number): this; indent(positionRangeOrPos: [number, number] | number, times = 1) { if (times === 0) return this; const sourceFileText = this.getFullText(); const positionRange = typeof positionRangeOrPos === "number" ? [positionRangeOrPos, positionRangeOrPos] as [number, number] : positionRangeOrPos; errors.throwIfRangeOutOfRange(positionRange, [0, sourceFileText.length], "positionRange"); const startLinePos = getPreviousMatchingPos(sourceFileText, positionRange[0], char => char === CharCodes.NEWLINE); const endLinePos = getNextMatchingPos(sourceFileText, positionRange[1], char => char === CharCodes.CARRIAGE_RETURN || char === CharCodes.NEWLINE); const correctedText = StringUtils.indent(sourceFileText.substring(startLinePos, endLinePos), times, { indentText: this._context.manipulationSettings.getIndentationText(), indentSizeInSpaces: this._context.manipulationSettings._getIndentSizeInSpaces(), isInStringAtPos: pos => this.isInStringAtPos(pos + startLinePos), }); replaceSourceFileTextForFormatting({ sourceFile: this, newText: sourceFileText.substring(0, startLinePos) + correctedText + sourceFileText.substring(endLinePos), }); return this; } /** * Asynchronously emits the source file as a JavaScript file. */ emit(options?: SourceFileEmitOptions): Promise<EmitResult> { return this._context.program.emit({ targetSourceFile: this, ...options }); } /** * Synchronously emits the source file as a JavaScript file. */ emitSync(options?: SourceFileEmitOptions): EmitResult { return this._context.program.emitSync({ targetSourceFile: this, ...options }); } /** * Gets the emit output of this source file. * @param options - Emit options. */ getEmitOutput(options: { emitOnlyDtsFiles?: boolean } = {}): EmitOutput { return this._context.languageService.getEmitOutput(this, options.emitOnlyDtsFiles || false); } /** * Formats the source file text using the internal TypeScript formatting API. * @param settings - Format code settings. */ formatText(settings: FormatCodeSettings = {}) { replaceSourceFileTextForFormatting({ sourceFile: this, newText: this._context.languageService.getFormattedDocumentText(this.getFilePath(), settings), }); } /** * Refresh the source file from the file system. * * WARNING: When updating from the file system, this will "forget" any previously navigated nodes. * @returns What action ended up taking place. */ async refreshFromFileSystem(): Promise<FileSystemRefreshResult> { const fileReadResult = await this._context.fileSystemWrapper.readFileOrNotExists(this.getFilePath(), this._context.getEncoding()); return this._refreshFromFileSystemInternal(fileReadResult); } /** * Synchronously refreshes the source file from the file system. * * WARNING: When updating from the file system, this will "forget" any previously navigated nodes. * @returns What action ended up taking place. */ refreshFromFileSystemSync(): FileSystemRefreshResult { const fileReadResult = this._context.fileSystemWrapper.readFileOrNotExistsSync(this.getFilePath(), this._context.getEncoding()); return this._refreshFromFileSystemInternal(fileReadResult); } /** * Gets the relative path to the specified path. * @param fileOrDirPath - The file or directory path. */ getRelativePathTo(fileOrDirPath: string): string; /** * Gets the relative path to another source file. * @param sourceFile - Source file. */ getRelativePathTo(sourceFile: SourceFile): string; /** * Gets the relative path to another directory. * @param directory - Directory. */ getRelativePathTo(directory: Directory): string; getRelativePathTo(sourceFileDirOrPath: SourceFile | Directory | string) { return this.getDirectory().getRelativePathTo(sourceFileDirOrPath); } /** * Gets the relative path to the specified file path as a module specifier. * @param filePath - File path. * @remarks To get to a directory, provide `path/to/directory/index.ts`. */ getRelativePathAsModuleSpecifierTo(filePath: string): string; /** * Gets the relative path to the specified source file as a module specifier. * @param sourceFile - Source file. */ getRelativePathAsModuleSpecifierTo(sourceFile: SourceFile): string; /** * Gets the relative path to the specified directory as a module specifier. * @param directory - Directory. */ getRelativePathAsModuleSpecifierTo(directory: Directory): string; getRelativePathAsModuleSpecifierTo(sourceFileDirOrFilePath: SourceFile | Directory | string) { return this.getDirectory().getRelativePathAsModuleSpecifierTo(sourceFileDirOrFilePath); } /** * Subscribe to when the source file is modified. * @param subscription - Subscription. * @param subscribe - Optional and defaults to true. Use an explicit false to unsubscribe. */ onModified(subscription: (sender: SourceFile) => void, subscribe = true) { if (subscribe) this._modifiedEventContainer.subscribe(subscription); else this._modifiedEventContainer.unsubscribe(subscription); return this; } /** * Do an action the next time the source file is modified. * @param action - Action to run. * @internal */ _doActionPreNextModification(action: () => void) { const wrappedSubscription = () => { action(); this._preModifiedEventContainer.unsubscribe(wrappedSubscription); }; this._preModifiedEventContainer.subscribe(wrappedSubscription); return this; } /** @internal */ _firePreModified() { this._preModifiedEventContainer.fire(this); } /** * Organizes the imports in the file. * * WARNING! This will forget all the nodes in the file! It's best to do this after you're all done with the file. * @param formatSettings - Format code settings. * @param userPreferences - User preferences for refactoring. */ organizeImports(formatSettings: FormatCodeSettings = {}, userPreferences: UserPreferences = {}) { this._context.languageService.organizeImports(this, formatSettings, userPreferences).forEach(fileTextChanges => fileTextChanges.applyChanges()); return this; } /** * Removes all unused declarations like interfaces, classes, enums, functions, variables, parameters, * methods, properties, imports, etc. from this file. * * Tip: For optimal results, sometimes this method needs to be called more than once. There could be nodes * that are only referenced in unused declarations and in this case, another call will also remove them. * * WARNING! This will forget all the nodes in the file! It's best to do this after you're all done with the file. * @param formatSettings - Format code settings. * @param userPreferences - User preferences for refactoring. */ fixUnusedIdentifiers(formatSettings: FormatCodeSettings = {}, userPreferences: UserPreferences = {}) { this._context.languageService.getCombinedCodeFix(this, "unusedIdentifier_delete", formatSettings, userPreferences).applyChanges(); this._context.languageService.getCombinedCodeFix(this, "unusedIdentifier_deleteImports", formatSettings, userPreferences).applyChanges(); return this; } /** * Code fix to add import declarations for identifiers that are referenced, but not imported in the source file. * @param formatSettings - Format code settings. * @param userPreferences - User preferences for refactoring. */ fixMissingImports(formatSettings: FormatCodeSettings = {}, userPreferences: UserPreferences = {}) { const combinedCodeFix = this._context.languageService.getCombinedCodeFix(this, "fixMissingImport", formatSettings, userPreferences); const sourceFile = this; for (const fileTextChanges of combinedCodeFix.getChanges()) { const changes = fileTextChanges.getTextChanges(); removeUnnecessaryDoubleBlankLines(changes); applyTextChanges(changes); } return this; function removeUnnecessaryDoubleBlankLines(changes: TextChange[]) { changes.sort((a, b) => a.getSpan().getStart() - b.getSpan().getStart()); // when a file has no imports, it will add a double newline to every change // so remove them except for the last change for (let i = 0; i < changes.length - 1; i++) { // skip last change const { compilerObject } = changes[i]; compilerObject.newText = compilerObject.newText.replace(/(\r?)\n\r?\n$/, "$1\n"); } } function applyTextChanges(changes: ReadonlyArray<TextChange>) { // group all the changes by their start position and insert them into the file const groups = ArrayUtils.groupBy(changes, change => change.getSpan().getStart()); let addedLength = 0; for (const group of groups) { // these should all be import declarations so it should be safe const insertPos = group[0].getSpan().getStart() + addedLength; const newText = group.map(item => item.getNewText()).join(""); insertIntoTextRange({ sourceFile, insertPos, newText, }); addedLength += newText.length; } } } /** * Applies the text changes to the source file. * * WARNING! This will forget all the nodes in the file! It's best to do this after you're all done with the file. * @param textChanges - Text changes. */ applyTextChanges(textChanges: ReadonlyArray<ts.TextChange | TextChange>) { // do nothing if no changes if (textChanges.length === 0) return this; this.forgetDescendants(); replaceNodeText({ sourceFile: this._sourceFile, start: 0, replacingLength: this.getFullWidth(), newText: getTextFromTextChanges(this, textChanges), }); return this; } /** * Sets the node from a structure. * @param structure - Structure to set the node with. */ set(structure: Partial<SourceFileStructure>) { callBaseSet(SourceFileBase.prototype, this, structure); return this; } /** * Gets the structure equivalent to this node. */ getStructure(): SourceFileStructure { return callBaseGetStructure<SourceFileSpecificStructure>(SourceFileBase.prototype, this, { kind: StructureKind.SourceFile, }); } private _refreshFromFileSystemInternal(fileReadResult: string | false): FileSystemRefreshResult { if (fileReadResult === false) { this.forget(); return FileSystemRefreshResult.Deleted; } const fileText = fileReadResult; if (fileText === this.getFullText()) return FileSystemRefreshResult.NoChange; this.replaceText([0, this.getEnd()], fileText); this._setIsSaved(true); // saved when loaded from file system return FileSystemRefreshResult.Updated; } /** @internal */ _isLibFileInMemory() { return this.compilerNode.fileName.startsWith(libFolderInMemoryPath); } /** @internal */ _throwIfIsInMemoryLibFile() { if (this._isLibFileInMemory()) throw new errors.InvalidOperationError(`This operation is not permitted on an in memory lib folder file.`); } /** @internal */ _isInProject() { return this._context.inProjectCoordinator.isSourceFileInProject(this); } /** @internal */ _markAsInProject() { this._context.inProjectCoordinator.markSourceFileAsInProject(this); } } function updateStringLiteralReferences(nodeReferences: ReadonlyArray<[StringLiteral, SourceFile]>) { for (const [stringLiteral, sourceFile] of nodeReferences) { if (ModuleUtils.isModuleSpecifierRelative(stringLiteral.getLiteralText())) stringLiteral.setLiteralValue(stringLiteral._sourceFile.getRelativePathAsModuleSpecifierTo(sourceFile)); } } function getReferencingNodeFromStringLiteral(literal: StringLiteral) { const parent = literal.getParentOrThrow(); const grandParent = parent.getParent(); if (grandParent != null && Node.isImportEqualsDeclaration(grandParent)) return grandParent; else return parent as SourceFileReferencingNodes; }
the_stack
import { Reader, Writer } from 'protobufjs/minimal' import { Coin } from '../../../cosmos/base/v1beta1/coin' export const protobufPackage = 'cosmos.distribution.v1beta1' /** * MsgSetWithdrawAddress sets the withdraw address for * a delegator (or validator self-delegation). */ export interface MsgSetWithdrawAddress { delegatorAddress: string withdrawAddress: string } /** MsgSetWithdrawAddressResponse defines the Msg/SetWithdrawAddress response type. */ export interface MsgSetWithdrawAddressResponse {} /** * MsgWithdrawDelegatorReward represents delegation withdrawal to a delegator * from a single validator. */ export interface MsgWithdrawDelegatorReward { delegatorAddress: string validatorAddress: string } /** MsgWithdrawDelegatorRewardResponse defines the Msg/WithdrawDelegatorReward response type. */ export interface MsgWithdrawDelegatorRewardResponse {} /** * MsgWithdrawValidatorCommission withdraws the full commission to the validator * address. */ export interface MsgWithdrawValidatorCommission { validatorAddress: string } /** MsgWithdrawValidatorCommissionResponse defines the Msg/WithdrawValidatorCommission response type. */ export interface MsgWithdrawValidatorCommissionResponse {} /** * MsgFundCommunityPool allows an account to directly * fund the community pool. */ export interface MsgFundCommunityPool { amount: Coin[] depositor: string } /** MsgFundCommunityPoolResponse defines the Msg/FundCommunityPool response type. */ export interface MsgFundCommunityPoolResponse {} const baseMsgSetWithdrawAddress: object = { delegatorAddress: '', withdrawAddress: '' } export const MsgSetWithdrawAddress = { encode( message: MsgSetWithdrawAddress, writer: Writer = Writer.create() ): Writer { if (message.delegatorAddress !== '') { writer.uint32(10).string(message.delegatorAddress) } if (message.withdrawAddress !== '') { writer.uint32(18).string(message.withdrawAddress) } return writer }, decode(input: Reader | Uint8Array, length?: number): MsgSetWithdrawAddress { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseMsgSetWithdrawAddress } as MsgSetWithdrawAddress while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.delegatorAddress = reader.string() break case 2: message.withdrawAddress = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): MsgSetWithdrawAddress { const message = { ...baseMsgSetWithdrawAddress } as MsgSetWithdrawAddress if ( object.delegatorAddress !== undefined && object.delegatorAddress !== null ) { message.delegatorAddress = String(object.delegatorAddress) } else { message.delegatorAddress = '' } if ( object.withdrawAddress !== undefined && object.withdrawAddress !== null ) { message.withdrawAddress = String(object.withdrawAddress) } else { message.withdrawAddress = '' } return message }, toJSON(message: MsgSetWithdrawAddress): unknown { const obj: any = {} message.delegatorAddress !== undefined && (obj.delegatorAddress = message.delegatorAddress) message.withdrawAddress !== undefined && (obj.withdrawAddress = message.withdrawAddress) return obj }, fromPartial( object: DeepPartial<MsgSetWithdrawAddress> ): MsgSetWithdrawAddress { const message = { ...baseMsgSetWithdrawAddress } as MsgSetWithdrawAddress if ( object.delegatorAddress !== undefined && object.delegatorAddress !== null ) { message.delegatorAddress = object.delegatorAddress } else { message.delegatorAddress = '' } if ( object.withdrawAddress !== undefined && object.withdrawAddress !== null ) { message.withdrawAddress = object.withdrawAddress } else { message.withdrawAddress = '' } return message } } const baseMsgSetWithdrawAddressResponse: object = {} export const MsgSetWithdrawAddressResponse = { encode( _: MsgSetWithdrawAddressResponse, writer: Writer = Writer.create() ): Writer { return writer }, decode( input: Reader | Uint8Array, length?: number ): MsgSetWithdrawAddressResponse { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseMsgSetWithdrawAddressResponse } as MsgSetWithdrawAddressResponse while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { default: reader.skipType(tag & 7) break } } return message }, fromJSON(_: any): MsgSetWithdrawAddressResponse { const message = { ...baseMsgSetWithdrawAddressResponse } as MsgSetWithdrawAddressResponse return message }, toJSON(_: MsgSetWithdrawAddressResponse): unknown { const obj: any = {} return obj }, fromPartial( _: DeepPartial<MsgSetWithdrawAddressResponse> ): MsgSetWithdrawAddressResponse { const message = { ...baseMsgSetWithdrawAddressResponse } as MsgSetWithdrawAddressResponse return message } } const baseMsgWithdrawDelegatorReward: object = { delegatorAddress: '', validatorAddress: '' } export const MsgWithdrawDelegatorReward = { encode( message: MsgWithdrawDelegatorReward, writer: Writer = Writer.create() ): Writer { if (message.delegatorAddress !== '') { writer.uint32(10).string(message.delegatorAddress) } if (message.validatorAddress !== '') { writer.uint32(18).string(message.validatorAddress) } return writer }, decode( input: Reader | Uint8Array, length?: number ): MsgWithdrawDelegatorReward { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseMsgWithdrawDelegatorReward } as MsgWithdrawDelegatorReward while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.delegatorAddress = reader.string() break case 2: message.validatorAddress = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): MsgWithdrawDelegatorReward { const message = { ...baseMsgWithdrawDelegatorReward } as MsgWithdrawDelegatorReward if ( object.delegatorAddress !== undefined && object.delegatorAddress !== null ) { message.delegatorAddress = String(object.delegatorAddress) } else { message.delegatorAddress = '' } if ( object.validatorAddress !== undefined && object.validatorAddress !== null ) { message.validatorAddress = String(object.validatorAddress) } else { message.validatorAddress = '' } return message }, toJSON(message: MsgWithdrawDelegatorReward): unknown { const obj: any = {} message.delegatorAddress !== undefined && (obj.delegatorAddress = message.delegatorAddress) message.validatorAddress !== undefined && (obj.validatorAddress = message.validatorAddress) return obj }, fromPartial( object: DeepPartial<MsgWithdrawDelegatorReward> ): MsgWithdrawDelegatorReward { const message = { ...baseMsgWithdrawDelegatorReward } as MsgWithdrawDelegatorReward if ( object.delegatorAddress !== undefined && object.delegatorAddress !== null ) { message.delegatorAddress = object.delegatorAddress } else { message.delegatorAddress = '' } if ( object.validatorAddress !== undefined && object.validatorAddress !== null ) { message.validatorAddress = object.validatorAddress } else { message.validatorAddress = '' } return message } } const baseMsgWithdrawDelegatorRewardResponse: object = {} export const MsgWithdrawDelegatorRewardResponse = { encode( _: MsgWithdrawDelegatorRewardResponse, writer: Writer = Writer.create() ): Writer { return writer }, decode( input: Reader | Uint8Array, length?: number ): MsgWithdrawDelegatorRewardResponse { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseMsgWithdrawDelegatorRewardResponse } as MsgWithdrawDelegatorRewardResponse while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { default: reader.skipType(tag & 7) break } } return message }, fromJSON(_: any): MsgWithdrawDelegatorRewardResponse { const message = { ...baseMsgWithdrawDelegatorRewardResponse } as MsgWithdrawDelegatorRewardResponse return message }, toJSON(_: MsgWithdrawDelegatorRewardResponse): unknown { const obj: any = {} return obj }, fromPartial( _: DeepPartial<MsgWithdrawDelegatorRewardResponse> ): MsgWithdrawDelegatorRewardResponse { const message = { ...baseMsgWithdrawDelegatorRewardResponse } as MsgWithdrawDelegatorRewardResponse return message } } const baseMsgWithdrawValidatorCommission: object = { validatorAddress: '' } export const MsgWithdrawValidatorCommission = { encode( message: MsgWithdrawValidatorCommission, writer: Writer = Writer.create() ): Writer { if (message.validatorAddress !== '') { writer.uint32(10).string(message.validatorAddress) } return writer }, decode( input: Reader | Uint8Array, length?: number ): MsgWithdrawValidatorCommission { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseMsgWithdrawValidatorCommission } as MsgWithdrawValidatorCommission while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.validatorAddress = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): MsgWithdrawValidatorCommission { const message = { ...baseMsgWithdrawValidatorCommission } as MsgWithdrawValidatorCommission if ( object.validatorAddress !== undefined && object.validatorAddress !== null ) { message.validatorAddress = String(object.validatorAddress) } else { message.validatorAddress = '' } return message }, toJSON(message: MsgWithdrawValidatorCommission): unknown { const obj: any = {} message.validatorAddress !== undefined && (obj.validatorAddress = message.validatorAddress) return obj }, fromPartial( object: DeepPartial<MsgWithdrawValidatorCommission> ): MsgWithdrawValidatorCommission { const message = { ...baseMsgWithdrawValidatorCommission } as MsgWithdrawValidatorCommission if ( object.validatorAddress !== undefined && object.validatorAddress !== null ) { message.validatorAddress = object.validatorAddress } else { message.validatorAddress = '' } return message } } const baseMsgWithdrawValidatorCommissionResponse: object = {} export const MsgWithdrawValidatorCommissionResponse = { encode( _: MsgWithdrawValidatorCommissionResponse, writer: Writer = Writer.create() ): Writer { return writer }, decode( input: Reader | Uint8Array, length?: number ): MsgWithdrawValidatorCommissionResponse { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseMsgWithdrawValidatorCommissionResponse } as MsgWithdrawValidatorCommissionResponse while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { default: reader.skipType(tag & 7) break } } return message }, fromJSON(_: any): MsgWithdrawValidatorCommissionResponse { const message = { ...baseMsgWithdrawValidatorCommissionResponse } as MsgWithdrawValidatorCommissionResponse return message }, toJSON(_: MsgWithdrawValidatorCommissionResponse): unknown { const obj: any = {} return obj }, fromPartial( _: DeepPartial<MsgWithdrawValidatorCommissionResponse> ): MsgWithdrawValidatorCommissionResponse { const message = { ...baseMsgWithdrawValidatorCommissionResponse } as MsgWithdrawValidatorCommissionResponse return message } } const baseMsgFundCommunityPool: object = { depositor: '' } export const MsgFundCommunityPool = { encode( message: MsgFundCommunityPool, writer: Writer = Writer.create() ): Writer { for (const v of message.amount) { Coin.encode(v!, writer.uint32(10).fork()).ldelim() } if (message.depositor !== '') { writer.uint32(18).string(message.depositor) } return writer }, decode(input: Reader | Uint8Array, length?: number): MsgFundCommunityPool { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseMsgFundCommunityPool } as MsgFundCommunityPool message.amount = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.amount.push(Coin.decode(reader, reader.uint32())) break case 2: message.depositor = reader.string() break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): MsgFundCommunityPool { const message = { ...baseMsgFundCommunityPool } as MsgFundCommunityPool message.amount = [] if (object.amount !== undefined && object.amount !== null) { for (const e of object.amount) { message.amount.push(Coin.fromJSON(e)) } } if (object.depositor !== undefined && object.depositor !== null) { message.depositor = String(object.depositor) } else { message.depositor = '' } return message }, toJSON(message: MsgFundCommunityPool): unknown { const obj: any = {} if (message.amount) { obj.amount = message.amount.map((e) => (e ? Coin.toJSON(e) : undefined)) } else { obj.amount = [] } message.depositor !== undefined && (obj.depositor = message.depositor) return obj }, fromPartial(object: DeepPartial<MsgFundCommunityPool>): MsgFundCommunityPool { const message = { ...baseMsgFundCommunityPool } as MsgFundCommunityPool message.amount = [] if (object.amount !== undefined && object.amount !== null) { for (const e of object.amount) { message.amount.push(Coin.fromPartial(e)) } } if (object.depositor !== undefined && object.depositor !== null) { message.depositor = object.depositor } else { message.depositor = '' } return message } } const baseMsgFundCommunityPoolResponse: object = {} export const MsgFundCommunityPoolResponse = { encode( _: MsgFundCommunityPoolResponse, writer: Writer = Writer.create() ): Writer { return writer }, decode( input: Reader | Uint8Array, length?: number ): MsgFundCommunityPoolResponse { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseMsgFundCommunityPoolResponse } as MsgFundCommunityPoolResponse while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { default: reader.skipType(tag & 7) break } } return message }, fromJSON(_: any): MsgFundCommunityPoolResponse { const message = { ...baseMsgFundCommunityPoolResponse } as MsgFundCommunityPoolResponse return message }, toJSON(_: MsgFundCommunityPoolResponse): unknown { const obj: any = {} return obj }, fromPartial( _: DeepPartial<MsgFundCommunityPoolResponse> ): MsgFundCommunityPoolResponse { const message = { ...baseMsgFundCommunityPoolResponse } as MsgFundCommunityPoolResponse return message } } /** Msg defines the distribution Msg service. */ export interface Msg { /** * SetWithdrawAddress defines a method to change the withdraw address * for a delegator (or validator self-delegation). */ SetWithdrawAddress( request: MsgSetWithdrawAddress ): Promise<MsgSetWithdrawAddressResponse> /** * WithdrawDelegatorReward defines a method to withdraw rewards of delegator * from a single validator. */ WithdrawDelegatorReward( request: MsgWithdrawDelegatorReward ): Promise<MsgWithdrawDelegatorRewardResponse> /** * WithdrawValidatorCommission defines a method to withdraw the * full commission to the validator address. */ WithdrawValidatorCommission( request: MsgWithdrawValidatorCommission ): Promise<MsgWithdrawValidatorCommissionResponse> /** * FundCommunityPool defines a method to allow an account to directly * fund the community pool. */ FundCommunityPool( request: MsgFundCommunityPool ): Promise<MsgFundCommunityPoolResponse> } export class MsgClientImpl implements Msg { private readonly rpc: Rpc constructor(rpc: Rpc) { this.rpc = rpc } SetWithdrawAddress( request: MsgSetWithdrawAddress ): Promise<MsgSetWithdrawAddressResponse> { const data = MsgSetWithdrawAddress.encode(request).finish() const promise = this.rpc.request( 'cosmos.distribution.v1beta1.Msg', 'SetWithdrawAddress', data ) return promise.then((data) => MsgSetWithdrawAddressResponse.decode(new Reader(data)) ) } WithdrawDelegatorReward( request: MsgWithdrawDelegatorReward ): Promise<MsgWithdrawDelegatorRewardResponse> { const data = MsgWithdrawDelegatorReward.encode(request).finish() const promise = this.rpc.request( 'cosmos.distribution.v1beta1.Msg', 'WithdrawDelegatorReward', data ) return promise.then((data) => MsgWithdrawDelegatorRewardResponse.decode(new Reader(data)) ) } WithdrawValidatorCommission( request: MsgWithdrawValidatorCommission ): Promise<MsgWithdrawValidatorCommissionResponse> { const data = MsgWithdrawValidatorCommission.encode(request).finish() const promise = this.rpc.request( 'cosmos.distribution.v1beta1.Msg', 'WithdrawValidatorCommission', data ) return promise.then((data) => MsgWithdrawValidatorCommissionResponse.decode(new Reader(data)) ) } FundCommunityPool( request: MsgFundCommunityPool ): Promise<MsgFundCommunityPoolResponse> { const data = MsgFundCommunityPool.encode(request).finish() const promise = this.rpc.request( 'cosmos.distribution.v1beta1.Msg', 'FundCommunityPool', data ) return promise.then((data) => MsgFundCommunityPoolResponse.decode(new Reader(data)) ) } } interface Rpc { request( service: string, method: string, data: Uint8Array ): Promise<Uint8Array> } type Builtin = Date | Function | Uint8Array | string | number | undefined export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T>
the_stack
import assert from '../stub/assert'; import { promiseRejectedWith, promiseResolvedWith, setPromiseIsHandledToTrue, transformPromiseWith } from './helpers/webidl'; import { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy'; import { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator'; import { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader'; import { AcquireReadableStreamDefaultReader, IsReadableStreamDefaultReader, ReadableStreamDefaultReader, ReadableStreamDefaultReadResult } from './readable-stream/default-reader'; import { AcquireReadableStreamBYOBReader, IsReadableStreamBYOBReader, ReadableStreamBYOBReader, ReadableStreamBYOBReadResult } from './readable-stream/byob-reader'; import { ReadableStreamPipeTo } from './readable-stream/pipe'; import { ReadableStreamTee } from './readable-stream/tee'; import { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream'; import { SimpleQueue } from './simple-queue'; import { ReadableByteStreamController, ReadableStreamBYOBRequest, SetUpReadableByteStreamController, SetUpReadableByteStreamControllerFromUnderlyingSource } from './readable-stream/byte-stream-controller'; import { ReadableStreamDefaultController, SetUpReadableStreamDefaultController, SetUpReadableStreamDefaultControllerFromUnderlyingSource } from './readable-stream/default-controller'; import { UnderlyingByteSource, UnderlyingByteSourcePullCallback, UnderlyingByteSourceStartCallback, UnderlyingSource, UnderlyingSourceCancelCallback, UnderlyingSourcePullCallback, UnderlyingSourceStartCallback } from './readable-stream/underlying-source'; import { noop } from '../utils'; import { typeIsObject } from './helpers/miscellaneous'; import { CreateArrayFromList } from './abstract-ops/ecmascript'; import { CancelSteps } from './abstract-ops/internal-methods'; import { IsNonNegativeNumber } from './abstract-ops/miscellaneous'; import { assertObject, assertRequiredArgument } from './validators/basic'; import { convertQueuingStrategy } from './validators/queuing-strategy'; import { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy'; import { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source'; import { ReadableStreamGetReaderOptions } from './readable-stream/reader-options'; import { convertReaderOptions } from './validators/reader-options'; import { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options'; import { ReadableStreamIteratorOptions } from './readable-stream/iterator-options'; import { convertIteratorOptions } from './validators/iterator-options'; import { convertPipeOptions } from './validators/pipe-options'; import { ReadableWritablePair } from './readable-stream/readable-writable-pair'; import { convertReadableWritablePair } from './validators/readable-writable-pair'; export type ReadableByteStream = ReadableStream<Uint8Array> & { _readableStreamController: ReadableByteStreamController }; type ReadableStreamState = 'readable' | 'closed' | 'errored'; /** * A readable stream represents a source of data, from which you can read. * * @public */ export class ReadableStream<R = any> { /** @internal */ _state!: ReadableStreamState; /** @internal */ _reader: ReadableStreamReader<R> | undefined; /** @internal */ _storedError: any; /** @internal */ _disturbed!: boolean; /** @internal */ _readableStreamController!: ReadableStreamDefaultController<R> | ReadableByteStreamController; constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined }); constructor(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>); constructor(rawUnderlyingSource: UnderlyingSource<R> | UnderlyingByteSource | null | undefined = {}, rawStrategy: QueuingStrategy<R> | null | undefined = {}) { if (rawUnderlyingSource === undefined) { rawUnderlyingSource = null; } else { assertObject(rawUnderlyingSource, 'First parameter'); } const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); InitializeReadableStream(this); if (underlyingSource.type === 'bytes') { if (strategy.size !== undefined) { throw new RangeError('The strategy for a byte stream cannot have a size function'); } const highWaterMark = ExtractHighWaterMark(strategy, 0); SetUpReadableByteStreamControllerFromUnderlyingSource( this as unknown as ReadableByteStream, underlyingSource, highWaterMark ); } else { assert(underlyingSource.type === undefined); const sizeAlgorithm = ExtractSizeAlgorithm(strategy); const highWaterMark = ExtractHighWaterMark(strategy, 1); SetUpReadableStreamDefaultControllerFromUnderlyingSource( this, underlyingSource, highWaterMark, sizeAlgorithm ); } } /** * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. */ get locked(): boolean { if (!IsReadableStream(this)) { throw streamBrandCheckException('locked'); } return IsReadableStreamLocked(this); } /** * Cancels the stream, signaling a loss of interest in the stream by a consumer. * * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} * method, which might or might not use it. */ cancel(reason: any = undefined): Promise<void> { if (!IsReadableStream(this)) { return promiseRejectedWith(streamBrandCheckException('cancel')); } if (IsReadableStreamLocked(this)) { return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); } return ReadableStreamCancel(this, reason); } /** * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader. * * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise * control over allocation. */ getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader; /** * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. * While the stream is locked, no other reader can be acquired until this one is released. * * This functionality is especially useful for creating abstractions that desire the ability to consume a stream * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours * or cancel the stream, which would interfere with your abstraction. */ getReader(): ReadableStreamDefaultReader<R>; getReader( rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined ): ReadableStreamDefaultReader<R> | ReadableStreamBYOBReader { if (!IsReadableStream(this)) { throw streamBrandCheckException('getReader'); } const options = convertReaderOptions(rawOptions, 'First parameter'); if (options.mode === undefined) { return AcquireReadableStreamDefaultReader(this); } assert(options.mode === 'byob'); return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream); } /** * Provides a convenient, chainable way of piping this readable stream through a transform stream * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream * into the writable side of the supplied pair, and returns the readable side for further use. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ pipeThrough<RS extends ReadableStream>( transform: { readable: RS; writable: WritableStream<R> }, options?: StreamPipeOptions ): RS; pipeThrough<RS extends ReadableStream>( rawTransform: { readable: RS; writable: WritableStream<R> } | null | undefined, rawOptions: StreamPipeOptions | null | undefined = {} ): RS { if (!IsReadableStream(this)) { throw streamBrandCheckException('pipeThrough'); } assertRequiredArgument(rawTransform, 1, 'pipeThrough'); const transform = convertReadableWritablePair(rawTransform, 'First parameter'); const options = convertPipeOptions(rawOptions, 'Second parameter'); if (IsReadableStreamLocked(this)) { throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); } if (IsWritableStreamLocked(transform.writable)) { throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); } const promise = ReadableStreamPipeTo( this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal ); setPromiseIsHandledToTrue(promise); return transform.readable; } /** * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under * various error conditions can be customized with a number of passed options. It returns a promise that fulfills * when the piping process completes successfully, or rejects if any errors were encountered. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>; pipeTo(destination: WritableStream<R> | null | undefined, rawOptions: StreamPipeOptions | null | undefined = {}): Promise<void> { if (!IsReadableStream(this)) { return promiseRejectedWith(streamBrandCheckException('pipeTo')); } if (destination === undefined) { return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); } if (!IsWritableStream(destination)) { return promiseRejectedWith( new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`) ); } let options: ValidatedStreamPipeOptions; try { options = convertPipeOptions(rawOptions, 'Second parameter'); } catch (e) { return promiseRejectedWith(e); } if (IsReadableStreamLocked(this)) { return promiseRejectedWith( new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream') ); } if (IsWritableStreamLocked(destination)) { return promiseRejectedWith( new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream') ); } return ReadableStreamPipeTo<R>( this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal ); } /** * Tees this readable stream, returning a two-element array containing the two resulting branches as * new {@link ReadableStream} instances. * * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be * propagated to the stream's underlying source. * * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, * this could allow interference between the two branches. */ tee(): [ReadableStream<R>, ReadableStream<R>] { if (!IsReadableStream(this)) { throw streamBrandCheckException('tee'); } const branches = ReadableStreamTee(this, false); return CreateArrayFromList(branches); } /** * Asynchronously iterates over the chunks in the stream's internal queue. * * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method * is called, e.g. by breaking out of the loop. * * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing * `true` for the `preventCancel` option. */ values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>; values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator<R> { if (!IsReadableStream(this)) { throw streamBrandCheckException('values'); } const options = convertIteratorOptions(rawOptions, 'First parameter'); return AcquireReadableStreamAsyncIterator<R>(this, options.preventCancel); } /** * {@inheritDoc ReadableStream.values} */ [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator<R>; } Object.defineProperties(ReadableStream.prototype, { cancel: { enumerable: true }, getReader: { enumerable: true }, pipeThrough: { enumerable: true }, pipeTo: { enumerable: true }, tee: { enumerable: true }, values: { enumerable: true }, locked: { enumerable: true } }); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { value: 'ReadableStream', configurable: true }); } if (typeof Symbol.asyncIterator === 'symbol') { Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, { value: ReadableStream.prototype.values, writable: true, configurable: true }); } export { ReadableStreamAsyncIterator, ReadableStreamDefaultReadResult, ReadableStreamBYOBReadResult, UnderlyingByteSource, UnderlyingSource, UnderlyingSourceStartCallback, UnderlyingSourcePullCallback, UnderlyingSourceCancelCallback, UnderlyingByteSourceStartCallback, UnderlyingByteSourcePullCallback, StreamPipeOptions, ReadableWritablePair, ReadableStreamIteratorOptions }; // Abstract operations for the ReadableStream. // Throws if and only if startAlgorithm throws. export function CreateReadableStream<R>(startAlgorithm: () => void | PromiseLike<void>, pullAlgorithm: () => Promise<void>, cancelAlgorithm: (reason: any) => Promise<void>, highWaterMark = 1, sizeAlgorithm: QueuingStrategySizeCallback<R> = () => 1): ReadableStream<R> { assert(IsNonNegativeNumber(highWaterMark)); const stream: ReadableStream<R> = Object.create(ReadableStream.prototype); InitializeReadableStream(stream); const controller: ReadableStreamDefaultController<R> = Object.create(ReadableStreamDefaultController.prototype); SetUpReadableStreamDefaultController( stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm ); return stream; } // Throws if and only if startAlgorithm throws. export function CreateReadableByteStream( startAlgorithm: () => void | PromiseLike<void>, pullAlgorithm: () => Promise<void>, cancelAlgorithm: (reason: any) => Promise<void> ): ReadableByteStream { const stream: ReadableByteStream = Object.create(ReadableStream.prototype); InitializeReadableStream(stream); const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype); SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); return stream; } function InitializeReadableStream(stream: ReadableStream) { stream._state = 'readable'; stream._reader = undefined; stream._storedError = undefined; stream._disturbed = false; } export function IsReadableStream(x: unknown): x is ReadableStream { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { return false; } return x instanceof ReadableStream; } export function IsReadableStreamDisturbed(stream: ReadableStream): boolean { assert(IsReadableStream(stream)); return stream._disturbed; } export function IsReadableStreamLocked(stream: ReadableStream): boolean { assert(IsReadableStream(stream)); if (stream._reader === undefined) { return false; } return true; } // ReadableStream API exposed for controllers. export function ReadableStreamCancel<R>(stream: ReadableStream<R>, reason: any): Promise<undefined> { stream._disturbed = true; if (stream._state === 'closed') { return promiseResolvedWith(undefined); } if (stream._state === 'errored') { return promiseRejectedWith(stream._storedError); } ReadableStreamClose(stream); const reader = stream._reader; if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { reader._readIntoRequests.forEach(readIntoRequest => { readIntoRequest._closeSteps(undefined); }); reader._readIntoRequests = new SimpleQueue(); } const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); return transformPromiseWith(sourceCancelPromise, noop); } export function ReadableStreamClose<R>(stream: ReadableStream<R>): void { assert(stream._state === 'readable'); stream._state = 'closed'; const reader = stream._reader; if (reader === undefined) { return; } defaultReaderClosedPromiseResolve(reader); if (IsReadableStreamDefaultReader<R>(reader)) { reader._readRequests.forEach(readRequest => { readRequest._closeSteps(); }); reader._readRequests = new SimpleQueue(); } } export function ReadableStreamError<R>(stream: ReadableStream<R>, e: any): void { assert(IsReadableStream(stream)); assert(stream._state === 'readable'); stream._state = 'errored'; stream._storedError = e; const reader = stream._reader; if (reader === undefined) { return; } defaultReaderClosedPromiseReject(reader, e); if (IsReadableStreamDefaultReader<R>(reader)) { reader._readRequests.forEach(readRequest => { readRequest._errorSteps(e); }); reader._readRequests = new SimpleQueue(); } else { assert(IsReadableStreamBYOBReader(reader)); reader._readIntoRequests.forEach(readIntoRequest => { readIntoRequest._errorSteps(e); }); reader._readIntoRequests = new SimpleQueue(); } } // Readers export type ReadableStreamReader<R> = ReadableStreamDefaultReader<R> | ReadableStreamBYOBReader; export { ReadableStreamDefaultReader, ReadableStreamBYOBReader }; // Controllers export { ReadableStreamDefaultController, ReadableStreamBYOBRequest, ReadableByteStreamController }; // Helper functions for the ReadableStream. function streamBrandCheckException(name: string): TypeError { return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); }
the_stack
import { CancellablePromise, Disposable, Dock, Pane, PaneItemObservedEvent, PaneItemOpenedEvent, Panel, TextEditor, TextEditorObservedEvent, ViewModel, WorkspaceCenter, } from '../index'; /** Represents the state of the user interface for the entire window. */ export interface Workspace { // Event Subscription /** * Invoke the given callback with all current and future text editors in * the workspace. */ observeTextEditors(callback: (editor: TextEditor) => void): Disposable; /** * Invoke the given callback with all current and future panes items in the * workspace. */ observePaneItems(callback: (item: object) => void): Disposable; /** Invoke the given callback when the active pane item changes. */ onDidChangeActivePaneItem(callback: (item: object) => void): Disposable; /** Invoke the given callback when the active pane item stops changing. */ onDidStopChangingActivePaneItem(callback: (item: object) => void): Disposable; /** * Invoke the given callback when a text editor becomes the active text editor and * when there is no longer an active text editor. */ onDidChangeActiveTextEditor(callback: (editor?: TextEditor) => void): Disposable; /** * Invoke the given callback with the current active pane item and with all * future active pane items in the workspace. */ observeActivePaneItem(callback: (item: object) => void): Disposable; /** * Invoke the given callback with the current active text editor (if any), with all * future active text editors, and when there is no longer an active text editor. */ observeActiveTextEditor(callback: (editor?: TextEditor) => void): Disposable; /** * Invoke the given callback whenever an item is opened. Unlike ::onDidAddPaneItem, * observers will be notified for items that are already present in the workspace * when they are reopened. */ onDidOpen(callback: (event: PaneItemOpenedEvent) => void): Disposable; /** Invoke the given callback when a pane is added to the workspace. */ onDidAddPane(callback: (event: { pane: Pane }) => void): Disposable; /** Invoke the given callback before a pane is destroyed in the workspace. */ onWillDestroyPane(callback: (event: { pane: Pane }) => void): Disposable; /** Invoke the given callback when a pane is destroyed in the workspace. */ onDidDestroyPane(callback: (event: { pane: Pane }) => void): Disposable; /** Invoke the given callback with all current and future panes in the workspace. */ observePanes(callback: (pane: Pane) => void): Disposable; /** Invoke the given callback when the active pane changes. */ onDidChangeActivePane(callback: (pane: Pane) => void): Disposable; /** * Invoke the given callback with the current active pane and when the * active pane changes. */ observeActivePane(callback: (pane: Pane) => void): Disposable; /** Invoke the given callback when a pane item is added to the workspace. */ onDidAddPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable; /** * Invoke the given callback when a pane item is about to be destroyed, * before the user is prompted to save it. * @param callback The function to be called before pane items are destroyed. * If this function returns a Promise, then the item will not be destroyed * until the promise resolves. */ onWillDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void | Promise<void>): Disposable; /** Invoke the given callback when a pane item is destroyed. */ onDidDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable; /** Invoke the given callback when a text editor is added to the workspace. */ onDidAddTextEditor(callback: (event: TextEditorObservedEvent) => void): Disposable; // Opening /** * Opens the given URI in Atom asynchronously. If the URI is already open, * the existing item for that URI will be activated. If no URI is given, or * no registered opener can open the URI, a new empty TextEditor will be created. */ open(uri: string, options?: WorkspaceOpenOptions): Promise<object>; /** * Opens the given item in Atom asynchronously. If the item is already open, * the existing item will be activated. If no item is given, a new empty TextEditor * will be created. */ open<T extends ViewModel = ViewModel>(item: T, options?: WorkspaceOpenOptions): Promise<T>; /** * Opens the given URI in Atom asynchronously. If the URI is already open, * the existing item for that URI will be activated. If no URI is given, or * no registered opener can open the URI, a new empty TextEditor will be created. */ open(): Promise<TextEditor>; /** * Search the workspace for items matching the given URI and hide them. * Returns a boolean indicating whether any items were found (and hidden). */ hide(itemOrURI: object | string): boolean; /** * Search the workspace for items matching the given URI. If any are found, * hide them. Otherwise, open the URL. * Returns a Promise that resolves when the item is shown or hidden. */ toggle(itemOrURI: object | string): Promise<void>; /** * Creates a new item that corresponds to the provided URI. * If no URI is given, or no registered opener can open the URI, a new empty TextEditor * will be created. */ createItemForURI(uri: string): Promise<object | TextEditor>; /** Returns a boolean that is true if object is a TextEditor. */ isTextEditor(object: object): object is TextEditor; /** * Asynchronously reopens the last-closed item's URI if it hasn't already * been reopened. */ reopenItem(): Promise<object | undefined>; /** Register an opener for a URI. */ addOpener(opener: (uri: string, options?: WorkspaceOpenOptions) => ViewModel | undefined): Disposable; /** Create a new text editor. */ buildTextEditor(params: object): TextEditor; // Pane Items /** Get all pane items in the workspace. */ getPaneItems(): object[]; /** Get the active Pane's active item. */ getActivePaneItem(): object; /** Get all text editors in the workspace. */ getTextEditors(): TextEditor[]; /** Get the workspace center's active item if it is a TextEditor. */ getActiveTextEditor(): TextEditor | undefined; // Panes /** Get the most recently focused pane container. */ getActivePaneContainer(): Dock | WorkspaceCenter; /** Get all panes in the workspace. */ getPanes(): Pane[]; /** Get the active Pane. */ getActivePane(): Pane; /** Make the next pane active. */ activateNextPane(): boolean; /** Make the previous pane active. */ activatePreviousPane(): boolean; /** Get the first pane container that contains an item with the given URI. */ paneContainerForURI(uri: string): Dock | WorkspaceCenter | undefined; /** Get the first pane container that contains the given item. */ paneContainerForItem(item: object): Dock | WorkspaceCenter | undefined; /** Get the first Pane with an item for the given URI. */ paneForURI(uri: string): Pane | undefined; /** Get the Pane containing the given item. */ paneForItem(item: object): Pane | undefined; // Pane Locations /** Get the WorkspaceCenter at the center of the editor window. */ getCenter(): WorkspaceCenter; /** Get the Dock to the left of the editor window. */ getLeftDock(): Dock; /** Get the Dock to the right of the editor window. */ getRightDock(): Dock; /** Get the Dock below the editor window. */ getBottomDock(): Dock; /** Returns all Pane containers. */ getPaneContainers(): [WorkspaceCenter, Dock, Dock, Dock]; // Panels /** Get an Array of all the panel items at the bottom of the editor window. */ getBottomPanels(): Panel[]; /** Adds a panel item to the bottom of the editor window. */ addBottomPanel<T>(options: { item: T; visible?: boolean | undefined; priority?: number | undefined }): Panel<T>; /** Get an Array of all the panel items to the left of the editor window. */ getLeftPanels(): Panel[]; /** Adds a panel item to the left of the editor window. */ addLeftPanel<T>(options: { item: T; visible?: boolean | undefined; priority?: number | undefined }): Panel<T>; /** Get an Array of all the panel items to the right of the editor window. */ getRightPanels(): Panel[]; /** Adds a panel item to the right of the editor window. */ addRightPanel<T>(options: { item: T; visible?: boolean | undefined; priority?: number | undefined }): Panel<T>; /** Get an Array of all the panel items at the top of the editor window. */ getTopPanels(): Panel[]; /** Adds a panel item to the top of the editor window above the tabs. */ addTopPanel<T>(options: { item: T; visible?: boolean | undefined; priority?: number | undefined }): Panel<T>; /** Get an Array of all the panel items in the header. */ getHeaderPanels(): Panel[]; /** Adds a panel item to the header. */ addHeaderPanel<T>(options: { item: T; visible?: boolean | undefined; priority?: number | undefined }): Panel<T>; /** Get an Array of all the panel items in the footer. */ getFooterPanels(): Panel[]; /** Adds a panel item to the footer. */ addFooterPanel<T>(options: { item: T; visible?: boolean | undefined; priority?: number | undefined }): Panel<T>; /** Get an Array of all the modal panel items. */ getModalPanels(): Panel[]; /** Adds a panel item as a modal dialog. */ addModalPanel<T>(options: { item: T; visible?: boolean | undefined; priority?: number | undefined; autoFocus?: boolean | FocusableHTMLElement | undefined; }): Panel<T>; /** * Returns the Panel associated with the given item or null when the item * has no panel. */ panelForItem<T>(item: T): Panel<T> | null; // Searching and Replacing /** Performs a search across all files in the workspace. */ scan(regex: RegExp, iterator: (result: ScandalResult) => void): CancellablePromise<string | null>; /** Performs a search across all files in the workspace. */ scan( regex: RegExp, options: WorkspaceScanOptions, iterator: (result: ScandalResult) => void, ): CancellablePromise<string | null>; /** Performs a replace across all the specified files in the project. */ replace( regex: RegExp, replacementText: string, filePaths: ReadonlyArray<string>, iterator: (result: { filePath: string | undefined; replacements: number }) => void, ): Promise<void>; } export interface WorkspaceOpenOptions { /** A number indicating which row to move the cursor to initially. Defaults to 0. */ initialLine?: number | undefined; /** A number indicating which column to move the cursor to initially. Defaults to 0. */ initialColumn?: number | undefined; /** * Either 'left', 'right', 'up' or 'down'. If 'left', the item will be opened in * leftmost pane of the current active pane's row. If 'right', the item will be * opened in the rightmost pane of the current active pane's row. If only one pane * exists in the row, a new pane will be created. If 'up', the item will be opened * in topmost pane of the current active pane's column. If 'down', the item will be * opened in the bottommost pane of the current active pane's column. If only one pane * exists in the column, a new pane will be created. */ split?: 'left' | 'right' | 'up' | 'down' | undefined; /** * A boolean indicating whether to call Pane::activate on containing pane. * Defaults to true. */ activatePane?: boolean | undefined; /** * A boolean indicating whether to call Pane::activateItem on containing pane. * Defaults to true. */ activateItem?: boolean | undefined; /** * A Boolean indicating whether or not the item should be opened in a pending state. * Existing pending items in a pane are replaced with new pending items when they * are opened. */ pending?: boolean | undefined; /** * A boolean. If true, the workspace will attempt to activate an existing item for * the given URI on any pane. If false, only the active pane will be searched for * an existing item for the same URI. Defaults to false. */ searchAllPanes?: boolean | undefined; /** * A String containing the name of the location in which this item should be opened. * If omitted, Atom will fall back to the last location in which a user has placed * an item with the same URI or, if this is a new URI, the default location specified * by the item. * NOTE: This option should almost always be omitted to honor user preference. */ location?: 'left' | 'right' | 'bottom' | 'center' | undefined; } export interface WorkspaceScanOptions { /** An array of glob patterns to search within. */ paths?: ReadonlyArray<string> | undefined; /** A function to be periodically called with the number of paths searched. */ onPathsSearched?(pathsSearched: number): void; /** The number of lines before the matched line to include in the results object. */ leadingContextLineCount?: number | undefined; /** The number of lines after the matched line to include in the results object. */ trailingContextLineCount?: number | undefined; } export interface ScandalResult { filePath: string; matches: Array<{ matchText: string; lineText: string; lineTextOffset: number; range: [[number, number], [number, number]]; leadingContextLines: string[]; trailingContextLines: string[]; }>; } /** * The type used by the `focus-trap` library to target a specific DOM node. * * A DOM node, a selector string (which will be passed to `document.querySelector()` * to find the DOM node), or a function that returns a DOM node. */ export type FocusableHTMLElement = HTMLElement | string | { (): HTMLElement };
the_stack
import {TAB} from '@angular/cdk/keycodes'; import { dispatchFakeEvent, dispatchKeyboardEvent, dispatchMouseEvent, patchElementFocus, createMouseEvent, dispatchEvent, } from '../../testing/private'; import {DOCUMENT} from '@angular/common'; import {Component, NgZone} from '@angular/core'; import {ComponentFixture, fakeAsync, flush, inject, TestBed, tick} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {A11yModule} from '../index'; import {TOUCH_BUFFER_MS} from '../input-modality/input-modality-detector'; import { FocusMonitor, FocusMonitorDetectionMode, FocusOrigin, FOCUS_MONITOR_DEFAULT_OPTIONS, } from './focus-monitor'; describe('FocusMonitor', () => { let fixture: ComponentFixture<PlainButton>; let buttonElement: HTMLElement; let focusMonitor: FocusMonitor; let changeHandler: (origin: FocusOrigin) => void; let fakeActiveElement: HTMLElement | null; beforeEach(() => { fakeActiveElement = null; TestBed.configureTestingModule({ imports: [A11yModule], declarations: [PlainButton], providers: [ { provide: DOCUMENT, useFactory: () => { // We have to stub out the `document` in order to be able to fake `activeElement`. const fakeDocument = {body: document.body}; [ 'createElement', 'dispatchEvent', 'querySelectorAll', 'addEventListener', 'removeEventListener', ].forEach(method => { (fakeDocument as any)[method] = function () { return (document as any)[method].apply(document, arguments); }; }); Object.defineProperty(fakeDocument, 'activeElement', { get: () => fakeActiveElement || document.activeElement, }); return fakeDocument; }, }, ], }).compileComponents(); }); beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => { fixture = TestBed.createComponent(PlainButton); fixture.detectChanges(); buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement; focusMonitor = fm; changeHandler = jasmine.createSpy('focus origin change handler'); focusMonitor.monitor(buttonElement).subscribe(changeHandler); patchElementFocus(buttonElement); })); it('manually registered element should receive focus classes', fakeAsync(() => { buttonElement.focus(); fixture.detectChanges(); tick(); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledTimes(1); })); it('should detect focus via keyboard', fakeAsync(() => { // Simulate focus via keyboard. dispatchKeyboardEvent(document, 'keydown', TAB); buttonElement.focus(); fixture.detectChanges(); flush(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-keyboard-focused')) .withContext('button should have cdk-keyboard-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledWith('keyboard'); })); it('should detect focus via mouse', fakeAsync(() => { // Simulate focus via mouse. dispatchMouseEvent(buttonElement, 'mousedown'); buttonElement.focus(); fixture.detectChanges(); flush(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-mouse-focused')) .withContext('button should have cdk-mouse-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledWith('mouse'); })); it('should detect focus via touch', fakeAsync(() => { // Simulate focus via touch. dispatchFakeEvent(buttonElement, 'touchstart'); buttonElement.focus(); fixture.detectChanges(); tick(TOUCH_BUFFER_MS); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-touch-focused')) .withContext('button should have cdk-touch-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledWith('touch'); })); it('should detect programmatic focus', fakeAsync(() => { // Programmatically focus. buttonElement.focus(); fixture.detectChanges(); tick(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-program-focused')) .withContext('button should have cdk-program-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledWith('program'); })); it('should detect fake mousedown from a screen reader', fakeAsync(() => { // Simulate focus via a fake mousedown from a screen reader. dispatchMouseEvent(buttonElement, 'mousedown'); const event = createMouseEvent('mousedown'); Object.defineProperties(event, {offsetX: {get: () => 0}, offsetY: {get: () => 0}}); dispatchEvent(buttonElement, event); buttonElement.focus(); fixture.detectChanges(); flush(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-keyboard-focused')) .withContext('button should have cdk-keyboard-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledWith('keyboard'); })); it('focusVia keyboard should simulate keyboard focus', fakeAsync(() => { focusMonitor.focusVia(buttonElement, 'keyboard'); flush(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-keyboard-focused')) .withContext('button should have cdk-keyboard-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledWith('keyboard'); })); it('focusVia mouse should simulate mouse focus', fakeAsync(() => { focusMonitor.focusVia(buttonElement, 'mouse'); fixture.detectChanges(); flush(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-mouse-focused')) .withContext('button should have cdk-mouse-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledWith('mouse'); })); it('focusVia touch should simulate touch focus', fakeAsync(() => { focusMonitor.focusVia(buttonElement, 'touch'); fixture.detectChanges(); flush(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-touch-focused')) .withContext('button should have cdk-touch-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledWith('touch'); })); it('focusVia program should simulate programmatic focus', fakeAsync(() => { focusMonitor.focusVia(buttonElement, 'program'); fixture.detectChanges(); flush(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-program-focused')) .withContext('button should have cdk-program-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledWith('program'); })); it('should remove focus classes on blur', fakeAsync(() => { buttonElement.focus(); fixture.detectChanges(); tick(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(changeHandler).toHaveBeenCalledWith('program'); // Call `blur` directly because invoking `buttonElement.blur()` does not always trigger the // handler on IE11 on SauceLabs. focusMonitor._onBlur({} as any, buttonElement); fixture.detectChanges(); expect(buttonElement.classList.length) .withContext('button should not have any focus classes') .toBe(0); expect(changeHandler).toHaveBeenCalledWith(null); })); it('should remove classes on stopMonitoring', fakeAsync(() => { buttonElement.focus(); fixture.detectChanges(); tick(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); focusMonitor.stopMonitoring(buttonElement); fixture.detectChanges(); expect(buttonElement.classList.length) .withContext('button should not have any focus classes') .toBe(0); })); it('should remove classes when destroyed', fakeAsync(() => { buttonElement.focus(); fixture.detectChanges(); tick(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); // Destroy manually since destroying the fixture won't do it. focusMonitor.ngOnDestroy(); fixture.detectChanges(); expect(buttonElement.classList.length) .withContext('button should not have any focus classes') .toBe(0); })); it('should pass focus options to the native focus method', fakeAsync(() => { spyOn(buttonElement, 'focus'); focusMonitor.focusVia(buttonElement, 'program', {preventScroll: true}); fixture.detectChanges(); flush(); expect(buttonElement.focus).toHaveBeenCalledWith( jasmine.objectContaining({ preventScroll: true, }), ); })); it('should not clear the focus origin too early in the current event loop', fakeAsync(() => { dispatchKeyboardEvent(document, 'keydown', TAB); // Simulate the behavior of Firefox 57 where the focus event sometimes happens *one* tick later. tick(); buttonElement.focus(); // Since the timeout doesn't clear the focus origin too early as with the `0ms` timeout, the // focus origin should be reported properly. expect(changeHandler).toHaveBeenCalledWith('keyboard'); flush(); })); it('should clear the focus origin after one tick with "immediate" detection', fakeAsync(() => { dispatchKeyboardEvent(document, 'keydown', TAB); tick(2); buttonElement.focus(); // After 2 ticks, the timeout has cleared the origin. Default is 'program'. expect(changeHandler).toHaveBeenCalledWith('program'); })); it('should check children if monitor was called with different checkChildren', fakeAsync(() => { const parent = fixture.nativeElement.querySelector('.parent'); focusMonitor.monitor(parent, true); focusMonitor.monitor(parent, false); // Simulate focus via mouse. dispatchMouseEvent(buttonElement, 'mousedown'); buttonElement.focus(); fixture.detectChanges(); flush(); expect(parent.classList).toContain('cdk-focused'); expect(parent.classList).toContain('cdk-mouse-focused'); })); it('focusVia should change the focus origin when called on the focused node', fakeAsync(() => { spyOn(buttonElement, 'focus').and.callThrough(); focusMonitor.focusVia(buttonElement, 'keyboard'); flush(); fakeActiveElement = buttonElement; expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-keyboard-focused')) .withContext('button should have cdk-keyboard-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledTimes(1); expect(changeHandler).toHaveBeenCalledWith('keyboard'); expect(buttonElement.focus).toHaveBeenCalledTimes(1); focusMonitor.focusVia(buttonElement, 'mouse'); flush(); fakeActiveElement = buttonElement; expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-mouse-focused')) .withContext('button should have cdk-mouse-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledTimes(2); expect(changeHandler).toHaveBeenCalledWith('mouse'); expect(buttonElement.focus).toHaveBeenCalledTimes(1); })); it('focusVia should change the focus origin when called a focused child node', fakeAsync(() => { const parent = fixture.nativeElement.querySelector('.parent'); focusMonitor.stopMonitoring(buttonElement); // The button gets monitored by default. focusMonitor.monitor(parent, true).subscribe(changeHandler); spyOn(buttonElement, 'focus').and.callThrough(); focusMonitor.focusVia(buttonElement, 'keyboard'); flush(); fakeActiveElement = buttonElement; expect(parent.classList.length) .withContext('Parent should have exactly 2 focus classes and the `parent` class') .toBe(3); expect(parent.classList.contains('cdk-focused')) .withContext('Parent should have cdk-focused class') .toBe(true); expect(parent.classList.contains('cdk-keyboard-focused')) .withContext('Parent should have cdk-keyboard-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledTimes(1); expect(changeHandler).toHaveBeenCalledWith('keyboard'); expect(buttonElement.focus).toHaveBeenCalledTimes(1); focusMonitor.focusVia(buttonElement, 'mouse'); flush(); fakeActiveElement = buttonElement; expect(parent.classList.length) .withContext('Parent should have exactly 2 focus classes and the `parent` class') .toBe(3); expect(parent.classList.contains('cdk-focused')) .withContext('Parent should have cdk-focused class') .toBe(true); expect(parent.classList.contains('cdk-mouse-focused')) .withContext('Parent should have cdk-mouse-focused class') .toBe(true); expect(changeHandler).toHaveBeenCalledTimes(2); expect(changeHandler).toHaveBeenCalledWith('mouse'); expect(buttonElement.focus).toHaveBeenCalledTimes(1); })); }); describe('FocusMonitor with "eventual" detection', () => { let fixture: ComponentFixture<PlainButton>; let buttonElement: HTMLElement; let focusMonitor: FocusMonitor; let changeHandler: (origin: FocusOrigin) => void; beforeEach(() => { TestBed.configureTestingModule({ imports: [A11yModule], declarations: [PlainButton], providers: [ { provide: FOCUS_MONITOR_DEFAULT_OPTIONS, useValue: { detectionMode: FocusMonitorDetectionMode.EVENTUAL, }, }, ], }).compileComponents(); }); beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => { fixture = TestBed.createComponent(PlainButton); fixture.detectChanges(); buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement; focusMonitor = fm; changeHandler = jasmine.createSpy('focus origin change handler'); focusMonitor.monitor(buttonElement).subscribe(changeHandler); patchElementFocus(buttonElement); })); it('should not clear the focus origin, even after a few seconds', fakeAsync(() => { dispatchKeyboardEvent(document, 'keydown', TAB); tick(2000); buttonElement.focus(); expect(changeHandler).toHaveBeenCalledWith('keyboard'); })); }); describe('cdkMonitorFocus', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [A11yModule], declarations: [ ButtonWithFocusClasses, ComplexComponentWithMonitorElementFocus, ComplexComponentWithMonitorSubtreeFocus, ComplexComponentWithMonitorSubtreeFocusAndMonitorElementFocus, FocusMonitorOnCommentNode, ], }).compileComponents(); }); describe('button with cdkMonitorElementFocus', () => { let fixture: ComponentFixture<ButtonWithFocusClasses>; let buttonElement: HTMLElement; beforeEach(() => { fixture = TestBed.createComponent(ButtonWithFocusClasses); fixture.detectChanges(); spyOn(fixture.componentInstance, 'focusChanged'); buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement; patchElementFocus(buttonElement); }); it('should initially not be focused', () => { expect(buttonElement.classList.length) .withContext('button should not have focus classes') .toBe(0); }); it('should detect focus via keyboard', fakeAsync(() => { // Simulate focus via keyboard. dispatchKeyboardEvent(document, 'keydown', TAB); buttonElement.focus(); fixture.detectChanges(); flush(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-keyboard-focused')) .withContext('button should have cdk-keyboard-focused class') .toBe(true); expect(fixture.componentInstance.focusChanged).toHaveBeenCalledWith('keyboard'); })); it('should detect focus via mouse', fakeAsync(() => { // Simulate focus via mouse. dispatchMouseEvent(buttonElement, 'mousedown'); buttonElement.focus(); fixture.detectChanges(); flush(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-mouse-focused')) .withContext('button should have cdk-mouse-focused class') .toBe(true); expect(fixture.componentInstance.focusChanged).toHaveBeenCalledWith('mouse'); })); it('should detect focus via touch', fakeAsync(() => { // Simulate focus via touch. dispatchFakeEvent(buttonElement, 'touchstart'); buttonElement.focus(); fixture.detectChanges(); tick(TOUCH_BUFFER_MS); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-touch-focused')) .withContext('button should have cdk-touch-focused class') .toBe(true); expect(fixture.componentInstance.focusChanged).toHaveBeenCalledWith('touch'); })); it('should detect programmatic focus', fakeAsync(() => { // Programmatically focus. buttonElement.focus(); fixture.detectChanges(); tick(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(buttonElement.classList.contains('cdk-focused')) .withContext('button should have cdk-focused class') .toBe(true); expect(buttonElement.classList.contains('cdk-program-focused')) .withContext('button should have cdk-program-focused class') .toBe(true); expect(fixture.componentInstance.focusChanged).toHaveBeenCalledWith('program'); })); it('should remove focus classes on blur', fakeAsync(() => { buttonElement.focus(); fixture.detectChanges(); tick(); expect(buttonElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); expect(fixture.componentInstance.focusChanged).toHaveBeenCalledWith('program'); buttonElement.blur(); fixture.detectChanges(); expect(buttonElement.classList.length) .withContext('button should not have any focus classes') .toBe(0); expect(fixture.componentInstance.focusChanged).toHaveBeenCalledWith(null); })); }); describe('complex component with cdkMonitorElementFocus', () => { let fixture: ComponentFixture<ComplexComponentWithMonitorElementFocus>; let parentElement: HTMLElement; let childElement: HTMLElement; beforeEach(() => { fixture = TestBed.createComponent(ComplexComponentWithMonitorElementFocus); fixture.detectChanges(); parentElement = fixture.debugElement.query(By.css('div'))!.nativeElement; childElement = fixture.debugElement.query(By.css('button'))!.nativeElement; patchElementFocus(parentElement); patchElementFocus(childElement); }); it('should add focus classes on parent focus', fakeAsync(() => { parentElement.focus(); fixture.detectChanges(); tick(); expect(parentElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); })); it('should not add focus classes on child focus', fakeAsync(() => { childElement.focus(); fixture.detectChanges(); tick(); expect(parentElement.classList.length) .withContext('button should not have any focus classes') .toBe(0); })); }); describe('complex component with cdkMonitorSubtreeFocus', () => { let fixture: ComponentFixture<ComplexComponentWithMonitorSubtreeFocus>; let parentElement: HTMLElement; let childElement: HTMLElement; beforeEach(() => { fixture = TestBed.createComponent(ComplexComponentWithMonitorSubtreeFocus); fixture.detectChanges(); parentElement = fixture.debugElement.query(By.css('div'))!.nativeElement; childElement = fixture.debugElement.query(By.css('button'))!.nativeElement; patchElementFocus(parentElement); patchElementFocus(childElement); }); it('should add focus classes on parent focus', fakeAsync(() => { parentElement.focus(); fixture.detectChanges(); tick(); expect(parentElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); })); it('should add focus classes on child focus', fakeAsync(() => { childElement.focus(); fixture.detectChanges(); tick(); expect(parentElement.classList.length) .withContext('button should have exactly 2 focus classes') .toBe(2); })); }); describe('complex component with cdkMonitorSubtreeFocus and cdkMonitorElementFocus', () => { let fixture: ComponentFixture<ComplexComponentWithMonitorSubtreeFocusAndMonitorElementFocus>; let parentElement: HTMLElement; let childElement: HTMLElement; let focusMonitor: FocusMonitor; beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => { focusMonitor = fm; fixture = TestBed.createComponent( ComplexComponentWithMonitorSubtreeFocusAndMonitorElementFocus, ); fixture.detectChanges(); parentElement = fixture.debugElement.query(By.css('div'))!.nativeElement; childElement = fixture.debugElement.query(By.css('button'))!.nativeElement; patchElementFocus(parentElement); patchElementFocus(childElement); })); it('should add keyboard focus classes on both elements when child is focused via keyboard', fakeAsync(() => { focusMonitor.focusVia(childElement, 'keyboard'); fixture.detectChanges(); flush(); expect(parentElement.classList).toContain('cdk-keyboard-focused'); expect(childElement.classList).toContain('cdk-keyboard-focused'); })); }); it('should not throw when trying to monitor focus on a non-element node', () => { expect(() => { const fixture = TestBed.createComponent(FocusMonitorOnCommentNode); fixture.detectChanges(); fixture.destroy(); }).not.toThrow(); }); }); describe('FocusMonitor observable stream', () => { let fixture: ComponentFixture<PlainButton>; let buttonElement: HTMLElement; let focusMonitor: FocusMonitor; beforeEach(() => { TestBed.configureTestingModule({ imports: [A11yModule], declarations: [PlainButton], }).compileComponents(); }); beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => { fixture = TestBed.createComponent(PlainButton); focusMonitor = fm; fixture.detectChanges(); buttonElement = fixture.debugElement.nativeElement.querySelector('button'); patchElementFocus(buttonElement); })); it('should emit inside the NgZone', fakeAsync(() => { const spy = jasmine.createSpy('zone spy'); focusMonitor.monitor(buttonElement).subscribe(() => spy(NgZone.isInAngularZone())); expect(spy).not.toHaveBeenCalled(); buttonElement.focus(); fixture.detectChanges(); tick(); expect(spy).toHaveBeenCalledWith(true); })); }); @Component({ template: `<div class="parent"><button>focus me!</button></div>`, }) class PlainButton {} @Component({ template: `<button cdkMonitorElementFocus (cdkFocusChange)="focusChanged($event)"></button>`, }) class ButtonWithFocusClasses { focusChanged(_origin: FocusOrigin) {} } @Component({ template: `<div tabindex="0" cdkMonitorElementFocus><button></button></div>`, }) class ComplexComponentWithMonitorElementFocus {} @Component({ template: `<div tabindex="0" cdkMonitorSubtreeFocus><button></button></div>`, }) class ComplexComponentWithMonitorSubtreeFocus {} @Component({ template: `<div cdkMonitorSubtreeFocus><button cdkMonitorElementFocus></button></div>`, }) class ComplexComponentWithMonitorSubtreeFocusAndMonitorElementFocus {} @Component({ template: `<ng-container cdkMonitorElementFocus></ng-container>`, }) class FocusMonitorOnCommentNode {}
the_stack
import * as React from "react" import colors from "../../styles/colors" import * as typographyStyles from "../../styles/typography.module.css" import * as tableStyles from "../../styles/table.module.css" import * as buttonStyles from "../../styles/button.module.css" import CodeArea from "../../components/CodeArea" import focusController from "../../components/codeExamples/focusController" import toggleFields from "../../components/codeExamples/toggleFields" export default { title: "FAQs", header: { title: "FAQs", description: "Preguntas frecuentes.", }, questions: [ { title: "Performance de React Hook Form", description: ( <p> El rendimiento es uno de los objetivos principales de construir este hook personalizado. React Hook Form se basa en componentes no controlados, de ahí la razón por la cual la función de registro se realiza en el ref. Este enfoque recude la cantidad de renderizados que ocurren debido a la escritura del usuario o al cambio de valores. El montaje de componentes en la página también es mucho más rápido porque son no controlados. Para la velocidad de montaje, realicé una prueba rápida de comparación a la que puedes acceder desde {""} <a href="https://github.com/bluebill1049/react-hook-form-performance-compare" target="_blank" rel="noopener noreferrer" > este link </a> . </p> ), }, { title: "¿Cómo crear un mensaje de error de Input accesible?", description: ( <p> React Hook Form está basado en{" "} <a href="https://reactjs.org/docs/uncontrolled-components.html" rel="noopener noreferrer" target="_blank" > Componentes no controlados </a> , lo que te brinda la posibilidad de hacer formularios personalizados accesibles con facilidad. </p> ), }, { title: "¿Funciona con componentes de clases?", description: ( <> <p> No, no por defecto. Pero puedes crear un contenedor y usarlo en tu componente de clase. </p> <blockquote> No puedes usar Hooks dentro de un componente de clase, pero puedes mezclar clases y componentes de funciones con Hooks en un solo árbol. Si un componente es una clase o una función que usa Hooks es un detalle de implementación de ese componente. A largo plazo, esperamos que Hooks sea la forma principal en que la gente escriba componentes en React. </blockquote> </> ), }, { title: "¿Cómo resetear el formulario?", description: ( <> <p>Hay dos métodos para resetear el formulario.</p> <ul> <li> <b>HTMLFormElement.reset()</b> <p> Este método es lo mismo que clickear el botón de reset, y solo limpia los valores de <code>input/select/checkbox</code>. </p> </li> <li> <b> React Hook Form API: <code>reset()</code> </b> <p> El método <code>reset</code> de React Hook Form resetea todos los valores de los campos, y además limpia todos los <code>errores</code> dentro del formulario. </p> </li> </ul> </> ), }, { title: "¿Como inicializar los valores del formulario?", description: ( <p> React Hook Form se basa en componentes no controlados. En un componente no controlado, puedes especificar el valor por defecto de un campo individual mediante <code>defaultValue</code> o{" "} <code>defaultChecked</code>. Sin embargo, el Hook proporciona una manera más fácil de inicializar todos los valores de entrada. Ejemplo a continuación: </p> ), }, { title: "¿Cómo compartir el uso de la referencia?", description: ( <p> React Hook Form necesita de <code>ref</code> para recolectar todos los valores de input, pero además puede que quieras usar <code>ref</code> para otros propósitos (ej.desplazarse por la pantalla). El siguiente ejemplo te muestra como realizarlo. </p> ), }, { title: "¿Qué pasa si no tengo acceso a la referencia?", description: ( <> <p> Puedes <code>registrar</code> un input sin una{" "} <code>referencia</code>. De hecho, puedes configurar el valor manualmente con <code>setValue</code>, <code>setError </code> y <code>trigger</code>. </p> <p> <b className={typographyStyles.note}> Nota: </b> Debido a que la{" "} <code>referencia</code> no se ha registrado, React Hook Form no podrá registrar listeners de eventos en los inputs. Esto significa que tendrás que actualizar manualmente el valor y el error. </p> </> ), }, { title: "¿Soporte en navegadores?", description: ( <> <p>React Hook Form soporta la majoría de los navegadores.</p> <p> Para el sporte de IE11, puedes importar la versión react-hook-form IE 11. </p> </> ), }, { title: "¿Por qué la primera pulsación de tecla no funciona?", description: ( <> <p> Vuelve a chequear si no estás utilizando <code>value</code> en vez de <code>defaultValue</code>. </p> <p> React Hook Form está basado en inputs no controlados, lo que significa que no necesitas cambiar el valor del input con{" "} <code>value</code>a través del <code>state</code> con{" "} <code>onChange</code>. De hecho no necesitas <code>value</code> en absoluto, solo necesitas <code>defaultValue</code> para el valor inicial del input. </p> </> ), }, { title: "¿El testing falló por MutationObserver?", description: ( <p> Si tienes dificultades en el testeo y el problema fue causado por{" "} <code>MutationObserver</code>. Asegurate que hayas instalado{" "} <code>mutationobserver</code> y has importado el paquete en tu test:{" "} <a href="https://jestjs.io/docs/en/configuration" target="_blank" rel="noopener noreferrer" > archivo setup.js </a> . </p> ), }, { title: "¿React Hook Form, Formik o Redux Form?", description: ( <> <p> En primer lugar, todas estas librerías intentan resolver el mismo problema, que construir formularios sea fácil y excelente. Sin embargo, hay algunas diferencias fundamentales entre los tres, react-hook-form está hecho con inputs no controlados en mente e intenta proporcionar un formulario con mejor rendimiento y menos renderizaciones si es posible. Además de eso, react-hook-form está construido con Hooks de React y se usa como tal, lo que significa que no hay ningún componente que importar. Estos son algunos de los detalles. diferencias: </p> <div className={tableStyles.tableWrapper}> <table className={tableStyles.table}> <thead> <tr style={{ borderBottom: `1px solid ${colors.lightPink}` }}> <th width={200} /> <th> <p>React Hook Form</p> </th> <th> <p>Formik</p> </th> <th> <p>Redux Form</p> </th> </tr> </thead> <tbody> <tr> <td> <b>Componente</b> </td> <td> <a href="https://reactjs.org/docs/uncontrolled-components.html" target="_blank" rel="noopener noreferrer" > no controlado </a>{" "} &{" "} <a href="https://reactjs.org/docs/forms.html" target="_blank" rel="noopener noreferrer" > controlado </a> </td> <td> <a href="https://reactjs.org/docs/forms.html" target="_blank" rel="noopener noreferrer" > controlado </a> </td> <td> <a href="https://reactjs.org/docs/forms.html" target="_blank" rel="noopener noreferrer" > controlado </a> </td> </tr> <tr> <td> <b>Renderizado</b> </td> <td>renderizado mínimo</td> <td> renderizado de acuerdo a cambios de estado locales, mientras escribes en el input. </td> <td> renderizado de acuerdo a cambios en librerías de administración de estado (Redux), mientras escribes en el input. </td> </tr> <tr> <td> <b>API</b> </td> <td>Hooks</td> <td>Componente (RenderProps, Form, Field) + Hooks</td> <td>Componente (RenderProps, Form, Field)</td> </tr> <tr> <td> <b>Tamaño del paquete</b> </td> <td> Pequeño <br /> <code> react-hook-form@4.0.0 <br /> <b className={typographyStyles.note}>6.2KB</b> </code> </td> <td> Mediano <br /> <code> formik@2.0.1 <br /> <b className={typographyStyles.note}>14.4KB</b> </code> </td> <td> Grande <br /> <code> redux-form@8.2.6 <br /> <b className={typographyStyles.note}>27KB</b> </code> </td> </tr> <tr> <td> <b>Validación</b> </td> <td> Incorporada &{" "} <a href="https://github.com/jquense/yup" target="_blank" rel="noopener noreferrer" > Yup </a> </td> <td> Construye tu propia &{" "} <a href="https://github.com/jquense/yup" target="_blank" rel="noopener noreferrer" > Yup </a> </td> <td>Construye tu propia & Plugins</td> </tr> <tr> <td> <b>Curva de aprendizaje</b> </td> <td>Baja</td> <td>Mediana</td> <td>Mediana</td> </tr> <tr> <td> <b>Estado</b> </td> <td>Comunidad Mediana: Nueva librería y creciendo.</td> <td> Comunidad Amplia: Librería establecida en la comunidad. </td> <td> Comunidad Amplia: Librería establecida en la comunidad. </td> </tr> </tbody> </table> </div> </> ), }, { title: "¿Puede funcionar con componentes Controlados?", description: ( <> <p> Respuesta corta: <b>Si</b> </p> <p> React-hook-form no recomienda construir un formulario controlado, sin embargo, puedes lograrlo fácilmente. </p> <p> El truco es utilizar el <code>watch</code> de la API para monitorear cada cambio en los input y asignar la propiedad value. </p> <p> De formar alterna, puedes utilizar nuestro componente wrapper{" "} <a href="https://www.react-hook-form.com/api#Controller" title="React Hook Form Controller" > Controller </a>{" "} es el encargado de realizar el registro por ti. </p> </> ), }, { title: "Testeando React Hook Form", description: ( <div> <ul> <li> <p> ¿Por qué recibo la advertencia de <code>act</code>? </p> <p> Todos los métodos de validación en React Hook Form son tratados como funciones async, es importante que wrappees con async{" "} <a className={buttonStyles.codeAsLink} href="https://reactjs.org/docs/test-utils.html#act" target="_blank" rel="noopener noreferrer" > act </a> . </p> </li> <li> <p>¿Por qué un cambio en un input no dispara un evento?</p> <p> React Hook Form utiliza el evento <code>input</code> para los cambios en input, para solucionarlo puedes cambiar a{" "} <code>fireEvent.input</code> para react-testing-library </p> </li> </ul> </div> ), }, { title: "watch vs getValues vs state", description: ( <div> <ul> <li> <p> <b className={typographyStyles.note}> watch: </b> puede suscríbirse a cambios en entradas a través del detector de eventos y renderizado en función de los campos suscritos. Renderizar en función de qué entrada es vista / suscrito revisa{" "} <a href="https://codesandbox.io/s/react-hook-form-watch-with-radio-buttons-and-select-examples-ovfus" rel="noopener noreferrer" target="_blank" > codesandbox </a>{" "} por comportamiento real. </p> </li> <li> <p> <b className={typographyStyles.note}>getValues</b>: obtener valor que almacena dentro del gancho personalizado como referencia, rápido y barato. Este método no activa el re-renderizado. </p> </li> <li> <p> <b className={typographyStyles.note}>estado</b>: Reaccionar local state representa más que solo el estado de entrada y también decide qué para renderizar Esto se activará con cada cambio de entrada. </p> </li> </ul> </div> ), }, { title: "¿Por qué los valores por defecto no cambian correctamente con un operador ternario?", description: ( <> <p> React Hook Form no controla todo el formulario y las entradas, es la razón por la cual React no reconocería la entrada real que ha sido intercambiado o cambiado. Como solución, puede resolver esto problema al dar un apoyo único de <code>key</code> a su entrada. También puede leer más sobre los accesorios clave de{" "} <a target="_blank" rel="noopener noreferrer" href="https://kentcdodds.com/blog/understanding-reacts-key-prop" > Este artículo escrito por Kent C. Dodds </a> . </p> <CodeArea rawData={toggleFields} url="https://codesandbox.io/s/react-hook-form-faq-toggle-fields-3htr6" /> </> ), }, { title: "¿la validación no funciona con submitFocusError?", description: ( <> <p> Después de un error de validación, React Hook Form se enfocará automáticamente en los elementos inválidos de los cuales tienen su referencia adecuada, como el entradas nativas (p. ej .:{" "} <code>{`<input />`}</code>) o algún tercero Componentes que exportan correctamente su referencia (por ejemplo: desde MUI <code>{`<TextField inputRef = {register ({required: 'Field Required'})} />`}</code> ) </p> <p> Sin embargo, para algunos Componentes controlados por terceros como <code>{`<Autocomplete>`}</code> de MUI o <code>{`<XX>`}</code> de AntD) es muy difícil predecir su referencia por los cambios de formato, por lo que React Hook Form detectará correctamente el error de validación pero no podrá enfocar automáticamente eso tipo de componentes. </p> <p> Como solución alternativa, después del error de validación, se puede enfocar manualmente en el componente controlado por terceros (si puede obtener la real entrada interna ref), por ejemplo: </p> <CodeArea rawData={focusController} /> <p> Si le resulta difícil hacer el enfoque automático con control externo componente. Es posible deshabilitar el "enfoque automático en caso de error" característica. Tal vez este comportamiento traerá una mejor experiencia de usuario en algunos casos.{" "} <code>{`useForm ({shouldFocusError: false});`}</code> </p> </> ), }, { title: "How to work with modal or tab forms?", description: ( <> <p> Es importante entender que React Hook Form abraza la forma nativa comportamiento por estado de entrada de la tienda dentro de cada entrada (excepto personalizado <code>registrarse</code> en <code>useEffect</code>). Uno de los comunes conceptos erróneos es cuando se trabaja con formularios modales o tabuladores, al montar y desmontando la forma / entradas que permanecerá el estado de las entradas. Eso es implementación incorrecta, en cambio, la solución correcta siempre debe construyendo un nuevo formulario para su formulario dentro de modal o cada pestaña y capturar sus datos de envío en estado local o global. </p> <ul> <li> <a href="https://codesandbox.io/s/react-hook-form-modal-form-conditional-inputs-c7n0r" target="_blank" rel="noopener noreferrer" > Modal form and toggle inputs Example </a> </li> <li> <a href="https://codesandbox.io/s/tabs-760h9" target="_blank" rel="noopener noreferrer" > Tab Form Example </a> </li> </ul> </> ), }, // { // title: "¿Aviso de componente desmontado?", // description: ( // <> // <p> // Ejecutar la función de envío de sincronización mientras que{" "} // <code>usarForma</code> obtiene sin montar resultará en la siguiente // advertencia de React at <b>dev build</b>. // </p> // <blockquote> // No se puede realizar una actualización del estado de Reacción en un // componente sin montar. // </blockquote> // <p> // Este no es el mismo caso en la construcción de la picana, tal // comportamiento se hace para que son compatibles con la actualización // rápida de React. Entradas' <code>ref</code> la llamada de retorno no // se ejecutará de nuevo durante el refresco rápido, así que tenemos // deshabilitó el control de desmontaje del gancho sólo en Dev. // </p> // </> // ), // }, ], }
the_stack
import { formatUnits } from '@ethersproject/units'; import { multicall } from '../../utils'; import { BigNumber } from '@ethersproject/bignumber'; import fetch from 'cross-fetch'; export const author = 'joaomajesus'; export const version = '0.2.0'; /* * Generic masterchef pool balance or price strategy. Accepted options: * - chefAddress: Masterchef contract address * - pid: Mastechef pool id (starting with zero) * * - uniPairAddress: Address of a uniswap pair (or a sushi pair or any other with the same interface) * - If the uniPairAddress option is provided, converts staked LP token balance to base token balance * (based on the pair total supply and base token reserve) * - If uniPairAddress is null or undefined, returns staked token balance of the pool * * - tokenAddress: Address of a token for single token Pools. * - if the uniPairAddress is provided the tokenAddress is ignored. * * - weight: Integer multiplier of the result (for combining strategies with different weights, totally optional) * - weightDecimals: Integer value of number of decimal places to apply to the final result * * - token0.address: Address of the uniPair token 0. If defined, the strategy will return the result for the token0. * can be used in conjunction with token1Address to get the sum of tokens or the UniPair token price * when used with usePrice and token1Address. * Can be used with usePrice to get the price value of the staked amount of token0 * - token0.weight: Integer multiplier of the result for token0 * - token0.weightDecimals: Integer value of number of decimal places to apply to the result of token0 * * - token1.address: Address of the uniPair token 1. If defined, the strategy will return the result for the token1. * can be used in conjunction with token0Address to get the sum of tokens or the UniPair token price * when used with usePrice and token0Address. * can be used with usePrice to get the price value of the staked amount of token1 * - token1,weight: Integer multiplier of the result for token1 * - token1.weightDecimal: Integer value of number of decimal places to apply to the result of token1 * * - usePrice: Boolean flag return the result in usd instead of token count * * - currency: currency for the price. (defaulted to 'usd'). * * - log: Boolean flag to enable or disable logging to the console (used for debugging purposes during development) * * - antiWhale.enable: Boolean flag to apply an anti-whale measure reducing the effect on the voting power as the token amount increases. * - if enabled will apply the the following to the result: * * If result > antiWhale.threshold * result = antiWhale.inflectionPoint * ( result / antiWhale.inflectionPoint ) ^ antiWhale.exponent * * If result <= antiWhale.threshold * thresholdMultiplier = ( antiWhale.inflectionPoint * ( antiWhale.threshold / antiWhale.inflectionPoint )^antiWhale.exponent ) / antiWhale.threshold * result = result * thresholdMultiplier * * - thresholdMultiplier: The multiplier at which all results below threshold are multiplied. This is ratio of antiWhale/result at the threshold point. * - antiWhale.threshold: Point at which antiWhale effect no longer applies. Results less than this will be treated with a static multiplier. * This is to reduce infinite incentive for multiple wallet exploits. * - default: 1625. * - lower cap: > 0 - set to default if <= 0. * - antiWhale.inflectionPoint: Point at which output matches result. Results less than this increase output. Results greater than this decrease output. * - default: 6500. * - lower cap: > 0 - set to default if <= 0. * - must be >= antiWhale.threshold. Otherwise will be same as antiWhale.threshold. * - antiWhale.exponent: The exponent is responsible for the antiWhale effect. Must be less than one, or else it will have a pro-whale effect. * Must be greater than zero, or else it will cause total voting power to trend to zero. * - default: 0.5. * - upper cap: 1. * - lower cap: > 0 - set to default if <= 0. * * Check the examples.json file for how to use the options. */ const abi = [ 'function userInfo(uint256, address) view returns (uint256 amount, uint256 rewardDebt)', 'function totalSupply() view returns (uint256)', 'function getReserves() view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast)', 'function token0() view returns (address)', 'function token1() view returns (address)', 'function decimals() view returns (uint8)' ]; const networksWithPlatforms = { 1: 'ethereum', 56: 'binance-smart-chain', 66: 'okex-chain', 88: 'tomochain', 100: 'xdai', 128: 'huobi-token', 137: 'polygon-pos', 250: 'fantom', 42220: 'celo', 43114: 'avalanche', 1666600000: 'harmony-shard-0' }; const priceCache = new Map<any, number>(); const blockCache = new Map<any, any>(); let log: string[] = []; let _options; const getUserInfoCalls = (addresses: any[]) => { const result: any[] = []; for (const address of addresses) { result.push([_options.chefAddress, 'userInfo', [_options.pid, address]]); } return result; }; const getTokenCalls = () => { const result: any[] = []; if (_options.uniPairAddress != null) { result.push([_options.uniPairAddress, 'totalSupply', []]); result.push([_options.uniPairAddress, 'getReserves', []]); result.push([_options.uniPairAddress, 'token0', []]); result.push([_options.uniPairAddress, 'token1', []]); result.push([_options.uniPairAddress, 'decimals', []]); if (_options.token0?.address != null) { result.push([_options.token0.address, 'decimals', []]); } if (_options.token1?.address != null) { result.push([_options.token1.address, 'decimals', []]); } } else if (_options.tokenAddress != null) { result.push([_options.tokenAddress, 'decimals', []]); } return result; }; function arrayChunk<T>(arr: T[], chunkSize: number): T[][] { const result: T[][] = []; for (let i = 0, j = arr.length; i < j; i += chunkSize) { result.push(arr.slice(i, i + chunkSize)); } return result; } async function processValues( values: any[], tokenValues: any[], network: any, provider: any, blockTag: string | number ) { log.push(`values = ${JSON.stringify(values, undefined, 2)}`); log.push(`tokenValues = ${JSON.stringify(tokenValues, undefined, 2)}`); printLog(); const poolStaked = values[0][0] as BigNumber; const weight = BigNumber.from(_options.weight || 1); const weightDecimals = BigNumber.from(10).pow( BigNumber.from(_options.weightDecimals || 0) ); let result = 0; if (_options.uniPairAddress == null) { log.push(`poolStaked = ${poolStaked}`); if (_options.tokenAddress != null) { const tokenDecimals = BigNumber.from(10).pow( BigNumber.from(tokenValues[0][0]) ); log.push(`tokenDecimals = ${tokenDecimals}`); log.push(`decimals = ${_options.decimals}`); printLog(); result = toFloat(poolStaked.div(tokenDecimals), _options.decimals); if (_options.usePrice == true) { const price = await getTokenPrice( _options.tokenAddress, network, provider, blockTag ); result *= price; } } else { printLog(); result = toFloat(poolStaked, _options.decimals); } } else { const uniTotalSupply = tokenValues[0][0]; const uniReserve0 = tokenValues[1][0]; const uniReserve1 = tokenValues[1][1]; const uniPairDecimalsIndex: any = _options.uniPairAddress != null ? 4 : null; const uniPairDecimalsCount = tokenValues[uniPairDecimalsIndex][0]; const uniPairDecimals = uniPairDecimalsIndex != null ? BigNumber.from(10).pow(BigNumber.from(uniPairDecimalsCount || 0)) : BigNumber.from(1); const token0Address = tokenValues[2][0]; const useToken0 = _options.token0?.address != null && _options.token0.address.toString().toLowerCase() == token0Address?.toString().toLowerCase(); log.push(`useToken0 = ${useToken0}`); if (useToken0) { const token0DecimalsIndex = 5; log.push(`token0DecimalsIndex = ${token0DecimalsIndex}`); log.push(`tokenValues = ${JSON.stringify(tokenValues, undefined, 2)}`); printLog(); result += await GetTokenValue( network, provider, blockTag, uniTotalSupply, uniReserve0, uniPairDecimals, poolStaked, tokenValues, token0Address, token0DecimalsIndex, _options.token0?.weight, _options.token0?.weightDecimals ); } const token1Address = tokenValues[3][0]; const useToken1 = _options.token1?.address != null && _options.token1.address.toString().toLowerCase() == token1Address?.toString().toLowerCase(); log.push(`useToken1 = ${useToken1}`); if (useToken1) { const token1DecimalsIndex = _options.token0?.address != null ? 6 : 5; log.push(`token1DecimalsIndex = ${token1DecimalsIndex}`); log.push(`tokenValues = ${JSON.stringify(tokenValues, undefined, 2)}`); printLog(); result += await GetTokenValue( network, provider, blockTag, uniTotalSupply, uniReserve1, uniPairDecimals, poolStaked, tokenValues, token1Address, token1DecimalsIndex, _options.token1?.weight, _options.token1?.WeightDecimals ); } if (!useToken0 && !useToken1) { log.push(`poolStaked = ${poolStaked}`); log.push(`uniPairDecimals = ${uniPairDecimals}`); printLog(); const tokenCount = poolStaked.toNumber() / 10 ** uniPairDecimalsCount; log.push(`tokenCount = ${tokenCount}`); result = tokenCount / 10 ** (_options.decimals || 0); } } log.push(`result = ${result}`); printLog(); result *= weight.toNumber() / weightDecimals.toNumber(); log.push(`weight = ${weight}`); log.push(`weightDecimals = ${weightDecimals}`); log.push(`result = ${result}`); printLog(); return applyAntiWhaleMeasures(result); } function applyAntiWhaleMeasures(result) { log.push(`antiWhale = ${_options.antiWhale?.enable}`); if (_options.antiWhale?.enable != true) { printLog(); return result; } const threshold = _options.antiWhale.threshold == null || _options.antiWhale.threshold <= 0 ? 1625 : _options.antiWhale.threshold; let inflectionPoint = _options.antiWhale.inflectionPoint == null || _options.antiWhale.inflectionPoint <= 0 ? 6500 : _options.antiWhale.inflectionPoint; inflectionPoint = inflectionPoint < threshold ? threshold : inflectionPoint; const exponent = _options.antiWhale.exponent == null || _options.antiWhale.exponent <= 0 ? 0.5 : _options.antiWhale.exponent > 1 ? 1 : _options.antiWhale.exponent; log.push(`inflectionPoint = ${inflectionPoint}`); log.push(`exponent = ${exponent}`); log.push(`threshold = ${threshold}`); printLog(); if (result > threshold) { result = inflectionPoint * (result / inflectionPoint) ** exponent; } else { const thresholdMultiplier = (inflectionPoint * (threshold / inflectionPoint) ** exponent) / threshold; log.push(`thresholdMultiplier = ${thresholdMultiplier}`); result = result * thresholdMultiplier; } log.push(`result = ${result}`); printLog(); return result; } function toFloat(value: BigNumber, decimals: any): number { const decimalsResult = decimals === 0 ? 0 : decimals || 18; log.push(`toFloat value = ${value}`); log.push(`toFloat decimals = ${decimals}`); log.push(`toFloat decimalsResult = ${decimalsResult}`); printLog(); return parseFloat(formatUnits(value.toString(), decimalsResult)); } async function GetTokenValue( network: any, provider: any, blockTag: string | number, uniTotalSupply: any, uniReserve: any, uniPairDecimals: BigNumber, poolStaked: BigNumber, tokenValues: any[], tokenAddress: any, tokenDecimalsIndex: any, tokenWeight: any, tokenWeightDecimals: any ) { const weightDecimals = BigNumber.from(10).pow( BigNumber.from(tokenWeightDecimals || 0) ); const weight = BigNumber.from(tokenWeight || 1); const tokensPerLp = uniReserve.mul(uniPairDecimals).div(uniTotalSupply); const tokenDecimals = tokenDecimalsIndex != null ? BigNumber.from(10).pow( BigNumber.from(tokenValues[tokenDecimalsIndex][0] || 0) ) : BigNumber.from(1); const price = await getTokenPrice(tokenAddress, network, provider, blockTag); log.push(`tokenAddress = ${tokenAddress}`); log.push(`tokenDecimals = ${tokenDecimals}`); log.push(`poolStaked = ${poolStaked}`); log.push(`uniReserve = ${uniReserve}`); log.push(`uniPairDecimals = ${uniPairDecimals}`); log.push(`uniTotalSupply = ${uniTotalSupply}`); log.push(`tokensPerLp = ${tokensPerLp}`); log.push(`tokenWeight = ${weight}`); log.push(`tokenWeightDecimals = ${weightDecimals}`); log.push(`price = ${price}`); printLog(); const tokenCount = poolStaked .mul(tokensPerLp) .div(tokenDecimals) .mul(weight) .div(weightDecimals); log.push(`tokenCount = ${tokenCount}`); return toFloat(tokenCount, _options.decimals) * price; } function printLog() { if (_options.log || false) { console.debug(log); log = []; } } async function getTokenPrice( tokenAddress: any, network: any, provider: any, blockTag: string | number ) { let price = 1; const cacheKey = tokenAddress + blockTag; if (_options.usePrice === true && !priceCache.has(cacheKey)) { log.push( `calling getPrice for token address: ${tokenAddress} and blockTag: ${blockTag}` ); priceCache.set( cacheKey, (await getPrice(network, provider, tokenAddress, blockTag)) || 1 ); } price = priceCache.get(cacheKey) || 1; return price; } async function getPrice(network, provider, address, blockTag) { if (!blockCache.has(blockTag)) { blockCache.set(blockTag, await provider.getBlock(blockTag)); } const block = blockCache.get(blockTag); const platform = networksWithPlatforms[network]; const currency = _options.currency || 'usd'; const from = block.timestamp - 100000; const to = block.timestamp; const coingeckoApiURL = `https://api.coingecko.com/api/v3/coins/${platform}/contract/${new String( address ).toLowerCase()}/market_chart/range?vs_currency=${currency}&from=${from}&to=${to}`; log.push(`platform = ${platform}`); log.push(`from = ${from}`); log.push(`to = ${from}`); log.push(`coingeckoApiURL = ${coingeckoApiURL}`); const coingeckoData = await fetch(coingeckoApiURL) .then(async (r) => { log.push(`coingeco response = ${JSON.stringify(r, undefined, 2)}`); const json = await r.json(); log.push(`coingecko json = ${JSON.stringify(json, undefined, 2)}`); return json; }) .catch((e) => { console.error(e); throw new Error( 'Strategy masterchef-pool-balance-of-token: coingecko api failed' ); }); return (coingeckoData.prices?.pop()?.pop() || 0) as number; } export async function strategy( space, network, provider, addresses, options, snapshot ) { _options = options; const blockTag = typeof snapshot === 'number' ? snapshot : 'latest'; const userInfoCalls = getUserInfoCalls(addresses); const tokenCalls = getTokenCalls(); const entries = new Map<PropertyKey, any>(); const userInfoResponse = await multicall( network, provider, abi, userInfoCalls, { blockTag } ); const userInfoChunks = arrayChunk(userInfoResponse, 1); const tokenResponse = await multicall(network, provider, abi, tokenCalls, { blockTag }); for (let i = 0; i < userInfoChunks.length; i++) { const value = userInfoChunks[i]; const score = await processValues( value, tokenResponse, network, provider, blockTag ); entries.set(addresses[i], score); } return Object.fromEntries(entries); }
the_stack
import { sectionHandler } from '@microsoft/bf-lu/lib/parser/composerindex'; import { updateIntent, addIntent, removeIntent, checkSection, parse, semanticValidate } from '../src/utils/luUtil'; const { luParser, luSectionTypes } = sectionHandler; describe('LU parse and validation', () => { it('should parse reference', () => { const fileContent = `[import](welcome.lu) # AskForName - {@userName=Jack} `; const luFiles = [ { id: 'welcome', content: `# welcome - hi `, }, ]; const result1 = parse('a.lu', fileContent, {}, luFiles); expect(result1.diagnostics.length).toEqual(0); expect(result1.intents.length).toEqual(1); expect(result1.allIntents.length).toEqual(2); expect(result1.allIntents[1].fileId).toEqual('welcome'); }); it('should parse reference deep and with locale', () => { const fileContent = `[import](welcome.lu) # AskForName - {@userName=Jack} `; const luFiles = [ { id: 'welcome.en-us', content: `[import](greeting.lu) # welcome - hi `, }, { id: 'greeting', content: `# greeting - hi `, }, ]; const result1 = parse('a.en-us.lu', fileContent, {}, luFiles); expect(result1.diagnostics.length).toEqual(0); expect(result1.intents.length).toEqual(1); expect(result1.allIntents.length).toEqual(3); expect(result1.allIntents[1].fileId).toEqual('welcome.en-us'); expect(result1.allIntents[2].fileId).toEqual('greeting'); }); it('should throws error when Orchestrator include entity', () => { const fileContent = `# AskForName - @{userName=Jack} `; const result1 = parse('a.lu', fileContent, { isOrchestartor: true }, []); expect(result1.diagnostics.length).toEqual(1); }); it('Throws when ML entity is disable (validateResource, not orchestrator)', () => { const fileContent = `# AskForName - {@userName=Jack} `; const result1 = parse('a.lu', fileContent, { isOrchestartor: false, enableMLEntities: false }, []); expect(result1.diagnostics.length).toEqual(1); const result2 = parse('a.lu', fileContent, { isOrchestartor: false, enableMLEntities: true }, []); expect(result2.diagnostics.length).toEqual(0); }); it('Throws when ML entity is disable (parseFile)', async () => { const fileContent = `# AskForName - {@userName=Jack} `; const diagnostics = await semanticValidate('a.lu', fileContent, { enableMLEntities: false }); expect(diagnostics.length).toEqual(1); const diagnostics2 = await semanticValidate('a.lu', fileContent, { enableMLEntities: true }); expect(diagnostics2.length).toEqual(0); }); }); describe('LU Check', () => { const diagnostics1 = checkSection({ Name: 'Greeting', Body: `- hi - hello`, }); expect(diagnostics1.length).toEqual(0); const diagnostics2 = checkSection({ Name: 'Greeting', Body: `- hi hello`, }); expect(diagnostics2.length).toEqual(1); expect(diagnostics2[0].range?.start.line).toEqual(3); }); describe('LU Section CRUD test', () => { const fileContent = `# Greeting - hi - hello # CheckEmail - check my email - show my emails `; const fileContentError1 = `# Greeting > not start with - hi - hello # CheckEmail - check my email - show my emails # Foo > nothing in body `; const fileId1 = 'a.lu'; const fileId2 = 'b.lu'; const luFeatures = {}; it('parse section test', () => { const luresource = parse(fileId1, fileContent, luFeatures, []).resource; const { Sections, Errors, Content } = luresource; expect(Content).toEqual(fileContent); expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[0].Errors.length).toEqual(0); expect(luresource.Sections[0].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(luresource.Sections[0].Name).toEqual('Greeting'); expect(luresource.Sections[0].UtteranceAndEntitiesMap.length).toEqual(2); expect(luresource.Sections[0].UtteranceAndEntitiesMap[0].utterance).toEqual('hi'); expect(luresource.Sections[0].UtteranceAndEntitiesMap[1].utterance).toEqual('hello'); }); it('parse section with syntax error test', () => { const luresource = parse(fileId2, fileContentError1, luFeatures, []).resource; const { Sections, Errors, Content } = luresource; expect(Content).toEqual(fileContentError1); expect(Errors.length).toEqual(2); expect(Sections.length).toEqual(3); expect(Sections[0].Errors.length).toEqual(1); expect(Sections[2].Errors.length).toEqual(1); }); it('parse section can get diagnostic line number', () => { const luFile = parse(fileId2, fileContentError1, luFeatures, []); const { intents, diagnostics, content } = luFile; expect(content).toEqual(fileContentError1); expect(intents.length).toEqual(3); expect(diagnostics.length).toEqual(2); expect(diagnostics[0].range?.start.line).toEqual(3); expect(diagnostics[0].range?.end.line).toEqual(3); expect(diagnostics[1].range?.start.line).toEqual(10); expect(diagnostics[1].range?.end.line).toEqual(10); }); it('add simpleIntentSection test', () => { const intent = { Name: 'CheckUnreadEmail', Body: `- check my unread email - show my unread emails`, }; const luFile1 = parse(fileId1, fileContent, luFeatures, []); const luFile1Updated = addIntent(luFile1, intent, luFeatures); const luresource = luParser.parse(luFile1Updated.content); const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(3); expect(Sections[2].Errors.length).toEqual(0); expect(luresource.Sections[2].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(luresource.Sections[2].Name).toEqual('CheckUnreadEmail'); expect(luresource.Sections[2].UtteranceAndEntitiesMap.length).toEqual(2); expect(luresource.Sections[2].UtteranceAndEntitiesMap[0].utterance).toEqual('check my unread email'); expect(luresource.Sections[2].UtteranceAndEntitiesMap[1].utterance).toEqual('show my unread emails'); }); it('update section test', () => { const intentName = 'CheckEmail'; const intent = { Name: 'CheckEmail', Body: `- check my email - show my emails - check my mail box please`, }; const intent2 = { Name: 'CheckEmail', Body: `- check my email - show my emails 2 - check my mail box please`, }; const luFile1 = parse(fileId1, fileContent, luFeatures, []); const updatedLuFile = updateIntent(luFile1, intentName, intent, luFeatures); const luresource = updatedLuFile.resource; const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[1].Errors.length).toEqual(0); expect(luresource.Sections[1].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(luresource.Sections[1].Name).toEqual('CheckEmail'); expect(luresource.Sections[1].UtteranceAndEntitiesMap.length).toEqual(3); expect(luresource.Sections[1].UtteranceAndEntitiesMap[0].utterance).toEqual('check my email'); expect(luresource.Sections[1].UtteranceAndEntitiesMap[1].utterance).toEqual('show my emails'); expect(luresource.Sections[1].UtteranceAndEntitiesMap[2].utterance).toEqual('check my mail box please'); // continue update on luresource const updatedLuFile2 = updateIntent(updatedLuFile, intentName, intent2, luFeatures); const luresource2 = updatedLuFile2.resource; expect(luresource2.Errors.length).toEqual(0); expect(luresource2.Sections.length).toEqual(2); expect(luresource2.Sections[1].Errors.length).toEqual(0); expect(luresource2.Sections[1].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(luresource2.Sections[1].Name).toEqual('CheckEmail'); expect(luresource2.Sections[1].UtteranceAndEntitiesMap.length).toEqual(3); expect(luresource2.Sections[1].UtteranceAndEntitiesMap[0].utterance).toEqual('check my email'); expect(luresource2.Sections[1].UtteranceAndEntitiesMap[1].utterance).toEqual('show my emails 2'); expect(luresource.Sections[1].UtteranceAndEntitiesMap[1].utterance).toEqual('show my emails'); // do not modify arguments expect(luresource2.Sections[1].UtteranceAndEntitiesMap[2].utterance).toEqual('check my mail box please'); }); it('update section with only name', () => { const intentName = 'CheckEmail'; const luFile1 = parse(fileId1, fileContent, luFeatures, []); const updatedLuFile = updateIntent(luFile1, intentName, { Name: 'CheckEmail1' }, luFeatures); const luresource = updatedLuFile.resource; const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[1].Errors.length).toEqual(0); expect(luresource.Sections[1].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(luresource.Sections[1].Name).toEqual('CheckEmail1'); expect(luresource.Sections[1].UtteranceAndEntitiesMap.length).toEqual(2); expect(luresource.Sections[1].UtteranceAndEntitiesMap[0].utterance).toEqual('check my email'); expect(luresource.Sections[1].UtteranceAndEntitiesMap[1].utterance).toEqual('show my emails'); }); it('update section with only body', () => { const intentName = 'CheckEmail'; const updatedBody = `- check my email - show my emails 2 - check my mail box please`; const luFile1 = parse(fileId1, fileContent, luFeatures, []); const updatedLuFile = updateIntent(luFile1, intentName, { Body: updatedBody }, luFeatures); const luresource = updatedLuFile.resource; const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[1].Errors.length).toEqual(0); expect(luresource.Sections[1].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(luresource.Sections[1].Name).toEqual('CheckEmail'); expect(luresource.Sections[1].UtteranceAndEntitiesMap.length).toEqual(3); expect(luresource.Sections[1].UtteranceAndEntitiesMap[0].utterance).toEqual('check my email'); expect(luresource.Sections[1].UtteranceAndEntitiesMap[1].utterance).toEqual('show my emails 2'); expect(luresource.Sections[1].UtteranceAndEntitiesMap[2].utterance).toEqual('check my mail box please'); }); it('update section with empty, should perform a remove', () => { const intentName = 'CheckEmail'; const luFile1 = parse(fileId1, fileContent, luFeatures, []); const updatedLuFile = updateIntent(luFile1, intentName, null, luFeatures); const luresource = updatedLuFile.resource; const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(1); }); it('update section with syntax error: missing -', () => { const intentName = 'CheckEmail'; const validFileContent = `#CheckEmail - check my email - show my emails`; const validIntent = { Name: 'CheckEmail', Body: `- check my email - show my emails `, }; const invalidIntent = { Name: 'CheckEmail', Body: `check my email - show my emails `, }; const luFile1 = parse('a.lu', validFileContent, luFeatures, []); // when intent invalid, after update can still be parsed const updatedContent2 = updateIntent(luFile1, intentName, invalidIntent, luFeatures).content; const updatedContent2Parsed = luParser.parse(updatedContent2); expect(updatedContent2Parsed.Sections.length).toEqual(1); expect(updatedContent2Parsed.Errors.length).toBeGreaterThan(0); // when file invalid, update with valid intent should fix error. const luFile2 = parse('a.lu', updatedContent2, luFeatures, []); const updatedContent3 = updateIntent(luFile2, intentName, validIntent, luFeatures).content; const updatedContent3Parsed = luParser.parse(updatedContent3); expect(updatedContent3Parsed.Sections.length).toEqual(1); expect(updatedContent3Parsed.Errors.length).toEqual(0); }); it('update section with syntax error: end with empty entity @', () => { const intentName = 'CheckEmail'; const validFileContent = `#CheckEmail - check my email - show my emails`; const invalidIntent = { Name: 'CheckEmail', Body: `- check my email - show my emails @`, }; const luFile1 = parse('a.lu', validFileContent, luFeatures, []); // when intent invalid, after update can still be parsed const updatedContent2 = updateIntent(luFile1, intentName, invalidIntent, luFeatures).content; const updatedContent2Parsed = luParser.parse(updatedContent2); expect(updatedContent2Parsed.Errors.length).toBeGreaterThan(0); // TODO: update back should fix error. // const updatedContent3 = updateIntent(updatedContent2, intentName, validIntent); // expect(updatedContent3).toEqual(validFileContent); }); it('update section with syntax error: include # IntentName in body', () => { const intentName = 'CheckEmail'; const validFileContent = `#CheckEmail - check my email - show my emails`; const invalidIntent = { Name: 'CheckEmail', Body: `- check my email - show my emails # UnexpectedIntentDefination `, }; const luFile1 = parse('a.lu', validFileContent, luFeatures, []); // should auto escape # to \# const updatedContent2 = updateIntent(luFile1, intentName, invalidIntent, luFeatures).content; const { Sections, Errors } = luParser.parse(updatedContent2); expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(1); expect(Sections[0].Errors.length).toEqual(0); expect(Sections[0].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(Sections[0].UtteranceAndEntitiesMap.length).toEqual(3); expect(Sections[0].UtteranceAndEntitiesMap[2].utterance).toEqual('\\# UnexpectedIntentDefination'); }); it('delete section test', () => { const intentName = 'CheckEmail'; const luFile1 = parse(fileId1, fileContent, luFeatures, []); const fileContentUpdated = removeIntent(luFile1, intentName, luFeatures).content; const luresource = luParser.parse(fileContentUpdated); const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(1); expect(Sections[0].Errors.length).toEqual(0); expect(luresource.Sections[0].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(luresource.Sections[0].Name).toEqual('Greeting'); }); }); describe('LU Nested Section CRUD test', () => { const fileContent = `> !# @enableSections = true # CheckTodo ## CheckUnreadTodo - check my unread todo - show my unread todos @ simple todoTitle ## CheckDeletedTodo - check my deleted todo - show my deleted todos @ simple todoSubject`; const fileId = 'a.lu'; const luFeatures = {}; it('update IntentSection test', () => { const intentName = 'CheckTodo'; const intent = { Name: 'CheckTodo', Body: `## CheckUnreadTodo - please check my unread todo - show my unread todos @ simple todoTitle `, }; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated = updateIntent(luFile1, intentName, intent, luFeatures); const result = luParser.parse(luFile1Updated.content); const { Sections, Errors } = result; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[0].SectionType).toEqual(luSectionTypes.MODELINFOSECTION); expect(Sections[1].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[1].Name).toEqual('CheckTodo'); expect(Sections[1].SimpleIntentSections.length).toEqual(1); }); it('parse Nested section test', () => { const luresource = luParser.parse(fileContent); const { Sections, Errors, Content } = luresource; expect(Content).toEqual(fileContent); expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[0].SectionType).toEqual(luSectionTypes.MODELINFOSECTION); expect(Sections[1].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[1].Name).toEqual('CheckTodo'); expect(Sections[1].SimpleIntentSections.length).toEqual(2); expect(Sections[1].SimpleIntentSections[0].Name).toEqual('CheckUnreadTodo'); expect(Sections[1].SimpleIntentSections[0].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(Sections[1].SimpleIntentSections[0].Errors.length).toEqual(0); expect(Sections[1].SimpleIntentSections[0].Entities.length).toEqual(1); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap.length).toEqual(2); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap[0].utterance).toEqual('check my unread todo'); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap[1].utterance).toEqual('show my unread todos'); }); it('add nestedIntentSection test', () => { const intent = { Name: 'CheckTodo/CheckCompletedTodo', Body: `- check my completed todo - show my completed todos @ simple todoTime `, }; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated = addIntent(luFile1, intent, luFeatures); const luresource = luParser.parse(luFile1Updated.content); const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[0].SectionType).toEqual(luSectionTypes.MODELINFOSECTION); expect(Sections[1].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[1].Name).toEqual('CheckTodo'); expect(Sections[1].SimpleIntentSections.length).toEqual(3); expect(Sections[1].SimpleIntentSections[2].Name).toEqual('CheckCompletedTodo'); expect(Sections[1].SimpleIntentSections[2].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(Sections[1].SimpleIntentSections[2].Errors.length).toEqual(0); expect(Sections[1].SimpleIntentSections[2].Entities.length).toEqual(1); expect(Sections[1].SimpleIntentSections[2].Entities[0].Name).toEqual('todoTime'); expect(Sections[1].SimpleIntentSections[2].UtteranceAndEntitiesMap.length).toEqual(2); expect(Sections[1].SimpleIntentSections[2].UtteranceAndEntitiesMap[0].utterance).toEqual('check my completed todo'); expect(Sections[1].SimpleIntentSections[2].UtteranceAndEntitiesMap[1].utterance).toEqual('show my completed todos'); }); it('add nestedIntentSection test, recursive', () => { const intent = { Name: 'CheckMyTodo/CheckCompletedTodo', Body: `- check my completed todo - show my completed todos @ simple todoTime `, }; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated = addIntent(luFile1, intent, luFeatures); const luresource = luParser.parse(luFile1Updated.content); const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(3); expect(Sections[0].SectionType).toEqual(luSectionTypes.MODELINFOSECTION); expect(Sections[1].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[2].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[2].Name).toEqual('CheckMyTodo'); expect(Sections[2].SimpleIntentSections.length).toEqual(1); expect(Sections[2].SimpleIntentSections[0].Name).toEqual('CheckCompletedTodo'); expect(Sections[2].SimpleIntentSections[0].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(Sections[2].SimpleIntentSections[0].Errors.length).toEqual(0); expect(Sections[2].SimpleIntentSections[0].Entities.length).toEqual(1); expect(Sections[2].SimpleIntentSections[0].Entities[0].Name).toEqual('todoTime'); expect(Sections[2].SimpleIntentSections[0].UtteranceAndEntitiesMap.length).toEqual(2); expect(Sections[2].SimpleIntentSections[0].UtteranceAndEntitiesMap[0].utterance).toEqual('check my completed todo'); expect(Sections[2].SimpleIntentSections[0].UtteranceAndEntitiesMap[1].utterance).toEqual('show my completed todos'); }); it('update nestedIntentSection test', () => { const intentName = 'CheckTodo/CheckUnreadTodo'; const intent = { Name: 'CheckMyUnreadTodo', Body: `- please check my unread todo - please show my unread todos @ simple todoTitle @ simple todoContent `, }; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated = updateIntent(luFile1, intentName, intent, luFeatures); const luresource = luParser.parse(luFile1Updated.content); const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[0].SectionType).toEqual(luSectionTypes.MODELINFOSECTION); expect(Sections[1].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[1].Name).toEqual('CheckTodo'); expect(Sections[1].SimpleIntentSections.length).toEqual(2); expect(Sections[1].SimpleIntentSections[0].Name).toEqual('CheckMyUnreadTodo'); expect(Sections[1].SimpleIntentSections[0].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(Sections[1].SimpleIntentSections[0].Errors.length).toEqual(0); expect(Sections[1].SimpleIntentSections[0].Entities.length).toEqual(2); expect(Sections[1].SimpleIntentSections[0].Entities[1].Name).toEqual('todoContent'); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap.length).toEqual(2); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap[0].utterance).toEqual( 'please check my unread todo' ); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap[1].utterance).toEqual( 'please show my unread todos' ); }); it('update nestedIntentSection and escape # in body', () => { const intentName = 'CheckTodo/CheckUnreadTodo'; const intent = { Name: 'CheckMyUnreadTodo', Body: `- please check my unread todo - please show my unread todos # Oops ## Oops @ simple todoTitle @ simple todoContent `, }; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated = updateIntent(luFile1, intentName, intent, luFeatures); const luresource = luParser.parse(luFile1Updated.content); const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[0].SectionType).toEqual(luSectionTypes.MODELINFOSECTION); expect(Sections[1].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[1].Name).toEqual('CheckTodo'); expect(Sections[1].SimpleIntentSections.length).toEqual(2); expect(Sections[1].SimpleIntentSections[0].Name).toEqual('CheckMyUnreadTodo'); expect(Sections[1].SimpleIntentSections[0].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(Sections[1].SimpleIntentSections[0].Errors.length).toEqual(0); expect(Sections[1].SimpleIntentSections[0].Entities.length).toEqual(2); expect(Sections[1].SimpleIntentSections[0].Entities[1].Name).toEqual('todoContent'); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap.length).toEqual(4); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap[0].utterance).toEqual( 'please check my unread todo' ); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap[2].utterance).toEqual('\\# Oops'); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap[3].utterance).toEqual('\\## Oops'); }); it('update nestedIntentSection with # ## ### in body', () => { const intentName = 'CheckTodo'; const intentBody1 = `# Oops ## Oops ### Oops `; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated1 = updateIntent(luFile1, intentName, { Name: intentName, Body: intentBody1 }, luFeatures); const luresource1 = luParser.parse(luFile1Updated1.content); expect(luresource1.Sections.length).toBeGreaterThan(0); expect(luresource1.Errors.length).toBeGreaterThan(0); const intentBody2 = `## Oops ### Oops `; const luFile1Updated2 = updateIntent(luFile1, intentName, { Name: intentName, Body: intentBody2 }, luFeatures); const luresource2 = luParser.parse(luFile1Updated2.content); expect(luresource2.Sections.length).toEqual(3); expect(luresource2.Errors.length).toBeGreaterThan(0); expect(luresource2.Sections[0].SectionType).toEqual(luSectionTypes.MODELINFOSECTION); expect(luresource2.Sections[1].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); // if nestedSection not enable const fileContent3 = `# Greeting - hi # CheckTodo - please check my todo `; const intentBody3 = `## Oops ### Oops `; const luFile2 = parse(fileId, fileContent3, luFeatures, []); const luFile1Updated3 = updateIntent(luFile2, intentName, { Name: intentName, Body: intentBody3 }, luFeatures); const luresource3 = luParser.parse(luFile1Updated3.content); expect(luresource3.Sections.length).toBeGreaterThan(0); expect(luresource3.Errors.length).toBeGreaterThan(0); }); /** * this will add #CheckMyTodo * in #CheckMyTodo, ##CheckUnreadTodo not exist, then will do add ##CheckMyUnreadTodo */ it('update nestedIntentSection test, recursive', () => { const intentName = 'CheckMyTodo/CheckUnreadTodo'; const intent = { Name: 'CheckMyUnreadTodo', Body: `- please check my unread todo - please show my unread todos @ simple todoContent `, }; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated = updateIntent(luFile1, intentName, intent, luFeatures); const luresource = luParser.parse(luFile1Updated.content); const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(3); expect(Sections[0].SectionType).toEqual(luSectionTypes.MODELINFOSECTION); expect(Sections[1].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[2].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[2].Name).toEqual('CheckMyTodo'); expect(Sections[2].SimpleIntentSections.length).toEqual(1); expect(Sections[2].SimpleIntentSections[0].Name).toEqual('CheckMyUnreadTodo'); expect(Sections[2].SimpleIntentSections[0].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(Sections[2].SimpleIntentSections[0].Errors.length).toEqual(0); expect(Sections[2].SimpleIntentSections[0].Entities.length).toEqual(1); expect(Sections[2].SimpleIntentSections[0].Entities[0].Name).toEqual('todoContent'); expect(Sections[2].SimpleIntentSections[0].UtteranceAndEntitiesMap.length).toEqual(2); expect(Sections[2].SimpleIntentSections[0].UtteranceAndEntitiesMap[0].utterance).toEqual( 'please check my unread todo' ); expect(Sections[2].SimpleIntentSections[0].UtteranceAndEntitiesMap[1].utterance).toEqual( 'please show my unread todos' ); }); it('delete nestedIntentSection test', () => { const Name = 'CheckTodo/CheckUnreadTodo'; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated = removeIntent(luFile1, Name, luFeatures); const luresource = luParser.parse(luFile1Updated.content); const { Sections, Errors } = luresource; expect(Errors.length).toEqual(0); expect(Sections.length).toEqual(2); expect(Sections[0].SectionType).toEqual(luSectionTypes.MODELINFOSECTION); expect(Sections[1].SectionType).toEqual(luSectionTypes.NESTEDINTENTSECTION); expect(Sections[1].Name).toEqual('CheckTodo'); expect(Sections[1].SimpleIntentSections.length).toEqual(1); expect(Sections[1].SimpleIntentSections[0].Name).toEqual('CheckDeletedTodo'); expect(Sections[1].SimpleIntentSections[0].SectionType).toEqual(luSectionTypes.SIMPLEINTENTSECTION); expect(Sections[1].SimpleIntentSections[0].Errors.length).toEqual(0); expect(Sections[1].SimpleIntentSections[0].Entities.length).toEqual(1); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap.length).toEqual(2); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap[0].utterance).toEqual('check my deleted todo'); expect(Sections[1].SimpleIntentSections[0].UtteranceAndEntitiesMap[1].utterance).toEqual('show my deleted todos'); }); it('delete nestedIntentSection test, parrent not exist', () => { const Name = 'CheckTodoNotExist/CheckUnreadTodo'; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated = removeIntent(luFile1, Name, luFeatures); const luresource = luParser.parse(luFile1Updated.content); const { Content } = luresource; expect(Content).toEqual(fileContent); }); it('delete nestedIntentSection test, child not exist', () => { const Name = 'CheckTodo/CheckUnreadTodoNotExist'; const luFile1 = parse(fileId, fileContent, luFeatures, []); const luFile1Updated = removeIntent(luFile1, Name, luFeatures); const luresource = luParser.parse(luFile1Updated.content); const { Content } = luresource; expect(Content).toEqual(fileContent); }); });
the_stack
import * as Generator from 'yeoman-generator'; import { kebabCase } from 'lodash'; import * as fs from 'fs'; import * as path from 'path'; import * as colors from 'colors'; import * as yosay from 'yosay'; import * as dargs from 'dargs'; import { Utils } from './scripts/utils'; import { npmDependencies, presetDependencies } from './scripts/install'; import { promptQuestions, promptAdditionalQuestions } from './scripts/prompts'; import * as configurators from './scripts/configs'; import { IGeneratorData, IAppConfig } from './scripts/interfaces'; module.exports = class extends Generator { private data: IGeneratorData = {}; private utils: Utils; private packageData: any; private existingProject: boolean = false; private isAngularProject: boolean = false; private headless: boolean; private skipNpmInstall: boolean; constructor(args, options) { super(args, options); this.utils = new Utils({ yo: this }); this.headless = process.argv.slice(2).indexOf('--headless') !== -1; this.skipNpmInstall = process.argv.slice(2).indexOf('--skip-npm-install') !== -1; // Custom options this.option('package-manager', { description: 'preferred package manager (npm, yarn, pnpm)', type: String, alias: 'pm', default: 'npm' }); } public initializing() { this.data.sppp = require(path.join(__dirname, '../package.json')); const spppVersion = this.data && this.data.sppp && this.data.sppp.version || 'unknown'; this.log(yosay(`Welcome to ${colors.yellow('SharePoint Pull-n-Push')} generator (v.${spppVersion})!`)); this.appname = kebabCase(this.appname); this.appname = this.appname || this.config.get('appname') || 'sharepoint-app'; this.config.set('app.name', this.appname); this.config.set('sppp.version', spppVersion); this.config.save(); // Check for existing project (() => { const packagePath: string = this.utils.resolveDestPath('package.json'); if (fs.existsSync(packagePath)) { this.existingProject = true; this.packageData = require(packagePath); } const angularCliPath: string = this.utils.resolveDestPath('.angular-cli.json'); if (fs.existsSync(angularCliPath)) { this.log(`\n${colors.yellow.bold('Angular project is detected, SPPP will be installed above safely.\n')}`); this.isAngularProject = true; } })(); } public prompting() { const done = (this as any).async(); if (this.headless) { return done(); } (async () => { // Step 1: General parameters await promptQuestions(this.data, this).then((answers) => { this.data.answers = { ...this.data.answers, ...answers }; }); // Step 2: Additional questions await promptAdditionalQuestions(this.data, this).then((answers) => { if (answers.additional) { let presets = answers.additional.presets || []; if (presets.indexOf('fluentui') !== -1 && presets.indexOf('react') === -1) { presets = [ 'react', ...presets ]; } answers.additional = { ...answers.additional, presets }; } this.data.answers = { ...this.data.answers, ...answers }; }); done(); })() .catch((error) => this.log(`\n${colors.red.bold(error.message)}\n`)); } public configuring() { if (!this.headless) { // no answers in headless mode, all the data is taken from .yo-rc.json automatically this.config.set('app.name', this.data.answers && this.data.answers.name); this.config.set('app.description', this.data.answers && this.data.answers.description); this.config.set('app.author', this.data.answers && this.data.answers.author); this.config.set('conf.spFolder', this.data.answers && this.data.answers.spFolder); this.config.set('conf.distFolder', this.data.answers && this.data.answers.distFolder); const additional = this.data.answers && this.data.answers.additional ? this.data.answers.additional : []; Object.keys(additional).forEach((key) => this.config.set(`conf.additional.${key}`, additional[key])); this.config.save(); } else { // automaticaly feel in answers from .yo-rc.json in CI mode const config = this.config.getAll(); this.data.answers = { name: config['app.name'], description: config['app.description'], author: config['app.author'], spFolder: config['conf.spFolder'], distFolder: config['conf.distFolder'], additional: Object.keys(config) .filter((key) => key.indexOf('conf.additional.') !== -1) .reduce((res, key) => { res[key.replace('conf.additional.', '')] = config[key]; return res; }, {} as any) }; } } public writing() { this.log(`\n${colors.yellow.bold('Writing files')}`); if (!this.existingProject) { this.utils.writeJsonSync('package.json', configurators.packageJson(this.data)); } const appJson: IAppConfig = configurators.configAppJson(this.data); // if (this.data.answers && this.data.answers.additional && this.data.answers.additional.presets.indexOf('react') !== -1) { // appJson.copyAssetsMap = [ // ...appJson.copyAssetsMap || [], { // name: 'React', // src: [ // './node_modules/react/umd/react.production.min.js', // './node_modules/react-dom/umd/react-dom.production.min.js' // ], // dist: './dist/libs' // } // ]; // } this.utils.writeJsonSync('config/app.json', appJson); this.utils.writeJsonSync('tsconfig.json', configurators.tsconfigJson(this.data)); this.utils.writeJsonSync('tslint.json', configurators.tslintJson(this.data)); this.utils.copyFile('gulpfile.js', null, true); this.utils.copyFile('gitignore', '.gitignore'); this.utils.copyFile('env', '.env'); this.utils.copyFile('webpack.config.js'); if (this.data.answers && this.data.answers.additional && this.data.answers.additional.customTasks) { this.utils.copyFile('tools/tasks/example.js'); this.utils.copyFile('tools/tasks/customDataLoader.js'); } // Ignore folder structure for Angular project if (!this.isAngularProject) { this.utils.createFolder('src/scripts'); this.utils.createFolder('src/libs'); this.utils.createFolder('src/styles'); this.utils.createFolder('src/fonts'); this.utils.createFolder('src/images'); this.utils.createFolder('src/masterpage/layouts'); this.utils.createFolder('src/webparts'); this.utils.createFolder('dist'); this.utils.copyFolder('src', 'src'); if (this.data.answers && this.data.answers.additional) { // Presets const presets = this.data.answers.additional.presets || []; if (presets.indexOf('react') !== -1) { this.utils.copyFolder('presets/react', 'src'); } if (presets.indexOf('fluentui') !== -1) { this.utils.copyFolder('presets/react', 'src'); this.utils.copyFolder('presets/fluentui', 'src'); } // Secondary presets const confPresets = this.data.answers.additional.confPresets || []; if (confPresets.indexOf('eslint') !== -1) { // this.utils.copyFolder('presets/eslint', 'src'); this.utils.writeJsonSync('.eslintrc', configurators.eslintJson(this.data)); } if (confPresets.indexOf('prettier') !== -1) { this.utils.writeJsonSync('.prettierrc', configurators.prettierJson(this.data)); } if (confPresets.indexOf('editorconfig') !== -1) { this.utils.copyFile('editorconfig', '.editorconfig'); } } } this.utils.copyFolder('vscode', '.vscode'); if (this.data.answers && this.data.answers.additional && this.data.answers.additional.sslCerts) { this.utils.copyFolder('config/ssl', 'config/ssl'); } this.log(`${colors.green('Done writing')}`); } public install() { this.log(`\n${colors.yellow.bold('Installing dependencies')}\n`); const done = (this as any).async(); if (this.isAngularProject) { // Add dependency for Angular project npmDependencies.devDependencies ? npmDependencies.devDependencies.push('concurrently') : npmDependencies.devDependencies = ['concurrently']; // Add angular tasks this.packageData.scripts.spdev = 'concurrently --kill-others \"ng build --watch\" \"gulp watch\"'; this.utils.writeJsonSync('package.json', this.packageData, true); } (async () => { let next = true; let installer: any = null; let depOptions: any = null; let devDepOptions: any = null; depOptions = { 'save': true }; if (this.options['package-manager'] === 'pnpm') { next && await this.utils.execPromise('pnpm --version').then(() => { installer = (dep: string | string[], opt: any) => { opt = { ...opt, 'shamefully-hoist': true }; const args = ['add'].concat(dep).concat(dargs(opt)); this.spawnCommandSync('pnpm', args); }; devDepOptions = { 'save-dev': true }; next = false; }).catch(() => next = true); } if (this.options['package-manager'] === 'yarn') { next && await this.utils.execPromise('yarn --version').then(() => { installer = this.yarnInstall.bind(this); devDepOptions = { 'dev': true }; next = false; }).catch(() => next = true); } next && (() => { installer = this.npmInstall.bind(this); devDepOptions = { 'save-dev': true }; })(); let dependencies = npmDependencies.dependencies || []; let devDependencies = npmDependencies.devDependencies || []; const presets = [ ...this.data.answers && this.data.answers.additional && this.data.answers.additional.presets || [], ...this.data.answers && this.data.answers.additional && this.data.answers.additional.confPresets || [] ]; presets.forEach((preset) => { // tslint:disable-next-line: strict-type-predicates if (typeof presetDependencies[preset] !== 'undefined') { const { dependencies: dep, devDependencies: devDep } = presetDependencies[preset]; if (dep) { dependencies = [ ...dependencies, ...dep ]; } if (devDep) { devDependencies = [ ...devDependencies, ...devDep ]; } } }); const mapDep = (dep: string | [ string, string ]): string => { return typeof dep === 'string' ? dep : dep.join('@'); }; const pkgJson = this.utils.readJsonSync('package.json'); if (pkgJson) { const reduceDependencies = (res: any = {}, dep: string | [ string, string ]): any => { if (typeof dep === 'string') { res[dep] = 'latest'; } if (Array.isArray(dep) && dep.length === 2) { res[dep[0]] = dep[1]; } return res; }; pkgJson.dependencies = { ...(pkgJson.dependencies || {}), ...dependencies.reduce(reduceDependencies, {}) }; pkgJson.devDependencies = { ...(pkgJson.devDependencies || {}), ...devDependencies.reduce(reduceDependencies, {}) }; this.utils.writeJsonSync('package.json', pkgJson, true); } if (!this.skipNpmInstall) { installer(dependencies.map(mapDep), depOptions); installer(devDependencies.map(mapDep), devDepOptions); } done(); })() .catch((error) => this.log(`\n${colors.red.bold(error.message)}\n`)); } public end() { this.log(`\n${colors.yellow.bold('Installation successful!')}`); this.log(`\n${colors.gray(`Run \`${colors.blue.bold('npm run config')}\` to configure SharePoint connection.`)}`); } };
the_stack
declare module Microsoft.Win32.SafeHandles { export class SafeHandleZeroOrMinusOneIsInvalid extends System.Runtime.InteropServices.SafeHandle { IsInvalid: boolean; } export class SafeWaitHandle extends Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid { ReleaseHandle(): boolean; //{ throw new Error("Not implemented.");} } } declare module System { export class Array { Length: number; LongLength: number; Rank: number; private System.Collections.ICollection.Count: number; SyncRoot: any; IsReadOnly: boolean; IsFixedSize: boolean; IsSynchronized: boolean; private System.Collections.IList.Item: any; AsReadOnly(array: any): any; //{ throw new Error("Not implemented.");} BinarySearch(array: any, index: number, length: number, value: any): number; //{ throw new Error("Not implemented.");} BinarySearch(array: any, value: any): number; //{ throw new Error("Not implemented.");} BinarySearch(array: any, value: any, comparer: any): number; //{ throw new Error("Not implemented.");} BinarySearch(array: any, index: number, length: number, value: any, comparer: any): number; //{ throw new Error("Not implemented.");} BinarySearch(array: System.Array, value: any): number; //{ throw new Error("Not implemented.");} BinarySearch(array: System.Array, index: number, length: number, value: any): number; //{ throw new Error("Not implemented.");} BinarySearch(array: System.Array, value: any, comparer: System.Collections.IComparer): number; //{ throw new Error("Not implemented.");} BinarySearch(array: System.Array, index: number, length: number, value: any, comparer: System.Collections.IComparer): number; //{ throw new Error("Not implemented.");} Clear(array: System.Array, index: number, length: number): any; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} CombineHashCodes(h1: number, h2: number): number; //{ throw new Error("Not implemented.");} ConstrainedCopy(sourceArray: System.Array, sourceIndex: number, destinationArray: System.Array, destinationIndex: number, length: number): any; //{ throw new Error("Not implemented.");} ConvertAll(array: any, converter: any): any; //{ throw new Error("Not implemented.");} Copy(sourceArray: System.Array, destinationArray: System.Array, length: number): any; //{ throw new Error("Not implemented.");} Copy(sourceArray: System.Array, sourceIndex: number, destinationArray: System.Array, destinationIndex: number, length: number): any; //{ throw new Error("Not implemented.");} Copy(sourceArray: System.Array, sourceIndex: number, destinationArray: System.Array, destinationIndex: number, length: number, reliable: boolean): any; //{ throw new Error("Not implemented.");} Copy(sourceArray: System.Array, destinationArray: System.Array, length: number): any; //{ throw new Error("Not implemented.");} Copy(sourceArray: System.Array, sourceIndex: number, destinationArray: System.Array, destinationIndex: number, length: number): any; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array, index: number): any; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array, index: number): any; //{ throw new Error("Not implemented.");} CreateInstance(elementType: System.Type, length: number): System.Array; //{ throw new Error("Not implemented.");} CreateInstance(elementType: System.Type, lengths: System.Int32[], lowerBounds: System.Int32[]): System.Array; //{ throw new Error("Not implemented.");} CreateInstance(elementType: System.Type, lengths: any): System.Array; //{ throw new Error("Not implemented.");} CreateInstance(elementType: System.Type, length1: number, length2: number, length3: number): System.Array; //{ throw new Error("Not implemented.");} CreateInstance(elementType: System.Type, lengths: System.Int32[]): System.Array; //{ throw new Error("Not implemented.");} CreateInstance(elementType: System.Type, length1: number, length2: number): System.Array; //{ throw new Error("Not implemented.");} Exists(array: any, match: any): boolean; //{ throw new Error("Not implemented.");} Find(array: any, match: any): any; //{ throw new Error("Not implemented.");} FindAll(array: any, match: any): any; //{ throw new Error("Not implemented.");} FindIndex(array: any, startIndex: number, count: number, match: any): number; //{ throw new Error("Not implemented.");} FindIndex(array: any, match: any): number; //{ throw new Error("Not implemented.");} FindIndex(array: any, startIndex: number, match: any): number; //{ throw new Error("Not implemented.");} FindLast(array: any, match: any): any; //{ throw new Error("Not implemented.");} FindLastIndex(array: any, startIndex: number, count: number, match: any): number; //{ throw new Error("Not implemented.");} FindLastIndex(array: any, startIndex: number, match: any): number; //{ throw new Error("Not implemented.");} FindLastIndex(array: any, match: any): number; //{ throw new Error("Not implemented.");} ForEach(array: any, action: any): any; //{ throw new Error("Not implemented.");} GetDataPtrOffsetInternal(): number; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetLength(dimension: number): number; //{ throw new Error("Not implemented.");} GetLongLength(dimension: number): number; //{ throw new Error("Not implemented.");} GetLowerBound(dimension: number): number; //{ throw new Error("Not implemented.");} GetMedian(low: number, hi: number): number; //{ throw new Error("Not implemented.");} GetUpperBound(dimension: number): number; //{ throw new Error("Not implemented.");} GetValue(indices: System.Int32[]): any; //{ throw new Error("Not implemented.");} GetValue(index: number): any; //{ throw new Error("Not implemented.");} GetValue(index1: number, index2: number): any; //{ throw new Error("Not implemented.");} GetValue(index: number): any; //{ throw new Error("Not implemented.");} GetValue(index1: number, index2: number, index3: number): any; //{ throw new Error("Not implemented.");} GetValue(index1: number, index2: number, index3: number): any; //{ throw new Error("Not implemented.");} GetValue(indices: any): any; //{ throw new Error("Not implemented.");} GetValue(index1: number, index2: number): any; //{ throw new Error("Not implemented.");} IndexOf(array: System.Array, value: any, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} IndexOf(array: System.Array, value: any, startIndex: number): number; //{ throw new Error("Not implemented.");} IndexOf(array: any, value: any): number; //{ throw new Error("Not implemented.");} IndexOf(array: any, value: any, startIndex: number): number; //{ throw new Error("Not implemented.");} IndexOf(array: any, value: any, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} IndexOf(array: System.Array, value: any): number; //{ throw new Error("Not implemented.");} Initialize(): any; //{ throw new Error("Not implemented.");} InternalCreate(elementType: any, rank: number, pLengths: any, pLowerBounds: any): System.Array; //{ throw new Error("Not implemented.");} InternalGetReference(elemRef: any, rank: number, pIndices: any): any; //{ throw new Error("Not implemented.");} InternalSetValue(target: any, value: any): any; //{ throw new Error("Not implemented.");} LastIndexOf(array: any, value: any, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} LastIndexOf(array: any, value: any): number; //{ throw new Error("Not implemented.");} LastIndexOf(array: System.Array, value: any, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} LastIndexOf(array: System.Array, value: any, startIndex: number): number; //{ throw new Error("Not implemented.");} LastIndexOf(array: System.Array, value: any): number; //{ throw new Error("Not implemented.");} LastIndexOf(array: any, value: any, startIndex: number): number; //{ throw new Error("Not implemented.");} Resize(array: any, newSize: number): any; //{ throw new Error("Not implemented.");} Reverse(array: System.Array, index: number, length: number): any; //{ throw new Error("Not implemented.");} Reverse(array: System.Array): any; //{ throw new Error("Not implemented.");} SetValue(value: any, indices: any): any; //{ throw new Error("Not implemented.");} SetValue(value: any, index: number): any; //{ throw new Error("Not implemented.");} SetValue(value: any, index1: number, index2: number): any; //{ throw new Error("Not implemented.");} SetValue(value: any, index1: number, index2: number, index3: number): any; //{ throw new Error("Not implemented.");} SetValue(value: any, indices: System.Int32[]): any; //{ throw new Error("Not implemented.");} SetValue(value: any, index: number): any; //{ throw new Error("Not implemented.");} SetValue(value: any, index1: number, index2: number): any; //{ throw new Error("Not implemented.");} SetValue(value: any, index1: number, index2: number, index3: number): any; //{ throw new Error("Not implemented.");} Sort(keys: System.Array, items: System.Array): any; //{ throw new Error("Not implemented.");} Sort(array: System.Array): any; //{ throw new Error("Not implemented.");} Sort(keys: any, items: any, index: number, length: number): any; //{ throw new Error("Not implemented.");} Sort(array: System.Array, comparer: System.Collections.IComparer): any; //{ throw new Error("Not implemented.");} Sort(keys: System.Array, items: System.Array, comparer: System.Collections.IComparer): any; //{ throw new Error("Not implemented.");} Sort(array: System.Array, index: number, length: number, comparer: System.Collections.IComparer): any; //{ throw new Error("Not implemented.");} Sort(keys: System.Array, items: System.Array, index: number, length: number, comparer: System.Collections.IComparer): any; //{ throw new Error("Not implemented.");} Sort(array: any, index: number, length: number): any; //{ throw new Error("Not implemented.");} Sort(array: System.Array, index: number, length: number): any; //{ throw new Error("Not implemented.");} Sort(keys: System.Array, items: System.Array, index: number, length: number): any; //{ throw new Error("Not implemented.");} Sort(array: any, index: number, length: number, comparer: any): any; //{ throw new Error("Not implemented.");} Sort(keys: any, items: any, comparer: any): any; //{ throw new Error("Not implemented.");} Sort(array: any): any; //{ throw new Error("Not implemented.");} Sort(keys: any, items: any, index: number, length: number, comparer: any): any; //{ throw new Error("Not implemented.");} Sort(array: any, comparison: any): any; //{ throw new Error("Not implemented.");} Sort(array: any, comparer: any): any; //{ throw new Error("Not implemented.");} Sort(keys: any, items: any): any; //{ throw new Error("Not implemented.");} TrueForAll(array: any, match: any): boolean; //{ throw new Error("Not implemented.");} TrySZBinarySearch(sourceArray: System.Array, sourceIndex: number, count: number, value: any, retVal: any): boolean; //{ throw new Error("Not implemented.");} TrySZIndexOf(sourceArray: System.Array, sourceIndex: number, count: number, value: any, retVal: any): boolean; //{ throw new Error("Not implemented.");} TrySZLastIndexOf(sourceArray: System.Array, sourceIndex: number, count: number, value: any, retVal: any): boolean; //{ throw new Error("Not implemented.");} TrySZReverse(array: System.Array, index: number, count: number): boolean; //{ throw new Error("Not implemented.");} TrySZSort(keys: System.Array, items: System.Array, left: number, right: number): boolean; //{ throw new Error("Not implemented.");} UnsafeCreateInstance(elementType: System.Type, length1: number, length2: number): System.Array; //{ throw new Error("Not implemented.");} UnsafeCreateInstance(elementType: System.Type, lengths: System.Int32[]): System.Array; //{ throw new Error("Not implemented.");} UnsafeCreateInstance(elementType: System.Type, length: number): System.Array; //{ throw new Error("Not implemented.");} UnsafeCreateInstance(elementType: System.Type, lengths: System.Int32[], lowerBounds: System.Int32[]): System.Array; //{ throw new Error("Not implemented.");} } export class AsyncCallback extends System.MulticastDelegate { BeginInvoke(ar: System.IAsyncResult, callback: System.AsyncCallback, object: any): System.IAsyncResult; //{ throw new Error("Not implemented.");} EndInvoke(result: System.IAsyncResult): any; //{ throw new Error("Not implemented.");} Invoke(ar: System.IAsyncResult): any; //{ throw new Error("Not implemented.");} } export class Attribute { TypeId: any; AddAttributesToList(attributeList: System.Collections.Generic.List<T>, attributes: any, types: System.Collections.Generic.Dictionary<TKey, TValue>): any; //{ throw new Error("Not implemented.");} AreFieldValuesEqual(thisValue: any, thatValue: any): boolean; //{ throw new Error("Not implemented.");} CopyToArrayList(attributeList: System.Collections.Generic.List<T>, attributes: any, types: System.Collections.Generic.Dictionary<TKey, TValue>): any; //{ throw new Error("Not implemented.");} CreateAttributeArrayHelper(elementType: System.Type, elementCount: number): any; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetCustomAttribute(element: System.Reflection.Assembly, attributeType: System.Type, inherit: boolean): System.Attribute; //{ throw new Error("Not implemented.");} GetCustomAttribute(element: System.Reflection.Assembly, attributeType: System.Type): System.Attribute; //{ throw new Error("Not implemented.");} GetCustomAttribute(element: System.Reflection.MemberInfo, attributeType: System.Type): System.Attribute; //{ throw new Error("Not implemented.");} GetCustomAttribute(element: System.Reflection.MemberInfo, attributeType: System.Type, inherit: boolean): System.Attribute; //{ throw new Error("Not implemented.");} GetCustomAttribute(element: System.Reflection.ParameterInfo, attributeType: System.Type, inherit: boolean): System.Attribute; //{ throw new Error("Not implemented.");} GetCustomAttribute(element: System.Reflection.ParameterInfo, attributeType: System.Type): System.Attribute; //{ throw new Error("Not implemented.");} GetCustomAttribute(element: System.Reflection.Module, attributeType: System.Type): System.Attribute; //{ throw new Error("Not implemented.");} GetCustomAttribute(element: System.Reflection.Module, attributeType: System.Type, inherit: boolean): System.Attribute; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.Assembly, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.Assembly, attributeType: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.Module, attributeType: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.Assembly, attributeType: System.Type): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.Module, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.Assembly): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.Module, attributeType: System.Type): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.MemberInfo, type: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.MemberInfo): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.Module): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.MemberInfo, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.ParameterInfo): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.ParameterInfo, attributeType: System.Type): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.MemberInfo, type: System.Type): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.ParameterInfo, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(element: System.Reflection.ParameterInfo, attributeType: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetParentDefinition(param: System.Reflection.ParameterInfo): System.Reflection.ParameterInfo; //{ throw new Error("Not implemented.");} GetParentDefinition(ev: System.Reflection.EventInfo): System.Reflection.EventInfo; //{ throw new Error("Not implemented.");} GetParentDefinition(property: System.Reflection.PropertyInfo): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} InternalGetAttributeUsage(type: System.Type): any; //{ throw new Error("Not implemented.");} InternalGetCustomAttributes(element: System.Reflection.EventInfo, type: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} InternalGetCustomAttributes(element: System.Reflection.PropertyInfo, type: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} InternalIsDefined(element: System.Reflection.PropertyInfo, attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} InternalIsDefined(element: System.Reflection.EventInfo, attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} InternalParamGetCustomAttributes(param: System.Reflection.ParameterInfo, type: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} InternalParamIsDefined(param: System.Reflection.ParameterInfo, type: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} IsDefaultAttribute(): boolean; //{ throw new Error("Not implemented.");} IsDefined(element: System.Reflection.ParameterInfo, attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} IsDefined(element: System.Reflection.Assembly, attributeType: System.Type): boolean; //{ throw new Error("Not implemented.");} IsDefined(element: System.Reflection.Module, attributeType: System.Type): boolean; //{ throw new Error("Not implemented.");} IsDefined(element: System.Reflection.Module, attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} IsDefined(element: System.Reflection.Assembly, attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} IsDefined(element: System.Reflection.MemberInfo, attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} IsDefined(element: System.Reflection.ParameterInfo, attributeType: System.Type): boolean; //{ throw new Error("Not implemented.");} IsDefined(element: System.Reflection.MemberInfo, attributeType: System.Type): boolean; //{ throw new Error("Not implemented.");} Match(obj: any): boolean; //{ throw new Error("Not implemented.");} } export class Delegate { Method: System.Reflection.MethodInfo; Target: any; _target: any; _methodBase: any; _methodPtr: number; _methodPtrAux: number; AdjustTarget(target: any, methodPtr: number): number; //{ throw new Error("Not implemented.");} BindToMethodInfo(target: any, method: any, methodType: any, flags: System.DelegateBindingFlags): boolean; //{ throw new Error("Not implemented.");} BindToMethodName(target: any, methodType: any, method: string, flags: System.DelegateBindingFlags): boolean; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} Combine(a: System.Delegate, b: System.Delegate): System.Delegate; //{ throw new Error("Not implemented.");} Combine(delegates: any): System.Delegate; //{ throw new Error("Not implemented.");} CombineImpl(d: System.Delegate): System.Delegate; //{ throw new Error("Not implemented.");} CompareUnmanagedFunctionPtrs(d1: System.Delegate, d2: System.Delegate): boolean; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, target: System.Type, method: string, ignoreCase: boolean, throwOnBindFailure: boolean): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, target: System.Type, method: string, ignoreCase: boolean): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, target: System.Type, method: string): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, target: any, method: string, ignoreCase: boolean, throwOnBindFailure: boolean): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, target: any, method: string, ignoreCase: boolean): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, firstArgument: any, method: System.Reflection.MethodInfo): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, method: System.Reflection.MethodInfo, throwOnBindFailure: boolean): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, method: System.Reflection.MethodInfo): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, target: any, method: string): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(type: System.Type, firstArgument: any, method: System.Reflection.MethodInfo, throwOnBindFailure: boolean): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegateInternal(rtType: any, rtMethod: any, firstArgument: any, flags: System.DelegateBindingFlags, stackMark: any): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegateNoSecurityCheck(type: System.Type, target: any, method: System.RuntimeMethodHandle): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegateNoSecurityCheck(type: any, firstArgument: any, method: System.Reflection.MethodInfo): System.Delegate; //{ throw new Error("Not implemented.");} DelegateConstruct(target: any, slot: number): any; //{ throw new Error("Not implemented.");} DynamicInvoke(args: any): any; //{ throw new Error("Not implemented.");} DynamicInvokeImpl(args: any): any; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} FindMethodHandle(): any; //{ throw new Error("Not implemented.");} GetCallStub(methodPtr: number): number; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetInvocationList(): any; //{ throw new Error("Not implemented.");} GetInvokeMethod(): number; //{ throw new Error("Not implemented.");} GetMethodImpl(): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMulticastInvoke(): number; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} GetTarget(): any; //{ throw new Error("Not implemented.");} InternalAlloc(type: any): System.MulticastDelegate; //{ throw new Error("Not implemented.");} InternalAllocLike(d: System.Delegate): System.MulticastDelegate; //{ throw new Error("Not implemented.");} InternalEqualMethodHandles(left: System.Delegate, right: System.Delegate): boolean; //{ throw new Error("Not implemented.");} InternalEqualTypes(a: any, b: any): boolean; //{ throw new Error("Not implemented.");} Remove(source: System.Delegate, value: System.Delegate): System.Delegate; //{ throw new Error("Not implemented.");} RemoveAll(source: System.Delegate, value: System.Delegate): System.Delegate; //{ throw new Error("Not implemented.");} RemoveImpl(d: System.Delegate): System.Delegate; //{ throw new Error("Not implemented.");} UnsafeCreateDelegate(rtType: any, rtMethod: any, firstArgument: any, flags: System.DelegateBindingFlags): System.Delegate; //{ throw new Error("Not implemented.");} } export class EventArgs { static Empty: System.EventArgs; } export class Exception { Data: System.Collections.IDictionary; Message: string; InnerException: System.Exception; TargetSite: System.Reflection.MethodBase; StackTrace: string; HelpLink: string; Source: string; IPForWatsonBuckets: number; WatsonBuckets: any; RemoteStackTrace: string; HResult: number; IsTransient: boolean; private _className: string; private _exceptionMethod: System.Reflection.MethodBase; private _exceptionMethodString: string; _message: string; private _data: System.Collections.IDictionary; private _innerException: System.Exception; private _helpURL: string; private _stackTrace: any; private _watsonBuckets: any; private _stackTraceString: string; private _remoteStackTraceString: string; private _remoteStackIndex: number; private _dynamicMethods: any; _HResult: number; private _source: string; private _xptrs: number; private _xcode: number; private _ipForWatsonBuckets: number; private _safeSerializationManager: any; private static s_EDILock: any; AddExceptionDataForRestrictedErrorInfo(restrictedError: string, restrictedErrorReference: string, restrictedCapabilitySid: string, restrictedErrorObject: any, hasrestrictedLanguageErrorObject?: boolean): any; //{ throw new Error("Not implemented.");} CopyDynamicMethods(currentDynamicMethods: any): any; //{ throw new Error("Not implemented.");} CopyStackTrace(currentStackTrace: any): any; //{ throw new Error("Not implemented.");} DeepCopyDynamicMethods(currentDynamicMethods: any): any; //{ throw new Error("Not implemented.");} DeepCopyStackTrace(currentStackTrace: any): any; //{ throw new Error("Not implemented.");} GetBaseException(): System.Exception; //{ throw new Error("Not implemented.");} GetClassName(): string; //{ throw new Error("Not implemented.");} GetExceptionMethodFromStackTrace(): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} GetExceptionMethodFromString(): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} GetExceptionMethodString(): string; //{ throw new Error("Not implemented.");} GetMessageFromNativeResources(kind: System.Exception.ExceptionMessageKind): string; //{ throw new Error("Not implemented.");} GetMessageFromNativeResources(kind: System.Exception.ExceptionMessageKind, retMesg: any): any; //{ throw new Error("Not implemented.");} GetMethodFromStackTrace(stackTrace: any): any; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} GetStackTrace(needFileInfo: boolean): string; //{ throw new Error("Not implemented.");} GetStackTracesDeepCopy(currentStackTrace: any, dynamicMethodArray: any): any; //{ throw new Error("Not implemented.");} GetStackTracesDeepCopy(exception: System.Exception, currentStackTrace: any, dynamicMethodArray: any): any; //{ throw new Error("Not implemented.");} GetTargetSiteInternal(): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} GetType(): System.Type; //{ throw new Error("Not implemented.");} Init(): any; //{ throw new Error("Not implemented.");} InternalPreserveStackTrace(): any; //{ throw new Error("Not implemented.");} InternalToString(): string; //{ throw new Error("Not implemented.");} IsImmutableAgileException(e: System.Exception): boolean; //{ throw new Error("Not implemented.");} nIsTransient(hr: number): boolean; //{ throw new Error("Not implemented.");} OnDeserialized(context: any): any; //{ throw new Error("Not implemented.");} PrepareForForeignExceptionRaise(): any; //{ throw new Error("Not implemented.");} PrepForRemoting(): System.Exception; //{ throw new Error("Not implemented.");} RestoreExceptionDispatchInfo(exceptionDispatchInfo: any): any; //{ throw new Error("Not implemented.");} SaveStackTracesFromDeepCopy(exception: System.Exception, currentStackTrace: any, dynamicMethodArray: any): any; //{ throw new Error("Not implemented.");} SetErrorCode(hr: number): any; //{ throw new Error("Not implemented.");} StripFileInfo(stackTrace: string, isRemoteStackTrace: boolean): string; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} ToString(needFileLineInfo: boolean, needMessage: boolean): string; //{ throw new Error("Not implemented.");} TryGetRestrictedLanguageErrorObject(restrictedErrorObject: any): boolean; //{ throw new Error("Not implemented.");} } export class Func<T, TResult> extends System.MulticastDelegate { BeginInvoke(arg: T, callback: System.AsyncCallback, object: any): System.IAsyncResult; //{ throw new Error("Not implemented.");} EndInvoke(result: System.IAsyncResult): TResult; //{ throw new Error("Not implemented.");} Invoke(arg: T): TResult; //{ throw new Error("Not implemented.");} } export class Guid { private _a: number; private _b: number; private _c: number; private _d: number; private _e: number; private _f: number; private _g: number; private _h: number; private _i: number; private _j: number; private _k: number; static Empty: System.Guid; CompareTo(value: System.Guid): number; //{ throw new Error("Not implemented.");} CompareTo(value: any): number; //{ throw new Error("Not implemented.");} EatAllWhitespace(str: string): string; //{ throw new Error("Not implemented.");} Equals(o: any): boolean; //{ throw new Error("Not implemented.");} Equals(g: System.Guid): boolean; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetResult(me: number, them: number): number; //{ throw new Error("Not implemented.");} HexsToChars(guidChars: any, offset: number, a: number, b: number, hex: boolean): number; //{ throw new Error("Not implemented.");} HexsToChars(guidChars: any, offset: number, a: number, b: number): number; //{ throw new Error("Not implemented.");} HexToChar(a: number): string; //{ throw new Error("Not implemented.");} IsHexPrefix(str: string, i: number): boolean; //{ throw new Error("Not implemented.");} NewGuid(): System.Guid; //{ throw new Error("Not implemented.");} Parse(input: string): System.Guid; //{ throw new Error("Not implemented.");} ParseExact(input: string, format: string): System.Guid; //{ throw new Error("Not implemented.");} StringToInt(str: string, parsePos: any, requiredLength: number, flags: number, result: any, parseResult: any): boolean; //{ throw new Error("Not implemented.");} StringToInt(str: string, requiredLength: number, flags: number, result: any, parseResult: any): boolean; //{ throw new Error("Not implemented.");} StringToInt(str: string, parsePos: any, requiredLength: number, flags: number, result: any, parseResult: any): boolean; //{ throw new Error("Not implemented.");} StringToLong(str: string, parsePos: any, flags: number, result: any, parseResult: any): boolean; //{ throw new Error("Not implemented.");} StringToLong(str: string, parsePos: any, flags: number, result: any, parseResult: any): boolean; //{ throw new Error("Not implemented.");} StringToLong(str: string, flags: number, result: any, parseResult: any): boolean; //{ throw new Error("Not implemented.");} StringToShort(str: string, requiredLength: number, flags: number, result: any, parseResult: any): boolean; //{ throw new Error("Not implemented.");} StringToShort(str: string, parsePos: any, requiredLength: number, flags: number, result: any, parseResult: any): boolean; //{ throw new Error("Not implemented.");} StringToShort(str: string, parsePos: any, requiredLength: number, flags: number, result: any, parseResult: any): boolean; //{ throw new Error("Not implemented.");} ToByteArray(): System.Byte[]; //{ throw new Error("Not implemented.");} ToString(format: string): string; //{ throw new Error("Not implemented.");} ToString(format: string, provider: System.IFormatProvider): string; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} TryParse(input: string, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseExact(input: string, format: string, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseGuid(g: string, flags: System.Guid.GuidStyles, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseGuidWithDashes(guidString: string, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseGuidWithHexPrefix(guidString: string, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseGuidWithNoStyle(guidString: string, result: any): boolean; //{ throw new Error("Not implemented.");} } interface IAsyncResult { IsCompleted: boolean; AsyncWaitHandle: System.Threading.WaitHandle; AsyncState: any; CompletedSynchronously: boolean; } interface IFormatProvider { GetFormat(formatType: System.Type): any; } export class MarshalByRefObject { private Identity: any; private __identity: any; __RaceSetServerIdentity(id: any): any; //{ throw new Error("Not implemented.");} __ResetServerIdentity(): any; //{ throw new Error("Not implemented.");} CanCastToXmlType(xmlTypeName: string, xmlTypeNamespace: string): boolean; //{ throw new Error("Not implemented.");} CanCastToXmlTypeHelper(castType: any, o: System.MarshalByRefObject): boolean; //{ throw new Error("Not implemented.");} CreateObjRef(requestedType: System.Type): any; //{ throw new Error("Not implemented.");} GetComIUnknown(fIsBeingMarshalled: boolean): number; //{ throw new Error("Not implemented.");} GetComIUnknown(o: System.MarshalByRefObject): number; //{ throw new Error("Not implemented.");} GetIdentity(obj: System.MarshalByRefObject, fServer: any): any; //{ throw new Error("Not implemented.");} GetIdentity(obj: System.MarshalByRefObject): any; //{ throw new Error("Not implemented.");} GetLifetimeService(): any; //{ throw new Error("Not implemented.");} InitializeLifetimeService(): any; //{ throw new Error("Not implemented.");} InvokeMember(name: string, invokeAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, args: any, modifiers: any, culture: System.Globalization.CultureInfo, namedParameters: System.String[]): any; //{ throw new Error("Not implemented.");} IsInstanceOfType(T: System.Type): boolean; //{ throw new Error("Not implemented.");} MemberwiseClone(cloneIdentity: boolean): System.MarshalByRefObject; //{ throw new Error("Not implemented.");} } export class ModuleHandle { MDStreamVersion: number; private m_ptr: any; static EmptyHandle: System.ModuleHandle; _ContainsPropertyMatchingHash(module: any, propertyToken: number, hash: number): boolean; //{ throw new Error("Not implemented.");} _GetMetadataImport(module: any): number; //{ throw new Error("Not implemented.");} ContainsPropertyMatchingHash(module: any, propertyToken: number, hash: number): boolean; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} Equals(handle: System.ModuleHandle): boolean; //{ throw new Error("Not implemented.");} GetAssembly(handle: any, retAssembly: any): any; //{ throw new Error("Not implemented.");} GetAssembly(module: any): any; //{ throw new Error("Not implemented.");} GetDynamicMethod(method: any, module: any, name: string, sig: System.Byte[], resolver: any): any; //{ throw new Error("Not implemented.");} GetEmptyMH(): System.ModuleHandle; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetMDStreamVersion(module: any): number; //{ throw new Error("Not implemented.");} GetMetadataImport(module: any): any; //{ throw new Error("Not implemented.");} GetModuleType(module: any): any; //{ throw new Error("Not implemented.");} GetModuleType(handle: any, type: any): any; //{ throw new Error("Not implemented.");} GetPEKind(handle: any, peKind: any, machine: any): any; //{ throw new Error("Not implemented.");} GetPEKind(module: any, peKind: any, machine: any): any; //{ throw new Error("Not implemented.");} GetRuntimeFieldHandleFromMetadataToken(fieldToken: number): System.RuntimeFieldHandle; //{ throw new Error("Not implemented.");} GetRuntimeMethodHandleFromMetadataToken(methodToken: number): System.RuntimeMethodHandle; //{ throw new Error("Not implemented.");} GetRuntimeModule(): any; //{ throw new Error("Not implemented.");} GetRuntimeTypeHandleFromMetadataToken(typeToken: number): System.RuntimeTypeHandle; //{ throw new Error("Not implemented.");} GetToken(module: any): number; //{ throw new Error("Not implemented.");} IsNullHandle(): boolean; //{ throw new Error("Not implemented.");} ResolveField(module: any, fieldToken: number, typeInstArgs: any, typeInstCount: number, methodInstArgs: any, methodInstCount: number, retField: any): any; //{ throw new Error("Not implemented.");} ResolveFieldHandle(fieldToken: number, typeInstantiationContext: any, methodInstantiationContext: any): System.RuntimeFieldHandle; //{ throw new Error("Not implemented.");} ResolveFieldHandle(fieldToken: number): System.RuntimeFieldHandle; //{ throw new Error("Not implemented.");} ResolveFieldHandleInternal(module: any, fieldToken: number, typeInstantiationContext: any, methodInstantiationContext: any): any; //{ throw new Error("Not implemented.");} ResolveMethod(module: any, methodToken: number, typeInstArgs: any, typeInstCount: number, methodInstArgs: any, methodInstCount: number): any; //{ throw new Error("Not implemented.");} ResolveMethodHandle(methodToken: number, typeInstantiationContext: any, methodInstantiationContext: any): System.RuntimeMethodHandle; //{ throw new Error("Not implemented.");} ResolveMethodHandle(methodToken: number): System.RuntimeMethodHandle; //{ throw new Error("Not implemented.");} ResolveMethodHandleInternal(module: any, methodToken: number): any; //{ throw new Error("Not implemented.");} ResolveMethodHandleInternal(module: any, methodToken: number, typeInstantiationContext: any, methodInstantiationContext: any): any; //{ throw new Error("Not implemented.");} ResolveMethodHandleInternalCore(module: any, methodToken: number, typeInstantiationContext: any, typeInstCount: number, methodInstantiationContext: any, methodInstCount: number): any; //{ throw new Error("Not implemented.");} ResolveType(module: any, typeToken: number, typeInstArgs: any, typeInstCount: number, methodInstArgs: any, methodInstCount: number, type: any): any; //{ throw new Error("Not implemented.");} ResolveTypeHandle(typeToken: number, typeInstantiationContext: any, methodInstantiationContext: any): System.RuntimeTypeHandle; //{ throw new Error("Not implemented.");} ResolveTypeHandle(typeToken: number): System.RuntimeTypeHandle; //{ throw new Error("Not implemented.");} ResolveTypeHandleInternal(module: any, typeToken: number, typeInstantiationContext: any, methodInstantiationContext: any): any; //{ throw new Error("Not implemented.");} ValidateModulePointer(module: any): any; //{ throw new Error("Not implemented.");} } export class MulticastDelegate extends System.Delegate { private _invocationList: any; private _invocationCount: number; CombineImpl(follow: System.Delegate): System.Delegate; //{ throw new Error("Not implemented.");} CtorClosed(target: any, methodPtr: number): any; //{ throw new Error("Not implemented.");} CtorClosedStatic(target: any, methodPtr: number): any; //{ throw new Error("Not implemented.");} CtorCollectibleClosedStatic(target: any, methodPtr: number, gchandle: number): any; //{ throw new Error("Not implemented.");} CtorCollectibleOpened(target: any, methodPtr: number, shuffleThunk: number, gchandle: number): any; //{ throw new Error("Not implemented.");} CtorCollectibleVirtualDispatch(target: any, methodPtr: number, shuffleThunk: number, gchandle: number): any; //{ throw new Error("Not implemented.");} CtorOpened(target: any, methodPtr: number, shuffleThunk: number): any; //{ throw new Error("Not implemented.");} CtorRTClosed(target: any, methodPtr: number): any; //{ throw new Error("Not implemented.");} CtorSecureClosed(target: any, methodPtr: number, callThunk: number, creatorMethod: number): any; //{ throw new Error("Not implemented.");} CtorSecureClosedStatic(target: any, methodPtr: number, callThunk: number, creatorMethod: number): any; //{ throw new Error("Not implemented.");} CtorSecureOpened(target: any, methodPtr: number, shuffleThunk: number, callThunk: number, creatorMethod: number): any; //{ throw new Error("Not implemented.");} CtorSecureRTClosed(target: any, methodPtr: number, callThunk: number, creatorMethod: number): any; //{ throw new Error("Not implemented.");} CtorSecureVirtualDispatch(target: any, methodPtr: number, shuffleThunk: number, callThunk: number, creatorMethod: number): any; //{ throw new Error("Not implemented.");} CtorVirtualDispatch(target: any, methodPtr: number, shuffleThunk: number): any; //{ throw new Error("Not implemented.");} DeleteFromInvocationList(invocationList: any, invocationCount: number, deleteIndex: number, deleteCount: number): any; //{ throw new Error("Not implemented.");} EqualInvocationLists(a: any, b: any, start: number, count: number): boolean; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetInvocationList(): any; //{ throw new Error("Not implemented.");} GetMethodImpl(): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} GetTarget(): any; //{ throw new Error("Not implemented.");} InvocationListEquals(d: System.MulticastDelegate): boolean; //{ throw new Error("Not implemented.");} InvocationListLogicallyNull(): boolean; //{ throw new Error("Not implemented.");} IsUnmanagedFunctionPtr(): boolean; //{ throw new Error("Not implemented.");} NewMulticastDelegate(invocationList: any, invocationCount: number): System.MulticastDelegate; //{ throw new Error("Not implemented.");} NewMulticastDelegate(invocationList: any, invocationCount: number, thisIsMultiCastAlready: boolean): System.MulticastDelegate; //{ throw new Error("Not implemented.");} RemoveImpl(value: System.Delegate): System.Delegate; //{ throw new Error("Not implemented.");} StoreDynamicMethod(dynamicMethod: System.Reflection.MethodInfo): any; //{ throw new Error("Not implemented.");} ThrowNullThisInDelegateToInstance(): any; //{ throw new Error("Not implemented.");} TrySetSlot(a: any, index: number, o: any): boolean; //{ throw new Error("Not implemented.");} } export class RuntimeFieldHandle { Value: number; private m_ptr: any; _GetUtf8Name(field: any): any; //{ throw new Error("Not implemented.");} AcquiresContextFromThis(field: any): boolean; //{ throw new Error("Not implemented.");} CheckAttributeAccess(fieldHandle: System.RuntimeFieldHandle, decoratedTarget: any): any; //{ throw new Error("Not implemented.");} Equals(handle: System.RuntimeFieldHandle): boolean; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetApproxDeclaringType(field: any): any; //{ throw new Error("Not implemented.");} GetApproxDeclaringType(field: any): any; //{ throw new Error("Not implemented.");} GetAttributes(field: any): System.Reflection.FieldAttributes; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetName(field: any): string; //{ throw new Error("Not implemented.");} GetNativeHandle(): System.RuntimeFieldHandle; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} GetRuntimeFieldInfo(): any; //{ throw new Error("Not implemented.");} GetStaticFieldForGenericType(field: any, declaringType: any): any; //{ throw new Error("Not implemented.");} GetToken(field: any): number; //{ throw new Error("Not implemented.");} GetUtf8Name(field: any): any; //{ throw new Error("Not implemented.");} GetValue(field: any, instance: any, fieldType: any, declaringType: any, domainInitialized: any): any; //{ throw new Error("Not implemented.");} GetValueDirect(field: any, fieldType: any, pTypedRef: any, contextType: any): any; //{ throw new Error("Not implemented.");} IsNullHandle(): boolean; //{ throw new Error("Not implemented.");} IsSecurityCritical(fieldHandle: System.RuntimeFieldHandle): boolean; //{ throw new Error("Not implemented.");} IsSecurityCritical(): boolean; //{ throw new Error("Not implemented.");} IsSecuritySafeCritical(): boolean; //{ throw new Error("Not implemented.");} IsSecuritySafeCritical(fieldHandle: System.RuntimeFieldHandle): boolean; //{ throw new Error("Not implemented.");} IsSecurityTransparent(fieldHandle: System.RuntimeFieldHandle): boolean; //{ throw new Error("Not implemented.");} IsSecurityTransparent(): boolean; //{ throw new Error("Not implemented.");} MatchesNameHash(handle: any, hash: number): boolean; //{ throw new Error("Not implemented.");} SetValue(field: any, obj: any, value: any, fieldType: any, fieldAttr: System.Reflection.FieldAttributes, declaringType: any, domainInitialized: any): any; //{ throw new Error("Not implemented.");} SetValueDirect(field: any, fieldType: any, pTypedRef: any, value: any, contextType: any): any; //{ throw new Error("Not implemented.");} } export class RuntimeMethodHandle { static EmptyHandle: System.RuntimeMethodHandle; Value: number; private m_value: any; _GetCurrentMethod(stackMark: any): any; //{ throw new Error("Not implemented.");} _GetUtf8Name(method: any): any; //{ throw new Error("Not implemented.");} _IsSecurityCritical(method: any): boolean; //{ throw new Error("Not implemented.");} _IsSecuritySafeCritical(method: any): boolean; //{ throw new Error("Not implemented.");} _IsSecurityTransparent(method: any): boolean; //{ throw new Error("Not implemented.");} _IsTokenSecurityTransparent(module: any, metaDataToken: number): boolean; //{ throw new Error("Not implemented.");} CheckLinktimeDemands(method: any, module: any, isDecoratedTargetSecurityTransparent: boolean): any; //{ throw new Error("Not implemented.");} ConstructInstantiation(method: any, format: System.TypeNameFormatFlags, retString: any): any; //{ throw new Error("Not implemented.");} ConstructInstantiation(method: any, format: System.TypeNameFormatFlags): string; //{ throw new Error("Not implemented.");} Destroy(method: any): any; //{ throw new Error("Not implemented.");} EnsureNonNullMethodInfo(method: any): any; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} Equals(handle: System.RuntimeMethodHandle): boolean; //{ throw new Error("Not implemented.");} GetAttributes(method: any): System.Reflection.MethodAttributes; //{ throw new Error("Not implemented.");} GetAttributes(method: any): System.Reflection.MethodAttributes; //{ throw new Error("Not implemented.");} GetCallerType(stackMark: any): any; //{ throw new Error("Not implemented.");} GetCallerType(stackMark: any, retType: any): any; //{ throw new Error("Not implemented.");} GetCurrentMethod(stackMark: any): any; //{ throw new Error("Not implemented.");} GetDeclaringType(method: any): any; //{ throw new Error("Not implemented.");} GetDeclaringType(method: any): any; //{ throw new Error("Not implemented.");} GetFunctionPointer(handle: any): number; //{ throw new Error("Not implemented.");} GetFunctionPointer(): number; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetImplAttributes(method: any): System.Reflection.MethodImplAttributes; //{ throw new Error("Not implemented.");} GetLoaderAllocator(method: any): any; //{ throw new Error("Not implemented.");} GetMethodBody(method: any, declaringType: any): any; //{ throw new Error("Not implemented.");} GetMethodDef(method: any): number; //{ throw new Error("Not implemented.");} GetMethodFromCanonical(method: any, declaringType: any): any; //{ throw new Error("Not implemented.");} GetMethodInfo(): any; //{ throw new Error("Not implemented.");} GetMethodInstantiation(method: any, types: any, fAsRuntimeTypeArray: boolean): any; //{ throw new Error("Not implemented.");} GetMethodInstantiationInternal(method: any): any; //{ throw new Error("Not implemented.");} GetMethodInstantiationInternal(method: any): any; //{ throw new Error("Not implemented.");} GetMethodInstantiationPublic(method: any): System.Type[]; //{ throw new Error("Not implemented.");} GetName(method: any): string; //{ throw new Error("Not implemented.");} GetName(method: any): string; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} GetResolver(method: any): any; //{ throw new Error("Not implemented.");} GetSecurityFlags(handle: any): System.Reflection.INVOCATION_FLAGS; //{ throw new Error("Not implemented.");} GetSlot(method: any): number; //{ throw new Error("Not implemented.");} GetSlot(method: any): number; //{ throw new Error("Not implemented.");} GetSpecialSecurityFlags(method: any): number; //{ throw new Error("Not implemented.");} GetStubIfNeeded(method: any, declaringType: any, methodInstantiation: any): any; //{ throw new Error("Not implemented.");} GetTypicalMethodDefinition(method: any, outMethod: any): any; //{ throw new Error("Not implemented.");} GetTypicalMethodDefinition(method: any): any; //{ throw new Error("Not implemented.");} GetUtf8Name(method: any): any; //{ throw new Error("Not implemented.");} GetValueInternal(rmh: System.RuntimeMethodHandle): number; //{ throw new Error("Not implemented.");} HasMethodInstantiation(method: any): boolean; //{ throw new Error("Not implemented.");} HasMethodInstantiation(method: any): boolean; //{ throw new Error("Not implemented.");} InvokeMethod(target: any, arguments: any, sig: any, constructor: boolean): any; //{ throw new Error("Not implemented.");} IsCAVisibleFromDecoratedType(attrTypeHandle: System.RuntimeTypeHandle, attrCtor: any, sourceTypeHandle: System.RuntimeTypeHandle, sourceModule: any): boolean; //{ throw new Error("Not implemented.");} IsConstructor(method: any): boolean; //{ throw new Error("Not implemented.");} IsDynamicMethod(method: any): boolean; //{ throw new Error("Not implemented.");} IsGenericMethodDefinition(method: any): boolean; //{ throw new Error("Not implemented.");} IsGenericMethodDefinition(method: any): boolean; //{ throw new Error("Not implemented.");} IsNullHandle(): boolean; //{ throw new Error("Not implemented.");} IsSecurityCritical(method: any): boolean; //{ throw new Error("Not implemented.");} IsSecuritySafeCritical(method: any): boolean; //{ throw new Error("Not implemented.");} IsSecurityTransparent(method: any): boolean; //{ throw new Error("Not implemented.");} IsTokenSecurityTransparent(module: System.Reflection.Module, metaDataToken: number): boolean; //{ throw new Error("Not implemented.");} IsTypicalMethodDefinition(method: any): boolean; //{ throw new Error("Not implemented.");} MatchesNameHash(method: any, hash: number): boolean; //{ throw new Error("Not implemented.");} PerformSecurityCheck(obj: any, method: any, parent: any, invocationFlags: number): any; //{ throw new Error("Not implemented.");} PerformSecurityCheck(obj: any, method: any, parent: any, invocationFlags: number): any; //{ throw new Error("Not implemented.");} SerializationInvoke(method: any, target: any, info: any, context: any): any; //{ throw new Error("Not implemented.");} StripMethodInstantiation(method: any): any; //{ throw new Error("Not implemented.");} StripMethodInstantiation(method: any, outMethod: any): any; //{ throw new Error("Not implemented.");} } export class RuntimeTypeHandle { static EmptyHandle: System.RuntimeTypeHandle; Value: number; private m_type: any; _GetMetadataImport(type: any): number; //{ throw new Error("Not implemented.");} _GetUtf8Name(type: any): any; //{ throw new Error("Not implemented.");} _IsVisible(typeHandle: System.RuntimeTypeHandle): boolean; //{ throw new Error("Not implemented.");} Allocate(type: any): any; //{ throw new Error("Not implemented.");} CanCastTo(type: any, target: any): boolean; //{ throw new Error("Not implemented.");} CompareCanonicalHandles(left: any, right: any): boolean; //{ throw new Error("Not implemented.");} ConstructName(formatFlags: System.TypeNameFormatFlags): string; //{ throw new Error("Not implemented.");} ConstructName(handle: System.RuntimeTypeHandle, formatFlags: System.TypeNameFormatFlags, retString: any): any; //{ throw new Error("Not implemented.");} ContainsGenericVariables(): boolean; //{ throw new Error("Not implemented.");} ContainsGenericVariables(handle: any): boolean; //{ throw new Error("Not implemented.");} CopyRuntimeTypeHandles(inHandles: any, length: any): any; //{ throw new Error("Not implemented.");} CopyRuntimeTypeHandles(inHandles: System.Type[], length: any): any; //{ throw new Error("Not implemented.");} CreateCaInstance(type: any, ctor: any): any; //{ throw new Error("Not implemented.");} CreateInstance(type: any, publicOnly: boolean, noCheck: boolean, canBeCached: any, ctor: any, bNeedSecurityCheck: any): any; //{ throw new Error("Not implemented.");} CreateInstanceForAnotherGenericParameter(type: any, genericParameter: any): any; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} Equals(handle: System.RuntimeTypeHandle): boolean; //{ throw new Error("Not implemented.");} GetArrayRank(type: any): number; //{ throw new Error("Not implemented.");} GetAssembly(type: any): any; //{ throw new Error("Not implemented.");} GetAttributes(type: any): System.Reflection.TypeAttributes; //{ throw new Error("Not implemented.");} GetBaseType(type: any): any; //{ throw new Error("Not implemented.");} GetConstraints(handle: System.RuntimeTypeHandle, types: any): any; //{ throw new Error("Not implemented.");} GetConstraints(): System.Type[]; //{ throw new Error("Not implemented.");} GetCorElementType(type: any): System.Reflection.CorElementType; //{ throw new Error("Not implemented.");} GetDeclaringMethod(type: any): any; //{ throw new Error("Not implemented.");} GetDeclaringType(type: any): any; //{ throw new Error("Not implemented.");} GetDefaultConstructor(): any; //{ throw new Error("Not implemented.");} GetDefaultConstructor(handle: System.RuntimeTypeHandle, method: any): any; //{ throw new Error("Not implemented.");} GetElementType(type: any): any; //{ throw new Error("Not implemented.");} GetFields(type: any, result: any, count: any): boolean; //{ throw new Error("Not implemented.");} GetFirstIntroducedMethod(type: any): any; //{ throw new Error("Not implemented.");} GetGCHandle(type: System.Runtime.InteropServices.GCHandleType): number; //{ throw new Error("Not implemented.");} GetGCHandle(handle: System.RuntimeTypeHandle, type: System.Runtime.InteropServices.GCHandleType): number; //{ throw new Error("Not implemented.");} GetGenericTypeDefinition(type: any): any; //{ throw new Error("Not implemented.");} GetGenericTypeDefinition(type: System.RuntimeTypeHandle, retType: any): any; //{ throw new Error("Not implemented.");} GetGenericVariableIndex(type: any): number; //{ throw new Error("Not implemented.");} GetGenericVariableIndex(): number; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetInstantiation(type: System.RuntimeTypeHandle, types: any, fAsRuntimeTypeArray: boolean): any; //{ throw new Error("Not implemented.");} GetInstantiationInternal(): any; //{ throw new Error("Not implemented.");} GetInstantiationPublic(): System.Type[]; //{ throw new Error("Not implemented.");} GetInterfaceMethodImplementationSlot(interfaceHandle: System.RuntimeTypeHandle, interfaceMethodHandle: any): number; //{ throw new Error("Not implemented.");} GetInterfaceMethodImplementationSlot(handle: System.RuntimeTypeHandle, interfaceHandle: System.RuntimeTypeHandle, interfaceMethodHandle: any): number; //{ throw new Error("Not implemented.");} GetInterfaces(type: any): System.Type[]; //{ throw new Error("Not implemented.");} GetIntroducedMethods(type: any): any; //{ throw new Error("Not implemented.");} GetMetadataImport(type: any): any; //{ throw new Error("Not implemented.");} GetMethodAt(type: any, slot: number): any; //{ throw new Error("Not implemented.");} GetModule(type: any): any; //{ throw new Error("Not implemented.");} GetModuleHandle(): System.ModuleHandle; //{ throw new Error("Not implemented.");} GetNativeHandle(): System.RuntimeTypeHandle; //{ throw new Error("Not implemented.");} GetNextIntroducedMethod(method: any): any; //{ throw new Error("Not implemented.");} GetNumVirtuals(type: any): number; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} GetRuntimeType(): any; //{ throw new Error("Not implemented.");} GetToken(type: any): number; //{ throw new Error("Not implemented.");} GetTypeByName(name: string, throwOnError: boolean, ignoreCase: boolean, reflectionOnly: boolean, stackMark: any, loadTypeFromPartialName: boolean): any; //{ throw new Error("Not implemented.");} GetTypeByName(name: string, throwOnError: boolean, ignoreCase: boolean, reflectionOnly: boolean, stackMark: any, pPrivHostBinder: number, loadTypeFromPartialName: boolean): any; //{ throw new Error("Not implemented.");} GetTypeByName(name: string, stackMark: any): System.Type; //{ throw new Error("Not implemented.");} GetTypeByName(name: string, throwOnError: boolean, ignoreCase: boolean, reflectionOnly: boolean, stackMark: any, pPrivHostBinder: number, loadTypeFromPartialName: boolean, type: any): any; //{ throw new Error("Not implemented.");} GetTypeByNameUsingCARules(name: string, scope: any): any; //{ throw new Error("Not implemented.");} GetTypeByNameUsingCARules(name: string, scope: any, type: any): any; //{ throw new Error("Not implemented.");} GetTypeChecked(): any; //{ throw new Error("Not implemented.");} GetTypeHelper(typeStart: System.Type, genericArgs: System.Type[], pModifiers: number, cModifiers: number): System.Type; //{ throw new Error("Not implemented.");} GetUtf8Name(type: any): any; //{ throw new Error("Not implemented.");} GetValueInternal(handle: System.RuntimeTypeHandle): number; //{ throw new Error("Not implemented.");} HasElementType(type: any): boolean; //{ throw new Error("Not implemented.");} HasInstantiation(type: any): boolean; //{ throw new Error("Not implemented.");} HasInstantiation(): boolean; //{ throw new Error("Not implemented.");} HasProxyAttribute(type: any): boolean; //{ throw new Error("Not implemented.");} Instantiate(inst: System.Type[]): any; //{ throw new Error("Not implemented.");} Instantiate(handle: System.RuntimeTypeHandle, pInst: any, numGenericArgs: number, type: any): any; //{ throw new Error("Not implemented.");} IsArray(type: any): boolean; //{ throw new Error("Not implemented.");} IsByRef(type: any): boolean; //{ throw new Error("Not implemented.");} IsCollectible(handle: System.RuntimeTypeHandle): boolean; //{ throw new Error("Not implemented.");} IsComObject(type: any, isGenericCOM: boolean): boolean; //{ throw new Error("Not implemented.");} IsContextful(type: any): boolean; //{ throw new Error("Not implemented.");} IsEquivalentTo(rtType1: any, rtType2: any): boolean; //{ throw new Error("Not implemented.");} IsEquivalentType(type: any): boolean; //{ throw new Error("Not implemented.");} IsGenericTypeDefinition(type: any): boolean; //{ throw new Error("Not implemented.");} IsGenericVariable(type: any): boolean; //{ throw new Error("Not implemented.");} IsGenericVariable(): boolean; //{ throw new Error("Not implemented.");} IsInstanceOfType(type: any, o: any): boolean; //{ throw new Error("Not implemented.");} IsInterface(type: any): boolean; //{ throw new Error("Not implemented.");} IsNullHandle(): boolean; //{ throw new Error("Not implemented.");} IsPointer(type: any): boolean; //{ throw new Error("Not implemented.");} IsPrimitive(type: any): boolean; //{ throw new Error("Not implemented.");} IsSecurityCritical(typeHandle: System.RuntimeTypeHandle): boolean; //{ throw new Error("Not implemented.");} IsSecurityCritical(): boolean; //{ throw new Error("Not implemented.");} IsSecuritySafeCritical(typeHandle: System.RuntimeTypeHandle): boolean; //{ throw new Error("Not implemented.");} IsSecuritySafeCritical(): boolean; //{ throw new Error("Not implemented.");} IsSecurityTransparent(typeHandle: System.RuntimeTypeHandle): boolean; //{ throw new Error("Not implemented.");} IsSecurityTransparent(): boolean; //{ throw new Error("Not implemented.");} IsSzArray(type: any): boolean; //{ throw new Error("Not implemented.");} IsValueType(type: any): boolean; //{ throw new Error("Not implemented.");} IsVisible(type: any): boolean; //{ throw new Error("Not implemented.");} MakeArray(rank: number): any; //{ throw new Error("Not implemented.");} MakeArray(handle: System.RuntimeTypeHandle, rank: number, type: any): any; //{ throw new Error("Not implemented.");} MakeByRef(handle: System.RuntimeTypeHandle, type: any): any; //{ throw new Error("Not implemented.");} MakeByRef(): any; //{ throw new Error("Not implemented.");} MakePointer(): any; //{ throw new Error("Not implemented.");} MakePointer(handle: System.RuntimeTypeHandle, type: any): any; //{ throw new Error("Not implemented.");} MakeSZArray(): any; //{ throw new Error("Not implemented.");} MakeSZArray(handle: System.RuntimeTypeHandle, type: any): any; //{ throw new Error("Not implemented.");} SatisfiesConstraints(paramType: any, pTypeContext: any, typeContextLength: number, pMethodContext: any, methodContextLength: number, toType: any): boolean; //{ throw new Error("Not implemented.");} SatisfiesConstraints(paramType: any, typeContext: any, methodContext: any, toType: any): boolean; //{ throw new Error("Not implemented.");} VerifyInterfaceIsImplemented(handle: System.RuntimeTypeHandle, interfaceHandle: System.RuntimeTypeHandle): any; //{ throw new Error("Not implemented.");} VerifyInterfaceIsImplemented(interfaceHandle: System.RuntimeTypeHandle): any; //{ throw new Error("Not implemented.");} } export class SystemException extends System.Exception { } export class TimeSpan { Ticks: number; Days: number; Hours: number; Milliseconds: number; Minutes: number; Seconds: number; TotalDays: number; TotalHours: number; TotalMilliseconds: number; TotalMinutes: number; TotalSeconds: number; private static LegacyMode: boolean; _ticks: number; static Zero: System.TimeSpan; static MaxValue: System.TimeSpan; static MinValue: System.TimeSpan; private static _legacyConfigChecked: boolean; private static _legacyMode: boolean; Add(ts: System.TimeSpan): System.TimeSpan; //{ throw new Error("Not implemented.");} Compare(t1: System.TimeSpan, t2: System.TimeSpan): number; //{ throw new Error("Not implemented.");} CompareTo(value: any): number; //{ throw new Error("Not implemented.");} CompareTo(value: System.TimeSpan): number; //{ throw new Error("Not implemented.");} Duration(): System.TimeSpan; //{ throw new Error("Not implemented.");} Equals(value: any): boolean; //{ throw new Error("Not implemented.");} Equals(obj: System.TimeSpan): boolean; //{ throw new Error("Not implemented.");} Equals(t1: System.TimeSpan, t2: System.TimeSpan): boolean; //{ throw new Error("Not implemented.");} FromDays(value: number): System.TimeSpan; //{ throw new Error("Not implemented.");} FromHours(value: number): System.TimeSpan; //{ throw new Error("Not implemented.");} FromMilliseconds(value: number): System.TimeSpan; //{ throw new Error("Not implemented.");} FromMinutes(value: number): System.TimeSpan; //{ throw new Error("Not implemented.");} FromSeconds(value: number): System.TimeSpan; //{ throw new Error("Not implemented.");} FromTicks(value: number): System.TimeSpan; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetLegacyFormatMode(): boolean; //{ throw new Error("Not implemented.");} Interval(value: number, scale: number): System.TimeSpan; //{ throw new Error("Not implemented.");} LegacyFormatMode(): boolean; //{ throw new Error("Not implemented.");} Negate(): System.TimeSpan; //{ throw new Error("Not implemented.");} Parse(s: string): System.TimeSpan; //{ throw new Error("Not implemented.");} Parse(input: string, formatProvider: System.IFormatProvider): System.TimeSpan; //{ throw new Error("Not implemented.");} ParseExact(input: string, format: string, formatProvider: System.IFormatProvider, styles: System.Globalization.TimeSpanStyles): System.TimeSpan; //{ throw new Error("Not implemented.");} ParseExact(input: string, formats: System.String[], formatProvider: System.IFormatProvider, styles: System.Globalization.TimeSpanStyles): System.TimeSpan; //{ throw new Error("Not implemented.");} ParseExact(input: string, format: string, formatProvider: System.IFormatProvider): System.TimeSpan; //{ throw new Error("Not implemented.");} ParseExact(input: string, formats: System.String[], formatProvider: System.IFormatProvider): System.TimeSpan; //{ throw new Error("Not implemented.");} Subtract(ts: System.TimeSpan): System.TimeSpan; //{ throw new Error("Not implemented.");} TimeToTicks(hour: number, minute: number, second: number): number; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} ToString(format: string): string; //{ throw new Error("Not implemented.");} ToString(format: string, formatProvider: System.IFormatProvider): string; //{ throw new Error("Not implemented.");} TryParse(s: string, result: any): boolean; //{ throw new Error("Not implemented.");} TryParse(input: string, formatProvider: System.IFormatProvider, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseExact(input: string, formats: System.String[], formatProvider: System.IFormatProvider, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseExact(input: string, format: string, formatProvider: System.IFormatProvider, styles: System.Globalization.TimeSpanStyles, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseExact(input: string, formats: System.String[], formatProvider: System.IFormatProvider, styles: System.Globalization.TimeSpanStyles, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseExact(input: string, format: string, formatProvider: System.IFormatProvider, result: any): boolean; //{ throw new Error("Not implemented.");} } export class TimeZoneInfo { Id: string; DisplayName: string; StandardName: string; DaylightName: string; BaseUtcOffset: System.TimeSpan; SupportsDaylightSavingTime: boolean; static Local: System.TimeZoneInfo; static Utc: System.TimeZoneInfo; private m_id: string; private m_displayName: string; private m_standardDisplayName: string; private m_daylightDisplayName: string; private m_baseUtcOffset: System.TimeSpan; private m_supportsDaylightSavingTime: boolean; private m_adjustmentRules: any; private static s_cachedData: any; private static s_maxDateOnly: Date; private static s_minDateOnly: Date; CheckDaylightSavingTimeNotSupported(timeZone: any): boolean; //{ throw new Error("Not implemented.");} CheckIsDst(startTime: Date, time: Date, endTime: Date): boolean; //{ throw new Error("Not implemented.");} ClearCachedData(): any; //{ throw new Error("Not implemented.");} ConvertTime(dateTimeOffset: Date, destinationTimeZone: System.TimeZoneInfo): Date; //{ throw new Error("Not implemented.");} ConvertTime(dateTime: Date, sourceTimeZone: System.TimeZoneInfo, destinationTimeZone: System.TimeZoneInfo): Date; //{ throw new Error("Not implemented.");} ConvertTime(dateTime: Date, sourceTimeZone: System.TimeZoneInfo, destinationTimeZone: System.TimeZoneInfo, flags: System.TimeZoneInfoOptions): Date; //{ throw new Error("Not implemented.");} ConvertTime(dateTime: Date, destinationTimeZone: System.TimeZoneInfo): Date; //{ throw new Error("Not implemented.");} ConvertTime(dateTime: Date, sourceTimeZone: System.TimeZoneInfo, destinationTimeZone: System.TimeZoneInfo, flags: System.TimeZoneInfoOptions, cachedData: any): Date; //{ throw new Error("Not implemented.");} ConvertTimeBySystemTimeZoneId(dateTime: Date, sourceTimeZoneId: string, destinationTimeZoneId: string): Date; //{ throw new Error("Not implemented.");} ConvertTimeBySystemTimeZoneId(dateTime: Date, destinationTimeZoneId: string): Date; //{ throw new Error("Not implemented.");} ConvertTimeBySystemTimeZoneId(dateTimeOffset: Date, destinationTimeZoneId: string): Date; //{ throw new Error("Not implemented.");} ConvertTimeFromUtc(dateTime: Date, destinationTimeZone: System.TimeZoneInfo): Date; //{ throw new Error("Not implemented.");} ConvertTimeToUtc(dateTime: Date): Date; //{ throw new Error("Not implemented.");} ConvertTimeToUtc(dateTime: Date, sourceTimeZone: System.TimeZoneInfo): Date; //{ throw new Error("Not implemented.");} ConvertTimeToUtc(dateTime: Date, flags: System.TimeZoneInfoOptions): Date; //{ throw new Error("Not implemented.");} ConvertUtcToTimeZone(ticks: number, destinationTimeZone: System.TimeZoneInfo, isAmbiguousLocalDst: any): Date; //{ throw new Error("Not implemented.");} CreateAdjustmentRuleFromTimeZoneInformation(timeZoneInformation: any, startDate: Date, endDate: Date): any; //{ throw new Error("Not implemented.");} CreateCustomTimeZone(id: string, baseUtcOffset: System.TimeSpan, displayName: string, standardDisplayName: string, daylightDisplayName: string, adjustmentRules: any, disableDaylightSavingTime: boolean): System.TimeZoneInfo; //{ throw new Error("Not implemented.");} CreateCustomTimeZone(id: string, baseUtcOffset: System.TimeSpan, displayName: string, standardDisplayName: string): System.TimeZoneInfo; //{ throw new Error("Not implemented.");} CreateCustomTimeZone(id: string, baseUtcOffset: System.TimeSpan, displayName: string, standardDisplayName: string, daylightDisplayName: string, adjustmentRules: any): System.TimeZoneInfo; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} Equals(other: System.TimeZoneInfo): boolean; //{ throw new Error("Not implemented.");} FindIdFromTimeZoneInformation(timeZone: any, dstDisabled: any): string; //{ throw new Error("Not implemented.");} FindSystemTimeZoneById(id: string): System.TimeZoneInfo; //{ throw new Error("Not implemented.");} FromSerializedString(source: string): System.TimeZoneInfo; //{ throw new Error("Not implemented.");} GetAdjustmentRuleForTime(dateTime: Date): any; //{ throw new Error("Not implemented.");} GetAdjustmentRules(): any; //{ throw new Error("Not implemented.");} GetAmbiguousTimeOffsets(dateTime: Date): any; //{ throw new Error("Not implemented.");} GetAmbiguousTimeOffsets(dateTimeOffset: Date): any; //{ throw new Error("Not implemented.");} GetDateTimeNowUtcOffsetFromUtc(time: Date, isAmbiguousLocalDst: any): System.TimeSpan; //{ throw new Error("Not implemented.");} GetDaylightTime(year: number, rule: any): any; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetIsAmbiguousTime(time: Date, rule: any, daylightTime: any): boolean; //{ throw new Error("Not implemented.");} GetIsDaylightSavings(time: Date, rule: any, daylightTime: any, flags: System.TimeZoneInfoOptions): boolean; //{ throw new Error("Not implemented.");} GetIsDaylightSavingsFromUtc(time: Date, Year: number, utc: System.TimeSpan, rule: any, isAmbiguousLocalDst: any): boolean; //{ throw new Error("Not implemented.");} GetIsInvalidTime(time: Date, rule: any, daylightTime: any): boolean; //{ throw new Error("Not implemented.");} GetLocalTimeZone(cachedData: any): System.TimeZoneInfo; //{ throw new Error("Not implemented.");} GetLocalTimeZoneFromWin32Data(timeZoneInformation: any, dstDisabled: boolean): System.TimeZoneInfo; //{ throw new Error("Not implemented.");} GetLocalUtcOffset(dateTime: Date, flags: System.TimeZoneInfoOptions): System.TimeSpan; //{ throw new Error("Not implemented.");} GetSystemTimeZones(): any; //{ throw new Error("Not implemented.");} GetUtcOffset(dateTime: Date, flags: System.TimeZoneInfoOptions, cachedData: any): System.TimeSpan; //{ throw new Error("Not implemented.");} GetUtcOffset(time: Date, zone: System.TimeZoneInfo, flags: System.TimeZoneInfoOptions): System.TimeSpan; //{ throw new Error("Not implemented.");} GetUtcOffset(dateTime: Date): System.TimeSpan; //{ throw new Error("Not implemented.");} GetUtcOffset(dateTimeOffset: Date): System.TimeSpan; //{ throw new Error("Not implemented.");} GetUtcOffset(dateTime: Date, flags: System.TimeZoneInfoOptions): System.TimeSpan; //{ throw new Error("Not implemented.");} GetUtcOffsetFromUtc(time: Date, zone: System.TimeZoneInfo, isDaylightSavings: any): System.TimeSpan; //{ throw new Error("Not implemented.");} GetUtcOffsetFromUtc(time: Date, zone: System.TimeZoneInfo): System.TimeSpan; //{ throw new Error("Not implemented.");} GetUtcOffsetFromUtc(time: Date, zone: System.TimeZoneInfo, isDaylightSavings: any, isAmbiguousLocalDst: any): System.TimeSpan; //{ throw new Error("Not implemented.");} HasSameRules(other: System.TimeZoneInfo): boolean; //{ throw new Error("Not implemented.");} IsAmbiguousTime(dateTimeOffset: Date): boolean; //{ throw new Error("Not implemented.");} IsAmbiguousTime(dateTime: Date, flags: System.TimeZoneInfoOptions): boolean; //{ throw new Error("Not implemented.");} IsAmbiguousTime(dateTime: Date): boolean; //{ throw new Error("Not implemented.");} IsDaylightSavingTime(dateTime: Date, flags: System.TimeZoneInfoOptions, cachedData: any): boolean; //{ throw new Error("Not implemented.");} IsDaylightSavingTime(dateTime: Date, flags: System.TimeZoneInfoOptions): boolean; //{ throw new Error("Not implemented.");} IsDaylightSavingTime(dateTime: Date): boolean; //{ throw new Error("Not implemented.");} IsDaylightSavingTime(dateTimeOffset: Date): boolean; //{ throw new Error("Not implemented.");} IsInvalidTime(dateTime: Date): boolean; //{ throw new Error("Not implemented.");} ToSerializedString(): string; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} TransitionTimeFromTimeZoneInformation(timeZoneInformation: any, transitionTime: any, readStartDate: boolean): boolean; //{ throw new Error("Not implemented.");} TransitionTimeToDateTime(year: number, transitionTime: any): Date; //{ throw new Error("Not implemented.");} TryCompareStandardDate(timeZone: any, registryTimeZoneInfo: any): boolean; //{ throw new Error("Not implemented.");} TryCompareTimeZoneInformationToRegistry(timeZone: any, id: string, dstDisabled: any): boolean; //{ throw new Error("Not implemented.");} TryCreateAdjustmentRules(id: string, defaultTimeZoneInformation: any, rules: any, e: any): boolean; //{ throw new Error("Not implemented.");} TryGetLocalizedNameByMuiNativeResource(resource: string): string; //{ throw new Error("Not implemented.");} TryGetLocalizedNameByNativeResource(filePath: string, resource: number): string; //{ throw new Error("Not implemented.");} TryGetLocalizedNamesByRegistryKey(key: any, displayName: any, standardName: any, daylightName: any): boolean; //{ throw new Error("Not implemented.");} TryGetTimeZone(id: string, dstDisabled: boolean, value: any, e: any, cachedData: any): System.TimeZoneInfo.TimeZoneInfoResult; //{ throw new Error("Not implemented.");} TryGetTimeZoneByRegistryKey(id: string, value: any, e: any): System.TimeZoneInfo.TimeZoneInfoResult; //{ throw new Error("Not implemented.");} UtcOffsetOutOfRange(offset: System.TimeSpan): boolean; //{ throw new Error("Not implemented.");} ValidateTimeZoneInfo(id: string, baseUtcOffset: System.TimeSpan, adjustmentRules: any, adjustmentRulesSupportDst: any): any; //{ throw new Error("Not implemented.");} } export class Type extends System.Reflection.MemberInfo { MemberType: System.Reflection.MemberTypes; DeclaringType: System.Type; DeclaringMethod: System.Reflection.MethodBase; ReflectedType: System.Type; StructLayoutAttribute: System.Runtime.InteropServices.StructLayoutAttribute; GUID: System.Guid; static DefaultBinder: System.Reflection.Binder; Module: System.Reflection.Module; Assembly: System.Reflection.Assembly; TypeHandle: System.RuntimeTypeHandle; FullName: string; Namespace: string; AssemblyQualifiedName: string; BaseType: System.Type; TypeInitializer: System.Reflection.ConstructorInfo; IsNested: boolean; Attributes: System.Reflection.TypeAttributes; GenericParameterAttributes: System.Reflection.GenericParameterAttributes; IsVisible: boolean; IsNotPublic: boolean; IsPublic: boolean; IsNestedPublic: boolean; IsNestedPrivate: boolean; IsNestedFamily: boolean; IsNestedAssembly: boolean; IsNestedFamANDAssem: boolean; IsNestedFamORAssem: boolean; IsAutoLayout: boolean; IsLayoutSequential: boolean; IsExplicitLayout: boolean; IsClass: boolean; IsInterface: boolean; IsValueType: boolean; IsAbstract: boolean; IsSealed: boolean; IsEnum: boolean; IsSpecialName: boolean; IsImport: boolean; IsSerializable: boolean; IsAnsiClass: boolean; IsUnicodeClass: boolean; IsAutoClass: boolean; IsArray: boolean; IsSzArray: boolean; IsGenericType: boolean; IsGenericTypeDefinition: boolean; IsConstructedGenericType: boolean; IsGenericParameter: boolean; GenericParameterPosition: number; ContainsGenericParameters: boolean; IsByRef: boolean; IsPointer: boolean; IsPrimitive: boolean; IsCOMObject: boolean; IsWindowsRuntimeObject: boolean; IsExportedToWindowsRuntime: boolean; HasElementType: boolean; IsContextful: boolean; IsMarshalByRef: boolean; HasProxyAttribute: boolean; GenericTypeArguments: System.Type[]; IsSecurityCritical: boolean; IsSecuritySafeCritical: boolean; IsSecurityTransparent: boolean; NeedsReflectionSecurityCheck: boolean; UnderlyingSystemType: System.Type; static FilterAttribute: any; static FilterName: any; static FilterNameIgnoreCase: any; static Missing: any; static Delimiter: string; static EmptyTypes: System.Type[]; private static defaultBinder: System.Reflection.Binder; BinarySearch(array: System.Array, value: any): number; //{ throw new Error("Not implemented.");} CreateBinder(): any; //{ throw new Error("Not implemented.");} Equals(o: System.Type): boolean; //{ throw new Error("Not implemented.");} Equals(o: any): boolean; //{ throw new Error("Not implemented.");} FindInterfaces(filter: any, filterCriteria: any): System.Type[]; //{ throw new Error("Not implemented.");} FindMembers(memberType: System.Reflection.MemberTypes, bindingAttr: System.Reflection.BindingFlags, filter: any, filterCriteria: any): any; //{ throw new Error("Not implemented.");} FormatTypeName(serialization: boolean): string; //{ throw new Error("Not implemented.");} FormatTypeName(): string; //{ throw new Error("Not implemented.");} GetArrayRank(): number; //{ throw new Error("Not implemented.");} GetAttributeFlagsImpl(): System.Reflection.TypeAttributes; //{ throw new Error("Not implemented.");} GetConstructor(types: System.Type[]): System.Reflection.ConstructorInfo; //{ throw new Error("Not implemented.");} GetConstructor(bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, types: System.Type[], modifiers: any): System.Reflection.ConstructorInfo; //{ throw new Error("Not implemented.");} GetConstructor(bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, callConvention: System.Reflection.CallingConventions, types: System.Type[], modifiers: any): System.Reflection.ConstructorInfo; //{ throw new Error("Not implemented.");} GetConstructorImpl(bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, callConvention: System.Reflection.CallingConventions, types: System.Type[], modifiers: any): System.Reflection.ConstructorInfo; //{ throw new Error("Not implemented.");} GetConstructors(bindingAttr: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetConstructors(): any; //{ throw new Error("Not implemented.");} GetDefaultMembers(): any; //{ throw new Error("Not implemented.");} GetElementType(): System.Type; //{ throw new Error("Not implemented.");} GetEnumData(enumNames: any, enumValues: any): any; //{ throw new Error("Not implemented.");} GetEnumName(value: any): string; //{ throw new Error("Not implemented.");} GetEnumNames(): System.String[]; //{ throw new Error("Not implemented.");} GetEnumRawConstantValues(): System.Array; //{ throw new Error("Not implemented.");} GetEnumUnderlyingType(): System.Type; //{ throw new Error("Not implemented.");} GetEnumValues(): System.Array; //{ throw new Error("Not implemented.");} GetEvent(name: string, bindingAttr: System.Reflection.BindingFlags): System.Reflection.EventInfo; //{ throw new Error("Not implemented.");} GetEvent(name: string): System.Reflection.EventInfo; //{ throw new Error("Not implemented.");} GetEvents(): any; //{ throw new Error("Not implemented.");} GetEvents(bindingAttr: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetField(name: string): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} GetField(name: string, bindingAttr: System.Reflection.BindingFlags): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} GetFields(bindingAttr: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetFields(): any; //{ throw new Error("Not implemented.");} GetGenericArguments(): System.Type[]; //{ throw new Error("Not implemented.");} GetGenericParameterConstraints(): System.Type[]; //{ throw new Error("Not implemented.");} GetGenericTypeDefinition(): System.Type; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetInterface(name: string, ignoreCase: boolean): System.Type; //{ throw new Error("Not implemented.");} GetInterface(name: string): System.Type; //{ throw new Error("Not implemented.");} GetInterfaceMap(interfaceType: System.Type): any; //{ throw new Error("Not implemented.");} GetInterfaces(): System.Type[]; //{ throw new Error("Not implemented.");} GetMember(name: string, type: System.Reflection.MemberTypes, bindingAttr: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetMember(name: string, bindingAttr: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetMember(name: string): any; //{ throw new Error("Not implemented.");} GetMembers(bindingAttr: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetMembers(): any; //{ throw new Error("Not implemented.");} GetMethod(name: string, bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, types: System.Type[], modifiers: any): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethod(name: string): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethod(name: string, bindingAttr: System.Reflection.BindingFlags): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethod(name: string, types: System.Type[]): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethod(name: string, types: System.Type[], modifiers: any): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethod(name: string, bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, callConvention: System.Reflection.CallingConventions, types: System.Type[], modifiers: any): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethodImpl(name: string, bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, callConvention: System.Reflection.CallingConventions, types: System.Type[], modifiers: any): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethods(bindingAttr: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetMethods(): any; //{ throw new Error("Not implemented.");} GetNestedType(name: string): System.Type; //{ throw new Error("Not implemented.");} GetNestedType(name: string, bindingAttr: System.Reflection.BindingFlags): System.Type; //{ throw new Error("Not implemented.");} GetNestedTypes(): System.Type[]; //{ throw new Error("Not implemented.");} GetNestedTypes(bindingAttr: System.Reflection.BindingFlags): System.Type[]; //{ throw new Error("Not implemented.");} GetProperties(): any; //{ throw new Error("Not implemented.");} GetProperties(bindingAttr: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetProperty(name: string, bindingAttr: System.Reflection.BindingFlags, returnType: System.Type): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} GetProperty(name: string): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} GetProperty(name: string, returnType: System.Type): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} GetProperty(name: string, returnType: System.Type, types: System.Type[]): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} GetProperty(name: string, bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, returnType: System.Type, types: System.Type[], modifiers: any): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} GetProperty(name: string, returnType: System.Type, types: System.Type[], modifiers: any): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} GetProperty(name: string, types: System.Type[]): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} GetProperty(name: string, bindingAttr: System.Reflection.BindingFlags): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} GetPropertyImpl(name: string, bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, returnType: System.Type, types: System.Type[], modifiers: any): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} GetRootElementType(): System.Type; //{ throw new Error("Not implemented.");} GetType(typeName: string, assemblyResolver: System.Func<T, TResult>, typeResolver: any, throwOnError: boolean, ignoreCase: boolean): System.Type; //{ throw new Error("Not implemented.");} GetType(typeName: string, assemblyResolver: System.Func<T, TResult>, typeResolver: any): System.Type; //{ throw new Error("Not implemented.");} GetType(typeName: string, assemblyResolver: System.Func<T, TResult>, typeResolver: any, throwOnError: boolean): System.Type; //{ throw new Error("Not implemented.");} GetType(typeName: string, throwOnError: boolean): System.Type; //{ throw new Error("Not implemented.");} GetType(): System.Type; //{ throw new Error("Not implemented.");} GetType(typeName: string, throwOnError: boolean, ignoreCase: boolean): System.Type; //{ throw new Error("Not implemented.");} GetType(typeName: string): System.Type; //{ throw new Error("Not implemented.");} GetTypeArray(args: any): System.Type[]; //{ throw new Error("Not implemented.");} GetTypeCode(type: System.Type): System.TypeCode; //{ throw new Error("Not implemented.");} GetTypeCodeImpl(): System.TypeCode; //{ throw new Error("Not implemented.");} GetTypeFromCLSID(clsid: System.Guid, server: string, throwOnError: boolean): System.Type; //{ throw new Error("Not implemented.");} GetTypeFromCLSID(clsid: System.Guid, server: string): System.Type; //{ throw new Error("Not implemented.");} GetTypeFromCLSID(clsid: System.Guid, throwOnError: boolean): System.Type; //{ throw new Error("Not implemented.");} GetTypeFromCLSID(clsid: System.Guid): System.Type; //{ throw new Error("Not implemented.");} GetTypeFromHandle(handle: System.RuntimeTypeHandle): System.Type; //{ throw new Error("Not implemented.");} GetTypeFromHandleUnsafe(handle: number): any; //{ throw new Error("Not implemented.");} GetTypeFromProgID(progID: string, server: string): System.Type; //{ throw new Error("Not implemented.");} GetTypeFromProgID(progID: string): System.Type; //{ throw new Error("Not implemented.");} GetTypeFromProgID(progID: string, throwOnError: boolean): System.Type; //{ throw new Error("Not implemented.");} GetTypeFromProgID(progID: string, server: string, throwOnError: boolean): System.Type; //{ throw new Error("Not implemented.");} GetTypeHandle(o: any): System.RuntimeTypeHandle; //{ throw new Error("Not implemented.");} GetTypeHandleInternal(): System.RuntimeTypeHandle; //{ throw new Error("Not implemented.");} HasElementTypeImpl(): boolean; //{ throw new Error("Not implemented.");} HasProxyAttributeImpl(): boolean; //{ throw new Error("Not implemented.");} ImplementInterface(ifaceType: System.Type): boolean; //{ throw new Error("Not implemented.");} InvokeMember(name: string, invokeAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, target: any, args: any): any; //{ throw new Error("Not implemented.");} InvokeMember(name: string, invokeAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, target: any, args: any, modifiers: any, culture: System.Globalization.CultureInfo, namedParameters: System.String[]): any; //{ throw new Error("Not implemented.");} InvokeMember(name: string, invokeAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, target: any, args: any, culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} IsArrayImpl(): boolean; //{ throw new Error("Not implemented.");} IsAssignableFrom(c: System.Type): boolean; //{ throw new Error("Not implemented.");} IsByRefImpl(): boolean; //{ throw new Error("Not implemented.");} IsCOMObjectImpl(): boolean; //{ throw new Error("Not implemented.");} IsContextfulImpl(): boolean; //{ throw new Error("Not implemented.");} IsEnumDefined(value: any): boolean; //{ throw new Error("Not implemented.");} IsEquivalentTo(other: System.Type): boolean; //{ throw new Error("Not implemented.");} IsExportedToWindowsRuntimeImpl(): boolean; //{ throw new Error("Not implemented.");} IsInstanceOfType(o: any): boolean; //{ throw new Error("Not implemented.");} IsIntegerType(t: System.Type): boolean; //{ throw new Error("Not implemented.");} IsMarshalByRefImpl(): boolean; //{ throw new Error("Not implemented.");} IsPointerImpl(): boolean; //{ throw new Error("Not implemented.");} IsPrimitiveImpl(): boolean; //{ throw new Error("Not implemented.");} IsSubclassOf(c: System.Type): boolean; //{ throw new Error("Not implemented.");} IsValueTypeImpl(): boolean; //{ throw new Error("Not implemented.");} IsWindowsRuntimeObjectImpl(): boolean; //{ throw new Error("Not implemented.");} MakeArrayType(): System.Type; //{ throw new Error("Not implemented.");} MakeArrayType(rank: number): System.Type; //{ throw new Error("Not implemented.");} MakeByRefType(): System.Type; //{ throw new Error("Not implemented.");} MakeGenericType(typeArguments: System.Type[]): System.Type; //{ throw new Error("Not implemented.");} MakePointerType(): System.Type; //{ throw new Error("Not implemented.");} ReflectionOnlyGetType(typeName: string, throwIfNotFound: boolean, ignoreCase: boolean): System.Type; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} } export class Uri { private IsImplicitFile: boolean; private IsUncOrDosPath: boolean; private IsDosPath: boolean; private IsUncPath: boolean; private HostType: System.Uri.Flags; private Syntax: System.UriParser; private IsNotAbsoluteUri: boolean; private AllowIdn: boolean; UserDrivenParsing: boolean; private SecuredPathIndex: number; AbsolutePath: string; private PrivateAbsolutePath: string; AbsoluteUri: string; LocalPath: string; Authority: string; HostNameType: System.UriHostNameType; IsDefaultPort: boolean; IsFile: boolean; IsLoopback: boolean; PathAndQuery: string; Segments: System.String[]; IsUnc: boolean; Host: string; private static InitializeLock: any; Port: number; Query: string; Fragment: string; Scheme: string; private OriginalStringSwitched: boolean; OriginalString: string; DnsSafeHost: string; IdnHost: string; IsAbsoluteUri: boolean; UserEscaped: boolean; UserInfo: string; HasAuthority: boolean; private m_String: string; private m_originalUnicodeString: string; private m_Syntax: System.UriParser; private m_DnsSafeHost: string; private m_Flags: System.Uri.Flags; private m_Info: any; private m_iriParsing: boolean; static UriSchemeFile: string; static UriSchemeFtp: string; static UriSchemeGopher: string; static UriSchemeHttp: string; static UriSchemeHttps: string; static UriSchemeWs: string; static UriSchemeWss: string; static UriSchemeMailto: string; static UriSchemeNews: string; static UriSchemeNntp: string; static UriSchemeNetTcp: string; static UriSchemeNetPipe: string; static SchemeDelimiter: string; private static s_ManagerRef: any; private static s_IntranetLock: any; private static s_ConfigInitialized: boolean; private static s_ConfigInitializing: boolean; private static s_IdnScope: System.UriIdnScope; private static s_IriParsing: boolean; private static s_initLock: any; static HexLowerChars: any; private static _WSchars: any; AllowIdnStatic(syntax: System.UriParser, flags: System.Uri.Flags): boolean; //{ throw new Error("Not implemented.");} CalculateCaseInsensitiveHashCode(text: string): number; //{ throw new Error("Not implemented.");} Canonicalize(): any; //{ throw new Error("Not implemented.");} CheckAuthorityHelper(pString: any, idx: number, length: number, err: any, flags: any, syntax: System.UriParser, newHost: any): number; //{ throw new Error("Not implemented.");} CheckAuthorityHelperHandleAnyHostIri(pString: any, startInput: number, end: number, iriParsing: boolean, hasUnicode: boolean, syntax: System.UriParser, flags: any, newHost: any, err: any): any; //{ throw new Error("Not implemented.");} CheckAuthorityHelperHandleDnsIri(pString: any, start: number, end: number, startInput: number, iriParsing: boolean, hasUnicode: boolean, syntax: System.UriParser, userInfoString: string, flags: any, justNormalized: any, newHost: any, err: any): any; //{ throw new Error("Not implemented.");} CheckCanonical(str: any, idx: any, end: number, delim: string): System.Uri.Check; //{ throw new Error("Not implemented.");} CheckForColonInFirstPathSegment(uriString: string): boolean; //{ throw new Error("Not implemented.");} CheckForConfigLoad(data: string): boolean; //{ throw new Error("Not implemented.");} CheckForEscapedUnreserved(data: string): boolean; //{ throw new Error("Not implemented.");} CheckForUnicode(data: string): boolean; //{ throw new Error("Not implemented.");} CheckHostName(name: string): System.UriHostNameType; //{ throw new Error("Not implemented.");} CheckKnownSchemes(lptr: any, nChars: number, syntax: any): boolean; //{ throw new Error("Not implemented.");} CheckSchemeName(schemeName: string): boolean; //{ throw new Error("Not implemented.");} CheckSchemeSyntax(ptr: any, length: number, syntax: any): System.ParsingError; //{ throw new Error("Not implemented.");} CheckSecurity(): any; //{ throw new Error("Not implemented.");} CombineUri(basePart: System.Uri, relativePart: string, uriFormat: System.UriFormat): string; //{ throw new Error("Not implemented.");} Compare(uri1: System.Uri, uri2: System.Uri, partsToCompare: System.UriComponents, compareFormat: System.UriFormat, comparisonType: System.StringComparison): number; //{ throw new Error("Not implemented.");} Compress(dest: any, start: number, destLength: any, syntax: System.UriParser): any; //{ throw new Error("Not implemented.");} CreateHelper(uriString: string, dontEscape: boolean, uriKind: System.UriKind, e: any): System.Uri; //{ throw new Error("Not implemented.");} CreateHostString(): any; //{ throw new Error("Not implemented.");} CreateHostStringHelper(str: string, idx: number, end: number, flags: any, scopeId: any): string; //{ throw new Error("Not implemented.");} CreateThis(uri: string, dontEscape: boolean, uriKind: System.UriKind): any; //{ throw new Error("Not implemented.");} CreateThisFromUri(otherUri: System.Uri): any; //{ throw new Error("Not implemented.");} CreateUri(baseUri: System.Uri, relativeUri: string, dontEscape: boolean): any; //{ throw new Error("Not implemented.");} CreateUriInfo(cF: System.Uri.Flags): any; //{ throw new Error("Not implemented.");} EnsureHostString(allowDnsOptimization: boolean): any; //{ throw new Error("Not implemented.");} EnsureParseRemaining(): any; //{ throw new Error("Not implemented.");} EnsureUriInfo(): any; //{ throw new Error("Not implemented.");} Equals(comparand: any): boolean; //{ throw new Error("Not implemented.");} Escape(): any; //{ throw new Error("Not implemented.");} EscapeDataString(stringToEscape: string): string; //{ throw new Error("Not implemented.");} EscapeString(str: string): string; //{ throw new Error("Not implemented.");} EscapeUnescapeIri(input: string, start: number, end: number, component: System.UriComponents): string; //{ throw new Error("Not implemented.");} EscapeUriString(stringToEscape: string): string; //{ throw new Error("Not implemented.");} FindEndOfComponent(str: any, idx: any, end: number, delim: string): any; //{ throw new Error("Not implemented.");} FindEndOfComponent(input: string, idx: any, end: number, delim: string): any; //{ throw new Error("Not implemented.");} FromHex(digit: string): number; //{ throw new Error("Not implemented.");} GetCanonicalPath(dest: any, pos: any, formatAs: System.UriFormat): any; //{ throw new Error("Not implemented.");} GetCombinedString(baseUri: System.Uri, relativeStr: string, dontEscape: boolean, result: any): System.ParsingError; //{ throw new Error("Not implemented.");} GetComponents(components: System.UriComponents, format: System.UriFormat): string; //{ throw new Error("Not implemented.");} GetComponentsHelper(uriComponents: System.UriComponents, uriFormat: System.UriFormat): string; //{ throw new Error("Not implemented.");} GetEscapedParts(uriParts: System.UriComponents): string; //{ throw new Error("Not implemented.");} GetException(err: System.ParsingError): any; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetHostViaCustomSyntax(): any; //{ throw new Error("Not implemented.");} GetLeftPart(part: System.UriPartial): string; //{ throw new Error("Not implemented.");} GetLocalPath(): string; //{ throw new Error("Not implemented.");} GetObjectData(serializationInfo: any, streamingContext: any): any; //{ throw new Error("Not implemented.");} GetParts(uriParts: System.UriComponents, formatAs: System.UriFormat): string; //{ throw new Error("Not implemented.");} GetRelativeSerializationString(format: System.UriFormat): string; //{ throw new Error("Not implemented.");} GetUnescapedParts(uriParts: System.UriComponents, formatAs: System.UriFormat): string; //{ throw new Error("Not implemented.");} GetUriPartsFromUserString(uriParts: System.UriComponents): string; //{ throw new Error("Not implemented.");} HexEscape(character: string): string; //{ throw new Error("Not implemented.");} HexUnescape(pattern: string, index: any): string; //{ throw new Error("Not implemented.");} InFact(flags: System.Uri.Flags): boolean; //{ throw new Error("Not implemented.");} InitializeUri(err: System.ParsingError, uriKind: System.UriKind, e: any): any; //{ throw new Error("Not implemented.");} InitializeUriConfig(): any; //{ throw new Error("Not implemented.");} InternalEscapeString(rawString: string): string; //{ throw new Error("Not implemented.");} InternalIsWellFormedOriginalString(): boolean; //{ throw new Error("Not implemented.");} IriParsingStatic(syntax: System.UriParser): boolean; //{ throw new Error("Not implemented.");} IsAsciiLetter(character: string): boolean; //{ throw new Error("Not implemented.");} IsAsciiLetterOrDigit(character: string): boolean; //{ throw new Error("Not implemented.");} IsBadFileSystemCharacter(character: string): boolean; //{ throw new Error("Not implemented.");} IsBaseOf(uri: System.Uri): boolean; //{ throw new Error("Not implemented.");} IsBaseOfHelper(uriLink: System.Uri): boolean; //{ throw new Error("Not implemented.");} IsBidiControlCharacter(ch: string): boolean; //{ throw new Error("Not implemented.");} IsExcludedCharacter(character: string): boolean; //{ throw new Error("Not implemented.");} IsGenDelim(ch: string): boolean; //{ throw new Error("Not implemented.");} IsHexDigit(character: string): boolean; //{ throw new Error("Not implemented.");} IsHexEncoding(pattern: string, index: number): boolean; //{ throw new Error("Not implemented.");} IsIntranet(schemeHost: string): boolean; //{ throw new Error("Not implemented.");} IsLWS(ch: string): boolean; //{ throw new Error("Not implemented.");} IsReservedCharacter(character: string): boolean; //{ throw new Error("Not implemented.");} IsWellFormedOriginalString(): boolean; //{ throw new Error("Not implemented.");} IsWellFormedUriString(uriString: string, uriKind: System.UriKind): boolean; //{ throw new Error("Not implemented.");} MakeRelative(toUri: System.Uri): string; //{ throw new Error("Not implemented.");} MakeRelativeUri(uri: System.Uri): System.Uri; //{ throw new Error("Not implemented.");} NotAny(flags: System.Uri.Flags): boolean; //{ throw new Error("Not implemented.");} Parse(): any; //{ throw new Error("Not implemented.");} ParseMinimal(): any; //{ throw new Error("Not implemented.");} ParseRemaining(): any; //{ throw new Error("Not implemented.");} ParseScheme(uriString: string, flags: any, syntax: any): System.ParsingError; //{ throw new Error("Not implemented.");} ParseSchemeCheckImplicitFile(uriString: any, length: number, err: any, flags: any, syntax: any): number; //{ throw new Error("Not implemented.");} PathDifference(path1: string, path2: string, compareCase: boolean): string; //{ throw new Error("Not implemented.");} PrivateParseMinimal(): System.ParsingError; //{ throw new Error("Not implemented.");} PrivateParseMinimalIri(newHost: string, idx: number): any; //{ throw new Error("Not implemented.");} ReCreateParts(parts: System.UriComponents, nonCanonical: number, formatAs: System.UriFormat): string; //{ throw new Error("Not implemented.");} ResolveHelper(baseUri: System.Uri, relativeUri: System.Uri, newUriString: any, userEscaped: any, e: any): System.Uri; //{ throw new Error("Not implemented.");} SetEscapedDotSlashSettings(uriSection: any, scheme: string): any; //{ throw new Error("Not implemented.");} SetUserDrivenParsing(): any; //{ throw new Error("Not implemented.");} StaticInFact(allFlags: System.Uri.Flags, checkFlags: System.Uri.Flags): boolean; //{ throw new Error("Not implemented.");} StaticIsFile(syntax: System.UriParser): boolean; //{ throw new Error("Not implemented.");} StaticNotAny(allFlags: System.Uri.Flags, checkFlags: System.Uri.Flags): boolean; //{ throw new Error("Not implemented.");} StripBidiControlCharacter(strToClean: any, start: number, length: number): string; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} TryCreate(baseUri: System.Uri, relativeUri: System.Uri, result: any): boolean; //{ throw new Error("Not implemented.");} TryCreate(baseUri: System.Uri, relativeUri: string, result: any): boolean; //{ throw new Error("Not implemented.");} TryCreate(uriString: string, uriKind: System.UriKind, result: any): boolean; //{ throw new Error("Not implemented.");} Unescape(path: string): string; //{ throw new Error("Not implemented.");} UnescapeDataString(stringToUnescape: string): string; //{ throw new Error("Not implemented.");} UnescapeOnly(pch: any, start: number, end: any, ch1: string, ch2: string, ch3: string): any; //{ throw new Error("Not implemented.");} } export class UriParser { SchemeName: string; DefaultPort: number; static ShouldUseLegacyV2Quirks: boolean; Flags: System.UriSyntaxFlags; IsSimple: boolean; private m_Flags: System.UriSyntaxFlags; private m_UpdatableFlags: System.UriSyntaxFlags; private m_UpdatableFlagsUsed: boolean; private m_Port: number; private m_Scheme: string; private static m_Table: System.Collections.Generic.Dictionary<TKey, TValue>; private static m_TempTable: System.Collections.Generic.Dictionary<TKey, TValue>; static HttpUri: System.UriParser; static HttpsUri: System.UriParser; static WsUri: System.UriParser; static WssUri: System.UriParser; static FtpUri: System.UriParser; static FileUri: System.UriParser; static GopherUri: System.UriParser; static NntpUri: System.UriParser; static NewsUri: System.UriParser; static MailToUri: System.UriParser; static UuidUri: System.UriParser; static TelnetUri: System.UriParser; static LdapUri: System.UriParser; static NetTcpUri: System.UriParser; static NetPipeUri: System.UriParser; static VsMacrosUri: System.UriParser; private static s_QuirksVersion: System.UriParser.UriQuirksVersion; private static HttpSyntaxFlags: System.UriSyntaxFlags; private static FileSyntaxFlags: System.UriSyntaxFlags; CheckSetIsSimpleFlag(): any; //{ throw new Error("Not implemented.");} FetchSyntax(syntax: System.UriParser, lwrCaseSchemeName: string, defaultPort: number): any; //{ throw new Error("Not implemented.");} FindOrFetchAsUnknownV1Syntax(lwrCaseScheme: string): System.UriParser; //{ throw new Error("Not implemented.");} GetComponents(uri: System.Uri, components: System.UriComponents, format: System.UriFormat): string; //{ throw new Error("Not implemented.");} GetSyntax(lwrCaseScheme: string): System.UriParser; //{ throw new Error("Not implemented.");} InFact(flags: System.UriSyntaxFlags): boolean; //{ throw new Error("Not implemented.");} InitializeAndValidate(uri: System.Uri, parsingError: any): any; //{ throw new Error("Not implemented.");} InternalGetComponents(thisUri: System.Uri, uriComponents: System.UriComponents, uriFormat: System.UriFormat): string; //{ throw new Error("Not implemented.");} InternalIsBaseOf(thisBaseUri: System.Uri, uriLink: System.Uri): boolean; //{ throw new Error("Not implemented.");} InternalIsWellFormedOriginalString(thisUri: System.Uri): boolean; //{ throw new Error("Not implemented.");} InternalOnNewUri(): System.UriParser; //{ throw new Error("Not implemented.");} InternalResolve(thisBaseUri: System.Uri, uriLink: System.Uri, parsingError: any): string; //{ throw new Error("Not implemented.");} InternalValidate(thisUri: System.Uri, parsingError: any): any; //{ throw new Error("Not implemented.");} IsAllSet(flags: System.UriSyntaxFlags): boolean; //{ throw new Error("Not implemented.");} IsBaseOf(baseUri: System.Uri, relativeUri: System.Uri): boolean; //{ throw new Error("Not implemented.");} IsFullMatch(flags: System.UriSyntaxFlags, expected: System.UriSyntaxFlags): boolean; //{ throw new Error("Not implemented.");} IsKnownScheme(schemeName: string): boolean; //{ throw new Error("Not implemented.");} IsWellFormedOriginalString(uri: System.Uri): boolean; //{ throw new Error("Not implemented.");} NotAny(flags: System.UriSyntaxFlags): boolean; //{ throw new Error("Not implemented.");} OnNewUri(): System.UriParser; //{ throw new Error("Not implemented.");} OnRegister(schemeName: string, defaultPort: number): any; //{ throw new Error("Not implemented.");} Register(uriParser: System.UriParser, schemeName: string, defaultPort: number): any; //{ throw new Error("Not implemented.");} Resolve(baseUri: System.Uri, relativeUri: System.Uri, parsingError: any): string; //{ throw new Error("Not implemented.");} SetUpdatableFlags(flags: System.UriSyntaxFlags): any; //{ throw new Error("Not implemented.");} } export class Version { Major: number; Minor: number; Build: number; Revision: number; MajorRevision: number; MinorRevision: number; private _Major: number; private _Minor: number; private _Build: number; private _Revision: number; private static SeparatorsArray: any; AppendPositiveNumber(num: number, sb: any): any; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} CompareTo(version: any): number; //{ throw new Error("Not implemented.");} CompareTo(value: System.Version): number; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} Equals(obj: System.Version): boolean; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} Parse(input: string): System.Version; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} ToString(fieldCount: number): string; //{ throw new Error("Not implemented.");} TryParse(input: string, result: any): boolean; //{ throw new Error("Not implemented.");} TryParseComponent(component: string, componentName: string, result: any, parsedComponent: any): boolean; //{ throw new Error("Not implemented.");} TryParseVersion(version: string, result: any): boolean; //{ throw new Error("Not implemented.");} } } declare module System.Collections { export class ArrayList { Capacity: number; Count: number; IsFixedSize: boolean; IsReadOnly: boolean; IsSynchronized: boolean; SyncRoot: any; Item: any; private _items: any; private _size: number; private _version: number; private _syncRoot: any; private static emptyArray: any; Adapter(list: System.Collections.IList): System.Collections.ArrayList; //{ throw new Error("Not implemented.");} Add(value: any): number; //{ throw new Error("Not implemented.");} AddRange(c: System.Collections.ICollection): any; //{ throw new Error("Not implemented.");} BinarySearch(index: number, count: number, value: any, comparer: System.Collections.IComparer): number; //{ throw new Error("Not implemented.");} BinarySearch(value: any): number; //{ throw new Error("Not implemented.");} BinarySearch(value: any, comparer: System.Collections.IComparer): number; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} Contains(item: any): boolean; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array): any; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array, arrayIndex: number): any; //{ throw new Error("Not implemented.");} CopyTo(index: number, array: System.Array, arrayIndex: number, count: number): any; //{ throw new Error("Not implemented.");} EnsureCapacity(min: number): any; //{ throw new Error("Not implemented.");} FixedSize(list: System.Collections.ArrayList): System.Collections.ArrayList; //{ throw new Error("Not implemented.");} FixedSize(list: System.Collections.IList): System.Collections.IList; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetEnumerator(index: number, count: number): any; //{ throw new Error("Not implemented.");} GetRange(index: number, count: number): System.Collections.ArrayList; //{ throw new Error("Not implemented.");} IndexOf(value: any): number; //{ throw new Error("Not implemented.");} IndexOf(value: any, startIndex: number): number; //{ throw new Error("Not implemented.");} IndexOf(value: any, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} Insert(index: number, value: any): any; //{ throw new Error("Not implemented.");} InsertRange(index: number, c: System.Collections.ICollection): any; //{ throw new Error("Not implemented.");} LastIndexOf(value: any): number; //{ throw new Error("Not implemented.");} LastIndexOf(value: any, startIndex: number): number; //{ throw new Error("Not implemented.");} LastIndexOf(value: any, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} ReadOnly(list: System.Collections.IList): System.Collections.IList; //{ throw new Error("Not implemented.");} ReadOnly(list: System.Collections.ArrayList): System.Collections.ArrayList; //{ throw new Error("Not implemented.");} Remove(obj: any): any; //{ throw new Error("Not implemented.");} RemoveAt(index: number): any; //{ throw new Error("Not implemented.");} RemoveRange(index: number, count: number): any; //{ throw new Error("Not implemented.");} Repeat(value: any, count: number): System.Collections.ArrayList; //{ throw new Error("Not implemented.");} Reverse(): any; //{ throw new Error("Not implemented.");} Reverse(index: number, count: number): any; //{ throw new Error("Not implemented.");} SetRange(index: number, c: System.Collections.ICollection): any; //{ throw new Error("Not implemented.");} Sort(): any; //{ throw new Error("Not implemented.");} Sort(comparer: System.Collections.IComparer): any; //{ throw new Error("Not implemented.");} Sort(index: number, count: number, comparer: System.Collections.IComparer): any; //{ throw new Error("Not implemented.");} Synchronized(list: System.Collections.IList): System.Collections.IList; //{ throw new Error("Not implemented.");} Synchronized(list: System.Collections.ArrayList): System.Collections.ArrayList; //{ throw new Error("Not implemented.");} ToArray(): any; //{ throw new Error("Not implemented.");} ToArray(type: System.Type): System.Array; //{ throw new Error("Not implemented.");} TrimToSize(): any; //{ throw new Error("Not implemented.");} } export class CollectionBase { InnerList: System.Collections.ArrayList; List: System.Collections.IList; Capacity: number; Count: number; private System.Collections.IList.IsReadOnly: boolean; private System.Collections.IList.IsFixedSize: boolean; private System.Collections.ICollection.IsSynchronized: boolean; private System.Collections.ICollection.SyncRoot: any; private System.Collections.IList.Item: any; private list: System.Collections.ArrayList; Clear(): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} OnClear(): any; //{ throw new Error("Not implemented.");} OnClearComplete(): any; //{ throw new Error("Not implemented.");} OnInsert(index: number, value: any): any; //{ throw new Error("Not implemented.");} OnInsertComplete(index: number, value: any): any; //{ throw new Error("Not implemented.");} OnRemove(index: number, value: any): any; //{ throw new Error("Not implemented.");} OnRemoveComplete(index: number, value: any): any; //{ throw new Error("Not implemented.");} OnSet(index: number, oldValue: any, newValue: any): any; //{ throw new Error("Not implemented.");} OnSetComplete(index: number, oldValue: any, newValue: any): any; //{ throw new Error("Not implemented.");} OnValidate(value: any): any; //{ throw new Error("Not implemented.");} RemoveAt(index: number): any; //{ throw new Error("Not implemented.");} } export class Hashtable { hcp: System.Collections.IHashCodeProvider; comparer: System.Collections.IComparer; EqualityComparer: System.Collections.IEqualityComparer; Item: any; IsReadOnly: boolean; IsFixedSize: boolean; IsSynchronized: boolean; Keys: System.Collections.ICollection; Values: System.Collections.ICollection; SyncRoot: any; Count: number; private buckets: any; private count: number; private occupancy: number; private loadsize: number; private loadFactor: number; private version: number; private isWriterInProgress: boolean; private keys: System.Collections.ICollection; private values: System.Collections.ICollection; private _keycomparer: System.Collections.IEqualityComparer; private _syncRoot: any; Add(key: any, value: any): any; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} Contains(key: any): boolean; //{ throw new Error("Not implemented.");} ContainsKey(key: any): boolean; //{ throw new Error("Not implemented.");} ContainsValue(value: any): boolean; //{ throw new Error("Not implemented.");} CopyEntries(array: System.Array, arrayIndex: number): any; //{ throw new Error("Not implemented.");} CopyKeys(array: System.Array, arrayIndex: number): any; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array, arrayIndex: number): any; //{ throw new Error("Not implemented.");} CopyValues(array: System.Array, arrayIndex: number): any; //{ throw new Error("Not implemented.");} expand(): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetHash(key: any): number; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} InitHash(key: any, hashsize: number, seed: any, incr: any): number; //{ throw new Error("Not implemented.");} Insert(key: any, nvalue: any, add: boolean): any; //{ throw new Error("Not implemented.");} KeyEquals(item: any, key: any): boolean; //{ throw new Error("Not implemented.");} OnDeserialization(sender: any): any; //{ throw new Error("Not implemented.");} putEntry(newBuckets: any, key: any, nvalue: any, hashcode: number): any; //{ throw new Error("Not implemented.");} rehash(newsize: number, forceNewHashCode: boolean): any; //{ throw new Error("Not implemented.");} rehash(): any; //{ throw new Error("Not implemented.");} Remove(key: any): any; //{ throw new Error("Not implemented.");} Synchronized(table: System.Collections.Hashtable): System.Collections.Hashtable; //{ throw new Error("Not implemented.");} ToKeyValuePairsArray(): any; //{ throw new Error("Not implemented.");} UpdateVersion(): any; //{ throw new Error("Not implemented.");} } interface ICollection { Count: number; SyncRoot: any; IsSynchronized: boolean; CopyTo(array: System.Array, index: number): any; } interface IComparer { Compare(x: any, y: any): number; } interface IDictionary { Item: any; Keys: System.Collections.ICollection; Values: System.Collections.ICollection; IsReadOnly: boolean; IsFixedSize: boolean; Add(key: any, value: any): any; Clear(): any; Contains(key: any): boolean; GetEnumerator(): any; Remove(key: any): any; } interface IEqualityComparer { Equals(x: any, y: any): boolean; GetHashCode(obj: any): number; } interface IHashCodeProvider { GetHashCode(obj: any): number; } interface IList { Item: any; IsReadOnly: boolean; IsFixedSize: boolean; Add(value: any): number; Clear(): any; Contains(value: any): boolean; IndexOf(value: any): number; Insert(index: number, value: any): any; Remove(value: any): any; RemoveAt(index: number): any; } export class SortedList { Capacity: number; Count: number; Keys: System.Collections.ICollection; Values: System.Collections.ICollection; IsReadOnly: boolean; IsFixedSize: boolean; IsSynchronized: boolean; SyncRoot: any; Item: any; private keys: any; private values: any; private _size: number; private version: number; private comparer: System.Collections.IComparer; private keyList: any; private valueList: any; private _syncRoot: any; private static emptyArray: any; Add(key: any, value: any): any; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} Contains(key: any): boolean; //{ throw new Error("Not implemented.");} ContainsKey(key: any): boolean; //{ throw new Error("Not implemented.");} ContainsValue(value: any): boolean; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array, arrayIndex: number): any; //{ throw new Error("Not implemented.");} EnsureCapacity(min: number): any; //{ throw new Error("Not implemented.");} GetByIndex(index: number): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetKey(index: number): any; //{ throw new Error("Not implemented.");} GetKeyList(): System.Collections.IList; //{ throw new Error("Not implemented.");} GetValueList(): System.Collections.IList; //{ throw new Error("Not implemented.");} IndexOfKey(key: any): number; //{ throw new Error("Not implemented.");} IndexOfValue(value: any): number; //{ throw new Error("Not implemented.");} Init(): any; //{ throw new Error("Not implemented.");} Insert(index: number, key: any, value: any): any; //{ throw new Error("Not implemented.");} Remove(key: any): any; //{ throw new Error("Not implemented.");} RemoveAt(index: number): any; //{ throw new Error("Not implemented.");} SetByIndex(index: number, value: any): any; //{ throw new Error("Not implemented.");} Synchronized(list: System.Collections.SortedList): System.Collections.SortedList; //{ throw new Error("Not implemented.");} ToKeyValuePairsArray(): any; //{ throw new Error("Not implemented.");} TrimToSize(): any; //{ throw new Error("Not implemented.");} } } declare module System.Collections.Generic { export class Dictionary<TKey, TValue> { Comparer: System.Collections.Generic.IEqualityComparer<TKey>; Count: number; Keys: System.Collections.Generic.Dictionary`2.KeyCollection<TKey, TValue>; private System.Collections.Generic.IDictionary<TKey, TValue>.Keys: System.Collections.Generic.ICollection<TKey>; private System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys: System.Collections.Generic.IEnumerable<TKey>; Values: System.Collections.Generic.Dictionary`2.ValueCollection<TKey, TValue>; private System.Collections.Generic.IDictionary<TKey, TValue>.Values: System.Collections.Generic.ICollection<TValue>; private System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values: System.Collections.Generic.IEnumerable<TValue>; Item: TValue; private System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue >>.IsReadOnly: boolean; private System.Collections.ICollection.IsSynchronized: boolean; private System.Collections.ICollection.SyncRoot: any; private System.Collections.IDictionary.IsFixedSize: boolean; private System.Collections.IDictionary.IsReadOnly: boolean; private System.Collections.IDictionary.Keys: System.Collections.ICollection; private System.Collections.IDictionary.Values: System.Collections.ICollection; private System.Collections.IDictionary.Item: any; private buckets: System.Int32[]; private entries: any; private count: number; private version: number; private freeList: number; private freeCount: number; private comparer: System.Collections.Generic.IEqualityComparer < TKey>; private keys: System.Collections.Generic.Dictionary`2.KeyCollection < TKey, TValue>; private values: System.Collections.Generic.Dictionary`2.ValueCollection < TKey, TValue>; private _syncRoot: any; Add(key: TKey, value: TValue): any; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} ContainsKey(key: TKey): boolean; //{ throw new Error("Not implemented.");} ContainsValue(value: TValue): boolean; //{ throw new Error("Not implemented.");} CopyTo(array: any, index: number): any; //{ throw new Error("Not implemented.");} FindEntry(key: TKey): number; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} GetValueOrDefault(key: TKey): TValue; //{ throw new Error("Not implemented.");} Initialize(capacity: number): any; //{ throw new Error("Not implemented.");} Insert(key: TKey, value: TValue, add: boolean): any; //{ throw new Error("Not implemented.");} IsCompatibleKey(key: any): boolean; //{ throw new Error("Not implemented.");} OnDeserialization(sender: any): any; //{ throw new Error("Not implemented.");} Remove(key: TKey): boolean; //{ throw new Error("Not implemented.");} Resize(newSize: number, forceNewHashCodes: boolean): any; //{ throw new Error("Not implemented.");} Resize(): any; //{ throw new Error("Not implemented.");} TryGetValue(key: TKey, value: any): boolean; //{ throw new Error("Not implemented.");} } interface ICollection<T> { Count: number; IsReadOnly: boolean; Add(item: T): any; Clear(): any; Contains(item: T): boolean; CopyTo(array: any, arrayIndex: number): any; Remove(item: T): boolean; } interface IDictionary<TKey, TValue> { Item: TValue; Keys: System.Collections.Generic.ICollection<TKey>; Values: System.Collections.Generic.ICollection<TValue>; Add(key: TKey, value: TValue): any; ContainsKey(key: TKey): boolean; Remove(key: TKey): boolean; TryGetValue(key: TKey, value: any): boolean; } interface IEnumerable<T> { GetEnumerator(): any; } interface IEqualityComparer<T> { Equals(x: T, y: T): boolean; GetHashCode(obj: T): number; } interface IList<T> { Item: T; IndexOf(item: T): number; Insert(index: number, item: T): any; RemoveAt(index: number): any; } class KeyValuePair<TKey, TValue> { Key: TKey; Value: TValue; private key: TKey; private value: TValue; ToString(): string; //{ throw new Error("Not implemented.");} } export class List<T> { Capacity: number; Count: number; private System.Collections.IList.IsFixedSize: boolean; private System.Collections.Generic.ICollection<T>.IsReadOnly: boolean; private System.Collections.IList.IsReadOnly: boolean; private System.Collections.ICollection.IsSynchronized: boolean; private System.Collections.ICollection.SyncRoot: any; Item: T; private System.Collections.IList.Item: any; private _items: any; private _size: number; private _version: number; private _syncRoot: any; private static _emptyArray: any; Add(item: T): any; //{ throw new Error("Not implemented.");} AddRange(collection: System.Collections.Generic.IEnumerable<T>): any; //{ throw new Error("Not implemented.");} AsReadOnly(): any; //{ throw new Error("Not implemented.");} BinarySearch(index: number, count: number, item: T, comparer: any): number; //{ throw new Error("Not implemented.");} BinarySearch(item: T): number; //{ throw new Error("Not implemented.");} BinarySearch(item: T, comparer: any): number; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} Contains(item: T): boolean; //{ throw new Error("Not implemented.");} ConvertAll(converter: any): System.Collections.Generic.List<T>; //{ throw new Error("Not implemented.");} CopyTo(array: any): any; //{ throw new Error("Not implemented.");} CopyTo(index: number, array: any, arrayIndex: number, count: number): any; //{ throw new Error("Not implemented.");} CopyTo(array: any, arrayIndex: number): any; //{ throw new Error("Not implemented.");} EnsureCapacity(min: number): any; //{ throw new Error("Not implemented.");} Exists(match: any): boolean; //{ throw new Error("Not implemented.");} Find(match: any): T; //{ throw new Error("Not implemented.");} FindAll(match: any): System.Collections.Generic.List<T>; //{ throw new Error("Not implemented.");} FindIndex(startIndex: number, count: number, match: any): number; //{ throw new Error("Not implemented.");} FindIndex(startIndex: number, match: any): number; //{ throw new Error("Not implemented.");} FindIndex(match: any): number; //{ throw new Error("Not implemented.");} FindLast(match: any): T; //{ throw new Error("Not implemented.");} FindLastIndex(match: any): number; //{ throw new Error("Not implemented.");} FindLastIndex(startIndex: number, match: any): number; //{ throw new Error("Not implemented.");} FindLastIndex(startIndex: number, count: number, match: any): number; //{ throw new Error("Not implemented.");} ForEach(action: any): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetRange(index: number, count: number): System.Collections.Generic.List<T>; //{ throw new Error("Not implemented.");} IndexOf(item: T, index: number): number; //{ throw new Error("Not implemented.");} IndexOf(item: T, index: number, count: number): number; //{ throw new Error("Not implemented.");} IndexOf(item: T): number; //{ throw new Error("Not implemented.");} Insert(index: number, item: T): any; //{ throw new Error("Not implemented.");} InsertRange(index: number, collection: System.Collections.Generic.IEnumerable<T>): any; //{ throw new Error("Not implemented.");} IsCompatibleObject(value: any): boolean; //{ throw new Error("Not implemented.");} LastIndexOf(item: T): number; //{ throw new Error("Not implemented.");} LastIndexOf(item: T, index: number, count: number): number; //{ throw new Error("Not implemented.");} LastIndexOf(item: T, index: number): number; //{ throw new Error("Not implemented.");} Remove(item: T): boolean; //{ throw new Error("Not implemented.");} RemoveAll(match: any): number; //{ throw new Error("Not implemented.");} RemoveAt(index: number): any; //{ throw new Error("Not implemented.");} RemoveRange(index: number, count: number): any; //{ throw new Error("Not implemented.");} Reverse(index: number, count: number): any; //{ throw new Error("Not implemented.");} Reverse(): any; //{ throw new Error("Not implemented.");} Sort(comparison: any): any; //{ throw new Error("Not implemented.");} Sort(index: number, count: number, comparer: any): any; //{ throw new Error("Not implemented.");} Sort(comparer: any): any; //{ throw new Error("Not implemented.");} Sort(): any; //{ throw new Error("Not implemented.");} Synchronized(list: System.Collections.Generic.List<T>): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} ToArray(): any; //{ throw new Error("Not implemented.");} TrimExcess(): any; //{ throw new Error("Not implemented.");} TrueForAll(match: any): boolean; //{ throw new Error("Not implemented.");} } } declare module System.Collections.Generic.Dictionary`2 { export class KeyCollection<TKey, TValue> { Count: number; private System.Collections.Generic.ICollection<TKey>.IsReadOnly: boolean; private System.Collections.ICollection.IsSynchronized: boolean; private System.Collections.ICollection.SyncRoot: any; private dictionary: System.Collections.Generic.Dictionary<TKey, TValue>; CopyTo(array: any, index: number): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} } export class ValueCollection<TKey, TValue> { Count: number; private System.Collections.Generic.ICollection<TValue>.IsReadOnly: boolean; private System.Collections.ICollection.IsSynchronized: boolean; private System.Collections.ICollection.SyncRoot: any; private dictionary: System.Collections.Generic.Dictionary<TKey, TValue>; CopyTo(array: any, index: number): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} } } declare module System.Collections.ObjectModel { export class Collection<T> { Count: number; Items: System.Collections.Generic.IList<T>; Item: T; private System.Collections.Generic.ICollection<T>.IsReadOnly: boolean; private System.Collections.ICollection.IsSynchronized: boolean; private System.Collections.ICollection.SyncRoot: any; private System.Collections.IList.Item: any; private System.Collections.IList.IsReadOnly: boolean; private System.Collections.IList.IsFixedSize: boolean; private items: System.Collections.Generic.IList<T>; private _syncRoot: any; Add(item: T): any; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} ClearItems(): any; //{ throw new Error("Not implemented.");} Contains(item: T): boolean; //{ throw new Error("Not implemented.");} CopyTo(array: any, index: number): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} IndexOf(item: T): number; //{ throw new Error("Not implemented.");} Insert(index: number, item: T): any; //{ throw new Error("Not implemented.");} InsertItem(index: number, item: T): any; //{ throw new Error("Not implemented.");} IsCompatibleObject(value: any): boolean; //{ throw new Error("Not implemented.");} Remove(item: T): boolean; //{ throw new Error("Not implemented.");} RemoveAt(index: number): any; //{ throw new Error("Not implemented.");} RemoveItem(index: number): any; //{ throw new Error("Not implemented.");} SetItem(index: number, item: T): any; //{ throw new Error("Not implemented.");} } } declare module System.Collections.Specialized { export class NameObjectCollectionBase { Comparer: System.Collections.IEqualityComparer; IsReadOnly: boolean; Count: number; private System.Collections.ICollection.SyncRoot: any; private System.Collections.ICollection.IsSynchronized: boolean; Keys: System.Collections.Specialized.NameObjectCollectionBase.KeysCollection; private _readOnly: boolean; private _entriesArray: System.Collections.ArrayList; private _keyComparer: System.Collections.IEqualityComparer; private _entriesTable: System.Collections.Hashtable; private _nullKeyEntry: any; private _keys: System.Collections.Specialized.NameObjectCollectionBase.KeysCollection; private _serializationInfo: any; private _version: number; private _syncRoot: any; private static defaultComparer: any; BaseAdd(name: string, value: any): any; //{ throw new Error("Not implemented.");} BaseClear(): any; //{ throw new Error("Not implemented.");} BaseGet(index: number): any; //{ throw new Error("Not implemented.");} BaseGet(name: string): any; //{ throw new Error("Not implemented.");} BaseGetAllKeys(): System.String[]; //{ throw new Error("Not implemented.");} BaseGetAllValues(type: System.Type): any; //{ throw new Error("Not implemented.");} BaseGetAllValues(): any; //{ throw new Error("Not implemented.");} BaseGetKey(index: number): string; //{ throw new Error("Not implemented.");} BaseHasKeys(): boolean; //{ throw new Error("Not implemented.");} BaseRemove(name: string): any; //{ throw new Error("Not implemented.");} BaseRemoveAt(index: number): any; //{ throw new Error("Not implemented.");} BaseSet(name: string, value: any): any; //{ throw new Error("Not implemented.");} BaseSet(index: number, value: any): any; //{ throw new Error("Not implemented.");} FindEntry(key: string): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} OnDeserialization(sender: any): any; //{ throw new Error("Not implemented.");} Reset(capacity: number): any; //{ throw new Error("Not implemented.");} Reset(): any; //{ throw new Error("Not implemented.");} } export class NameValueCollection extends System.Collections.Specialized.NameObjectCollectionBase { Item: string; Item: string; AllKeys: System.String[]; private _all: System.String[]; private _allKeys: System.String[]; Add(c: System.Collections.Specialized.NameValueCollection): any; //{ throw new Error("Not implemented.");} Add(name: string, value: string): any; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} CopyTo(dest: System.Array, index: number): any; //{ throw new Error("Not implemented.");} Get(name: string): string; //{ throw new Error("Not implemented.");} Get(index: number): string; //{ throw new Error("Not implemented.");} GetAsOneString(list: System.Collections.ArrayList): string; //{ throw new Error("Not implemented.");} GetAsStringArray(list: System.Collections.ArrayList): System.String[]; //{ throw new Error("Not implemented.");} GetKey(index: number): string; //{ throw new Error("Not implemented.");} GetValues(name: string): System.String[]; //{ throw new Error("Not implemented.");} GetValues(index: number): System.String[]; //{ throw new Error("Not implemented.");} HasKeys(): boolean; //{ throw new Error("Not implemented.");} InternalHasKeys(): boolean; //{ throw new Error("Not implemented.");} InvalidateCachedArrays(): any; //{ throw new Error("Not implemented.");} Remove(name: string): any; //{ throw new Error("Not implemented.");} Set(name: string, value: string): any; //{ throw new Error("Not implemented.");} } } declare module System.Collections.Specialized.NameObjectCollectionBase { export class KeysCollection { Item: string; Count: number; private System.Collections.ICollection.SyncRoot: any; private System.Collections.ICollection.IsSynchronized: boolean; private _coll: System.Collections.Specialized.NameObjectCollectionBase; Get(index: number): string; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} } } declare module System.ComponentModel { export class Win32Exception extends System.Runtime.InteropServices.ExternalException { NativeErrorCode: number; private nativeErrorCode: number; GetErrorMessage(error: number): string; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} } } declare module System.Globalization { export class Calendar { MinSupportedDateTime: Date; MaxSupportedDateTime: Date; ID: number; BaseCalendarID: number; AlgorithmType: System.Globalization.CalendarAlgorithmType; IsReadOnly: boolean; CurrentEraValue: number; Eras: System.Int32[]; DaysInYearBeforeMinSupportedYear: number; TwoDigitYearMax: number; m_currentEraValue: number; private m_isReadOnly: boolean; twoDigitYearMax: number; Add(time: Date, value: number, scale: number): Date; //{ throw new Error("Not implemented.");} AddDays(time: Date, days: number): Date; //{ throw new Error("Not implemented.");} AddHours(time: Date, hours: number): Date; //{ throw new Error("Not implemented.");} AddMilliseconds(time: Date, milliseconds: number): Date; //{ throw new Error("Not implemented.");} AddMinutes(time: Date, minutes: number): Date; //{ throw new Error("Not implemented.");} AddMonths(time: Date, months: number): Date; //{ throw new Error("Not implemented.");} AddSeconds(time: Date, seconds: number): Date; //{ throw new Error("Not implemented.");} AddWeeks(time: Date, weeks: number): Date; //{ throw new Error("Not implemented.");} AddYears(time: Date, years: number): Date; //{ throw new Error("Not implemented.");} CheckAddResult(ticks: number, minValue: Date, maxValue: Date): any; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} GetDayOfMonth(time: Date): number; //{ throw new Error("Not implemented.");} GetDayOfWeek(time: Date): System.DayOfWeek; //{ throw new Error("Not implemented.");} GetDayOfYear(time: Date): number; //{ throw new Error("Not implemented.");} GetDaysInMonth(year: number, month: number): number; //{ throw new Error("Not implemented.");} GetDaysInMonth(year: number, month: number, era: number): number; //{ throw new Error("Not implemented.");} GetDaysInYear(year: number): number; //{ throw new Error("Not implemented.");} GetDaysInYear(year: number, era: number): number; //{ throw new Error("Not implemented.");} GetEra(time: Date): number; //{ throw new Error("Not implemented.");} GetFirstDayWeekOfYear(time: Date, firstDayOfWeek: number): number; //{ throw new Error("Not implemented.");} GetHour(time: Date): number; //{ throw new Error("Not implemented.");} GetLeapMonth(year: number): number; //{ throw new Error("Not implemented.");} GetLeapMonth(year: number, era: number): number; //{ throw new Error("Not implemented.");} GetMilliseconds(time: Date): number; //{ throw new Error("Not implemented.");} GetMinute(time: Date): number; //{ throw new Error("Not implemented.");} GetMonth(time: Date): number; //{ throw new Error("Not implemented.");} GetMonthsInYear(year: number): number; //{ throw new Error("Not implemented.");} GetMonthsInYear(year: number, era: number): number; //{ throw new Error("Not implemented.");} GetSecond(time: Date): number; //{ throw new Error("Not implemented.");} GetSystemTwoDigitYearSetting(CalID: number, defaultYearValue: number): number; //{ throw new Error("Not implemented.");} GetWeekOfYear(time: Date, rule: System.Globalization.CalendarWeekRule, firstDayOfWeek: System.DayOfWeek): number; //{ throw new Error("Not implemented.");} GetWeekOfYearFullDays(time: Date, firstDayOfWeek: number, fullDays: number): number; //{ throw new Error("Not implemented.");} GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek: number, minimumDaysInFirstWeek: number): number; //{ throw new Error("Not implemented.");} GetYear(time: Date): number; //{ throw new Error("Not implemented.");} IsLeapDay(year: number, month: number, day: number, era: number): boolean; //{ throw new Error("Not implemented.");} IsLeapDay(year: number, month: number, day: number): boolean; //{ throw new Error("Not implemented.");} IsLeapMonth(year: number, month: number): boolean; //{ throw new Error("Not implemented.");} IsLeapMonth(year: number, month: number, era: number): boolean; //{ throw new Error("Not implemented.");} IsLeapYear(year: number, era: number): boolean; //{ throw new Error("Not implemented.");} IsLeapYear(year: number): boolean; //{ throw new Error("Not implemented.");} IsValidDay(year: number, month: number, day: number, era: number): boolean; //{ throw new Error("Not implemented.");} IsValidMonth(year: number, month: number, era: number): boolean; //{ throw new Error("Not implemented.");} IsValidYear(year: number, era: number): boolean; //{ throw new Error("Not implemented.");} ReadOnly(calendar: System.Globalization.Calendar): System.Globalization.Calendar; //{ throw new Error("Not implemented.");} SetReadOnlyState(readOnly: boolean): any; //{ throw new Error("Not implemented.");} TimeToTicks(hour: number, minute: number, second: number, millisecond: number): number; //{ throw new Error("Not implemented.");} ToDateTime(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number): Date; //{ throw new Error("Not implemented.");} ToDateTime(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, era: number): Date; //{ throw new Error("Not implemented.");} ToFourDigitYear(year: number): number; //{ throw new Error("Not implemented.");} TryToDateTime(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, era: number, result: any): boolean; //{ throw new Error("Not implemented.");} VerifyWritable(): any; //{ throw new Error("Not implemented.");} } export class CompareInfo { Name: string; LCID: number; static IsLegacy20SortingBehaviorRequested: boolean; private static InternalSortVersion: number; Version: System.Globalization.SortVersion; private m_name: string; private m_sortName: string; private m_dataHandle: number; private m_handleOrigin: number; private win32LCID: number; private culture: number; private m_SortVersion: System.Globalization.SortVersion; Compare(string1: string, offset1: number, length1: number, string2: string, offset2: number, length2: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} Compare(string1: string, string2: string): number; //{ throw new Error("Not implemented.");} Compare(string1: string, string2: string, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} Compare(string1: string, offset1: number, length1: number, string2: string, offset2: number, length2: number): number; //{ throw new Error("Not implemented.");} Compare(string1: string, offset1: number, string2: string, offset2: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} Compare(string1: string, offset1: number, string2: string, offset2: number): number; //{ throw new Error("Not implemented.");} CompareOrdinal(string1: string, offset1: number, length1: number, string2: string, offset2: number, length2: number): number; //{ throw new Error("Not implemented.");} CreateSortKey(source: string, options: System.Globalization.CompareOptions): any; //{ throw new Error("Not implemented.");} Equals(value: any): boolean; //{ throw new Error("Not implemented.");} GetCompareInfo(culture: number, assembly: System.Reflection.Assembly): System.Globalization.CompareInfo; //{ throw new Error("Not implemented.");} GetCompareInfo(name: string, assembly: System.Reflection.Assembly): System.Globalization.CompareInfo; //{ throw new Error("Not implemented.");} GetCompareInfo(culture: number): System.Globalization.CompareInfo; //{ throw new Error("Not implemented.");} GetCompareInfo(name: string): System.Globalization.CompareInfo; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetHashCode(source: string, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} GetHashCodeOfString(source: string, options: System.Globalization.CompareOptions, forceRandomizedHashing: boolean, additionalEntropy: number): number; //{ throw new Error("Not implemented.");} GetHashCodeOfString(source: string, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} GetNativeCompareFlags(options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} GetSortKey(source: string, options: System.Globalization.CompareOptions): any; //{ throw new Error("Not implemented.");} GetSortKey(source: string): any; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, startIndex: number, count: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, startIndex: number, count: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, startIndex: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, startIndex: number): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, startIndex: number): number; //{ throw new Error("Not implemented.");} IndexOf(source: string, value: string, startIndex: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} InternalCompareString(handle: number, handleOrigin: number, localeName: string, string1: string, offset1: number, length1: number, string2: string, offset2: number, length2: number, flags: number): number; //{ throw new Error("Not implemented.");} InternalFindNLSStringEx(handle: number, handleOrigin: number, localeName: string, flags: number, source: string, sourceCount: number, startIndex: number, target: string, targetCount: number): number; //{ throw new Error("Not implemented.");} InternalGetGlobalizedHashCode(handle: number, handleOrigin: number, localeName: string, source: string, length: number, dwFlags: number, forceRandomizedHashing: boolean, additionalEntropy: number): number; //{ throw new Error("Not implemented.");} InternalGetNlsVersionEx(handle: number, handleOrigin: number, localeName: string, lpNlsVersionInformation: any): boolean; //{ throw new Error("Not implemented.");} InternalGetSortKey(handle: number, handleOrigin: number, localeName: string, flags: number, source: string, sourceCount: number, target: System.Byte[], targetCount: number): number; //{ throw new Error("Not implemented.");} InternalGetSortVersion(): number; //{ throw new Error("Not implemented.");} InternalInitSortHandle(localeName: string, handleOrigin: any): number; //{ throw new Error("Not implemented.");} InternalIsSortable(handle: number, handleOrigin: number, localeName: string, source: string, length: number): boolean; //{ throw new Error("Not implemented.");} IsPrefix(source: string, prefix: string, options: System.Globalization.CompareOptions): boolean; //{ throw new Error("Not implemented.");} IsPrefix(source: string, prefix: string): boolean; //{ throw new Error("Not implemented.");} IsSortable(ch: string): boolean; //{ throw new Error("Not implemented.");} IsSortable(text: string): boolean; //{ throw new Error("Not implemented.");} IsSuffix(source: string, suffix: string, options: System.Globalization.CompareOptions): boolean; //{ throw new Error("Not implemented.");} IsSuffix(source: string, suffix: string): boolean; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, startIndex: number): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, startIndex: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, startIndex: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, startIndex: number, count: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, startIndex: number, count: number, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, startIndex: number): number; //{ throw new Error("Not implemented.");} LastIndexOf(source: string, value: string, options: System.Globalization.CompareOptions): number; //{ throw new Error("Not implemented.");} NativeInternalInitSortHandle(localeName: string, handleOrigin: any): number; //{ throw new Error("Not implemented.");} OnDeserialized(ctx: any): any; //{ throw new Error("Not implemented.");} OnDeserialized(): any; //{ throw new Error("Not implemented.");} OnDeserializing(ctx: any): any; //{ throw new Error("Not implemented.");} OnSerializing(ctx: any): any; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} } export class CultureInfo { static CurrentUICulture: System.Globalization.CultureInfo; Name: string; IsSafeCrossDomain: boolean; CreatedDomainID: number; static CurrentCulture: System.Globalization.CultureInfo; static UserDefaultCulture: System.Globalization.CultureInfo; static UserDefaultUICulture: System.Globalization.CultureInfo; static InstalledUICulture: System.Globalization.CultureInfo; static DefaultThreadCurrentCulture: System.Globalization.CultureInfo; static DefaultThreadCurrentUICulture: System.Globalization.CultureInfo; static InvariantCulture: System.Globalization.CultureInfo; Parent: System.Globalization.CultureInfo; LCID: number; KeyboardLayoutId: number; SortName: string; IetfLanguageTag: string; DisplayName: string; NativeName: string; EnglishName: string; TwoLetterISOLanguageName: string; ThreeLetterISOLanguageName: string; ThreeLetterWindowsLanguageName: string; CompareInfo: System.Globalization.CompareInfo; private Region: System.Globalization.RegionInfo; TextInfo: System.Globalization.TextInfo; IsNeutralCulture: boolean; CultureTypes: System.Globalization.CultureTypes; NumberFormat: System.Globalization.NumberFormatInfo; DateTimeFormat: System.Globalization.DateTimeFormatInfo; Calendar: System.Globalization.Calendar; OptionalCalendars: System.Globalization.Calendar[]; UseUserOverride: boolean; IsReadOnly: boolean; HasInvariantCultureName: boolean; static IsTaiwanSku: boolean; m_isReadOnly: boolean; compareInfo: System.Globalization.CompareInfo; textInfo: System.Globalization.TextInfo; regionInfo: System.Globalization.RegionInfo; numInfo: System.Globalization.NumberFormatInfo; dateTimeInfo: System.Globalization.DateTimeFormatInfo; calendar: System.Globalization.Calendar; m_dataItem: number; cultureID: number; m_cultureData: any; m_isInherited: boolean; private m_isSafeCrossDomain: boolean; private m_createdDomainID: number; private m_consoleFallbackCulture: System.Globalization.CultureInfo; m_name: string; private m_nonSortName: string; private m_sortName: string; private m_parent: System.Globalization.CultureInfo; private m_useUserOverride: boolean; private static s_userDefaultCulture: System.Globalization.CultureInfo; private static s_InvariantCultureInfo: System.Globalization.CultureInfo; private static s_userDefaultUICulture: System.Globalization.CultureInfo; private static s_InstalledUICultureInfo: System.Globalization.CultureInfo; private static s_DefaultThreadCurrentUICulture: System.Globalization.CultureInfo; private static s_DefaultThreadCurrentCulture: System.Globalization.CultureInfo; private static s_LcidCachedCultures: System.Collections.Hashtable; private static s_NameCachedCultures: System.Collections.Hashtable; private static s_WindowsRuntimeResourceManager: any; private static init: boolean; private static s_isTaiwanSku: boolean; private static s_haveIsTaiwanSku: boolean; private static ts_IsDoingAppXCultureInfoLookup: boolean; CanSendCrossDomain(): boolean; //{ throw new Error("Not implemented.");} CheckDomainSafetyObject(obj: any, container: any): any; //{ throw new Error("Not implemented.");} ClearCachedData(): any; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} CreateSpecificCulture(name: string): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} Equals(value: any): boolean; //{ throw new Error("Not implemented.");} GetCalendarInstance(calType: number): System.Globalization.Calendar; //{ throw new Error("Not implemented.");} GetCalendarInstanceRare(calType: number): System.Globalization.Calendar; //{ throw new Error("Not implemented.");} GetConsoleFallbackUICulture(): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} GetCultureByName(name: string, userOverride: boolean): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} GetCultureInfo(name: string): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} GetCultureInfo(name: string, altName: string): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} GetCultureInfo(culture: number): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} GetCultureInfoByIetfLanguageTag(name: string): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} GetCultureInfoForUserPreferredLanguageInAppX(): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} GetCultureInfoHelper(lcid: number, name: string, altName: string): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} GetCultures(types: System.Globalization.CultureTypes): any; //{ throw new Error("Not implemented.");} GetDefaultLocaleName(localeType: number): string; //{ throw new Error("Not implemented.");} GetFormat(formatType: System.Type): any; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetSystemDefaultUILanguage(): string; //{ throw new Error("Not implemented.");} GetUserDefaultUILanguage(): string; //{ throw new Error("Not implemented.");} Init(): boolean; //{ throw new Error("Not implemented.");} InitializeFromCultureId(culture: number, useUserOverride: boolean): any; //{ throw new Error("Not implemented.");} InitUserDefaultCulture(): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} InitUserDefaultUICulture(): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} InternalGetDefaultLocaleName(localetype: number, localeString: any): boolean; //{ throw new Error("Not implemented.");} InternalGetSystemDefaultUILanguage(systemDefaultUiLanguage: any): boolean; //{ throw new Error("Not implemented.");} InternalGetUserDefaultUILanguage(userDefaultUiLanguage: any): boolean; //{ throw new Error("Not implemented.");} IsAlternateSortLcid(lcid: number): boolean; //{ throw new Error("Not implemented.");} nativeGetLocaleInfoEx(localeName: string, field: number): string; //{ throw new Error("Not implemented.");} nativeGetLocaleInfoExInt(localeName: string, field: number): number; //{ throw new Error("Not implemented.");} nativeSetThreadLocale(localeName: string): boolean; //{ throw new Error("Not implemented.");} OnDeserialized(ctx: any): any; //{ throw new Error("Not implemented.");} OnSerializing(ctx: any): any; //{ throw new Error("Not implemented.");} ReadOnly(ci: System.Globalization.CultureInfo): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} StartCrossDomainTracking(): any; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} VerifyCultureName(cultureName: string, throwException: boolean): boolean; //{ throw new Error("Not implemented.");} VerifyCultureName(culture: System.Globalization.CultureInfo, throwException: boolean): boolean; //{ throw new Error("Not implemented.");} VerifyWritable(): any; //{ throw new Error("Not implemented.");} } export class DateTimeFormatInfo { private CultureName: string; private Culture: System.Globalization.CultureInfo; private LanguageName: string; static InvariantInfo: System.Globalization.DateTimeFormatInfo; static CurrentInfo: System.Globalization.DateTimeFormatInfo; AMDesignator: string; Calendar: System.Globalization.Calendar; private OptionalCalendars: System.Int32[]; EraNames: System.String[]; AbbreviatedEraNames: System.String[]; AbbreviatedEnglishEraNames: System.String[]; DateSeparator: string; FirstDayOfWeek: System.DayOfWeek; CalendarWeekRule: System.Globalization.CalendarWeekRule; FullDateTimePattern: string; LongDatePattern: string; LongTimePattern: string; MonthDayPattern: string; PMDesignator: string; RFC1123Pattern: string; ShortDatePattern: string; ShortTimePattern: string; SortableDateTimePattern: string; GeneralShortTimePattern: string; GeneralLongTimePattern: string; DateTimeOffsetPattern: string; TimeSeparator: string; UniversalSortableDateTimePattern: string; YearMonthPattern: string; AbbreviatedDayNames: System.String[]; ShortestDayNames: System.String[]; DayNames: System.String[]; AbbreviatedMonthNames: System.String[]; MonthNames: System.String[]; HasSpacesInMonthNames: boolean; HasSpacesInDayNames: boolean; private AllYearMonthPatterns: System.String[]; private AllShortDatePatterns: System.String[]; private AllShortTimePatterns: System.String[]; private AllLongDatePatterns: System.String[]; private AllLongTimePatterns: System.String[]; private UnclonedYearMonthPatterns: System.String[]; private UnclonedShortDatePatterns: System.String[]; private UnclonedLongDatePatterns: System.String[]; private UnclonedShortTimePatterns: System.String[]; private UnclonedLongTimePatterns: System.String[]; IsReadOnly: boolean; NativeCalendarName: string; AbbreviatedMonthGenitiveNames: System.String[]; MonthGenitiveNames: System.String[]; FullTimeSpanPositivePattern: string; FullTimeSpanNegativePattern: string; CompareInfo: System.Globalization.CompareInfo; FormatFlags: System.Globalization.DateTimeFormatFlags; HasForceTwoDigitYears: boolean; HasYearMonthAdjustment: boolean; private m_cultureData: any; m_name: string; private m_langName: string; private m_compareInfo: System.Globalization.CompareInfo; private m_cultureInfo: System.Globalization.CultureInfo; amDesignator: string; pmDesignator: string; dateSeparator: string; generalShortTimePattern: string; generalLongTimePattern: string; timeSeparator: string; monthDayPattern: string; dateTimeOffsetPattern: string; calendar: System.Globalization.Calendar; firstDayOfWeek: number; calendarWeekRule: number; fullDateTimePattern: string; abbreviatedDayNames: System.String[]; m_superShortDayNames: System.String[]; dayNames: System.String[]; abbreviatedMonthNames: System.String[]; monthNames: System.String[]; genitiveMonthNames: System.String[]; m_genitiveAbbreviatedMonthNames: System.String[]; leapYearMonthNames: System.String[]; longDatePattern: string; shortDatePattern: string; yearMonthPattern: string; longTimePattern: string; shortTimePattern: string; private allYearMonthPatterns: System.String[]; allShortDatePatterns: System.String[]; allLongDatePatterns: System.String[]; allShortTimePatterns: System.String[]; allLongTimePatterns: System.String[]; m_eraNames: System.String[]; m_abbrevEraNames: System.String[]; m_abbrevEnglishEraNames: System.String[]; optionalCalendars: System.Int32[]; m_isReadOnly: boolean; formatFlags: System.Globalization.DateTimeFormatFlags; private CultureID: number; private m_useUserOverride: boolean; private bUseCalendarInfo: boolean; private nDataItem: number; m_isDefaultCalendar: boolean; m_dateWords: System.String[]; private m_fullTimeSpanPositivePattern: string; private m_fullTimeSpanNegativePattern: string; private m_dtfiTokenHash: any; private static invariantInfo: System.Globalization.DateTimeFormatInfo; static preferExistingTokens: boolean; private static s_calendarNativeNames: System.Collections.Hashtable; private static MonthSpaces: any; private static s_jajpDTFI: System.Globalization.DateTimeFormatInfo; private static s_zhtwDTFI: System.Globalization.DateTimeFormatInfo; AddMonthNames(temp: any, monthPostfix: string): any; //{ throw new Error("Not implemented.");} CheckNullValue(values: System.String[], length: number): any; //{ throw new Error("Not implemented.");} ClearTokenHashTable(): any; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} CreateTokenHashTable(): any; //{ throw new Error("Not implemented.");} GetAbbreviatedDayName(dayofweek: System.DayOfWeek): string; //{ throw new Error("Not implemented.");} GetAbbreviatedEraName(era: number): string; //{ throw new Error("Not implemented.");} GetAbbreviatedMonthName(month: number): string; //{ throw new Error("Not implemented.");} GetAllDateTimePatterns(): System.String[]; //{ throw new Error("Not implemented.");} GetAllDateTimePatterns(format: string): System.String[]; //{ throw new Error("Not implemented.");} GetCombinedPatterns(patterns1: System.String[], patterns2: System.String[], connectString: string): System.String[]; //{ throw new Error("Not implemented.");} GetDayName(dayofweek: System.DayOfWeek): string; //{ throw new Error("Not implemented.");} GetEra(eraName: string): number; //{ throw new Error("Not implemented.");} GetEraName(era: number): string; //{ throw new Error("Not implemented.");} GetFormat(formatType: System.Type): any; //{ throw new Error("Not implemented.");} GetInstance(provider: System.IFormatProvider): System.Globalization.DateTimeFormatInfo; //{ throw new Error("Not implemented.");} GetJapaneseCalendarDTFI(): System.Globalization.DateTimeFormatInfo; //{ throw new Error("Not implemented.");} GetMergedPatterns(patterns: System.String[], defaultPattern: string): System.String[]; //{ throw new Error("Not implemented.");} GetMonthName(month: number): string; //{ throw new Error("Not implemented.");} GetShortestDayName(dayOfWeek: System.DayOfWeek): string; //{ throw new Error("Not implemented.");} GetTaiwanCalendarDTFI(): System.Globalization.DateTimeFormatInfo; //{ throw new Error("Not implemented.");} InitializeOverridableProperties(cultureData: any, calendarID: number): any; //{ throw new Error("Not implemented.");} InitPreferExistingTokens(): boolean; //{ throw new Error("Not implemented.");} InsertAtCurrentHashNode(hashTable: any, str: string, ch: string, tokenType: System.TokenType, tokenValue: number, pos: number, hashcode: number, hashProbe: number): any; //{ throw new Error("Not implemented.");} InsertHash(hashTable: any, str: string, tokenType: System.TokenType, tokenValue: number): any; //{ throw new Error("Not implemented.");} internalGetAbbreviatedDayOfWeekNames(): System.String[]; //{ throw new Error("Not implemented.");} internalGetAbbreviatedMonthNames(): System.String[]; //{ throw new Error("Not implemented.");} internalGetDayOfWeekNames(): System.String[]; //{ throw new Error("Not implemented.");} internalGetGenitiveMonthNames(abbreviated: boolean): System.String[]; //{ throw new Error("Not implemented.");} internalGetLeapYearMonthNames(): System.String[]; //{ throw new Error("Not implemented.");} internalGetMonthName(month: number, style: System.Globalization.MonthNameStyles, abbreviated: boolean): string; //{ throw new Error("Not implemented.");} internalGetMonthNames(): System.String[]; //{ throw new Error("Not implemented.");} internalGetSuperShortDayNames(): System.String[]; //{ throw new Error("Not implemented.");} IsHebrewChar(ch: string): boolean; //{ throw new Error("Not implemented.");} OnDeserialized(ctx: any): any; //{ throw new Error("Not implemented.");} OnSerializing(ctx: any): any; //{ throw new Error("Not implemented.");} ReadOnly(dtfi: System.Globalization.DateTimeFormatInfo): System.Globalization.DateTimeFormatInfo; //{ throw new Error("Not implemented.");} SetAllDateTimePatterns(patterns: System.String[], format: string): any; //{ throw new Error("Not implemented.");} Tokenize(TokenMask: System.TokenType, tokenType: any, tokenValue: any, str: any): boolean; //{ throw new Error("Not implemented.");} TryParseHebrewNumber(str: any, badFormat: any, number: any): boolean; //{ throw new Error("Not implemented.");} ValidateStyles(style: System.Globalization.DateTimeStyles, parameterName: string): any; //{ throw new Error("Not implemented.");} YearMonthAdjustment(year: any, month: any, parsedMonthName: boolean): boolean; //{ throw new Error("Not implemented.");} } export class NumberFormatInfo { static InvariantInfo: System.Globalization.NumberFormatInfo; CurrencyDecimalDigits: number; CurrencyDecimalSeparator: string; IsReadOnly: boolean; CurrencyGroupSizes: System.Int32[]; NumberGroupSizes: System.Int32[]; PercentGroupSizes: System.Int32[]; CurrencyGroupSeparator: string; CurrencySymbol: string; static CurrentInfo: System.Globalization.NumberFormatInfo; NaNSymbol: string; CurrencyNegativePattern: number; NumberNegativePattern: number; PercentPositivePattern: number; PercentNegativePattern: number; NegativeInfinitySymbol: string; NegativeSign: string; NumberDecimalDigits: number; NumberDecimalSeparator: string; NumberGroupSeparator: string; CurrencyPositivePattern: number; PositiveInfinitySymbol: string; PositiveSign: string; PercentDecimalDigits: number; PercentDecimalSeparator: string; PercentGroupSeparator: string; PercentSymbol: string; PerMilleSymbol: string; NativeDigits: System.String[]; DigitSubstitution: System.Globalization.DigitShapes; numberGroupSizes: System.Int32[]; currencyGroupSizes: System.Int32[]; percentGroupSizes: System.Int32[]; positiveSign: string; negativeSign: string; numberDecimalSeparator: string; numberGroupSeparator: string; currencyGroupSeparator: string; currencyDecimalSeparator: string; currencySymbol: string; ansiCurrencySymbol: string; nanSymbol: string; positiveInfinitySymbol: string; negativeInfinitySymbol: string; percentDecimalSeparator: string; percentGroupSeparator: string; percentSymbol: string; perMilleSymbol: string; nativeDigits: System.String[]; m_dataItem: number; numberDecimalDigits: number; currencyDecimalDigits: number; currencyPositivePattern: number; currencyNegativePattern: number; numberNegativePattern: number; percentPositivePattern: number; percentNegativePattern: number; percentDecimalDigits: number; digitSubstitution: number; isReadOnly: boolean; m_useUserOverride: boolean; m_isInvariant: boolean; validForParseAsNumber: boolean; validForParseAsCurrency: boolean; private static invariantInfo: System.Globalization.NumberFormatInfo; CheckGroupSize(propName: string, groupSize: System.Int32[]): any; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} GetFormat(formatType: System.Type): any; //{ throw new Error("Not implemented.");} GetInstance(formatProvider: System.IFormatProvider): System.Globalization.NumberFormatInfo; //{ throw new Error("Not implemented.");} OnDeserialized(ctx: any): any; //{ throw new Error("Not implemented.");} OnDeserializing(ctx: any): any; //{ throw new Error("Not implemented.");} OnSerializing(ctx: any): any; //{ throw new Error("Not implemented.");} ReadOnly(nfi: System.Globalization.NumberFormatInfo): System.Globalization.NumberFormatInfo; //{ throw new Error("Not implemented.");} ValidateParseStyleFloatingPoint(style: System.Globalization.NumberStyles): any; //{ throw new Error("Not implemented.");} ValidateParseStyleInteger(style: System.Globalization.NumberStyles): any; //{ throw new Error("Not implemented.");} VerifyDecimalSeparator(decSep: string, propertyName: string): any; //{ throw new Error("Not implemented.");} VerifyDigitSubstitution(digitSub: System.Globalization.DigitShapes, propertyName: string): any; //{ throw new Error("Not implemented.");} VerifyGroupSeparator(groupSep: string, propertyName: string): any; //{ throw new Error("Not implemented.");} VerifyNativeDigits(nativeDig: System.String[], propertyName: string): any; //{ throw new Error("Not implemented.");} VerifyWritable(): any; //{ throw new Error("Not implemented.");} } export class RegionInfo { static CurrentRegion: System.Globalization.RegionInfo; Name: string; EnglishName: string; DisplayName: string; NativeName: string; TwoLetterISORegionName: string; ThreeLetterISORegionName: string; ThreeLetterWindowsRegionName: string; IsMetric: boolean; GeoId: number; CurrencyEnglishName: string; CurrencyNativeName: string; CurrencySymbol: string; ISOCurrencySymbol: string; m_name: string; m_cultureData: any; private m_cultureId: number; m_dataItem: number; static s_currentRegionInfo: System.Globalization.RegionInfo; private static IdFromEverettRegionInfoDataItem: System.Int32[]; Equals(value: any): boolean; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} OnDeserialized(ctx: any): any; //{ throw new Error("Not implemented.");} OnSerializing(ctx: any): any; //{ throw new Error("Not implemented.");} SetName(name: string): any; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} } export class SortVersion { FullVersion: number; SortId: System.Guid; private m_NlsVersion: number; private m_SortId: System.Guid; Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} Equals(other: System.Globalization.SortVersion): boolean; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} } export class TextInfo { static Invariant: System.Globalization.TextInfo; ANSICodePage: number; OEMCodePage: number; MacCodePage: number; EBCDICCodePage: number; LCID: number; CultureName: string; IsReadOnly: boolean; ListSeparator: string; private IsAsciiCasingSameAsInvariant: boolean; IsRightToLeft: boolean; private m_listSeparator: string; private m_isReadOnly: boolean; private m_cultureName: string; private m_cultureData: any; private m_textInfoName: string; private m_dataHandle: number; private m_handleOrigin: number; private m_IsAsciiCasingSameAsInvariant: boolean; private customCultureName: string; m_nDataItem: number; m_useUserOverride: boolean; m_win32LangID: number; static s_Invariant: System.Globalization.TextInfo; AddNonLetter(result: any, input: any, inputIndex: number, charLen: number): number; //{ throw new Error("Not implemented.");} AddTitlecaseLetter(result: any, input: any, inputIndex: number, charLen: number): number; //{ throw new Error("Not implemented.");} Clone(): any; //{ throw new Error("Not implemented.");} CompareOrdinalIgnoreCase(str1: string, str2: string): number; //{ throw new Error("Not implemented.");} CompareOrdinalIgnoreCaseEx(strA: string, indexA: number, strB: string, indexB: number, lengthA: number, lengthB: number): number; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetCaseInsensitiveHashCode(str: string, forceRandomizedHashing: boolean, additionalEntropy: number): number; //{ throw new Error("Not implemented.");} GetCaseInsensitiveHashCode(str: string): number; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetHashCodeOrdinalIgnoreCase(s: string): number; //{ throw new Error("Not implemented.");} GetHashCodeOrdinalIgnoreCase(s: string, forceRandomizedHashing: boolean, additionalEntropy: number): number; //{ throw new Error("Not implemented.");} IndexOfStringOrdinalIgnoreCase(source: string, value: string, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} InternalChangeCaseChar(handle: number, handleOrigin: number, localeName: string, ch: string, isToUpper: boolean): string; //{ throw new Error("Not implemented.");} InternalChangeCaseString(handle: number, handleOrigin: number, localeName: string, str: string, isToUpper: boolean): string; //{ throw new Error("Not implemented.");} InternalCompareStringOrdinalIgnoreCase(string1: string, index1: number, string2: string, index2: number, length1: number, length2: number): number; //{ throw new Error("Not implemented.");} InternalGetCaseInsHash(handle: number, handleOrigin: number, localeName: string, str: string, forceRandomizedHashing: boolean, additionalEntropy: number): number; //{ throw new Error("Not implemented.");} InternalTryFindStringOrdinalIgnoreCase(searchFlags: number, source: string, sourceCount: number, startIndex: number, target: string, targetCount: number, foundIndex: any): boolean; //{ throw new Error("Not implemented.");} IsAscii(c: string): boolean; //{ throw new Error("Not implemented.");} IsLetterCategory(uc: System.Globalization.UnicodeCategory): boolean; //{ throw new Error("Not implemented.");} IsWordSeparator(category: System.Globalization.UnicodeCategory): boolean; //{ throw new Error("Not implemented.");} LastIndexOfStringOrdinalIgnoreCase(source: string, value: string, startIndex: number, count: number): number; //{ throw new Error("Not implemented.");} OnDeserialized(ctx: any): any; //{ throw new Error("Not implemented.");} OnDeserialized(): any; //{ throw new Error("Not implemented.");} OnDeserializing(ctx: any): any; //{ throw new Error("Not implemented.");} OnSerializing(ctx: any): any; //{ throw new Error("Not implemented.");} ReadOnly(textInfo: System.Globalization.TextInfo): System.Globalization.TextInfo; //{ throw new Error("Not implemented.");} SetReadOnlyState(readOnly: boolean): any; //{ throw new Error("Not implemented.");} ToLower(str: string): string; //{ throw new Error("Not implemented.");} ToLower(c: string): string; //{ throw new Error("Not implemented.");} ToLowerAsciiInvariant(c: string): string; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} ToTitleCase(str: string): string; //{ throw new Error("Not implemented.");} ToUpper(c: string): string; //{ throw new Error("Not implemented.");} ToUpper(str: string): string; //{ throw new Error("Not implemented.");} ToUpperAsciiInvariant(c: string): string; //{ throw new Error("Not implemented.");} TryFastFindStringOrdinalIgnoreCase(searchFlags: number, source: string, startIndex: number, value: string, count: number, foundIndex: any): boolean; //{ throw new Error("Not implemented.");} VerifyWritable(): any; //{ throw new Error("Not implemented.");} } } declare module System.IO { export class Stream extends System.MarshalByRefObject { CanRead: boolean; CanSeek: boolean; CanTimeout: boolean; CanWrite: boolean; Length: number; Position: number; ReadTimeout: number; WriteTimeout: number; private _activeReadWriteTask: any; private _asyncActiveSemaphore: any; static Null: System.IO.Stream; BeginEndReadAsync(buffer: System.Byte[], offset: number, count: number): any; //{ throw new Error("Not implemented.");} BeginEndWriteAsync(buffer: System.Byte[], offset: number, count: number): any; //{ throw new Error("Not implemented.");} BeginRead(buffer: System.Byte[], offset: number, count: number, callback: System.AsyncCallback, state: any): System.IAsyncResult; //{ throw new Error("Not implemented.");} BeginReadInternal(buffer: System.Byte[], offset: number, count: number, callback: System.AsyncCallback, state: any, serializeAsynchronously: boolean): System.IAsyncResult; //{ throw new Error("Not implemented.");} BeginWrite(buffer: System.Byte[], offset: number, count: number, callback: System.AsyncCallback, state: any): System.IAsyncResult; //{ throw new Error("Not implemented.");} BeginWriteInternal(buffer: System.Byte[], offset: number, count: number, callback: System.AsyncCallback, state: any, serializeAsynchronously: boolean): System.IAsyncResult; //{ throw new Error("Not implemented.");} BlockingBeginRead(buffer: System.Byte[], offset: number, count: number, callback: System.AsyncCallback, state: any): System.IAsyncResult; //{ throw new Error("Not implemented.");} BlockingBeginWrite(buffer: System.Byte[], offset: number, count: number, callback: System.AsyncCallback, state: any): System.IAsyncResult; //{ throw new Error("Not implemented.");} BlockingEndRead(asyncResult: System.IAsyncResult): number; //{ throw new Error("Not implemented.");} BlockingEndWrite(asyncResult: System.IAsyncResult): any; //{ throw new Error("Not implemented.");} Close(): any; //{ throw new Error("Not implemented.");} CopyTo(destination: System.IO.Stream, bufferSize: number): any; //{ throw new Error("Not implemented.");} CopyTo(destination: System.IO.Stream): any; //{ throw new Error("Not implemented.");} CopyToAsync(destination: System.IO.Stream, bufferSize: number, cancellationToken: any): any; //{ throw new Error("Not implemented.");} CopyToAsync(destination: System.IO.Stream, bufferSize: number): any; //{ throw new Error("Not implemented.");} CopyToAsync(destination: System.IO.Stream): any; //{ throw new Error("Not implemented.");} CopyToAsyncInternal(destination: System.IO.Stream, bufferSize: number, cancellationToken: any): any; //{ throw new Error("Not implemented.");} CreateWaitHandle(): System.Threading.WaitHandle; //{ throw new Error("Not implemented.");} Dispose(disposing: boolean): any; //{ throw new Error("Not implemented.");} Dispose(): any; //{ throw new Error("Not implemented.");} EndRead(asyncResult: System.IAsyncResult): number; //{ throw new Error("Not implemented.");} EndWrite(asyncResult: System.IAsyncResult): any; //{ throw new Error("Not implemented.");} EnsureAsyncActiveSemaphoreInitialized(): any; //{ throw new Error("Not implemented.");} Flush(): any; //{ throw new Error("Not implemented.");} FlushAsync(): any; //{ throw new Error("Not implemented.");} FlushAsync(cancellationToken: any): any; //{ throw new Error("Not implemented.");} InternalCopyTo(destination: System.IO.Stream, bufferSize: number): any; //{ throw new Error("Not implemented.");} ObjectInvariant(): any; //{ throw new Error("Not implemented.");} Read(buffer: System.Byte[], offset: number, count: number): number; //{ throw new Error("Not implemented.");} ReadAsync(buffer: System.Byte[], offset: number, count: number): any; //{ throw new Error("Not implemented.");} ReadAsync(buffer: System.Byte[], offset: number, count: number, cancellationToken: any): any; //{ throw new Error("Not implemented.");} ReadByte(): number; //{ throw new Error("Not implemented.");} RunReadWriteTask(readWriteTask: any): any; //{ throw new Error("Not implemented.");} RunReadWriteTaskWhenReady(asyncWaiter: any, readWriteTask: any): any; //{ throw new Error("Not implemented.");} Seek(offset: number, origin: System.IO.SeekOrigin): number; //{ throw new Error("Not implemented.");} SetLength(value: number): any; //{ throw new Error("Not implemented.");} Synchronized(stream: System.IO.Stream): System.IO.Stream; //{ throw new Error("Not implemented.");} Write(buffer: System.Byte[], offset: number, count: number): any; //{ throw new Error("Not implemented.");} WriteAsync(buffer: System.Byte[], offset: number, count: number, cancellationToken: any): any; //{ throw new Error("Not implemented.");} WriteAsync(buffer: System.Byte[], offset: number, count: number): any; //{ throw new Error("Not implemented.");} WriteByte(value: number): any; //{ throw new Error("Not implemented.");} } export class TextWriter extends System.MarshalByRefObject { FormatProvider: System.IFormatProvider; Encoding: System.Text.Encoding; NewLine: string; CoreNewLine: any; private InternalFormatProvider: System.IFormatProvider; static Null: System.IO.TextWriter; private static _WriteCharDelegate: any; private static _WriteStringDelegate: any; private static _WriteCharArrayRangeDelegate: any; private static _WriteLineCharDelegate: any; private static _WriteLineStringDelegate: any; private static _WriteLineCharArrayRangeDelegate: any; private static _FlushDelegate: any; Close(): any; //{ throw new Error("Not implemented.");} Dispose(disposing: boolean): any; //{ throw new Error("Not implemented.");} Dispose(): any; //{ throw new Error("Not implemented.");} Flush(): any; //{ throw new Error("Not implemented.");} FlushAsync(): any; //{ throw new Error("Not implemented.");} Synchronized(writer: System.IO.TextWriter): System.IO.TextWriter; //{ throw new Error("Not implemented.");} Write(buffer: any, index: number, count: number): any; //{ throw new Error("Not implemented.");} Write(buffer: any): any; //{ throw new Error("Not implemented.");} Write(value: string): any; //{ throw new Error("Not implemented.");} Write(format: string, arg: any): any; //{ throw new Error("Not implemented.");} Write(format: string, arg0: any, arg1: any, arg2: any): any; //{ throw new Error("Not implemented.");} Write(format: string, arg0: any, arg1: any): any; //{ throw new Error("Not implemented.");} Write(value: boolean): any; //{ throw new Error("Not implemented.");} Write(value: any): any; //{ throw new Error("Not implemented.");} Write(value: number): any; //{ throw new Error("Not implemented.");} Write(format: string, arg0: any): any; //{ throw new Error("Not implemented.");} Write(value: number): any; //{ throw new Error("Not implemented.");} Write(value: number): any; //{ throw new Error("Not implemented.");} Write(value: number): any; //{ throw new Error("Not implemented.");} Write(value: number): any; //{ throw new Error("Not implemented.");} Write(value: number): any; //{ throw new Error("Not implemented.");} Write(value: string): any; //{ throw new Error("Not implemented.");} Write(value: number): any; //{ throw new Error("Not implemented.");} WriteAsync(buffer: any, index: number, count: number): any; //{ throw new Error("Not implemented.");} WriteAsync(buffer: any): any; //{ throw new Error("Not implemented.");} WriteAsync(value: string): any; //{ throw new Error("Not implemented.");} WriteAsync(value: string): any; //{ throw new Error("Not implemented.");} WriteLine(format: string, arg0: any, arg1: any, arg2: any): any; //{ throw new Error("Not implemented.");} WriteLine(format: string, arg: any): any; //{ throw new Error("Not implemented.");} WriteLine(format: string, arg0: any, arg1: any): any; //{ throw new Error("Not implemented.");} WriteLine(value: number): any; //{ throw new Error("Not implemented.");} WriteLine(value: any): any; //{ throw new Error("Not implemented.");} WriteLine(): any; //{ throw new Error("Not implemented.");} WriteLine(value: string): any; //{ throw new Error("Not implemented.");} WriteLine(buffer: any): any; //{ throw new Error("Not implemented.");} WriteLine(buffer: any, index: number, count: number): any; //{ throw new Error("Not implemented.");} WriteLine(value: boolean): any; //{ throw new Error("Not implemented.");} WriteLine(value: number): any; //{ throw new Error("Not implemented.");} WriteLine(format: string, arg0: any): any; //{ throw new Error("Not implemented.");} WriteLine(value: number): any; //{ throw new Error("Not implemented.");} WriteLine(value: number): any; //{ throw new Error("Not implemented.");} WriteLine(value: number): any; //{ throw new Error("Not implemented.");} WriteLine(value: number): any; //{ throw new Error("Not implemented.");} WriteLine(value: number): any; //{ throw new Error("Not implemented.");} WriteLine(value: string): any; //{ throw new Error("Not implemented.");} WriteLineAsync(value: string): any; //{ throw new Error("Not implemented.");} WriteLineAsync(): any; //{ throw new Error("Not implemented.");} WriteLineAsync(value: string): any; //{ throw new Error("Not implemented.");} WriteLineAsync(buffer: any): any; //{ throw new Error("Not implemented.");} WriteLineAsync(buffer: any, index: number, count: number): any; //{ throw new Error("Not implemented.");} } } declare module System.Net { export class CookieContainer { Capacity: number; Count: number; MaxCookieSize: number; PerDomainCapacity: number; private m_domainTable: System.Collections.Hashtable; private m_maxCookieSize: number; private m_maxCookies: number; private m_maxCookiesPerDomain: number; private m_count: number; private m_fqdnMyDomain: string; private static HeaderInfo: any; Add(cookie: any): any; //{ throw new Error("Not implemented.");} Add(cookie: any, throwOnError: boolean): any; //{ throw new Error("Not implemented.");} Add(cookies: any): any; //{ throw new Error("Not implemented.");} Add(uri: System.Uri, cookie: any): any; //{ throw new Error("Not implemented.");} Add(uri: System.Uri, cookies: any): any; //{ throw new Error("Not implemented.");} AddRemoveDomain(key: string, value: any): any; //{ throw new Error("Not implemented.");} AgeCookies(domain: string): boolean; //{ throw new Error("Not implemented.");} BuildCookieCollectionFromDomainMatches(uri: System.Uri, isSecure: boolean, port: number, cookies: any, domainAttribute: System.Collections.Generic.List<string>, matchOnlyPlainCookie: boolean): any; //{ throw new Error("Not implemented.");} CookieCutter(uri: System.Uri, headerName: string, setCookieHeader: string, isThrow: boolean): any; //{ throw new Error("Not implemented.");} ExpireCollection(cc: any): number; //{ throw new Error("Not implemented.");} GetCookieHeader(uri: System.Uri): string; //{ throw new Error("Not implemented.");} GetCookieHeader(uri: System.Uri, optCookie2: any): string; //{ throw new Error("Not implemented.");} GetCookies(uri: System.Uri): any; //{ throw new Error("Not implemented.");} InternalGetCookies(uri: System.Uri): any; //{ throw new Error("Not implemented.");} IsLocalDomain(host: string): boolean; //{ throw new Error("Not implemented.");} MergeUpdateCollections(destination: any, source: any, port: number, isSecure: boolean, isPlainOnly: boolean): any; //{ throw new Error("Not implemented.");} SetCookies(uri: System.Uri, cookieHeader: string): any; //{ throw new Error("Not implemented.");} } interface ICredentials { GetCredential(uri: System.Uri, authType: string): any; } export class IPAddress { Address: number; AddressFamily: System.Net.Sockets.AddressFamily; ScopeId: number; IsBroadcast: boolean; IsIPv6Multicast: boolean; IsIPv6LinkLocal: boolean; IsIPv6SiteLocal: boolean; IsIPv6Teredo: boolean; IsIPv4MappedToIPv6: boolean; m_Address: number; m_ToString: string; private m_Family: System.Net.Sockets.AddressFamily; private m_Numbers: any; private m_ScopeId: number; private m_HashCode: number; static Any: System.Net.IPAddress; static Loopback: System.Net.IPAddress; static Broadcast: System.Net.IPAddress; static None: System.Net.IPAddress; static IPv6Any: System.Net.IPAddress; static IPv6Loopback: System.Net.IPAddress; static IPv6None: System.Net.IPAddress; Equals(comparand: any): boolean; //{ throw new Error("Not implemented.");} Equals(comparandObj: any, compareScopeId: boolean): boolean; //{ throw new Error("Not implemented.");} GetAddressBytes(): System.Byte[]; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} HostToNetworkOrder(host: number): number; //{ throw new Error("Not implemented.");} HostToNetworkOrder(host: number): number; //{ throw new Error("Not implemented.");} HostToNetworkOrder(host: number): number; //{ throw new Error("Not implemented.");} InternalParse(ipString: string, tryParse: boolean): System.Net.IPAddress; //{ throw new Error("Not implemented.");} IsLoopback(address: System.Net.IPAddress): boolean; //{ throw new Error("Not implemented.");} MapToIPv4(): System.Net.IPAddress; //{ throw new Error("Not implemented.");} MapToIPv6(): System.Net.IPAddress; //{ throw new Error("Not implemented.");} NetworkToHostOrder(network: number): number; //{ throw new Error("Not implemented.");} NetworkToHostOrder(network: number): number; //{ throw new Error("Not implemented.");} NetworkToHostOrder(network: number): number; //{ throw new Error("Not implemented.");} Parse(ipString: string): System.Net.IPAddress; //{ throw new Error("Not implemented.");} Snapshot(): System.Net.IPAddress; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} TryParse(ipString: string, address: any): boolean; //{ throw new Error("Not implemented.");} } interface IWebProxy { Credentials: System.Net.ICredentials; GetProxy(destination: System.Uri): System.Uri; IsBypassed(host: System.Uri): boolean; } export class WebHeaderCollection extends System.Collections.Specialized.NameValueCollection { ContentLength: string; CacheControl: string; ContentType: string; Date: string; Expires: string; ETag: string; LastModified: string; Location: string; ProxyAuthenticate: string; SetCookie2: string; SetCookie: string; Server: string; Via: string; private InnerCollection: System.Collections.Specialized.NameValueCollection; private AllowHttpRequestHeader: boolean; AllowHttpResponseHeader: boolean; Item: string; Item: string; Count: number; Keys: System.Collections.Specialized.NameObjectCollectionBase.KeysCollection; AllKeys: System.String[]; private m_CommonHeaders: System.String[]; private m_NumCommonHeaders: number; private m_InnerCollection: System.Collections.Specialized.NameValueCollection; private m_Type: System.Net.WebHeaderCollectionType; private static HInfo: any; private static s_CommonHeaderNames: System.String[]; private static s_CommonHeaderHints: any; private static HttpTrimCharacters: any; private static RfcCharMap: any; Add(header: System.Net.HttpRequestHeader, value: string): any; //{ throw new Error("Not implemented.");} Add(header: System.Net.HttpResponseHeader, value: string): any; //{ throw new Error("Not implemented.");} Add(header: string): any; //{ throw new Error("Not implemented.");} Add(name: string, value: string): any; //{ throw new Error("Not implemented.");} AddInternal(name: string, value: string): any; //{ throw new Error("Not implemented.");} AddInternalNotCommon(name: string, value: string): any; //{ throw new Error("Not implemented.");} AddWithoutValidate(headerName: string, headerValue: string): any; //{ throw new Error("Not implemented.");} ChangeInternal(name: string, value: string): any; //{ throw new Error("Not implemented.");} CheckBadChars(name: string, isHeaderValue: boolean): string; //{ throw new Error("Not implemented.");} CheckUpdate(name: string, value: string): any; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} ContainsNonAsciiChars(token: string): boolean; //{ throw new Error("Not implemented.");} Get(index: number): string; //{ throw new Error("Not implemented.");} Get(name: string): string; //{ throw new Error("Not implemented.");} GetAsString(cc: System.Collections.Specialized.NameValueCollection, winInetCompat: boolean, forTrace: boolean): string; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetKey(index: number): string; //{ throw new Error("Not implemented.");} GetObjectData(serializationInfo: any, streamingContext: any): any; //{ throw new Error("Not implemented.");} GetValues(index: number): System.String[]; //{ throw new Error("Not implemented.");} GetValues(header: string): System.String[]; //{ throw new Error("Not implemented.");} InternalHasKeys(): boolean; //{ throw new Error("Not implemented.");} IsRestricted(headerName: string, response: boolean): boolean; //{ throw new Error("Not implemented.");} IsRestricted(headerName: string): boolean; //{ throw new Error("Not implemented.");} IsValidToken(token: string): boolean; //{ throw new Error("Not implemented.");} NormalizeCommonHeaders(): any; //{ throw new Error("Not implemented.");} OnDeserialization(sender: any): any; //{ throw new Error("Not implemented.");} ParseHeaders(buffer: System.Byte[], size: number, unparsed: any, totalResponseHeadersLength: any, maximumResponseHeadersLength: number, parseError: any): System.Net.DataParseStatus; //{ throw new Error("Not implemented.");} ParseHeadersStrict(buffer: System.Byte[], size: number, unparsed: any, totalResponseHeadersLength: any, maximumResponseHeadersLength: number, parseError: any): System.Net.DataParseStatus; //{ throw new Error("Not implemented.");} Remove(header: System.Net.HttpResponseHeader): any; //{ throw new Error("Not implemented.");} Remove(name: string): any; //{ throw new Error("Not implemented.");} Remove(header: System.Net.HttpRequestHeader): any; //{ throw new Error("Not implemented.");} RemoveInternal(name: string): any; //{ throw new Error("Not implemented.");} Set(name: string, value: string): any; //{ throw new Error("Not implemented.");} Set(header: System.Net.HttpRequestHeader, value: string): any; //{ throw new Error("Not implemented.");} Set(header: System.Net.HttpResponseHeader, value: string): any; //{ throw new Error("Not implemented.");} SetAddVerified(name: string, value: string): any; //{ throw new Error("Not implemented.");} SetInternal(name: string, value: string): any; //{ throw new Error("Not implemented.");} SetInternal(header: System.Net.HttpResponseHeader, value: string): any; //{ throw new Error("Not implemented.");} ThrowOnRestrictedHeader(headerName: string): any; //{ throw new Error("Not implemented.");} ToByteArray(): System.Byte[]; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} ToString(forTrace: boolean): string; //{ throw new Error("Not implemented.");} } } declare module System.Net.Sockets { } declare module System.Reflection { export class Assembly { CodeBase: string; EscapedCodeBase: string; FullName: string; EntryPoint: System.Reflection.MethodInfo; ExportedTypes: System.Collections.Generic.IEnumerable<System.Type>; DefinedTypes: System.Collections.Generic.IEnumerable<System.Reflection.TypeInfo>; Evidence: System.Security.Policy.Evidence; PermissionSet: System.Security.PermissionSet; IsFullyTrusted: boolean; SecurityRuleSet: System.Security.SecurityRuleSet; ManifestModule: System.Reflection.Module; CustomAttributes: System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>; ReflectionOnly: boolean; Modules: System.Collections.Generic.IEnumerable<System.Reflection.Module>; Location: string; ImageRuntimeVersion: string; GlobalAssemblyCache: boolean; HostContext: number; IsDynamic: boolean; CreateInstance(typeName: string, ignoreCase: boolean): any; //{ throw new Error("Not implemented.");} CreateInstance(typeName: string): any; //{ throw new Error("Not implemented.");} CreateInstance(typeName: string, ignoreCase: boolean, bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, args: any, culture: System.Globalization.CultureInfo, activationAttributes: any): any; //{ throw new Error("Not implemented.");} CreateQualifiedName(assemblyName: string, typeName: string): string; //{ throw new Error("Not implemented.");} Equals(o: any): boolean; //{ throw new Error("Not implemented.");} GetAssembly(type: System.Type): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} GetCallingAssembly(): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} GetCustomAttributes(attributeType: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributesData(): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetEntryAssembly(): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} GetExecutingAssembly(): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} GetExportedTypes(): System.Type[]; //{ throw new Error("Not implemented.");} GetFile(name: string): any; //{ throw new Error("Not implemented.");} GetFiles(): any; //{ throw new Error("Not implemented.");} GetFiles(getResourceModules: boolean): any; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetLoadedModules(getResourceModules: boolean): any; //{ throw new Error("Not implemented.");} GetLoadedModules(): any; //{ throw new Error("Not implemented.");} GetManifestResourceInfo(resourceName: string): any; //{ throw new Error("Not implemented.");} GetManifestResourceNames(): System.String[]; //{ throw new Error("Not implemented.");} GetManifestResourceStream(name: string): System.IO.Stream; //{ throw new Error("Not implemented.");} GetManifestResourceStream(type: System.Type, name: string): System.IO.Stream; //{ throw new Error("Not implemented.");} GetModule(name: string): System.Reflection.Module; //{ throw new Error("Not implemented.");} GetModules(getResourceModules: boolean): any; //{ throw new Error("Not implemented.");} GetModules(): any; //{ throw new Error("Not implemented.");} GetName(copiedName: boolean): any; //{ throw new Error("Not implemented.");} GetName(): any; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} GetReferencedAssemblies(): any; //{ throw new Error("Not implemented.");} GetSatelliteAssembly(culture: System.Globalization.CultureInfo): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} GetSatelliteAssembly(culture: System.Globalization.CultureInfo, version: System.Version): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} GetType(name: string, throwOnError: boolean): System.Type; //{ throw new Error("Not implemented.");} GetType(name: string, throwOnError: boolean, ignoreCase: boolean): System.Type; //{ throw new Error("Not implemented.");} GetType(name: string): System.Type; //{ throw new Error("Not implemented.");} GetType_Compat(assemblyString: string, typeName: string): System.Type; //{ throw new Error("Not implemented.");} GetTypes(): System.Type[]; //{ throw new Error("Not implemented.");} IsDefined(attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} Load(rawAssembly: System.Byte[], rawSymbolStore: System.Byte[], securityEvidence: System.Security.Policy.Evidence): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} Load(assemblyString: string): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} Load(assemblyString: string, assemblySecurity: System.Security.Policy.Evidence): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} Load(rawAssembly: System.Byte[], rawSymbolStore: System.Byte[], securityContextSource: System.Security.SecurityContextSource): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} Load(rawAssembly: System.Byte[], rawSymbolStore: System.Byte[]): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} Load(assemblyRef: any): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} Load(assemblyRef: any, assemblySecurity: System.Security.Policy.Evidence): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} Load(rawAssembly: System.Byte[]): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} LoadFile(path: string): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} LoadFile(path: string, securityEvidence: System.Security.Policy.Evidence): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} LoadFrom(assemblyFile: string, securityEvidence: System.Security.Policy.Evidence, hashValue: System.Byte[], hashAlgorithm: System.Configuration.Assemblies.AssemblyHashAlgorithm): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} LoadFrom(assemblyFile: string): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} LoadFrom(assemblyFile: string, hashValue: System.Byte[], hashAlgorithm: System.Configuration.Assemblies.AssemblyHashAlgorithm): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} LoadFrom(assemblyFile: string, securityEvidence: System.Security.Policy.Evidence): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} LoadModule(moduleName: string, rawModule: System.Byte[]): System.Reflection.Module; //{ throw new Error("Not implemented.");} LoadModule(moduleName: string, rawModule: System.Byte[], rawSymbolStore: System.Byte[]): System.Reflection.Module; //{ throw new Error("Not implemented.");} LoadWithPartialName(partialName: string): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} LoadWithPartialName(partialName: string, securityEvidence: System.Security.Policy.Evidence): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} ReflectionOnlyLoad(rawAssembly: System.Byte[]): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} ReflectionOnlyLoad(assemblyString: string): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} ReflectionOnlyLoadFrom(assemblyFile: string): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} UnsafeLoadFrom(assemblyFile: string): System.Reflection.Assembly; //{ throw new Error("Not implemented.");} } export class Binder { BindToField(bindingAttr: System.Reflection.BindingFlags, match: any, value: any, culture: System.Globalization.CultureInfo): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} BindToMethod(bindingAttr: System.Reflection.BindingFlags, match: any, args: any, modifiers: any, culture: System.Globalization.CultureInfo, names: System.String[], state: any): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} ChangeType(value: any, type: System.Type, culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} ReorderArgumentArray(args: any, state: any): any; //{ throw new Error("Not implemented.");} SelectMethod(bindingAttr: System.Reflection.BindingFlags, match: any, types: System.Type[], modifiers: any): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} SelectProperty(bindingAttr: System.Reflection.BindingFlags, match: any, returnType: System.Type, indexes: System.Type[], modifiers: any): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} } export class ConstructorInfo extends System.Reflection.MethodBase { MemberType: System.Reflection.MemberTypes; static ConstructorName: string; static TypeConstructorName: string; Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetReturnType(): System.Type; //{ throw new Error("Not implemented.");} Invoke(invokeAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, parameters: any, culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} Invoke(parameters: any): any; //{ throw new Error("Not implemented.");} } export class CustomAttributeData { AttributeType: System.Type; Constructor: System.Reflection.ConstructorInfo; ConstructorArguments: System.Collections.Generic.IList<System.Reflection.CustomAttributeTypedArgument>; NamedArguments: System.Collections.Generic.IList<System.Reflection.CustomAttributeNamedArgument>; private m_ctor: System.Reflection.ConstructorInfo; private m_scope: any; private m_members: any; private m_ctorParams: any; private m_namedParams: any; private m_typedCtorArgs: System.Collections.Generic.IList<System.Reflection.CustomAttributeTypedArgument>; private m_namedArgs: System.Collections.Generic.IList<System.Reflection.CustomAttributeNamedArgument>; Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} Filter(attrs: System.Collections.Generic.IList<T>, caType: System.Type, parameter: number): System.Reflection.CustomAttributeTypedArgument; //{ throw new Error("Not implemented.");} GetCustomAttributeRecords(module: any, targetToken: number): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(target: System.Reflection.MemberInfo): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributes(target: System.Reflection.Module): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributes(target: System.Reflection.Assembly): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributes(target: System.Reflection.ParameterInfo): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributes(module: any, tkTarget: number): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributesInternal(target: any): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributesInternal(target: any): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributesInternal(target: any): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributesInternal(target: any): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributesInternal(target: any): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributesInternal(target: any): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributesInternal(target: any): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributesInternal(target: any): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetCustomAttributesInternal(target: any): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} Init(forwardedTo: any): any; //{ throw new Error("Not implemented.");} Init(dllImport: any): any; //{ throw new Error("Not implemented.");} Init(fieldOffset: any): any; //{ throw new Error("Not implemented.");} Init(marshalAs: any): any; //{ throw new Error("Not implemented.");} Init(pca: any): any; //{ throw new Error("Not implemented.");} InitCustomAttributeType(parameterType: any): any; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} TypeToCustomAttributeEncoding(type: any): System.Reflection.CustomAttributeEncoding; //{ throw new Error("Not implemented.");} } export class CustomAttributeNamedArgument { ArgumentType: System.Type; MemberInfo: System.Reflection.MemberInfo; TypedValue: System.Reflection.CustomAttributeTypedArgument; MemberName: string; IsField: boolean; private m_memberInfo: System.Reflection.MemberInfo; private m_value: System.Reflection.CustomAttributeTypedArgument; Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} } export class CustomAttributeTypedArgument { ArgumentType: System.Type; Value: any; private m_value: any; private m_argumentType: System.Type; CanonicalizeValue(value: any): any; //{ throw new Error("Not implemented.");} CustomAttributeEncodingToType(encodedType: System.Reflection.CustomAttributeEncoding): System.Type; //{ throw new Error("Not implemented.");} EncodedValueToRawValue(val: number, encodedType: System.Reflection.CustomAttributeEncoding): any; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} ResolveType(scope: any, typeName: string): any; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} ToString(typed: boolean): string; //{ throw new Error("Not implemented.");} } export class EventInfo extends System.Reflection.MemberInfo { MemberType: System.Reflection.MemberTypes; Attributes: System.Reflection.EventAttributes; AddMethod: System.Reflection.MethodInfo; RemoveMethod: System.Reflection.MethodInfo; RaiseMethod: System.Reflection.MethodInfo; EventHandlerType: System.Type; IsSpecialName: boolean; IsMulticast: boolean; AddEventHandler(target: any, handler: System.Delegate): any; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetAddMethod(nonPublic: boolean): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetAddMethod(): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetOtherMethods(nonPublic: boolean): any; //{ throw new Error("Not implemented.");} GetOtherMethods(): any; //{ throw new Error("Not implemented.");} GetRaiseMethod(nonPublic: boolean): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetRaiseMethod(): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetRemoveMethod(): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetRemoveMethod(nonPublic: boolean): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} RemoveEventHandler(target: any, handler: System.Delegate): any; //{ throw new Error("Not implemented.");} } export class FieldInfo extends System.Reflection.MemberInfo { MemberType: System.Reflection.MemberTypes; FieldHandle: System.RuntimeFieldHandle; FieldType: System.Type; Attributes: System.Reflection.FieldAttributes; IsPublic: boolean; IsPrivate: boolean; IsFamily: boolean; IsAssembly: boolean; IsFamilyAndAssembly: boolean; IsFamilyOrAssembly: boolean; IsStatic: boolean; IsInitOnly: boolean; IsLiteral: boolean; IsNotSerialized: boolean; IsSpecialName: boolean; IsPinvokeImpl: boolean; IsSecurityCritical: boolean; IsSecuritySafeCritical: boolean; IsSecurityTransparent: boolean; Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetFieldFromHandle(handle: System.RuntimeFieldHandle): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} GetFieldFromHandle(handle: System.RuntimeFieldHandle, declaringType: System.RuntimeTypeHandle): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetOptionalCustomModifiers(): System.Type[]; //{ throw new Error("Not implemented.");} GetRawConstantValue(): any; //{ throw new Error("Not implemented.");} GetRequiredCustomModifiers(): System.Type[]; //{ throw new Error("Not implemented.");} GetValue(obj: any): any; //{ throw new Error("Not implemented.");} GetValueDirect(obj: any): any; //{ throw new Error("Not implemented.");} SetValue(obj: any, value: any, invokeAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} SetValue(obj: any, value: any): any; //{ throw new Error("Not implemented.");} SetValueDirect(obj: any, value: any): any; //{ throw new Error("Not implemented.");} } interface ICustomAttributeProvider { GetCustomAttributes(attributeType: System.Type, inherit: boolean): any; GetCustomAttributes(inherit: boolean): any; IsDefined(attributeType: System.Type, inherit: boolean): boolean; } export class MemberInfo { MemberType: System.Reflection.MemberTypes; Name: string; DeclaringType: System.Type; ReflectedType: System.Type; CustomAttributes: System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>; MetadataToken: number; Module: System.Reflection.Module; CacheEquals(o: any): boolean; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetCustomAttributes(inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(attributeType: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributesData(): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} IsDefined(attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} } export class MethodBase extends System.Reflection.MemberInfo { IsDynamicallyInvokable: boolean; MethodImplementationFlags: System.Reflection.MethodImplAttributes; MethodHandle: System.RuntimeMethodHandle; Attributes: System.Reflection.MethodAttributes; CallingConvention: System.Reflection.CallingConventions; IsGenericMethodDefinition: boolean; ContainsGenericParameters: boolean; IsGenericMethod: boolean; IsSecurityCritical: boolean; IsSecuritySafeCritical: boolean; IsSecurityTransparent: boolean; IsPublic: boolean; IsPrivate: boolean; IsFamily: boolean; IsAssembly: boolean; IsFamilyAndAssembly: boolean; IsFamilyOrAssembly: boolean; IsStatic: boolean; IsFinal: boolean; IsVirtual: boolean; IsHideBySig: boolean; IsAbstract: boolean; IsSpecialName: boolean; IsConstructor: boolean; FullName: string; private System.Runtime.InteropServices._MethodBase.IsPublic: boolean; private System.Runtime.InteropServices._MethodBase.IsPrivate: boolean; private System.Runtime.InteropServices._MethodBase.IsFamily: boolean; private System.Runtime.InteropServices._MethodBase.IsAssembly: boolean; private System.Runtime.InteropServices._MethodBase.IsFamilyAndAssembly: boolean; private System.Runtime.InteropServices._MethodBase.IsFamilyOrAssembly: boolean; private System.Runtime.InteropServices._MethodBase.IsStatic: boolean; private System.Runtime.InteropServices._MethodBase.IsFinal: boolean; private System.Runtime.InteropServices._MethodBase.IsVirtual: boolean; private System.Runtime.InteropServices._MethodBase.IsHideBySig: boolean; private System.Runtime.InteropServices._MethodBase.IsAbstract: boolean; private System.Runtime.InteropServices._MethodBase.IsSpecialName: boolean; private System.Runtime.InteropServices._MethodBase.IsConstructor: boolean; CheckArguments(parameters: any, binder: System.Reflection.Binder, invokeAttr: System.Reflection.BindingFlags, culture: System.Globalization.CultureInfo, sig: any): any; //{ throw new Error("Not implemented.");} ConstructParameters(parameterTypes: System.Type[], callingConvention: System.Reflection.CallingConventions, serialization: boolean): string; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} FormatNameAndSig(serialization: boolean): string; //{ throw new Error("Not implemented.");} FormatNameAndSig(): string; //{ throw new Error("Not implemented.");} GetCurrentMethod(): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} GetGenericArguments(): System.Type[]; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetMethodBody(): any; //{ throw new Error("Not implemented.");} GetMethodDesc(): number; //{ throw new Error("Not implemented.");} GetMethodFromHandle(handle: System.RuntimeMethodHandle, declaringType: System.RuntimeTypeHandle): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} GetMethodFromHandle(handle: System.RuntimeMethodHandle): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} GetMethodImplementationFlags(): System.Reflection.MethodImplAttributes; //{ throw new Error("Not implemented.");} GetParameters(): any; //{ throw new Error("Not implemented.");} GetParametersNoCopy(): any; //{ throw new Error("Not implemented.");} GetParameterTypes(): System.Type[]; //{ throw new Error("Not implemented.");} Invoke(obj: any, parameters: any): any; //{ throw new Error("Not implemented.");} Invoke(obj: any, invokeAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, parameters: any, culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} } export class MethodInfo extends System.Reflection.MethodBase { MemberType: System.Reflection.MemberTypes; ReturnType: System.Type; ReturnParameter: System.Reflection.ParameterInfo; ReturnTypeCustomAttributes: System.Reflection.ICustomAttributeProvider; CreateDelegate(delegateType: System.Type): System.Delegate; //{ throw new Error("Not implemented.");} CreateDelegate(delegateType: System.Type, target: any): System.Delegate; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetBaseDefinition(): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetGenericArguments(): System.Type[]; //{ throw new Error("Not implemented.");} GetGenericMethodDefinition(): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} MakeGenericMethod(typeArguments: System.Type[]): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} } export class Module { CustomAttributes: System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>; MDStreamVersion: number; FullyQualifiedName: string; ModuleVersionId: System.Guid; MetadataToken: number; ScopeName: string; Name: string; Assembly: System.Reflection.Assembly; ModuleHandle: System.ModuleHandle; static FilterTypeName: any; static FilterTypeNameIgnoreCase: any; Equals(o: any): boolean; //{ throw new Error("Not implemented.");} FindTypes(filter: any, filterCriteria: any): System.Type[]; //{ throw new Error("Not implemented.");} GetCustomAttributes(inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(attributeType: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributesData(): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetField(name: string): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} GetField(name: string, bindingAttr: System.Reflection.BindingFlags): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} GetFields(): any; //{ throw new Error("Not implemented.");} GetFields(bindingFlags: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetMethod(name: string, bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, callConvention: System.Reflection.CallingConventions, types: System.Type[], modifiers: any): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethod(name: string): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethod(name: string, types: System.Type[]): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethodImpl(name: string, bindingAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, callConvention: System.Reflection.CallingConventions, types: System.Type[], modifiers: any): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetMethods(bindingFlags: System.Reflection.BindingFlags): any; //{ throw new Error("Not implemented.");} GetMethods(): any; //{ throw new Error("Not implemented.");} GetModuleHandle(): System.ModuleHandle; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} GetPEKind(peKind: any, machine: any): any; //{ throw new Error("Not implemented.");} GetSignerCertificate(): System.Security.Cryptography.X509Certificates.X509Certificate; //{ throw new Error("Not implemented.");} GetType(className: string, throwOnError: boolean, ignoreCase: boolean): System.Type; //{ throw new Error("Not implemented.");} GetType(className: string): System.Type; //{ throw new Error("Not implemented.");} GetType(className: string, ignoreCase: boolean): System.Type; //{ throw new Error("Not implemented.");} GetTypes(): System.Type[]; //{ throw new Error("Not implemented.");} IsDefined(attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} IsResource(): boolean; //{ throw new Error("Not implemented.");} ResolveField(metadataToken: number): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} ResolveField(metadataToken: number, genericTypeArguments: System.Type[], genericMethodArguments: System.Type[]): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} ResolveMember(metadataToken: number): System.Reflection.MemberInfo; //{ throw new Error("Not implemented.");} ResolveMember(metadataToken: number, genericTypeArguments: System.Type[], genericMethodArguments: System.Type[]): System.Reflection.MemberInfo; //{ throw new Error("Not implemented.");} ResolveMethod(metadataToken: number, genericTypeArguments: System.Type[], genericMethodArguments: System.Type[]): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} ResolveMethod(metadataToken: number): System.Reflection.MethodBase; //{ throw new Error("Not implemented.");} ResolveSignature(metadataToken: number): System.Byte[]; //{ throw new Error("Not implemented.");} ResolveString(metadataToken: number): string; //{ throw new Error("Not implemented.");} ResolveType(metadataToken: number, genericTypeArguments: System.Type[], genericMethodArguments: System.Type[]): System.Type; //{ throw new Error("Not implemented.");} ResolveType(metadataToken: number): System.Type; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} } export class ParameterInfo { ParameterType: System.Type; Name: string; HasDefaultValue: boolean; DefaultValue: any; RawDefaultValue: any; Position: number; Attributes: System.Reflection.ParameterAttributes; Member: System.Reflection.MemberInfo; IsIn: boolean; IsOut: boolean; IsLcid: boolean; IsRetval: boolean; IsOptional: boolean; MetadataToken: number; CustomAttributes: System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>; NameImpl: string; ClassImpl: System.Type; PositionImpl: number; AttrsImpl: System.Reflection.ParameterAttributes; DefaultValueImpl: any; MemberImpl: System.Reflection.MemberInfo; private _importer: number; private _token: number; private bExtraConstChecked: boolean; GetCustomAttributes(inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributes(attributeType: System.Type, inherit: boolean): any; //{ throw new Error("Not implemented.");} GetCustomAttributesData(): System.Collections.Generic.IList<T>; //{ throw new Error("Not implemented.");} GetOptionalCustomModifiers(): System.Type[]; //{ throw new Error("Not implemented.");} GetRealObject(context: any): any; //{ throw new Error("Not implemented.");} GetRequiredCustomModifiers(): System.Type[]; //{ throw new Error("Not implemented.");} IsDefined(attributeType: System.Type, inherit: boolean): boolean; //{ throw new Error("Not implemented.");} SetAttributes(attributes: System.Reflection.ParameterAttributes): any; //{ throw new Error("Not implemented.");} SetName(name: string): any; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} } export class PropertyInfo extends System.Reflection.MemberInfo { MemberType: System.Reflection.MemberTypes; PropertyType: System.Type; Attributes: System.Reflection.PropertyAttributes; CanRead: boolean; CanWrite: boolean; GetMethod: System.Reflection.MethodInfo; SetMethod: System.Reflection.MethodInfo; IsSpecialName: boolean; Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} GetAccessors(nonPublic: boolean): any; //{ throw new Error("Not implemented.");} GetAccessors(): any; //{ throw new Error("Not implemented.");} GetConstantValue(): any; //{ throw new Error("Not implemented.");} GetGetMethod(nonPublic: boolean): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetGetMethod(): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetIndexParameters(): any; //{ throw new Error("Not implemented.");} GetOptionalCustomModifiers(): System.Type[]; //{ throw new Error("Not implemented.");} GetRawConstantValue(): any; //{ throw new Error("Not implemented.");} GetRequiredCustomModifiers(): System.Type[]; //{ throw new Error("Not implemented.");} GetSetMethod(): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetSetMethod(nonPublic: boolean): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetValue(obj: any, invokeAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, index: any, culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} GetValue(obj: any, index: any): any; //{ throw new Error("Not implemented.");} GetValue(obj: any): any; //{ throw new Error("Not implemented.");} SetValue(obj: any, value: any): any; //{ throw new Error("Not implemented.");} SetValue(obj: any, value: any, invokeAttr: System.Reflection.BindingFlags, binder: System.Reflection.Binder, index: any, culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} SetValue(obj: any, value: any, index: any): any; //{ throw new Error("Not implemented.");} } export class TypeInfo extends System.Type { GenericTypeParameters: System.Type[]; DeclaredConstructors: System.Collections.Generic.IEnumerable<System.Reflection.ConstructorInfo>; DeclaredEvents: System.Collections.Generic.IEnumerable<System.Reflection.EventInfo>; DeclaredFields: System.Collections.Generic.IEnumerable<System.Reflection.FieldInfo>; DeclaredMembers: System.Collections.Generic.IEnumerable<System.Reflection.MemberInfo>; DeclaredMethods: System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo>; DeclaredNestedTypes: System.Collections.Generic.IEnumerable<System.Reflection.TypeInfo>; DeclaredProperties: System.Collections.Generic.IEnumerable<System.Reflection.PropertyInfo>; ImplementedInterfaces: System.Collections.Generic.IEnumerable<System.Type>; AsType(): System.Type; //{ throw new Error("Not implemented.");} GetDeclaredEvent(name: string): System.Reflection.EventInfo; //{ throw new Error("Not implemented.");} GetDeclaredField(name: string): System.Reflection.FieldInfo; //{ throw new Error("Not implemented.");} GetDeclaredMethod(name: string): System.Reflection.MethodInfo; //{ throw new Error("Not implemented.");} GetDeclaredMethods(name: string): System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo>; //{ throw new Error("Not implemented.");} GetDeclaredNestedType(name: string): System.Reflection.TypeInfo; //{ throw new Error("Not implemented.");} GetDeclaredProperty(name: string): System.Reflection.PropertyInfo; //{ throw new Error("Not implemented.");} IsAssignableFrom(typeInfo: System.Reflection.TypeInfo): boolean; //{ throw new Error("Not implemented.");} } } declare module System.Resources { export class ResourceManager { BaseName: string; IgnoreCase: boolean; ResourceSetType: System.Type; FallbackLocation: System.Resources.UltimateResourceFallbackLocation; BaseNameField: string; ResourceSets: System.Collections.Hashtable; private _resourceSets: System.Collections.Generic.Dictionary<TKey, TValue>; private moduleDir: string; MainAssembly: System.Reflection.Assembly; private _locationInfo: System.Type; private _userResourceSet: System.Type; private _neutralResourcesCulture: System.Globalization.CultureInfo; private _lastUsedResourceCache: any; private _ignoreCase: boolean; private UseManifest: boolean; private UseSatelliteAssem: boolean; private _fallbackLoc: System.Resources.UltimateResourceFallbackLocation; private _satelliteContractVersion: System.Version; private _lookedForSatelliteContractVersion: boolean; private _callingAssembly: System.Reflection.Assembly; private m_callingAssembly: any; private resourceGroveler: any; private _bUsingModernResourceManagement: boolean; private _WinRTResourceManager: any; private _PRIonAppXInitialized: boolean; private _PRIExceptionInfo: any; private static _installedSatelliteInfo: System.Collections.Hashtable; private static _checkedConfigFile: boolean; static MagicNumber: number; static HeaderVersionNumber: number; private static _minResourceSet: System.Type; static ResReaderTypeName: string; static ResSetTypeName: string; static MscorlibName: string; static DEBUG: number; private static s_IsAppXModel: boolean; AddResourceSet(localResourceSets: System.Collections.Generic.Dictionary<TKey, TValue>, cultureName: string, rs: any): any; //{ throw new Error("Not implemented.");} CommonAssemblyInit(): any; //{ throw new Error("Not implemented.");} CompareNames(asmTypeName1: string, typeName2: string, asmName2: any): boolean; //{ throw new Error("Not implemented.");} CreateFileBasedResourceManager(baseName: string, resourceDir: string, usingResourceSet: System.Type): System.Resources.ResourceManager; //{ throw new Error("Not implemented.");} GetFirstResourceSet(culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} GetNeutralResourcesLanguage(a: System.Reflection.Assembly): System.Globalization.CultureInfo; //{ throw new Error("Not implemented.");} GetObject(name: string, culture: System.Globalization.CultureInfo, wrapUnmanagedMemStream: boolean): any; //{ throw new Error("Not implemented.");} GetObject(name: string, culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} GetObject(name: string): any; //{ throw new Error("Not implemented.");} GetResourceFileName(culture: System.Globalization.CultureInfo): string; //{ throw new Error("Not implemented.");} GetResourceSet(culture: System.Globalization.CultureInfo, createIfNotExists: boolean, tryParents: boolean): any; //{ throw new Error("Not implemented.");} GetSatelliteAssembliesFromConfig(): System.Collections.Hashtable; //{ throw new Error("Not implemented.");} GetSatelliteContractVersion(a: System.Reflection.Assembly): System.Version; //{ throw new Error("Not implemented.");} GetStream(name: string): any; //{ throw new Error("Not implemented.");} GetStream(name: string, culture: System.Globalization.CultureInfo): any; //{ throw new Error("Not implemented.");} GetString(name: string): string; //{ throw new Error("Not implemented.");} GetString(name: string, culture: System.Globalization.CultureInfo): string; //{ throw new Error("Not implemented.");} GetStringFromPRI(stringName: string, startingCulture: string, neutralResourcesCulture: string): string; //{ throw new Error("Not implemented.");} GetWinRTResourceManager(): any; //{ throw new Error("Not implemented.");} Init(): any; //{ throw new Error("Not implemented.");} InternalGetResourceSet(requestedCulture: System.Globalization.CultureInfo, createIfNotExists: boolean, tryParents: boolean, stackMark: any): any; //{ throw new Error("Not implemented.");} InternalGetResourceSet(culture: System.Globalization.CultureInfo, createIfNotExists: boolean, tryParents: boolean): any; //{ throw new Error("Not implemented.");} OnDeserialized(ctx: any): any; //{ throw new Error("Not implemented.");} OnDeserializing(ctx: any): any; //{ throw new Error("Not implemented.");} OnSerializing(ctx: any): any; //{ throw new Error("Not implemented.");} ReleaseAllResources(): any; //{ throw new Error("Not implemented.");} SetAppXConfiguration(): any; //{ throw new Error("Not implemented.");} ShouldUseSatelliteAssemblyResourceLookupUnderAppX(resourcesAssembly: any): boolean; //{ throw new Error("Not implemented.");} TryLookingForSatellite(lookForCulture: System.Globalization.CultureInfo): boolean; //{ throw new Error("Not implemented.");} } } declare module System.Runtime.ConstrainedExecution { export class CriticalFinalizerObject { Finalize(): any; //{ throw new Error("Not implemented.");} } } declare module System.Runtime.InteropServices { export class ExternalException extends System.SystemException { ErrorCode: number; ToString(): string; //{ throw new Error("Not implemented.");} } export class SafeHandle extends System.Runtime.ConstrainedExecution.CriticalFinalizerObject { IsClosed: boolean; IsInvalid: boolean; handle: number; private _state: number; private _ownsHandle: boolean; private _fullyInitialized: boolean; Close(): any; //{ throw new Error("Not implemented.");} DangerousAddRef(success: any): any; //{ throw new Error("Not implemented.");} DangerousGetHandle(): number; //{ throw new Error("Not implemented.");} DangerousRelease(): any; //{ throw new Error("Not implemented.");} Dispose(): any; //{ throw new Error("Not implemented.");} Dispose(disposing: boolean): any; //{ throw new Error("Not implemented.");} Finalize(): any; //{ throw new Error("Not implemented.");} InternalDispose(): any; //{ throw new Error("Not implemented.");} InternalFinalize(): any; //{ throw new Error("Not implemented.");} ReleaseHandle(): boolean; //{ throw new Error("Not implemented.");} SetHandle(handle: number): any; //{ throw new Error("Not implemented.");} SetHandleAsInvalid(): any; //{ throw new Error("Not implemented.");} } export class StructLayoutAttribute extends System.Attribute { Value: System.Runtime.InteropServices.LayoutKind; _val: System.Runtime.InteropServices.LayoutKind; Pack: number; Size: number; CharSet: System.Runtime.InteropServices.CharSet; GetCustomAttribute(type: any): System.Attribute; //{ throw new Error("Not implemented.");} IsDefined(type: any): boolean; //{ throw new Error("Not implemented.");} } } declare module System.Security { interface IEvidenceFactory { Evidence: System.Security.Policy.Evidence; } export class PermissionSet { SyncRoot: any; IsSynchronized: boolean; IsReadOnly: boolean; Count: number; IgnoreTypeLoadFailures: boolean; private m_Unrestricted: boolean; private m_allPermissionsDecoded: boolean; m_permSet: any; private m_ignoreTypeLoadFailures: boolean; private m_serializedPermissionSet: string; private m_CheckedForNonCas: boolean; private m_ContainsCas: boolean; private m_ContainsNonCas: boolean; private m_permSetSaved: any; private readableonly: boolean; private m_unrestrictedPermSet: any; private m_normalPermSet: any; private m_canUnrestrictedOverride: boolean; static s_fullTrust: System.Security.PermissionSet; AddPermission(perm: any): any; //{ throw new Error("Not implemented.");} AddPermissionImpl(perm: any): any; //{ throw new Error("Not implemented.");} Assert(): any; //{ throw new Error("Not implemented.");} CheckAssertion(target: System.Security.PermissionSet): boolean; //{ throw new Error("Not implemented.");} CheckDecoded(demandedPerm: any, tokenDemandedPerm: any): any; //{ throw new Error("Not implemented.");} CheckDecoded(index: number): any; //{ throw new Error("Not implemented.");} CheckDecoded(demandedSet: System.Security.PermissionSet): any; //{ throw new Error("Not implemented.");} CheckDemand(target: System.Security.PermissionSet, firstPermThatFailed: any): boolean; //{ throw new Error("Not implemented.");} CheckDeny(deniedSet: System.Security.PermissionSet, firstPermThatFailed: any): boolean; //{ throw new Error("Not implemented.");} CheckPermitOnly(target: System.Security.PermissionSet, firstPermThatFailed: any): boolean; //{ throw new Error("Not implemented.");} CheckSet(): any; //{ throw new Error("Not implemented.");} Contains(perm: any): boolean; //{ throw new Error("Not implemented.");} ContainsNonCodeAccessPermissions(): boolean; //{ throw new Error("Not implemented.");} ConvertPermissionSet(inFormat: string, inData: System.Byte[], outFormat: string): System.Byte[]; //{ throw new Error("Not implemented.");} Copy(): System.Security.PermissionSet; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array, index: number): any; //{ throw new Error("Not implemented.");} CopyWithNoIdentityPermissions(): System.Security.PermissionSet; //{ throw new Error("Not implemented.");} CreateEmptyPermissionSetXml(): any; //{ throw new Error("Not implemented.");} CreatePerm(obj: any): any; //{ throw new Error("Not implemented.");} CreatePerm(obj: any, ignoreTypeLoadFailures: boolean): any; //{ throw new Error("Not implemented.");} CreatePermission(obj: any, index: number): any; //{ throw new Error("Not implemented.");} CreateSerialized(attrs: any, serialize: boolean, nonCasBlob: any, casPset: any, fullTrustOnlyResources: System.Security.Permissions.HostProtectionResource, allowEmptyPermissionSets: boolean): System.Byte[]; //{ throw new Error("Not implemented.");} DEBUG_COND_WRITE(exp: boolean, str: string): any; //{ throw new Error("Not implemented.");} DEBUG_PRINTSTACK(e: System.Exception): any; //{ throw new Error("Not implemented.");} DEBUG_WRITE(str: string): any; //{ throw new Error("Not implemented.");} DecodeAllPermissions(): any; //{ throw new Error("Not implemented.");} DecodeXml(data: System.Byte[], fullTrustOnlyResources: System.Security.Permissions.HostProtectionResource, inaccessibleResources: System.Security.Permissions.HostProtectionResource): boolean; //{ throw new Error("Not implemented.");} Demand(): any; //{ throw new Error("Not implemented.");} DemandNonCAS(): any; //{ throw new Error("Not implemented.");} Deny(): any; //{ throw new Error("Not implemented.");} EncodeXml(): System.Byte[]; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} FastIsEmpty(): boolean; //{ throw new Error("Not implemented.");} FilterHostProtectionPermissions(fullTrustOnly: System.Security.Permissions.HostProtectionResource, inaccessible: System.Security.Permissions.HostProtectionResource): any; //{ throw new Error("Not implemented.");} FromXml(doc: any, position: number, allowInternalOnly: boolean): any; //{ throw new Error("Not implemented.");} FromXml(et: any, allowInternalOnly: boolean, ignoreTypeLoadFailures: boolean): any; //{ throw new Error("Not implemented.");} FromXml(et: any): any; //{ throw new Error("Not implemented.");} GetCasOnlySet(): System.Security.PermissionSet; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetEnumeratorImpl(): any; //{ throw new Error("Not implemented.");} GetEnumeratorInternal(): any; //{ throw new Error("Not implemented.");} GetFirstPerm(): any; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetPermission(permClass: System.Type): any; //{ throw new Error("Not implemented.");} GetPermission(perm: any): any; //{ throw new Error("Not implemented.");} GetPermission(permToken: any): any; //{ throw new Error("Not implemented.");} GetPermission(index: number): any; //{ throw new Error("Not implemented.");} GetPermissionElement(el: any): any; //{ throw new Error("Not implemented.");} GetPermissionImpl(permClass: System.Type): any; //{ throw new Error("Not implemented.");} InplaceIntersect(other: System.Security.PermissionSet): any; //{ throw new Error("Not implemented.");} InplaceUnion(other: System.Security.PermissionSet): any; //{ throw new Error("Not implemented.");} InternalToXml(): any; //{ throw new Error("Not implemented.");} Intersect(other: System.Security.PermissionSet): System.Security.PermissionSet; //{ throw new Error("Not implemented.");} IsEmpty(): boolean; //{ throw new Error("Not implemented.");} IsIntersectingAssertedPermissions(assertSet1: System.Security.PermissionSet, assertSet2: System.Security.PermissionSet): boolean; //{ throw new Error("Not implemented.");} IsPermissionTag(tag: string, allowInternalOnly: boolean): boolean; //{ throw new Error("Not implemented.");} IsSubsetOf(target: System.Security.PermissionSet): boolean; //{ throw new Error("Not implemented.");} IsSubsetOfHelper(target: System.Security.PermissionSet, type: System.Security.PermissionSet.IsSubsetOfType, firstPermThatFailed: any, ignoreNonCas: boolean): boolean; //{ throw new Error("Not implemented.");} IsUnrestricted(): boolean; //{ throw new Error("Not implemented.");} MergeDeniedSet(denied: System.Security.PermissionSet): any; //{ throw new Error("Not implemented.");} MergePermission(perm: any, separateCasFromNonCas: boolean, casPset: any, nonCasPset: any): any; //{ throw new Error("Not implemented.");} NormalizePermissionSet(): any; //{ throw new Error("Not implemented.");} OnDeserialized(ctx: any): any; //{ throw new Error("Not implemented.");} OnDeserializing(ctx: any): any; //{ throw new Error("Not implemented.");} OnSerialized(context: any): any; //{ throw new Error("Not implemented.");} OnSerializing(ctx: any): any; //{ throw new Error("Not implemented.");} PermitOnly(): any; //{ throw new Error("Not implemented.");} RemoveAssertedPermissionSet(demandSet: System.Security.PermissionSet, assertSet: System.Security.PermissionSet, alteredDemandSet: any): any; //{ throw new Error("Not implemented.");} RemovePermission(index: number): any; //{ throw new Error("Not implemented.");} RemovePermission(permClass: System.Type): any; //{ throw new Error("Not implemented.");} RemovePermissionImpl(permClass: System.Type): any; //{ throw new Error("Not implemented.");} RemoveRefusedPermissionSet(assertSet: System.Security.PermissionSet, refusedSet: System.Security.PermissionSet, bFailedToCompress: any): System.Security.PermissionSet; //{ throw new Error("Not implemented.");} Reset(): any; //{ throw new Error("Not implemented.");} RevertAssert(): any; //{ throw new Error("Not implemented.");} SafeChildAdd(parent: any, child: any, copy: boolean): any; //{ throw new Error("Not implemented.");} SetPermission(perm: any): any; //{ throw new Error("Not implemented.");} SetPermissionImpl(perm: any): any; //{ throw new Error("Not implemented.");} SetUnrestricted(unrestricted: boolean): any; //{ throw new Error("Not implemented.");} SetupSecurity(): any; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} ToXml(permName: string): any; //{ throw new Error("Not implemented.");} ToXml(): any; //{ throw new Error("Not implemented.");} Union(other: System.Security.PermissionSet): System.Security.PermissionSet; //{ throw new Error("Not implemented.");} } } declare module System.Security.Cryptography { export class AsymmetricAlgorithm { KeySize: number; LegalKeySizes: System.Security.Cryptography.KeySizes[]; SignatureAlgorithm: string; KeyExchangeAlgorithm: string; KeySizeValue: number; LegalKeySizesValue: System.Security.Cryptography.KeySizes[]; Clear(): any; //{ throw new Error("Not implemented.");} Create(): System.Security.Cryptography.AsymmetricAlgorithm; //{ throw new Error("Not implemented.");} Create(algName: string): System.Security.Cryptography.AsymmetricAlgorithm; //{ throw new Error("Not implemented.");} Dispose(): any; //{ throw new Error("Not implemented.");} Dispose(disposing: boolean): any; //{ throw new Error("Not implemented.");} FromXmlString(xmlString: string): any; //{ throw new Error("Not implemented.");} ToXmlString(includePrivateParameters: boolean): string; //{ throw new Error("Not implemented.");} } } declare module System.Security.Cryptography.X509Certificates { export class SafeCertContextHandle extends Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid { static InvalidHandle: System.Security.Cryptography.X509Certificates.SafeCertContextHandle; pCertContext: number; _FreePCertContext(pCert: number): any; //{ throw new Error("Not implemented.");} ReleaseHandle(): boolean; //{ throw new Error("Not implemented.");} } export class X509Certificate { Handle: number; Issuer: string; Subject: string; CertContext: System.Security.Cryptography.X509Certificates.SafeCertContextHandle; private NotAfter: Date; private NotBefore: Date; private RawData: System.Byte[]; private SerialNumber: string; private m_subjectName: string; private m_issuerName: string; private m_serialNumber: System.Byte[]; private m_publicKeyParameters: System.Byte[]; private m_publicKeyValue: System.Byte[]; private m_publicKeyOid: string; private m_rawData: System.Byte[]; private m_thumbprint: System.Byte[]; private m_notBefore: Date; private m_notAfter: Date; private m_safeCertContext: System.Security.Cryptography.X509Certificates.SafeCertContextHandle; private m_certContextCloned: boolean; CreateFromCertFile(filename: string): System.Security.Cryptography.X509Certificates.X509Certificate; //{ throw new Error("Not implemented.");} CreateFromSignedFile(filename: string): System.Security.Cryptography.X509Certificates.X509Certificate; //{ throw new Error("Not implemented.");} Dispose(disposing: boolean): any; //{ throw new Error("Not implemented.");} Dispose(): any; //{ throw new Error("Not implemented.");} Equals(other: System.Security.Cryptography.X509Certificates.X509Certificate): boolean; //{ throw new Error("Not implemented.");} Equals(obj: any): boolean; //{ throw new Error("Not implemented.");} Export(contentType: System.Security.Cryptography.X509Certificates.X509ContentType, password: any): System.Byte[]; //{ throw new Error("Not implemented.");} Export(contentType: System.Security.Cryptography.X509Certificates.X509ContentType, password: string): System.Byte[]; //{ throw new Error("Not implemented.");} Export(contentType: System.Security.Cryptography.X509Certificates.X509ContentType): System.Byte[]; //{ throw new Error("Not implemented.");} ExportHelper(contentType: System.Security.Cryptography.X509Certificates.X509ContentType, password: any): System.Byte[]; //{ throw new Error("Not implemented.");} FormatDate(date: Date): string; //{ throw new Error("Not implemented.");} GetCertContextForCloning(): System.Security.Cryptography.X509Certificates.SafeCertContextHandle; //{ throw new Error("Not implemented.");} GetCertHash(): System.Byte[]; //{ throw new Error("Not implemented.");} GetCertHashString(): string; //{ throw new Error("Not implemented.");} GetEffectiveDateString(): string; //{ throw new Error("Not implemented.");} GetExpirationDateString(): string; //{ throw new Error("Not implemented.");} GetFormat(): string; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetIssuerName(): string; //{ throw new Error("Not implemented.");} GetKeyAlgorithm(): string; //{ throw new Error("Not implemented.");} GetKeyAlgorithmParameters(): System.Byte[]; //{ throw new Error("Not implemented.");} GetKeyAlgorithmParametersString(): string; //{ throw new Error("Not implemented.");} GetName(): string; //{ throw new Error("Not implemented.");} GetPublicKey(): System.Byte[]; //{ throw new Error("Not implemented.");} GetPublicKeyString(): string; //{ throw new Error("Not implemented.");} GetRawCertData(): System.Byte[]; //{ throw new Error("Not implemented.");} GetRawCertDataString(): string; //{ throw new Error("Not implemented.");} GetSerialNumber(): System.Byte[]; //{ throw new Error("Not implemented.");} GetSerialNumberString(): string; //{ throw new Error("Not implemented.");} Import(fileName: string): any; //{ throw new Error("Not implemented.");} Import(fileName: string, password: string, keyStorageFlags: System.Security.Cryptography.X509Certificates.X509KeyStorageFlags): any; //{ throw new Error("Not implemented.");} Import(rawData: System.Byte[], password: any, keyStorageFlags: System.Security.Cryptography.X509Certificates.X509KeyStorageFlags): any; //{ throw new Error("Not implemented.");} Import(rawData: System.Byte[], password: string, keyStorageFlags: System.Security.Cryptography.X509Certificates.X509KeyStorageFlags): any; //{ throw new Error("Not implemented.");} Import(rawData: System.Byte[]): any; //{ throw new Error("Not implemented.");} Import(fileName: string, password: any, keyStorageFlags: System.Security.Cryptography.X509Certificates.X509KeyStorageFlags): any; //{ throw new Error("Not implemented.");} Init(): any; //{ throw new Error("Not implemented.");} LoadCertificateFromBlob(rawData: System.Byte[], password: any, keyStorageFlags: System.Security.Cryptography.X509Certificates.X509KeyStorageFlags): any; //{ throw new Error("Not implemented.");} LoadCertificateFromFile(fileName: string, password: any, keyStorageFlags: System.Security.Cryptography.X509Certificates.X509KeyStorageFlags): any; //{ throw new Error("Not implemented.");} Reset(): any; //{ throw new Error("Not implemented.");} SetThumbprint(): any; //{ throw new Error("Not implemented.");} ThrowIfContextInvalid(): any; //{ throw new Error("Not implemented.");} ToString(fVerbose: boolean): string; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} } export class X509CertificateCollection extends System.Collections.CollectionBase { Item: System.Security.Cryptography.X509Certificates.X509Certificate; Add(value: System.Security.Cryptography.X509Certificates.X509Certificate): number; //{ throw new Error("Not implemented.");} AddRange(value: any): any; //{ throw new Error("Not implemented.");} AddRange(value: System.Security.Cryptography.X509Certificates.X509CertificateCollection): any; //{ throw new Error("Not implemented.");} Contains(value: System.Security.Cryptography.X509Certificates.X509Certificate): boolean; //{ throw new Error("Not implemented.");} CopyTo(array: any, index: number): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} IndexOf(value: System.Security.Cryptography.X509Certificates.X509Certificate): number; //{ throw new Error("Not implemented.");} Insert(index: number, value: System.Security.Cryptography.X509Certificates.X509Certificate): any; //{ throw new Error("Not implemented.");} Remove(value: System.Security.Cryptography.X509Certificates.X509Certificate): any; //{ throw new Error("Not implemented.");} } } declare module System.Security.Cryptography.Xml { export class CanonicalXmlNodeList extends System.Xml.XmlNodeList { Count: number; IsFixedSize: boolean; IsReadOnly: boolean; private System.Collections.IList.Item: any; SyncRoot: any; IsSynchronized: boolean; private m_nodeArray: System.Collections.ArrayList; Add(value: any): number; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} Contains(value: any): boolean; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array, index: number): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} IndexOf(value: any): number; //{ throw new Error("Not implemented.");} Insert(index: number, value: any): any; //{ throw new Error("Not implemented.");} Item(index: number): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} Remove(value: any): any; //{ throw new Error("Not implemented.");} RemoveAt(index: number): any; //{ throw new Error("Not implemented.");} } export class EncryptedXml { DocumentEvidence: System.Security.Policy.Evidence; Resolver: System.Xml.XmlResolver; Padding: System.Security.Cryptography.PaddingMode; Mode: System.Security.Cryptography.CipherMode; Encoding: System.Text.Encoding; Recipient: string; private m_document: System.Xml.XmlDocument; private m_evidence: System.Security.Policy.Evidence; private m_xmlResolver: System.Xml.XmlResolver; private m_keyNameMapping: System.Collections.Hashtable; private m_padding: System.Security.Cryptography.PaddingMode; private m_mode: System.Security.Cryptography.CipherMode; private m_encoding: System.Text.Encoding; private m_recipient: string; AddKeyNameMapping(keyName: string, keyObject: any): any; //{ throw new Error("Not implemented.");} ClearKeyNameMappings(): any; //{ throw new Error("Not implemented.");} DecryptData(encryptedData: any, symmetricAlgorithm: any): System.Byte[]; //{ throw new Error("Not implemented.");} DecryptDocument(): any; //{ throw new Error("Not implemented.");} DecryptEncryptedKey(encryptedKey: any): System.Byte[]; //{ throw new Error("Not implemented.");} DecryptKey(keyData: System.Byte[], rsa: any, useOAEP: boolean): System.Byte[]; //{ throw new Error("Not implemented.");} DecryptKey(keyData: System.Byte[], symmetricAlgorithm: any): System.Byte[]; //{ throw new Error("Not implemented.");} DownloadCipherValue(cipherData: any, inputStream: any, decInputStream: any, response: any): any; //{ throw new Error("Not implemented.");} Encrypt(inputElement: System.Xml.XmlElement, certificate: any): any; //{ throw new Error("Not implemented.");} Encrypt(inputElement: System.Xml.XmlElement, keyName: string): any; //{ throw new Error("Not implemented.");} EncryptData(plaintext: System.Byte[], symmetricAlgorithm: any): System.Byte[]; //{ throw new Error("Not implemented.");} EncryptData(inputElement: System.Xml.XmlElement, symmetricAlgorithm: any, content: boolean): System.Byte[]; //{ throw new Error("Not implemented.");} EncryptKey(keyData: System.Byte[], symmetricAlgorithm: any): System.Byte[]; //{ throw new Error("Not implemented.");} EncryptKey(keyData: System.Byte[], rsa: any, useOAEP: boolean): System.Byte[]; //{ throw new Error("Not implemented.");} GetCipherValue(cipherData: any): System.Byte[]; //{ throw new Error("Not implemented.");} GetDecryptionIV(encryptedData: any, symmetricAlgorithmUri: string): System.Byte[]; //{ throw new Error("Not implemented.");} GetDecryptionKey(encryptedData: any, symmetricAlgorithmUri: string): any; //{ throw new Error("Not implemented.");} GetIdElement(document: System.Xml.XmlDocument, idValue: string): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} ReplaceData(inputElement: System.Xml.XmlElement, decryptedData: System.Byte[]): any; //{ throw new Error("Not implemented.");} ReplaceElement(inputElement: System.Xml.XmlElement, encryptedData: any, content: boolean): any; //{ throw new Error("Not implemented.");} } export class KeyInfo { Id: string; Count: number; private m_id: string; private m_KeyInfoClauses: System.Collections.ArrayList; AddClause(clause: any): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetEnumerator(requestedObjectType: System.Type): any; //{ throw new Error("Not implemented.");} GetXml(): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} GetXml(xmlDocument: System.Xml.XmlDocument): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} LoadXml(value: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} } export class Reference { Id: string; Uri: string; Type: string; DigestMethod: string; DigestValue: System.Byte[]; TransformChain: System.Security.Cryptography.Xml.TransformChain; CacheValid: boolean; SignedXml: System.Security.Cryptography.Xml.SignedXml; ReferenceTargetType: System.Security.Cryptography.Xml.ReferenceTargetType; private m_id: string; private m_uri: string; private m_type: string; private m_transformChain: System.Security.Cryptography.Xml.TransformChain; private m_digestMethod: string; private m_digestValue: System.Byte[]; private m_hashAlgorithm: any; private m_refTarget: any; private m_refTargetType: System.Security.Cryptography.Xml.ReferenceTargetType; private m_cachedXml: System.Xml.XmlElement; private m_signedXml: System.Security.Cryptography.Xml.SignedXml; m_namespaces: System.Security.Cryptography.Xml.CanonicalXmlNodeList; AddTransform(transform: System.Security.Cryptography.Xml.Transform): any; //{ throw new Error("Not implemented.");} CalculateHashValue(document: System.Xml.XmlDocument, refList: System.Security.Cryptography.Xml.CanonicalXmlNodeList): System.Byte[]; //{ throw new Error("Not implemented.");} GetXml(): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} GetXml(document: System.Xml.XmlDocument): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} LoadXml(value: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} UpdateHashValue(document: System.Xml.XmlDocument, refList: System.Security.Cryptography.Xml.CanonicalXmlNodeList): any; //{ throw new Error("Not implemented.");} } export class Signature { SignedXml: System.Security.Cryptography.Xml.SignedXml; Id: string; SignedInfo: System.Security.Cryptography.Xml.SignedInfo; SignatureValue: System.Byte[]; KeyInfo: System.Security.Cryptography.Xml.KeyInfo; ObjectList: System.Collections.IList; ReferencedItems: System.Security.Cryptography.Xml.CanonicalXmlNodeList; private m_id: string; private m_signedInfo: System.Security.Cryptography.Xml.SignedInfo; private m_signatureValue: System.Byte[]; private m_signatureValueId: string; private m_keyInfo: System.Security.Cryptography.Xml.KeyInfo; private m_embeddedObjects: System.Collections.IList; private m_referencedItems: System.Security.Cryptography.Xml.CanonicalXmlNodeList; private m_signedXml: System.Security.Cryptography.Xml.SignedXml; AddObject(dataObject: any): any; //{ throw new Error("Not implemented.");} GetXml(): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} GetXml(document: System.Xml.XmlDocument): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} LoadXml(value: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} } export class SignedInfo { SignedXml: System.Security.Cryptography.Xml.SignedXml; Count: number; IsReadOnly: boolean; IsSynchronized: boolean; SyncRoot: any; Id: string; CanonicalizationMethod: string; CanonicalizationMethodObject: System.Security.Cryptography.Xml.Transform; SignatureMethod: string; SignatureLength: string; References: System.Collections.ArrayList; CacheValid: boolean; private m_id: string; private m_canonicalizationMethod: string; private m_signatureMethod: string; private m_signatureLength: string; private m_references: System.Collections.ArrayList; private m_cachedXml: System.Xml.XmlElement; private m_signedXml: System.Security.Cryptography.Xml.SignedXml; private m_canonicalizationMethodTransform: System.Security.Cryptography.Xml.Transform; AddReference(reference: System.Security.Cryptography.Xml.Reference): any; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array, index: number): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetXml(): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} GetXml(document: System.Xml.XmlDocument): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} LoadXml(value: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} } export class SignedXml { SigningKeyName: string; Resolver: System.Xml.XmlResolver; ResolverSet: boolean; SignatureFormatValidator: System.Func<System.Security.Cryptography.Xml.SignedXml, boolean>; SafeCanonicalizationMethods: System.Collections.ObjectModel.Collection<string>; SigningKey: System.Security.Cryptography.AsymmetricAlgorithm; EncryptedXml: System.Security.Cryptography.Xml.EncryptedXml; Signature: System.Security.Cryptography.Xml.Signature; SignedInfo: System.Security.Cryptography.Xml.SignedInfo; SignatureMethod: string; SignatureLength: string; SignatureValue: System.Byte[]; KeyInfo: System.Security.Cryptography.Xml.KeyInfo; private static KnownCanonicalizationMethods: System.Collections.Generic.IList<string>; m_signature: System.Security.Cryptography.Xml.Signature; m_strSigningKeyName: string; private m_signingKey: System.Security.Cryptography.AsymmetricAlgorithm; private m_containingDocument: System.Xml.XmlDocument; private m_keyInfoEnum: any; private m_x509Collection: any; private m_x509Enum: any; private m_refProcessed: any; private m_refLevelCache: System.Int32[]; m_xmlResolver: System.Xml.XmlResolver; m_context: System.Xml.XmlElement; private m_bResolverSet: boolean; private m_signatureFormatValidator: System.Func<System.Security.Cryptography.Xml.SignedXml, boolean>; private m_safeCanonicalizationMethods: System.Collections.ObjectModel.Collection<string>; private m_exml: System.Security.Cryptography.Xml.EncryptedXml; private bCacheValid: boolean; private _digestedSignedInfo: System.Byte[]; private static s_knownCanonicalizationMethods: System.Collections.Generic.IList<string>; AddObject(dataObject: any): any; //{ throw new Error("Not implemented.");} AddReference(reference: System.Security.Cryptography.Xml.Reference): any; //{ throw new Error("Not implemented.");} BuildBagOfCerts(): any; //{ throw new Error("Not implemented.");} BuildDigestedReferences(): any; //{ throw new Error("Not implemented.");} CheckDigestedReferences(): boolean; //{ throw new Error("Not implemented.");} CheckSignature(): boolean; //{ throw new Error("Not implemented.");} CheckSignature(key: System.Security.Cryptography.AsymmetricAlgorithm): boolean; //{ throw new Error("Not implemented.");} CheckSignature(macAlg: any): boolean; //{ throw new Error("Not implemented.");} CheckSignature(certificate: any, verifySignatureOnly: boolean): boolean; //{ throw new Error("Not implemented.");} CheckSignatureFormat(): boolean; //{ throw new Error("Not implemented.");} CheckSignatureReturningKey(signingKey: any): boolean; //{ throw new Error("Not implemented.");} CheckSignedInfo(key: System.Security.Cryptography.AsymmetricAlgorithm): boolean; //{ throw new Error("Not implemented.");} CheckSignedInfo(macAlg: any): boolean; //{ throw new Error("Not implemented.");} ComputeSignature(macAlg: any): any; //{ throw new Error("Not implemented.");} ComputeSignature(): any; //{ throw new Error("Not implemented.");} DefaultSignatureFormatValidator(signedXml: System.Security.Cryptography.Xml.SignedXml): boolean; //{ throw new Error("Not implemented.");} DoesSignatureUseSafeCanonicalizationMethod(): boolean; //{ throw new Error("Not implemented.");} DoesSignatureUseTruncatedHmac(): boolean; //{ throw new Error("Not implemented.");} GetC14NDigest(hash: any): System.Byte[]; //{ throw new Error("Not implemented.");} GetIdElement(document: System.Xml.XmlDocument, idValue: string): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} GetNextCertificatePublicKey(): System.Security.Cryptography.AsymmetricAlgorithm; //{ throw new Error("Not implemented.");} GetPublicKey(): System.Security.Cryptography.AsymmetricAlgorithm; //{ throw new Error("Not implemented.");} GetReferenceLevel(index: number, references: System.Collections.ArrayList): number; //{ throw new Error("Not implemented.");} GetXml(): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} Initialize(element: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} LoadXml(value: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} ReadAdditionalSafeCanonicalizationMethods(): System.Collections.Generic.List<string>; //{ throw new Error("Not implemented.");} } export class Transform { BaseURI: string; SignedXml: System.Security.Cryptography.Xml.SignedXml; Reference: System.Security.Cryptography.Xml.Reference; Algorithm: string; Resolver: System.Xml.XmlResolver; ResolverSet: boolean; InputTypes: System.Type[]; OutputTypes: System.Type[]; Context: System.Xml.XmlElement; PropagatedNamespaces: System.Collections.Hashtable; private m_algorithm: string; private m_baseUri: string; m_xmlResolver: System.Xml.XmlResolver; private m_bResolverSet: boolean; private m_signedXml: System.Security.Cryptography.Xml.SignedXml; private m_reference: System.Security.Cryptography.Xml.Reference; private m_propagatedNamespaces: System.Collections.Hashtable; private m_context: System.Xml.XmlElement; AcceptsType(inputType: System.Type): boolean; //{ throw new Error("Not implemented.");} GetDigestedOutput(hash: any): System.Byte[]; //{ throw new Error("Not implemented.");} GetInnerXml(): System.Xml.XmlNodeList; //{ throw new Error("Not implemented.");} GetOutput(): any; //{ throw new Error("Not implemented.");} GetOutput(type: System.Type): any; //{ throw new Error("Not implemented.");} GetXml(): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} GetXml(document: System.Xml.XmlDocument): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} GetXml(document: System.Xml.XmlDocument, name: string): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} LoadInnerXml(nodeList: System.Xml.XmlNodeList): any; //{ throw new Error("Not implemented.");} LoadInput(obj: any): any; //{ throw new Error("Not implemented.");} } export class TransformChain { Count: number; Item: System.Security.Cryptography.Xml.Transform; private m_transforms: System.Collections.ArrayList; Add(transform: System.Security.Cryptography.Xml.Transform): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetXml(document: System.Xml.XmlDocument, ns: string): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} LoadXml(value: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} TransformToOctetStream(inputObject: any, inputType: System.Type, resolver: System.Xml.XmlResolver, baseUri: string): System.IO.Stream; //{ throw new Error("Not implemented.");} TransformToOctetStream(input: System.IO.Stream, resolver: System.Xml.XmlResolver, baseUri: string): System.IO.Stream; //{ throw new Error("Not implemented.");} TransformToOctetStream(document: System.Xml.XmlDocument, resolver: System.Xml.XmlResolver, baseUri: string): System.IO.Stream; //{ throw new Error("Not implemented.");} } } declare module System.Security.Policy { export class Evidence { static RuntimeEvidenceTypes: System.Type[]; private IsReaderLockHeld: boolean; private IsWriterLockHeld: boolean; IsUnmodified: boolean; Locked: boolean; Target: System.Security.Policy.IRuntimeEvidenceFactory; Count: number; RawCount: number; SyncRoot: any; IsSynchronized: boolean; IsReadOnly: boolean; private m_evidence: System.Collections.Generic.Dictionary<TKey, TValue>; private m_deserializedTargetEvidence: boolean; private m_hostList: System.Collections.ArrayList; private m_assemblyList: System.Collections.ArrayList; private m_evidenceLock: any; private m_version: number; private m_target: System.Security.Policy.IRuntimeEvidenceFactory; private m_locked: boolean; private m_cloneOrigin: any; private static s_runtimeEvidenceTypes: System.Type[]; AcquireReaderLock(): any; //{ throw new Error("Not implemented.");} AcquireWriterlock(): any; //{ throw new Error("Not implemented.");} AddAssembly(id: any): any; //{ throw new Error("Not implemented.");} AddAssemblyEvidence(evidence: any): any; //{ throw new Error("Not implemented.");} AddAssemblyEvidence(evidence: any, evidenceType: System.Type, duplicateAction: System.Security.Policy.Evidence.DuplicateEvidenceAction): any; //{ throw new Error("Not implemented.");} AddAssemblyEvidenceNoLock(evidence: any, evidenceType: System.Type, duplicateAction: System.Security.Policy.Evidence.DuplicateEvidenceAction): any; //{ throw new Error("Not implemented.");} AddHost(id: any): any; //{ throw new Error("Not implemented.");} AddHostEvidence(evidence: any): any; //{ throw new Error("Not implemented.");} AddHostEvidence(evidence: any, evidenceType: System.Type, duplicateAction: System.Security.Policy.Evidence.DuplicateEvidenceAction): any; //{ throw new Error("Not implemented.");} AddHostEvidenceNoLock(evidence: any, evidenceType: System.Type, duplicateAction: System.Security.Policy.Evidence.DuplicateEvidenceAction): any; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} Clone(): System.Security.Policy.Evidence; //{ throw new Error("Not implemented.");} CopyTo(array: System.Array, index: number): any; //{ throw new Error("Not implemented.");} DeserializeTargetEvidence(): any; //{ throw new Error("Not implemented.");} DowngradeFromWriterLock(lockCookie: any): any; //{ throw new Error("Not implemented.");} GenerateHostEvidence(type: System.Type, hostCanGenerate: boolean): any; //{ throw new Error("Not implemented.");} GetAssemblyEnumerator(): any; //{ throw new Error("Not implemented.");} GetAssemblyEvidence(): any; //{ throw new Error("Not implemented.");} GetAssemblyEvidence(type: System.Type): any; //{ throw new Error("Not implemented.");} GetAssemblyEvidenceNoLock(type: System.Type): any; //{ throw new Error("Not implemented.");} GetDelayEvaluatedHostEvidence(): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetEvidenceIndexType(evidence: any): System.Type; //{ throw new Error("Not implemented.");} GetEvidenceTypeDescriptor(evidenceType: System.Type, addIfNotExist: boolean): any; //{ throw new Error("Not implemented.");} GetEvidenceTypeDescriptor(evidenceType: System.Type): any; //{ throw new Error("Not implemented.");} GetHostEnumerator(): any; //{ throw new Error("Not implemented.");} GetHostEvidence(type: System.Type): any; //{ throw new Error("Not implemented.");} GetHostEvidence(): any; //{ throw new Error("Not implemented.");} GetHostEvidence(type: System.Type, markDelayEvaluatedEvidenceUsed: boolean): any; //{ throw new Error("Not implemented.");} GetHostEvidenceNoLock(type: System.Type): any; //{ throw new Error("Not implemented.");} GetRawAssemblyEvidenceEnumerator(): any; //{ throw new Error("Not implemented.");} GetRawHostEvidenceEnumerator(): any; //{ throw new Error("Not implemented.");} HandleDuplicateEvidence(original: any, duplicate: any, action: System.Security.Policy.Evidence.DuplicateEvidenceAction): any; //{ throw new Error("Not implemented.");} MarkAllEvidenceAsUsed(): any; //{ throw new Error("Not implemented.");} Merge(evidence: System.Security.Policy.Evidence): any; //{ throw new Error("Not implemented.");} MergeWithNoDuplicates(evidence: System.Security.Policy.Evidence): any; //{ throw new Error("Not implemented.");} OnDeserialized(context: any): any; //{ throw new Error("Not implemented.");} OnSerializing(context: any): any; //{ throw new Error("Not implemented.");} QueryHostForPossibleEvidenceTypes(): any; //{ throw new Error("Not implemented.");} RawSerialize(): System.Byte[]; //{ throw new Error("Not implemented.");} ReleaseReaderLock(): any; //{ throw new Error("Not implemented.");} ReleaseWriterLock(): any; //{ throw new Error("Not implemented.");} RemoveType(t: System.Type): any; //{ throw new Error("Not implemented.");} UnwrapEvidence(evidence: any): any; //{ throw new Error("Not implemented.");} UpgradeToWriterLock(): any; //{ throw new Error("Not implemented.");} WasStrongNameEvidenceUsed(): boolean; //{ throw new Error("Not implemented.");} WrapLegacyEvidence(evidence: any): any; //{ throw new Error("Not implemented.");} } interface IRuntimeEvidenceFactory { Target: System.Security.IEvidenceFactory; GenerateEvidence(evidenceType: System.Type): any; GetFactorySuppliedEvidence(): System.Collections.Generic.IEnumerable<T>; } } declare module System.Text { export class DecoderFallback { private static InternalSyncObject: any; static ReplacementFallback: System.Text.DecoderFallback; static ExceptionFallback: System.Text.DecoderFallback; MaxCharCount: number; IsMicrosoftBestFitFallback: boolean; bIsMicrosoftBestFitFallback: boolean; private static replacementFallback: System.Text.DecoderFallback; private static exceptionFallback: System.Text.DecoderFallback; private static s_InternalSyncObject: any; CreateFallbackBuffer(): any; //{ throw new Error("Not implemented.");} } export class EncoderFallback { private static InternalSyncObject: any; static ReplacementFallback: System.Text.EncoderFallback; static ExceptionFallback: System.Text.EncoderFallback; MaxCharCount: number; bIsMicrosoftBestFitFallback: boolean; private static replacementFallback: System.Text.EncoderFallback; private static exceptionFallback: System.Text.EncoderFallback; private static s_InternalSyncObject: any; CreateFallbackBuffer(): any; //{ throw new Error("Not implemented.");} } export class Encoding { private static InternalSyncObject: any; BodyName: string; EncodingName: string; HeaderName: string; WebName: string; WindowsCodePage: number; IsBrowserDisplay: boolean; IsBrowserSave: boolean; IsMailNewsDisplay: boolean; IsMailNewsSave: boolean; IsSingleByte: boolean; EncoderFallback: System.Text.EncoderFallback; DecoderFallback: System.Text.DecoderFallback; IsReadOnly: boolean; static ASCII: System.Text.Encoding; private static Latin1: System.Text.Encoding; CodePage: number; static Default: System.Text.Encoding; static Unicode: System.Text.Encoding; static BigEndianUnicode: System.Text.Encoding; static UTF7: System.Text.Encoding; static UTF8: System.Text.Encoding; static UTF32: System.Text.Encoding; m_codePage: number; dataItem: any; m_deserializedFromEverett: boolean; private m_isReadOnly: boolean; encoderFallback: System.Text.EncoderFallback; decoderFallback: System.Text.DecoderFallback; private static defaultEncoding: System.Text.Encoding; private static unicodeEncoding: System.Text.Encoding; private static bigEndianUnicode: System.Text.Encoding; private static utf7Encoding: System.Text.Encoding; private static utf8Encoding: System.Text.Encoding; private static utf32Encoding: System.Text.Encoding; private static asciiEncoding: System.Text.Encoding; private static latin1Encoding: System.Text.Encoding; private static encodings: System.Collections.Hashtable; private static s_InternalSyncObject: any; Clone(): any; //{ throw new Error("Not implemented.");} Convert(srcEncoding: System.Text.Encoding, dstEncoding: System.Text.Encoding, bytes: System.Byte[]): System.Byte[]; //{ throw new Error("Not implemented.");} Convert(srcEncoding: System.Text.Encoding, dstEncoding: System.Text.Encoding, bytes: System.Byte[], index: number, count: number): System.Byte[]; //{ throw new Error("Not implemented.");} CreateDefaultEncoding(): System.Text.Encoding; //{ throw new Error("Not implemented.");} DeserializeEncoding(info: any, context: any): any; //{ throw new Error("Not implemented.");} Equals(value: any): boolean; //{ throw new Error("Not implemented.");} GetBestFitBytesToUnicodeData(): any; //{ throw new Error("Not implemented.");} GetBestFitUnicodeToBytesData(): any; //{ throw new Error("Not implemented.");} GetByteCount(s: string): number; //{ throw new Error("Not implemented.");} GetByteCount(chars: any, count: number, encoder: any): number; //{ throw new Error("Not implemented.");} GetByteCount(chars: any, count: number): number; //{ throw new Error("Not implemented.");} GetByteCount(chars: any, index: number, count: number): number; //{ throw new Error("Not implemented.");} GetByteCount(chars: any): number; //{ throw new Error("Not implemented.");} GetBytes(chars: any, charIndex: number, charCount: number, bytes: System.Byte[], byteIndex: number): number; //{ throw new Error("Not implemented.");} GetBytes(chars: any, charCount: number, bytes: any, byteCount: number, encoder: any): number; //{ throw new Error("Not implemented.");} GetBytes(s: string, charIndex: number, charCount: number, bytes: System.Byte[], byteIndex: number): number; //{ throw new Error("Not implemented.");} GetBytes(chars: any): System.Byte[]; //{ throw new Error("Not implemented.");} GetBytes(chars: any, charCount: number, bytes: any, byteCount: number): number; //{ throw new Error("Not implemented.");} GetBytes(s: string): System.Byte[]; //{ throw new Error("Not implemented.");} GetBytes(chars: any, index: number, count: number): System.Byte[]; //{ throw new Error("Not implemented.");} GetCharCount(bytes: System.Byte[]): number; //{ throw new Error("Not implemented.");} GetCharCount(bytes: any, count: number): number; //{ throw new Error("Not implemented.");} GetCharCount(bytes: any, count: number, decoder: any): number; //{ throw new Error("Not implemented.");} GetCharCount(bytes: System.Byte[], index: number, count: number): number; //{ throw new Error("Not implemented.");} GetChars(bytes: any, byteCount: number, chars: any, charCount: number, decoder: any): number; //{ throw new Error("Not implemented.");} GetChars(bytes: System.Byte[]): any; //{ throw new Error("Not implemented.");} GetChars(bytes: System.Byte[], index: number, count: number): any; //{ throw new Error("Not implemented.");} GetChars(bytes: System.Byte[], byteIndex: number, byteCount: number, chars: any, charIndex: number): number; //{ throw new Error("Not implemented.");} GetChars(bytes: any, byteCount: number, chars: any, charCount: number): number; //{ throw new Error("Not implemented.");} GetDataItem(): any; //{ throw new Error("Not implemented.");} GetDecoder(): any; //{ throw new Error("Not implemented.");} GetEncoder(): any; //{ throw new Error("Not implemented.");} GetEncoding(name: string, encoderFallback: System.Text.EncoderFallback, decoderFallback: System.Text.DecoderFallback): System.Text.Encoding; //{ throw new Error("Not implemented.");} GetEncoding(name: string): System.Text.Encoding; //{ throw new Error("Not implemented.");} GetEncoding(codepage: number, encoderFallback: System.Text.EncoderFallback, decoderFallback: System.Text.DecoderFallback): System.Text.Encoding; //{ throw new Error("Not implemented.");} GetEncoding(codepage: number): System.Text.Encoding; //{ throw new Error("Not implemented.");} GetEncodingCodePage(CodePage: number): System.Text.Encoding; //{ throw new Error("Not implemented.");} GetEncodingRare(codepage: number): System.Text.Encoding; //{ throw new Error("Not implemented.");} GetEncodings(): any; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetMaxByteCount(charCount: number): number; //{ throw new Error("Not implemented.");} GetMaxCharCount(byteCount: number): number; //{ throw new Error("Not implemented.");} GetPreamble(): System.Byte[]; //{ throw new Error("Not implemented.");} GetString(bytes: System.Byte[], index: number, count: number): string; //{ throw new Error("Not implemented.");} GetString(bytes: System.Byte[]): string; //{ throw new Error("Not implemented.");} GetString(bytes: any, byteCount: number): string; //{ throw new Error("Not implemented.");} IsAlwaysNormalized(form: System.Text.NormalizationForm): boolean; //{ throw new Error("Not implemented.");} IsAlwaysNormalized(): boolean; //{ throw new Error("Not implemented.");} OnDeserialized(): any; //{ throw new Error("Not implemented.");} OnDeserialized(ctx: any): any; //{ throw new Error("Not implemented.");} OnDeserializing(): any; //{ throw new Error("Not implemented.");} OnDeserializing(ctx: any): any; //{ throw new Error("Not implemented.");} OnSerializing(ctx: any): any; //{ throw new Error("Not implemented.");} RegisterProvider(provider: any): any; //{ throw new Error("Not implemented.");} SerializeEncoding(info: any, context: any): any; //{ throw new Error("Not implemented.");} SetDefaultFallbacks(): any; //{ throw new Error("Not implemented.");} ThrowBytesOverflow(): any; //{ throw new Error("Not implemented.");} ThrowBytesOverflow(encoder: any, nothingEncoded: boolean): any; //{ throw new Error("Not implemented.");} ThrowCharsOverflow(): any; //{ throw new Error("Not implemented.");} ThrowCharsOverflow(decoder: any, nothingDecoded: boolean): any; //{ throw new Error("Not implemented.");} } } declare module System.Threading { export class WaitHandle extends System.MarshalByRefObject { Handle: number; SafeWaitHandle: Microsoft.Win32.SafeHandles.SafeWaitHandle; private waitHandle: number; safeWaitHandle: Microsoft.Win32.SafeHandles.SafeWaitHandle; hasThreadAffinity: boolean; static InvalidHandle: number; Close(): any; //{ throw new Error("Not implemented.");} Dispose(): any; //{ throw new Error("Not implemented.");} Dispose(explicitDisposing: boolean): any; //{ throw new Error("Not implemented.");} GetInvalidHandle(): number; //{ throw new Error("Not implemented.");} Init(): any; //{ throw new Error("Not implemented.");} InternalWaitOne(waitableSafeHandle: System.Runtime.InteropServices.SafeHandle, millisecondsTimeout: number, hasThreadAffinity: boolean, exitContext: boolean): boolean; //{ throw new Error("Not implemented.");} SetHandleInternal(handle: Microsoft.Win32.SafeHandles.SafeWaitHandle): any; //{ throw new Error("Not implemented.");} SignalAndWait(toSignal: System.Threading.WaitHandle, toWaitOn: System.Threading.WaitHandle, millisecondsTimeout: number, exitContext: boolean): boolean; //{ throw new Error("Not implemented.");} SignalAndWait(toSignal: System.Threading.WaitHandle, toWaitOn: System.Threading.WaitHandle, timeout: System.TimeSpan, exitContext: boolean): boolean; //{ throw new Error("Not implemented.");} SignalAndWait(toSignal: System.Threading.WaitHandle, toWaitOn: System.Threading.WaitHandle): boolean; //{ throw new Error("Not implemented.");} SignalAndWaitOne(waitHandleToSignal: Microsoft.Win32.SafeHandles.SafeWaitHandle, waitHandleToWaitOn: Microsoft.Win32.SafeHandles.SafeWaitHandle, millisecondsTimeout: number, hasThreadAffinity: boolean, exitContext: boolean): number; //{ throw new Error("Not implemented.");} ThrowAbandonedMutexException(): any; //{ throw new Error("Not implemented.");} ThrowAbandonedMutexException(location: number, handle: System.Threading.WaitHandle): any; //{ throw new Error("Not implemented.");} WaitAll(waitHandles: any, timeout: System.TimeSpan): boolean; //{ throw new Error("Not implemented.");} WaitAll(waitHandles: any, millisecondsTimeout: number): boolean; //{ throw new Error("Not implemented.");} WaitAll(waitHandles: any): boolean; //{ throw new Error("Not implemented.");} WaitAll(waitHandles: any, millisecondsTimeout: number, exitContext: boolean): boolean; //{ throw new Error("Not implemented.");} WaitAll(waitHandles: any, timeout: System.TimeSpan, exitContext: boolean): boolean; //{ throw new Error("Not implemented.");} WaitAny(waitHandles: any, timeout: System.TimeSpan, exitContext: boolean): number; //{ throw new Error("Not implemented.");} WaitAny(waitHandles: any): number; //{ throw new Error("Not implemented.");} WaitAny(waitHandles: any, timeout: System.TimeSpan): number; //{ throw new Error("Not implemented.");} WaitAny(waitHandles: any, millisecondsTimeout: number, exitContext: boolean): number; //{ throw new Error("Not implemented.");} WaitAny(waitHandles: any, millisecondsTimeout: number): number; //{ throw new Error("Not implemented.");} WaitMultiple(waitHandles: any, millisecondsTimeout: number, exitContext: boolean, WaitAll: boolean): number; //{ throw new Error("Not implemented.");} WaitOne(timeout: System.TimeSpan): boolean; //{ throw new Error("Not implemented.");} WaitOne(millisecondsTimeout: number): boolean; //{ throw new Error("Not implemented.");} WaitOne(): boolean; //{ throw new Error("Not implemented.");} WaitOne(timeout: System.TimeSpan, exitContext: boolean): boolean; //{ throw new Error("Not implemented.");} WaitOne(timeout: number, exitContext: boolean): boolean; //{ throw new Error("Not implemented.");} WaitOne(millisecondsTimeout: number, exitContext: boolean): boolean; //{ throw new Error("Not implemented.");} WaitOneNative(waitableSafeHandle: System.Runtime.InteropServices.SafeHandle, millisecondsTimeout: number, hasThreadAffinity: boolean, exitContext: boolean): number; //{ throw new Error("Not implemented.");} WaitOneWithoutFAS(): boolean; //{ throw new Error("Not implemented.");} } } declare module System.Uri { } declare module System.Xml { interface IDtdDefaultAttributeInfo { DefaultValueExpanded: string; DefaultValueTyped: any; ValueLineNumber: number; ValueLinePosition: number; } interface IXmlNamespaceResolver { GetNamespacesInScope(scope: System.Xml.XmlNamespaceScope): System.Collections.Generic.IDictionary<string, string>; LookupNamespace(prefix: string): string; LookupPrefix(namespaceName: string): string; } export class XmlAttribute extends System.Xml.XmlNode { LocalNameHash: number; XmlName: System.Xml.XmlName; ParentNode: System.Xml.XmlNode; Name: string; LocalName: string; NamespaceURI: string; Prefix: string; NodeType: System.Xml.XmlNodeType; OwnerDocument: System.Xml.XmlDocument; Value: string; SchemaInfo: System.Xml.Schema.IXmlSchemaInfo; InnerText: string; IsContainer: boolean; LastNode: System.Xml.XmlLinkedNode; Specified: boolean; OwnerElement: System.Xml.XmlElement; InnerXml: string; BaseURI: string; XmlSpace: System.Xml.XmlSpace; XmlLang: string; XPNodeType: System.Xml.XPath.XPathNodeType; XPLocalName: string; IsNamespace: boolean; private name: System.Xml.XmlName; private lastChild: System.Xml.XmlLinkedNode; AppendChild(newChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} AppendChildForLoad(newChild: System.Xml.XmlNode, doc: System.Xml.XmlDocument): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} CloneNode(deep: boolean): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} InsertAfter(newChild: System.Xml.XmlNode, refChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} InsertBefore(newChild: System.Xml.XmlNode, refChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} IsValidChildType(type: System.Xml.XmlNodeType): boolean; //{ throw new Error("Not implemented.");} PrepareOwnerElementInElementIdAttrMap(): boolean; //{ throw new Error("Not implemented.");} PrependChild(newChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} RemoveChild(oldChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} ReplaceChild(newChild: System.Xml.XmlNode, oldChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} ResetOwnerElementInElementIdAttrMap(oldInnerText: string): any; //{ throw new Error("Not implemented.");} SetParent(node: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} WriteContentTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} WriteTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} } export class XmlAttributeCollection extends System.Xml.XmlNamedNodeMap { ItemOf: System.Xml.XmlAttribute; ItemOf: System.Xml.XmlAttribute; ItemOf: System.Xml.XmlAttribute; private System.Collections.ICollection.IsSynchronized: boolean; private System.Collections.ICollection.SyncRoot: any; private System.Collections.ICollection.Count: number; AddNode(node: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} Append(node: System.Xml.XmlAttribute): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} CopyTo(array: System.Xml.XmlAttribute[], index: number): any; //{ throw new Error("Not implemented.");} Detach(attr: System.Xml.XmlAttribute): any; //{ throw new Error("Not implemented.");} FindNodeOffset(node: System.Xml.XmlAttribute): number; //{ throw new Error("Not implemented.");} FindNodeOffsetNS(node: System.Xml.XmlAttribute): number; //{ throw new Error("Not implemented.");} InsertAfter(newNode: System.Xml.XmlAttribute, refNode: System.Xml.XmlAttribute): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} InsertBefore(newNode: System.Xml.XmlAttribute, refNode: System.Xml.XmlAttribute): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} InsertNodeAt(i: number, node: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} InsertParentIntoElementIdAttrMap(attr: System.Xml.XmlAttribute): any; //{ throw new Error("Not implemented.");} InternalAppendAttribute(node: System.Xml.XmlAttribute): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} PrepareParentInElementIdAttrMap(attrPrefix: string, attrLocalName: string): boolean; //{ throw new Error("Not implemented.");} Prepend(node: System.Xml.XmlAttribute): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} Remove(node: System.Xml.XmlAttribute): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} RemoveAll(): any; //{ throw new Error("Not implemented.");} RemoveAt(i: number): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} RemoveDuplicateAttribute(attr: System.Xml.XmlAttribute): number; //{ throw new Error("Not implemented.");} RemoveNodeAt(i: number): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} RemoveParentFromElementIdAttrMap(attr: System.Xml.XmlAttribute): any; //{ throw new Error("Not implemented.");} ResetParentInElementIdAttrMap(oldVal: string, newVal: string): any; //{ throw new Error("Not implemented.");} SetNamedItem(node: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} } export class XmlDeclaration extends System.Xml.XmlLinkedNode { Version: string; Encoding: string; Standalone: string; Value: string; InnerText: string; Name: string; LocalName: string; NodeType: System.Xml.XmlNodeType; private version: string; private encoding: string; private standalone: string; CloneNode(deep: boolean): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} IsValidXmlVersion(ver: string): boolean; //{ throw new Error("Not implemented.");} WriteContentTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} WriteTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} } export class XmlDocument extends System.Xml.XmlNode { DtdSchemaInfo: System.Xml.Schema.SchemaInfo; NodeType: System.Xml.XmlNodeType; ParentNode: System.Xml.XmlNode; DocumentType: System.Xml.XmlDocumentType; Declaration: System.Xml.XmlDeclaration; Implementation: System.Xml.XmlImplementation; Name: string; LocalName: string; DocumentElement: System.Xml.XmlElement; IsContainer: boolean; LastNode: System.Xml.XmlLinkedNode; OwnerDocument: System.Xml.XmlDocument; Schemas: System.Xml.Schema.XmlSchemaSet; CanReportValidity: boolean; HasSetResolver: boolean; XmlResolver: System.Xml.XmlResolver; NameTable: System.Xml.XmlNameTable; PreserveWhitespace: boolean; IsReadOnly: boolean; Entities: System.Xml.XmlNamedNodeMap; IsLoading: boolean; ActualLoadingStatus: boolean; TextEncoding: System.Text.Encoding; InnerText: string; InnerXml: string; Version: string; Encoding: string; Standalone: string; SchemaInfo: System.Xml.Schema.IXmlSchemaInfo; BaseURI: string; XPNodeType: System.Xml.XPath.XPathNodeType; HasEntityReferences: boolean; NamespaceXml: System.Xml.XmlAttribute; private implementation: System.Xml.XmlImplementation; private domNameTable: any; private lastChild: System.Xml.XmlLinkedNode; private entities: System.Xml.XmlNamedNodeMap; private htElementIdMap: System.Collections.Hashtable; private htElementIDAttrDecl: System.Collections.Hashtable; private schemaInfo: System.Xml.Schema.SchemaInfo; private schemas: System.Xml.Schema.XmlSchemaSet; private reportValidity: boolean; private actualLoadingStatus: boolean; private onNodeInsertingDelegate: any; private onNodeInsertedDelegate: any; private onNodeRemovingDelegate: any; private onNodeRemovedDelegate: any; private onNodeChangingDelegate: any; private onNodeChangedDelegate: any; fEntRefNodesPresent: boolean; fCDataNodesPresent: boolean; private preserveWhitespace: boolean; private isLoading: boolean; strDocumentName: string; strDocumentFragmentName: string; strCommentName: string; strTextName: string; strCDataSectionName: string; strEntityName: string; strID: string; strXmlns: string; strXml: string; strSpace: string; strLang: string; strEmpty: string; strNonSignificantWhitespaceName: string; strSignificantWhitespaceName: string; strReservedXmlns: string; strReservedXml: string; baseURI: string; private resolver: System.Xml.XmlResolver; bSetResolver: boolean; objLock: any; private namespaceXml: System.Xml.XmlAttribute; static EmptyEnumerator: any; static NotKnownSchemaInfo: System.Xml.Schema.IXmlSchemaInfo; static ValidSchemaInfo: System.Xml.Schema.IXmlSchemaInfo; static InvalidSchemaInfo: System.Xml.Schema.IXmlSchemaInfo; AddAttrXmlName(prefix: string, localName: string, namespaceURI: string, schemaInfo: System.Xml.Schema.IXmlSchemaInfo): System.Xml.XmlName; //{ throw new Error("Not implemented.");} AddDefaultAttributes(elem: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} AddElementWithId(id: string, elem: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} AddIdInfo(eleName: System.Xml.XmlName, attrName: System.Xml.XmlName): boolean; //{ throw new Error("Not implemented.");} AddXmlName(prefix: string, localName: string, namespaceURI: string, schemaInfo: System.Xml.Schema.IXmlSchemaInfo): System.Xml.XmlName; //{ throw new Error("Not implemented.");} AfterEvent(args: any): any; //{ throw new Error("Not implemented.");} AppendChildForLoad(newChild: System.Xml.XmlNode, doc: System.Xml.XmlDocument): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} BeforeEvent(args: any): any; //{ throw new Error("Not implemented.");} CanInsertAfter(newChild: System.Xml.XmlNode, refChild: System.Xml.XmlNode): boolean; //{ throw new Error("Not implemented.");} CanInsertBefore(newChild: System.Xml.XmlNode, refChild: System.Xml.XmlNode): boolean; //{ throw new Error("Not implemented.");} CheckName(name: string): any; //{ throw new Error("Not implemented.");} CloneNode(deep: boolean): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} ConvertToNodeType(nodeTypeString: string): System.Xml.XmlNodeType; //{ throw new Error("Not implemented.");} CreateAttribute(name: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} CreateAttribute(prefix: string, localName: string, namespaceURI: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} CreateAttribute(qualifiedName: string, namespaceURI: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} CreateCDataSection(data: string): any; //{ throw new Error("Not implemented.");} CreateComment(data: string): any; //{ throw new Error("Not implemented.");} CreateDefaultAttribute(prefix: string, localName: string, namespaceURI: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} CreateDocumentFragment(): any; //{ throw new Error("Not implemented.");} CreateDocumentType(name: string, publicId: string, systemId: string, internalSubset: string): System.Xml.XmlDocumentType; //{ throw new Error("Not implemented.");} CreateElement(prefix: string, localName: string, namespaceURI: string): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} CreateElement(qualifiedName: string, namespaceURI: string): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} CreateElement(name: string): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} CreateEntityReference(name: string): any; //{ throw new Error("Not implemented.");} CreateNavigator(node: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} CreateNavigator(): any; //{ throw new Error("Not implemented.");} CreateNode(type: System.Xml.XmlNodeType, prefix: string, name: string, namespaceURI: string): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} CreateNode(nodeTypeString: string, name: string, namespaceURI: string): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} CreateNode(type: System.Xml.XmlNodeType, name: string, namespaceURI: string): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} CreateProcessingInstruction(target: string, data: string): any; //{ throw new Error("Not implemented.");} CreateSignificantWhitespace(text: string): any; //{ throw new Error("Not implemented.");} CreateTextNode(text: string): any; //{ throw new Error("Not implemented.");} CreateWhitespace(text: string): any; //{ throw new Error("Not implemented.");} CreateXmlDeclaration(version: string, encoding: string, standalone: string): System.Xml.XmlDeclaration; //{ throw new Error("Not implemented.");} GetDefaultAttribute(elem: System.Xml.XmlElement, attrPrefix: string, attrLocalname: string, attrNamespaceURI: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} GetElement(elementList: System.Collections.ArrayList, elem: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} GetElementById(elementId: string): System.Xml.XmlElement; //{ throw new Error("Not implemented.");} GetElementsByTagName(localName: string, namespaceURI: string): System.Xml.XmlNodeList; //{ throw new Error("Not implemented.");} GetElementsByTagName(name: string): System.Xml.XmlNodeList; //{ throw new Error("Not implemented.");} GetEntityNode(name: string): any; //{ throw new Error("Not implemented.");} GetEventArgs(node: System.Xml.XmlNode, oldParent: System.Xml.XmlNode, newParent: System.Xml.XmlNode, oldValue: string, newValue: string, action: System.Xml.XmlNodeChangedAction): any; //{ throw new Error("Not implemented.");} GetIDInfoByElement(eleName: System.Xml.XmlName): System.Xml.XmlName; //{ throw new Error("Not implemented.");} GetIDInfoByElement_(eleName: System.Xml.XmlName): System.Xml.XmlName; //{ throw new Error("Not implemented.");} GetInsertEventArgsForLoad(node: System.Xml.XmlNode, newParent: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} GetResolver(): System.Xml.XmlResolver; //{ throw new Error("Not implemented.");} GetSchemaElementDecl(elem: System.Xml.XmlElement): System.Xml.Schema.SchemaElementDecl; //{ throw new Error("Not implemented.");} GetXmlName(prefix: string, localName: string, namespaceURI: string, schemaInfo: System.Xml.Schema.IXmlSchemaInfo): System.Xml.XmlName; //{ throw new Error("Not implemented.");} HasNodeTypeInNextSiblings(nt: System.Xml.XmlNodeType, refNode: System.Xml.XmlNode): boolean; //{ throw new Error("Not implemented.");} HasNodeTypeInPrevSiblings(nt: System.Xml.XmlNodeType, refNode: System.Xml.XmlNode): boolean; //{ throw new Error("Not implemented.");} ImportAttributes(fromElem: System.Xml.XmlNode, toElem: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} ImportChildren(fromNode: System.Xml.XmlNode, toNode: System.Xml.XmlNode, deep: boolean): any; //{ throw new Error("Not implemented.");} ImportNode(node: System.Xml.XmlNode, deep: boolean): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} ImportNodeInternal(node: System.Xml.XmlNode, deep: boolean): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} IsTextNode(nt: System.Xml.XmlNodeType): boolean; //{ throw new Error("Not implemented.");} IsValidChildType(type: System.Xml.XmlNodeType): boolean; //{ throw new Error("Not implemented.");} Load(filename: string): any; //{ throw new Error("Not implemented.");} Load(txtReader: any): any; //{ throw new Error("Not implemented.");} Load(inStream: System.IO.Stream): any; //{ throw new Error("Not implemented.");} Load(reader: any): any; //{ throw new Error("Not implemented.");} LoadXml(xml: string): any; //{ throw new Error("Not implemented.");} NormalizeText(n: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} PrepareDefaultAttribute(attdef: System.Xml.Schema.SchemaAttDef, attrPrefix: string, attrLocalname: string, attrNamespaceURI: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} ReadNode(reader: any): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} RemoveElementWithId(id: string, elem: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} Save(writer: System.IO.TextWriter): any; //{ throw new Error("Not implemented.");} Save(filename: string): any; //{ throw new Error("Not implemented.");} Save(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} Save(outStream: System.IO.Stream): any; //{ throw new Error("Not implemented.");} SetBaseURI(inBaseURI: string): any; //{ throw new Error("Not implemented.");} SetDefaultNamespace(prefix: string, localName: string, namespaceURI: any): any; //{ throw new Error("Not implemented.");} SetupReader(tr: any): any; //{ throw new Error("Not implemented.");} Validate(validationEventHandler: any): any; //{ throw new Error("Not implemented.");} Validate(validationEventHandler: any, nodeToValidate: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} WriteContentTo(xw: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} WriteTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} } export class XmlDocumentType extends System.Xml.XmlLinkedNode { Name: string; LocalName: string; NodeType: System.Xml.XmlNodeType; IsReadOnly: boolean; Entities: System.Xml.XmlNamedNodeMap; Notations: System.Xml.XmlNamedNodeMap; PublicId: string; SystemId: string; InternalSubset: string; ParseWithNamespaces: boolean; DtdSchemaInfo: System.Xml.Schema.SchemaInfo; private name: string; private publicId: string; private systemId: string; private internalSubset: string; private namespaces: boolean; private entities: System.Xml.XmlNamedNodeMap; private notations: System.Xml.XmlNamedNodeMap; private schemaInfo: System.Xml.Schema.SchemaInfo; CloneNode(deep: boolean): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} WriteContentTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} WriteTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} } export class XmlElement extends System.Xml.XmlLinkedNode { XmlName: System.Xml.XmlName; Name: string; LocalName: string; NamespaceURI: string; Prefix: string; NodeType: System.Xml.XmlNodeType; ParentNode: System.Xml.XmlNode; OwnerDocument: System.Xml.XmlDocument; IsContainer: boolean; IsEmpty: boolean; LastNode: System.Xml.XmlLinkedNode; Attributes: System.Xml.XmlAttributeCollection; HasAttributes: boolean; SchemaInfo: System.Xml.Schema.IXmlSchemaInfo; InnerXml: string; InnerText: string; NextSibling: System.Xml.XmlNode; XPNodeType: System.Xml.XPath.XPathNodeType; XPLocalName: string; private name: System.Xml.XmlName; private attributes: System.Xml.XmlAttributeCollection; private lastChild: System.Xml.XmlLinkedNode; AppendChildForLoad(newChild: System.Xml.XmlNode, doc: System.Xml.XmlDocument): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} CloneNode(deep: boolean): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} GetAttribute(name: string): string; //{ throw new Error("Not implemented.");} GetAttribute(localName: string, namespaceURI: string): string; //{ throw new Error("Not implemented.");} GetAttributeNode(name: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} GetAttributeNode(localName: string, namespaceURI: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} GetElementsByTagName(name: string): System.Xml.XmlNodeList; //{ throw new Error("Not implemented.");} GetElementsByTagName(localName: string, namespaceURI: string): System.Xml.XmlNodeList; //{ throw new Error("Not implemented.");} GetXPAttribute(localName: string, ns: string): string; //{ throw new Error("Not implemented.");} HasAttribute(localName: string, namespaceURI: string): boolean; //{ throw new Error("Not implemented.");} HasAttribute(name: string): boolean; //{ throw new Error("Not implemented.");} IsValidChildType(type: System.Xml.XmlNodeType): boolean; //{ throw new Error("Not implemented.");} RemoveAll(): any; //{ throw new Error("Not implemented.");} RemoveAllAttributes(): any; //{ throw new Error("Not implemented.");} RemoveAllChildren(): any; //{ throw new Error("Not implemented.");} RemoveAttribute(localName: string, namespaceURI: string): any; //{ throw new Error("Not implemented.");} RemoveAttribute(name: string): any; //{ throw new Error("Not implemented.");} RemoveAttributeAt(i: number): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} RemoveAttributeNode(oldAttr: System.Xml.XmlAttribute): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} RemoveAttributeNode(localName: string, namespaceURI: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} SetAttribute(localName: string, namespaceURI: string, value: string): string; //{ throw new Error("Not implemented.");} SetAttribute(name: string, value: string): any; //{ throw new Error("Not implemented.");} SetAttributeNode(localName: string, namespaceURI: string): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} SetAttributeNode(newAttr: System.Xml.XmlAttribute): System.Xml.XmlAttribute; //{ throw new Error("Not implemented.");} SetParent(node: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} WriteContentTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} WriteElementTo(writer: System.Xml.XmlWriter, e: System.Xml.XmlElement): any; //{ throw new Error("Not implemented.");} WriteStartElement(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} WriteTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} } export class XmlException extends System.SystemException { LineNumber: number; LinePosition: number; SourceUri: string; Message: string; ResString: string; private res: string; private args: System.String[]; private lineNumber: number; private linePosition: number; private sourceUri: string; private message: string; BuildCharExceptionArgs(data: string, invCharIndex: number): System.String[]; //{ throw new Error("Not implemented.");} BuildCharExceptionArgs(data: any, invCharIndex: number): System.String[]; //{ throw new Error("Not implemented.");} BuildCharExceptionArgs(data: any, length: number, invCharIndex: number): System.String[]; //{ throw new Error("Not implemented.");} BuildCharExceptionArgs(invChar: string, nextChar: string): System.String[]; //{ throw new Error("Not implemented.");} CreateMessage(res: string, args: System.String[], lineNumber: number, linePosition: number): string; //{ throw new Error("Not implemented.");} FormatUserMessage(message: string, lineNumber: number, linePosition: number): string; //{ throw new Error("Not implemented.");} GetObjectData(info: any, context: any): any; //{ throw new Error("Not implemented.");} IsCatchableException(e: System.Exception): boolean; //{ throw new Error("Not implemented.");} } export class XmlImplementation { NameTable: System.Xml.XmlNameTable; private nameTable: System.Xml.XmlNameTable; CreateDocument(): System.Xml.XmlDocument; //{ throw new Error("Not implemented.");} HasFeature(strFeature: string, strVersion: string): boolean; //{ throw new Error("Not implemented.");} } export class XmlLinkedNode extends System.Xml.XmlNode { PreviousSibling: System.Xml.XmlNode; NextSibling: System.Xml.XmlNode; next: System.Xml.XmlLinkedNode; } export class XmlName { LocalName: string; NamespaceURI: string; Prefix: string; HashCode: number; OwnerDocument: System.Xml.XmlDocument; Name: string; Validity: System.Xml.Schema.XmlSchemaValidity; IsDefault: boolean; IsNil: boolean; MemberType: System.Xml.Schema.XmlSchemaSimpleType; SchemaType: System.Xml.Schema.XmlSchemaType; SchemaElement: System.Xml.Schema.XmlSchemaElement; SchemaAttribute: System.Xml.Schema.XmlSchemaAttribute; private prefix: string; private localName: string; private ns: string; private name: string; private hashCode: number; ownerDoc: System.Xml.XmlDocument; next: System.Xml.XmlName; Create(prefix: string, localName: string, ns: string, hashCode: number, ownerDoc: System.Xml.XmlDocument, next: System.Xml.XmlName, schemaInfo: System.Xml.Schema.IXmlSchemaInfo): System.Xml.XmlName; //{ throw new Error("Not implemented.");} Equals(schemaInfo: System.Xml.Schema.IXmlSchemaInfo): boolean; //{ throw new Error("Not implemented.");} GetHashCode(name: string): number; //{ throw new Error("Not implemented.");} } export class XmlNamedNodeMap { Count: number; parent: System.Xml.XmlNode; nodes: any; AddNode(node: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} AddNodeForLoad(node: System.Xml.XmlNode, doc: System.Xml.XmlDocument): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} FindNodeOffset(name: string): number; //{ throw new Error("Not implemented.");} FindNodeOffset(localName: string, namespaceURI: string): number; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetNamedItem(name: string): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} GetNamedItem(localName: string, namespaceURI: string): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} InsertNodeAt(i: number, node: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} Item(index: number): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} RemoveNamedItem(name: string): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} RemoveNamedItem(localName: string, namespaceURI: string): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} RemoveNodeAt(i: number): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} ReplaceNodeAt(i: number, node: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} SetNamedItem(node: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} } export class XmlNamespaceManager { static EmptyResolver: System.Xml.IXmlNamespaceResolver; NameTable: System.Xml.XmlNameTable; DefaultNamespace: string; private nsdecls: any; private lastDecl: number; private nameTable: System.Xml.XmlNameTable; private scopeId: number; private hashTable: System.Collections.Generic.Dictionary<TKey, TValue>; private useHashtable: boolean; private xml: string; private xmlNs: string; private static s_EmptyResolver: System.Xml.IXmlNamespaceResolver; AddNamespace(prefix: string, uri: string): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetNamespaceDeclaration(idx: number, prefix: any, uri: any): boolean; //{ throw new Error("Not implemented.");} GetNamespacesInScope(scope: System.Xml.XmlNamespaceScope): System.Collections.Generic.IDictionary<string, string>; //{ throw new Error("Not implemented.");} HasNamespace(prefix: string): boolean; //{ throw new Error("Not implemented.");} LookupNamespace(prefix: string): string; //{ throw new Error("Not implemented.");} LookupNamespaceDecl(prefix: string): number; //{ throw new Error("Not implemented.");} LookupPrefix(uri: string): string; //{ throw new Error("Not implemented.");} PopScope(): boolean; //{ throw new Error("Not implemented.");} PushScope(): any; //{ throw new Error("Not implemented.");} RemoveNamespace(prefix: string, uri: string): any; //{ throw new Error("Not implemented.");} } export class XmlNameTable { Add(array: any, offset: number, length: number): string; //{ throw new Error("Not implemented.");} Add(array: string): string; //{ throw new Error("Not implemented.");} Get(array: any, offset: number, length: number): string; //{ throw new Error("Not implemented.");} Get(array: string): string; //{ throw new Error("Not implemented.");} } export class XmlNode { Name: string; Value: string; NodeType: System.Xml.XmlNodeType; ParentNode: System.Xml.XmlNode; ChildNodes: System.Xml.XmlNodeList; PreviousSibling: System.Xml.XmlNode; NextSibling: System.Xml.XmlNode; Attributes: System.Xml.XmlAttributeCollection; OwnerDocument: System.Xml.XmlDocument; FirstChild: System.Xml.XmlNode; LastChild: System.Xml.XmlNode; IsContainer: boolean; LastNode: System.Xml.XmlLinkedNode; HasChildNodes: boolean; NamespaceURI: string; Prefix: string; LocalName: string; IsReadOnly: boolean; InnerText: string; OuterXml: string; InnerXml: string; SchemaInfo: System.Xml.Schema.IXmlSchemaInfo; BaseURI: string; Document: System.Xml.XmlDocument; Item: System.Xml.XmlElement; Item: System.Xml.XmlElement; XmlSpace: System.Xml.XmlSpace; XmlLang: string; XPNodeType: System.Xml.XPath.XPathNodeType; XPLocalName: string; IsText: boolean; PreviousText: System.Xml.XmlNode; private debuggerDisplayProxy: any; parentNode: System.Xml.XmlNode; AfterEvent(args: any): any; //{ throw new Error("Not implemented.");} AncestorNode(node: System.Xml.XmlNode): boolean; //{ throw new Error("Not implemented.");} AppendChild(newChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} AppendChildForLoad(newChild: System.Xml.XmlNode, doc: System.Xml.XmlDocument): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} AppendChildText(builder: any): any; //{ throw new Error("Not implemented.");} BeforeEvent(args: any): any; //{ throw new Error("Not implemented.");} CanInsertAfter(newChild: System.Xml.XmlNode, refChild: System.Xml.XmlNode): boolean; //{ throw new Error("Not implemented.");} CanInsertBefore(newChild: System.Xml.XmlNode, refChild: System.Xml.XmlNode): boolean; //{ throw new Error("Not implemented.");} Clone(): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} CloneNode(deep: boolean): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} CopyChildren(doc: System.Xml.XmlDocument, container: System.Xml.XmlNode, deep: boolean): any; //{ throw new Error("Not implemented.");} CreateNavigator(): any; //{ throw new Error("Not implemented.");} FindChild(type: System.Xml.XmlNodeType): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} GetEventArgs(node: System.Xml.XmlNode, oldParent: System.Xml.XmlNode, newParent: System.Xml.XmlNode, oldValue: string, newValue: string, action: System.Xml.XmlNodeChangedAction): any; //{ throw new Error("Not implemented.");} GetNamespaceOfPrefix(prefix: string): string; //{ throw new Error("Not implemented.");} GetNamespaceOfPrefixStrict(prefix: string): string; //{ throw new Error("Not implemented.");} GetPrefixOfNamespace(namespaceURI: string): string; //{ throw new Error("Not implemented.");} GetPrefixOfNamespaceStrict(namespaceURI: string): string; //{ throw new Error("Not implemented.");} GetXPAttribute(localName: string, namespaceURI: string): string; //{ throw new Error("Not implemented.");} HasReadOnlyParent(n: System.Xml.XmlNode): boolean; //{ throw new Error("Not implemented.");} InsertAfter(newChild: System.Xml.XmlNode, refChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} InsertBefore(newChild: System.Xml.XmlNode, refChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} IsConnected(): boolean; //{ throw new Error("Not implemented.");} IsValidChildType(type: System.Xml.XmlNodeType): boolean; //{ throw new Error("Not implemented.");} NestTextNodes(prevNode: System.Xml.XmlNode, nextNode: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} Normalize(): any; //{ throw new Error("Not implemented.");} NormalizeWinner(firstNode: System.Xml.XmlNode, secondNode: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} PrependChild(newChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} RemoveAll(): any; //{ throw new Error("Not implemented.");} RemoveChild(oldChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} ReplaceChild(newChild: System.Xml.XmlNode, oldChild: System.Xml.XmlNode): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} SelectNodes(xpath: string): System.Xml.XmlNodeList; //{ throw new Error("Not implemented.");} SelectNodes(xpath: string, nsmgr: System.Xml.XmlNamespaceManager): System.Xml.XmlNodeList; //{ throw new Error("Not implemented.");} SelectSingleNode(xpath: string, nsmgr: System.Xml.XmlNamespaceManager): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} SelectSingleNode(xpath: string): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} SetParent(node: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} SetParentForLoad(node: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} SplitName(name: string, prefix: any, localName: any): any; //{ throw new Error("Not implemented.");} Supports(feature: string, version: string): boolean; //{ throw new Error("Not implemented.");} UnnestTextNodes(prevNode: System.Xml.XmlNode, nextNode: System.Xml.XmlNode): any; //{ throw new Error("Not implemented.");} WriteContentTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} WriteTo(w: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} } export class XmlNodeList { Count: number; ItemOf: System.Xml.XmlNode; GetEnumerator(): any; //{ throw new Error("Not implemented.");} Item(index: number): System.Xml.XmlNode; //{ throw new Error("Not implemented.");} PrivateDisposeNodeList(): any; //{ throw new Error("Not implemented.");} } export class XmlQualifiedName { Namespace: string; Name: string; IsEmpty: boolean; private name: string; private ns: string; private hash: number; private static hashCodeDelegate: any; static Empty: System.Xml.XmlQualifiedName; Atomize(nameTable: System.Xml.XmlNameTable): any; //{ throw new Error("Not implemented.");} Clone(): System.Xml.XmlQualifiedName; //{ throw new Error("Not implemented.");} Compare(a: System.Xml.XmlQualifiedName, b: System.Xml.XmlQualifiedName): number; //{ throw new Error("Not implemented.");} Equals(other: any): boolean; //{ throw new Error("Not implemented.");} GetHashCode(): number; //{ throw new Error("Not implemented.");} GetHashCodeDelegate(): any; //{ throw new Error("Not implemented.");} GetHashCodeOfString(s: string, length: number, additionalEntropy: number): number; //{ throw new Error("Not implemented.");} Init(name: string, ns: string): any; //{ throw new Error("Not implemented.");} IsRandomizedHashingDisabled(): boolean; //{ throw new Error("Not implemented.");} Parse(s: string, nsmgr: System.Xml.IXmlNamespaceResolver, prefix: any): System.Xml.XmlQualifiedName; //{ throw new Error("Not implemented.");} ReadBoolFromXmlRegistrySettings(hive: any, regValueName: string, value: any): boolean; //{ throw new Error("Not implemented.");} SetNamespace(ns: string): any; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} ToString(name: string, ns: string): string; //{ throw new Error("Not implemented.");} Verify(): any; //{ throw new Error("Not implemented.");} } export class XmlReaderSettings { Async: boolean; NameTable: System.Xml.XmlNameTable; IsXmlResolverSet: boolean; XmlResolver: System.Xml.XmlResolver; LineNumberOffset: number; LinePositionOffset: number; ConformanceLevel: System.Xml.ConformanceLevel; CheckCharacters: boolean; MaxCharactersInDocument: number; MaxCharactersFromEntities: number; IgnoreWhitespace: boolean; IgnoreProcessingInstructions: boolean; IgnoreComments: boolean; ProhibitDtd: boolean; DtdProcessing: System.Xml.DtdProcessing; CloseInput: boolean; ValidationType: System.Xml.ValidationType; ValidationFlags: System.Xml.Schema.XmlSchemaValidationFlags; Schemas: System.Xml.Schema.XmlSchemaSet; ReadOnly: boolean; private useAsync: boolean; private nameTable: System.Xml.XmlNameTable; private xmlResolver: System.Xml.XmlResolver; private lineNumberOffset: number; private linePositionOffset: number; private conformanceLevel: System.Xml.ConformanceLevel; private checkCharacters: boolean; private maxCharactersInDocument: number; private maxCharactersFromEntities: number; private ignoreWhitespace: boolean; private ignorePIs: boolean; private ignoreComments: boolean; private dtdProcessing: System.Xml.DtdProcessing; private validationType: System.Xml.ValidationType; private validationFlags: System.Xml.Schema.XmlSchemaValidationFlags; private schemas: System.Xml.Schema.XmlSchemaSet; private valEventHandler: any; private closeInput: boolean; private isReadOnly: boolean; private static s_enableLegacyXmlSettings: boolean; AddConformanceWrapper(baseReader: any): any; //{ throw new Error("Not implemented.");} AddValidation(reader: any): any; //{ throw new Error("Not implemented.");} AddValidationAndConformanceWrapper(reader: any): any; //{ throw new Error("Not implemented.");} CheckReadOnly(propertyName: string): any; //{ throw new Error("Not implemented.");} Clone(): System.Xml.XmlReaderSettings; //{ throw new Error("Not implemented.");} CreateDefaultResolver(): System.Xml.XmlResolver; //{ throw new Error("Not implemented.");} CreateDtdValidatingReader(baseReader: any): any; //{ throw new Error("Not implemented.");} CreateReader(inputUri: string, inputContext: any): any; //{ throw new Error("Not implemented.");} CreateReader(input: System.IO.Stream, baseUri: System.Uri, baseUriString: string, inputContext: any): any; //{ throw new Error("Not implemented.");} CreateReader(input: any, baseUriString: string, inputContext: any): any; //{ throw new Error("Not implemented.");} CreateReader(reader: any): any; //{ throw new Error("Not implemented.");} EnableLegacyXmlSettings(): boolean; //{ throw new Error("Not implemented.");} GetEventHandler(): any; //{ throw new Error("Not implemented.");} GetXmlResolver(): System.Xml.XmlResolver; //{ throw new Error("Not implemented.");} GetXmlResolver_CheckConfig(): System.Xml.XmlResolver; //{ throw new Error("Not implemented.");} Initialize(resolver: System.Xml.XmlResolver): any; //{ throw new Error("Not implemented.");} Initialize(): any; //{ throw new Error("Not implemented.");} ReadSettingsFromRegistry(hive: any, value: any): boolean; //{ throw new Error("Not implemented.");} Reset(): any; //{ throw new Error("Not implemented.");} } export class XmlResolver { Credentials: System.Net.ICredentials; GetEntity(absoluteUri: System.Uri, role: string, ofObjectToReturn: System.Type): any; //{ throw new Error("Not implemented.");} GetEntityAsync(absoluteUri: System.Uri, role: string, ofObjectToReturn: System.Type): any; //{ throw new Error("Not implemented.");} ResolveUri(baseUri: System.Uri, relativeUri: string): System.Uri; //{ throw new Error("Not implemented.");} SupportsType(absoluteUri: System.Uri, type: System.Type): boolean; //{ throw new Error("Not implemented.");} } } declare module System.Xml.Schema { export class ContentValidator { ContentType: System.Xml.Schema.XmlSchemaContentType; PreserveWhitespace: boolean; IsEmptiable: boolean; IsOpen: boolean; private contentType: System.Xml.Schema.XmlSchemaContentType; private isOpen: boolean; private isEmptiable: boolean; static Empty: System.Xml.Schema.ContentValidator; static TextOnly: System.Xml.Schema.ContentValidator; static Mixed: System.Xml.Schema.ContentValidator; static Any: System.Xml.Schema.ContentValidator; AddParticleToExpected(p: System.Xml.Schema.XmlSchemaParticle, schemaSet: System.Xml.Schema.XmlSchemaSet, particles: System.Collections.ArrayList): any; //{ throw new Error("Not implemented.");} AddParticleToExpected(p: System.Xml.Schema.XmlSchemaParticle, schemaSet: System.Xml.Schema.XmlSchemaSet, particles: System.Collections.ArrayList, global: boolean): any; //{ throw new Error("Not implemented.");} CompleteValidation(context: any): boolean; //{ throw new Error("Not implemented.");} ExpectedElements(context: any, isRequiredOnly: boolean): System.Collections.ArrayList; //{ throw new Error("Not implemented.");} ExpectedParticles(context: any, isRequiredOnly: boolean, schemaSet: System.Xml.Schema.XmlSchemaSet): System.Collections.ArrayList; //{ throw new Error("Not implemented.");} InitValidation(context: any): any; //{ throw new Error("Not implemented.");} ValidateElement(name: System.Xml.XmlQualifiedName, context: any, errorCode: any): any; //{ throw new Error("Not implemented.");} } export class FacetsChecker { CheckLexicalFacets(parseString: any, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckPatternFacets(restriction: System.Xml.Schema.RestrictionFacets, value: string): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: System.Xml.XmlQualifiedName, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: System.TimeSpan, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: System.Byte[], datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: string, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: number, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: number, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: number, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: number, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: number, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: number, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: number, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: any, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckValueFacets(value: Date, datatype: System.Xml.Schema.XmlSchemaDatatype): System.Exception; //{ throw new Error("Not implemented.");} CheckWhitespaceFacets(s: any, datatype: System.Xml.Schema.XmlSchemaDatatype): any; //{ throw new Error("Not implemented.");} ConstructRestriction(datatype: any, facets: System.Xml.Schema.XmlSchemaObjectCollection, nameTable: System.Xml.XmlNameTable): System.Xml.Schema.RestrictionFacets; //{ throw new Error("Not implemented.");} MatchEnumeration(value: any, enumeration: System.Collections.ArrayList, datatype: System.Xml.Schema.XmlSchemaDatatype): boolean; //{ throw new Error("Not implemented.");} Power(x: number, y: number): number; //{ throw new Error("Not implemented.");} } interface IXmlSchemaInfo { Validity: System.Xml.Schema.XmlSchemaValidity; IsDefault: boolean; IsNil: boolean; MemberType: System.Xml.Schema.XmlSchemaSimpleType; SchemaType: System.Xml.Schema.XmlSchemaType; SchemaElement: System.Xml.Schema.XmlSchemaElement; SchemaAttribute: System.Xml.Schema.XmlSchemaAttribute; } export class NamespaceList { Type: System.Xml.Schema.NamespaceList.ListType; Excluded: string; Enumerate: System.Collections.ICollection; private type: System.Xml.Schema.NamespaceList.ListType; private set: System.Collections.Hashtable; private targetNamespace: string; Allows(ns: string): boolean; //{ throw new Error("Not implemented.");} Allows(qname: System.Xml.XmlQualifiedName): boolean; //{ throw new Error("Not implemented.");} Clone(): System.Xml.Schema.NamespaceList; //{ throw new Error("Not implemented.");} CompareSetToOther(other: System.Xml.Schema.NamespaceList): System.Xml.Schema.NamespaceList; //{ throw new Error("Not implemented.");} Intersection(o1: System.Xml.Schema.NamespaceList, o2: System.Xml.Schema.NamespaceList, v1Compat: boolean): System.Xml.Schema.NamespaceList; //{ throw new Error("Not implemented.");} IsEmpty(): boolean; //{ throw new Error("Not implemented.");} IsSubset(sub: System.Xml.Schema.NamespaceList, super: System.Xml.Schema.NamespaceList): boolean; //{ throw new Error("Not implemented.");} RemoveNamespace(tns: string): any; //{ throw new Error("Not implemented.");} ToString(): string; //{ throw new Error("Not implemented.");} Union(o1: System.Xml.Schema.NamespaceList, o2: System.Xml.Schema.NamespaceList, v1Compat: boolean): System.Xml.Schema.NamespaceList; //{ throw new Error("Not implemented.");} } export class RestrictionFacets { Length: number; MinLength: number; MaxLength: number; Patterns: System.Collections.ArrayList; Enumeration: System.Collections.ArrayList; WhiteSpace: System.Xml.Schema.XmlSchemaWhiteSpace; MaxInclusive: any; MaxExclusive: any; MinInclusive: any; MinExclusive: any; TotalDigits: number; FractionDigits: number; Flags: System.Xml.Schema.RestrictionFlags; FixedFlags: System.Xml.Schema.RestrictionFlags; } export class SchemaAttDef extends System.Xml.Schema.SchemaDeclBase { private System.Xml.IDtdAttributeInfo.Prefix: string; private System.Xml.IDtdAttributeInfo.LocalName: string; private System.Xml.IDtdAttributeInfo.LineNumber: number; private System.Xml.IDtdAttributeInfo.LinePosition: number; private System.Xml.IDtdAttributeInfo.IsNonCDataType: boolean; private System.Xml.IDtdAttributeInfo.IsDeclaredInExternal: boolean; private System.Xml.IDtdAttributeInfo.IsXmlAttribute: boolean; private System.Xml.IDtdDefaultAttributeInfo.DefaultValueExpanded: string; private System.Xml.IDtdDefaultAttributeInfo.DefaultValueTyped: any; private System.Xml.IDtdDefaultAttributeInfo.ValueLineNumber: number; private System.Xml.IDtdDefaultAttributeInfo.ValueLinePosition: number; LinePosition: number; LineNumber: number; ValueLinePosition: number; ValueLineNumber: number; DefaultValueExpanded: string; TokenizedType: System.Xml.XmlTokenizedType; Reserved: System.Xml.Schema.SchemaAttDef.Reserve; DefaultValueChecked: boolean; HasEntityRef: boolean; SchemaAttribute: System.Xml.Schema.XmlSchemaAttribute; private defExpanded: string; private lineNum: number; private linePos: number; private valueLineNum: number; private valueLinePos: number; private reserved: System.Xml.Schema.SchemaAttDef.Reserve; private defaultValueChecked: boolean; private hasEntityRef: boolean; private schemaAttribute: System.Xml.Schema.XmlSchemaAttribute; static Empty: System.Xml.Schema.SchemaAttDef; CheckXmlSpace(validationEventHandling: any): any; //{ throw new Error("Not implemented.");} Clone(): System.Xml.Schema.SchemaAttDef; //{ throw new Error("Not implemented.");} } export class SchemaDeclBase { Name: System.Xml.XmlQualifiedName; Prefix: string; IsDeclaredInExternal: boolean; Presence: System.Xml.Schema.SchemaDeclBase.Use; MaxLength: number; MinLength: number; SchemaType: System.Xml.Schema.XmlSchemaType; Datatype: System.Xml.Schema.XmlSchemaDatatype; Values: System.Collections.Generic.List<string>; DefaultValueRaw: string; DefaultValueTyped: any; name: System.Xml.XmlQualifiedName; prefix: string; isDeclaredInExternal: boolean; presence: System.Xml.Schema.SchemaDeclBase.Use; schemaType: System.Xml.Schema.XmlSchemaType; datatype: System.Xml.Schema.XmlSchemaDatatype; defaultValueRaw: string; defaultValueTyped: any; maxLength: number; minLength: number; values: System.Collections.Generic.List<string>; AddValue(value: string): any; //{ throw new Error("Not implemented.");} CheckEnumeration(pVal: any): boolean; //{ throw new Error("Not implemented.");} CheckValue(pVal: any): boolean; //{ throw new Error("Not implemented.");} } export class SchemaElementDecl extends System.Xml.Schema.SchemaDeclBase { private System.Xml.IDtdAttributeListInfo.Prefix: string; private System.Xml.IDtdAttributeListInfo.LocalName: string; private System.Xml.IDtdAttributeListInfo.HasNonCDataAttributes: boolean; IsIdDeclared: boolean; HasNonCDataAttribute: boolean; IsAbstract: boolean; IsNillable: boolean; Block: System.Xml.Schema.XmlSchemaDerivationMethod; IsNotationDeclared: boolean; HasDefaultAttribute: boolean; HasRequiredAttribute: boolean; ContentValidator: System.Xml.Schema.ContentValidator; AnyAttribute: System.Xml.Schema.XmlSchemaAnyAttribute; Constraints: System.Xml.Schema.CompiledIdentityConstraint[]; SchemaElement: System.Xml.Schema.XmlSchemaElement; DefaultAttDefs: System.Collections.Generic.IList<System.Xml.IDtdDefaultAttributeInfo>; AttDefs: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaAttDef>; ProhibitedAttributes: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.XmlQualifiedName>; private attdefs: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaAttDef>; private defaultAttdefs: System.Collections.Generic.List<T>; private isIdDeclared: boolean; private hasNonCDataAttribute: boolean; private isAbstract: boolean; private isNillable: boolean; private hasRequiredAttribute: boolean; private isNotationDeclared: boolean; private prohibitedAttributes: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.XmlQualifiedName>; private contentValidator: System.Xml.Schema.ContentValidator; private anyAttribute: System.Xml.Schema.XmlSchemaAnyAttribute; private block: System.Xml.Schema.XmlSchemaDerivationMethod; private constraints: System.Xml.Schema.CompiledIdentityConstraint[]; private schemaElement: System.Xml.Schema.XmlSchemaElement; static Empty: System.Xml.Schema.SchemaElementDecl; AddAttDef(attdef: System.Xml.Schema.SchemaAttDef): any; //{ throw new Error("Not implemented.");} CheckAttributes(presence: System.Collections.Hashtable, standalone: boolean): any; //{ throw new Error("Not implemented.");} Clone(): System.Xml.Schema.SchemaElementDecl; //{ throw new Error("Not implemented.");} CreateAnyTypeElementDecl(): System.Xml.Schema.SchemaElementDecl; //{ throw new Error("Not implemented.");} GetAttDef(qname: System.Xml.XmlQualifiedName): System.Xml.Schema.SchemaAttDef; //{ throw new Error("Not implemented.");} } export class SchemaEntity { private System.Xml.IDtdEntityInfo.Name: string; private System.Xml.IDtdEntityInfo.IsExternal: boolean; private System.Xml.IDtdEntityInfo.IsDeclaredInExternal: boolean; private System.Xml.IDtdEntityInfo.IsUnparsedEntity: boolean; private System.Xml.IDtdEntityInfo.IsParameterEntity: boolean; private System.Xml.IDtdEntityInfo.BaseUriString: string; private System.Xml.IDtdEntityInfo.DeclaredUriString: string; private System.Xml.IDtdEntityInfo.SystemId: string; private System.Xml.IDtdEntityInfo.PublicId: string; private System.Xml.IDtdEntityInfo.Text: string; private System.Xml.IDtdEntityInfo.LineNumber: number; private System.Xml.IDtdEntityInfo.LinePosition: number; Name: System.Xml.XmlQualifiedName; Url: string; Pubid: string; IsExternal: boolean; DeclaredInExternal: boolean; NData: System.Xml.XmlQualifiedName; Text: string; Line: number; Pos: number; BaseURI: string; ParsingInProgress: boolean; DeclaredURI: string; private qname: System.Xml.XmlQualifiedName; private url: string; private pubid: string; private text: string; private ndata: System.Xml.XmlQualifiedName; private lineNumber: number; private linePosition: number; private isParameter: boolean; private isExternal: boolean; private parsingInProgress: boolean; private isDeclaredInExternal: boolean; private baseURI: string; private declaredURI: string; IsPredefinedEntity(n: string): boolean; //{ throw new Error("Not implemented.");} } export class SchemaInfo { DocTypeName: System.Xml.XmlQualifiedName; InternalDtdSubset: string; ElementDecls: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaElementDecl>; UndeclaredElementDecls: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaElementDecl>; GeneralEntities: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaEntity>; ParameterEntities: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaEntity>; SchemaType: System.Xml.Schema.SchemaType; TargetNamespaces: System.Collections.Generic.Dictionary<string, boolean>; ElementDeclsByType: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaElementDecl>; AttributeDecls: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaAttDef>; Notations: System.Collections.Generic.Dictionary<string, System.Xml.Schema.SchemaNotation>; ErrorCount: number; private System.Xml.IDtdInfo.HasDefaultAttributes: boolean; private System.Xml.IDtdInfo.HasNonCDataAttributes: boolean; private System.Xml.IDtdInfo.Name: System.Xml.XmlQualifiedName; private System.Xml.IDtdInfo.InternalDtdSubset: string; private elementDecls: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaElementDecl>; private undeclaredElementDecls: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaElementDecl>; private generalEntities: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaEntity>; private parameterEntities: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaEntity>; private docTypeName: System.Xml.XmlQualifiedName; private internalDtdSubset: string; private hasNonCDataAttributes: boolean; private hasDefaultAttributes: boolean; private targetNamespaces: System.Collections.Generic.Dictionary<string, boolean>; private attributeDecls: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaAttDef>; private errorCount: number; private schemaType: System.Xml.Schema.SchemaType; private elementDeclsByType: System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Xml.Schema.SchemaElementDecl>; private notations: System.Collections.Generic.Dictionary<string, System.Xml.Schema.SchemaNotation>; Add(sinfo: System.Xml.Schema.SchemaInfo, eventhandler: any): any; //{ throw new Error("Not implemented.");} Contains(ns: string): boolean; //{ throw new Error("Not implemented.");} Finish(): any; //{ throw new Error("Not implemented.");} GetAttribute(qname: System.Xml.XmlQualifiedName): System.Xml.Schema.XmlSchemaAttribute; //{ throw new Error("Not implemented.");} GetAttributeXdr(ed: System.Xml.Schema.SchemaElementDecl, qname: System.Xml.XmlQualifiedName): System.Xml.Schema.SchemaAttDef; //{ throw new Error("Not implemented.");} GetAttributeXsd(ed: System.Xml.Schema.SchemaElementDecl, qname: System.Xml.XmlQualifiedName, partialValidationType: System.Xml.Schema.XmlSchemaObject, attributeMatchState: any): System.Xml.Schema.SchemaAttDef; //{ throw new Error("Not implemented.");} GetAttributeXsd(ed: System.Xml.Schema.SchemaElementDecl, qname: System.Xml.XmlQualifiedName, skip: any): System.Xml.Schema.SchemaAttDef; //{ throw new Error("Not implemented.");} GetElement(qname: System.Xml.XmlQualifiedName): System.Xml.Schema.XmlSchemaElement; //{ throw new Error("Not implemented.");} GetElementDecl(qname: System.Xml.XmlQualifiedName): System.Xml.Schema.SchemaElementDecl; //{ throw new Error("Not implemented.");} GetType(qname: System.Xml.XmlQualifiedName): System.Xml.Schema.XmlSchemaElement; //{ throw new Error("Not implemented.");} GetTypeDecl(qname: System.Xml.XmlQualifiedName): System.Xml.Schema.SchemaElementDecl; //{ throw new Error("Not implemented.");} HasSchema(ns: string): boolean; //{ throw new Error("Not implemented.");} } export class SchemaNotation { Name: System.Xml.XmlQualifiedName; SystemLiteral: string; Pubid: string; private name: System.Xml.XmlQualifiedName; private systemLiteral: string; private pubid: string; } export class XmlSchema extends System.Xml.Schema.XmlSchemaObject { AttributeFormDefault: System.Xml.Schema.XmlSchemaForm; BlockDefault: System.Xml.Schema.XmlSchemaDerivationMethod; FinalDefault: System.Xml.Schema.XmlSchemaDerivationMethod; ElementFormDefault: System.Xml.Schema.XmlSchemaForm; TargetNamespace: string; Version: string; Includes: System.Xml.Schema.XmlSchemaObjectCollection; Items: System.Xml.Schema.XmlSchemaObjectCollection; IsCompiled: boolean; IsCompiledBySet: boolean; IsPreprocessed: boolean; IsRedefined: boolean; Attributes: System.Xml.Schema.XmlSchemaObjectTable; AttributeGroups: System.Xml.Schema.XmlSchemaObjectTable; SchemaTypes: System.Xml.Schema.XmlSchemaObjectTable; Elements: System.Xml.Schema.XmlSchemaObjectTable; Id: string; UnhandledAttributes: System.Xml.XmlAttribute[]; Groups: System.Xml.Schema.XmlSchemaObjectTable; Notations: System.Xml.Schema.XmlSchemaObjectTable; IdentityConstraints: System.Xml.Schema.XmlSchemaObjectTable; BaseUri: System.Uri; SchemaId: number; IsChameleon: boolean; Ids: System.Collections.Hashtable; Document: System.Xml.XmlDocument; ErrorCount: number; IdAttribute: string; NameTable: System.Xml.XmlNameTable; ImportedSchemas: System.Collections.ArrayList; ImportedNamespaces: System.Collections.ArrayList; private attributeFormDefault: System.Xml.Schema.XmlSchemaForm; private elementFormDefault: System.Xml.Schema.XmlSchemaForm; private blockDefault: System.Xml.Schema.XmlSchemaDerivationMethod; private finalDefault: System.Xml.Schema.XmlSchemaDerivationMethod; private targetNs: string; private version: string; private includes: System.Xml.Schema.XmlSchemaObjectCollection; private items: System.Xml.Schema.XmlSchemaObjectCollection; private id: string; private moreAttributes: System.Xml.XmlAttribute[]; private isCompiled: boolean; private isCompiledBySet: boolean; private isPreprocessed: boolean; private isRedefined: boolean; private errorCount: number; private attributes: System.Xml.Schema.XmlSchemaObjectTable; private attributeGroups: System.Xml.Schema.XmlSchemaObjectTable; private elements: System.Xml.Schema.XmlSchemaObjectTable; private types: System.Xml.Schema.XmlSchemaObjectTable; private groups: System.Xml.Schema.XmlSchemaObjectTable; private notations: System.Xml.Schema.XmlSchemaObjectTable; private identityConstraints: System.Xml.Schema.XmlSchemaObjectTable; private importedSchemas: System.Collections.ArrayList; private importedNamespaces: System.Collections.ArrayList; private schemaId: number; private baseUri: System.Uri; private isChameleon: boolean; private ids: System.Collections.Hashtable; private document: System.Xml.XmlDocument; private nameTable: System.Xml.XmlNameTable; private static globalIdCounter: number; AddAnnotation(annotation: System.Xml.Schema.XmlSchemaAnnotation): any; //{ throw new Error("Not implemented.");} Clone(): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} Compile(validationEventHandler: any): any; //{ throw new Error("Not implemented.");} Compile(validationEventHandler: any, resolver: System.Xml.XmlResolver): any; //{ throw new Error("Not implemented.");} CompileSchema(xsc: any, resolver: System.Xml.XmlResolver, schemaInfo: System.Xml.Schema.SchemaInfo, ns: string, validationEventHandler: any, nameTable: System.Xml.XmlNameTable, CompileContentModel: boolean): boolean; //{ throw new Error("Not implemented.");} CompileSchemaInSet(nameTable: System.Xml.XmlNameTable, eventHandler: any, compilationSettings: System.Xml.Schema.XmlSchemaCompilationSettings): any; //{ throw new Error("Not implemented.");} DeepClone(): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} GetExternalSchemasList(extList: System.Collections.IList, schema: System.Xml.Schema.XmlSchema): any; //{ throw new Error("Not implemented.");} Read(reader: any, validationEventHandler: any): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} Read(stream: System.IO.Stream, validationEventHandler: any): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} Read(reader: any, validationEventHandler: any): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} SetIsCompiled(isCompiled: boolean): any; //{ throw new Error("Not implemented.");} SetUnhandledAttributes(moreAttributes: System.Xml.XmlAttribute[]): any; //{ throw new Error("Not implemented.");} Write(writer: System.Xml.XmlWriter, namespaceManager: System.Xml.XmlNamespaceManager): any; //{ throw new Error("Not implemented.");} Write(writer: System.IO.TextWriter, namespaceManager: System.Xml.XmlNamespaceManager): any; //{ throw new Error("Not implemented.");} Write(writer: System.IO.TextWriter): any; //{ throw new Error("Not implemented.");} Write(stream: System.IO.Stream, namespaceManager: System.Xml.XmlNamespaceManager): any; //{ throw new Error("Not implemented.");} Write(stream: System.IO.Stream): any; //{ throw new Error("Not implemented.");} Write(writer: System.Xml.XmlWriter): any; //{ throw new Error("Not implemented.");} } export class XmlSchemaAnnotated extends System.Xml.Schema.XmlSchemaObject { Id: string; Annotation: System.Xml.Schema.XmlSchemaAnnotation; UnhandledAttributes: System.Xml.XmlAttribute[]; IdAttribute: string; private id: string; private annotation: System.Xml.Schema.XmlSchemaAnnotation; private moreAttributes: System.Xml.XmlAttribute[]; AddAnnotation(annotation: System.Xml.Schema.XmlSchemaAnnotation): any; //{ throw new Error("Not implemented.");} SetUnhandledAttributes(moreAttributes: System.Xml.XmlAttribute[]): any; //{ throw new Error("Not implemented.");} } export class XmlSchemaAnnotation extends System.Xml.Schema.XmlSchemaObject { Id: string; Items: System.Xml.Schema.XmlSchemaObjectCollection; UnhandledAttributes: System.Xml.XmlAttribute[]; IdAttribute: string; private id: string; private items: System.Xml.Schema.XmlSchemaObjectCollection; private moreAttributes: System.Xml.XmlAttribute[]; SetUnhandledAttributes(moreAttributes: System.Xml.XmlAttribute[]): any; //{ throw new Error("Not implemented.");} } export class XmlSchemaAnyAttribute extends System.Xml.Schema.XmlSchemaAnnotated { Namespace: string; ProcessContents: System.Xml.Schema.XmlSchemaContentProcessing; NamespaceList: System.Xml.Schema.NamespaceList; ProcessContentsCorrect: System.Xml.Schema.XmlSchemaContentProcessing; private ns: string; private processContents: System.Xml.Schema.XmlSchemaContentProcessing; private namespaceList: System.Xml.Schema.NamespaceList; Allows(qname: System.Xml.XmlQualifiedName): boolean; //{ throw new Error("Not implemented.");} BuildNamespaceList(targetNamespace: string): any; //{ throw new Error("Not implemented.");} BuildNamespaceListV1Compat(targetNamespace: string): any; //{ throw new Error("Not implemented.");} Intersection(o1: System.Xml.Schema.XmlSchemaAnyAttribute, o2: System.Xml.Schema.XmlSchemaAnyAttribute, v1Compat: boolean): System.Xml.Schema.XmlSchemaAnyAttribute; //{ throw new Error("Not implemented.");} IsSubset(sub: System.Xml.Schema.XmlSchemaAnyAttribute, super: System.Xml.Schema.XmlSchemaAnyAttribute): boolean; //{ throw new Error("Not implemented.");} Union(o1: System.Xml.Schema.XmlSchemaAnyAttribute, o2: System.Xml.Schema.XmlSchemaAnyAttribute, v1Compat: boolean): System.Xml.Schema.XmlSchemaAnyAttribute; //{ throw new Error("Not implemented.");} } export class XmlSchemaAttribute extends System.Xml.Schema.XmlSchemaAnnotated { DefaultValue: string; FixedValue: string; Form: System.Xml.Schema.XmlSchemaForm; Name: string; RefName: System.Xml.XmlQualifiedName; SchemaTypeName: System.Xml.XmlQualifiedName; SchemaType: System.Xml.Schema.XmlSchemaSimpleType; Use: System.Xml.Schema.XmlSchemaUse; QualifiedName: System.Xml.XmlQualifiedName; AttributeType: any; AttributeSchemaType: System.Xml.Schema.XmlSchemaSimpleType; Datatype: System.Xml.Schema.XmlSchemaDatatype; AttDef: System.Xml.Schema.SchemaAttDef; HasDefault: boolean; NameAttribute: string; private defaultValue: string; private fixedValue: string; private name: string; private form: System.Xml.Schema.XmlSchemaForm; private use: System.Xml.Schema.XmlSchemaUse; private refName: System.Xml.XmlQualifiedName; private typeName: System.Xml.XmlQualifiedName; private qualifiedName: System.Xml.XmlQualifiedName; private type: System.Xml.Schema.XmlSchemaSimpleType; private attributeType: System.Xml.Schema.XmlSchemaSimpleType; private attDef: System.Xml.Schema.SchemaAttDef; Clone(): System.Xml.Schema.XmlSchemaObject; //{ throw new Error("Not implemented.");} SetAttributeType(value: System.Xml.Schema.XmlSchemaSimpleType): any; //{ throw new Error("Not implemented.");} SetQualifiedName(value: System.Xml.XmlQualifiedName): any; //{ throw new Error("Not implemented.");} Validate(reader: any, resolver: System.Xml.XmlResolver, schemaSet: System.Xml.Schema.XmlSchemaSet, valEventHandler: any): any; //{ throw new Error("Not implemented.");} } export class XmlSchemaCompilationSettings { EnableUpaCheck: boolean; private enableUpaCheck: boolean; } export class XmlSchemaDatatype { ValueType: System.Type; TokenizedType: System.Xml.XmlTokenizedType; Variety: System.Xml.Schema.XmlSchemaDatatypeVariety; TypeCode: System.Xml.Schema.XmlTypeCode; HasLexicalFacets: boolean; HasValueFacets: boolean; ValueConverter: System.Xml.Schema.XmlValueConverter; Restriction: System.Xml.Schema.RestrictionFacets; FacetsChecker: System.Xml.Schema.FacetsChecker; BuiltInWhitespaceFacet: System.Xml.Schema.XmlSchemaWhiteSpace; TypeCodeString: string; ChangeType(value: any, targetType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: any, targetType: System.Type, namespaceResolver: System.Xml.IXmlNamespaceResolver): any; //{ throw new Error("Not implemented.");} Compare(value1: any, value2: any): number; //{ throw new Error("Not implemented.");} ConcatenatedToString(value: any): string; //{ throw new Error("Not implemented.");} DeriveByList(schemaType: System.Xml.Schema.XmlSchemaType): System.Xml.Schema.XmlSchemaDatatype; //{ throw new Error("Not implemented.");} DeriveByRestriction(facets: System.Xml.Schema.XmlSchemaObjectCollection, nameTable: System.Xml.XmlNameTable, schemaType: System.Xml.Schema.XmlSchemaType): System.Xml.Schema.XmlSchemaDatatype; //{ throw new Error("Not implemented.");} DeriveByUnion(types: any, schemaType: System.Xml.Schema.XmlSchemaType): System.Xml.Schema.XmlSchemaDatatype; //{ throw new Error("Not implemented.");} FromXdrName(name: string): System.Xml.Schema.XmlSchemaDatatype; //{ throw new Error("Not implemented.");} FromXmlTokenizedType(token: System.Xml.XmlTokenizedType): System.Xml.Schema.XmlSchemaDatatype; //{ throw new Error("Not implemented.");} FromXmlTokenizedTypeXsd(token: System.Xml.XmlTokenizedType): System.Xml.Schema.XmlSchemaDatatype; //{ throw new Error("Not implemented.");} IsComparable(dtype: System.Xml.Schema.XmlSchemaDatatype): boolean; //{ throw new Error("Not implemented.");} IsDerivedFrom(datatype: System.Xml.Schema.XmlSchemaDatatype): boolean; //{ throw new Error("Not implemented.");} IsEqual(o1: any, o2: any): boolean; //{ throw new Error("Not implemented.");} ParseValue(s: string, nameTable: System.Xml.XmlNameTable, nsmgr: System.Xml.IXmlNamespaceResolver): any; //{ throw new Error("Not implemented.");} ParseValue(s: string, nameTable: System.Xml.XmlNameTable, nsmgr: System.Xml.IXmlNamespaceResolver, createAtomicValue: boolean): any; //{ throw new Error("Not implemented.");} ParseValue(s: string, typDest: System.Type, nameTable: System.Xml.XmlNameTable, nsmgr: System.Xml.IXmlNamespaceResolver): any; //{ throw new Error("Not implemented.");} TryParseValue(value: any, nameTable: System.Xml.XmlNameTable, namespaceResolver: System.Xml.IXmlNamespaceResolver, typedValue: any): System.Exception; //{ throw new Error("Not implemented.");} TryParseValue(s: string, nameTable: System.Xml.XmlNameTable, nsmgr: System.Xml.IXmlNamespaceResolver, typedValue: any): System.Exception; //{ throw new Error("Not implemented.");} TypeCodeToString(typeCode: System.Xml.Schema.XmlTypeCode): string; //{ throw new Error("Not implemented.");} VerifySchemaValid(notations: System.Xml.Schema.XmlSchemaObjectTable, caller: System.Xml.Schema.XmlSchemaObject): any; //{ throw new Error("Not implemented.");} XdrCanonizeUri(uri: string, nameTable: System.Xml.XmlNameTable, schemaNames: any): string; //{ throw new Error("Not implemented.");} } export class XmlSchemaElement extends System.Xml.Schema.XmlSchemaParticle { IsAbstract: boolean; Block: System.Xml.Schema.XmlSchemaDerivationMethod; DefaultValue: string; Final: System.Xml.Schema.XmlSchemaDerivationMethod; FixedValue: string; Form: System.Xml.Schema.XmlSchemaForm; Name: string; IsNillable: boolean; HasNillableAttribute: boolean; HasAbstractAttribute: boolean; RefName: System.Xml.XmlQualifiedName; SubstitutionGroup: System.Xml.XmlQualifiedName; SchemaTypeName: System.Xml.XmlQualifiedName; SchemaType: System.Xml.Schema.XmlSchemaType; Constraints: System.Xml.Schema.XmlSchemaObjectCollection; QualifiedName: System.Xml.XmlQualifiedName; ElementType: any; ElementSchemaType: System.Xml.Schema.XmlSchemaType; BlockResolved: System.Xml.Schema.XmlSchemaDerivationMethod; FinalResolved: System.Xml.Schema.XmlSchemaDerivationMethod; HasDefault: boolean; HasConstraints: boolean; IsLocalTypeDerivationChecked: boolean; ElementDecl: System.Xml.Schema.SchemaElementDecl; NameAttribute: string; NameString: string; private isAbstract: boolean; private hasAbstractAttribute: boolean; private isNillable: boolean; private hasNillableAttribute: boolean; private isLocalTypeDerivationChecked: boolean; private block: System.Xml.Schema.XmlSchemaDerivationMethod; private final: System.Xml.Schema.XmlSchemaDerivationMethod; private form: System.Xml.Schema.XmlSchemaForm; private defaultValue: string; private fixedValue: string; private name: string; private refName: System.Xml.XmlQualifiedName; private substitutionGroup: System.Xml.XmlQualifiedName; private typeName: System.Xml.XmlQualifiedName; private type: System.Xml.Schema.XmlSchemaType; private qualifiedName: System.Xml.XmlQualifiedName; private elementType: System.Xml.Schema.XmlSchemaType; private blockResolved: System.Xml.Schema.XmlSchemaDerivationMethod; private finalResolved: System.Xml.Schema.XmlSchemaDerivationMethod; private constraints: System.Xml.Schema.XmlSchemaObjectCollection; private elementDecl: System.Xml.Schema.SchemaElementDecl; Clone(): System.Xml.Schema.XmlSchemaObject; //{ throw new Error("Not implemented.");} Clone(parentSchema: System.Xml.Schema.XmlSchema): System.Xml.Schema.XmlSchemaObject; //{ throw new Error("Not implemented.");} SetBlockResolved(value: System.Xml.Schema.XmlSchemaDerivationMethod): any; //{ throw new Error("Not implemented.");} SetElementType(value: System.Xml.Schema.XmlSchemaType): any; //{ throw new Error("Not implemented.");} SetFinalResolved(value: System.Xml.Schema.XmlSchemaDerivationMethod): any; //{ throw new Error("Not implemented.");} SetQualifiedName(value: System.Xml.XmlQualifiedName): any; //{ throw new Error("Not implemented.");} Validate(reader: any, resolver: System.Xml.XmlResolver, schemaSet: System.Xml.Schema.XmlSchemaSet, valEventHandler: any): any; //{ throw new Error("Not implemented.");} } export class XmlSchemaObject { LineNumber: number; LinePosition: number; SourceUri: string; Parent: System.Xml.Schema.XmlSchemaObject; Namespaces: System.Xml.Serialization.XmlSerializerNamespaces; IdAttribute: string; NameAttribute: string; IsProcessing: boolean; private lineNum: number; private linePos: number; private sourceUri: string; private namespaces: System.Xml.Serialization.XmlSerializerNamespaces; private parent: System.Xml.Schema.XmlSchemaObject; private isProcessing: boolean; AddAnnotation(annotation: System.Xml.Schema.XmlSchemaAnnotation): any; //{ throw new Error("Not implemented.");} Clone(): System.Xml.Schema.XmlSchemaObject; //{ throw new Error("Not implemented.");} OnAdd(container: System.Xml.Schema.XmlSchemaObjectCollection, item: any): any; //{ throw new Error("Not implemented.");} OnClear(container: System.Xml.Schema.XmlSchemaObjectCollection): any; //{ throw new Error("Not implemented.");} OnRemove(container: System.Xml.Schema.XmlSchemaObjectCollection, item: any): any; //{ throw new Error("Not implemented.");} SetUnhandledAttributes(moreAttributes: System.Xml.XmlAttribute[]): any; //{ throw new Error("Not implemented.");} } export class XmlSchemaObjectCollection extends System.Collections.CollectionBase { Item: System.Xml.Schema.XmlSchemaObject; private parent: System.Xml.Schema.XmlSchemaObject; Add(item: System.Xml.Schema.XmlSchemaObject): number; //{ throw new Error("Not implemented.");} Add(collToAdd: System.Xml.Schema.XmlSchemaObjectCollection): any; //{ throw new Error("Not implemented.");} Clone(): System.Xml.Schema.XmlSchemaObjectCollection; //{ throw new Error("Not implemented.");} Contains(item: System.Xml.Schema.XmlSchemaObject): boolean; //{ throw new Error("Not implemented.");} CopyTo(array: any, index: number): any; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} IndexOf(item: System.Xml.Schema.XmlSchemaObject): number; //{ throw new Error("Not implemented.");} Insert(index: number, item: System.Xml.Schema.XmlSchemaObject): any; //{ throw new Error("Not implemented.");} OnClear(): any; //{ throw new Error("Not implemented.");} OnInsert(index: number, item: any): any; //{ throw new Error("Not implemented.");} OnRemove(index: number, item: any): any; //{ throw new Error("Not implemented.");} OnSet(index: number, oldValue: any, newValue: any): any; //{ throw new Error("Not implemented.");} Remove(item: System.Xml.Schema.XmlSchemaObject): any; //{ throw new Error("Not implemented.");} } export class XmlSchemaObjectTable { Count: number; Item: System.Xml.Schema.XmlSchemaObject; Names: System.Collections.ICollection; Values: System.Collections.ICollection; private table: System.Collections.Generic.Dictionary<TKey, TValue>; private entries: System.Collections.Generic.List<T>; Add(name: System.Xml.XmlQualifiedName, value: System.Xml.Schema.XmlSchemaObject): any; //{ throw new Error("Not implemented.");} Clear(): any; //{ throw new Error("Not implemented.");} Contains(name: System.Xml.XmlQualifiedName): boolean; //{ throw new Error("Not implemented.");} FindIndexByValue(xso: System.Xml.Schema.XmlSchemaObject): number; //{ throw new Error("Not implemented.");} GetEnumerator(): any; //{ throw new Error("Not implemented.");} Insert(name: System.Xml.XmlQualifiedName, value: System.Xml.Schema.XmlSchemaObject): any; //{ throw new Error("Not implemented.");} Remove(name: System.Xml.XmlQualifiedName): any; //{ throw new Error("Not implemented.");} Replace(name: System.Xml.XmlQualifiedName, value: System.Xml.Schema.XmlSchemaObject): any; //{ throw new Error("Not implemented.");} } export class XmlSchemaParticle extends System.Xml.Schema.XmlSchemaAnnotated { MinOccursString: string; MaxOccursString: string; MinOccurs: number; MaxOccurs: number; IsEmpty: boolean; IsMultipleOccurrence: boolean; NameString: string; private minOccurs: number; private maxOccurs: number; private flags: System.Xml.Schema.XmlSchemaParticle.Occurs; static Empty: System.Xml.Schema.XmlSchemaParticle; GetQualifiedName(): System.Xml.XmlQualifiedName; //{ throw new Error("Not implemented.");} } export class XmlSchemaSet { InternalSyncObject: any; NameTable: System.Xml.XmlNameTable; IsCompiled: boolean; XmlResolver: System.Xml.XmlResolver; CompilationSettings: System.Xml.Schema.XmlSchemaCompilationSettings; Count: number; GlobalElements: System.Xml.Schema.XmlSchemaObjectTable; GlobalAttributes: System.Xml.Schema.XmlSchemaObjectTable; GlobalTypes: System.Xml.Schema.XmlSchemaObjectTable; SubstitutionGroups: System.Xml.Schema.XmlSchemaObjectTable; SchemaLocations: System.Collections.Hashtable; TypeExtensions: System.Xml.Schema.XmlSchemaObjectTable; CompiledInfo: System.Xml.Schema.SchemaInfo; ReaderSettings: System.Xml.XmlReaderSettings; SortedSchemas: System.Collections.SortedList; CompileAll: boolean; private nameTable: System.Xml.XmlNameTable; private schemaNames: any; private schemas: System.Collections.SortedList; private internalEventHandler: any; private eventHandler: any; private isCompiled: boolean; private schemaLocations: System.Collections.Hashtable; private chameleonSchemas: System.Collections.Hashtable; private targetNamespaces: System.Collections.Hashtable; private compileAll: boolean; private cachedCompiledInfo: System.Xml.Schema.SchemaInfo; private readerSettings: System.Xml.XmlReaderSettings; private schemaForSchema: System.Xml.Schema.XmlSchema; private compilationSettings: System.Xml.Schema.XmlSchemaCompilationSettings; elements: System.Xml.Schema.XmlSchemaObjectTable; attributes: System.Xml.Schema.XmlSchemaObjectTable; schemaTypes: System.Xml.Schema.XmlSchemaObjectTable; substitutionGroups: System.Xml.Schema.XmlSchemaObjectTable; private typeExtensions: System.Xml.Schema.XmlSchemaObjectTable; private internalSyncObject: any; Add(targetNamespace: string, schemaUri: string): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} Add(targetNamespace: string, schemaDocument: any): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} Add(schemas: System.Xml.Schema.XmlSchemaSet): any; //{ throw new Error("Not implemented.");} Add(schema: System.Xml.Schema.XmlSchema): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} Add(targetNamespace: string, schema: System.Xml.Schema.XmlSchema): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} Add(targetNamespace: string, reader: any, validatedNamespaces: System.Collections.Hashtable): any; //{ throw new Error("Not implemented.");} AddSchemaToSet(schema: System.Xml.Schema.XmlSchema): any; //{ throw new Error("Not implemented.");} AddToTable(table: System.Xml.Schema.XmlSchemaObjectTable, qname: System.Xml.XmlQualifiedName, item: System.Xml.Schema.XmlSchemaObject): boolean; //{ throw new Error("Not implemented.");} ClearTables(): any; //{ throw new Error("Not implemented.");} Compile(): any; //{ throw new Error("Not implemented.");} Contains(targetNamespace: string): boolean; //{ throw new Error("Not implemented.");} Contains(schema: System.Xml.Schema.XmlSchema): boolean; //{ throw new Error("Not implemented.");} CopyFromCompiledSet(otherSet: System.Xml.Schema.XmlSchemaSet): any; //{ throw new Error("Not implemented.");} CopyTo(schemas: any, index: number): any; //{ throw new Error("Not implemented.");} FindSchemaByNSAndUrl(schemaUri: System.Uri, ns: string, locationsTable: any): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} GetEventHandler(): any; //{ throw new Error("Not implemented.");} GetResolver(): System.Xml.XmlResolver; //{ throw new Error("Not implemented.");} GetSchemaByUri(schemaUri: System.Uri, schema: any): boolean; //{ throw new Error("Not implemented.");} GetSchemaNames(nt: System.Xml.XmlNameTable): any; //{ throw new Error("Not implemented.");} GetTargetNamespace(schema: System.Xml.Schema.XmlSchema): string; //{ throw new Error("Not implemented.");} InternalValidationCallback(sender: any, e: any): any; //{ throw new Error("Not implemented.");} IsSchemaLoaded(schemaUri: System.Uri, targetNamespace: string, schema: any): boolean; //{ throw new Error("Not implemented.");} ParseSchema(targetNamespace: string, reader: any): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} PreprocessSchema(schema: any, targetNamespace: string): boolean; //{ throw new Error("Not implemented.");} ProcessNewSubstitutionGroups(substitutionGroupsTable: System.Xml.Schema.XmlSchemaObjectTable, resolve: boolean): any; //{ throw new Error("Not implemented.");} Remove(schema: System.Xml.Schema.XmlSchema): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} Remove(schema: System.Xml.Schema.XmlSchema, forceCompile: boolean): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} RemoveRecursive(schemaToRemove: System.Xml.Schema.XmlSchema): boolean; //{ throw new Error("Not implemented.");} RemoveSchemaFromCaches(schema: System.Xml.Schema.XmlSchema): any; //{ throw new Error("Not implemented.");} RemoveSchemaFromGlobalTables(schema: System.Xml.Schema.XmlSchema): any; //{ throw new Error("Not implemented.");} Reprocess(schema: System.Xml.Schema.XmlSchema): System.Xml.Schema.XmlSchema; //{ throw new Error("Not implemented.");} ResolveSubstitutionGroup(substitutionGroup: any, substTable: System.Xml.Schema.XmlSchemaObjectTable): any; //{ throw new Error("Not implemented.");} Schemas(): System.Collections.ICollection; //{ throw new Error("Not implemented.");} Schemas(targetNamespace: string): System.Collections.ICollection; //{ throw new Error("Not implemented.");} SendValidationEvent(e: any, severity: System.Xml.Schema.XmlSeverityType): any; //{ throw new Error("Not implemented.");} SetDtdProcessing(reader: any): any; //{ throw new Error("Not implemented.");} VerifyTables(): any; //{ throw new Error("Not implemented.");} } export class XmlSchemaSimpleType extends System.Xml.Schema.XmlSchemaType { Content: System.Xml.Schema.XmlSchemaSimpleTypeContent; DerivedFrom: System.Xml.XmlQualifiedName; private content: System.Xml.Schema.XmlSchemaSimpleTypeContent; Clone(): System.Xml.Schema.XmlSchemaObject; //{ throw new Error("Not implemented.");} } export class XmlSchemaSimpleTypeContent extends System.Xml.Schema.XmlSchemaAnnotated { } export class XmlSchemaType extends System.Xml.Schema.XmlSchemaAnnotated { Name: string; Final: System.Xml.Schema.XmlSchemaDerivationMethod; QualifiedName: System.Xml.XmlQualifiedName; FinalResolved: System.Xml.Schema.XmlSchemaDerivationMethod; BaseSchemaType: any; BaseXmlSchemaType: System.Xml.Schema.XmlSchemaType; DerivedBy: System.Xml.Schema.XmlSchemaDerivationMethod; Datatype: System.Xml.Schema.XmlSchemaDatatype; IsMixed: boolean; TypeCode: System.Xml.Schema.XmlTypeCode; ValueConverter: System.Xml.Schema.XmlValueConverter; SchemaContentType: System.Xml.Schema.XmlSchemaContentType; ElementDecl: System.Xml.Schema.SchemaElementDecl; Redefined: System.Xml.Schema.XmlSchemaType; DerivedFrom: System.Xml.XmlQualifiedName; NameAttribute: string; private name: string; private final: System.Xml.Schema.XmlSchemaDerivationMethod; private derivedBy: System.Xml.Schema.XmlSchemaDerivationMethod; private baseSchemaType: System.Xml.Schema.XmlSchemaType; private datatype: System.Xml.Schema.XmlSchemaDatatype; private finalResolved: System.Xml.Schema.XmlSchemaDerivationMethod; private elementDecl: System.Xml.Schema.SchemaElementDecl; private qname: System.Xml.XmlQualifiedName; private redefined: System.Xml.Schema.XmlSchemaType; private contentType: System.Xml.Schema.XmlSchemaContentType; GetBuiltInComplexType(typeCode: System.Xml.Schema.XmlTypeCode): any; //{ throw new Error("Not implemented.");} GetBuiltInComplexType(qualifiedName: System.Xml.XmlQualifiedName): any; //{ throw new Error("Not implemented.");} GetBuiltInSimpleType(qualifiedName: System.Xml.XmlQualifiedName): System.Xml.Schema.XmlSchemaSimpleType; //{ throw new Error("Not implemented.");} GetBuiltInSimpleType(typeCode: System.Xml.Schema.XmlTypeCode): System.Xml.Schema.XmlSchemaSimpleType; //{ throw new Error("Not implemented.");} IsDerivedFrom(derivedType: System.Xml.Schema.XmlSchemaType, baseType: System.Xml.Schema.XmlSchemaType, except: System.Xml.Schema.XmlSchemaDerivationMethod): boolean; //{ throw new Error("Not implemented.");} IsDerivedFromDatatype(derivedDataType: System.Xml.Schema.XmlSchemaDatatype, baseDataType: System.Xml.Schema.XmlSchemaDatatype, except: System.Xml.Schema.XmlSchemaDerivationMethod): boolean; //{ throw new Error("Not implemented.");} SetBaseSchemaType(value: System.Xml.Schema.XmlSchemaType): any; //{ throw new Error("Not implemented.");} SetContentType(value: System.Xml.Schema.XmlSchemaContentType): any; //{ throw new Error("Not implemented.");} SetDatatype(value: System.Xml.Schema.XmlSchemaDatatype): any; //{ throw new Error("Not implemented.");} SetDerivedBy(value: System.Xml.Schema.XmlSchemaDerivationMethod): any; //{ throw new Error("Not implemented.");} SetFinalResolved(value: System.Xml.Schema.XmlSchemaDerivationMethod): any; //{ throw new Error("Not implemented.");} SetQualifiedName(value: System.Xml.XmlQualifiedName): any; //{ throw new Error("Not implemented.");} Validate(reader: any, resolver: System.Xml.XmlResolver, schemaSet: System.Xml.Schema.XmlSchemaSet, valEventHandler: any): any; //{ throw new Error("Not implemented.");} } export class XmlValueConverter { ChangeType(value: any, destinationType: System.Type, nsResolver: System.Xml.IXmlNamespaceResolver): any; //{ throw new Error("Not implemented.");} ChangeType(value: string, destinationType: System.Type, nsResolver: System.Xml.IXmlNamespaceResolver): any; //{ throw new Error("Not implemented.");} ChangeType(value: string, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: Date, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: Date, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: number, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: number, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: number, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: number, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: number, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: boolean, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ChangeType(value: any, destinationType: System.Type): any; //{ throw new Error("Not implemented.");} ToBoolean(value: boolean): boolean; //{ throw new Error("Not implemented.");} ToBoolean(value: any): boolean; //{ throw new Error("Not implemented.");} ToBoolean(value: number): boolean; //{ throw new Error("Not implemented.");} ToBoolean(value: number): boolean; //{ throw new Error("Not implemented.");} ToBoolean(value: number): boolean; //{ throw new Error("Not implemented.");} ToBoolean(value: number): boolean; //{ throw new Error("Not implemented.");} ToBoolean(value: Date): boolean; //{ throw new Error("Not implemented.");} ToBoolean(value: Date): boolean; //{ throw new Error("Not implemented.");} ToBoolean(value: string): boolean; //{ throw new Error("Not implemented.");} ToBoolean(value: number): boolean; //{ throw new Error("Not implemented.");} ToDateTime(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTime(value: boolean): Date; //{ throw new Error("Not implemented.");} ToDateTime(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTime(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTime(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTime(value: Date): Date; //{ throw new Error("Not implemented.");} ToDateTime(value: string): Date; //{ throw new Error("Not implemented.");} ToDateTime(value: any): Date; //{ throw new Error("Not implemented.");} ToDateTime(value: Date): Date; //{ throw new Error("Not implemented.");} ToDateTime(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: boolean): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: number): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: Date): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: Date): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: string): Date; //{ throw new Error("Not implemented.");} ToDateTimeOffset(value: any): Date; //{ throw new Error("Not implemented.");} ToDecimal(value: Date): number; //{ throw new Error("Not implemented.");} ToDecimal(value: string): number; //{ throw new Error("Not implemented.");} ToDecimal(value: boolean): number; //{ throw new Error("Not implemented.");} ToDecimal(value: number): number; //{ throw new Error("Not implemented.");} ToDecimal(value: number): number; //{ throw new Error("Not implemented.");} ToDecimal(value: number): number; //{ throw new Error("Not implemented.");} ToDecimal(value: number): number; //{ throw new Error("Not implemented.");} ToDecimal(value: number): number; //{ throw new Error("Not implemented.");} ToDecimal(value: Date): number; //{ throw new Error("Not implemented.");} ToDecimal(value: any): number; //{ throw new Error("Not implemented.");} ToDouble(value: number): number; //{ throw new Error("Not implemented.");} ToDouble(value: boolean): number; //{ throw new Error("Not implemented.");} ToDouble(value: any): number; //{ throw new Error("Not implemented.");} ToDouble(value: string): number; //{ throw new Error("Not implemented.");} ToDouble(value: number): number; //{ throw new Error("Not implemented.");} ToDouble(value: Date): number; //{ throw new Error("Not implemented.");} ToDouble(value: number): number; //{ throw new Error("Not implemented.");} ToDouble(value: number): number; //{ throw new Error("Not implemented.");} ToDouble(value: number): number; //{ throw new Error("Not implemented.");} ToDouble(value: Date): number; //{ throw new Error("Not implemented.");} ToInt32(value: number): number; //{ throw new Error("Not implemented.");} ToInt32(value: number): number; //{ throw new Error("Not implemented.");} ToInt32(value: number): number; //{ throw new Error("Not implemented.");} ToInt32(value: number): number; //{ throw new Error("Not implemented.");} ToInt32(value: Date): number; //{ throw new Error("Not implemented.");} ToInt32(value: Date): number; //{ throw new Error("Not implemented.");} ToInt32(value: string): number; //{ throw new Error("Not implemented.");} ToInt32(value: any): number; //{ throw new Error("Not implemented.");} ToInt32(value: number): number; //{ throw new Error("Not implemented.");} ToInt32(value: boolean): number; //{ throw new Error("Not implemented.");} ToInt64(value: number): number; //{ throw new Error("Not implemented.");} ToInt64(value: boolean): number; //{ throw new Error("Not implemented.");} ToInt64(value: number): number; //{ throw new Error("Not implemented.");} ToInt64(value: number): number; //{ throw new Error("Not implemented.");} ToInt64(value: Date): number; //{ throw new Error("Not implemented.");} ToInt64(value: Date): number; //{ throw new Error("Not implemented.");} ToInt64(value: string): number; //{ throw new Error("Not implemented.");} ToInt64(value: any): number; //{ throw new Error("Not implemented.");} ToInt64(value: number): number; //{ throw new Error("Not implemented.");} ToInt64(value: number): number; //{ throw new Error("Not implemented.");} ToSingle(value: string): number; //{ throw new Error("Not implemented.");} ToSingle(value: number): number; //{ throw new Error("Not implemented.");} ToSingle(value: boolean): number; //{ throw new Error("Not implemented.");} ToSingle(value: number): number; //{ throw new Error("Not implemented.");} ToSingle(value: number): number; //{ throw new Error("Not implemented.");} ToSingle(value: number): number; //{ throw new Error("Not implemented.");} ToSingle(value: number): number; //{ throw new Error("Not implemented.");} ToSingle(value: Date): number; //{ throw new Error("Not implemented.");} ToSingle(value: Date): number; //{ throw new Error("Not implemented.");} ToSingle(value: any): number; //{ throw new Error("Not implemented.");} ToString(value: number): string; //{ throw new Error("Not implemented.");} ToString(value: boolean): string; //{ throw new Error("Not implemented.");} ToString(value: any, nsResolver: System.Xml.IXmlNamespaceResolver): string; //{ throw new Error("Not implemented.");} ToString(value: any): string; //{ throw new Error("Not implemented.");} ToString(value: string, nsResolver: System.Xml.IXmlNamespaceResolver): string; //{ throw new Error("Not implemented.");} ToString(value: string): string; //{ throw new Error("Not implemented.");} ToString(value: Date): string; //{ throw new Error("Not implemented.");} ToString(value: Date): string; //{ throw new Error("Not implemented.");} ToString(value: number): string; //{ throw new Error("Not implemented.");} ToString(value: number): string; //{ throw new Error("Not implemented.");} ToString(value: number): string; //{ throw new Error("Not implemented.");} ToString(value: number): string; //{ throw new Error("Not implemented.");} } } declare module System.Xml.Schema.NamespaceList { } declare module System.Xml.Schema.SchemaAttDef { } declare module System.Xml.Schema.SchemaDeclBase { } declare module System.Xml.Serialization { export class XmlSerializerNamespaces { Count: number; NamespaceList: System.Collections.ArrayList; Namespaces: System.Collections.Hashtable; private namespaces: System.Collections.Hashtable; Add(prefix: string, ns: string): any; //{ throw new Error("Not implemented.");} AddInternal(prefix: string, ns: string): any; //{ throw new Error("Not implemented.");} LookupPrefix(ns: string): string; //{ throw new Error("Not implemented.");} ToArray(): any; //{ throw new Error("Not implemented.");} } } declare module System.Xml.XPath { }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormRMA { interface tab__967655CB_D318_4E85_A768_3B42E0FC398E_Sections { _567C00B9_7BCD_4668_9FD1_010DD4039922: DevKit.Controls.Section; _967655CB_D318_4E85_A768_3B42E0FC398E_SECTION_2: DevKit.Controls.Section; _967655CB_D318_4E85_A768_3B42E0FC398E_SECTION_3: DevKit.Controls.Section; tab_1_section_2: DevKit.Controls.Section; tab_1_section_3: DevKit.Controls.Section; tab_3_section_3: DevKit.Controls.Section; } interface tab_rmaproductstab_Sections { tab_3_section_1: DevKit.Controls.Section; } interface tab_tab_3_Sections { } interface tab__967655CB_D318_4E85_A768_3B42E0FC398E extends DevKit.Controls.ITab { Section: tab__967655CB_D318_4E85_A768_3B42E0FC398E_Sections; } interface tab_rmaproductstab extends DevKit.Controls.ITab { Section: tab_rmaproductstab_Sections; } interface tab_tab_3 extends DevKit.Controls.ITab { Section: tab_tab_3_Sections; } interface Tabs { _967655CB_D318_4E85_A768_3B42E0FC398E: tab__967655CB_D318_4E85_A768_3B42E0FC398E; rmaproductstab: tab_rmaproductstab; tab_3: tab_tab_3; } interface Body { Tab: Tabs; /** User who approved RMA */ msdyn_ApprovedBy: DevKit.Controls.Lookup; /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; /** Enter the date RMA was requested by the customer. */ msdyn_DateRequested: DevKit.Controls.Date; /** Enter a short description of the RMA. */ msdyn_Description: DevKit.Controls.String; /** ETA */ msdyn_ETA: DevKit.Controls.Date; /** Shows the unique number identifying this RMA record. */ msdyn_name: DevKit.Controls.String; /** Shows the tracking number of package */ msdyn_PackagingTrackingNo: DevKit.Controls.String; /** Price List that determines the pricing for this product */ msdyn_PriceList: DevKit.Controls.Lookup; /** Shows the default action to be taken on all RMA Products. */ msdyn_ProcessingAction: DevKit.Controls.OptionSet; msdyn_ReferenceNo: DevKit.Controls.String; /** Contact who requested this return */ msdyn_RequestedByContact: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Shows the tracking number of the shipment. */ msdyn_ShippingTrackingNo: DevKit.Controls.String; /** Method of shipment by Customer */ msdyn_ShipVia: DevKit.Controls.Lookup; /** RMA Substatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Enter the current status of the RMA. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Specify if RMA is taxable */ msdyn_Taxable: DevKit.Controls.Boolean; /** Tax Code to be used to calculate tax when RMA is taxable. By default the system will use the tax code specified on the service account */ msdyn_TaxCode: DevKit.Controls.Lookup; /** Shows the total amount of all RMA Products including tax. */ msdyn_TotalAmount: DevKit.Controls.Money; /** Work Order this RMA is linked to */ msdyn_WorkOrder: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_rma_msdyn_rmaproduct_RMA: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_rma_msdyn_rmareceipt_RMA: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_rma_msdyn_rmareceiptproduct_RMA: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_rma_msdyn_rtvproduct_RMA: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface Grid { receiptsgrid: DevKit.Controls.Grid; rmaproductsgrid: DevKit.Controls.Grid; } } class FormRMA extends DevKit.IForm { /** * DynamicsCrm.DevKit form RMA * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form RMA */ Body: DevKit.FormRMA.Body; /** The Navigation of form RMA */ Navigation: DevKit.FormRMA.Navigation; /** The Grid of form RMA */ Grid: DevKit.FormRMA.Grid; } class msdyn_rmaApi { /** * DynamicsCrm.DevKit msdyn_rmaApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows the exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** User who approved RMA */ msdyn_ApprovedBy: DevKit.WebApi.LookupValue; /** Internal field used to generate the next name upon entity creation. It is optionally copied to the msdyn_name field. */ msdyn_AutoNumbering: DevKit.WebApi.StringValue; /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.WebApi.LookupValue; /** Enter the date RMA was requested by the customer. */ msdyn_DateRequested_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter a short description of the RMA. */ msdyn_Description: DevKit.WebApi.StringValue; /** ETA */ msdyn_ETA_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the unique number identifying this RMA record. */ msdyn_name: DevKit.WebApi.StringValue; /** Shows the tracking number of package */ msdyn_PackagingTrackingNo: DevKit.WebApi.StringValue; /** Price List that determines the pricing for this product */ msdyn_PriceList: DevKit.WebApi.LookupValue; /** Shows the default action to be taken on all RMA Products. */ msdyn_ProcessingAction: DevKit.WebApi.OptionSetValue; msdyn_ReferenceNo: DevKit.WebApi.StringValue; /** Contact who requested this return */ msdyn_RequestedByContact: DevKit.WebApi.LookupValue; /** Shows the entity instances. */ msdyn_rmaId: DevKit.WebApi.GuidValue; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.WebApi.LookupValue; /** Shows the tracking number of the shipment. */ msdyn_ShippingTrackingNo: DevKit.WebApi.StringValue; /** Method of shipment by Customer */ msdyn_ShipVia: DevKit.WebApi.LookupValue; /** RMA Substatus */ msdyn_SubStatus: DevKit.WebApi.LookupValue; /** Enter the current status of the RMA. */ msdyn_SystemStatus: DevKit.WebApi.OptionSetValue; /** Specify if RMA is taxable */ msdyn_Taxable: DevKit.WebApi.BooleanValue; /** Tax Code to be used to calculate tax when RMA is taxable. By default the system will use the tax code specified on the service account */ msdyn_TaxCode: DevKit.WebApi.LookupValue; /** Shows the total amount of all RMA Products including tax. */ msdyn_TotalAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the total amount in the base currency. */ msdyn_totalamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Work Order this RMA is linked to */ msdyn_WorkOrder: DevKit.WebApi.LookupValue; /** Shows the date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the RMA */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the RMA */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Shows the time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_rma { enum msdyn_ProcessingAction { /** 690970002 */ Change_Asset_Ownership, /** 690970000 */ Create_RTV, /** 690970001 */ Return_to_Warehouse } enum msdyn_SystemStatus { /** 690970001 */ Canceled, /** 690970000 */ Pending, /** 690970002 */ Products_Received } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['RMA'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Endpoints } from "@octokit/types"; export interface PaginatingEndpoints { /** * @see https://docs.github.com/rest/reference/apps#list-deliveries-for-an-app-webhook */ "GET /app/hook/deliveries": { parameters: Endpoints["GET /app/hook/deliveries"]["parameters"]; response: Endpoints["GET /app/hook/deliveries"]["response"]; }; /** * @see https://docs.github.com/rest/reference/apps#list-installations-for-the-authenticated-app */ "GET /app/installations": { parameters: Endpoints["GET /app/installations"]["parameters"]; response: Endpoints["GET /app/installations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/oauth-authorizations#list-your-grants */ "GET /applications/grants": { parameters: Endpoints["GET /applications/grants"]["parameters"]; response: Endpoints["GET /applications/grants"]["response"]; }; /** * @see https://docs.github.com/rest/reference/oauth-authorizations#list-your-authorizations */ "GET /authorizations": { parameters: Endpoints["GET /authorizations"]["parameters"]; response: Endpoints["GET /authorizations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/enterprise-admin#list-selected-organizations-enabled-for-github-actions-in-an-enterprise */ "GET /enterprises/{enterprise}/actions/permissions/organizations": { parameters: Endpoints["GET /enterprises/{enterprise}/actions/permissions/organizations"]["parameters"]; response: Endpoints["GET /enterprises/{enterprise}/actions/permissions/organizations"]["response"] & { data: Endpoints["GET /enterprises/{enterprise}/actions/permissions/organizations"]["response"]["data"]["organizations"]; }; }; /** * @see https://docs.github.com/rest/reference/enterprise-admin#list-self-hosted-runner-groups-for-an-enterprise */ "GET /enterprises/{enterprise}/actions/runner-groups": { parameters: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups"]["parameters"]; response: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups"]["response"] & { data: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups"]["response"]["data"]["runner_groups"]; }; }; /** * @see https://docs.github.com/rest/reference/enterprise-admin#list-organization-access-to-a-self-hosted-runner-group-in-a-enterprise */ "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations": { parameters: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations"]["parameters"]; response: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations"]["response"] & { data: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations"]["response"]["data"]["organizations"]; }; }; /** * @see https://docs.github.com/rest/reference/enterprise-admin#list-self-hosted-runners-in-a-group-for-an-enterprise */ "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners": { parameters: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners"]["parameters"]; response: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners"]["response"] & { data: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://docs.github.com/rest/reference/enterprise-admin#list-self-hosted-runners-for-an-enterprise */ "GET /enterprises/{enterprise}/actions/runners": { parameters: Endpoints["GET /enterprises/{enterprise}/actions/runners"]["parameters"]; response: Endpoints["GET /enterprises/{enterprise}/actions/runners"]["response"] & { data: Endpoints["GET /enterprises/{enterprise}/actions/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://docs.github.com/rest/reference/enterprise-admin#list-runner-applications-for-an-enterprise */ "GET /enterprises/{enterprise}/actions/runners/downloads": { parameters: Endpoints["GET /enterprises/{enterprise}/actions/runners/downloads"]["parameters"]; response: Endpoints["GET /enterprises/{enterprise}/actions/runners/downloads"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-public-events */ "GET /events": { parameters: Endpoints["GET /events"]["parameters"]; response: Endpoints["GET /events"]["response"]; }; /** * @see https://docs.github.com/rest/reference/gists#list-gists-for-the-authenticated-user */ "GET /gists": { parameters: Endpoints["GET /gists"]["parameters"]; response: Endpoints["GET /gists"]["response"]; }; /** * @see https://docs.github.com/rest/reference/gists#list-public-gists */ "GET /gists/public": { parameters: Endpoints["GET /gists/public"]["parameters"]; response: Endpoints["GET /gists/public"]["response"]; }; /** * @see https://docs.github.com/rest/reference/gists#list-starred-gists */ "GET /gists/starred": { parameters: Endpoints["GET /gists/starred"]["parameters"]; response: Endpoints["GET /gists/starred"]["response"]; }; /** * @see https://docs.github.com/rest/reference/gists#list-gist-comments */ "GET /gists/{gist_id}/comments": { parameters: Endpoints["GET /gists/{gist_id}/comments"]["parameters"]; response: Endpoints["GET /gists/{gist_id}/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/gists#list-gist-commits */ "GET /gists/{gist_id}/commits": { parameters: Endpoints["GET /gists/{gist_id}/commits"]["parameters"]; response: Endpoints["GET /gists/{gist_id}/commits"]["response"]; }; /** * @see https://docs.github.com/rest/reference/gists#list-gist-forks */ "GET /gists/{gist_id}/forks": { parameters: Endpoints["GET /gists/{gist_id}/forks"]["parameters"]; response: Endpoints["GET /gists/{gist_id}/forks"]["response"]; }; /** * @see https://docs.github.com/rest/reference/apps#list-repositories-accessible-to-the-app-installation */ "GET /installation/repositories": { parameters: Endpoints["GET /installation/repositories"]["parameters"]; response: Endpoints["GET /installation/repositories"]["response"] & { data: Endpoints["GET /installation/repositories"]["response"]["data"]["repositories"]; }; }; /** * @see https://docs.github.com/rest/reference/issues#list-issues-assigned-to-the-authenticated-user */ "GET /issues": { parameters: Endpoints["GET /issues"]["parameters"]; response: Endpoints["GET /issues"]["response"]; }; /** * @see https://docs.github.com/rest/reference/apps#list-plans */ "GET /marketplace_listing/plans": { parameters: Endpoints["GET /marketplace_listing/plans"]["parameters"]; response: Endpoints["GET /marketplace_listing/plans"]["response"]; }; /** * @see https://docs.github.com/rest/reference/apps#list-accounts-for-a-plan */ "GET /marketplace_listing/plans/{plan_id}/accounts": { parameters: Endpoints["GET /marketplace_listing/plans/{plan_id}/accounts"]["parameters"]; response: Endpoints["GET /marketplace_listing/plans/{plan_id}/accounts"]["response"]; }; /** * @see https://docs.github.com/rest/reference/apps#list-plans-stubbed */ "GET /marketplace_listing/stubbed/plans": { parameters: Endpoints["GET /marketplace_listing/stubbed/plans"]["parameters"]; response: Endpoints["GET /marketplace_listing/stubbed/plans"]["response"]; }; /** * @see https://docs.github.com/rest/reference/apps#list-accounts-for-a-plan-stubbed */ "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts": { parameters: Endpoints["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"]["parameters"]; response: Endpoints["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-public-events-for-a-network-of-repositories */ "GET /networks/{owner}/{repo}/events": { parameters: Endpoints["GET /networks/{owner}/{repo}/events"]["parameters"]; response: Endpoints["GET /networks/{owner}/{repo}/events"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-notifications-for-the-authenticated-user */ "GET /notifications": { parameters: Endpoints["GET /notifications"]["parameters"]; response: Endpoints["GET /notifications"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-organizations */ "GET /organizations": { parameters: Endpoints["GET /organizations"]["parameters"]; response: Endpoints["GET /organizations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/actions#list-selected-repositories-enabled-for-github-actions-in-an-organization */ "GET /orgs/{org}/actions/permissions/repositories": { parameters: Endpoints["GET /orgs/{org}/actions/permissions/repositories"]["parameters"]; response: Endpoints["GET /orgs/{org}/actions/permissions/repositories"]["response"] & { data: Endpoints["GET /orgs/{org}/actions/permissions/repositories"]["response"]["data"]["repositories"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-self-hosted-runner-groups-for-an-organization */ "GET /orgs/{org}/actions/runner-groups": { parameters: Endpoints["GET /orgs/{org}/actions/runner-groups"]["parameters"]; response: Endpoints["GET /orgs/{org}/actions/runner-groups"]["response"] & { data: Endpoints["GET /orgs/{org}/actions/runner-groups"]["response"]["data"]["runner_groups"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-repository-access-to-a-self-hosted-runner-group-in-an-organization */ "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories": { parameters: Endpoints["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories"]["parameters"]; response: Endpoints["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories"]["response"] & { data: Endpoints["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories"]["response"]["data"]["repositories"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-self-hosted-runners-in-a-group-for-an-organization */ "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners": { parameters: Endpoints["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners"]["parameters"]; response: Endpoints["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners"]["response"] & { data: Endpoints["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-self-hosted-runners-for-an-organization */ "GET /orgs/{org}/actions/runners": { parameters: Endpoints["GET /orgs/{org}/actions/runners"]["parameters"]; response: Endpoints["GET /orgs/{org}/actions/runners"]["response"] & { data: Endpoints["GET /orgs/{org}/actions/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-runner-applications-for-an-organization */ "GET /orgs/{org}/actions/runners/downloads": { parameters: Endpoints["GET /orgs/{org}/actions/runners/downloads"]["parameters"]; response: Endpoints["GET /orgs/{org}/actions/runners/downloads"]["response"]; }; /** * @see https://docs.github.com/rest/reference/actions#list-organization-secrets */ "GET /orgs/{org}/actions/secrets": { parameters: Endpoints["GET /orgs/{org}/actions/secrets"]["parameters"]; response: Endpoints["GET /orgs/{org}/actions/secrets"]["response"] & { data: Endpoints["GET /orgs/{org}/actions/secrets"]["response"]["data"]["secrets"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-selected-repositories-for-an-organization-secret */ "GET /orgs/{org}/actions/secrets/{secret_name}/repositories": { parameters: Endpoints["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"]["parameters"]; response: Endpoints["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"]["response"] & { data: Endpoints["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"]["response"]["data"]["repositories"]; }; }; /** * @see https://docs.github.com/rest/reference/orgs#list-users-blocked-by-an-organization */ "GET /orgs/{org}/blocks": { parameters: Endpoints["GET /orgs/{org}/blocks"]["parameters"]; response: Endpoints["GET /orgs/{org}/blocks"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-saml-sso-authorizations-for-an-organization */ "GET /orgs/{org}/credential-authorizations": { parameters: Endpoints["GET /orgs/{org}/credential-authorizations"]["parameters"]; response: Endpoints["GET /orgs/{org}/credential-authorizations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-public-organization-events */ "GET /orgs/{org}/events": { parameters: Endpoints["GET /orgs/{org}/events"]["parameters"]; response: Endpoints["GET /orgs/{org}/events"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-failed-organization-invitations */ "GET /orgs/{org}/failed_invitations": { parameters: Endpoints["GET /orgs/{org}/failed_invitations"]["parameters"]; response: Endpoints["GET /orgs/{org}/failed_invitations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-organization-webhooks */ "GET /orgs/{org}/hooks": { parameters: Endpoints["GET /orgs/{org}/hooks"]["parameters"]; response: Endpoints["GET /orgs/{org}/hooks"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-deliveries-for-an-organization-webhook */ "GET /orgs/{org}/hooks/{hook_id}/deliveries": { parameters: Endpoints["GET /orgs/{org}/hooks/{hook_id}/deliveries"]["parameters"]; response: Endpoints["GET /orgs/{org}/hooks/{hook_id}/deliveries"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-app-installations-for-an-organization */ "GET /orgs/{org}/installations": { parameters: Endpoints["GET /orgs/{org}/installations"]["parameters"]; response: Endpoints["GET /orgs/{org}/installations"]["response"] & { data: Endpoints["GET /orgs/{org}/installations"]["response"]["data"]["installations"]; }; }; /** * @see https://docs.github.com/rest/reference/orgs#list-pending-organization-invitations */ "GET /orgs/{org}/invitations": { parameters: Endpoints["GET /orgs/{org}/invitations"]["parameters"]; response: Endpoints["GET /orgs/{org}/invitations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-organization-invitation-teams */ "GET /orgs/{org}/invitations/{invitation_id}/teams": { parameters: Endpoints["GET /orgs/{org}/invitations/{invitation_id}/teams"]["parameters"]; response: Endpoints["GET /orgs/{org}/invitations/{invitation_id}/teams"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-organization-issues-assigned-to-the-authenticated-user */ "GET /orgs/{org}/issues": { parameters: Endpoints["GET /orgs/{org}/issues"]["parameters"]; response: Endpoints["GET /orgs/{org}/issues"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-organization-members */ "GET /orgs/{org}/members": { parameters: Endpoints["GET /orgs/{org}/members"]["parameters"]; response: Endpoints["GET /orgs/{org}/members"]["response"]; }; /** * @see https://docs.github.com/rest/reference/migrations#list-organization-migrations */ "GET /orgs/{org}/migrations": { parameters: Endpoints["GET /orgs/{org}/migrations"]["parameters"]; response: Endpoints["GET /orgs/{org}/migrations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/migrations#list-repositories-in-an-organization-migration */ "GET /orgs/{org}/migrations/{migration_id}/repositories": { parameters: Endpoints["GET /orgs/{org}/migrations/{migration_id}/repositories"]["parameters"]; response: Endpoints["GET /orgs/{org}/migrations/{migration_id}/repositories"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-outside-collaborators-for-an-organization */ "GET /orgs/{org}/outside_collaborators": { parameters: Endpoints["GET /orgs/{org}/outside_collaborators"]["parameters"]; response: Endpoints["GET /orgs/{org}/outside_collaborators"]["response"]; }; /** * @see https://docs.github.com/rest/reference/packages#list-packages-for-an-organization */ "GET /orgs/{org}/packages": { parameters: Endpoints["GET /orgs/{org}/packages"]["parameters"]; response: Endpoints["GET /orgs/{org}/packages"]["response"]; }; /** * @see https://docs.github.com/rest/reference/projects#list-organization-projects */ "GET /orgs/{org}/projects": { parameters: Endpoints["GET /orgs/{org}/projects"]["parameters"]; response: Endpoints["GET /orgs/{org}/projects"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-public-organization-members */ "GET /orgs/{org}/public_members": { parameters: Endpoints["GET /orgs/{org}/public_members"]["parameters"]; response: Endpoints["GET /orgs/{org}/public_members"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-organization-repositories */ "GET /orgs/{org}/repos": { parameters: Endpoints["GET /orgs/{org}/repos"]["parameters"]; response: Endpoints["GET /orgs/{org}/repos"]["response"]; }; /** * @see https://docs.github.com/rest/reference/secret-scanning#list-secret-scanning-alerts-by-organization */ "GET /orgs/{org}/secret-scanning/alerts": { parameters: Endpoints["GET /orgs/{org}/secret-scanning/alerts"]["parameters"]; response: Endpoints["GET /orgs/{org}/secret-scanning/alerts"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-idp-groups-for-an-organization */ "GET /orgs/{org}/team-sync/groups": { parameters: Endpoints["GET /orgs/{org}/team-sync/groups"]["parameters"]; response: Endpoints["GET /orgs/{org}/team-sync/groups"]["response"] & { data: Endpoints["GET /orgs/{org}/team-sync/groups"]["response"]["data"]["groups"]; }; }; /** * @see https://docs.github.com/rest/reference/teams#list-teams */ "GET /orgs/{org}/teams": { parameters: Endpoints["GET /orgs/{org}/teams"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-discussions */ "GET /orgs/{org}/teams/{team_slug}/discussions": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-discussion-comments */ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/reactions#list-reactions-for-a-team-discussion-comment */ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/reactions#list-reactions-for-a-team-discussion */ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-pending-team-invitations */ "GET /orgs/{org}/teams/{team_slug}/invitations": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/invitations"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/invitations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-team-members */ "GET /orgs/{org}/teams/{team_slug}/members": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/members"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/members"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-team-projects */ "GET /orgs/{org}/teams/{team_slug}/projects": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/projects"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/projects"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-team-repositories */ "GET /orgs/{org}/teams/{team_slug}/repos": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/repos"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/repos"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-idp-groups-for-a-team */ "GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings"]["response"] & { data: Endpoints["GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings"]["response"]["data"]["groups"]; }; }; /** * @see https://docs.github.com/rest/reference/teams#list-child-teams */ "GET /orgs/{org}/teams/{team_slug}/teams": { parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/teams"]["parameters"]; response: Endpoints["GET /orgs/{org}/teams/{team_slug}/teams"]["response"]; }; /** * @see https://docs.github.com/rest/reference/projects#list-project-cards */ "GET /projects/columns/{column_id}/cards": { parameters: Endpoints["GET /projects/columns/{column_id}/cards"]["parameters"]; response: Endpoints["GET /projects/columns/{column_id}/cards"]["response"]; }; /** * @see https://docs.github.com/rest/reference/projects#list-project-collaborators */ "GET /projects/{project_id}/collaborators": { parameters: Endpoints["GET /projects/{project_id}/collaborators"]["parameters"]; response: Endpoints["GET /projects/{project_id}/collaborators"]["response"]; }; /** * @see https://docs.github.com/rest/reference/projects#list-project-columns */ "GET /projects/{project_id}/columns": { parameters: Endpoints["GET /projects/{project_id}/columns"]["parameters"]; response: Endpoints["GET /projects/{project_id}/columns"]["response"]; }; /** * @see https://docs.github.com/rest/reference/actions#list-artifacts-for-a-repository */ "GET /repos/{owner}/{repo}/actions/artifacts": { parameters: Endpoints["GET /repos/{owner}/{repo}/actions/artifacts"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/actions/artifacts"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/actions/artifacts"]["response"]["data"]["artifacts"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-self-hosted-runners-for-a-repository */ "GET /repos/{owner}/{repo}/actions/runners": { parameters: Endpoints["GET /repos/{owner}/{repo}/actions/runners"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/actions/runners"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/actions/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-runner-applications-for-a-repository */ "GET /repos/{owner}/{repo}/actions/runners/downloads": { parameters: Endpoints["GET /repos/{owner}/{repo}/actions/runners/downloads"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/actions/runners/downloads"]["response"]; }; /** * @see https://docs.github.com/rest/reference/actions#list-workflow-runs-for-a-repository */ "GET /repos/{owner}/{repo}/actions/runs": { parameters: Endpoints["GET /repos/{owner}/{repo}/actions/runs"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/actions/runs"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/actions/runs"]["response"]["data"]["workflow_runs"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-workflow-run-artifacts */ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts": { parameters: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"]["response"]["data"]["artifacts"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-jobs-for-a-workflow-run */ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs": { parameters: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"]["response"]["data"]["jobs"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-repository-secrets */ "GET /repos/{owner}/{repo}/actions/secrets": { parameters: Endpoints["GET /repos/{owner}/{repo}/actions/secrets"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/actions/secrets"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/actions/secrets"]["response"]["data"]["secrets"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-repository-workflows */ "GET /repos/{owner}/{repo}/actions/workflows": { parameters: Endpoints["GET /repos/{owner}/{repo}/actions/workflows"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/actions/workflows"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/actions/workflows"]["response"]["data"]["workflows"]; }; }; /** * @see https://docs.github.com/rest/reference/actions#list-workflow-runs */ "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs": { parameters: Endpoints["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"]["response"]["data"]["workflow_runs"]; }; }; /** * @see https://docs.github.com/rest/reference/issues#list-assignees */ "GET /repos/{owner}/{repo}/assignees": { parameters: Endpoints["GET /repos/{owner}/{repo}/assignees"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/assignees"]["response"]; }; /** * @see https://docs.github.com/v3/repos#list-autolinks */ "GET /repos/{owner}/{repo}/autolinks": { parameters: Endpoints["GET /repos/{owner}/{repo}/autolinks"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/autolinks"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-branches */ "GET /repos/{owner}/{repo}/branches": { parameters: Endpoints["GET /repos/{owner}/{repo}/branches"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/branches"]["response"]; }; /** * @see https://docs.github.com/rest/reference/checks#list-check-run-annotations */ "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations": { parameters: Endpoints["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/checks#list-check-runs-in-a-check-suite */ "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs": { parameters: Endpoints["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"]["response"]["data"]["check_runs"]; }; }; /** * @see https://docs.github.com/rest/reference/code-scanning#list-code-scanning-alerts-for-a-repository */ "GET /repos/{owner}/{repo}/code-scanning/alerts": { parameters: Endpoints["GET /repos/{owner}/{repo}/code-scanning/alerts"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/code-scanning/alerts"]["response"]; }; /** * @see https://docs.github.com/rest/reference/code-scanning#list-instances-of-a-code-scanning-alert */ "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances": { parameters: Endpoints["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"]["response"]; }; /** * @see https://docs.github.com/rest/reference/code-scanning#list-code-scanning-analyses-for-a-repository */ "GET /repos/{owner}/{repo}/code-scanning/analyses": { parameters: Endpoints["GET /repos/{owner}/{repo}/code-scanning/analyses"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/code-scanning/analyses"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-repository-collaborators */ "GET /repos/{owner}/{repo}/collaborators": { parameters: Endpoints["GET /repos/{owner}/{repo}/collaborators"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/collaborators"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-commit-comments-for-a-repository */ "GET /repos/{owner}/{repo}/comments": { parameters: Endpoints["GET /repos/{owner}/{repo}/comments"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/reactions#list-reactions-for-a-commit-comment */ "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions": { parameters: Endpoints["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-commits */ "GET /repos/{owner}/{repo}/commits": { parameters: Endpoints["GET /repos/{owner}/{repo}/commits"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/commits"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-branches-for-head-commit */ "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head": { parameters: Endpoints["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-commit-comments */ "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments": { parameters: Endpoints["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-pull-requests-associated-with-a-commit */ "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls": { parameters: Endpoints["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"]["response"]; }; /** * @see https://docs.github.com/rest/reference/checks#list-check-runs-for-a-git-reference */ "GET /repos/{owner}/{repo}/commits/{ref}/check-runs": { parameters: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"]["response"]["data"]["check_runs"]; }; }; /** * @see https://docs.github.com/rest/reference/checks#list-check-suites-for-a-git-reference */ "GET /repos/{owner}/{repo}/commits/{ref}/check-suites": { parameters: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"]["response"]["data"]["check_suites"]; }; }; /** * @see https://docs.github.com/rest/reference/repos#list-commit-statuses-for-a-reference */ "GET /repos/{owner}/{repo}/commits/{ref}/statuses": { parameters: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/statuses"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/statuses"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-repository-contributors */ "GET /repos/{owner}/{repo}/contributors": { parameters: Endpoints["GET /repos/{owner}/{repo}/contributors"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/contributors"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-deployments */ "GET /repos/{owner}/{repo}/deployments": { parameters: Endpoints["GET /repos/{owner}/{repo}/deployments"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/deployments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-deployment-statuses */ "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses": { parameters: Endpoints["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-repository-events */ "GET /repos/{owner}/{repo}/events": { parameters: Endpoints["GET /repos/{owner}/{repo}/events"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/events"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-forks */ "GET /repos/{owner}/{repo}/forks": { parameters: Endpoints["GET /repos/{owner}/{repo}/forks"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/forks"]["response"]; }; /** * @see https://docs.github.com/rest/reference/git#list-matching-references */ "GET /repos/{owner}/{repo}/git/matching-refs/{ref}": { parameters: Endpoints["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-repository-webhooks */ "GET /repos/{owner}/{repo}/hooks": { parameters: Endpoints["GET /repos/{owner}/{repo}/hooks"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/hooks"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-deliveries-for-a-repository-webhook */ "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries": { parameters: Endpoints["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-repository-invitations */ "GET /repos/{owner}/{repo}/invitations": { parameters: Endpoints["GET /repos/{owner}/{repo}/invitations"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/invitations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-repository-issues */ "GET /repos/{owner}/{repo}/issues": { parameters: Endpoints["GET /repos/{owner}/{repo}/issues"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/issues"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-issue-comments-for-a-repository */ "GET /repos/{owner}/{repo}/issues/comments": { parameters: Endpoints["GET /repos/{owner}/{repo}/issues/comments"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/issues/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/reactions#list-reactions-for-an-issue-comment */ "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions": { parameters: Endpoints["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-issue-events-for-a-repository */ "GET /repos/{owner}/{repo}/issues/events": { parameters: Endpoints["GET /repos/{owner}/{repo}/issues/events"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/issues/events"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-issue-comments */ "GET /repos/{owner}/{repo}/issues/{issue_number}/comments": { parameters: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-issue-events */ "GET /repos/{owner}/{repo}/issues/{issue_number}/events": { parameters: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/events"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/events"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-labels-for-an-issue */ "GET /repos/{owner}/{repo}/issues/{issue_number}/labels": { parameters: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"]["response"]; }; /** * @see https://docs.github.com/rest/reference/reactions#list-reactions-for-an-issue */ "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions": { parameters: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-timeline-events-for-an-issue */ "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline": { parameters: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-deploy-keys */ "GET /repos/{owner}/{repo}/keys": { parameters: Endpoints["GET /repos/{owner}/{repo}/keys"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/keys"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-labels-for-a-repository */ "GET /repos/{owner}/{repo}/labels": { parameters: Endpoints["GET /repos/{owner}/{repo}/labels"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/labels"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-milestones */ "GET /repos/{owner}/{repo}/milestones": { parameters: Endpoints["GET /repos/{owner}/{repo}/milestones"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/milestones"]["response"]; }; /** * @see https://docs.github.com/rest/reference/issues#list-labels-for-issues-in-a-milestone */ "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels": { parameters: Endpoints["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-repository-notifications-for-the-authenticated-user */ "GET /repos/{owner}/{repo}/notifications": { parameters: Endpoints["GET /repos/{owner}/{repo}/notifications"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/notifications"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-github-pages-builds */ "GET /repos/{owner}/{repo}/pages/builds": { parameters: Endpoints["GET /repos/{owner}/{repo}/pages/builds"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pages/builds"]["response"]; }; /** * @see https://docs.github.com/rest/reference/projects#list-repository-projects */ "GET /repos/{owner}/{repo}/projects": { parameters: Endpoints["GET /repos/{owner}/{repo}/projects"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/projects"]["response"]; }; /** * @see https://docs.github.com/rest/reference/pulls#list-pull-requests */ "GET /repos/{owner}/{repo}/pulls": { parameters: Endpoints["GET /repos/{owner}/{repo}/pulls"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pulls"]["response"]; }; /** * @see https://docs.github.com/rest/reference/pulls#list-review-comments-in-a-repository */ "GET /repos/{owner}/{repo}/pulls/comments": { parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/comments"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pulls/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/reactions#list-reactions-for-a-pull-request-review-comment */ "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions": { parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/pulls#list-review-comments-on-a-pull-request */ "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments": { parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/pulls#list-commits-on-a-pull-request */ "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits": { parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"]["response"]; }; /** * @see https://docs.github.com/rest/reference/pulls#list-pull-requests-files */ "GET /repos/{owner}/{repo}/pulls/{pull_number}/files": { parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"]["response"]; }; /** * @see https://docs.github.com/rest/reference/pulls#list-requested-reviewers-for-a-pull-request */ "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers": { parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"]["response"] & { data: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"]["response"]["data"]["users"]; }; }; /** * @see https://docs.github.com/rest/reference/pulls#list-reviews-for-a-pull-request */ "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews": { parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"]["response"]; }; /** * @see https://docs.github.com/rest/reference/pulls#list-comments-for-a-pull-request-review */ "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments": { parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-releases */ "GET /repos/{owner}/{repo}/releases": { parameters: Endpoints["GET /repos/{owner}/{repo}/releases"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/releases"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-release-assets */ "GET /repos/{owner}/{repo}/releases/{release_id}/assets": { parameters: Endpoints["GET /repos/{owner}/{repo}/releases/{release_id}/assets"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/releases/{release_id}/assets"]["response"]; }; /** * @see https://docs.github.com/rest/reference/secret-scanning#list-secret-scanning-alerts-for-a-repository */ "GET /repos/{owner}/{repo}/secret-scanning/alerts": { parameters: Endpoints["GET /repos/{owner}/{repo}/secret-scanning/alerts"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/secret-scanning/alerts"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-stargazers */ "GET /repos/{owner}/{repo}/stargazers": { parameters: Endpoints["GET /repos/{owner}/{repo}/stargazers"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/stargazers"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-watchers */ "GET /repos/{owner}/{repo}/subscribers": { parameters: Endpoints["GET /repos/{owner}/{repo}/subscribers"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/subscribers"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-repository-tags */ "GET /repos/{owner}/{repo}/tags": { parameters: Endpoints["GET /repos/{owner}/{repo}/tags"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/tags"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-repository-teams */ "GET /repos/{owner}/{repo}/teams": { parameters: Endpoints["GET /repos/{owner}/{repo}/teams"]["parameters"]; response: Endpoints["GET /repos/{owner}/{repo}/teams"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-public-repositories */ "GET /repositories": { parameters: Endpoints["GET /repositories"]["parameters"]; response: Endpoints["GET /repositories"]["response"]; }; /** * @see https://docs.github.com/rest/reference/actions#list-environment-secrets */ "GET /repositories/{repository_id}/environments/{environment_name}/secrets": { parameters: Endpoints["GET /repositories/{repository_id}/environments/{environment_name}/secrets"]["parameters"]; response: Endpoints["GET /repositories/{repository_id}/environments/{environment_name}/secrets"]["response"] & { data: Endpoints["GET /repositories/{repository_id}/environments/{environment_name}/secrets"]["response"]["data"]["secrets"]; }; }; /** * @see https://docs.github.com/rest/reference/enterprise-admin#list-provisioned-scim-groups-for-an-enterprise */ "GET /scim/v2/enterprises/{enterprise}/Groups": { parameters: Endpoints["GET /scim/v2/enterprises/{enterprise}/Groups"]["parameters"]; response: Endpoints["GET /scim/v2/enterprises/{enterprise}/Groups"]["response"] & { data: Endpoints["GET /scim/v2/enterprises/{enterprise}/Groups"]["response"]["data"]["Resources"]; }; }; /** * @see https://docs.github.com/rest/reference/enterprise-admin#list-scim-provisioned-identities-for-an-enterprise */ "GET /scim/v2/enterprises/{enterprise}/Users": { parameters: Endpoints["GET /scim/v2/enterprises/{enterprise}/Users"]["parameters"]; response: Endpoints["GET /scim/v2/enterprises/{enterprise}/Users"]["response"] & { data: Endpoints["GET /scim/v2/enterprises/{enterprise}/Users"]["response"]["data"]["Resources"]; }; }; /** * @see https://docs.github.com/rest/reference/scim#list-scim-provisioned-identities */ "GET /scim/v2/organizations/{org}/Users": { parameters: Endpoints["GET /scim/v2/organizations/{org}/Users"]["parameters"]; response: Endpoints["GET /scim/v2/organizations/{org}/Users"]["response"] & { data: Endpoints["GET /scim/v2/organizations/{org}/Users"]["response"]["data"]["Resources"]; }; }; /** * @see https://docs.github.com/rest/reference/search#search-code */ "GET /search/code": { parameters: Endpoints["GET /search/code"]["parameters"]; response: Endpoints["GET /search/code"]["response"] & { data: Endpoints["GET /search/code"]["response"]["data"]["items"]; }; }; /** * @see https://docs.github.com/rest/reference/search#search-commits */ "GET /search/commits": { parameters: Endpoints["GET /search/commits"]["parameters"]; response: Endpoints["GET /search/commits"]["response"] & { data: Endpoints["GET /search/commits"]["response"]["data"]["items"]; }; }; /** * @see https://docs.github.com/rest/reference/search#search-issues-and-pull-requests */ "GET /search/issues": { parameters: Endpoints["GET /search/issues"]["parameters"]; response: Endpoints["GET /search/issues"]["response"] & { data: Endpoints["GET /search/issues"]["response"]["data"]["items"]; }; }; /** * @see https://docs.github.com/rest/reference/search#search-labels */ "GET /search/labels": { parameters: Endpoints["GET /search/labels"]["parameters"]; response: Endpoints["GET /search/labels"]["response"] & { data: Endpoints["GET /search/labels"]["response"]["data"]["items"]; }; }; /** * @see https://docs.github.com/rest/reference/search#search-repositories */ "GET /search/repositories": { parameters: Endpoints["GET /search/repositories"]["parameters"]; response: Endpoints["GET /search/repositories"]["response"] & { data: Endpoints["GET /search/repositories"]["response"]["data"]["items"]; }; }; /** * @see https://docs.github.com/rest/reference/search#search-topics */ "GET /search/topics": { parameters: Endpoints["GET /search/topics"]["parameters"]; response: Endpoints["GET /search/topics"]["response"] & { data: Endpoints["GET /search/topics"]["response"]["data"]["items"]; }; }; /** * @see https://docs.github.com/rest/reference/search#search-users */ "GET /search/users": { parameters: Endpoints["GET /search/users"]["parameters"]; response: Endpoints["GET /search/users"]["response"] & { data: Endpoints["GET /search/users"]["response"]["data"]["items"]; }; }; /** * @see https://docs.github.com/rest/reference/teams#list-discussions-legacy */ "GET /teams/{team_id}/discussions": { parameters: Endpoints["GET /teams/{team_id}/discussions"]["parameters"]; response: Endpoints["GET /teams/{team_id}/discussions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-discussion-comments-legacy */ "GET /teams/{team_id}/discussions/{discussion_number}/comments": { parameters: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/comments"]["parameters"]; response: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/comments"]["response"]; }; /** * @see https://docs.github.com/rest/reference/reactions/#list-reactions-for-a-team-discussion-comment-legacy */ "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions": { parameters: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions"]["parameters"]; response: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/reactions/#list-reactions-for-a-team-discussion-legacy */ "GET /teams/{team_id}/discussions/{discussion_number}/reactions": { parameters: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/reactions"]["parameters"]; response: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/reactions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-pending-team-invitations-legacy */ "GET /teams/{team_id}/invitations": { parameters: Endpoints["GET /teams/{team_id}/invitations"]["parameters"]; response: Endpoints["GET /teams/{team_id}/invitations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-team-members-legacy */ "GET /teams/{team_id}/members": { parameters: Endpoints["GET /teams/{team_id}/members"]["parameters"]; response: Endpoints["GET /teams/{team_id}/members"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams/#list-team-projects-legacy */ "GET /teams/{team_id}/projects": { parameters: Endpoints["GET /teams/{team_id}/projects"]["parameters"]; response: Endpoints["GET /teams/{team_id}/projects"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams/#list-team-repositories-legacy */ "GET /teams/{team_id}/repos": { parameters: Endpoints["GET /teams/{team_id}/repos"]["parameters"]; response: Endpoints["GET /teams/{team_id}/repos"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-idp-groups-for-a-team-legacy */ "GET /teams/{team_id}/team-sync/group-mappings": { parameters: Endpoints["GET /teams/{team_id}/team-sync/group-mappings"]["parameters"]; response: Endpoints["GET /teams/{team_id}/team-sync/group-mappings"]["response"] & { data: Endpoints["GET /teams/{team_id}/team-sync/group-mappings"]["response"]["data"]["groups"]; }; }; /** * @see https://docs.github.com/rest/reference/teams/#list-child-teams-legacy */ "GET /teams/{team_id}/teams": { parameters: Endpoints["GET /teams/{team_id}/teams"]["parameters"]; response: Endpoints["GET /teams/{team_id}/teams"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-users-blocked-by-the-authenticated-user */ "GET /user/blocks": { parameters: Endpoints["GET /user/blocks"]["parameters"]; response: Endpoints["GET /user/blocks"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-email-addresses-for-the-authenticated-user */ "GET /user/emails": { parameters: Endpoints["GET /user/emails"]["parameters"]; response: Endpoints["GET /user/emails"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-followers-of-the-authenticated-user */ "GET /user/followers": { parameters: Endpoints["GET /user/followers"]["parameters"]; response: Endpoints["GET /user/followers"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-the-people-the-authenticated-user-follows */ "GET /user/following": { parameters: Endpoints["GET /user/following"]["parameters"]; response: Endpoints["GET /user/following"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-gpg-keys-for-the-authenticated-user */ "GET /user/gpg_keys": { parameters: Endpoints["GET /user/gpg_keys"]["parameters"]; response: Endpoints["GET /user/gpg_keys"]["response"]; }; /** * @see https://docs.github.com/rest/reference/apps#list-app-installations-accessible-to-the-user-access-token */ "GET /user/installations": { parameters: Endpoints["GET /user/installations"]["parameters"]; response: Endpoints["GET /user/installations"]["response"] & { data: Endpoints["GET /user/installations"]["response"]["data"]["installations"]; }; }; /** * @see https://docs.github.com/rest/reference/apps#list-repositories-accessible-to-the-user-access-token */ "GET /user/installations/{installation_id}/repositories": { parameters: Endpoints["GET /user/installations/{installation_id}/repositories"]["parameters"]; response: Endpoints["GET /user/installations/{installation_id}/repositories"]["response"] & { data: Endpoints["GET /user/installations/{installation_id}/repositories"]["response"]["data"]["repositories"]; }; }; /** * @see https://docs.github.com/rest/reference/issues#list-user-account-issues-assigned-to-the-authenticated-user */ "GET /user/issues": { parameters: Endpoints["GET /user/issues"]["parameters"]; response: Endpoints["GET /user/issues"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-public-ssh-keys-for-the-authenticated-user */ "GET /user/keys": { parameters: Endpoints["GET /user/keys"]["parameters"]; response: Endpoints["GET /user/keys"]["response"]; }; /** * @see https://docs.github.com/rest/reference/apps#list-subscriptions-for-the-authenticated-user */ "GET /user/marketplace_purchases": { parameters: Endpoints["GET /user/marketplace_purchases"]["parameters"]; response: Endpoints["GET /user/marketplace_purchases"]["response"]; }; /** * @see https://docs.github.com/rest/reference/apps#list-subscriptions-for-the-authenticated-user-stubbed */ "GET /user/marketplace_purchases/stubbed": { parameters: Endpoints["GET /user/marketplace_purchases/stubbed"]["parameters"]; response: Endpoints["GET /user/marketplace_purchases/stubbed"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-organization-memberships-for-the-authenticated-user */ "GET /user/memberships/orgs": { parameters: Endpoints["GET /user/memberships/orgs"]["parameters"]; response: Endpoints["GET /user/memberships/orgs"]["response"]; }; /** * @see https://docs.github.com/rest/reference/migrations#list-user-migrations */ "GET /user/migrations": { parameters: Endpoints["GET /user/migrations"]["parameters"]; response: Endpoints["GET /user/migrations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/migrations#list-repositories-for-a-user-migration */ "GET /user/migrations/{migration_id}/repositories": { parameters: Endpoints["GET /user/migrations/{migration_id}/repositories"]["parameters"]; response: Endpoints["GET /user/migrations/{migration_id}/repositories"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-organizations-for-the-authenticated-user */ "GET /user/orgs": { parameters: Endpoints["GET /user/orgs"]["parameters"]; response: Endpoints["GET /user/orgs"]["response"]; }; /** * @see https://docs.github.com/rest/reference/packages#list-packages-for-the-authenticated-user */ "GET /user/packages": { parameters: Endpoints["GET /user/packages"]["parameters"]; response: Endpoints["GET /user/packages"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-public-email-addresses-for-the-authenticated-user */ "GET /user/public_emails": { parameters: Endpoints["GET /user/public_emails"]["parameters"]; response: Endpoints["GET /user/public_emails"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-repositories-for-the-authenticated-user */ "GET /user/repos": { parameters: Endpoints["GET /user/repos"]["parameters"]; response: Endpoints["GET /user/repos"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-repository-invitations-for-the-authenticated-user */ "GET /user/repository_invitations": { parameters: Endpoints["GET /user/repository_invitations"]["parameters"]; response: Endpoints["GET /user/repository_invitations"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-repositories-starred-by-the-authenticated-user */ "GET /user/starred": { parameters: Endpoints["GET /user/starred"]["parameters"]; response: Endpoints["GET /user/starred"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-repositories-watched-by-the-authenticated-user */ "GET /user/subscriptions": { parameters: Endpoints["GET /user/subscriptions"]["parameters"]; response: Endpoints["GET /user/subscriptions"]["response"]; }; /** * @see https://docs.github.com/rest/reference/teams#list-teams-for-the-authenticated-user */ "GET /user/teams": { parameters: Endpoints["GET /user/teams"]["parameters"]; response: Endpoints["GET /user/teams"]["response"]; }; /** * @see https://docs.github.com/rest/reference/packages#list-packages-for-user */ "GET /user/{username}/packages": { parameters: Endpoints["GET /user/{username}/packages"]["parameters"]; response: Endpoints["GET /user/{username}/packages"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-users */ "GET /users": { parameters: Endpoints["GET /users"]["parameters"]; response: Endpoints["GET /users"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-events-for-the-authenticated-user */ "GET /users/{username}/events": { parameters: Endpoints["GET /users/{username}/events"]["parameters"]; response: Endpoints["GET /users/{username}/events"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-organization-events-for-the-authenticated-user */ "GET /users/{username}/events/orgs/{org}": { parameters: Endpoints["GET /users/{username}/events/orgs/{org}"]["parameters"]; response: Endpoints["GET /users/{username}/events/orgs/{org}"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-public-events-for-a-user */ "GET /users/{username}/events/public": { parameters: Endpoints["GET /users/{username}/events/public"]["parameters"]; response: Endpoints["GET /users/{username}/events/public"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-followers-of-a-user */ "GET /users/{username}/followers": { parameters: Endpoints["GET /users/{username}/followers"]["parameters"]; response: Endpoints["GET /users/{username}/followers"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-the-people-a-user-follows */ "GET /users/{username}/following": { parameters: Endpoints["GET /users/{username}/following"]["parameters"]; response: Endpoints["GET /users/{username}/following"]["response"]; }; /** * @see https://docs.github.com/rest/reference/gists#list-gists-for-a-user */ "GET /users/{username}/gists": { parameters: Endpoints["GET /users/{username}/gists"]["parameters"]; response: Endpoints["GET /users/{username}/gists"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-gpg-keys-for-a-user */ "GET /users/{username}/gpg_keys": { parameters: Endpoints["GET /users/{username}/gpg_keys"]["parameters"]; response: Endpoints["GET /users/{username}/gpg_keys"]["response"]; }; /** * @see https://docs.github.com/rest/reference/users#list-public-keys-for-a-user */ "GET /users/{username}/keys": { parameters: Endpoints["GET /users/{username}/keys"]["parameters"]; response: Endpoints["GET /users/{username}/keys"]["response"]; }; /** * @see https://docs.github.com/rest/reference/orgs#list-organizations-for-a-user */ "GET /users/{username}/orgs": { parameters: Endpoints["GET /users/{username}/orgs"]["parameters"]; response: Endpoints["GET /users/{username}/orgs"]["response"]; }; /** * @see https://docs.github.com/rest/reference/projects#list-user-projects */ "GET /users/{username}/projects": { parameters: Endpoints["GET /users/{username}/projects"]["parameters"]; response: Endpoints["GET /users/{username}/projects"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-events-received-by-the-authenticated-user */ "GET /users/{username}/received_events": { parameters: Endpoints["GET /users/{username}/received_events"]["parameters"]; response: Endpoints["GET /users/{username}/received_events"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-public-events-received-by-a-user */ "GET /users/{username}/received_events/public": { parameters: Endpoints["GET /users/{username}/received_events/public"]["parameters"]; response: Endpoints["GET /users/{username}/received_events/public"]["response"]; }; /** * @see https://docs.github.com/rest/reference/repos#list-repositories-for-a-user */ "GET /users/{username}/repos": { parameters: Endpoints["GET /users/{username}/repos"]["parameters"]; response: Endpoints["GET /users/{username}/repos"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-repositories-starred-by-a-user */ "GET /users/{username}/starred": { parameters: Endpoints["GET /users/{username}/starred"]["parameters"]; response: Endpoints["GET /users/{username}/starred"]["response"]; }; /** * @see https://docs.github.com/rest/reference/activity#list-repositories-watched-by-a-user */ "GET /users/{username}/subscriptions": { parameters: Endpoints["GET /users/{username}/subscriptions"]["parameters"]; response: Endpoints["GET /users/{username}/subscriptions"]["response"]; }; } export declare const paginatingEndpoints: (keyof PaginatingEndpoints)[];
the_stack
module ts { export var optionDeclarations: CommandLineOption[] = [ { name: "charset", type: "string", }, { name: "codepage", type: "number", }, { name: "declaration", shortName: "d", type: "boolean", description: Diagnostics.Generates_corresponding_d_ts_file, }, { name: "diagnostics", type: "boolean", }, { name: "emitBOM", type: "boolean" }, { name: "help", shortName: "h", type: "boolean", description: Diagnostics.Print_this_message, }, { name: "listFiles", type: "boolean", }, { name: "locale", type: "string", }, { name: "mapRoot", type: "string", isFilePath: true, description: Diagnostics.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, paramType: Diagnostics.LOCATION, }, { name: "module", shortName: "m", type: { "commonjs": ModuleKind.CommonJS, "amd": ModuleKind.AMD }, description: Diagnostics.Specify_module_code_generation_Colon_commonjs_or_amd, paramType: Diagnostics.KIND, error: Diagnostics.Argument_for_module_option_must_be_commonjs_or_amd }, { name: "noEmit", type: "boolean", description: Diagnostics.Do_not_emit_outputs, }, { name: "noEmitOnError", type: "boolean", description: Diagnostics.Do_not_emit_outputs_if_any_type_checking_errors_were_reported, }, { name: "noImplicitAny", type: "boolean", description: Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, { name: "noLib", type: "boolean", }, { name: "noLibCheck", type: "boolean", }, { name: "noResolve", type: "boolean", }, { name: "out", type: "string", description: Diagnostics.Concatenate_and_emit_output_to_single_file, paramType: Diagnostics.FILE, }, { name: "outDir", type: "string", isFilePath: true, description: Diagnostics.Redirect_output_structure_to_the_directory, paramType: Diagnostics.DIRECTORY, }, { name: "preserveConstEnums", type: "boolean", description: Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code }, { name: "project", shortName: "p", type: "string", isFilePath: true, description: Diagnostics.Compile_the_project_in_the_given_directory, paramType: Diagnostics.DIRECTORY }, { name: "removeComments", type: "boolean", description: Diagnostics.Do_not_emit_comments_to_output, }, { name: "sourceMap", type: "boolean", description: Diagnostics.Generates_corresponding_map_file, }, { name: "sourceRoot", type: "string", isFilePath: true, description: Diagnostics.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, paramType: Diagnostics.LOCATION, }, { name: "suppressImplicitAnyIndexErrors", type: "boolean", description: Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, { name: "target", shortName: "t", type: { "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5, "es6": ScriptTarget.ES6 }, description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental, paramType: Diagnostics.VERSION, error: Diagnostics.Argument_for_target_option_must_be_es3_es5_or_es6 }, { name: "version", shortName: "v", type: "boolean", description: Diagnostics.Print_the_compiler_s_version, }, { name: "watch", shortName: "w", type: "boolean", description: Diagnostics.Watch_input_files, } ]; export function parseCommandLine(commandLine: string[]): ParsedCommandLine { var options: CompilerOptions = {}; var filenames: string[] = []; var errors: Diagnostic[] = []; var shortOptionNames: Map<string> = {}; var optionNameMap: Map<CommandLineOption> = {}; forEach(optionDeclarations, option => { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { shortOptionNames[option.shortName] = option.name; } }); parseStrings(commandLine); return { options, filenames, errors }; function parseStrings(args: string[]) { var i = 0; while (i < args.length) { var s = args[i++]; if (s.charCodeAt(0) === CharacterCodes.at) { parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === CharacterCodes.minus) { s = s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase(); // Try to translate short option names to their full equivalents. if (hasProperty(shortOptionNames, s)) { s = shortOptionNames[s]; } if (hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); } switch (opt.type) { case "number": options[opt.name] = parseInt(args[i++]); break; case "boolean": options[opt.name] = true; break; case "string": options[opt.name] = args[i++] || ""; break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: var map = <Map<number>>opt.type; var key = (args[i++] || "").toLowerCase(); if (hasProperty(map, key)) { options[opt.name] = map[key]; } else { errors.push(createCompilerDiagnostic(opt.error)); } } } else { errors.push(createCompilerDiagnostic(Diagnostics.Unknown_compiler_option_0, s)); } } else { filenames.push(s); } } } function parseResponseFile(filename: string) { var text = sys.readFile(filename); if (!text) { errors.push(createCompilerDiagnostic(Diagnostics.File_0_not_found, filename)); return; } var args: string[] = []; var pos = 0; while (true) { while (pos < text.length && text.charCodeAt(pos) <= CharacterCodes.space) pos++; if (pos >= text.length) break; var start = pos; if (text.charCodeAt(start) === CharacterCodes.doubleQuote) { pos++; while (pos < text.length && text.charCodeAt(pos) !== CharacterCodes.doubleQuote) pos++; if (pos < text.length) { args.push(text.substring(start + 1, pos)); pos++; } else { errors.push(createCompilerDiagnostic(Diagnostics.Unterminated_quoted_string_in_response_file_0, filename)); } } else { while (text.charCodeAt(pos) > CharacterCodes.space) pos++; args.push(text.substring(start, pos)); } } parseStrings(args); } } export function readConfigFile(filename: string): any { try { var text = sys.readFile(filename); return /\S/.test(text) ? JSON.parse(text) : {}; } catch (e) { } } export function parseConfigFile(json: any, basePath?: string): ParsedCommandLine { var errors: Diagnostic[] = []; return { options: getCompilerOptions(), filenames: getFiles(), errors }; function getCompilerOptions(): CompilerOptions { var options: CompilerOptions = {}; var optionNameMap: Map<CommandLineOption> = {}; forEach(optionDeclarations, option => { optionNameMap[option.name] = option; }); var jsonOptions = json["compilerOptions"]; if (jsonOptions) { for (var id in jsonOptions) { if (hasProperty(optionNameMap, id)) { var opt = optionNameMap[id]; var optType = opt.type; var value = jsonOptions[id]; var expectedType = typeof optType === "string" ? optType : "string"; if (typeof value === expectedType) { if (typeof optType !== "string") { var key = value.toLowerCase(); if (hasProperty(optType, key)) { value = optType[key]; } else { errors.push(createCompilerDiagnostic(opt.error)); value = 0; } } if (opt.isFilePath) { value = normalizePath(combinePaths(basePath, value)); } options[opt.name] = value; } else { errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, id, expectedType)); } } else { errors.push(createCompilerDiagnostic(Diagnostics.Unknown_compiler_option_0, id)); } } } return options; } function getFiles(): string[] { var files: string[] = []; if (hasProperty(json, "files")) { if (json["files"] instanceof Array) { var files = map(<string[]>json["files"], s => combinePaths(basePath, s)); } } else { var sysFiles = sys.readDirectory(basePath, ".ts"); for (var i = 0; i < sysFiles.length; i++) { var name = sysFiles[i]; if (!fileExtensionIs(name, ".d.ts") || !contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) { files.push(name); } } } return files; } } }
the_stack
'use strict'; import request = require('request'); import { sleep } from '../utils'; import { HappeningType, HelpfulAction, search } from 'pddl-workspace'; import { DEFAULT_EPSILON } from '../configuration/configuration'; export class MockSearch { url: string; constructor(port: number) { this.url = `http://localhost:${port}`; } async run(): Promise<void> { const helloWorld = await new Promise<string>((resolve, reject) => { request.get(this.url + '/about', (error, httpResponse, httpBody) => { if (error) { reject(error); return; } else { if (httpResponse && httpResponse.statusCode > 204) { reject("HTTP status code " + httpResponse.statusCode); return; } else { resolve(httpBody); } } }); }); console.log(helloWorld); for (const mockEvent of this.events) { console.log("sending mock event: "); console.log(mockEvent); await sleep(100); try { await this.send(mockEvent); } catch (ex) { console.log(ex); break; } } console.log('Mock-search finished.'); } private async send(mockEvent: MockEvent): Promise<void> { switch (mockEvent.operation) { case 'post-initial': return await this.post('/state/initial', mockEvent.toWireMessage()); case 'post': return await this.post('/state', mockEvent.toWireMessage()); case 'patch': // this should really be a 'patch' verb, but the clients have more trouble making it work return await this.post('/state/heuristic', mockEvent.toWireMessage()); default: console.log("Unsupported mock event: " + mockEvent.operation); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any private async post(path: string, content: any): Promise<void> { return await new Promise<void>((resolve, reject) => { request.post(this.url + path, { json: content }, (error, httpResponse) => { if (error) { reject(error); return; } else { if (httpResponse && httpResponse.statusCode > 204) { reject('HTTP status code ' + httpResponse.statusCode); return; } else { resolve(void 0); } } }); }); } /** * the `patch` method will be useful when the contract migrates `patch` HTTP verb. */ // private async patch(path: string, content: any): Promise<void> { // return await new Promise<void>((resolve, reject) => { // request.patch(this.url + path, { json: content }, (error, httpResponse, _httpBody) => { // if (error) { // reject(error); // } // else { // if (httpResponse && httpResponse.statusCode > 204) { // reject('HTTP status code ' + httpResponse.statusCode); // } // else { // resolve(void 0); // } // } // }); // }); // } private state0: MockStateContext | undefined = undefined; private state0_0: MockStateContext | undefined = undefined; private state0_1: MockStateContext | undefined = undefined; private state0_0_0: MockStateContext | undefined = undefined; private state0_0_1: MockStateContext | undefined = undefined; private state0_1_0: MockStateContext | undefined = undefined; private state0_1_1: MockStateContext | undefined = undefined; private state0_1_0_0: MockStateContext | undefined = undefined; private state0_1_0_0_0: MockStateContext | undefined = undefined; private readonly events = [ new MockStateContextEvent("post-initial", this.state0 = MockStateContext.createInitial()), new MockStateSearchContextEvent("patch", this.state0.evaluate(5, [MockHelpfulAction.start("drive"), MockHelpfulAction.start("load")], state => state.buildRelaxedPlan().start("drive").start("load").end(1, "load").end(3, "drive"))), new MockStateContextEvent("post", this.state0_0 = this.state0.applyStart("drive", 0)), new MockStateContextEvent("post", this.state0_1 = this.state0.applyStart("load", 0)), new MockStateSearchContextEvent("patch", this.state0_0.evaluate(5, [MockHelpfulAction.start("load"), MockHelpfulAction.end("drive")], state => state.buildRelaxedPlan().end(4, "drive").start("load").end(1, "load"))), new MockStateSearchContextEvent("patch", this.state0_1.evaluate(4, [MockHelpfulAction.start("drive"), MockHelpfulAction.end("load")], state => state.buildRelaxedPlan().end(1, "load").start("drive").end(4, "drive"))), new MockStateContextEvent("post", this.state0_0_0 = this.state0_0.applyEnd("drive", 0, 3)), new MockStateContextEvent("post", this.state0_0_1 = this.state0_0.applyStart("load", 0)), new MockStateSearchContextEvent("patch", this.state0_0_0.evaluate(4, [MockHelpfulAction.start("load")], state => state.buildRelaxedPlan().start("load").end(1, "load"))), new MockStateSearchContextEvent("patch", this.state0_0_1.evaluate(3, [MockHelpfulAction.end("load"), MockHelpfulAction.end("drive")], state => state.buildRelaxedPlan().end(4, "drive").end(1, "load"))), new MockStateContextEvent("post", this.state0_1_0 = this.state0_1.applyEnd("load", 0, .5)), new MockStateContextEvent("post", this.state0_1_1 = this.state0_1.applyStart("drive", 0)), new MockStateSearchContextEvent("patch", this.state0_1_0.evaluate(2, [MockHelpfulAction.start("drive")], state => state.buildRelaxedPlan().start("drive").end(4, "drive"))), new MockStateSearchContextEvent("patch", this.state0_1_1.evaluate(3, [MockHelpfulAction.end("drive"), MockHelpfulAction.end("load")], state => state.buildRelaxedPlan().end(4, "drive").end(1, "load"))), new MockStateContextEvent("post", this.state0_1_0_0 = this.state0_1_0.applyStart("drive", 0)), new MockStateSearchContextEvent("patch", this.state0_1_0_0.evaluate(1, [MockHelpfulAction.end("drive")], state => state.buildRelaxedPlan().end(4, "drive"))), new MockStateContextEvent("post", this.state0_1_0_0_0 = this.state0_1_0_0.applyEnd("drive", 0, 4)), new MockStateSearchContextEvent("patch", this.state0_1_0_0_0.evaluate(0, [], state => state.buildRelaxedPlan())), ]; } abstract class MockEvent { constructor(public readonly operation: string) { } // eslint-disable-next-line @typescript-eslint/no-explicit-any abstract toWireMessage(): any; } class MockStateContextEvent extends MockEvent { constructor(readonly operation: string, public readonly stateContext: MockStateContext) { super(operation); } // eslint-disable-next-line @typescript-eslint/no-explicit-any toWireMessage(): any { return { id: this.stateContext.state.id, parentId: this.stateContext.parentId, g: this.stateContext.g, earliestTime: this.stateContext.earliestTime, appliedAction: this.stateContext.appliedAction ? toWireSearchHappening(this.stateContext.appliedAction) : null, planHead: this.stateContext.planHead.map(h => toWireSearchHappening(h)) }; } } class MockStateSearchContextEvent extends MockEvent { constructor(readonly operation: string, public readonly stateSearchContext: MockStateSearchContext) { super(operation); } // eslint-disable-next-line @typescript-eslint/no-explicit-any toWireMessage(): any { return { id: this.stateSearchContext.stateContext.state.id, totalMakespan: this.stateSearchContext.totalMakespan, h: this.stateSearchContext.h, helpfulActions: this.stateSearchContext.helpfulActions.map(a => toWireHelpfulAction(a)), relaxedPlan: this.stateSearchContext.relaxedPlan.map(h => toWireSearchHappening(h)) }; } } // eslint-disable-next-line @typescript-eslint/no-explicit-any function toWireSearchHappening(happening: search.SearchHappening): any { return { earliestTime: happening.earliestTime, actionName: happening.actionName, shotCounter: happening.shotCounter, kind: HappeningType[happening.kind] }; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function toWireHelpfulAction(action: HelpfulAction): any { return { actionName: action.actionName, kind: HappeningType[action.kind] }; } class MockStateSearchContext { constructor(public readonly stateContext: MockStateContext, public readonly totalMakespan: number, public readonly h: number, public readonly helpfulActions: HelpfulAction[], public readonly relaxedPlan: search.SearchHappening[]) { } } class MockStateContext { static createInitial(): MockStateContext { return new MockStateContext(MockState.createInitial(), 0, EPSILON, undefined, [], undefined); } constructor(public readonly state: MockState, public readonly g: number, public readonly earliestTime: number, public readonly appliedAction: MockSearchHappening | undefined, public readonly planHead: search.SearchHappening[], public readonly parentId?: string) { } get actionName(): string | undefined{ return this.appliedAction?.actionName; } isInitialState(): boolean { return this.planHead.length === 0; } getLastHappening(): search.SearchHappening { if (this.isInitialState()) { throw new Error("Check if this is an initial state first.."); } return this.planHead[this.planHead.length - 1]; } applyStart(actionName: string, shotCounter: number): MockStateContext { return this.apply(actionName, shotCounter, HappeningType.START, EPSILON); } applyEnd(actionName: string, shotCounter: number, duration: number): MockStateContext { return this.apply(actionName, shotCounter, HappeningType.END, duration); } apply(actionName: string, shotCounter: number, kind: HappeningType, timeIncrement: number): MockStateContext { const id = ++MockState.lastStateId; const earliestTime = this.earliestTime + timeIncrement; const appliedAction = new MockSearchHappening(earliestTime, actionName, shotCounter, 1, kind, false); const newPlanHead = this.planHead.concat([appliedAction]); return new MockStateContext(new MockState(id.toString()), this.g + 1, earliestTime, appliedAction, newPlanHead, this.state.id); } evaluate(h: number, helpfulActions: HelpfulAction[], relaxedPlanFactory: (stateContext: MockStateContext) => RelaxedPlanBuilder): MockStateSearchContext { const relaxedStateBuilder: RelaxedPlanBuilder = relaxedPlanFactory(this); const relaxedPlan = relaxedStateBuilder.build(); const totalMakespan = relaxedPlan.length ? Math.max(...relaxedPlan.map(step => step.earliestTime)) : this.earliestTime; const newState = new MockStateSearchContext(this, totalMakespan, h, helpfulActions, relaxedPlan); return newState; } buildRelaxedPlan(): RelaxedPlanBuilder { return new RelaxedPlanBuilder(this.earliestTime); } toString(): string { return `State={id: ${this.state.id}, G: ${this.g}}`; } } class MockState { constructor(public readonly id: string) { } static createInitial(): MockState { const id = ++this.lastStateId; return new MockState(id.toString()); } static lastStateId = -1; } const EPSILON = DEFAULT_EPSILON; class RelaxedPlanBuilder { happenings: search.SearchHappening[] = []; time: number; constructor(private readonly earliestStateTime: number) { this.time = this.earliestStateTime; } start(actionName: string): RelaxedPlanBuilder { const time = this.time += EPSILON; this.happenings.push(new MockSearchHappening(time, actionName, 0, 1, HappeningType.START, true)); return this; } end(timeOffset: number, actionName: string): RelaxedPlanBuilder { const time = this.time += timeOffset; this.happenings.push(new MockSearchHappening(time, actionName, 0, 1, HappeningType.END, true)); return this; } build(): search.SearchHappening[] { return this.happenings; } } class MockSearchHappening implements search.SearchHappening{ constructor(public readonly earliestTime: number, public readonly actionName: string, public readonly shotCounter: number, public readonly iterations: number, public readonly kind: HappeningType, public readonly isRelaxed: boolean) { } toString(): string { const relaxed = this.isRelaxed ? '*' : ''; const iterations = this.iterations > 1 ? ` ${this.iterations}x` : ''; return `${this.earliestTime}: ${this.actionName}[${this.shotCounter}] ${this.kind}${relaxed}${iterations}`; } } class MockHelpfulAction implements HelpfulAction { constructor(public readonly actionName: string, public readonly kind: HappeningType) { } static start(actionName: string): MockHelpfulAction { return new MockHelpfulAction(actionName, HappeningType.START); } static end(actionName: string): MockHelpfulAction { return new MockHelpfulAction(actionName, HappeningType.END); } }
the_stack
import test from 'japa' import { BelongsTo } from '@ioc:Adonis/Lucid/Orm' import { ApplicationContract } from '@ioc:Adonis/Core/Application' import { FactoryManager } from '../../src/Factory/index' import { column, belongsTo } from '../../src/Orm/Decorators' import { fs, setup, getDb, cleanup, ormAdapter, resetTables, getBaseModel, setupApplication, getFactoryModel, } from '../../test-helpers' let db: ReturnType<typeof getDb> let app: ApplicationContract let BaseModel: ReturnType<typeof getBaseModel> const FactoryModel = getFactoryModel() const factoryManager = new FactoryManager() test.group('Factory | BelongTo | make', (group) => { group.before(async () => { app = await setupApplication() db = getDb(app) BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.after(async () => { await db.manager.closeAll() await cleanup() await fs.cleanup() }) group.afterEach(async () => { await resetTables() }) test('make model with relationship', async (assert) => { class Profile extends BaseModel { @column() public id: number @column() public userId: number @column() public displayName: string @belongsTo(() => User) public user: BelongsTo<typeof User> } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) public id: number @column() public username: string @column() public points: number = 0 } const profileFactory = new FactoryModel( Profile, () => { return { displayName: 'virk', } }, factoryManager ) .relation('user', () => factory) .build() const factory = new FactoryModel( User, () => { return {} }, factoryManager ).build() const profile = await profileFactory.with('user').makeStubbed() assert.exists(profile.id) assert.isFalse(profile.$isPersisted) assert.exists(profile.user.id) assert.instanceOf(profile.user, User) assert.isFalse(profile.user.$isPersisted) assert.equal(profile.user.id, profile.userId) }) test('pass custom attributes to the relationship', async (assert) => { class Profile extends BaseModel { @column() public id: number @column() public userId: number @column() public displayName: string @belongsTo(() => User) public user: BelongsTo<typeof User> } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) public id: number @column() public username: string @column() public points: number = 0 } const profileFactory = new FactoryModel( Profile, () => { return { displayName: 'virk', } }, factoryManager ) .relation('user', () => factory) .build() const factory = new FactoryModel( User, () => { return { points: 0, } }, factoryManager ).build() const profile = await profileFactory .with('user', 1, (related) => related.merge({ points: 10 })) .makeStubbed() assert.exists(profile.id) assert.isFalse(profile.$isPersisted) assert.instanceOf(profile.user, User) assert.exists(profile.user.id) assert.isFalse(profile.user.$isPersisted) assert.equal(profile.user.id, profile.userId) assert.equal(profile.user.points, 10) }) test('invoke make hook on the related factory', async (assert) => { class Profile extends BaseModel { @column() public id: number @column() public userId: number @column() public displayName: string @belongsTo(() => User) public user: BelongsTo<typeof User> } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) public id: number @column() public username: string @column() public points: number = 0 } User.boot() const profileFactory = new FactoryModel( Profile, () => { return { displayName: 'virk', } }, factoryManager ) .relation('user', () => factory) .build() const factory = new FactoryModel( User, () => { return { points: 0, } }, factoryManager ) .after('make', (_, user) => { user.id = 100 }) .build() const profile = await profileFactory .with('user', 1, (related) => related.merge({ points: 10 })) .makeStubbed() assert.exists(profile.id) assert.isFalse(profile.$isPersisted) assert.instanceOf(profile.user, User) assert.exists(profile.user.id) assert.equal(profile.user.points, 10) assert.isFalse(profile.user.$isPersisted) assert.equal(profile.userId, 100) assert.equal(profile.user.id, 100) }) }) test.group('Factory | BelongTo | create', (group) => { group.before(async () => { app = await setupApplication() db = getDb(app) BaseModel = getBaseModel(ormAdapter(db), app) await setup() }) group.after(async () => { await db.manager.closeAll() await cleanup() await fs.cleanup() }) group.afterEach(async () => { await resetTables() }) test('create model with relationship', async (assert) => { class Profile extends BaseModel { @column() public userId: number @column() public displayName: string @belongsTo(() => User) public user: BelongsTo<typeof User> } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) public id: number @column() public username: string @column() public points: number = 0 } const profileFactory = new FactoryModel( Profile, () => { return { displayName: 'virk', } }, factoryManager ) .relation('user', () => factory) .build() const factory = new FactoryModel( User, () => { return {} }, factoryManager ).build() const profile = await profileFactory.with('user').create() assert.isTrue(profile.$isPersisted) assert.instanceOf(profile.user, User) assert.isTrue(profile.user.$isPersisted) assert.equal(profile.user.id, profile.userId) const users = await db.from('users').select('*') const profiles = await db.from('profiles').select('*') assert.lengthOf(profiles, 1) assert.lengthOf(users, 1) assert.equal(profiles[0].user_id, users[0].id) }) test('pass custom attributes to the relationship', async (assert) => { class Profile extends BaseModel { @column() public userId: number @column() public displayName: string @belongsTo(() => User) public user: BelongsTo<typeof User> } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) public id: number @column() public username: string @column() public points: number = 0 } const profileFactory = new FactoryModel( Profile, () => { return { displayName: 'virk', } }, factoryManager ) .relation('user', () => factory) .build() const factory = new FactoryModel( User, () => { return { points: 0, } }, factoryManager ).build() const profile = await profileFactory .with('user', 1, (related) => related.merge({ points: 10 })) .create() assert.isTrue(profile.$isPersisted) assert.instanceOf(profile.user, User) assert.isTrue(profile.user.$isPersisted) assert.equal(profile.user.id, profile.userId) assert.equal(profile.user.points, 10) }) test('create model with custom foreign key', async (assert) => { class Profile extends BaseModel { @column({ columnName: 'user_id' }) public authorId: number @column() public displayName: string @belongsTo(() => User, { foreignKey: 'authorId' }) public user: BelongsTo<typeof User> } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) public id: number @column() public username: string @column() public points: number = 0 } const profileFactory = new FactoryModel( Profile, () => { return { displayName: 'virk', } }, factoryManager ) .relation('user', () => factory) .build() const factory = new FactoryModel( User, () => { return { points: 0, } }, factoryManager ).build() const profile = await profileFactory .with('user', 1, (related) => related.merge({ points: 10 })) .create() assert.isTrue(profile.$isPersisted) assert.instanceOf(profile.user, User) assert.isTrue(profile.user.$isPersisted) assert.equal(profile.user.id, profile.authorId) assert.equal(profile.user.points, 10) }) test('rollback changes on error', async (assert) => { assert.plan(3) class Profile extends BaseModel { @column() public userId: number @column() public displayName: string @belongsTo(() => User) public user: BelongsTo<typeof User> } Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) public id: number @column() public username: string @column() public points: number = 0 } const profileFactory = new FactoryModel( Profile, () => { return { displayName: 'virk', } }, factoryManager ) .relation('user', () => factory) .build() /** * Creating user in advance, so that the `user` relationship * create call raises a unique constraint exception. * * After the exception, we except the profile insert to be * rolled back as well. */ await db.table('users').insert({ username: 'virk' }) const factory = new FactoryModel( User, () => { return { username: 'virk', } }, factoryManager ).build() try { await profileFactory.with('user').create() } catch (error) { assert.exists(error) } const profiles = await db.from('profiles').exec() const users = await db.from('users').exec() assert.lengthOf(profiles, 0) assert.lengthOf(users, 1) // one user still exists from the setup insert call }) })
the_stack